int main(void)
{
	system_init();

//! [main_1]
//! [critical_section_start]
	system_interrupt_enter_critical_section();
//! [critical_section_start]

//! [do_critical_code]
	if (is_ready == true) {
		/* Do something in response to the global shared flag */
		is_ready = false;
	}
//! [do_critical_code]

//! [critical_section_end]
	system_interrupt_leave_critical_section();
//! [critical_section_end]
//! [main_1]

//! [main_2]
//! [module_int_enable]
	system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_RTC);
//! [module_int_enable]

//! [global_int_enable]
	system_interrupt_enable_global();
//! [global_int_enable]
//! [main_2]

	while (true) {
		/* Infinite loop */
	}
}
Esempio n. 2
0
/*---------------------------------------------------------------------------*/
void
button_sensor_init(void)
{
  struct extint_chan_conf config_extint_chan;
  struct port_config pin_conf;
  port_get_config_defaults(&pin_conf);
  pin_conf.direction  = PORT_PIN_DIR_INPUT;
  pin_conf.input_pull = PORT_PIN_PULL_UP;
  port_pin_set_config(BUTTON_0_PIN, &pin_conf);

  //  extint_enable();
  extint_chan_get_config_defaults(&config_extint_chan);
  config_extint_chan.gpio_pin           = BUTTON_0_EIC_PIN;
  config_extint_chan.gpio_pin_mux       = BUTTON_0_EIC_MUX;
  config_extint_chan.gpio_pin_pull      = EXTINT_PULL_UP;
  config_extint_chan.detection_criteria = EXTINT_DETECT_FALLING;
  // config_extint_chan.detection_criteria = EXTINT_DETECT_BOTH;
  extint_chan_set_config(BUTTON_0_EIC_LINE, &config_extint_chan);

  extint_register_callback((extint_callback_t)extint_detection_callback,
                           BUTTON_0_EIC_LINE,
                           EXTINT_CALLBACK_TYPE_DETECT);
  extint_chan_enable_callback(BUTTON_0_EIC_LINE, EXTINT_CALLBACK_TYPE_DETECT);

  timer_set(&debouncetimer, 0);
  system_interrupt_enable_global();

  /* on by default */
  button_sensor_configure(0, 1);

}
int main(void)
{
	system_init();

//! [setup_init]
	configure_usart();
	configure_usart_callbacks();
//! [setup_init]

//! [main]
//! [enable_global_interrupts]
	system_interrupt_enable_global();
//! [enable_global_interrupts]

//! [main_send_string]
	uint8_t string[] = "Hello World!\r\n";
	usart_write_buffer_job(&usart_instance, string, sizeof(string));
//! [main_send_string]

//! [main_loop]
	while (true) {
//! [main_loop]
//! [main_read]
		usart_read_buffer_job(&usart_instance,
				(uint8_t *)rx_buffer, MAX_RX_BUFFER_LENGTH);
//! [main_read]
	}
//! [main]
}
Esempio n. 4
0
int main(void)
{
	system_init();

//! [setup_init]
	configure_adc();
	configure_adc_callbacks();
//! [setup_init]

//! [main]
//! [enable_global_interrupts]
	system_interrupt_enable_global();
//! [enable_global_interrupts]

//! [start_adc_job]
	adc_read_buffer_job(&adc_instance, adc_result_buffer, ADC_SAMPLES);
//! [start_adc_job]

//! [job_complete_poll]
	while (adc_read_done == false) {
		/* Wait for asynchronous ADC read to complete */
	}
//! [job_complete_poll]

//! [inf_loop]
	while (1) {
		/* Infinite loop */
	}
//! [inf_loop]
//! [main]
}
Esempio n. 5
0
/**
 * \brief Application entry point.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	//SystemInit();
	
	// Set the registers for input and output
	board_led_setup();
	
	system_init();
	
	port_pin_set_output_level(LED_DEBUG, false);
	
	while ( !system_clock_source_is_ready(SYSTEM_CLOCK_SOURCE_DPLL) ) {
	}
	

	/* Initialize the SAM system */
	
	// TCC Configuration
	tcc_configure_function();		// Counter Configuration
	tcc_callback_configuration();	// Timer Callback Configuration
	
	// Run SERCOM Setup
	bastian_complete_sercom_setup();	

	system_interrupt_enable_global();	// Enable all sources of interrupt
	//spi_transceive_buffer_job(&spi_slave, slave_empty_response_buffer, slave_rx_buffer, SYSTEM_SLAVE_RX_BYTES_TO_RECEIVE);
	// Send IrDA data only once
	//
	//usart_read_buffer_job(&irda_master, slave_rx_buffer, 1);	// Read only one character
	
    while (1) {
		//usart_read_buffer_job(&irda_master, slave_rx_buffer, 1);	// Read only one character	
		
    }
}
unsigned long millis(void)
{
	system_interrupt_disable_global();
	uint32_t tc_count = tc_get_count_value(&tc6_instance);
	system_interrupt_enable_global();
	return (((tc6_overflows<<16)+tc_count)*(1/8000.0));
}
Esempio n. 7
0
int main(void)
{
	system_init();

//! [setup_init]
	_configure_i2s();
	_configure_i2s_callbacks();
//! [setup_init]

//! [main]
	//! [enable_global_interrupts]
	system_interrupt_enable_global();
	//! [enable_global_interrupts]

//! [start_job]
	i2s_serializer_write_buffer_job(&i2s_instance,
			I2S_SERIALIZER_0, data_buffer, 4);
//! [start_job]

	//! [main_loop]
	while (true) {
	}
	//! [main_loop]
//! [main]
}
Esempio n. 8
0
int main (void)
{
	system_init();

  configure_port_pins();

  configure_usart();

  printf("--TEST prepare: ATMEL SAMD10 watchdog callback!\r\n");
  
  configure_wdt();
  configure_wdt_callbacks();  
  
  printf("--TEST prepare: Config WDT:4096 ms!\r\n");
  printf("--TEST prepare: Config WDT:Early Warning,2048ms!\r\n");
  
  system_interrupt_enable_global();

  printf("--TEST prepare: Enable gobale Interrupt!\r\n");
  
  printf("--TEST information: Waitting for WDT Early Warning Interrupt!\r\n");  
  printf("\r\n\r\n\r\n");    

  while(1)
  {
    ;
  }
	/* Insert application code here, after the board has been initialized. */
}
Esempio n. 9
0
int main(void)
{

	//! [setup_init]
	struct tc_module       tc_instance;
	struct events_resource example_event;
	struct events_hook     hook;

	system_init();
	system_interrupt_enable_global();

	configure_event_channel(&example_event);
	configure_event_user(&example_event);
	configure_event_interrupt(&example_event, &hook);
	configure_tc(&tc_instance);
	//! [setup_init]

	//! [main]

	//! [main_1]
	while (events_is_busy(&example_event)) {
		/* Wait for channel */
	};
	//! [main_1]

	//! [main_2]
	tc_start_counter(&tc_instance);
	//! [main_2]

	while (true) {
		/* Nothing to do */
	}

	//! [main]
}
Esempio n. 10
0
int main(void)
{
	system_init();
	configure_usart();
	configure_usart_callbacks();
	
	struct port_config pin_conf;
	port_get_config_defaults(&pin_conf);

	/* Configure LEDs as outputs, turn them off */
	pin_conf.direction  = PORT_PIN_DIR_OUTPUT;
	port_pin_set_config(LED_1_PIN, &pin_conf);
	port_pin_set_output_level(LED_1_PIN, LED_1_INACTIVE);

	/* Set buttons as inputs */
	pin_conf.direction  = PORT_PIN_DIR_INPUT;
	pin_conf.input_pull = PORT_PIN_PULL_UP;
	port_pin_set_config(BUTTON_1_PIN, &pin_conf);


#if USE_EIC == true
	configure_extint();
#endif

#if USE_INTERRUPTS == true
#  if USE_EIC == false
	configure_systick_handler();
#  else
	configure_eic_callback();
#  endif

	system_interrupt_enable_global();

	uint16_t temp;
	while (true) {
		/* Do nothing - use interrupts */
		//if (usart_read_wait(&usart_instance, &temp) == STATUS_OK)
		//{
			//while (usart_write_wait(&usart_instance, temp) != STATUS_OK);
		//}
		usart_read_buffer_job(&usart_instance, (uint8_t *)rx_buffer, 1);
		//sleepmgr_sleep(SLEEPMGR_STANDBY);
	}
#else
#  if USE_EIC == false
	while (true) {
		update_led_state();
	}
#  else
	while (true) {
		if (extint_chan_is_detected(BUTTON_1_EIC_LINE)) {
			extint_chan_clear_detected(BUTTON_1_EIC_LINE);

			update_led_state();
		}
	}
#  endif
#endif
}
Esempio n. 11
0
/*==============================================================================
 hal_extIntInit()
 =============================================================================*/
uint8_t hal_extIntInit( en_targetExtInt_t e_intSource,
        pfn_intCallb_t pfn_intCallback )
{
    int8_t c_ret = 0;

    if( pfn_intCallback != NULL )
    {
        switch( e_intSource )
        {
            case E_TARGET_RADIO_INT:
                //! [setup_init]
                //extint_enable();

                //! [conf_channel]
                //! [setup_1]
                extint_chan_get_config_defaults( &( radio_extInt.st_chan ) );
                //! [setup_1]

                //! [setup_2]
                radio_extInt.st_chan.gpio_pin = radio_extInt.l_pin; //EXT1_IRQ_PIN;
                radio_extInt.st_chan.gpio_pin_mux = radio_extInt.l_pinMux; //MUX_PB04A_EIC_EXTINT4;
                radio_extInt.st_chan.gpio_pin_pull = radio_extInt.c_pinPull; //EXTINT_PULL_DOWN;
                radio_extInt.st_chan.detection_criteria =
                        radio_extInt.c_detCrit; //EXTINT_DETECT_RISING;
                //! [setup_2]

                //! [setup_3]
                extint_chan_set_config( (uint8_t)radio_extInt.l_line,
                        &( radio_extInt.st_chan ) );
                //! [setup_3]

                _radio_callback = pfn_intCallback;
                //! [setup_4]
                extint_register_callback(
                        (extint_callback_t)_isr_radio_callback,
                        (uint8_t)radio_extInt.l_line,
                        EXTINT_CALLBACK_TYPE_DETECT );
                //! [setup_4]
                //! [setup_5]
                extint_chan_enable_callback( (uint8_t)radio_extInt.l_line, //EXT1_IRQ_INPUT,
                        EXTINT_CALLBACK_TYPE_DETECT );
                //! [setup_6]

                //! [conf_channel]
                //! [setup_init]
                system_interrupt_enable_global();
                c_ret = 1;
                break;
            case E_TARGET_USART_INT:
                break;
            default:
                break;
        }
    }
    return c_ret;

} /* hal_extIntInit() */
Esempio n. 12
0
/**
 * \brief      Init the radio
 * \return     Returns success/fail
 * \retval 0   Success
 */
static int
rf212_init(void)
{
  volatile uint8_t regtemp;
   uint8_t radio_state;  /* don't optimize this away, it's important */
  //uint8_t temp;
  PRINTF("RF212: init.\n");

  /* init SPI and GPIOs, wake up from sleep/power up. */
  //rf212_arch_init();
  trx_spi_init();
 
  /* reset will put us into TRX_OFF state */
  /* reset the radio core */
  port_pin_set_output_level(AT86RFX_RST_PIN, false);
  delay_cycles_ms(1);
  port_pin_set_output_level(AT86RFX_RST_PIN, true);
  
  port_pin_set_output_level(AT86RFX_SLP_PIN, false); /*wakeup from sleep*/

  /* before enabling interrupts, make sure we have cleared IRQ status */
  regtemp = trx_reg_read(RF212_REG_IRQ_STATUS);
  printf("After wake from sleep\n");
  radio_state = rf212_status();
  printf("After arch read reg: state 0x%04x\n", radio_state);
 
  /* Assign regtemp to regtemp to avoid compiler warnings */
  regtemp = regtemp;
if(radio_state == STATE_P_ON) {
	trx_reg_write(RF212_REG_TRX_STATE, TRXCMD_TRX_OFF);
	}  
  trx_irq_init((FUNC_PTR)rf212_interrupt_poll);
  ENABLE_TRX_IRQ();  
  system_interrupt_enable_global();
  /* Configure the radio using the default values except these. */
  trx_reg_write(RF212_REG_TRX_CTRL_1,      RF212_REG_TRX_CTRL_1_CONF);
  trx_reg_write(RF212_REG_PHY_CC_CCA,      RF212_REG_PHY_CC_CCA_CONF);
  trx_reg_write(RF212_REG_PHY_TX_PWR_CONF, RF212_REG_PHY_TX_PWR_CONF);
  //temp = rf212_arch_read_reg(RF212_REG_TRX_CTRL_2);
  trx_reg_write(RF212_REG_TRX_CTRL_2, RF212_REG_TRX_CTRL_2_CONF);
  trx_reg_write(RF212_REG_IRQ_MASK,        RF212_REG_IRQ_MASK_CONF);
#if HW_CSMA_FRAME_RETRIES
  trx_bit_write(SR_MAX_FRAME_RETRIES, 3);
  trx_bit_write(SR_MAX_CSMA_RETRIES, 4);
#else  
  trx_bit_write(SR_MAX_FRAME_RETRIES, 0);
  trx_bit_write(SR_MAX_CSMA_RETRIES, 7);
#endif  
  SetPanId(IEEE802154_CONF_PANID);
  rf_generate_random_seed();
  /* start the radio process */
  process_start(&rf212_radio_process, NULL);
  return 0;
}
Esempio n. 13
0
/*==============================================================================
  hwinit_init()
==============================================================================*/
int8_t hal_init (void)
{
	system_init();

	_hal_usartInit();
	_hal_wdtInit();
	_hal_tcInit();
	_hal_ledInit();
	delay_init();
	system_interrupt_enable_global();
	return 1;
}/* hal_init() */
Esempio n. 14
0
/*==============================================================================
 hwinit_init()
 ==============================================================================*/
int8_t hal_init( void )
{
    system_init();

    _hal_usartInit();
    _hal_wdtInit();
    _hal_tcInit();
#if    LEDS_ON_BOARD == TRUE
    _hal_ledInit();
#endif
    delay_init();
    system_interrupt_enable_global();
    return 1;
}/* hal_init() */
Esempio n. 15
0
int main (void)
{
	system_init();
	system_interrupt_enable_global();
	
	
	/* Configure various sensors and their associated peripherals */
  	configure_i2c();
  	
 	configure_mag_sw_int(extint_callback);
  	configure_S70FL01(S70FL01_CS1, false);
  	configure_SP1ML();
  	configure_ADXL375(); 	
 	configure_sleepmode();
  	configure_rtc();
	port_pin_set_output_level(SP1ML_EN_PIN,true);
	configure_ADT7420();
	configure_databuffers();
	
	// Assume that we are in active mode during stationary period
	ucActiveInactive_Mode = ACTIVE_MODE;
	ucMotion_State = STATIONARY_MODE;
	
	// Per Dr. Buck, 30C is the pivot point -- These don't necessarily have to be the same, they can build in some hysteresis depending upon the subject
	ucActivityTemperatureThreshold = 30;
	ucInactivityTemperatureThreshold = 30;
	
	while(true)
	{	
		if((uiAccelerometerMatrixPtr > (300 - 32)) || (ucTemperatureArrayPtr > 71)){
			// Accelerometer total buffer size minus the ADXL375 internal FIFO size
			// If either buffer is full enough that another set of samples cannot be stored, trigger an offload
			offload_data();
			uiAccelerometerMatrixPtr = 0;
			ucTemperatureArrayPtr = 0;
		}
		// If we are at the end of the die, then switch die and reset the address pointer
		// If we hit the end of the second die, then we restart at the beginning of the first die (ring buffer)
		if(S70FL01_address >= S70FL01_MAX_ADDR){
			S70FL01_active_die++;
			S70FL01_active_die %= 2;
			S70FL01_address = 0;
		}
		ADT7420_read_temp();
		// Housekeeping done -- go back to sleep
		sleep();
	}
}
int main(void)
{
	system_init();

	//! [setup_init]
	configure_extint_channel();
	configure_extint_callbacks();

	system_interrupt_enable_global();
	//! [setup_init]

	//! [main]
	while (true) {
		/* Do nothing - EXTINT will fire callback asynchronously */
	}
	//! [main]
}
Esempio n. 17
0
int main(void) {
	system_init();

	cph_millis_init();
	cph_stdio_init();

	TRACE("DECAWAVE CPH       \r\n");
	TRACE(SOFTWARE_VER_STRING);
	TRACE("\r\n");

	uint32_t f = system_gclk_gen_get_hz(0);
	TRACE("CPU FREQ: %lu\r\n", f);

	// Blink LED for 5 seconds
	for (int i = 0; i < (5 * 4); i++) {
		port_pin_set_output_level(LED_PIN, false);
		cph_millis_delay(125);
		port_pin_set_output_level(LED_PIN, true);
		cph_millis_delay(125);
	}

	// init cph_deca
//#ifdef ANCHOR
//	anchor_init();
//#else
//	tag_init();
//#endif
	ss_twr_init();	// blocks

	system_interrupt_enable_global();

	uint32_t count = 0;
	uint32_t timestamp = cph_get_millis();
	uint32_t elapsed = 0;
	while (1) {
		cph_deca_run();
		elapsed = (cph_get_millis() - timestamp);
		if (elapsed > 5000) {
			timestamp = cph_get_millis();
			cph_deca_print_status(count++);
		}
	}



}
Esempio n. 18
0
/*
 *	@fn		nm_bsp_init
 *	@brief	Initialize BSP
 *	@return	0 in case of success and -1 in case of failure
 */
sint8 nm_bsp_init(void)
{
	gpfIsr = NULL;

	/* Initialize chip IOs. */
	init_chip_pins();

    /* Make sure a 1ms Systick is configured. */
    if (!(SysTick->CTRL & SysTick_CTRL_ENABLE_Msk && SysTick->CTRL & SysTick_CTRL_TICKINT_Msk)) {
	    delay_init();
    }

	/* Perform chip reset. */
	nm_bsp_reset();

	system_interrupt_enable_global();

	return M2M_SUCCESS;
}
Esempio n. 19
0
void sys_init_timing(void)
{
	struct tc_config config_tc;
	tc_get_config_defaults(&config_tc);

	config_tc.counter_size    = TC_COUNTER_SIZE_16BIT;
	config_tc.wave_generation = TC_WAVE_GENERATION_MATCH_FREQ;
	config_tc.counter_16_bit.compare_capture_channel[0] = 0x5DC0;
	config_tc.clock_source = GCLK_GENERATOR_0;
	config_tc.clock_prescaler = TC_CLOCK_PRESCALER_DIV2;

	tc_init(&tc_instance, TIMER, &config_tc);
	tc_enable(&tc_instance);
	tc_register_callback(&tc_instance, tc_callback, TC_CALLBACK_CC_CHANNEL0);
	tc_enable_callback(&tc_instance, TC_CALLBACK_CC_CHANNEL0);

	/* Enable system interrupts. */
	system_interrupt_enable_global();
}
Esempio n. 20
0
int main(void)
{
	system_init();

//! [setup_init]
	configure_tcc();
	configure_tcc_callbacks();
//! [setup_init]

//! [main]
	//! [enable_global_interrupts]
	system_interrupt_enable_global();
	//! [enable_global_interrupts]

	//! [main_loop]
	while (true) {
	}
	//! [main_loop]
//! [main]
}
Esempio n. 21
0
int main(void) {

	system_init();

	cph_millis_init();
	cph_stdio_init();

	uint32_t f = system_gclk_gen_get_hz(0);
	printf("CPU FREQ: %lu\r\n", f);

	system_interrupt_enable_global();

	decawave_run();

//	while (1) {
//		printf("HELLO\r\n");
//		port_pin_toggle_output_level(LED_PIN);
//		cph_millis_delay(500);
//	}

}
Esempio n. 22
0
int main (void)
{
	/* Prepare the hardware for the demo. */
	prvSetupHardware();
    //lepton kernel start 
   _start_kernel(0);
   //lepton_start();
	//
   system_interrupt_enable_global();
   //
   /* Start the scheduler. */
	vTaskStartScheduler();
   
	
	/* If all is well, the scheduler will now be running, and the following line
	will never be reached.  If the following line does execute, then there was
	insufficient FreeRTOS heap memory available for the idle and/or timer tasks
	to be created.  See the memory management section on the FreeRTOS web site
	for more details. */
	for( ;; );	

}
Esempio n. 23
0
int main(void)
{
	system_init();

#if USE_EIC == true
	configure_extint();
#endif

#if USE_INTERRUPTS == true
#  if USE_EIC == false
	configure_systick_handler();
#  else
	configure_eic_callback();
#  endif

	system_interrupt_enable_global();

	while (true) {
		/* Do nothing - use interrupts */
	}
#else
#  if USE_EIC == false
	while (true) {
		update_led_state();
	}
#  else
	while (true) {
		if (extint_chan_is_detected(BUTTON_0_EIC_LINE)) {
			extint_chan_clear_detected(BUTTON_0_EIC_LINE);

			update_led_state();
		}
	}
#  endif
#endif
}
Esempio n. 24
0
int main(void)
{
	struct port_config pin;
	unsigned int count;
	unsigned char Write_Reg_DRATE[3]={0x53,0x01,0xc0};
	unsigned char Read_Reg_DRATE[2]={0x11,0x02};
	unsigned char read_buffer[10]={0};
	unsigned char read_data;
	unsigned int result;
	unsigned char Init_Data[5]={0x51,0x02,0x08,0x20,0xA1};
	unsigned char RDATAC[1]={0x03};
	unsigned char SDATAC[1]={0x0F};
	unsigned char RDATA[1] ={0x01};
	system_init();

	/*Configure UART console.*/
	configure_console();

	/*Initialize the delay driver*/
	delay_init();

	/* Output example information */
	puts(STRING_HEADER);

	/*Enable system interrupt*/
	system_interrupt_enable_global();


	//SPI0TX = 0x51;  // ADS1256_CMD_WREG | ADS1256_REG_MUX;
	//SPI0TX = 0x02;	// write 3 registers starting REG_MUX
	//SPI0TX = 0x08;	// REG_MUX
	//SPI0TX = 0x20;	// REG_ADCON
	//SPI0TX = 0xA1;	// REG_DRATE, set to 1ksps
	
	spi_init();
		
	ss_enable(1);
	delay_us(10);
	spi_write(Init_Data,5);
	delay_us(10);
	ss_enable(0);
	
	ss_enable(1);
	delay_us(10);
	spi_write(Read_Reg_DRATE,2);
	spi_read(read_buffer,3);
	delay_us(10);
	ss_enable(0);
	delay_us(10);
	
	count = 1;
	
	while(1)
	{
		result = 0;
		
		ss_enable(1);	
		delay_us(2);	
		//spi_write(RDATAC,1);
		spi_write(RDATA,1);
		while(ADS1256_DRDY);
		//while(1){
			//while(!ADS1256_DRDY);
			//if(ADS1256_DRDY == 0){
				spi_read(read_buffer,3);
			//	break;
			//}
		//}	
		//spi_write(SDATAC,1);
		delay_us(2);
		ss_enable(0);
		result = read_buffer[0] << 16 | read_buffer[1] << 8 | read_buffer[2];
		printf("#%d,0x%x\r\n",count++,result );	
		delay_ms(100);
	}
	
}
Esempio n. 25
0
/**
 *  \brief getting-started Application entry point.
 *
 *  \return Unused (ANSI-C compatibility).
*/
int main(void)
{
    struct port_config pin;
    unsigned char c;

    system_init();

    //Configure UART console.
    configure_console();

    configure_usart_callbacks();
    usart_enable_rx_interrupt(&cdc_uart_module,&c);

    usart_enable(&cdc_uart_module);
    //Configures  TC driver
    configure_tc();

    //Configures TC callback
    configure_tc_callbacks();

    //Initialize the delay driver
    delay_init();

    //Enable system interrupt
    system_interrupt_enable_global();

    //Configures PORT for LED0
    port_get_config_defaults(&pin);
    pin.direction = PORT_PIN_DIR_OUTPUT;
    port_pin_set_config(LED0_PIN, &pin);

    port_pin_set_output_level(LED0_PIN, LED0_INACTIVE);
    port_pin_set_output_level(LED0_PIN, LED0_INACTIVE);

    /*main loop*/
    while(1)
    {
        if (is_running)
        {
            //Handle user's input
            //		if (uart_getc(&c))
            //		{
            switch (c)
            {
            case 'w':
            case ' ':
                //ROTATE
                tetris_rotate();
                break;
            case 's':
                //DOWN
                tetris_gravity();
                break;
            case 'd':
                //RIGHT
                tetris_move_right();
                break;
            case 'a':
                //LEFT
                tetris_move_left();
                break;
            default:
                break;
            }
            c=0;
            //		}
            // was here if(!iterate_game)
            if(iterate_game)
            {
                //Update game
                iterate_game = false;
                tetris_gravity();
                tetris_check_lines();
                terminal_cursor_home();
                tetris_print();
                if (tetris_is_game_over())
                {
                    is_running = false;
                }
            }
        }
        else
        {
            //	if (uart_getc(&c))
            //	{
            if (c == 'n')
            {
                c=0;
                //Seed random function so we do not get same start condition
                //for each new game. In essence we will not start a new game
                //exactly at the same time.
                srand(tick);

                //New Game
                is_running = true;
                terminal_cursor_off();
                terminal_clear();
                tetris_init();
                tetris_new_block();
                terminal_cursor_home();
                tetris_print();
            }
            //	}
        }
    }
}
Esempio n. 26
0
int main(void)
{
    /**
     * Initialize and configure system and generic clocks.
     * Use conf_clocks.h to configure system and generic clocks.
     */
    system_init();

    hal_if_usart_init();

    /**
     * Enable global interrupts.
     */
    system_interrupt_enable_global();

    /**
     * Initialize delay service.
     */
    delay_init();

    /* initialize timer */
    timer_init();

    /* Setup and enable generic clock source for PTC module. */
    surface_configure_ptc_clock();

    touch_time.measurement_period_ms = DEF_TOUCH_MEASUREMENT_PERIOD_MS;


    /* Initialize touchpad input parameters */
    qts_init_surface();

    qts_sensors_config();

    /*initialize event system*/
#if (DEF_SURF_LOW_POWER_SENSOR_ENABLE == 1)
    init_evsys_config();
#endif

    /* Configure System Sleep mode to STANDBY. */

    system_set_sleepmode(SYSTEM_SLEEPMODE_STANDBY);
#ifdef POWER_OPT_ENABLE
    turn_off_bod33();
    configure_power_manager();

#endif

    /* Calibration */
    qts_start();

    LOG("Hello QT6~\r\n");

    /* Appl maintains this flag,
     * marked as 1 initially to start measurement cycle.
     */
    qts_process_done = 1u;

    /* Appl maintains this flag,
     * marked as 1 initially to start measurement cycle.
     */
    touch_time.time_to_measure_touch = 1u;

    while (1) {
        /**
         * Start touch surface process
         */

#if DEF_SURF_LOW_POWER_SENSOR_ENABLE == 1
        qts_process_lp();
#else
        if (qts_process_done == 1) {
            qts_normal_process();
        }
#endif
        if (p_mutlcap_measure_data->measurement_done_touch == 1u) {
            p_mutlcap_measure_data->measurement_done_touch = 0u;
        }

        system_sleep();
    }
}
Esempio n. 27
0
/**
 * \brief Main Application Routine                              \n
 * - Initialize the system clocks                               \n
 * NOTE: The clock should be configured in conf_clock.h         \n
 * - Configure port pins (PA14 and PA16) are used here          \n
 * - Enable Global Interrupt                                    \n
 * - Configure and enable USART                                 \n
 * - Configure and enable ADC                                   \n
 * - Configure and enable DMAC and EVSYS if DMAC mode is chosen \n
 * - Start first ADC conversion                                 \n
 * - Count idle loop count in forever loop                      \n
 */
int main(void)
{

	/* Initialize system clocks */
	system_init();

#if defined(ENABLE_PORT_TOGGLE)
	/* Configure PORT pins PA14 and PA16 are configured here
	 * NOTE: Use oscilloscope to probe the pin.
	 */
	configure_port();
#endif

	/* ENable Global interrupt */
	system_interrupt_enable_global();

	/* Start SysTick Timer */
	systick_init();
 
	/* Configure SERCOM - USART */
	configure_usart();

	/* Configure and enable ADC */
	configure_adc();

	/* Configure and enable EVSYS */
	configure_event();

	/* Configure and enable DMA channel and descriptor */
	configure_dma();

	/* Get the time stamp 1 before starting ADC transfer */
	time_stamp1 = SysTick->VAL;
	

	/*
	 * Trigger first ADC conversion through software.
	 * NOTE: In case of using DMA, further conversions are triggered through
	 * event generated when previous ADC result is transferred to destination 
	 * (can be USART DATA register [or] RAM buffer).
	 * When DMA is not used, further conversions are triggered via software in 
	 * ADC handler after each result ready.
	 */
	adc_start_conversion(&adc_instance);

	while (1){

		#if defined (ENABLE_PORT_TOGGLE)
			/* 	 Use oscilloscope to probe the pin. */
			port_base->OUTTGL.reg = (1UL << PIN_PA16 % 32 );
		#endif
		
		/* Increment idle count whenever application reached while(1) loop */
		idle_loop_count++;

		/*
		 * Check if 1024 bytes transfer is done in either case (I.e. with or without
		 * using DMA.
		 * 'adc_conv_done' flag is set to true in the ADC handler once 
		 * 'adc_sample_count' reaches BLOCK_COUNT.
		 * 'adc_dma_transfer_is_done' is set to true once DMA transfer is done 
		 * in DMA call back for channel zero when 'ADC_DMAC_USART' is chosen.
		 * When choosing ADC_DMAC_MEM_MEM_USART mode, 'adc_dma_transfer_is_done' 
		 * is set to true in DMA channel call back for channel 2.
		 * DMA channel is disabled once reaching BLOCK_COUNT (with DMA cases).
		 * ADC is disabled once reaching BLOBK_COUNT samples (without DMA cases).
		 */
		if (adc_dma_transfer_is_done == true){
			
			/*
			 * Calculate number of cycles taken from the time stamp 
			 * taken before start of the conversion and after 1024 transfer
			 * is completed.
			 * NOTE: This value in relation to the idle_loop_count is 
			 * used in calculating CPU usage.
			 */
			cycles_taken = calculate_cycles_taken(time_stamp1,time_stamp2);

			/* Write the CPU cycles taken on USART */
			usart_write_buffer_wait(&usart_instance, (uint8_t *)&cycles_taken, sizeof(cycles_taken));
			/* Print idle loop count on USART */
			usart_write_buffer_wait(&usart_instance,(uint8_t *)&idle_loop_count, sizeof(idle_loop_count));

			/*
			 * Enter into forever loop as all transfers are completed and 
			 * DMAC/ADC is disabled 
			 */
			while(1);
		}
	}

}//end of main
Esempio n. 28
0
int
main(int argc, char *argv[])
{
  node_id_restore();
  /* init system: clocks, board etc */
  system_init();
  sio2host_init();

  leds_init();
  leds_on(LEDS_ALL);

  system_interrupt_enable_global();
  flash_init();
  delay_init();

  /* Initialize Contiki and our processes. */
  
  #ifdef LOW_POWER_MODE
  configure_tc3();
  #else
  clock_init();
  #endif

  process_init();
  ctimer_init();
  rtimer_init();
  process_start(&etimer_process, NULL);
  
  /* Set MAC address and node ID */
#ifdef NODEID
  node_id = NODEID;
#ifdef BURN_NODEID
  node_id_burn(node_id);
#endif /* BURN_NODEID */
#else/* NODE_ID */
#endif /* NODE_ID */

  printf("\r\n\n\n\n Starting the SmartConnect-6LoWPAN \r\n Platform : Atmel IoT device \r\n");
  print_reset_causes();
  netstack_init();
 #if BOARD == SAMR21_XPLAINED_PRO
  eui64 = edbg_eui_read_eui64();
  SetIEEEAddr(eui64);
#else
  SetIEEEAddr(node_mac);  
#endif 
  set_link_addr();  
  rf_set_channel(RF_CHANNEL);
  printf("\r\n Configured RF channel: %d\r\n", rf_get_channel());
  leds_off(LEDS_ALL);
  process_start(&sensors_process, NULL);
  energest_init();

  ENERGEST_ON(ENERGEST_TYPE_CPU);
  if(node_id > 0) {
    printf(" Node id %u.\r\n", node_id);
  } else {
    printf(" Node id not set.\r\n");
  }

  /* Setup nullmac-like MAC for 802.15.4 */
#if SAMD
  memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr));
#else 
  memcpy(&uip_lladdr.addr, eui64, sizeof(uip_lladdr.addr));
#endif
   
  queuebuf_init();
  printf(" %s %lu %d\r\n",
         NETSTACK_RDC.name,
         (uint32_t) (CLOCK_SECOND / (NETSTACK_RDC.channel_check_interval() == 0 ? 1:
                         NETSTACK_RDC.channel_check_interval())),
         RF_CHANNEL);

  process_start(&tcpip_process, NULL);
  printf(" IPv6 Address: ");
  {
    uip_ds6_addr_t *lladdr;
    int i;
    lladdr = uip_ds6_get_link_local(-1);
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:", lladdr->ipaddr.u8[i * 2],
             lladdr->ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\r\n", lladdr->ipaddr.u8[14], lladdr->ipaddr.u8[15]);
  }

  {
    uip_ipaddr_t ipaddr;
    int i;
    uip_ip6addr(&ipaddr, 0xfc00, 0, 0, 0, 0, 0, 0, 0);
    uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
    uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE);
    printf("Tentative global IPv6 address ");
    for(i = 0; i < 7; ++i) {
      printf("%02x%02x:",
             ipaddr.u8[i * 2], ipaddr.u8[i * 2 + 1]);
    }
    printf("%02x%02x\r\n",
           ipaddr.u8[7 * 2], ipaddr.u8[7 * 2 + 1]);
  }

  print_processes(autostart_processes);

  /* set up AES key */
#if ((THSQ_CONF_NETSTACK) & THSQ_CONF_AES)
#ifndef NETSTACK_AES_KEY
#error Please define NETSTACK_AES_KEY!
#endif /* NETSTACK_AES_KEY */
  {
    const uint8_t key[] = NETSTACK_AES_KEY;
    netstack_aes_set_key(key);
  }
  printf("AES encryption is enabled\n");
#else /* ((THSQ_CONF_NETSTACK) & THSQ_CONF_AES) */
  printf("\r\n Warning: AES encryption is disabled\n");
#endif /* ((THSQ_CONF_NETSTACK) & THSQ_CONF_AES) */

#ifdef ENABLE_LEDCTRL
  ledctrl_init();
#endif
  autostart_start(autostart_processes);


  while(1){
    int r = 0;

	serial_data_handler();

  do {

     
     r = process_run();

    } while(r > 0);

  }
}
Esempio n. 29
0
/*!
* @brief	Initializes the whole system and runs the desired application
*
* This is the main function of the project. It calls initialization functions
* of the MCU and the sensors. In the infinite loop it repeatedly checks
* the USART module read buffer and Streams sensor data periodically (100 ms) via USART.
*
*/
int main(void)
{
	/********************* Initialize global variables **********************/

	bmf055_input_state = USART_INPUT_STATE_PRINT_DATA;
	
	/************************* Initializations ******************************/
	
	/*Initialize SAMD20 MCU*/
	system_init();
	
	/*Initialize clock module of SAMD20 MCU - Internal RC clock*/
	//clock_initialize(); // done via conf_clocks.h --> ASF
	
	/*SPI master for communicating with sensors*/
	spi_initialize();
	
	/*eeprom emulator for configuration storage */
	eeprom_emulator_initialize();
	
	/*Initialize timers */
	tc_initialize();
	
	/*Initialize UART for communication with PC*/
	usart_initialize();
	
	/*Enable the system interrupts*/
	system_interrupt_enable_global();/* All interrupts have a priority of level 0 which is the highest. */
	
	/* Initialize the sensors */
	bmf055_sensors_initialize();
	
	readEEPROM();
	checkFirstTime(0);
	//readEEPROM();
	
	configureReceiver();
	initSensors();
	previousTime = micros();
	calibratingG = 400;
	f.SMALL_ANGLES_25=1; // important for gyro only conf
  if(conf.copterType == 0){//0=Bi,1=Tri,2=QUADP,3=QUADX,4=Y4,5=Y6,6=H6P,7=H6X,8=Vtail4
    MULTITYPE      = 4;
    NUMBER_MOTOR   = 2;
  }
  if(conf.copterType == 1){
    MULTITYPE      = 1;
    NUMBER_MOTOR   = 3;
  }
  if(conf.copterType == 2){
    MULTITYPE      = 2;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 3){
    MULTITYPE      = 3;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 4){
    MULTITYPE      = 9;
    NUMBER_MOTOR   = 4;
  }
  if(conf.copterType == 5){
    MULTITYPE      = 6;
    NUMBER_MOTOR   = 6;
  }
  if(conf.copterType == 6){
    MULTITYPE      = 7;
    NUMBER_MOTOR   = 6;
  }
  if(conf.copterType == 7){
    MULTITYPE      = 10;
    NUMBER_MOTOR   = 6;
  }     
  if(conf.copterType == 8){
    MULTITYPE      = 17;
    NUMBER_MOTOR   = 4;
  }
  
  initOutput();
	
	/************************** Infinite Loop *******************************/
	while (true)
	{

		
		static uint8_t rcDelayCommand; // this indicates the number of time (multiple of RC measurement at 50Hz) the sticks must be maintained to run or switch off motors
  static uint8_t beepon = 0;
  uint8_t axis,i;
  int16_t error,errorAngle;
  int16_t delta,deltaSum;
  int16_t PTerm=0,ITerm=0,PTermACC=0,ITermACC=0,PTermGYRO=0,ITermGYRO=0,DTerm=0;
  static int16_t lastGyro[3] = {0,0,0};
  static int16_t delta1[3],delta2[3];
  static int16_t errorGyroI[3] = {0,0,0};
  static int16_t errorAngleI[2] = {0,0};
  static uint32_t rcTime  = 0;
  static uint32_t BeepTime  = 0;
  static uint8_t stickarmed = 0;
  //static int16_t initialThrottleHold;
  
  if(!rcOptions[BOXARM] && stickarmed == 0 && f.ARMED == 0){
    if(rcData[YAW]<conf.MINCHECK && rcData[ROLL]>conf.MAXCHECK){
      conf.calibState=1;
      writeParams(1);
      while(true){
        //blinkLED(10,30,1);
      }      
    }
  } 
 
  while(SetupMode == 1){
    checkSetup();
  }
 
 
  if(conf.RxType == 1 || conf.RxType == 2){
    if (rcFrameComplete) computeRC();
  }
  
  if(!rcOptions[BOXARM] && stickarmed == 0) {
    f.ARMED = 0;
  }

  if (currentTime > rcTime ) { // 50Hz
    rcTime = currentTime + 20000;
    if(failsave < 250)failsave++;
    debug[0] = failsave;
    if(conf.RxType != 1 && conf.RxType != 2){
      computeRC();
    }
  
    if ((rcData[THROTTLE] < conf.MINCHECK && s3D == 0) || (rcData[THROTTLE] > (1500-conf.MIDDLEDEADBAND) && rcData[THROTTLE] < (1500+conf.MIDDLEDEADBAND) && s3D == 1 && f.ARMED == 0)) {
      errorGyroI[ROLL] = 0; errorGyroI[PITCH] = 0; errorGyroI[YAW] = 0;
      errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;

      rcDelayCommand++;
      if (rcData[YAW] < conf.MINCHECK && rcData[PITCH] < conf.MINCHECK && !f.ARMED) {
        if (rcDelayCommand == 20 && failsave < 20) {
          calibratingG=400;
        }
      }else if (rcData[YAW] > conf.MAXCHECK && rcData[PITCH] > conf.MAXCHECK && !f.ARMED) {
        if (rcDelayCommand == 20) {
          previousTime = micros();
        }
      }else if (conf.activate[BOXARM] > 0) {
        if ( rcOptions[BOXARM] && f.OK_TO_ARM && good_calib) {
	  f.ARMED = 1;
          stickarmed = 0;
        } else if (f.ARMED) f.ARMED = 0;
        rcDelayCommand = 0;
        
      
      } else if ( (rcData[YAW] < conf.MINCHECK ) && f.ARMED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 0) {
        if (rcDelayCommand == 20) f.ARMED = 0; // rcDelayCommand = 20 => 20x20ms = 0.4s = time to wait for a specific RC command to be acknowledged
      } else if ( (rcData[YAW] > conf.MAXCHECK ) && rcData[PITCH] < conf.MAXCHECK && !f.ARMED && calibratingG == 0 && f.ACC_CALIBRATED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 0) {
        if (rcDelayCommand == 20 && good_calib) {
	  f.ARMED = 1;
          stickarmed = 1;
        }
  
       } else if ( (rcData[ROLL] < conf.MINCHECK ) && f.ARMED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 1) {
        if (rcDelayCommand == 20) f.ARMED = 0; // rcDelayCommand = 20 => 20x20ms = 0.4s = time to wait for a specific RC command to be acknowledged
      } else if ( (rcData[ROLL] > conf.MAXCHECK ) && rcData[PITCH] < conf.MAXCHECK && !f.ARMED && calibratingG == 0 && f.ACC_CALIBRATED && !rcOptions[BOXARM] && s3D == 0 && conf.ArmRoll == 1) {
        if (rcDelayCommand == 20 && good_calib) {
	  f.ARMED = 1;
          stickarmed = 1;
        }       
        
        
      } else
        rcDelayCommand = 0;
    } else if (rcData[THROTTLE] > conf.MAXCHECK && !f.ARMED) {
      if (rcData[YAW] < conf.MINCHECK && rcData[PITCH] < conf.MINCHECK) {        // throttle=max, yaw=left, pitch=min
        if (rcDelayCommand == 20) calibratingA=400;
        rcDelayCommand++;
      } else if (rcData[PITCH] > conf.MAXCHECK) {
         conf.angleTrim[PITCH]+=2;writeParams(1);
      } else if (rcData[PITCH] < conf.MINCHECK) {
         conf.angleTrim[PITCH]-=2;writeParams(1);
      } else if (rcData[ROLL] > conf.MAXCHECK) {
         conf.angleTrim[ROLL]+=2;writeParams(1);
      } else if (rcData[ROLL] < conf.MINCHECK) {
         conf.angleTrim[ROLL]-=2;writeParams(1);
      } else {
        rcDelayCommand = 0;
      }
    }
    
    

    uint16_t auxState = 0;
    for(i=0;i<4;i++)
      auxState |= (rcData[AUX1+i]<1300)<<(3*i) | (1300<rcData[AUX1+i] && rcData[AUX1+i]<1700)<<(3*i+1) | (rcData[AUX1+i]>1700)<<(3*i+2);
    for(i=0;i<CHECKBOXITEMS;i++)
      rcOptions[i] = (auxState & conf.activate[i])>0;
      
      
     if(failsave > 200 && f.ARMED){
      rcOptions[BOXACC] = 1;
      s3D = 0;
      rcData[THROTTLE] = 1190;
      rcCommand[THROTTLE] = 1190;
    }

    if (rcOptions[BOXACC] && s3D == 0) { 
      // bumpless transfer to Level mode
      if (!f.ACC_MODE) {
        errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;
        f.ACC_MODE = 1;
      }  
    } else {
      // failsafe support
      f.ACC_MODE = 0;
    }
    if (rcOptions[BOXBEEP]) { 
      f.FSBEEP = 1;
      if(currentTime > BeepTime){
        BeepTime = currentTime + 50000;
        if(beepon == 0){
          if(conf.RxType == 0){
            //digitalWrite(A2,HIGH); 
          }else{
            //digitalWrite(8,HIGH); 
          }          
          beepon = 1;
        }else{
          if(conf.RxType == 0){
            //digitalWrite(A2,LOW); 
          }else{
            //digitalWrite(8,LOW); 
          }
          beepon = 0;
        }
      }
    } else {
      f.FSBEEP = 0;
      if(conf.RxType == 0){
        //digitalWrite(A2,LOW); 
      }else{
        //digitalWrite(8,LOW); 
      }
    }    

    
    if (rcOptions[BOXHORIZON] && s3D == 0) { 
      // bumpless transfer to Horizon mode
      if (!f.HORIZON_MODE) {
        errorAngleI[ROLL] = 0; errorAngleI[PITCH] = 0;
        f.HORIZON_MODE = 1;
      }  
    } else {
      f.HORIZON_MODE = 0;
    }
    
    if (rcOptions[BOX3D] && conf.F3D == 1) {  
      if(f.ARMED == 0 && s3D == 0){
        s3D = 1;
        f.ACC_MODE = 0;
        f.HORIZON_MODE = 0;
      }
    } else if(f.ARMED == 0){
      s3D = 0;
    }   
    

    if (rcOptions[BOXARM] == 0) f.OK_TO_ARM = 1;
  }
 
  computeIMU();
  int16_t prop;
  if (f.HORIZON_MODE)
    prop = max(abs(rcCommand[PITCH]),abs(rcCommand[ROLL])); // range [0;500]  
  
  
  if (f.ACC_MODE){
    if(Zadd > 0)Zadd--;
    if(Zadd < 0)Zadd++;
  }else{
    Zadd = 0;
  }

  

  //**** PITCH & ROLL & YAW PID ****    
  for(axis=0;axis<3;axis++) {
    if ((f.ACC_MODE || f.HORIZON_MODE) && axis<2 ) { //LEVEL MODE
      // 50 degrees max inclination
      errorAngle = constrain(2*rcCommand[axis],-500,+500) - angle[axis] + conf.angleTrim[axis]; //16 bits is ok here
      #ifdef LEVEL_PDF
        PTermACC      = -(int32_t)angle[axis]*conf.P8[PIDLEVEL]/100 ;
      #else  
        PTermACC      = (int32_t)errorAngle*conf.P8[PIDLEVEL]/100 ;                          // 32 bits is needed for calculation: errorAngle*P8[PIDLEVEL] could exceed 32768   16 bits is ok for result
      #endif
      PTermACC = constrain(PTermACC,-conf.D8[PIDLEVEL]*5,+conf.D8[PIDLEVEL]*5);

      errorAngleI[axis]  = constrain(errorAngleI[axis]+errorAngle,-10000,+10000);    // WindUp     //16 bits is ok here
      ITermACC           = ((int32_t)errorAngleI[axis]*conf.I8[PIDLEVEL])>>12;            // 32 bits is needed for calculation:10000*I8 could exceed 32768   16 bits is ok for result
    }
    if ( !f.ACC_MODE || f.HORIZON_MODE || axis == 2 ) { // MODE relying on GYRO or YAW axis
      if (abs(rcCommand[axis])<350) error =          rcCommand[axis]*10*8/conf.P8[axis] ; // 16 bits is needed for calculation: 350*10*8 = 28000      16 bits is ok for result if P8>2 (P>0.2)
                               else error = (int32_t)rcCommand[axis]*10*8/conf.P8[axis] ; // 32 bits is needed for calculation: 500*5*10*8 = 200000   16 bits is ok for result if P8>2 (P>0.2)
      error -= gyroData[axis];

      PTermGYRO = rcCommand[axis];
      
      errorGyroI[axis]  = constrain(errorGyroI[axis]+error,-16000,+16000);          // WindUp   16 bits is ok here
      if (abs(gyroData[axis])>640) errorGyroI[axis] = 0;
      ITermGYRO         = (errorGyroI[axis]/125*conf.I8[axis])>>6;                                   // 16 bits is ok here 16000/125 = 128 ; 128*250 = 32000
    }
    if ( f.HORIZON_MODE && axis<2) {
      PTerm = ((int32_t)PTermACC*(500-prop) + (int32_t)PTermGYRO*prop)/500;
      ITerm = ((int32_t)ITermACC*(500-prop) + (int32_t)ITermGYRO*prop)/500;
    } else {
      if ( f.ACC_MODE && axis<2) {
        PTerm = PTermACC;
        ITerm = ITermACC;
      } else {
        PTerm = PTermGYRO;
        ITerm = ITermGYRO;
      }
    }
    if (abs(gyroData[axis])<160) PTerm -=          gyroData[axis]*dynP8[axis]/10/8; // 16 bits is needed for calculation   160*200 = 32000         16 bits is ok for result
                            else PTerm -= (int32_t)gyroData[axis]*dynP8[axis]/10/8; // 32 bits is needed for calculation   

    delta          = gyroData[axis] - lastGyro[axis];                               // 16 bits is ok here, the dif between 2 consecutive gyro reads is limited to 800
    lastGyro[axis] = gyroData[axis];
    deltaSum       = delta1[axis]+delta2[axis]+delta;
    delta2[axis]   = delta1[axis];
    delta1[axis]   = delta;
 
    if (abs(deltaSum)<640) DTerm = (deltaSum*dynD8[axis])>>5;                       // 16 bits is needed for calculation 640*50 = 32000           16 bits is ok for result 
                      else DTerm = ((int32_t)deltaSum*dynD8[axis])>>5;              // 32 bits is needed for calculation
                      
    axisPID[axis] =  PTerm + ITerm - DTerm;
  }
Esempio n. 30
0
/* Timer 0 Initialization */
void timer_init(void)
{
	struct tc_config conf_tc;
	struct tc_events conf_tc_events = {.generate_event_on_compare_channel[0] = 1};
	tc_get_config_defaults(&conf_tc);
	conf_tc.clock_source = GCLK_GENERATOR_0;
	conf_tc.wave_generation = TC_WAVE_GENERATION_MATCH_FREQ;
	conf_tc.counter_16_bit.compare_capture_channel[0] = 0xFFFF;
	tc_init(&tc_inst, TC0, &conf_tc);
	tc_enable_events(&tc_inst, &conf_tc_events);
	tc_enable(&tc_inst);
	tc_stop_counter(&tc_inst);
	/* Enable TC0 match/capture channel 0 interrupt */
	TC0->COUNT16.INTENSET.bit.MC0 = 1;
	/* Enable TC0 module interrupt */
	NVIC_EnableIRQ(TC0_IRQn);
}

/* DAC Initialization */
void dac_initialize(void)
{
	struct dac_config conf_dac;
	struct dac_events conf_dac_events = {.on_event_start_conversion = 1};
	dac_get_config_defaults(&conf_dac);
	conf_dac.clock_source = GCLK_GENERATOR_3;
	conf_dac.reference = DAC_REFERENCE_INT1V;
	dac_init(&dac_inst, DAC, &conf_dac);
	dac_enable_events(&dac_inst, &conf_dac_events);
	dac_enable(&dac_inst);
}

/* Event System Initialization */
void evsys_init(void)
{
	struct events_resource conf_event_resource;
	struct events_config conf_event;
	events_get_config_defaults(&conf_event);
	conf_event.edge_detect = EVENTS_EDGE_DETECT_NONE;
	conf_event.path = EVENTS_PATH_ASYNCHRONOUS;
	conf_event.generator = EVSYS_ID_GEN_TC0_MCX_0;
	events_allocate(&conf_event_resource, &conf_event);
	events_attach_user(&conf_event_resource, EVSYS_ID_USER_DAC_START);
}

/* Initialize the selected waveform buffer with output data */
void buffer_init(void)
{
#if WAVE_MODE==SINE_WAVE
	for (i = 0; i < DEGREES_PER_CYCLE; i++)	{
		sine_wave_buf[i] = (uint16_t)(500 + (500*sin((double)i*DEGREE)));
	}
#elif WAVE_MODE==SAW_TOOTH_WAVE
	for (i = 0; i < 256; i++) {
		sawtooth_wave_buf[i] = i*4;
	}
#elif WAVE_MODE==TRIANGLE_WAVE
	for (i = 0; i < 128; i++) {
		triangle_wave_buf[i] = i*8;
	}
	for (i = 128; i < 256; i++) {
		triangle_wave_buf[i] = 1023 - (i*8);
	}
#endif
}

/* Main function */
int main(void)
{
	system_init();
	timer_init();
	dac_initialize();
	evsys_init();
	buffer_init();
	/* Set the TC0 compare value corresponding to specified frequency */
#if WAVE_MODE==SINE_WAVE
	tc_set_compare_value(&tc_inst, 0, \
		system_gclk_gen_get_hz(GCLK_GENERATOR_0)/(FREQUENCY*360));
#else
	tc_set_compare_value(&tc_inst, 0, \
		system_gclk_gen_get_hz(GCLK_GENERATOR_0)/(FREQUENCY*256));
#endif
	/* Start TC0 timer */
	tc_start_counter(&tc_inst);
	/* Enable global interrupt */
	system_interrupt_enable_global();
	
	while (true) {

	}
}