/** @brief main function, entry point of the application */
int
main (void)
{
  init_system ();
  HAL_Init ();

  lcd_init ();
  lcd_write_line (0, (char *) "Hello FreeRTOS");

  //xTaskCreate( (pdTASK_CODE)test_task, 	"test", configMINIMAL_STACK_SIZE, 0, TEST_TASK_PRIORITY, NULL);

  //xTaskCreate( (pdTASK_CODE)led1_task, 	"led1", 256, 0, LED_TASK_PRIORITY, NULL);
  //xTaskCreate( (pdTASK_CODE)led2_task, 	"led2", 256, 0, LED_TASK_PRIORITY, NULL);
  //xTaskCreate( (pdTASK_CODE)lcd_task, 	"lcd", 256, 0, LCD_TASK_PRIORITY, NULL);

  //xTaskCreate( (pdTASK_CODE)led1_task_timeslicing, 	"led1", 256, 0, LED_TASK_PRIORITY, NULL);
  //xTaskCreate( (pdTASK_CODE)led2_task_timeslicing, 	"led1", 256, 0, LED_TASK_PRIORITY, NULL);
  //xTaskCreate( (pdTASK_CODE)led3_task_timeslicing, 	"led1", 256, 0, LED_TASK_PRIORITY, NULL);

  //job_descriptor blink1_job_descriptor = job_descriptor(1000/3, LED1);
  //xTaskCreate( (pdTASK_CODE)blink1_task, 	"led1", 256, &blink1_job_descriptor, LED_TASK_PRIORITY, NULL);

  //job_descriptor blink2_job_descriptor = job_descriptor(2000/3, LED2);
  //xTaskCreate( (pdTASK_CODE)blink2_task, 	"led2", 256, &blink2_job_descriptor, LED_TASK_PRIORITY, NULL);

  //job_descriptor blink3_job_descriptor = job_descriptor(3000/3, LED3);
  //xTaskCreate( (pdTASK_CODE)blink3_task, 	"led3", 256, &blink3_job_descriptor, LED_TASK_PRIORITY, NULL);

  //job_descriptor blink4_job_descriptor = job_descriptor(4000/3, LED4);
  //xTaskCreate( (pdTASK_CODE)blink4_task, 	"led4", 256, &blink4_job_descriptor, LED_TASK_PRIORITY, NULL);

  xTaskCreate( (pdTASK_CODE)blink_task_low_priority, 	"led4", 256, 0, LED_TASK_PRIORITY_LOW, NULL);
  xTaskCreate( (pdTASK_CODE)blink_task_high_priority, 	"led4", 256, 0, LED_TASK_PRIORITY_HIGH, NULL);

  vTaskStartScheduler ();
  return 0;
}
Exemple #2
0
/**************************************************************************//**
*  \brief Initialize QTouch.
******************************************************************************/
void BSP_InitQTouch(BSP_TouchEventHandler_t handler)
{
	/* initialise host app, pins, watchdog, etc */
	init_system();

	/* Reset touch sensing */
	qt_reset_sensing();

	/*Configure Burst Length*/
	burst_len_config();
	config_sensors();

	/* Initialise and set touch params */
	qt_init_sensing();
	qt_set_parameters();
	init_timer_isr();

	buzzer_init();

	/*  Address to pass address of user functions   */

	/*  This function is called after the library has made capacitive
	 * measurements,
	 *   but before it has processed them. The user can use this hook to
	 * apply filter
	 *   functions to the measured signal values.(Possibly to fix sensor
	 * layout faults)    */

	/* This function is also used to send signal values to simulate Accelero
	 * meter,
	 * Just for demo purpose */
	qt_filter_callback = qt_avr477_filter_cb;

	cpu_irq_enable();

	handler = handler;
}
int main(int argc, char* argv[])
{
  double *x, ret, ratio;
  unsigned  nonreliable_threads,reliable_threads;
  
  
  if (argc != 6) {
    printf("usage: %s terms reliable_threads nonreliable_threads ratio input \n", argv[0]);
    exit(1);
  }
  
  NUM_TERMS = atoi(argv[1]);
  reliable_threads = atoi(argv[2]);
  nonreliable_threads = atoi(argv[3]);
  printf("Reliable threads are %d non reliable %d\n",reliable_threads,nonreliable_threads);
  ratio = atof(argv[4]);
  init_system(reliable_threads,nonreliable_threads);
  x = malloc(sizeof(double));
  *x = atof(argv[5]);
  
  simple_sum();
  
  return 0;
}
Exemple #4
0
//QuadCopt
int main(void)
{
	CSPR = CRP;  //set code protection to none

	CycleCount 				= 0;
	printCount 				= 0;
	refreshCount 			= 0;
	I2C0Mode 				= 1;
	int oldSec 				= 0;
	int countComponentCheck = 0;
	int countToCalc 		= 0;
	int countToI2C 			= 0;
	int servoCount 			= 0;

	init_system();



	print_uart0("FCm0;OsiFC v0.%d successful started;00#",VERSION);

	I2C0Mode = I2CMODE_FLIGHTMODE;
	I2C0State = 0;
	//I2C0Start();

	while(1){

		/*
		if (countComponentCheck++ > sysSetup.CYCLE.componentCycle) {
			//components enabled ?
			if (fcSetup.components[2] == 1) {
				if (navSol.packetStatus == 1 && PWM_channel[PWM_POTI1] > 80) {
					if (led2Status == 1) {
						LED2_OFF;
						led2Status = 0;
					} else {
						LED2_ON;
						led2Status = 1;
					}
					navSol.packetStatus = 0;
				} else {
					LED2_OFF;
					led2Status = 0;
				}

			}

			//compass enabled ?

			countComponentCheck = 0;
		}
		*/

		if (adcRead++ > adcRate) {
				ReadADC();
				adcRead = 0;

		}



		if (countToCalc++ > sysSetup.CYCLE.calcCycle) {
			countToCalc = 0;
			CycleCount++;

			if (servoCount++ > 80){
				setServo();
				servoCount = 0;
			}
			checkUBat();

			if (HMC5843Read++ > 130) {
				HMC5843Read = 0;
				//readHMC5843();
				//heading = calcHeading(HMC_runtime.X_axis,HMC_runtime.Y_axis,HMC_runtime.Z_axis);
			}


			//print telemtrie ?
			if(printCount++ > sysSetup.CYCLE.telemetrieCycle && sysSetup.CYCLE.telemetrieCycle != 0) {
				printTelemetrie();
				printCount = 0;
			}

			current_time = RTCGetTime();
			if (current_time.RTC_Sec != oldSec) {
				I2C1Mode = 0;

				//adjustSensorDrift();
				lastCycleCount = (int)CycleCount;
				CycleCount = 0;
				oldSec = current_time.RTC_Sec;
			}

			//the serial user interface always active
			serialUI();

			//engines Off so do...
			if (engineStatus == ENGINE_OFF) {
				//check for I2C commands to be send out
				//this is mainly for YGE setup
				checkI2C();
				//off flight RC UI to do setup and engines startup
				offFlightRcUI();			//the RC user interface off flight
			}
			//engines On so do...
			if (engineStatus == ENGINE_ON && PWM_valid >= 10000) {
				//check the in flight RC UI
				inFlightRcUI();				//the RC UI for in flight
			}

			I2C0Start();
		}
	}

	return (1);
}
Exemple #5
0
int main ( int argc, char ** argv )
{
	glutInit ( &argc, argv );

	if( argc < 2 ){
                printf("Usage: ./%s integrator=(1-euler, 2-RK2, 3-sympleticEuler, 4-RK4) [N dt d]", argv[0]);
		exit(0);
	}
	
        // decide which integrator to use
        switch ( argv[1][0] )
        {
        case '1':
            integrator = new EulerIntegrator();
            break;

        case '2':
            integrator = new RK2Integrator();
            break;

        case '3':
            integrator = new SymplecticEulerIntegrator();
            break;

        case '4':
            integrator = new RK4Integrator();
            break;

        default:
            integrator = new RK4Integrator();
        }
	
	if ( argc == 2 ) {
		N = 64;
                dt = 0.01f;
		d = 5.f;
		fprintf ( stderr, "Using defaults : N=%d dt=%g d=%g\n",
			N, dt, d );
	} else {
		N = atoi(argv[2]);
		dt = atof(argv[3]);
		d = atof(argv[4]);
	}

	printf ( "\n\nHow to use this application:\n\n" );
	printf ( "\t Toggle construction/simulation display with the spacebar key\n" );
	printf ( "\t Dump frames by pressing the 'd' key\n" );
	printf ( "\t Quit by pressing the 'q' key\n" );

	dsim = 0;
	dump_frames = 0;
	frame_number = 0;
	
	init_system();
	
        win_x = 720;
        win_y = 720;
	open_glut_window ();

	glutMainLoop ();

	exit ( 0 );
}
/*! \brief Example application entry function.
 */
int
main (void)
{

/*  BEFORE USING THE EXAMPLE PROJECTS.

1. For support queries on,
     - QTouch Library usage
     - Capacitive Touch Sensor Tuning
     - Capacitive Touch Schematic design
     - Capacitive Touch Sensor design
   refer to http://www.atmel.com/design-support/

2. For more QTouch Library documentation,
   refer Atmel QTouch Library User Guide doc8207.pdf.

   For Capacitive Touch Sensor tuning guidelines,
   refer QTAN0062: QTouch and QMatrix Sensitivity Tuning for Keys, Sliders and Wheels.

   For Capacitive Touch Sensor design,
   refer doc10620.pdf: Touch Sensors Design Guide.

   http://www.atmel.com/dyn/products/app_notes.asp?family_id=697

3. The Example application uses a CPU, PBA and PBB clock of 48MHz.
   When using a different frequency setting, the following parameters must be
   changed accordingly to ensure proper QTouch operation.
   a. QTx_CAT_CLK_DIV.
   b. TOUCH_SPREAD_SPECTRUM_MAX_DEV, when Spread spectrum is enabled.
   c. PBA_HZ, when using qdebug/SPI_Master.c
   d. TARGET_PBA_FREQ_HZ and TARGET_CPU_FREQ_HZ, when using qdebug/SERIAL.c

4. STK600-QTouch Test setup pin information.
   The following table indicates the STK600 pin connections for the STK600-QTouch
   test setup.

   Important Note: The (csa1/csab1) and (csa2/csb2) Touch channel connections are
   multiplexed with the JTAG pins.  So, when using the JTAG debugging mode, these
   Touch channel connections MUST be removed. In the Flash mode, this will not
   cause any issues.

        ----------------------------------------------
	CAT CSA/CSB name - STK600 board Port-pin name
	----------------------------------------------
	ROTOR/WHEEL
	csa1 		 - 	pa1 (This pair is multiplexed with JTAG pins.
	csb1 		 - 	pa6  Remove Touch connections on these pins during JTAG debug mode.)

	csa2 		 - 	pa0 (This pair is multiplexed with JTAG pins.
	csb2 		 - 	pa7  Remove Touch connections on these pins during JTAG debug mode.)

	csa5 		 - 	pb2
	csb5 		 - 	pb4

	SLIDER
	csa9 		 - 	pd0
	csb9 		 - 	pd1

	csa7 		 - 	pa4
	csb7 		 - 	pa5

	csa8 		 - 	pc0
	csb8 		 - 	pc1

	KEY 1
	csa15 		 - 	pe4
	csb15 		 - 	pe1

	KEY 2
	csa16 		 - 	pe3
	csb16 		 - 	pe2

    ----------------------------------------------
	QT600 USB Bridge
	'TOUCH DATA' Header Pin name - STK600 board Port-pin name
	----------------------------------------------
	PA22 - 'TOUCH DATA' header pin 8 - clk 	 - pc6
	PA21 - 'TOUCH DATA' header pin 7 - miso	 - pc5
	PA20 - 'TOUCH DATA' header pin 6 - mosi  - pc4
	PA14 - 'TOUCH DATA' header pin 5 - nss 	 - pb6

5. When two or more acquisition methods are used, care must be taken such that a
   given port pin is not used by more than one method at the same time.  The following
   pin configuration options available in touch_config_at32uc3l.h must be carefully
   chosen to avoid any overlapping.
   a. QMatrix Pin Configuration Options.
   b. Autonomous QTouch Pin Configuration Options.
   c. QTouch Group A Pin Configuration Options.
   d. QTouch Group B Pin Configuration Options.
   e. Touch Sync Pin option.
*/

  touch_ret_t touch_ret = TOUCH_SUCCESS;
  touch_qt_dma_t qt_dma_ch;

  /* Initialize host clock, pins, watchdog, etc. */
  init_system ();

  /* Disable interrupts. */
  Disable_global_interrupt ();

  /* The INTC driver has to be used only for GNU GCC for AVR32. */
#if (defined __GNUC__)

  /* initialize interrupt vectors. */
  INTC_init_interrupts ();

  /* Register the Timer interrupt handler to the interrupt controller. */
  INTC_register_interrupt (&tc_irq, EXAMPLE_TC_IRQ, AVR32_INTC_INT0);

  /* Register the Touch Library CAT interrupt handler to the interrupt controller.
     Note: This interrupt registration is a MUST before using the Touch Library
     with the GCC compiler.

     For the case of IAR the registration of interrupt is automatically taken
     care by the compiler. The Touch Libary CAT interrupt level for the case
     of IAR is fixed to Interrupt level 3. */
  INTC_register_interrupt (&touch_acq_done_irq, AVR32_CAT_IRQ,
			   AVR32_INTC_INT3);

#endif

  /* Enable interrupts. */
  Enable_global_interrupt ();

  /* Configure timer to fire ISR regularly. */
  init_timer ();

  /* Initialize touch library and uc3l cat module for QTouch Group A operation. */
  touch_ret = touch_qt_sensors_init (TOUCH_QT_GRP_A, &touch_config);
  if (touch_ret != TOUCH_SUCCESS)
    {
      while (1u);		/* Check API Error return code. */
    }

#if DEF_TOUCH_QDEBUG_ENABLE == 1
  /* Initialize the debug interface. */
  QDebug_Init ();
#endif

  /* configure the touch library sensors. */
  touch_ret = config_qt_grp_a_touch_sensors ();
  if (touch_ret != TOUCH_SUCCESS)
    {
      while (1u);		/* Check API Error return code. */
    }

  /* Initialize touch sensing. */
  touch_ret = touch_qt_sensors_calibrate (TOUCH_QT_GRP_A);
  if (touch_ret != TOUCH_SUCCESS)
    {
      while (1u);		/* Check API Error return code. */
    }

  /* Provide the dma channel to be used by the CAT module.  For each
     acquisition cycle, any different dma channel from 0 to 11 can be provided.
     The touch library can handle a different dma channel for each call of the
     touch_qt_sensors_start_acquisition API. */
  qt_dma_ch = QTA_DMA_CHANNEL_0;


  /* Loop forever */
  for (;;)
    {
      /* Process touch library events. The touch_event_dispatcher API needs to
         be called as frequently as possible in order to have a good touch response. */
      touch_event_dispatcher ();

      if (time_to_measure_touch == 1u)
	{
	  /* Clear flag: it's time to measure touch */
	  time_to_measure_touch = 0u;

	  /* Start a touch sensors measurement process. */
	  touch_ret = touch_qt_sensors_start_acquisition (TOUCH_QT_GRP_A,
							  current_time_ms_touch,
							  qt_dma_ch,
							  NORMAL_ACQ_MODE,
							  touch_qta_measure_complete_callback);
	  if ((touch_ret != TOUCH_SUCCESS) &&
	      (touch_ret != TOUCH_ACQ_INCOMPLETE))
	    {
	      while (1);
	      /* Reaching this point can be due to -
	         1. The api has retured an error due to a invalid input parameter.
	         2. The api has been called during a invalid Touch Library state. */
	    }
	}


      /* Host application code goes here */


      if (qta_measurement_done_touch == 1u)
	{
	  /* Clear flag: QTouch Group A measurement complete. */
	  qta_measurement_done_touch = 0u;

#if DEF_TOUCH_QDEBUG_ENABLE == 1
	  /* QT600 two-way QDebug communication application Example. */
	  /* Process any commands received from QTouch Studio. */
	  QDebug_ProcessCommands ();

	  /* Send out the Touch debug information data each time when Touch
	     measurement process is completed . */
	  QDebug_SendData (p_qta_measure_data->acq_status);
#endif

	}
    }				/* Loop forever */

}
Exemple #7
0
int     mcpp_lib_main
#else
int     main
#endif
(
    int argc,
    char ** argv
)
{
    char *  in_file = NULL;
    char *  out_file = NULL;
    char *  stdin_name = "<stdin>";

    if (setjmp( error_exit) == -1) {
        errors++;
        goto  fatal_error_exit;
    }

#if MCPP_LIB
    /* Initialize global and static variables.  */
    init_main();
    init_directive();
    init_eval();
    init_support();
    init_system();
#endif

    fp_in = stdin;
    fp_out = stdout;
    fp_err = stderr;
    fp_debug = stdout;
        /*
         * Debugging information is output to stdout in order to
         *      synchronize with preprocessed output.
         */

    inc_dirp = &null;   /* Initialize to current (null) directory   */
    cur_fname = cur_fullname = "(predefined)";  /* For predefined macros    */
    init_defines();                         /* Predefine macros     */
    mb_init();      /* Should be initialized prior to get options   */
    do_options( argc, argv, &in_file, &out_file);   /* Command line options */

    /* Open input file, "-" means stdin.    */
    if (in_file != NULL && ! str_eq( in_file, "-")) {
        if ((fp_in = fopen( in_file, "r")) == NULL) {
            mcpp_fprintf( ERR, "Can't open input file \"%s\".\n", in_file);
            errors++;
#if MCPP_LIB
            goto  fatal_error_exit;
#else
            return( IO_ERROR);
#endif
        }
    } else {
        in_file = stdin_name;
    }
    /* Open output file, "-" means stdout.  */
    if (out_file != NULL && ! str_eq( out_file, "-")) {
        if ((fp_out = fopen( out_file, "w")) == NULL) {
            mcpp_fprintf( ERR, "Can't open output file \"%s\".\n", out_file);
            errors++;
#if MCPP_LIB
            goto  fatal_error_exit;
#else
            return( IO_ERROR);
#endif
        }
        fp_debug = fp_out;
    }
    if (option_flags.q) {                   /* Redirect diagnostics */
        if ((fp_err = fopen( "mcpp.err", "a")) == NULL) {
            errors++;
            mcpp_fprintf( OUT, "Can't open \"mcpp.err\"\n");
#if MCPP_LIB
            goto  fatal_error_exit;
#else
            return( IO_ERROR);
#endif
        }
    }
    init_sys_macro();       /* Initialize system-specific macros    */
    add_file( fp_in, NULL, in_file, in_file, FALSE);
                                        /* "open" main input file   */
    infile->dirp = inc_dirp;
    infile->sys_header = FALSE;
    cur_fullname = in_file;
    if (mkdep && str_eq( infile->real_fname, stdin_name) == FALSE)
        put_depend( in_file);       /* Putout target file name      */
    at_start();                     /* Do the pre-main commands     */

    mcpp_main();                    /* Process main file            */

    if (mkdep)
        put_depend( NULL);      /* Append '\n' to dependency line   */
    at_end();                       /* Do the final commands        */

fatal_error_exit:
#if MCPP_LIB
    /* Free malloced memory */
    if (mcpp_debug & MACRO_CALL) {
        if (in_file != stdin_name)
            free( in_file);
    }
    clear_filelist();
    clear_symtable();
#endif

    if (fp_in != stdin)
        fclose( fp_in);
    if (fp_out != stdout)
        fclose( fp_out);
    if (fp_err != stderr)
        fclose( fp_err);

    if (mcpp_debug & MEMORY)
        print_heap();
    if (errors > 0 && option_flags.no_source_line == FALSE) {
        mcpp_fprintf( ERR, "%d error%s in preprocessor.\n",
                errors, (errors == 1) ? "" : "s");
        return  IO_ERROR;
    }
    return  IO_SUCCESS;                             /* No errors    */
}
Exemple #8
0
int main(int argc, char const *argv[])
{
    int i = 0;
    int t = 1;

    int n_mostros = 5;
    bool click = false;
    bool nova_horda = true;
    bool render = false;
    bool torre_mouse = false;

    char a;
    char b;
    int r;
    int l;

    Sistema sistema;
    Torre torre[10];
    Tiro tiro[10];
    Monstro monstro[n_mostros];
    Coord coordenada[A*B];

    //Declara�ao vair�veis allegro
    ALLEGRO_DISPLAY *janela = NULL;	            //Vari�vel para a janela
    ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;   //  ''     para eventos
    ALLEGRO_BITMAP *imagem = NULL;              //  ''     para imagem
    ALLEGRO_TIMER *timer = NULL;                //  ''     para o tempo (fps)
    ALLEGRO_FONT *fonte = NULL;                 //  ''     para fonte

    //Inicializa o allegro, mouse e add-ons
    al_init();
    al_install_mouse();
    al_init_primitives_addon();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    a_coord(coordenada, fonte);
    init_horda(monstro, n_mostros);
    init_system(sistema);
    initTorre(torre, tiro, t-1);



    //Atribui atributos às variáveis allegro

    janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
    fila_eventos = al_create_event_queue();
    imagem = al_load_bitmap("virus.png");
    timer = al_create_timer(1.0 / fps);
    fonte = al_load_font("arial.ttf", 12, 0);    //Fonte DejaVu

    //Inicializa o mouse e tempo
    al_set_system_mouse_cursor(janela, ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);
    al_start_timer(timer);
    al_install_keyboard();

    init_fail(janela, fonte, fila_eventos, imagem, timer); //Fun�ao de teste

    //Regista os eventos da janela, mouse e timer na vari�vel de eventos (fila_eventos)
    al_register_event_source(fila_eventos, al_get_display_event_source(janela));
    al_register_event_source(fila_eventos, al_get_mouse_event_source());
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

    al_clear_to_color(al_map_rgb(235, 235, 235));   //Limpa a tela
    al_flip_display();                              //Atualiza a tela

    //Loop principal
    while (!GameOver)
    {
        ALLEGRO_EVENT evento;                         //Variavel para eventos
        al_wait_for_event(fila_eventos, &evento);

        if(evento.type == ALLEGRO_EVENT_TIMER)  //Evento de renderiza�ao
        {
            i++;
            render = true;

            FireTiro(tiro, torre, monstro, t-1);
            UpdateTiro(tiro, monstro, t-1);
            update_horda(monstro, mapa, n_mostros);
            colisao_horda(tiro, monstro, n_mostros);

        }

        if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            GameOver = true;
        }

        else if(evento.type == ALLEGRO_EVENT_MOUSE_AXES)
        {
            pos_x = evento.mouse.x;
            pos_y = evento.mouse.y;

            a =  coordenada[(pos_x/l_celula)].letra[0];
            b =  coordenada[(pos_x/l_celula)].letra[1];
            l =  coordenada[(pos_y/a_celula)].numero;

            r = conversao_coordenadas(coordenada, a, b);
        }

        else if(evento.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
        {
            if (mapa[pos_y/a_celula][pos_x/l_celula] == 9)
            {
                torre_mouse = true;
                torre[t].in_mouse = true;
            }
            if(torre_mouse && !click)
            {
                if (mapa[pos_y/a_celula][pos_x/l_celula] != 9)
                {
                    mapa[pos_y/a_celula][pos_x/l_celula] = 10;
                    torre_mouse = false;
                    torre[t].in_mouse = false;
                    t++;
                }
            }
            click = !click;
        }

        else if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
        {
            switch(evento.keyboard.keycode)
            {
            case ALLEGRO_KEY_SPACE:
                start_horda(monstro, n_mostros);
                break;
            }
        }
        else if(render && al_is_event_queue_empty(fila_eventos))
        {
            render = false;

            coor_matrix(mapa, coordenada, fonte);

            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/4, 50, ALLEGRO_ALIGN_CENTRE, "Taxa de Frames: %i", i);
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y, ALLEGRO_ALIGN_LEFT, "   x:%i y:%i", pos_x, pos_y);

            draw_horda(monstro, n_mostros, imagem);

            if(torre_mouse)
            {
                draw_tower(r, l, torre, t);
            }
            drawTiro(tiro, t-1);

            al_flip_display();
            al_clear_to_color(al_map_rgb(255,255,255));
        }
    }

    destroy_al(janela, fonte, fila_eventos, imagem, timer); //Destroi as vari�veis allegro

    return 0;
}
Exemple #9
0
/*============================================================================
Name    :   main
------------------------------------------------------------------------------
Purpose :   main code entry point.
Input   :   n/a
Output  :   n/a
Notes   :
============================================================================*/
int main( void )
{

/*  BEFORE USING THE EXAMPLE PROJECTS.

1. The Example application uses a CPU, PBA and PBB clock of 48MHz.
   When using a different frequency setting, the following parameters must be
   changed accordingly to ensure proper QMatrix operation.
   a. QM_GCLK_CAT_DIV.
   b. QM_CAT_CLK_DIV.
   c. TOUCH_SPREAD_SPECTRUM_MAX_DEV, when Spread spectrum is enabled.
   d. PBA_HZ, when using QDebug/SPI_Master.c
   e. TARGET_PBA_FREQ_HZ and TARGET_CPU_FREQ_HZ, when using QDebug/SERIAL.c

2. In the UC3L-Evaluation kit (Rev2), the R42 and R54 (both 470KOhm) resistors
   MUST be replaced to 910KOhms.

3. The QTouch library uses PDCA channels 0 and 1.
   (QM_DMA_CHANNEL_0, QM_DMA_CHANNEL_1).
   Similarly, the QDebug/SERIAL.c uses PDCA channels 2 and 3.
   (PDCA_CHANNEL_RX_USART, PDCA_CHANNEL_TX_USART)

4. For QMatrix operation, the Analog comparators channels are used (using the
   ACIFB interface) depending on the Y Lines enabled.  For example, when
   Y lines Y2 and Y7 are enabled the Analog comparator channels 2 and 7
   are used by the CAT module for QMatrix operation.  The user can uses the rest
   of the Analog comparator channels in the main application. The QTouch Library
   enables the ACIFB using the Control register (if not already enabled by the main
   application) when the touch_qm_sensors_init API is called.

5. When two or more acquisition methods are used, care must be taken such that a
   given port pin is not used by more than one method at the same time.  The following
   pin configuration options available in touch_config_at32uc3l.h must be carefully
   chosen to avoid any overlapping.
   a. QMatrix Pin Configuration Options.
   b. Autonomous QTouch Pin Configuration Options.
   c. QTouch Group A Pin Configuration Options.
   d. QTouch Group B Pin Configuration Options.
   e. Touch Sync Pin option.
*/

  touch_ret_t touch_ret = TOUCH_SUCCESS;
  touch_qm_dma_t qm_dma;

  /* Initialize host clock, pins, watchdog, etc. */
  init_system();

  /* Disable interrupts. */
  Disable_global_interrupt();

  /* The INTC driver has to be used only for GNU GCC for AVR32. */
#if (defined __GNUC__)

  /* initialize interrupt vectors. */
  INTC_init_interrupts();

  /* Register the Timer interrupt handler to the interrupt controller. */
  INTC_register_interrupt(&tc_irq, EXAMPLE_TC_IRQ, AVR32_INTC_INT1);

  /* Register the Touch Library CAT interrupt handler to the interrupt controller.
     Note: This interrupt registration is a MUST before using the Touch Library
     with the GCC compiler.

     For the case of IAR the registration of interrupt is automatically taken
     care by the compiler. The Touch Library CAT interrupt level for the case
     of IAR is fixed to Interrupt level 3. */
  INTC_register_interrupt(&touch_acq_done_irq, AVR32_CAT_IRQ, AVR32_INTC_INT3);

#endif

  /* Enable interrupts. */
  Enable_global_interrupt();

  /* Configure timer to fire ISR regularly. */
  init_timer();

  /* Initialize touch library and uc3l cat module for QMatrix operation.
     Note: Set up the GCLK_CAT for proper QMatrix operation.  Refer init_system(). */
  touch_ret = touch_qm_sensors_init( &touch_config );
  if(touch_ret != TOUCH_SUCCESS)
  {
    while(1u); /* Check API Error return code. */
  }

#if DEF_TOUCH_QDEBUG_ENABLE == 1
  /* Initialize the debug interface. */
  QDebug_Init();
#endif

  /* configure the touch library sensors. */
  touch_ret = config_uc3lek_touch_sensors();
  if(touch_ret != TOUCH_SUCCESS)
  {
    while(1u); /* Check API Error return code. */
  }

  /* Initialize touch sensing. */
  touch_ret = touch_qm_sensors_calibrate();
  if(touch_ret != TOUCH_SUCCESS)
  {
    while(1u); /* Check API Error return code. */
  }

  /* Provide the dma channels to be used by the CAT module.  For each
     acquisition cycle, any different combination of dma channels from 0 to 11
     can be provided. The touch library can also handle a different combination
     of dma channels for each call of the touch_qm_sensors_start_acquisition API. */
  qm_dma.dma_ch1 = QM_DMA_CHANNEL_0;
  qm_dma.dma_ch2 = QM_DMA_CHANNEL_1;

  // Initialize the PWMA module
  demo_init_pwma();

  // At the start of the demo, automatically change several times the PWMA duty
  // cycle (i.e. the intensity) of all LEDs.
  demo_automatic_ledshow_play(DEMO_INIT_NB_AUTOMATIC_CHANGES);

  /* Loop forever */
  for( ; ; )
  {
    /* Process touch library events. The touch_event_dispatcher API needs to
       be called as frequently as possible in order to have a good touch response. */
    touch_event_dispatcher();

    if( time_to_measure_touch == 1u )
    {
      /* Clear flag: it's time to measure touch */
      time_to_measure_touch = 0u;

      /* Start a touch sensors measurement process. */
      touch_ret = touch_qm_sensors_start_acquisition( current_time_ms_touch,
                                                      &qm_dma,
                                                      NORMAL_ACQ_MODE,
                                                      touch_qm_measure_complete_callback);
      if( (touch_ret != TOUCH_SUCCESS)       &&
          (touch_ret != TOUCH_ACQ_INCOMPLETE) )
      {
        gpio_clr_gpio_pin(LED0_GPIO);  // LED0
        gpio_clr_gpio_pin(LED1_GPIO);  // LED1
        gpio_clr_gpio_pin(LED2_GPIO);  // LED2
        gpio_clr_gpio_pin(LED3_GPIO);  // LED3
        do{
            delay_ms(50);
            gpio_tgl_gpio_pin(LED0_GPIO); gpio_tgl_gpio_pin(LED1_GPIO);
            gpio_tgl_gpio_pin(LED2_GPIO); gpio_tgl_gpio_pin(LED3_GPIO);
        }while(1);
       /* Reaching this point can be due to -
          1. The api has returned an error due to a invalid input parameter.
          2. The api has been called during a invalid Touch Library state. */
      }
    }


    /* Host application code goes here */


    /* Led demo application. */
    if(qm_measurement_done_touch == 1u)
    {
#if DEF_TOUCH_QDEBUG_ENABLE == 1
      /* UC3L_EK two-way QDebug communication application Example. */
      /* Process any commands received from QTouch Studio. */
      QDebug_ProcessCommands();

      /* Send out the Touch debug information data each time when Touch */
      /* measurement process is completed . */
      QDebug_SendData(p_qm_measure_data->acq_status);
#endif
      // New touch data measurement are available.
      process_qtouchlib_data();
      /* Clear flag: QMatrix measurement complete. */
      qm_measurement_done_touch = 0u;

      // Once the latest touch data measurements have been processed, clear them.
      // Here we clear only the measurements that are used by the application.
      p_qm_measure_data->p_sensor_states[0] = 0;
      p_qm_measure_data->acq_status = TOUCH_NO_ACTIVITY;
      p_qm_measure_data->p_rotor_slider_values[0] = 0;
    }
    else
      process_qtouchlib_data();
    // Note: we cannot go deeper than the IDLE sleep mode because the QMatrix lib
    // uses the PDMA.
    SLEEP(AVR32_PM_SMODE_IDLE);
  }
}
Exemple #10
0
void main(void)
{
//	XBYTE[0xB091]=0x01;	// 1.8v/3.3v regulator turn on
    XBYTE[0xB092]=0x78; // 3.2V & 2.0V
//	XBYTE[0xB093]=0x00;	// LVR=2.4V

    // DSP initial
    XBYTE[0xB010]&=0xFE;	// Disable DSP clock, Jimi 080729 for pop noise as 1st time play
    XBYTE[0xB002]&=0xFE;	// Release DSP Reset, Jimi 080729 for pop noise as 1st time play
    XBYTE[0xB08a]|=0x08; 	//(JC)MCU:audio DAC on
    XBYTE[0xB08a]|=0x10; 	//(JC)MCU:Headphone driver on
    XBYTE[0xB08a]|=0x20; 	//(JC)MCU:Headphone driver DD comm-mode bias o/p
    XBYTE[0xB0ED]|=0x02;	//(Jimi 091027)Audio DA zero cross reset bypass on
    XBYTE[0xB0C1]=0xB0;		//(Jimi 091027)Pre-mux , post-mux and internal XCK select
    XBYTE[0xB0C4]=2;		//(Jimi 091027)LCH speaker volume(i.e LCH OP Gain)
    XBYTE[0xB0C5]=2;		//(Jimi 091027)RCH speaker volume(i.e RCH OP Gain)

    //SAR ADC init
    XBYTE[0xB05E] = 0; // disable SAR FS clock
    XBYTE[0xB05F] = 0x5F; // SAR clock = 12MHz/16/6 = 125kHz = 8us

    //--------------------------------------------	//
    gbt_Force_USB_FullSpeed =FALSE;
    gbt_USB_Detected = 0;
    gc_CardDetect = 0x00 ;
    gc_CardExist  = 0x00 ;  			// bit 0  : Nand Flash  bit 1: SD_Card
    gc_CardType   = 0x01 ;				// default Flash Interface
    gc_CardChangeStage =0x00;           // bit 0 : Nand  bit 1 : SD_Card
    gw_FileSkipNumber=0;
    gb_TriggerFileSkip=0;
    gb_FindFile=0;
    gbt_Support_Dummy_Capacity =0;              // default disable dummy capacity function
    gc_bCBWLUN=0;
    gbt_enableCDROM =0;							//09/04/24,joyce
    gc_CDROM_Size=0 ;
    init_system();
    USB_PlugDetect();                               // Detect USB plug
    //----------------------------------------------// Initial Flash module
    Init_Flash_Reg();
    Init_Flash_Variable();
    //-------------- Need search Bank,Dsp ,hzk block info ,first---------//
    FDBP.cFDev = 0;
    XBYTE[0xB40F] = FDBP.cFDev;
    FlashReadID();
    Flash_State_Initial();
    Search_BankCode_Block();

    InitFlash();

    Timer0_init();
    XBYTE[0xB09F]|=0x06;//(JC)Vref Fast setup mode 'n Internal reference voltage power control
    gc_Vrefinit_Timer=60;
    XBYTE[0xB421]=0x13;
//	dbprintf("tftinit\n");
    TFT_init();
#ifdef CAR_48
    XBYTE[0xB102]|=0x3C;
#else
    XBYTE[0xB102] |= 0x01;
#endif
//	dbprintf("tftinit end\n");
    TFT_PowerOnlogo();
    if(gbt_USB_Detected)
    {
        USB_Task();
    }

    gb_Host_Exist=1;
    gb_SD_Exist=1;
    if(!Host_DetectDevice())
    {
        if(!Host_Initial())
        {
            gc_CurrentCard = CURRENT_MEDIA_HOST;
            gb_FindFlag = 0;
        }
        else
        {
            gc_CurrentCard=0;
        }
    }
    else
    {
        if(SD_Card_Detect())
        {
            if(SD_Identification_Flow())
            {
                gc_CardExist |=0x02;
                gc_CurrentCard=2;
            }
            else
            {
                gc_CurrentCard=0;
                gc_CardExist &=0xFD;
                gb_FindFlag = 0;
            }
        }
        else
        {
            gb_SD_Exist=0;
            gc_CurrentCard = 0;
        }
    }
    XBYTE[0xB400] =0x01;
    XBYTE[0xB010]&=0xFE;	// Disable DSP clock, Jimi 080729 for pop noise as 1st time play
    XBYTE[0xB002]&=0xFE;	// Release DSP Reset, Jimi 080729 for pop noise as 1st time play
    XBYTE[0xB08a]|=0x08;//(JC)MCU:audio DAC on
    XBYTE[0xB08a]|=0x10;//(JC)MCU:Headphone driver on
    XBYTE[0xB08a]|=0x20;//(JC)MCU:Headphone driver DD comm-mode bias o/p

    //SAR ADC init
    XBYTE[0xB05E] = 0; // disable SAR FS clock
    XBYTE[0xB05F] = 0x5f; // SAR clock = 12MHz/16/6 = 125kHz = 8us

    Get_LogData_PageIndex();  //chiayen0808
    USER_LogFile_ReadWrite(0);//use reserveblock for log
    if((gw_FM_frequency<875) || (gw_FM_frequency>1080))
    {
        gw_FM_frequency=875;
    }
    FM_initial();
    FM_drive();
    gc_SetNumber = gw_PagesPerBlock >> 2; //1set=4pages for dir management, Ching 080816  //20090107 chiayen add
    gc_SetIndex = 0; //Ching 080816  //20090107 chiayen add
    USER_GetUISetIndex();	//for DIR table	index  //20090107 chiayen add

    gb_FindFlag = 0;
    if (DOS_Initialize()) //20090803 chiayen modify
    {
        gdw_HOSTStartSectorRead=0xFFFFFFF0;
        if(gc_CurrentCard==CURRENT_MEDIA_HOST)
        {
            if(SD_Card_Detect())
            {
                gb_SD_Exist=1;
                if(SD_Identification_Flow())
                {
                    gc_CardExist |=0x02;
                    gc_CurrentCard=2;
                }
                else
                {
                    DEVICE_REG[0x00]= 0x01;
                    gc_CurrentCard=0;
                    gc_CardExist &=0xFD;
                    gb_FindFlag = 0;
                }
            }
            else
            {
                DEVICE_REG[0x00]= 0x01;
                gb_SD_Exist=0;
                gc_CurrentCard = 0;
            }
        }
        else
        {
            DEVICE_REG[0x00]= 0x01;  //20090730 chiayen add
            gc_CurrentCard=0;
            gc_CardExist &=0xFD;
            gb_FindFlag = 0;
            InitFlash();
        }
        DOS_Initialize();
    }
    gc_CurrentCard_backup=gc_CurrentCard; //20090803 chiayen move here
    gs_File_FCB[0].dw_FDB_StartCluster = gdw_DOS_RootDirClus;
    DOS_Search_File(C_File_All|C_Cnt_FileNo, C_MusicFileType, C_CmpExtName|C_Next);//(JC)count music file no. in root
    ir_init();
    EA  = 1;
    gc_Task_Current=C_Task_Play;
    gc_Task_Next=C_Task_Play;
    gc_PhaseInx=0;
    gw_init_needed=0xffff;
    Detect_USB();
    Polling_TaskEvents();
    if(gc_Task_Current!=gc_Task_Next)
    {
        gc_Task_Current=gc_Task_Next;
    }
    while(1)
    {
        switch(gc_Task_Current)
        {
        case C_Task_Play:
            Play_Task();
            break;

        case C_Task_USB:
            USB_Task();
            break;

        case C_Task_Dir:  //20090107 chiayen add
            Dir_Task();
            break;

        case C_Task_Jpeg:  //20090107 chiayen add
            Jpeg_Task();
            break;

        case C_Task_Mjpeg:  //20090107 chiayen add
            Mjpeg_Task();
            break;

        case C_Task_PlayMenu:  //20090107 chiayen add
//				PlayMenuProcess();
            break;

        case C_Task_PlayMenu_IR:  //20090107 chiayen add
//				PlayMenuProcess_IR();
            break;

        case C_Task_Setting:  //20090107 chiayen add
            SetupMenuProcess();
            break;

        case C_Task_Menu:
            MainMenuProcess();
            break;

        case C_Task_PowerOff:
            PowerOffProcess();
            break;
        }
    }
}
Exemple #11
0
int main()
{
	struct remote_proc *proc;
	int uninit = 0;
	struct ept_cmd_data *ept_data;

#ifdef ZYNQ7_BAREMETAL
	/* Switch to System Mode */
	SWITCH_TO_SYS_MODE();
#endif

	/* Initialize HW system components */
	init_system();

	rsc_info.rsc_tab = (struct resource_table *)&resources;
	rsc_info.size = sizeof(resources);

	/* This API creates the virtio devices for this remote node and initializes
	   other relevant resources defined in the resource table */
	remoteproc_resource_init(&rsc_info, rpmsg_channel_created,
				 rpmsg_channel_deleted, rpmsg_read_default_cb,
				 &proc);

	for (;;) {

		if (intr_flag) {
			struct command *cmd = (struct command *)r_buffer;
			if (cmd->comm_start == CMD_START) {
				unsigned int cm_code = cmd->comm_code;
				void *data = cmd->data;

				switch (cm_code) {
				case CREATE_EPT:
					ept_data = (struct ept_cmd_data *)data;
					rp_ept =
					    rpmsg_create_ept(app_rp_chnl,
							     rpmsg_read_ept_cb,
							     RPMSG_NULL,
							     ept_data->dst);
					if (rp_ept) {
						/* Send data back to ack. */
						rpmsg_sendto(app_rp_chnl,
							     r_buffer, Len,
							     Src);
					}
					break;
				case DELETE_EPT:
					rpmsg_destroy_ept(rp_ept);
					rpmsg_sendto(app_rp_chnl, r_buffer, Len,
						     Src);

					break;
				case CREATE_CHNL:
					break;
				case DELETE_CHNL:
					rpmsg_sendto(app_rp_chnl, r_buffer, Len,
						     Src);
					remoteproc_resource_deinit(proc);
					uninit = 1;
					break;
				case QUERY_FW_NAME:
					rpmsg_send(app_rp_chnl,
						   &firmware_name[0],
						   strlen(firmware_name) + 1);
					break;
				default:
					rpmsg_sendto(app_rp_chnl, r_buffer, Len,
						     Src);
					break;
				}
			} else {
				rpmsg_sendto(app_rp_chnl, r_buffer, Len, Src);
			}
			intr_flag = 0;
			if (uninit)
				break;
		}

		sleep();
	}

	return 0;
}
Exemple #12
0
int main(int argc, char **argv)
{
	if (argc != 4 && argc != 5 && argc != 6) {
		DP("Usage: %s <svc_conf> <svc_name> <uid> [row] [col]", argv[0]);
		return -1;
	}
	int show_one_row = 0;
	char *svc_conf = argv[1];
	char *svc_name = argv[2];
	uint32_t uid = atoi(argv[3]);

	if (uid == 0 && argc != 5 && argc != 6) {
		DP("Usage: %s <svc_conf> <svc_name> <uid> <row> [col]", argv[0]);
		return -1;
	}

	uint32_t row = 0, col = 0;
	if (argc >= 5) {
		row = atoi(argv[4]);
		show_one_row = 1;
		if (argc == 6) {
			col = atoi(argv[5]);
			show_one_row = 0;
		}
	}

	uint32_t row_num, *nodes_num, *mods;
	if (init_system(svc_conf, svc_name, &row_num, &nodes_num, &mods) == -1) {
		DP("Failed to init_system");
		return -1;
	}

	if (row >= row_num || col >= nodes_num[row]) {
		DP("Invalid row: %u(max: %u), or col: %u(max: %u)",
				row, col, row_num, (row < row_num) ? nodes_num[row] : 0);
		return -1;
	}

	struct uid_node_t *uid_node = NULL;

	if (show_one_row) { /* show one row */
		int c = 0;
		for (; c < nodes_num[row]; c++) {
			uid_node = hash_table_get_node(uid_nodes_htab, row, c);
			if (uid_node->uid == 0) {
				//DP("row: %u, col: %u svc: %s is empty", row, c, svc_name);
				continue;
			}
			show_one_uid_node(uid_node, row, c);
		}
		return 0;
	}

	if (uid == 0) {
		uid_node = hash_table_get_node(uid_nodes_htab, row, col);
		if (uid_node->uid == 0) {
			DP("row: %u, col: %u svc: %s is empty", row, col, svc_name);
			return 0;
		}
	} else {
		uid_node = HTAB_LOOKUP_POSINFO(uid_nodes_htab, uid, row, col);
		if (!uid_node) {
			DP("uid: %u is not coming in svc: %s", uid, svc_name);
			return 0;
		}
	}

	/* show uid_node info */
	show_one_uid_node(uid_node, row, col);

	return 0;
}
Exemple #13
0
void main(void) {

	init_system();

	volatile enum states state;
	state = IDLE;
	volatile enum button_states button_state;
	button_state = NO_PUSH;

	__enable_interrupt();

	while(1) {

		/* Check push button */
		if (button_flag == 1) {
			button_flag = 0;

			// Check push button
			unsigned int push_cnt = 0;
			button_state = NO_PUSH;
			__delay_cycles(200000);  // Wait 25 msec to debounce
			__delay_cycles(200000);  // Wait 25 msec to debounce
			while (!(P4IN & BIT0)) {  // Button pushed
				__delay_cycles(8000);  // Wait 1 msec
				push_cnt++;

				if (push_cnt > TIME_SHORT_PUSH) {  // Push button was pushed a short time
					button_state = SHORT_PUSH;
					LED1_on();
				}
				if (push_cnt > TIME_LONG_PUSH) {  // Push button was pushed a long time
					button_state = LONG_PUSH;
					LED2_on();
				}
			}
			LED1_off();
			LED2_off();
			__delay_cycles(400000);  // Wait 50 msec to debounce
			__delay_cycles(400000);  // Wait 50 msec to debounce
		}


		/* Check states */
		switch (state) {
			case IDLE:
//				toggle_led(LED1_PIN, TIME_3SEC);
				switch (button_state) {
					case LONG_PUSH:
						state = TRANSMIT;
						wdt_disable();
						LED1_off();
						toggle_led(LED2_PIN, TIME_05SEC);
						transmit_data();
						break;
					case SHORT_PUSH:
						state = RECORD;
						wdt_disable();
						LED2_off();
						toggle_led(LED1_PIN, TIME_1SEC);
						record_data();
						break;
					default:
						break;
				}
				break;

			case RECORD:
				switch (button_state) {
					case LONG_PUSH:  // Delete data
						delete_data();
						state = IDLE;
						break;
					case SHORT_PUSH:  // Stop recording
						// Recording stop from inside recorde()
						state = IDLE;
						break;
					default:
						break;
				}
//				state = IDLE;
				break;
			case TRANSMIT:
				switch (button_state) {
					case LONG_PUSH:
						break;
					case SHORT_PUSH:
						break;
					default:
						break;
				}
				state = IDLE;
				break;
			default:
				break;
		}

		//button_state = NO_PUSH;
		PAIE |= BIT0;  // Enable interrupt for push button

		if (state == IDLE) {
			toggle_led(LED1_PIN, TIME_3SEC);
			wdt_enable();  // Activate auto-deep-sleep-watchdog
			LPM3;
			_nop();
		}

	}

}
Exemple #14
0
/********************* Main*/
int omain(int argc, char *argv[]){
	int i, cnt, cntt, cnttt, way;
	static char file[MAXC], attr[MAXC], val[MAXC], *p, *binver;
	#if defined(ALLEGRO_WINDOWS)
	binver = "Windows binary";
	#elif defined(ALLEGRO_DOS)
	binver = "DOS binary";
	#elif defined(ALLEGRO_LINUX)
	binver = "Linux binary";
	#elif defined(ALLEGRO_BEOS)
	binver = "BEOS binary";
	#elif defined(ALLEGRO_QNX)
	binver = "QNX binary";
	#elif defined(ALLEGRO_UNIX)
	binver = "UNIX binary";
	#elif defined(ALLEGRO_MPW)
	binver = "MacOS binary";
	#else
	binver = "Unknown binary";
	#endif
	printf("%s %s\n","\nO2EM v" O2EM_VERSION " " RELEASE_DATE "  - ", binver);
	printf("Free Odyssey2 / Videopac+ Emulator - http://o2em.sourceforge.net\n");
	printf("Created by Daniel Boris (c)1996/1998\n");
    printf("Developed by:\n");
	printf("     Andre de la Rocha since version 0.80\n");
	printf("     Arlindo M. de Oliveira since version 1.16\n");
    printf("\n");

    app_data.debug = 0;
	app_data.stick[0] = app_data.stick[1] = 1;
	app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
	set_defjoykeys(0,0);
	set_defjoykeys(1,1);
	set_defsystemkeys();
	app_data.bank = 0;
	app_data.limit = 1;
	app_data.sound_en = 1;
	app_data.speed = 100;
	app_data.wsize = 2;
	#ifdef ALLEGRO_DOS
	app_data.fullscreen = 1;
	#else
	app_data.fullscreen = 0;
	#endif
	app_data.scanlines = 0;
	app_data.voice = 1;
	app_data.window_title = "O2EM v" O2EM_VERSION;
	app_data.svolume = 100;
	app_data.vvolume = 100;
	app_data.filter = 0;
	app_data.exrom = 0;
	app_data.three_k = 0;
	app_data.crc = 0;
	app_data.scshot = scshot;
	app_data.statefile = statefile;
	app_data.euro = 0;
	app_data.openb = 0;
	app_data.vpp = 0;
	app_data.bios = 0;
	app_data.scoretype = 0;
	app_data.scoreaddress = 0;
	app_data.default_highscore = 0;
	app_data.breakpoint = 65535;
	app_data.megaxrom = 0;
	strcpy(file,"");
	strcpy(file_l,"");
	strcpy(bios_l,"");
    strcpy(bios,"");
	strcpy(scshot,"");
	strcpy(statefile,"");
    strcpy(xrom,"");
	strcpy(scorefile,"highscore.txt");
	read_default_config();
	if (argc >= 2){
    for(i=1; i<argc; i++) {
		if (argv[i][0] != '-') 	{
			strncat(file,argv[i],MAXC-1);
	        file[MAXC-1]=0;
	        strcpy(file_v,file);
		} else {
			p=strtok(argv[i],"=");
	        if (p){
				strncpy(attr,p+1,MAXC-1);
				attr[MAXC-1]=0;
			   } else
				strcpy(attr,"");
			    p=strtok(NULL,"=");
			if (p){
				strncpy(val,p,MAXC-1);
				val[MAXC-1]=0;
			    if (!strcmp(attr,"romdir")||!strcmp(attr,"ROMDIR"))
                   {
                    strcpy(romdir,val);
                    strcat(romdir,file);
                    strcpy(file,romdir);
                    strcpy(romdir,val);
                   }
                if (!strcmp(attr,"biosdir")||!strcmp(attr,"BIOSDIR"))
                   {
                    strcpy(biosdir,val);
                   }                                       
            } else
			strcpy(val,"");
			strlwr(attr);
			if (!parse_option(attr, val)) exit(EXIT_FAILURE);
		}
    }
    if (helpflag) helpus();
    if (strlen(file)==0) {
		fprintf(stderr,"Error: file name missing\n");
		exit(EXIT_FAILURE);
	}

#ifdef __LIBRETRO__
sprintf(statefile,"%s.state\0",file);
#endif
	printf("Starting emulation ...\n");
#ifndef __LIBRETRO__
	allegro_init();
	install_timer();
#endif
	init_audio();

#ifndef __LIBRETRO__
	printf("Using Allegro %s\n",allegro_id);
#endif 


/********************** ROMs if Launcher running... */
    k = strchr(romdir, '/'); 

    launcher_flag_r = strchr(file, '\\');

    if (k != 0) {
                 strcpy (xrom,romdir);
                }
                else if (!launcher_flag_r)
                        {

                        strcpy(xrom,"roms/");
                        strcpy(romdir,file);
#ifndef __LIBRETRO__
                        strcpy(file,xrom);
                        strcat(file,romdir);
#endif
                        strcpy(romdir,xrom);

                        }
                        else
                        {    
         
                        cnt = 0;
                        cntt = 0;
                        cnttt = 0;
                        way = 0;
                        for (cnt=0; file[cnt] != '\0'; cnt=cnt+1) 
                        { 
                        if ( file[cnt] == '\\' ) 
                           {
                           cnttt = cnt;
                           }
                        } 
                        for (cnt=0; cnt<=cnttt; cnt++)
                        { 
                        file_l[cnt] = file[cnt];
                        } 

                        strcpy (romdir,file_l);
                        strcpy (xrom,romdir);
                        }

#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xrom,"%s\0","/mnt/sdcard/O2EM/roms/");
	strcpy(romdir,xrom);
#else
	sprintf(xrom,"%s\0","./roms/");
	strcpy(romdir,xrom);
#endif
#endif


    file_name(xrom);

    if (contax < 3)
                 {
                 printf("\nROMs directory empty!\n");
                 exit(EXIT_FAILURE);
                 }

    app_data.crc = crc32_file(file);

    crcx = app_data.crc;
    suck_roms(); 

/********************** BIOSs if Launcher running... */     
launcher_flag_b = strchr(bios, '\\');

if (!launcher_flag_b){
    k = strchr(biosdir, '/');

    if (k != 0) {    
                 strcpy (xbios,biosdir);
                }
                else           
                        {
                        strcpy (xbios,"bios/");
                        strcpy (biosdir,xbios);
                        }
#ifdef __LIBRETRO__
#ifdef AND
	sprintf(xbios,"%s\0","/mnt/sdcard/O2EM/bios/");
	strcpy (biosdir,xbios);
#else	
	sprintf(xbios,"%s\0","./bios/");
	strcpy (biosdir,xbios);
#endif
#endif

    file_name(xbios);

    if (contax < 3)
                 {
                 printf("\nBIOS directory empty!\n");
                 exit(EXIT_FAILURE);                 
                 }

    suck_bios();

    c_j = strcmp(bios,"jopac");
    if ((rom_f!=1) && (c_j!=0)) strcpy(bios,g7400);
    if ((!o2flag) && (!jopflag) && (!c52flag) && (!g74flag))
                                              {
                                             printf("\ndir '%s' without BIOS !",biosdir);
                                             exit(EXIT_FAILURE);
                                              }
    printf("BIOS found:\n");
    if (!strcmp(bios,"g7400")){
                               strcpy(bios,g7400);
                               if (g74flag != 1) {
                                             printf("\nG7400 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                               }
    if (g74flag) printf("  G7400 VP+\n");
    if (!strcmp(bios,"c52")){ 
                             strcpy(bios,c52);
                             if (c52flag != 1) {
                                             printf("\nC52 BIOS not found !");
                                             exit(EXIT_FAILURE);
                                             } 
                                 }
    if (c52flag) printf("  C52\n");
    if (!strcmp(bios,"jopac")){
                               strcpy(bios,jopac);
                               if (jopflag != 1) {
                                          printf("\nJOPAC BIOS not found !");
                                          exit(EXIT_FAILURE);
                                             } 
                               }
    if (jopflag) printf("  JOPAC VP+\n");
    if ((!strcmp(bios,"")) || (!strcmp(bios,"o2rom")))
                            {
                            strcpy(bios,odyssey2);
                            if ((!o2flag)&&(!c52flag)&&(rom_f)){
                                             printf("Odyssey2 BIOS not found !\n");
                                             exit(EXIT_FAILURE);
                                             } 
                            if ((!o2flag)&&(c52flag)&&(rom_f)){
                                             printf("\nOdyssey2 BIOS not found !\n");
                                             printf("Loading C52 BIOS ... ");
                                             strcpy(bios,c52);
                                             }
                            }
    if (o2flag) printf("  Odyssey 2\n");
    }                                           
    if (launcher_flag_b)
       {
       identify_bios(bios);
                if (rom_f!=1)
                   {
                   if (!((g74flag)||(jopflag)))
                      {
                      fprintf(stderr,"\nError: ROM only VP+ BIOS");
                      exit(EXIT_FAILURE);
                      }
                   }
       }      


      if (!launcher_flag_b)
                  {  
                  if (rom_f!=1)
                     {  
                     if (!((g74flag)||(jopflag)))
                         {
                         printf("\nROM only VP+ BIOS\n");
                         exit(EXIT_FAILURE);
                         }
                     if (!(g74flag))
                         {
                         printf("\nVP+ G7400 BIOS not found !");
                         printf("\nLoading VP+ Jopac BIOS ...");
                         strcpy(bios,jopac);
                         }
                     }
                  }
    load_bios(bios);

	load_cart(file);
	if (app_data.voice) load_voice_samples(path);

	init_display();

	init_cpu();

	init_system();

	set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);
	int stateError;
	if ((stateError=loadstate(app_data.statefile))==0)
	{
		printf("Savefile loaded.");
	}
	else if (stateError>=199)
	{
		if (stateError==199) fprintf(stderr,"Wrong ROM-File for Savefile.");
		else if (stateError==200+ROM_O2) fprintf(stderr,"Wrong BIOS for Savefile: O2ROM needed.");
		else if (stateError==200+ROM_G7400) fprintf(stderr,"Wrong BIOS for Savefile: G7400 ROM needed.");
		else if (stateError==200+ROM_C52) fprintf(stderr,"Wrong BIOS for Savefile: C52 ROM needed.");
		else if (stateError==200+ROM_JOPAC) fprintf(stderr,"Wrong BIOS for Savefile: JOPAC ROM needed.");
		else fprintf(stderr,"Wrong BIOS for Savefile: UNKNOWN ROM needed.");
		return(0);
	}
	if (app_data.debug) key_debug=1;
	#ifndef _DEBUG
	#ifdef ALLEGRO_WINDOWS
	FreeConsole();
	#endif
	#endif

#ifdef __LIBRETRO__
return 1;
#endif
	run();

    if (app_data.scoretype!=0) save_highscore(get_score(app_data.scoretype, app_data.scoreaddress), scorefile);
	exit(EXIT_SUCCESS);
 }
if (!strcmp(attr,"help")||!strcmp(attr,"HELP")) helpus();
printf("type o2em -help");
exit(EXIT_SUCCESS);
}
Exemple #15
0
bool retro_load_game(const struct retro_game_info *info)
{
    char bios_file_path[256];
    const char *full_path, *system_directory_c;

    enum retro_pixel_format fmt = RETRO_PIXEL_FORMAT_RGB565;
    if (!environ_cb(RETRO_ENVIRONMENT_SET_PIXEL_FORMAT, &fmt))
    {
        if (log_cb)
            log_cb(RETRO_LOG_INFO, "[O2EM]: RGB565 is not supported.\n");
        return false;
    }

    struct retro_input_descriptor desc[] = {
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "Left" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "Up" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "Down" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
       { 0, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Fire" },

       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_LEFT,  "Left" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_UP,    "Up" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_DOWN,  "Down" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_RIGHT, "Right" },
       { 1, RETRO_DEVICE_JOYPAD, 0, RETRO_DEVICE_ID_JOYPAD_A,     "Action" },

       { 0 },
    };

   environ_cb(RETRO_ENVIRONMENT_SET_INPUT_DESCRIPTORS, desc);

    full_path = info->path;
    system_directory_c = NULL;

    // BIOS is required
    environ_cb(RETRO_ENVIRONMENT_GET_SYSTEM_DIRECTORY, &system_directory_c);
    if (!system_directory_c)
    {
       if (log_cb)
          log_cb(RETRO_LOG_WARN, "[O2EM]: no system directory defined, unable to look for o2rom.bin\n");
       return false;
    }
    else
    {

#ifdef _WIN32
      char slash = '\\';
#else
      char slash = '/';
#endif

       snprintf(bios_file_path, sizeof(bios_file_path), "%s%c%s", system_directory_c, slash, "o2rom.bin");

       if (!does_file_exist(bios_file_path))
       {
          if (log_cb)
             log_cb(RETRO_LOG_WARN, "[O2EM]: o2rom.bin not found, cannot load BIOS\n");
          return false;
       }
    }

    app_data.debug = 0;
    app_data.stick[0] = app_data.stick[1] = 1;
    app_data.sticknumber[0] = app_data.sticknumber[1] = 0;
    set_defjoykeys(0,0);
    set_defjoykeys(1,1);
    set_defsystemkeys();
    app_data.bank = 0;
    app_data.limit = 1;
    app_data.sound_en = 1;
    app_data.speed = 100;
    app_data.wsize = 2;
    app_data.fullscreen = 0;
    app_data.scanlines = 0;
    app_data.voice = 1;
    app_data.window_title = "O2EM v" O2EM_VERSION;
    app_data.svolume = 100;
    app_data.vvolume = 100;
    app_data.filter = 0;
    app_data.exrom = 0;
    app_data.three_k = 0;
    app_data.crc = 0;
    app_data.scshot = scshot;
    app_data.statefile = statefile;
    app_data.euro = 0;
    app_data.openb = 0;
    app_data.vpp = 0;
    app_data.bios = 0;
    app_data.scoretype = 0;
    app_data.scoreaddress = 0;
    app_data.default_highscore = 0;
    app_data.breakpoint = 65535;
    app_data.megaxrom = 0;
    //strcpy(file,"");
    //strcpy(file_l,"");
    //strcpy(bios_l,"");
    //strcpy(bios,"");
    //strcpy(scshot,"");
    //strcpy(statefile,"");
    //strcpy(xrom,"");
    strcpy(scorefile,"highscore.txt");
    //read_default_config();

    init_audio();

    app_data.crc = crc32_file(full_path);

    //suck_bios();
    o2flag = 1;

    crcx = app_data.crc;
    //suck_roms();

    load_bios(bios_file_path);

    load_cart(full_path);
    //if (app_data.voice) load_voice_samples(path2);

    init_display();

    init_cpu();

    init_system();

    set_score(app_data.scoretype, app_data.scoreaddress, app_data.default_highscore);

    return true;
}
Exemple #16
0
int main( void )
{
    init_system();      // initialise host app, pins, watchdog, etc 
    
    init_timer_isr();      // configure timer ISR to fire regularly 

    softuart_init();
    softuart_puts("\nbattir3\n");

    ir_init();

    i2c_init();
    
    blinkm_stop();
    blinkm_setRGB( 0,0,0 );
    _delay_ms(300);

    // a little hello fanfare
    for( int i=0;i<2; i++ ) {
        softuart_printHex16( i );
        softuart_puts("!");
        blinkm_setRGB( 0x02,0x02,0x02);
        _delay_ms(50);
        blinkm_setRGB( 0x01,0x01,0x01);
        _delay_ms(50);
    }
    blinkm_setRGB( 0,0,0 );
    blinkm_playScript(0,0);

    sei();       // enable interrupts 

    softuart_puts(":\n");

    int power_on = 1;
    // loop forever 
    for( ; ; ) {
        if( time_to_measure ) {
            time_to_measure = 0; // clear flag: time to measure touch 

            uint16_t key = ir_getkey();
            if( key==0 )  // no key
                continue;

            softuart_puts("k:");
            softuart_printHex16( key );
            softuart_putc('\n');

            if(      key == IRKEY_ONE ) {
                blinkm_fadeToRGB( 0xff,0x00,0x00 );
            }
            else if( key == IRKEY_TWO ) {
                blinkm_fadeToRGB( 0x00,0xff,0x00 );
            }
            else if( key == IRKEY_THREE ) {
                blinkm_fadeToRGB( 0x00,0x00,0xff );
            }
            else if( key == IRKEY_FOUR ) {
                blinkm_fadeToRGB( 0xff,0xff,0x00 );
            }
            else if( key == IRKEY_FIVE ) {
                blinkm_fadeToRGB( 0x00,0xff,0xff );
            }
            else if( key == IRKEY_SIX ) {
                blinkm_fadeToRGB( 0xff,0x00,0xff );
            }
            else if( key == IRKEY_SEVEN ) {
                blinkm_fadeToRGB( 0x11,0x11,0x11 );
            }
            else if( key == IRKEY_EIGHT ) {
                blinkm_fadeToRGB( 0x80,0x80,0x80 );
            }
            else if( key == IRKEY_NINE ) {
                blinkm_fadeToRGB( 0xff,0xff,0xff );
            }
            else if( key == IRKEY_ZERO ) {
                blinkm_fadeToRGB( 0x00,0x00,0x00 );
            }
            else if( key == IRKEY_VOLUP ) {
                blinkm_setFadespeed( 80 );
            }
            else if( key == IRKEY_VOLDN ) {
                blinkm_setFadespeed( 5 );
            }
            else if( key == IRKEY_POWER ) {
                if( power_on ) { 
                    blinkm_stop();
                    blinkm_fadeToRGB( 0x00,0x00,0x00 );
                    power_on = 0;
                } else {
                    blinkm_playScript(0,0);
                    power_on = 1;
                }
                _delay_ms(500);  // arbitrary wait to approximate key debounce
            }
             else if( key == IRKEY_PLAY ) { 
                blinkm_playScript( 0, 0 );
            }
        }

    } // for
}
Exemple #17
0
/*-----------------------------------------------------------------------------*
 *  Application specific
 *-----------------------------------------------------------------------------*/
static void rpc_demo(void)
{
	int fd, bytes_written, bytes_read;
	char fname[] = "remote.file";
	char wbuff[50];
	char rbuff[1024];
	char ubuff[50];
	float fdata;
	int idata;
	int ret;
	int status = 0;

	/* Initialize HW and SW components/objects */
	init_system();

	env_create_sync_lock(&chnl_cb_flag, LOCKED);

	/* Resource table needs to be provided to remoteproc_resource_init() */
	rsc_info.rsc_tab = (struct resource_table *)&resources;
	rsc_info.size = sizeof(resources);

	/* Initialize OpenAMP framework */
	status = remoteproc_resource_init(&rsc_info, rpmsg_channel_created,
                            rpmsg_channel_deleted, rpmsg_read_cb,
							&proc);
	if (RPROC_SUCCESS != status) {
		/* print error directly on serial port */
		xil_printf("Error: initializing OpenAMP framework\n");
        return;
	}

	/* wait for notification that will happen on channel creation (interrupt) */
	env_acquire_sync_lock(chnl_cb_flag);

	/* redirect I/Os */
	rpmsg_retarget_init(app_rp_chnl, shutdown_cb);

	printf("\r\nRemote>Baremetal Remote Procedure Call (RPC) Demonstration\r\n");
	printf("\r\nRemote>***************************************************\r\n");

	printf("\r\nRemote>Rpmsg based retargetting to proxy initialized..\r\n");

	/* Remote performing file IO on Master */
	printf("\r\nRemote>FileIO demo ..\r\n");

	printf("\r\nRemote>Creating a file on master and writing to it..\r\n");
	fd = open(fname, REDEF_O_CREAT | REDEF_O_WRONLY | REDEF_O_APPEND,
			S_IRUSR | S_IWUSR);
	printf("\r\nRemote>Opened file '%s' with fd = %d\r\n", fname, fd);

	sprintf(wbuff, "This is a test string being written to file..");
	bytes_written = write(fd, wbuff, strlen(wbuff));
	printf("\r\nRemote>Wrote to fd = %d, size = %d, content = %s\r\n", fd,
			bytes_written, wbuff);
	close(fd);
	printf("\r\nRemote>Closed fd = %d\r\n", fd);

	/* Remote performing file IO on Master */
	printf("\r\nRemote>Reading a file on master and displaying its contents..\r\n");
	fd = open(fname, REDEF_O_RDONLY, S_IRUSR | S_IWUSR);
	printf("\r\nRemote>Opened file '%s' with fd = %d\r\n", fname, fd);
	bytes_read = read(fd, rbuff, 1024);
	*(char*) (&rbuff[0] + bytes_read + 1) = 0;
	printf( "\r\nRemote>Read from fd = %d, size = %d, printing contents below .. %s\r\n",
			fd, bytes_read, rbuff);
	close(fd);
	printf("\r\nRemote>Closed fd = %d\r\n", fd);

	while (1) {
		/* Remote performing STDIO on Master */
		printf("\r\nRemote>Remote firmware using scanf and printf ..\r\n");
		printf("\r\nRemote>Scanning user input from master..\r\n");
		printf("\r\nRemote>Enter name\r\n");
		ret = scanf("%s", ubuff);
		if (ret) {
			printf("\r\nRemote>Enter age\r\n");
			ret = scanf("%d", &idata);
			if(ret) {
				printf("\r\nRemote>Enter value for pi\r\n");
				ret = scanf("%f", &fdata);
				if(ret) {
					printf("\r\nRemote>User name = '%s'\r\n", ubuff);
					printf("\r\nRemote>User age = '%d'\r\n", idata);
					printf("\r\nRemote>User entered value of pi = '%f'\r\n", fdata);
				}
			}
		}
		if(!ret) {
			scanf("%s", ubuff);
			printf("Remote> Invalid value. Starting again....");
		} else {
			printf("\r\nRemote>Repeat demo ? (enter yes or no) \r\n");
			scanf("%s", ubuff);
			if((strcmp(ubuff,"no")) && (strcmp(ubuff,"yes"))) {
				printf("\r\nRemote>Invalid option. Starting again....\r\n");
			} else if((!strcmp(ubuff,"no"))) {
				printf("\r\nRemote>RPC retargetting quitting ...\r\n");
				sprintf(wbuff, RPC_CHANNEL_READY_TO_CLOSE);
				rpmsg_retarget_send(wbuff, sizeof(RPC_CHANNEL_READY_TO_CLOSE) + 1);
				break;
			}
		}
	}
	printf("\r\nRemote> Firmware's rpmsg-openamp-demo-channel going down! \r\n");
}
Exemple #18
0
void
bbsstart(void)
{
unsigned char stdinbuf[STDINBUFSIZ];
long    uglastmsg;	/* last msg seen in prev. rm */
long    ugtemp = TWILIGHTZONE;
short   prev_rm = TWILIGHTZONE;
char    cit_cmd;
char    bueller = 0;

  room = &sroom;
  setvbuf(stdin, (char *)stdinbuf, _IOFBF, STDINBUFSIZ);
  setvbuf(stdout, (char *)stdoutbuf, _IOFBF, STDOUTBUFSIZ);

  init_system();
  /* Putty.exe is obstinate */
  /* IAC WILL SGA */
  putchar(IAC); putchar(WILL); putchar(TELOPT_SGA);
  /* magic to set telnet into character mode */
  /* IAC  DO LINEMODE, IAC WILL ECHO */
  write(1,"\377\375\042\377\373\001",6);
  /* let window sizes come through */
  /* IAC DO NAWS */
  write(1,"\377\375\037",3);

  reserve_slot();
  do_login();

  colorize("\n@G");

  curr = LOBBY_RM_NBR;
  inituser();

  openroom();
  storeug(&uglastmsg, &ugtemp);

  /* The first thing we do is make the user read the lobby */
  cit_cmd = 'N';

  readroom(cit_cmd);


  for(;;)
  {
    /*
     * check if user has been kicked out of this room while they were in it,
     * or if room was deleted
     */
    if (ouruser->generation[curr] < 0 || !msg->room[curr].flags)
    {
      curr = LOBBY_RM_NBR;
      openroom();
      storeug(&uglastmsg, &ugtemp);
    }

    if (cit_cmd)
      colorize("\n@Y%s>@G ", msg->room[curr].name);

    checkx(0);

    if (ouruser->f_prog)
      cit_cmd = get_single_quiet("ABCD\005eEFGHIJKLNOpPqQRsSTUvVwWxX\027\030yYZ /?#%@-\"");
    else if (ouruser->f_aide)
      cit_cmd = get_single_quiet("ABC\005eEFGHIJKLNOpPqQRsSTUvVwWxX\027\030yYZ /?#%@-\"");
    else if (ouruser->usernum == msg->room[curr].roomaide && !ouruser->f_twit)
      cit_cmd = get_single_quiet("ABC\005eEFGHIJKLNOpPqQRsSTUwWxX\027\030yYZ /?#%-\"");
    else
      cit_cmd = get_single_quiet("BCeEFGHIJKLNOpPqQRsSTUwWxX\027\030yYZ /?#%-\"");

    if (cit_cmd == SP)
      cit_cmd = 'N';

    if (guest && !strchr("BFGHIJKLNOpPRsSTUwWyY/?#-", cit_cmd))
    {
      colorize("\n\n@RThe Guest user cannot do that.@G\n");
      continue;
    }

    if (curr == LOBBY_RM_NBR && strchr("DGNqsTU\027X\030Z% ", cit_cmd))
    {
      if (bueller++ >= 12)
        flush_input(bueller / 25);
      if (bueller >= 100)
      {
        colorize("@R\n\n\nGo away until you have something useful to do!\n\n\n@G");
        my_exit(10);
      }
    }
    else
      bueller = 0;

    if (strchr("AC\005eEHJpPQSvVx\030yYZ#-\"", cit_cmd))
      mybtmp->nox = 1;

    switch (cit_cmd)
    {

      case 'A':
	printf("Sysop commands (%s)\n", msg->room[curr].name);
	aide_menu();
	break;

      case 'R':
      case 'B':
	cit_cmd = 'R';
	printf("Read Reverse\n");
	readroom(cit_cmd);
	break;

      case 'C':
        printf("Change config\n");
        change_setup(NULL);
	break;

      case 'D':
	printf("Debug\n");
	debug();
	break;

      case '\005':
	if (ouruser->usernum == msg->room[curr].roomaide)
	{
	  printf("Enter Forum Moderator message\n\nAre you sure you want to enter a message as Forum Moderator? (Y/N) -> ");
	  if (!yesno(-1))
	    break;
	  sysopflags |= SYSOP_FROM_FM;
	}
	else if (ouruser->f_admin)
        {
	  printf("Enter Sysop message\n\nNOTE: You are entering this message as Sysop!\n\n");
	  sysopflags |= SYSOP_FROM_SYSOP;
        }
	/* FALL THRU */

      case 'e':
      case 'E':
	{
	  char work[20];

	  if (ouruser->f_newbie && (curr == MAIL_RM_NBR || curr > 4))
	    help("newuseraccess", NO);
	  else
	  {
	    if (cit_cmd == 'E')
	      printf("Upload message\n\n");
	    else if (cit_cmd == 'e')
	      printf("Enter message\n\n");
	    *work = 0;
	    (void)entermessage(curr, work, cit_cmd == 'e' ? 0 : 2);
	    sysopflags &= ~(SYSOP_FROM_SYSOP | SYSOP_FROM_FM);
	  }
	}
	break;

      case 'F':
	printf("Read Forward\n");
	readroom(cit_cmd);
	break;

      case 'G':
	printf("Goto ");
	updatels(&prev_rm);
	/* find next room with unread msgs and open it */
	nextroom();
	openroom();
	storeug(&uglastmsg, &ugtemp);
	break;

      case 'H':
	printf("Help!\n");
	help("topics", YES);
	break;

      case 'q':
      case 'Q':
        get_syself_help(cit_cmd);
        break;

      case 'I':
	printf("Forum Info\n");
	readdesc();
	break;

      case 'J':
	{
	  int old_rm;

	  printf("Jump to ");
	  old_rm = curr;
	  if (findroom() == YES)
	  {
	    int save_rm;
  
            mybtmp->nox = 0;
	    save_rm = curr;
	    curr = old_rm;
	    updatels(&prev_rm);
	    curr = save_rm;
	    openroom();
	    storeug(&uglastmsg, &ugtemp);
	  }
	}
	break;

      case 'K':
	printf("Known forums and zapped list\n");
	knrooms();
	break;

      case 'L':
        dologout();
	break;

      case 'N':
	if (ouruser->lastseen[curr] < room->num[MSGSPERRM - 1])
	{
	  printf("Read New\n");
	  readroom(cit_cmd);
	}
	else
	{			/* No new notes so just do a Goto now */
	  printf("Goto ");
	  updatels(&prev_rm);
	  /* find next room with unread msgs and open it */
	  nextroom();
	  openroom();
	  storeug(&uglastmsg, &ugtemp);
	}
	break;

      case 'O':
	printf("Read Old messages reverse\n");
	readroom(cit_cmd);
	break;

      case 'p':
      case 'P':
	profile_user(cit_cmd == 'P');
	break;

      case 's':		/* don't update lastseen, you're skipping the room */
	printf("Skip %s\n", msg->room[curr].name);
	skipping[curr >> 3] |= 1 << (curr & 7);
	/* after skipping a room, find the next unread room (not a goto) */
	nextroom();
	openroom();
	ugtemp = ouruser->lastseen[curr];
	break;

      case 'S':
	{
	  int old_rm;

	  printf("Skip %s to ", msg->room[curr].name);
	  old_rm = curr;
	  if (findroom() == YES)
	  {
            mybtmp->nox = 0;
	    skipping[old_rm >> 3] |= 1 << (old_rm & 7);
	    openroom();
	    ugtemp = ouruser->lastseen[curr];
	  }
	}
	break;

      case 'T':
	printdate("Time\n\n%s");
	break;

      case 'U':
	printf("Ungoto\n");
	ungoto(prev_rm, &uglastmsg, &ugtemp);
	break;

      case 'v':
	cit_cmd = 0;
	break;

      case 'V':
	printf("Validate new users\n");
	validate_users(1);
	break;

      case '\027':
	if (client)
	  clientwho();
	else
	  cit_cmd = 0;
	break;

      case 'w':		/* Short form of who's online */
	show_online(3);
	break;

      case 'W':		/* Who's online */
	show_online(0);
	break;

      case 'x':
	express();
	break;

      case 'X':
	change_express(1);
	break;

      case CTRL_X:
	old_express();
	break;

      case 'y':
      case 'Y':
        if (!wanttoyell(cit_cmd))
          break;
	(void)entermessage(-1, "", cit_cmd == 'y' ? 0 : 2);
	break;

      case 'Z':
	printf("Zap forum\n");
	if (forgetroom())
        {
	  nextroom();
	  openroom();
	  ugtemp = ouruser->lastseen[curr];
        }
	break;

      case '?':
      case '/':
	if (guest)
	  help("guestforumlevel", NO);
	else
	  help("doccmd", NO);
	break;

      case '#':
	readroom(cit_cmd);
	break;

      case '%':
	if (ouruser->f_elf && !ouruser->f_restricted && !ouruser->f_twit)
          if (mybtmp->xstat && !mybtmp->elf)
            printf("\n\nYou can't enable yourself as a guide while your X's are disabled.\n");
	  else if ((mybtmp->elf = !mybtmp->elf))
	    printf("\n\nYou are now marked as being available to help others.\n");
	  else
	    printf("\n\nYou are no longer marked as being available to help others.\n");
	else
	  cit_cmd = 0;
	break;

      case '-':
	readroom(cit_cmd);
	break;

      case '@':
	printf("Sysops, programmers, and forum moderators\n");
	more(AIDELIST, 0);
	break;

      case '"':
	{
	  char work[20];

	  printf("Quote X messages to Sysop\n");
          *work = 0;
          (void)entermessage(-1, work, -1);
	}
	break;

      default:
	break;
    }				/* switch */

  }
Exemple #19
0
void sleep_stat_hendler( )
{
//  if ( last_sw_stat != SLEEP )
//    {
//      printf( "\n\rTO SLEEP MODE" );
//      last_sw_stat = SLEEP;
//      normal_charging = 0;
//      trickl_charging = 0;
//      red_led = 0;
//      green_led = 0;
//      main_led_stat = 0;
//    }
//  else
//    {
    printf( "\n\r\n\r\n\r sw_stat = SLEEP" );
      //      TRISD = TRISD_MASK_AT_SLEEP;
      //      TRISE = TRISE_MASK_AT_SLEEP;
      FVRCONbits.FVREN = 0; //disnable the FVR

      WDT_cnter = 156; //set counter for WDT evrey 32msec so 156*32=5 sec
      blink_GREEN_LED_and_RED_LED_and_BUZZER( 6, 40 );
      //wait here making shure the user relese the SW
      while  ( !TEST_SW )//continue incation system go to sleep after the user relese the sw
        //  blink_GREEN_LED_and_RED_LED_and_BUZZER( 1, 40 );
        DelayMs( 255 );
      DelayMs( 255 ); //to avoid noise on the SW
      while  ( !TEST_SW )//continue incation system go to sleep after the user relese the sw
        blink_GREEN_LED_and_RED_LED_and_BUZZER( 1, 40 );
      //~~~~~~~time base for 50Ms~~~~~~~~~~~~~~~~
      //do WDT*3 so the timing will be 17Ms*3=49Ms ~50Ms
      //                      pulse_send_interval=my_eeprom_read(PULSE_SENDING_INTERVAL_EE_ADD);//##$$
      //                      WDT_cnter = WDT_MULTIPLYER_FOR_50Ms;

      TRISA = TRISA_MASK_AT_SLEEP;
      TRISB = TRISB_MASK_AT_SLEEP;
      TRISC = TRISC_MASK_AT_SLEEP;
      LATA = 0x00;
      LATB = 0x00;
      LATC = 0x00;

      exit_sleep_count = 0;
      while ( sw_stat == SLEEP )                   //enter to sleep as mutch as needed//##$$
        {
          /////////////////////////////
#ifdef  debeg
          T0CON = 0b11000101;    //1:64 PRESCALER GIVING 16.3ms full range inTMR0
          TMR0 = 0;
          TMR0IE = 0;
          TMR0IF = 0;
          while ( !TMR0IF );
#else
          SLEEP( );
#endif

          //GREEN_LED = 1 - GREEN_LED;

          if ( GREEN_LED )
            GREEN_LED = 0;
          WDT_cnter--;
          if ( !WDT_cnter )
            {
              FVRCONbits.FVRS = 2; //so FVR is 2.048V
              FVRCONbits.FVREN = 1; //enable the FVR
              GREEN_LED = 1;
              WDT_cnter = 156;
                            
              GRID_Voltage_ADC_val = readA2D( ADC_CHANNEL_VIN );
              if ( GRID_Voltage_ADC_val > grid_power_low_voltage ) //grid power is to low
                {
                  DelayMs(30);
                  GRID_Voltage_ADC_val = readA2D( ADC_CHANNEL_VIN );
              
                  if ( GRID_Voltage_ADC_val > grid_power_low_voltage ) //grid power is to low
                    {
                      DelayMs(30);
                      GRID_Voltage_ADC_val = readA2D( ADC_CHANNEL_VIN );

                      if ( GRID_Voltage_ADC_val > grid_power_low_voltage ) //grid power is to low
                        {
                        init_system( ); // Initialize System Function and Variables
                        init_USART( );
                        printf( "\n\r Vin ADC = %d", GRID_Voltage_ADC_val );
                        printf( " GRID POWER DETECTED so WAKING UP" );
                        sw_stat = ST_BY;
                        }
                    }
                }
              if (sw_stat == SLEEP)
              FVRCONbits.FVREN = 0; //disnable the FVR
            }
          
          
          if( !TEST_SW )//press detected
            {
              exit_sleep_count++;
              if ( exit_sleep_count >= exit_sleep_press )
                {
                 
                  init_system( ); // Initialize System Function and Variables
                  init_USART( );
                   printf( "\n\rTEST_SW press detected so" );
                   printf( "WAKING UP" );
                  sw_stat = ST_BY;
                }
            }
          else
            exit_sleep_count = 0;
        }
//    }
}
Exemple #20
0
/* Application entry point */
int main() {

    int status;
    struct remote_proc *proc;
    int i;
	int shutdown_msg = SHUTDOWN_MSG;
    
    /* Switch to System Mode */
    SWITCH_TO_SYS_MODE();

    /* Initialize HW system components */
    init_system();
    
    status = remoteproc_init((void *) fw_name, rpmsg_channel_created, rpmsg_channel_deleted, rpmsg_read_cb, &proc);
    
    if(!status)
    {
        status = remoteproc_boot(proc);
    }
    
    if(status)
    {
	    return -1;	
	}
    while (1) {
		
        if (int_flag) {
			
			if(shutdown_called == 1)
			{
			    break;	
			}

			 /* Process received data and multiple matrices. */
			Matrix_Multiply(&matrix_array[0], &matrix_array[1], &matrix_result);

			/* Send the result of matrix multiplication back to master. */
			rpmsg_send(app_rp_chnl, &matrix_result, sizeof(matrix));
			
			int_flag = 0;
			
			sleep();
        }
        
        sleep();
    }
    
    /* Send shutdown message to remote */
	rpmsg_send(app_rp_chnl, &shutdown_msg, sizeof(int));

    for (i = 0; i < 100000; i++)
    {
	    sleep();
    }
    
    remoteproc_shutdown(proc);
        
    remoteproc_deinit(proc);

    return 0;
}
//=======================================================================================
// EJECUCIÓN FILTRO FIR
//=======================================================================================
int main(int argc, char *argv[])
{
    if (argc > 1)
    {
    }
    else
    {
        printf("The command had no other arguments.\n");
        return 0;
    }

    //<><><><><><><><><><><><><><><><><>//
    // 		SYSTEM INITIALIZING			//
    //<><><><><><><><><><><><><><><><><>//
    init_system();

    //<><><><><><><><><><><><><><><><><>//
    // 		  SIGNALS DECLARATION		//
    //<><><><><><><><><><><><><><><><><>//
    FIR_filter filtro,filtro2,filtro3;
    SIGNAL signal1;
    SIGNAL signal1_output;
    SIGNAL signal2_output;
    SIGNAL signal3_output;

    sscanf (argv[1],"%d",&filtro.F1);
    sscanf (argv[2],"%d",&filtro.F2);
    sscanf (argv[3],"%d",&filtro.order);
    sscanf (argv[4],"%d",&filtro.FS);
    sscanf (argv[5],"%d",&filtro.window_type);
    sscanf (argv[6],"%d",&filtro.filter_type);
    sscanf (argv[7],"%d",&filtro.sw_hw);

//	filtro.F1=12071;
//	filtro.F2=12171;
//	filtro.order=200;
//	filtro.FS=44100;
//	filtro.window_type=BLACKMAN_HARRIS;
//	filtro.filter_type=BS_FILTER;

    //<><><><><><><><><><><><><><><><><>//
    // FILTER COEFFICIENTS CALCULATION	//
    //<><><><><><><><><><><><><><><><><>//
    calc_FIR_coefs(&filtro);
//	calc_FIR_coefs(&filtro2);
//	calc_FIR_coefs(&filtro3);

    //<><><><><><><><><><><><><><><><><>//
    // 			 LOAD FILE 				//
    //<><><><><><><><><><><><><><><><><>//
    load_signal(&signal1,argv[8]);

    //<><><><><><><><><><><><><><><><><>//
    // 		 SIGNAL REPLICATION 		//
    //<><><><><><><><><><><><><><><><><>//
    signal1_output.lenght=signal1.lenght;
//	signal2_output.lenght=signal1.lenght;
//	signal3_output.lenght=signal1.lenght;
    signal1_output.signal=(int*) malloc (sizeof(int)*signal1.lenght);
//	signal2_output.signal=(int*) malloc (sizeof(int)*signal1.lenght);
//	signal3_output.signal=(int*) malloc (sizeof(int)*signal1.lenght);

    //<><><><><><><><><><><><><><><><><>//
    // 			START TIMER				//
    //<><><><><><><><><><><><><><><><><>//
    alt_write_word(h2p_start_timer_addr, 1 );  //0:ligh, 1:unlight

    //<><><><><><><><><><><><><><><><><>//
    // APPLY FILTER & NORMALIZE SIGNAL	//
    //<><><><><><><><><><><><><><><><><>//
    normalize_signal( &signal1, 128);
    apply_FIR_whole_signal(&filtro, &signal1, &signal1_output);
    normalize_signal( &signal1_output, 128);
//	apply_FIR_whole_signal(&filtro2, &signal1_output, &signal2_output);
//	normalize_signal( &signal2_output, 128);
//	apply_FIR_whole_signal(&filtro3, &signal2_output, &signal3_output);
//	normalize_signal( &signal3_output, 128);

    //<><><><><><><><><><><><><><><><><>//
    // 		   GET TICK <TIMER>			//
    //<><><><><><><><><><><><><><><><><>//
    int time_cont;
    time_cont = alt_read_word(p2h_get_tick_addr);
    printf("valor del timer: %d\n",time_cont);

    //<><><><><><><><><><><><><><><><><>//
    // 		   TIMER SHUTDOWN			//
    //<><><><><><><><><><><><><><><><><>//
    alt_write_word(h2p_start_timer_addr, 0 );

    save_signal( &signal1_output, argv[9]);
//	save_signal( &signal2_output, "filtrito2.bin");
//	save_signal( &signal3_output, "filtrito3.bin");

    printf("Finalizando Ejecucion.\n");
    return 0;
}
int
main(int argc, char **argv)
{
    int i;
    char *device;
    char *rasname;
    int physport;
    int ptyiosize;
    int netiosize;
    int retrydelay;
    int retry, nretries;
    int opt;
    int retst;
    int devmodem;
    int closemode;
    int baseport;
    struct sockaddr_un control_addr;
    struct sigaction act;
    struct stat stat_buf;

    act.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &act, NULL))
        sysmessage(MSG_ERR, "Can't block SIGPIPE.\n");

    ptyiosize = DEV_DEFIOSZ;
    netiosize = SOCK_DEFIOSZ;
    retrydelay = RETRY_DELAY;
    nretries = NUM_RETRIES;
    Nvt.servertype = SRV_RTELNET;
    devmodem = DEV_MODEM;
    closemode = CLOSE_HANG;
    baseport = 0;

    Console = FALSE;
    Foreground = FALSE;
    LogFile = NULL;

    Pgname = argv[0];
    Debug = 0;

    while ((opt = getopt(argc, argv, "u:n:r:fi:st:m:c:p:d:xvhHl:")) != EOF) {
        switch (opt) {
        case 'u':
            ptyiosize = atoi(optarg);
            if (ptyiosize > DEV_MAXIOSZ) {
                ptyiosize = DEV_MAXIOSZ;
            }
            break;
        case 'n':
            netiosize = atoi(optarg);
            if (netiosize > SOCK_MAXIOSZ) {
                netiosize = SOCK_MAXIOSZ;
            }
            break;
        case 'r':
            nretries = atoi(optarg);
            break;
        case 'f':
            Foreground = TRUE;
            break;
        case 'i':
            retrydelay = atoi(optarg) * 1000;
            break;
        case 's':
            Nvt.servertype = SRV_SOCKET;
            if (!baseport)
                baseport = SOCKET_BASE;
            break;
        case 'm':
            devmodem = atoi(optarg);
            break;
        case 'c':
            closemode = atoi(optarg);
            break;
        case 'p':
            baseport = atoi(optarg);
            break;
        case 'd':
            Debug = atoi(optarg);
            break;
        case 'x':
            Console = TRUE;
            Foreground = TRUE;
            break;
        case 'v':
            printf("%s\n", Version);
            exit(E_NORMAL);
        case 'l':
            LogFile = strdup(optarg);
            break;
        case 'h':
        case 'H':
        default:
            helpmsg();
            exit(E_PARMINVAL);
        }
    }
    if (!baseport)
        baseport = RTELNET_BASE;

    argc -= optind;
    argv += optind;

    if (argc != 3) {
        helpmsg();
        exit(E_PARMINVAL);
    }

    device = argv[0];

    mkidmsg(Pgname, device);

    rasname = argv[1];

    physport = atoi(argv[2]);

    if (physport == 0) {
        if (Nvt.servertype == SRV_RTELNET) {
            baseport = RTELNET_STD;
        }
        else {
            fprintf(stderr,
                    "%s: Physical port must be > 0 for socket service\n",
                    Idmsg);
            exit(E_PARMINVAL);
        }
    }

    init_system();

    /* Get socket and device addresses */

    if ((retst = dev_getaddr(device)) != E_NORMAL) {
        exit(retst);
    }

    if (Nvt.servertype == SRV_RTELNET) {
        P_contr_listen = socket(PF_UNIX, SOCK_STREAM, 0);
        if (P_contr_listen == -1) {
            sysmessage(MSG_ERR, "Can't create Unix socket.\n");
            exit(1);
        }
        control_addr.sun_family = AF_UNIX;
        snprintf(P_contrname, sizeof(P_contrname), "%s.control", device);
        P_contrname[sizeof(P_contrname) - 1] = '\0';
        if (!stat(P_contrname, &stat_buf)) {
            sysmessage(MSG_WARNING, "Removing old control socket \"%s\".\n",
                       P_contrname);
            unlink(P_contrname);
        }
        strcpy(control_addr.sun_path, P_contrname);
        if (bind
                (P_contr_listen, (struct sockaddr *) &control_addr,
                 sizeof(control_addr)) || listen(P_contr_listen, 8)) {
            sysmessage(MSG_ERR, "Can't bind Unix socket.\n");
            exit(1);
        }
        for (i = 0; i < MAX_CONTROL_SOCKS; i++)
            P_contr[i] = -1;
    }

    if ((retst = sock_getaddr(rasname, baseport, physport)) != E_NORMAL)
        exit(retst);


    retry = 0;

    if (!Foreground)
        daemon(0, 0);

    while (retry < nretries) {

        if (retry) {
            if (retrydelay) {
                sysdelay(retrydelay);
            }
            sysmessage(MSG_WARNING, "Trying again ... \n");
        }


        if ((retst = sock_link(netiosize)) != E_NORMAL) {
            if (retst != E_CONNECT) {
                doexit(retst);
            }
            retry++;
            continue;
        }

        retry = 0;

        tsr_init(netiosize, ptyiosize, devmodem, closemode);

        /* Main scheduler */

        tsr_io();

        retry++;
    }

    sysmessage(MSG_ERR, "Exiting ...\n");

    doexit(E_RETRYEND);

    /* Not Reached */
    return 0;			/* gcc gives a warning otherwise */
}
Exemple #23
0
/**
 *  \brief getting-started Application entry point.
 *
 *  \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	/*Status flags to indicate the re-burst for library */
	uint16_t status_flag = 0u;
	uint16_t burst_flag = 0u;

	/* Initialize the SAM system */
	init_system();

	/* Reset touch sensing */
	qt_reset_sensing();

	/* Configure the Sensors as keys or Keys With Rotor/Sliders in this
	   function */
	config_sensors();

	/* Initialize touch sensing */
	qt_init_sensing();

	/* Set the parameters like recalibration threshold, Max_On_Duration etc
	   in this function by the user */
	qt_set_parameters();

	/* Configure timer ISR to fire regularly */
	init_timer_isr();

	/* Address to pass address of user functions */

	/* This function is called after the library has made capacitive
	   measurements, but before it has processed them. The user can
	   use this hook to apply filter functions to the measured signal
	   values.(Possibly to fix sensor layout faults) */
	qt_filter_callback = 0;

	/* Loop forever */
	for (;;) {
		if (time_to_measure_touch) {
			/* Clear flag: it's time to measure touch */
			time_to_measure_touch = 0u;

			do {
				/*  One time measure touch sensors    */
				status_flag = qt_measure_sensors
							(current_time_ms_touch);

				burst_flag = status_flag & QTLIB_BURST_AGAIN;

				/*Time critical host application code goes here */

			} while (burst_flag);
		}

		/* Get slider value and update the blink frequency */
		if (GET_ROTOR_SLIDER_POSITION(0) != qt_shift_data) {
			qt_shift_data = GET_ROTOR_SLIDER_POSITION(0);
#ifdef QT_DATA_REVERT
			configure_tc((QT_MAX_DATA - qt_shift_data)/LED_FREQ_DIV);
#else
			configure_tc(qt_shift_data/LED_FREQ_DIV);
#endif
		}
	}
}
Exemple #24
0
	fin = init_task_main();

	/* Stop System */
	shutdown_system(fin);	/* Never return */
}

/*
 * Initial task creation parameter
 */
IMPORT const T_CTSK c_init_task;

/*
 * Entry for starting Kernel
 */
EXPORT int main( void )
{
	int err;
	
	DO_DEBUG( tm_monitor(); )

	/* Initialize sequence before T-Kernel starts */
	if (err = init_system()) {
		return(err);
	}

	/* Start T-Kernel */
	t_kernel_main((T_CTSK *)&c_init_task);	/* Never return */

	return 0;
}
Exemple #25
0
int main( void )
{
    /*status flags to indicate the re-burst for library*/
    uint16_t status_flag = 0u;
    uint16_t burst_flag = 0u;
    /* initialise host app, pins, watchdog, etc */
    init_system();

    /* Configure the Sensors as keys or Keys With Rotor/Sliders in this function */
    config_sensors();

    /* initialise touch sensing */
    qt_init_sensing();

    /*  Set the parameters like recalibration threshold, Max_On_Duration etc in this function by the user */
    qt_set_parameters( );

    /* configure timer ISR to fire regularly */
    init_timer_isr();
#ifdef _DEBUG_INTERFACE_
    timestamp1_hword = current_time_ms_touch;
    timestamp1_lword = (uint16_t)TIMER_COUNTER_L;
    timestamp1_lword |= (uint16_t)(TIMER_COUNTER_H << 8);
#endif
    /*  Address to pass address of user functions   */
    /*  This function is called after the library has made capacitive measurements,
    *   but before it has processed them. The user can use this hook to apply filter
    *   functions to the measured signal values.(Possibly to fix sensor layout faults)    */
    qt_filter_callback = 0;
#ifdef _DEBUG_INTERFACE_
		QDebug_Init();
#endif

    /* enable interrupts */
    __enable_interrupt();
#ifdef _DEBUG_INTERFACE_
  /* Process commands from PC */
    QDebug_ProcessCommands();
#endif

    /* loop forever */
   for( ; ; )
   {
      if( time_to_measure_touch )
      {
         /*  clear flag: it's time to measure touch  */
         time_to_measure_touch = 0u;

         do {
 #ifdef _DEBUG_INTERFACE_           
	 	timestamp2_hword = current_time_ms_touch;
        timestamp2_lword = (uint16_t)TIMER_COUNTER_L;
        timestamp2_lword |= (uint16_t)(TIMER_COUNTER_H << 8);
#endif
            /*  one time measure touch sensors    */
            status_flag = qt_measure_sensors( current_time_ms_touch );
 #ifdef _DEBUG_INTERFACE_
		timestamp3_hword = current_time_ms_touch;
        timestamp3_lword = (uint16_t)TIMER_COUNTER_L;
        timestamp3_lword |= (uint16_t)(TIMER_COUNTER_H << 8);
#endif
            burst_flag = status_flag & QTLIB_BURST_AGAIN;
#ifdef _DEBUG_INTERFACE_   
		/* send debug data */ 
        QDebug_SendData(status_flag);
#endif
            /*Time critical host application code goes here*/

         }while (  burst_flag) ;
      }
#ifdef _DEBUG_INTERFACE_
  			/* Process commands from PC */
            QDebug_ProcessCommands();
#endif

      /*  Time Non-critical host application code goes here  */

   }
}
Exemple #26
0
int main(int argc, char const *argv[])
{
    int n_hordas = 0;             //Numero de hordas chamadas
    bool nova_horda = true;       //Chama nova horda

    bool torre_mouse = false;     //Se a torre está no mouse
    bool info_torre = false;      //Chama a funçao de informaçoes da torre
    bool compra_torre = false;    //Exibe as informaçoes da torre a ser comprada
    bool upgrade_torre;           //Guarda os upgrades da torre]

    int tower_posx = 0;           //Posiçao x de determinada torre
    int tower_posy = 0;           //Posiçao y de determinada torre
    int torre_ID;                 //Identifica as torres
    int t = 0;                    //Contagem das torres
    int t_1, t_2;                 //Contagem para disparo

    int r;                        //Variável para colunas
    int l;                        //Variável para linhas
    bool render = false;          //Renderizaçao

    int resposta = 0;             //Resposta se os monstros estão todos mortos

    int gamestate = 0;            //Gamestates

    //Setup inicial
    Sistema sistema;

    Monstro monstro[tipos_monstros][n_monstros];

    Tipo tipo_torre;
    Tipo tipo1;
    Tipo tipo2;
    Tipo upgrade1_torre1;
    Torre torre[100];

    //Declaracao vairaveis allegro
    ALLEGRO_DISPLAY *janela = NULL;	            //Vari�vel para a janela
    ALLEGRO_EVENT_QUEUE *fila_eventos = NULL;   //  ''     para eventos
    ALLEGRO_BITMAP *imagem = NULL;              //  ''     para imagem
    ALLEGRO_TIMER *timer = NULL;                //  ''     para o tempo (fps)
    ALLEGRO_FONT *fonte = NULL;                 //  ''     para fonte
    ALLEGRO_BITMAP *trilha = NULL;
    ALLEGRO_BITMAP *fundao = NULL;
    ALLEGRO_BITMAP *spawn = NULL;
    ALLEGRO_BITMAP *the_end = NULL;
    ALLEGRO_BITMAP *monstro2 = NULL;
    ALLEGRO_BITMAP *torre1 = NULL;
    ALLEGRO_FONT *fonte40 = NULL;

    //Inicializa o allegro, mouse e add-ons
    al_init();
    al_install_mouse();
    al_init_primitives_addon();
    al_init_image_addon();
    al_init_font_addon();
    al_init_ttf_addon();

    //Setup inicial do sistema, monstros e torres
    init_horda(monstro, n_monstros, n_hordas, tipos_monstros);
    init_system(sistema);

    setup_torre1(tipo1);
    setup_torre2(tipo2);

    upgrade1_tower1(upgrade1_torre1);

    //Atribui atributos às variáveis allegro
    janela = al_create_display(LARGURA_TELA, ALTURA_TELA);
    fila_eventos = al_create_event_queue();
    imagem = al_load_bitmap("virus.jpg");
    trilha = al_load_bitmap("fundoc.jpg");
    fundao = al_load_bitmap("fundod.jpg");
    spawn = al_load_bitmap("spawn.jpg");
    the_end = al_load_bitmap("the end.jpg");
    monstro2 = al_load_bitmap("virus2.jpg");
    torre1 = al_load_bitmap("halter.png");
    timer = al_create_timer(1.0 / fps);
    fonte = al_load_font("arial.ttf", 12, 0);
    fonte40 = al_load_font("arial.ttf", 40, 0);

    //Inicializa o mouse e tempo
    al_set_system_mouse_cursor(janela, ALLEGRO_SYSTEM_MOUSE_CURSOR_DEFAULT);
    al_start_timer(timer);
    al_install_keyboard();

    init_fail(janela, fonte, fila_eventos, imagem, timer, trilha); //Fun�ao de teste de inicializaçao do allegro

    //Regista os eventos da janela, mouse e timer na vari�vel de eventos (fila_eventos)
    al_register_event_source(fila_eventos, al_get_display_event_source(janela));
    al_register_event_source(fila_eventos, al_get_mouse_event_source());
    al_register_event_source(fila_eventos, al_get_keyboard_event_source());
    al_register_event_source(fila_eventos, al_get_timer_event_source(timer));

    al_clear_to_color(al_map_rgb(235, 235, 235));       //Limpa a tela
    al_flip_display();                                  //Atualiza a tela

    //Loop principal
    while (!GameOver)
    {
        ALLEGRO_EVENT evento;                           //Variavel para eventos
        al_wait_for_event(fila_eventos, &evento);       //Espera por eventos

        if (evento.type == ALLEGRO_EVENT_DISPLAY_CLOSE)
        {
            GameOver = true;
        }

        switch(gamestate)
        {
        case 0:  //Menu inicial
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                render = true;
            }
            if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_ENTER:
                    gamestate = 1;
                    break;
                case ALLEGRO_KEY_BACKSPACE:
                    gamestate = 2;
                    break;
                }
            }
            break;
        }

        case 1:  //Jogo
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                if(info_torre)
                {
                    if (torre[torre_ID].upgrade == 0 && sistema.money >= 60)
                    {
                        mapa[25][30] = 12;
                    }
                }
                if(!info_torre)
                {
                    mapa[25][30] = 0;
                }

                for(int j = 0; j < t; j++)  //Loop para o disparo das torres
                {
                    if(torre[j].n == 1)
                    {
                        if(t_1 >= fps*(torre[j].fire_rate))
                        {
                            fire_tiro(torre, monstro, t, n_monstros, tipos_monstros); //Dispara tiros
                            t_1 = 0;
                        }
                    }

                    if(torre[j].n == 2)
                    {
                        if(t_2 >= fps*(torre[j].fire_rate))
                        {
                            fire_tiro(torre, monstro, t, n_monstros, tipos_monstros); //Dispara tiros
                            t_2 = 0;
                        }
                    }
                }

                update_horda(monstro, sistema, mapa, n_monstros, tipos_monstros);
                update_tiro(torre, monstro, t, n_monstros, tipos_monstros);
                colisao_horda(torre, monstro, t, n_monstros, sistema, &resposta, tipos_monstros);

                t_1++;
                t_2++;
                render = true;
                if(sistema.lives <= 0)
                    gamestate = 2;
            }



            else if(evento.type == ALLEGRO_EVENT_MOUSE_AXES)
            {
                pos_x = evento.mouse.x; //Armazena a posiçao x do mouse
                pos_y = evento.mouse.y; //Armazena a posiçao y do mouse

                r = pos_x/l_celula; // Atribui uma celula de coluna
                l = pos_y/a_celula; // Atribui uma celula de linha
            }

            else if(evento.type == ALLEGRO_EVENT_MOUSE_BUTTON_DOWN)
            {
                switch (mapa[l][r])
                {
                case 10:
                    info_torre = false;
                    compra_torre = true;
                    tipo_torre = tipo1;
                    if(sistema.money >= tipo_torre.price && evento.mouse.button & 1)
                        torre_mouse = true;
                    break;
                case 20:
                    info_torre = false;
                    compra_torre = true;
                    tipo_torre = tipo2;
                    if(sistema.money >= tipo_torre.price && evento.mouse.button & 1)
                        torre_mouse = true;
                    break;
                case 11:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                case 12:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                case 21:
                    torre_ID = find_tower_ID(torre, t, r, l);
                    info_torre = true;
                    break;
                default:
                    info_torre = false;
                }

                if(torre_mouse && (mapa[l][r] == 0 || mapa[l][r] == 5) && evento.mouse.button & 1) //Posicionamento da torre enquanto ela estiver no mouse
                {
                    setup_tower(torre, tipo_torre, t, r, l);
                    sistema.money -= tipo_torre.price;      //Pagamento da torre
                    torre_mouse = false;
                    compra_torre = false;
                    t++;
                }

                if(torre_mouse && evento.mouse.button & 2)  //Cancela compra
                {
                    torre_mouse = false;
                    compra_torre = false;
                }

                if(compra_torre && mapa[l][r] != 10 && mapa[l][r] != 20)  //Termina a exibiçao da torre a ser comprada
                {
                    compra_torre = false;
                }

                if(info_torre && mapa[l][r] == 12 )
                {
                    sistema.money -= 60;
                    torre_ID = find_tower_ID(torre, t, r, l);
                    upgrade_tower(torre, upgrade1_torre1, torre_ID);
                    //upgrade_torre = true;
                }
            }

            else if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                printf("resposta = %d\n", resposta);
                if(resposta == 1 || n_hordas == 0)
                {
                    switch(evento.keyboard.keycode)
                    {
                    case ALLEGRO_KEY_SPACE: //Inicializa uma nova horda
                        start_horda(monstro, n_monstros, n_hordas, tipos_monstros);
                        n_hordas++;
                        break;
                    }
                }
            }
        }
        break;

    case 2: //Fim de jogo
        {
            if(evento.type == ALLEGRO_EVENT_TIMER)
            {
                render = true;
            }
            if(evento.type == ALLEGRO_EVENT_KEY_DOWN)
            {
                switch(evento.keyboard.keycode)
                {
                case ALLEGRO_KEY_R:
                    init_system(sistema);
                    init_horda(monstro, n_monstros, n_hordas, tipos_monstros);
                    restart_tower(torre, t);
                    n_hordas = 0;
                    setup_array(mapa);
                    gamestate = 1;
                    break;
                case ALLEGRO_KEY_ESCAPE:
                    GameOver = true;
                    break;
                }
            }
            break;
        }
    }

    if(render && al_is_event_queue_empty(fila_eventos))
    {
        render = false;

        if(gamestate == 0)
        {
            al_clear_to_color(al_map_rgb(255,255,255));
            al_draw_textf(fonte, al_map_rgb(0, 0, 255), LARGURA_TELA/2, (ALTURA_TELA/2) - 20, 0, "Pressione ENTER para Jogar");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) + 20, 0, "Pressione BACKSPACE para Sair");
        }
        if(gamestate == 1)
        {
            al_clear_to_color(al_map_rgb(61, 10, 10));

            draw_background(mapa, fonte, trilha, fundao, spawn, the_end); //Desenha o plano de fundo
            draw_towers(mapa, sistema, fonte, the_end, torre1); //Desenha as torres

            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 900, 15, ALLEGRO_ALIGN_LEFT, "Vidas do sistema %i", sistema.lives);
            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 900, 35, ALLEGRO_ALIGN_LEFT, "Bitcoins %.2f", sistema.money);
            al_draw_textf(fonte, al_map_rgb(255, 255, 255), 100, 15, ALLEGRO_ALIGN_LEFT, "Monstros mortos: %i  Wave: %i", sistema.score, n_hordas);
            /*
            Mouse debug     al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y, ALLEGRO_ALIGN_LEFT, "l:%i r:%i", l, r);
                            al_draw_textf(fonte, al_map_rgb(0, 0, 0), pos_x, pos_y + 15, ALLEGRO_ALIGN_CENTRE, "mapa[l][r]: %i", mapa[l][r]);
            */
            draw_horda(monstro, n_monstros, imagem, tipos_monstros, monstro2); //Desenha os montros

            if(torre_mouse)
            {
                draw_mouse_tower(r, l, tipo_torre); //Desenha a torre somente enquanto ela estiver no mouse
            }
            if(info_torre)
            {
                show_tower_information(torre, torre_ID, fonte); //info torres
                if (mapa[25][30] == 12)
                {
                    al_draw_filled_circle(25 * l_celula + (l_celula/2), 30 * a_celula + (a_celula/2), l_celula/2, al_map_rgb(40, 150, 10));
                }
            }
            if(compra_torre)
            {
                buy_tower(tipo_torre, fonte); //Exibe as informaçoes da torre a ser comprada
            }

            draw_tiro(torre, t); //Desenha os tiros
        }
        if(gamestate == 2)
        {
            al_clear_to_color(al_map_rgb(255,255,255));
            al_draw_textf(fonte40, al_map_rgb(255, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) - 100, 0, "Game Over");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) - 20, 0, "Pressione R para Jogar Novamente");
            al_draw_textf(fonte, al_map_rgb(0, 0, 0), LARGURA_TELA/2, (ALTURA_TELA/2) + 20, 0, "Pressione ESC para Sair");
        }

        al_flip_display();
    }
}

destroy_al(janela, fonte, fila_eventos, imagem, timer); //Destroi as vari�veis allegro

return 0;
}