Beispiel #1
0
/** \brief Prepare ADC for touch measuring.
 *
 * Register the interrupt handler, set sample, hold and startup time.
 */
static void inline rtouch_prepare_adc(void)
{
	Disable_global_interrupt();
	INTC_register_interrupt(&rtouch_adc_int_handler, RTOUCH_ADC_IRQ,
			RTOUCH_ADC_INT_LEVEL);
	Enable_global_interrupt();

#ifdef AVR32_ADCIFA
	volatile avr32_adcifa_t *adcifa = &RTOUCH_ADC;

	/* configure ADCIFA */
	adcifa_configure(adcifa, &adcifa_opt, FOSC0);
#else
	volatile avr32_adc_t *adc = &RTOUCH_ADC;

	adc_configure(adc);

	/* we need to lower the adc clock under 5MHz */
	/* adc_clock = adc_input_clock /((prescaler + 1)*2) */
	adc->mr |= 0x1 << AVR32_ADC_MR_PRESCAL_OFFSET;
#endif
}
Beispiel #2
0
/*!
 *  \brief Init the joystick sensor.
 *
 *  \return true upon success, false if error.
 */
bool b_joystick_init ( void )
{
portCHAR token[6];

   // Get the xCFGMutex.
   if( pdTRUE == x_supervisor_SemaphoreTake( xCFGMutex, 0 ) )
   {
       // get the field
       if (config_file_get_value(SENSOR_JS_CONFIG_FILE, "alarm" , token) >= 0)
       {
         // update value
         if (!strcmp(token, "on"))
         {
           bAlarm = pdTRUE;
         }
       }
     // Release the xCFGMutex.
     x_supervisor_SemaphoreGive( xCFGMutex );
   }
   /* configure joystick up to produce IT on all state change */
   gpio_enable_pin_interrupt(GPIO_JOYSTICK_UP , GPIO_PIN_CHANGE);
   /* configure joystick down to produce IT on all state change */
   gpio_enable_pin_interrupt(GPIO_JOYSTICK_DOWN , GPIO_PIN_CHANGE);
   /* configure joystick right to produce IT on all state change */
   gpio_enable_pin_interrupt(GPIO_JOYSTICK_RIGHT , GPIO_PIN_CHANGE);
   /* configure joystick left to produce IT on all state change */
   gpio_enable_pin_interrupt(GPIO_JOYSTICK_LEFT , GPIO_PIN_CHANGE);
   /* configure joystick press to produce IT on all state change */
   gpio_enable_pin_interrupt(GPIO_JOYSTICK_PUSH , GPIO_PIN_CHANGE);
   /* Disable all interrupts */
   Disable_global_interrupt();
   /* register joystick handler on level 3 */
   INTC_register_interrupt( (__int_handler)&vjoystick_ISR, AVR32_GPIO_IRQ_0 + (GPIO_JOYSTICK_UP/8), AVR32_INTC_INT3);
   INTC_register_interrupt( (__int_handler)&vjoystick_ISR, AVR32_GPIO_IRQ_0 + (GPIO_JOYSTICK_PUSH/8), AVR32_INTC_INT3);
   /* Enable all interrupts */
   Enable_global_interrupt();
   return (true);
}
uint32_t  readClock(Clock* timeClock){
	//rtc_count_disable(&rtc_instance);
	Disable_global_interrupt();
	uint32_t timeCounter=0;
	RTC->MODE0.CTRL.reg &=  0b1111111111111101;//disable timer
	while(RTC->MODE0.STATUS.bit.SYNCBUSY==1);//wait timer disable
	
	timeCounter=RTC->MODE0.COUNT.reg; 
	timeClock->second=timeManage.second;	
	timeClock->halfmillis=timeManage.halfmillis;	
	//timeCounter=0;
	

	//Enable_global_interrupt();
	timeClock->sign=true;	

	timeClock->halfmillis+=timeCounter;
	timeClock->second+=timeClock->halfmillis/RTC_FREQ;
	timeClock->halfmillis=timeClock->halfmillis%RTC_FREQ;
	RTC->MODE0.CTRL.reg |= RTC_MODE0_CTRL_ENABLE; //enable timer
	Enable_global_interrupt();
	return timeCounter;
}
void ppsISR(void)
{	
	Disable_global_interrupt();
	Clock timeCopy={0,0,true};
	//Disable_global_interrupt();
	Clock timeMaster={0,0,true};
	readClock(&timeCopy);
	//Enable_global_interrupt();
	timeMaster.second=timeCopy.second;
	timeMaster.halfmillis=timeCopy.halfmillis;
	if(timeMaster.halfmillis>=RTC_FREQ/2){//for the accurate 500ms
		timeMaster.second++;
	}
	timeMaster.halfmillis=0;
	/*if((timeMaster.halfmillis>RTC_FREQ)||(timeMaster.halfmillis<0)){
			printf("timeMasterpps");
			printfClock(timeMaster);
	}
	if((timeCopy.halfmillis>RTC_FREQ)||(timeCopy.halfmillis<0)){
		printf("timeCopypps:'");
		printfClock(timeCopy);
	}*/
	timeProt.offset=subClock(timeMaster,timeCopy);
	//timeProt.offset.second=0;
	#ifdef MASTERMODE
		updateClock();
	#else
		if(timeProt.offset.sign==true){
			sprintf(messageHMIError,"		error pps: %lus %u	t:%lus",timeProt.offset.second,(unsigned int)(timeProt.offset.halfmillis/2),timeMaster.second);
		}
		else{
			sprintf(messageHMIError,"		error pps: -%lus %u	t:%lus",timeProt.offset.second,(unsigned int)(timeProt.offset.halfmillis/2),timeMaster.second);
		}
		sendHMI(messageHMIError);
	#endif
	Enable_global_interrupt();
}
Beispiel #5
0
int pwm_init(const pwm_opt_t *opt)
{
  volatile avr32_pwm_t *pwm = &AVR32_PWM;
  Bool global_interrupt_enabled = Is_global_interrupt_enabled();

  if (opt == 0 ) // Null pointer.
    return PWM_INVALID_INPUT;

  // Disable interrupt.
  if (global_interrupt_enabled) Disable_global_interrupt();
  pwm->idr = ((1 << (AVR32_PWM_LINES_MSB + 1)) - 1) << AVR32_PWM_IDR_CHID0_OFFSET;
  pwm->isr;
  if (global_interrupt_enabled) Enable_global_interrupt();

  // Set PWM mode register.
  pwm->mr =
    ((opt->diva)<<AVR32_PWM_DIVA_OFFSET) |
    ((opt->divb)<<AVR32_PWM_DIVB_OFFSET) |
    ((opt->prea)<<AVR32_PWM_PREA_OFFSET) |
    ((opt->preb)<<AVR32_PWM_PREB_OFFSET)
    ;

  return PWM_SUCCESS;
}
Beispiel #6
0
//! host_disable_all_pipes
//!
//!  This function disables all pipes for the host controller.
//!  Useful to execute upon disconnection.
//!
//! @return Void
//!
void host_disable_all_pipes(void)
{
#if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
  Bool sav_glob_int_en;
#endif
  U8 p;

#if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
  // Disable global interrupts
  if ((sav_glob_int_en = Is_global_interrupt_enabled())) Disable_global_interrupt();
#endif
  for (p = 0; p < MAX_PEP_NB; p++)
  { // Disable the pipe <p> (disable interrupt, free memory, reset pipe, ...)
    Host_disable_pipe_interrupt(p);
    Host_reset_pipe(p);
    Host_unallocate_memory(p);
    Host_disable_pipe(p);
  }
#if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
  (void)Is_host_pipe_enabled(MAX_PEP_NB - 1);
  // Restore the global interrupts to the initial state
  if (sav_glob_int_en) Enable_global_interrupt();
#endif
}
Beispiel #7
0
void vDisableMACBOperations(volatile avr32_macb_t *macb)
{
	bool global_interrupt_enabled = Is_global_interrupt_enabled();
#if ETHERNET_CONF_USE_PHY_IT == 1
	#if EXTPHY_MACB_USE_EXTINT
	volatile avr32_eic_t *eic = &AVR32_EIC;
	eic->idr = 1 << EXTPHY_MACB_INTERRUPT;
	eic->imr;
	#else
	volatile avr32_gpio_t *gpio = &AVR32_GPIO;
	volatile avr32_gpio_port_t *gpio_port = &gpio->port[EXTPHY_MACB_INTERRUPT_PIN/32];
	gpio_port->ierc =  1 << (EXTPHY_MACB_INTERRUPT_PIN%32);
	#endif
#endif

	// write the MACB control register : disable Tx & Rx
	macb->ncr &= ~((1 << AVR32_MACB_RE_OFFSET) | (1 << AVR32_MACB_TE_OFFSET));

	// We no more want to interrupt on Rx and Tx events.
	if (global_interrupt_enabled) Disable_global_interrupt();
	macb->idr = AVR32_MACB_IER_RCOMP_MASK | AVR32_MACB_IER_TCOMP_MASK;
	macb->isr;
	if (global_interrupt_enabled) Enable_global_interrupt();
}
Beispiel #8
0
void rtc_init_qt( void ) {
  // Init touch_states
  controller_clear();

  // Disable all interrupts
  Disable_global_interrupt();

  // Register the RTC interrupt handler to the interrupt controller.
  BSP_INTC_IntReg( &rtc_irq, AVR32_RTC_IRQ, AVR32_INTC_INT1);

  // Initialize the RTC
  rtc_init(&AVR32_RTC, RTC_OSC_32KHZ, 4);

  rtc_set_top_value(&AVR32_RTC, 1);
  // Enable the interrupts
  rtc_enable_interrupt(&AVR32_RTC);

  // Enable the RTC
  rtc_enable(&AVR32_RTC);

  // Enable global interrupts
  Enable_global_interrupt();

}
Beispiel #9
0
void rtc_init_qt( void ) {

  // Disable all interrupts. */
  Disable_global_interrupt();

  // Register the RTC interrupt handler to the interrupt controller.
  INTC_register_interrupt(&rtc_irq, AVR32_RTC_IRQ, AVR32_INTC_INT0);

  // Initialize the RTC
  // Frtc = 1024Hz
  rtc_init(&AVR32_RTC, RTC_OSC_32KHZ, 4);

  // Set top value to 0 to generate an interrupt every seconds */
  rtc_set_top_value(&AVR32_RTC, 1);
  // Enable the interrupts
  rtc_enable_interrupt(&AVR32_RTC);

  // Enable the RTC
  rtc_enable(&AVR32_RTC);

  // Enable global interrupts
  Enable_global_interrupt();

}
/**
 * \brief The main function.
 *
 * It sets up the USART module on EXAMPLE_USART. The terminal settings are 57600
 * 8N1.
 * Then it sets up the interrupt handler and waits for a USART interrupt to
 * trigger.
 */
int main(void)
{
	static const gpio_map_t USART_GPIO_MAP =
	{
		{EXAMPLE_USART_RX_PIN, EXAMPLE_USART_RX_FUNCTION},
		{EXAMPLE_USART_TX_PIN, EXAMPLE_USART_TX_FUNCTION}
	};

	// USART options.
	static const usart_options_t USART_OPTIONS =
	{
		.baudrate     = EXAMPLE_USART_BAUDRATE,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = USART_NORMAL_CHMODE
	};

#if BOARD == EVK1100 || BOARD == EVK1101 || BOARD == UC3C_EK \
	|| BOARD == EVK1104 || BOARD == EVK1105 || BOARD == STK600_RCUC3L0 \
	|| BOARD == STK600_RCUC3D
	/*
	 * Configure Osc0 in crystal mode (i.e. use of an external crystal
	 * source, with frequency FOSC0) with an appropriate startup time then
	 * switch the main clock source to Osc0.
	 */
	pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);

#elif BOARD == STK1000
	pm_reset();
#elif BOARD == UC3L_EK
	/*
	 * Note: on the AT32UC3L-EK board, there is no crystal/external clock
	 * connected to the OSC0 pinout XIN0/XOUT0. We shall then program the
	 * DFLL and switch the main clock source to the DFLL.
	 */
	pcl_configure_clocks(&pcl_dfll_freq_param);
	/*
	 * Note: since it is dynamically computing the appropriate field values
	 * of the configuration registers from the parameters structure, this
	 * function is not optimal in terms of code size. For a code size
	 * optimal solution, it is better to create a new function from
	 * pcl_configure_clocks_dfll0() and modify it to use preprocessor
	 * computation from pre-defined target frequencies.
	 */
#endif

	// Assign GPIO to USART.
	gpio_enable_module(USART_GPIO_MAP,
		sizeof(USART_GPIO_MAP) / sizeof(USART_GPIO_MAP[0]));

	// Initialize USART in RS232 mode.
	usart_init_rs232(EXAMPLE_USART, &USART_OPTIONS,
		EXAMPLE_TARGET_PBACLK_FREQ_HZ);
	print(EXAMPLE_USART, ".: Using interrupts with the USART :.\r\n\r\n");

	// Disable all interrupts.
	Disable_global_interrupt();

	// Initialize interrupt vectors.
	INTC_init_interrupts();

	/*
	 * Register the USART interrupt handler to the interrupt controller.
	 * usart_int_handler is the interrupt handler to register.
	 * EXAMPLE_USART_IRQ is the IRQ of the interrupt handler to register.
	 * AVR32_INTC_INT0 is the interrupt priority level to assign to the
	 * group of this IRQ.
	 */
	INTC_register_interrupt(&usart_int_handler, EXAMPLE_USART_IRQ,
		AVR32_INTC_INT0);

	// Enable USART Rx interrupt.
	EXAMPLE_USART->ier = AVR32_USART_IER_RXRDY_MASK;
	print(EXAMPLE_USART, "Type a character to use the interrupt handler."
		"\r\nIt will show up on your screen.\r\n\r\n");

	// Enable all interrupts.
	Enable_global_interrupt();

	/**
	 * We have nothing left to do in the main, so we may switch to a device
	 * sleep mode: we just need to be sure that the USART module will be
	 * still be active in the chosen sleep mode. The sleep mode to use is
	 * the FROZEN sleep mode: in this mode the PB clocks are still active
	 * (so the USART module which is on the Peripheral Bus will still be
	 * active while the CPU and HSB will be stopped).
	 * --
	 * Modules communicating with external circuits should normally be
	 * disabled before entering a sleep mode that will stop the module
	 * operation: this is not the case for the FROZEN sleep mode.
	 * --
	 * When the USART interrupt occurs, this will wake the CPU up which will
	 * then execute the interrupt handler code then come back to the
	 * while(1) loop below to execute the sleep instruction again.
	 */

	while(1)
	{
		/*
		 * If there is a chance that any PB write operations are
		 * incomplete, the CPU should perform a read operation from any
		 * register on the PB bus before executing the sleep
		 * instruction.
		 */
		AVR32_INTC.ipr[0];  // Dummy read

		// Go to FROZEN sleep mode.
		SLEEP(AVR32_PM_SMODE_FROZEN);
		/*
		 * When the device wakes up due to an interrupt, once the
		 * interrupt has been serviced, go back into FROZEN sleep mode.
		 */
	}
}
Beispiel #11
0
void usb_task(void *pvParameters)
{
#endif  // FREERTOS_USED
  // Register the USB interrupt handler to the interrupt controller and enable
  // the USB interrupt.
  Disable_global_interrupt();
  INTC_register_interrupt((__int_handler)&usb_general_interrupt, AVR32_USBB_IRQ, USB_INT_LEV);
  Enable_global_interrupt();

#ifdef FREERTOS_USED
  while (true)
  {
    // Wait for the semaphore
    while (!xSemaphoreTake(usb_tsk_semphr, portMAX_DELAY));

#endif  // FREERTOS_USED
// ---- DUAL-ROLE DEVICE/HOST USB MODE -----------------------------------------
#if USB_DEVICE_FEATURE == true && USB_HOST_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_device_tsk) vTaskDelete(usb_device_tsk), usb_device_tsk = NULL;
    if (usb_host_tsk) vTaskDelete(usb_host_tsk), usb_host_tsk = NULL;
  #endif
    Usb_input_id_pin();
    Usb_enable_id_pin();
    if (Is_usb_id_device())
    {
      g_usb_mode = USB_MODE_DEVICE;
      usb_device_task_init();
    }
    else
    {
      private_sof_counter = 0;
      g_usb_mode = USB_MODE_HOST;
      usb_host_task_init();
    }
    g_old_usb_mode = g_usb_mode;  // Store current USB mode, for mode change detection
    Usb_raise_id_transition();  // Check no ID transition has been missed during initialization
    Usb_enable_id_interrupt();
    Enable_global_interrupt();
// -----------------------------------------------------------------------------

// ---- DEVICE-ONLY USB MODE ---------------------------------------------------
#elif USB_DEVICE_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_device_tsk) vTaskDelete(usb_device_tsk), usb_device_tsk = NULL;
  #endif
    Usb_force_device_mode();
    usb_device_task_init();
// -----------------------------------------------------------------------------

// ---- REDUCED-HOST-ONLY USB MODE ---------------------------------------------
#elif USB_HOST_FEATURE == true
  #ifdef FREERTOS_USED
    if (usb_host_tsk) vTaskDelete(usb_host_tsk), usb_host_tsk = NULL;
  #endif
    private_sof_counter = 0;
    Usb_force_host_mode();
    usb_host_task_init();
// -----------------------------------------------------------------------------

// ---- ERROR, NO MODE true -------------------------------------------------
#else
  #error At least one of USB_DEVICE_FEATURE and USB_HOST_FEATURE must be enabled
#endif
// -----------------------------------------------------------------------------
#ifdef FREERTOS_USED
  }
#endif
}
Beispiel #12
0
/*! \brief  This function initializes the LIN controller and, if needed, the LIN
 *          interrupts.
 *
 * \param master \c true for master, \c false for slave
 * \param l_node Node Value
 * \param b_rate Baudrate Value
 * \param pba_hz PBA Value
 * \return Status PASS / FAIL
 *
 */
U8 lin_init (bool master,
             U8 l_node,
             U16 b_rate,
             long pba_hz) {
if (l_node == 0)
{
    // Enable GPIO Alternate Functions
    gpio_enable_module(USART_LIN_NODE0_GPIO_MAP,
                     sizeof(USART_LIN_NODE0_GPIO_MAP) / sizeof(USART_LIN_NODE0_GPIO_MAP[0]));

    gpio_enable_pin_pull_up(USART_LIN_NODE0_RX_PIN);

    // USART options.
    if (master)
      usart_init_lin_master(usart_lin_node0,b_rate,pba_hz);
    else
      usart_init_lin_slave(usart_lin_node0,b_rate,pba_hz);

    Disable_global_interrupt();

    if (master==false)
    {
		        //! Enable Interrupt for Error flags and end ID Reception
			#if ( defined (AVR32_USART_400_H_INCLUDED) ||  \
                              defined (AVR32_USART_410_H_INCLUDED) ||  \
                              defined (AVR32_USART_420_H_INCLUDED) )
				usart_lin_node0->ier = AVR32_USART_IER_LINIR_MASK  |
							 AVR32_USART_IER_LINBE_MASK  |
							 AVR32_USART_IER_LINISFE_MASK |
							 AVR32_USART_IER_LINIPE_MASK |
							 AVR32_USART_IER_LINCE_MASK  |
							 AVR32_USART_IER_LINSNRE_MASK;
				//! Register Interrupt for LIN
				INTC_register_interrupt(&lin_int_handler_node0,
										USART_LIN_NODE0_USART_IRQ,
										USART_LIN_NODE0_USART_IRQ_LEVEL);
			#else

				usart_lin_node0->ier = AVR32_USART_IER_LINID_MASK  |
							 AVR32_USART_IER_LINBE_MASK  |
							 AVR32_USART_IER_LINISFE_MASK |
							 AVR32_USART_IER_LINIPE_MASK |
							 AVR32_USART_IER_LINCE_MASK  |
							 AVR32_USART_IER_LINSNRE_MASK;
				//! Register Interrupt for LIN
				INTC_register_interrupt(&lin_int_handler_node0,
										USART_LIN_NODE0_USART_IRQ,
										USART_LIN_NODE0_USART_IRQ_LEVEL);
			#endif
    }

    //! Register Interrupt for PDCA Transfer TX
    INTC_register_interrupt(&lin_pdca_int_tx_handler_node0,
                            USART_LIN_NODE0_PDCA_TX_IRQ,
                            USART_LIN_NODE0_PDCA_TX_IRQ_LEVEL);

    //! Register Interrupt for PDCA Transfer RX
    INTC_register_interrupt(&lin_pdca_int_rx_handler_node0,
                            USART_LIN_NODE0_PDCA_RX_IRQ,
                            USART_LIN_NODE0_PDCA_RX_IRQ_LEVEL);

}
#ifdef USART_LIN_NODE1_INSTANCE
else
{
    // Enable GPIO Alternate Functions
    gpio_enable_module(USART_LIN_NODE1_GPIO_MAP,
                     sizeof(USART_LIN_NODE1_GPIO_MAP) / sizeof(USART_LIN_NODE1_GPIO_MAP[0]));


    gpio_enable_pin_pull_up(USART_LIN_NODE1_RX_PIN);

    // USART options.
    if (master)
      usart_init_lin_master(usart_lin_node1,b_rate,pba_hz);
    else
      usart_init_lin_slave(usart_lin_node1,b_rate,pba_hz);

    Disable_global_interrupt();

    if (master==false)
    {
		        //! Enable Interrupt for Error flags and end ID Reception
			#if ( defined (AVR32_USART_400_H_INCLUDED) ||  \
                              defined (AVR32_USART_410_H_INCLUDED) ||  \
                              defined (AVR32_USART_420_H_INCLUDED) )
				usart_lin_node1->ier = AVR32_USART_IER_LINIR_MASK  |
							 AVR32_USART_IER_LINBE_MASK  |
							 AVR32_USART_IER_LINISFE_MASK |
							 AVR32_USART_IER_LINIPE_MASK |
							 AVR32_USART_IER_LINCE_MASK  |
							 AVR32_USART_IER_LINSNRE_MASK;
				//! Register Interrupt for LIN
				INTC_register_interrupt(&lin_int_handler_node1,
										USART_LIN_NODE1_USART_IRQ,
										USART_LIN_NODE1_USART_IRQ_LEVEL);
			#else
				usart_lin_node1->ier = AVR32_USART_IER_LINID_MASK  |
							 AVR32_USART_IER_LINBE_MASK  |
							 AVR32_USART_IER_LINISFE_MASK |
							 AVR32_USART_IER_LINIPE_MASK |
							 AVR32_USART_IER_LINCE_MASK  |
							 AVR32_USART_IER_LINSNRE_MASK;
				//! Register Interrupt for LIN
				INTC_register_interrupt(&lin_int_handler_node1,
										USART_LIN_NODE1_USART_IRQ,
										USART_LIN_NODE1_USART_IRQ_LEVEL);
			#endif
    }

    //! Register Interrupt for PDCA Transfer TX
    INTC_register_interrupt(&lin_pdca_int_tx_handler_node1,
                            USART_LIN_NODE1_PDCA_TX_IRQ,
                            USART_LIN_NODE1_PDCA_TX_IRQ_LEVEL);

    //! Register Interrupt for PDCA Transfer RX
    INTC_register_interrupt(&lin_pdca_int_rx_handler_node1,
                            USART_LIN_NODE1_PDCA_RX_IRQ,
                            USART_LIN_NODE1_PDCA_RX_IRQ_LEVEL);
}
#endif
    return PASS;
}
Beispiel #13
0
/** Main function to configure the CAN, and begin transfers. */
int main(void)
{
	/* Initialize the system clocks */
	sysclk_init();

	/* Setup the generic clock for CAN */
	scif_gc_setup(AVR32_SCIF_GCLK_CANIF,
				SCIF_GCCTRL_OSC0,
				AVR32_SCIF_GC_NO_DIV_CLOCK,
				0);
	/* Now enable the generic clock */
	scif_gc_enable(AVR32_SCIF_GCLK_CANIF);

	init_dbg_rs232(FPBA_HZ);

	/* Disable all interrupts. */
	Disable_global_interrupt();

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

	static const gpio_map_t CAN_GPIO_MAP = {
		{AVR32_CANIF_RXLINE_0_0_PIN, AVR32_CANIF_RXLINE_0_0_FUNCTION},
		{AVR32_CANIF_TXLINE_0_0_PIN, AVR32_CANIF_TXLINE_0_0_FUNCTION}
	};
	/* Assign GPIO to CAN. */
	gpio_enable_module(CAN_GPIO_MAP,
		sizeof(CAN_GPIO_MAP) / sizeof(CAN_GPIO_MAP[0]));

	/* Initialize channel 0 */
	can_init(CAN_CHANNEL_EXAMPLE, ((uint32_t)&mob_ram_ch0[0]), 
		CANIF_CHANNEL_MODE_LISTENING, can_out_callback_channel0);

	/* Enable all interrupts. */
	Enable_global_interrupt();

	print_dbg("\r\nUC3C CAN Examples 1\r\n");

	print_dbg(CAN_Wakeup);

	/* Initialize CAN Channel 0 */
	can_init(CAN_CHANNEL_EXAMPLE, ((uint32_t)&mob_ram_ch0[0]), 
		CANIF_CHANNEL_MODE_NORMAL, can_out_callback_channel0);

	/* Allocate one mob for RX */
	appli_rx_msg.handle = can_mob_alloc(CAN_CHANNEL_EXAMPLE);

	/* Initialize RX message */
	can_rx(CAN_CHANNEL_EXAMPLE, appli_rx_msg.handle, appli_rx_msg.req_type,
		appli_rx_msg.can_msg);

	/* Enable Async Wake Up Mode */
	pm_asyn_wake_up_enable(CAN_WAKEUP_MASK_EXAMPLE);

	/* ---------SLEEP MODE PROCEDURE------------- */
	/* Disable CAN Channel 0 */
	CANIF_disable(CAN_CHANNEL_EXAMPLE);
	/* Wait CAN Channel 0 is disabled */
	while(!CANIF_channel_enable_status(CAN_CHANNEL_EXAMPLE));
	/* Enable Wake-Up Mode */
	CANIF_enable_wakeup(CAN_CHANNEL_EXAMPLE);
	/* Go to sleep mode. */
	SLEEP(AVR32_PM_SMODE_STATIC);
	/* ---------SLEEP MODE PROCEDURE------------- */
	print_dbg(CAN_WakeupD);
	/* Initialize again CAN Channel 0 */
	can_init(CAN_CHANNEL_EXAMPLE, ((uint32_t)&mob_ram_ch0[0]),
		CANIF_CHANNEL_MODE_NORMAL, can_out_callback_channel0);

	/* Allocate one mob for RX */
	appli_rx_msg.handle = can_mob_alloc(CAN_CHANNEL_EXAMPLE);

	/* Initialize RX message */
	can_rx(CAN_CHANNEL_EXAMPLE, appli_rx_msg.handle, appli_rx_msg.req_type,
		appli_rx_msg.can_msg);

	for (;;) {
		/* Do nothing; interrupts handle the DAC conversions */
	}

}
Beispiel #14
0
static void twi_init(U32 fpba_hz)
{
  const gpio_map_t AT42QT1060_TWI_GPIO_MAP =
  {
  {AT42QT1060_TWI_SCL_PIN, AT42QT1060_TWI_SCL_FUNCTION},
  {AT42QT1060_TWI_SDA_PIN, AT42QT1060_TWI_SDA_FUNCTION}
  };

  const twi_options_t AT42QT1060_TWI_OPTIONS =
  {
    .pba_hz = 24000000,
    .speed = AT42QT1060_TWI_MASTER_SPEED,
    .chip = AT42QT1060_TWI_ADDRESS
  };

  // Assign I/Os to SPI.
  gpio_enable_module(AT42QT1060_TWI_GPIO_MAP,
    sizeof(AT42QT1060_TWI_GPIO_MAP) / sizeof(AT42QT1060_TWI_GPIO_MAP[0]));
  // Initialize as master.
  twi_master_init(AT42QT1060_TWI, &AT42QT1060_TWI_OPTIONS);

}

/*! \brief Callback function for a detect event of the touch sensor device.
 */
void touch_detect_callback(void)
{
  touch_detect = true;
}

struct at42qt1060_data touch_data;

void controller_task(void)
{
    // if a touch is detected we read the status
    if(touch_detect)
    {
      touch_data.detect_status =
      	at42qt1060_read_reg(AT42QT1060_DETECTION_STATUS);
      // need to read input port status too to reset CHG line
      at42qt1060_read_reg(AT42QT1060_INPUT_PORT_STATUS);
      touch_detect = false;
    }
}

static void controller_detect_int_handler(void)
{
  if(gpio_get_pin_interrupt_flag(AT42QT1060_DETECT_PIN))
  {
    gpio_clear_pin_interrupt_flag(AT42QT1060_DETECT_PIN);
    touch_detect_callback();
  }
}

void controller_init(U32 fcpu_hz, U32 fhsb_hz, U32 fpbb_hz, U32 fpba_hz)
{
  // Disable all interrupts
  Disable_global_interrupt();

  twi_init(fpba_hz);
  // wait until the device settles its CHG line
  cpu_delay_ms(230, fcpu_hz);
  at42qt1060_init(fcpu_hz);
  BSP_INTC_IntReg(&controller_detect_int_handler, AVR32_GPIO_IRQ_0 + AT42QT1060_DETECT_PIN/8, AVR32_INTC_INT1);
  // For now we only react on falling edge
  // Actually this is a level interrupt (low active)
  gpio_enable_pin_interrupt(AT42QT1060_DETECT_PIN, GPIO_FALLING_EDGE);
  gpio_clear_pin_interrupt_flag(AT42QT1060_DETECT_PIN);
  //static_fcpu_hz = fcpu_hz;
  cpu_set_timeout(cpu_ms_2_cy(JOYSTICK_KEY_DEBOUNCE_MS, static_fcpu_hz),
  	&joystick_key_sensibility_timer);

  // Enable global interrupts
  Enable_global_interrupt();

}
Beispiel #15
0
void aic23b_dac_start(uint32_t sample_rate_hz,
                      uint8_t num_channels,
                      uint8_t bits_per_sample,
                      bool swap_channels,
                      void (*callback)(uint32_t arg),
                      uint32_t callback_opt,
                      uint32_t pba_hz)
{
#if AIC23B_CTRL_INTERFACE == AIC23B_CTRL_INTERFACE_SPI
  static const spi_options_t AIC23B_SPI_OPTIONS =
  {
    .reg          = AIC23B_SPI_NPCS,
    .baudrate     = AIC23B_SPI_MASTER_SPEED,
    .bits         = AIC23B_CTRL_SIZE,
    .spck_delay   = 0,
    .trans_delay  = 0,
    .stay_act     = 0,
    .spi_mode     = 3,
    .modfdis      = 1
  };
  spi_setupChipReg(AIC23B_SPI, &AIC23B_SPI_OPTIONS, pba_hz);
#endif

  aic23b_dac_stop();

  gpio_enable_module(AIC23B_SSC_DAC_GPIO_MAP,
                     sizeof(AIC23B_SSC_DAC_GPIO_MAP) / sizeof(AIC23B_SSC_DAC_GPIO_MAP[0]));

  aic23b_pdc_t pdc;
  pdc.data  = AIC23B_DEFAULT(AIC23B_PDC);
  pdc.off   = 0;
  pdc.clk   = 0;
  pdc.osc   = 0;
  pdc.out   = 0;
  pdc.dac   = 0;
  pdc.adc   = 1;
  pdc.mic   = 1;
  pdc.line  = 1;
  aic23b_set_power_down_state(pdc);

  aic23b_dac_setup(sample_rate_hz,
                   num_channels,
                   bits_per_sample,
                   swap_channels,
                   callback,
                   callback_opt,
                   pba_hz);

  aic23b_aapc_t aapc;
  aapc.data = AIC23B_DEFAULT(AIC23B_AAPC);
  aapc.ste  = 0;
  aapc.dac  = 1;
  aapc.byp  = 0;
  aapc.micm = 1;
  aapc.micb = 0;
  aic23b_set_analog_audio_path(aapc);

  aic23b_dapc_t dapc;
  dapc.data   = AIC23B_DEFAULT(AIC23B_DAPC);
  dapc.dacm   = 0;
  dapc.deemp  = AIC23B_DAPC_DEEMP_NONE;
  dapc.adchp  = 1;
  aic23b_set_digital_audio_path(dapc);

  // set an acceptable start volume
  aic23b_set_headphone_volume(AIC23B_LEFT_CHANNEL | AIC23B_RIGHT_CHANNEL,
                              -30,
                              true);

  aic23b_activate_dig_audio(true);

  INTC_register_interrupt(&aic23b_ssc_tx_pdca_int_handler,
                          AIC23B_SSC_TX_PDCA_IRQ,
                          AIC23B_SSC_TX_PDCA_INT_LEVEL);
}


void aic23b_dac_setup(uint32_t sample_rate_hz,
                      uint8_t num_channels,
                      uint8_t bits_per_sample,
                      bool swap_channels,
                      void (*callback)(uint32_t arg),
                      uint32_t callback_opt,
                      uint32_t pba_hz)
{
#if defined(AIC23B_DAC_USE_RX_CLOCK) && AIC23B_DAC_USE_RX_CLOCK == true
  #if defined(AIC23B_DAC_RX_CLOCK_SET_CALLBACK)
    AIC23B_DAC_RX_CLOCK_SET_CALLBACK(2 * sample_rate_hz *
                                     ((bits_per_sample <= 16) ? 16 :
                                     (bits_per_sample <= 20) ? 20 :
                                     (bits_per_sample <= 24) ? 24 :
                                     32));
  #endif
  ssc_i2s_init(AIC23B_SSC,
               sample_rate_hz,
               bits_per_sample,
               (bits_per_sample <= 16) ? 16 :
               (bits_per_sample <= 20) ? 20 :
               (bits_per_sample <= 24) ? 24 :
                                         32,
               SSC_I2S_MODE_STEREO_OUT_EXT_CLK,
               pba_hz);
#else
  ssc_i2s_init(AIC23B_SSC,
               sample_rate_hz,
               bits_per_sample,
               (bits_per_sample <= 16) ? 16 :
               (bits_per_sample <= 20) ? 20 :
               (bits_per_sample <= 24) ? 24 :
                                         32,
               SSC_I2S_MODE_STEREO_OUT,
               pba_hz);
#endif

  pdca_channel_options_t aic23b_ssc_pdca_options =
  {
    .addr           = NULL,
    .size           = 0,
    .r_addr         = NULL,
    .r_size         = 0,
    .pid            = AIC23B_SSC_TX_PDCA_PID,
    .transfer_size  = (bits_per_sample <=  8) ? PDCA_TRANSFER_SIZE_BYTE      :
                      (bits_per_sample <= 16) ? PDCA_TRANSFER_SIZE_HALF_WORD :
                                                PDCA_TRANSFER_SIZE_WORD
  };
  pdca_init_channel(AIC23B_SSC_TX_PDCA_CHANNEL, &aic23b_ssc_pdca_options);
  pdca_enable(AIC23B_SSC_TX_PDCA_CHANNEL);

#if !defined(AIC23B_DAC_USE_RX_CLOCK) || AIC23B_DAC_USE_RX_CLOCK == false || \
    !defined(AIC23B_DAC_RX_CLOCK_SET_CALLBACK)
  // Set DAC frequency
  aic23b_configure_freq(AIC23B_MCLK_HZ, sample_rate_hz);
#endif

  aic23b_daif_t daif;
  daif.data   = AIC23B_DEFAULT(AIC23B_DAIF);
  daif.ms     = AIC23B_DAIF_MS_SLAVE;
  daif.lrswap = swap_channels;
  daif.lrp    = 0;
  daif.iwl    = (bits_per_sample <= 16) ? AIC23B_DAIF_IWL_16 :
                (bits_per_sample <= 20) ? AIC23B_DAIF_IWL_20 :
                (bits_per_sample <= 24) ? AIC23B_DAIF_IWL_24 :
                                          AIC23B_DAIF_IWL_32;
  daif.fmt    = AIC23B_DAIF_FMT_I2S;
  aic23b_write_reg(AIC23B_DAIF, daif.data);

  aic23b_output_params.num_channels             = num_channels;
  aic23b_output_params.callback                 = callback;
  aic23b_output_params.callback_opt             = callback_opt;
}
#endif

bool aic23b_dac_output(void *sample_buffer, size_t sample_length)
{
  bool global_interrupt_enabled;

  if (!(pdca_get_transfer_status(AIC23B_SSC_TX_PDCA_CHANNEL) &
        PDCA_TRANSFER_COUNTER_RELOAD_IS_ZERO))
    return false;

  if (sample_length)
  {
    if (aic23b_output_params.num_channels == 1)
    {
      int16_t *s16_sample_buffer = sample_buffer;
      int i;

      for (i = sample_length - 1; i >= 0; i--)
      {
        s16_sample_buffer[2 * i + 1] =
        s16_sample_buffer[2 * i]     = s16_sample_buffer[i];
      }
    }

    // The PDCA is not able to synchronize its start of transfer with the SSC
    // start of period, so this has to be done by polling the TF pin.
    // Not doing so may result in channels being swapped randomly.
    if ((global_interrupt_enabled = Is_global_interrupt_enabled()))
      Disable_global_interrupt();
    if (pdca_get_transfer_status(AIC23B_SSC_TX_PDCA_CHANNEL) &
        PDCA_TRANSFER_COMPLETE)
    {
      while (gpio_get_pin_value(AIC23B_SSC_TX_FRAME_SYNC_PIN));
      while (!gpio_get_pin_value(AIC23B_SSC_TX_FRAME_SYNC_PIN));
    }
    pdca_reload_channel(AIC23B_SSC_TX_PDCA_CHANNEL, sample_buffer, sample_length * 2);
    pdca_get_reload_size(AIC23B_SSC_TX_PDCA_CHANNEL);
    if (global_interrupt_enabled)
      Enable_global_interrupt();

    if (aic23b_output_params.callback_opt & AUDIO_DAC_OUT_OF_SAMPLE_CB)
      pdca_enable_interrupt_transfer_complete(AIC23B_SSC_TX_PDCA_CHANNEL);
    if (aic23b_output_params.callback_opt & AUDIO_DAC_RELOAD_CB)
      pdca_enable_interrupt_reload_counter_zero(AIC23B_SSC_TX_PDCA_CHANNEL);
  }
  return true;
}
Beispiel #16
0
int main (void)
{	
	// Variables -- Misc
	const twim_options_t twi_option_GYRO = twi_opt_GYRO;
	const twim_options_t twi_option_ACC = twi_opt_ACC;
	const twim_options_t twi_option_MAGN = twi_opt_MAGN;
	
	// Variables -- Control system
	float prev_e_z = 0;
	float prev_e_roll = 0;
	float prev_e_pitch = 0;
	float prev_e_yaw = 0;
	float eint_z = 0;
	float eint_roll = 0;
	float eint_pitch = 0;
	float eint_yaw = 0;
	float pitch_ederiv = 0; // Error derivative
	float roll_ederiv = 0;
	float prev_deriv_e_roll = 0;
	float yaw_ederiv = 0;
	float z_ederiv = 0;
	float e = 0;
	float dt;					// Time between samples
	unsigned long t1 = 0;
	unsigned long t2 = 0;
	float u1, u2, u3, u4 = 0;
	float m1, m2, m3, m4 = 0;
	float g_force = 240;
	int xcount = 0;
	float gain = 1;
	int time_to_update_data = 0;
	
	int deriv_count=0;
	
	const usart_options_t usart_option =  usart_opt;
	const usart_options_t usart_option_2 =  usart_opt_2;
	
	// Setting up the board		
	pcl_configure_clocks(&pcl_freq_param);
	board_init();
	
	// Initialize Bluetooth
	configure_AT(FPBA_HZ, usart_option);
	
	irq_initialize_vectors();
	cpu_irq_enable();
	
	Disable_global_interrupt();
	
	// Initialize interrupt vectors.
	INTC_init_interrupts();		
	INTC_register_interrupt(&usart_int_handler, USART_IRQ, AVR32_INTC_INT0);
	
	USART->ier = AVR32_USART_IER_RXRDY_MASK;
	
	// Enable all interrupts.
	Enable_global_interrupt();		
	
	// Enable Ultrasonic sensors
	enable_Ultrasonic();
	
	// Initialize motors
	initialize_PWM();
	

	
	tc_start(tc1, PWM_MOTOR1_CHANNEL);
	tc_start(tc0, PWM_MOTOR2_CHANNEL);
	tc_start(tc1, PWM_MOTOR3_CHANNEL);
	tc_start(tc1, PWM_MOTOR4_CHANNEL);
	
	// Waits for button press here after battery is connected
	while (gpio_get_pin_value(GPIO_PUSH_BUTTON_0));
	delay_ms(1000);
	/*
	while(1){
		while (motor2_speed<60)
		{
			motor2_speed += 1;	
			update_Motors();
			delay_ms(300);
		}
		while (motor2_speed>0)
		{
			motor2_speed -= 1;
			update_Motors();
			delay_ms(300);
		}
	}	
	while (gpio_get_pin_value(GPIO_PUSH_BUTTON_0));*/
	
	//delay_ms(3000);
	
	// Initialize RTC
	//AVR32_RTC->ctrl & AVR32_RTC_CTRL_BUSY_MASK = 0;
	rtc_init(&AVR32_RTC, RTC_OSC_32KHZ, 1);
	rtc_enable(&AVR32_RTC);
	
	// Initialize IMU parts
	initialize_IMU();
	
	// TESTING ONLY

	float test_array[2000];
	float test_array_2[2000];
	float test_array_3[2000];
	
	for (int k = 0; k < FILTER_LENGTH; k++){
		FIFO_deriv_roll[k] = roll;
	}
	
	time_to_update_data = 0;
	
	// Control system code begins
	while(1)
	{
		t1 = rtc_get_value(&AVR32_RTC); // Current time in ms
		dt = ((float)(t1-t2))*0.001*0.125;	// dt in seconds
		if (t1 < t2) // Timer overflowed
		{
			dt = ((float)(t1 + rtc_get_top_value(&AVR32_RTC))*0.001*0.125);		
		}
		t2 = t1;
		
		get_Angles();
		//pitch = 0;
		yaw = 0;
		
		e = des_z-z;											//calculating height error
		eint_z = eint_z + ((e+prev_e_z)/2)*dt;					//calculate error integral term
		z_ederiv = (e - prev_e_z)/dt;								//calculate error derivative term
		u1 =(KP_Z*e) + (KI_Z*eint_z) + (KD_Z*z_ederiv)+g_force;	//calculating control output
		prev_e_z=e;
		
		//ROLL
		e = des_roll-roll;										//calculating roll error
		eint_roll = eint_roll + ((e+prev_e_roll)/2)*dt;			//calculate error integral term
		prev_e_roll=e;
		
		for (int i = 0; i < (FILTER_LENGTH - 1); i++)
		{
			FIFO_deriv_roll[i] = FIFO_deriv_roll[i+1];	
		}
		FIFO_deriv_roll[FILTER_LENGTH-1] = e;
		
		roll_ederiv = (FIFO_deriv_roll[FILTER_LENGTH-1] - FIFO_deriv_roll[0])/(FILTER_LENGTH*dt);
	
		u2 =(KP_ROLL*e) + (KI_ROLL*eint_roll) + (KD_ROLL*roll_ederiv); //calculating control output

		if(xcount < 2000){
			test_array[xcount] = roll_ederiv;
			test_array_2[xcount] = roll;
			test_array_3[xcount] = g_roll;
		}		
		xcount++;
		
		//PITCH
		e = des_pitch-pitch;									//calculating pitch error
		eint_pitch = eint_pitch + ((e+prev_e_pitch)/2)*dt;		//calculate error integral term
		pitch_ederiv = (e - prev_e_pitch)/dt;							//calculate error derivative term
		u3 =(KP_PITCH*e) + (KI_PITCH*eint_pitch) + (KD_PITCH*pitch_ederiv);	//calculating control output
		prev_e_pitch=e;
		
		//YAW
		e = des_yaw-yaw;										//calculating yaw error
		eint_yaw = eint_yaw + ((e+prev_e_yaw)/2)*dt;			//calculate error integral term
		yaw_ederiv = (e - prev_e_yaw)/dt;							//calculate error derivative term
		u4 =(KPYAW*e) + (KIYAW*eint_yaw) + (KDYAW*yaw_ederiv);		//calculating control output
		prev_e_yaw=e;
		
		//MOTOR SPEEDS
		
		m1=(0.25*u1+0.5*u2+0.25*u4)*gain;
		m2=(0.25*u1+0.5*u3-0.25*u4)*gain;
		m3=(0.25*u1-0.5*u2+0.25*u4)*gain;
		m4=(0.25*u1-0.5*u3-0.25*u4)*gain;
		
		if (m1 > 95)
		m1 = 95;
		else if (m1 < 5)
		m1 = 5;
		
		if (m2 > 95)
		{
			m2 = 95;
		}
		else if (m2 < 5)
		{
			m2 = 5;
		}		
				
		if (m3 > 95)
		{
			m3 = 95;
		}
		else if (m3 < 5)
		{
			m3 = 5;
		}
		
		if (m4 > 95)
		{
			m4 = 95;
		}
		else if (m4 < 5)
		{
			m4 = 5;
		}
		
		motor1_speed = m2; //m2
		motor2_speed = m1; //m3
		motor3_speed = m4; //m4
		motor4_speed = m3; //m1..... the imu was turned 90 degrees....
		
		update_Motors();
		

		//Bluetooth Send
		if (time_to_update_data > 3)
		{
			// Get Ultrasonic data
			update_Ultrasonic();
					
			// Send out update through Bluetooth
			meas_roll = roll;
			meas_pitch = pitch;
			meas_yaw = yaw;

			transmitted_data();
			time_to_update_data = 0;
			
			received_data();			
		}
		else
		{
			delay_ms(7);			
		}	
		time_to_update_data++;		

	}
	
}
Beispiel #17
0
// main function
int main(void) {

	pm_switch_to_osc0(&AVR32_PM, FOSC0, OSC0_STARTUP);

	// Enable edge-triggered interrupt.
	eic_options[0].eic_mode  = EIC_MODE_EDGE_TRIGGERED;
	// Interrupt will trigger on falling edge (this is a must-do for the keypad scan
	// feature if the chosen mode is edge-triggered).
	eic_options[0].eic_edge  = EIC_EDGE_RISING_EDGE;
	// Initialize in synchronous mode : interrupt is synchronized to the clock
	eic_options[0].eic_async = EIC_SYNCH_MODE;
	// Set the interrupt line number.
	eic_options[0].eic_line  = QT1081_EIC_EXTINT_INT;

	// Activate LED0 & LED1 & LED2 & LED3 pins in GPIO output mode and switch them off.
	gpio_set_gpio_pin(LED0_GPIO);
	gpio_set_gpio_pin(LED1_GPIO);
	gpio_set_gpio_pin(LED2_GPIO);
	gpio_set_gpio_pin(LED3_GPIO);

	gpio_enable_module_pin( QT1081_EIC_EXTINT_PIN, QT1081_EIC_EXTINT_FUNCTION);

#if( INT_MODE == INT_MODE_GPIO)
	Disable_global_interrupt();

#if __GNUC__
	INTC_init_interrupts();
    /* Register interrupt handler to the interrupt controller
     * up, down buttons on PB22, PB23 -> GPIO_IRQ_6
     */
	INTC_register_interrupt(&touch_button_isr, AVR32_GPIO_IRQ_6, 0);//AVR32_INTC_INT0);
	/* Other buttons on PB[24..26] -> GPIO_IRQ_7 (PB23 - PB31) */
	INTC_register_interrupt(&touch_button_isr, AVR32_GPIO_IRQ_7, 0);
#endif
	gpio_enable_pin_interrupt(QT1081_TOUCH_SENSOR_0, GPIO_RISING_EDGE);
	gpio_enable_pin_interrupt(QT1081_TOUCH_SENSOR_1, GPIO_RISING_EDGE);
	gpio_enable_pin_interrupt(QT1081_TOUCH_SENSOR_2, GPIO_RISING_EDGE);
	gpio_enable_pin_interrupt(QT1081_TOUCH_SENSOR_3, GPIO_RISING_EDGE);
	gpio_enable_pin_interrupt(QT1081_TOUCH_SENSOR_4, GPIO_RISING_EDGE);

	Enable_global_interrupt();
#endif

#if(INT_MODE == INT_MODE_EIC)
	Disable_global_interrupt();

#if __GNUC__
	INTC_init_interrupts();
    /* Register the EXTINT1 interrupt handler to the interrupt controller
     */
	INTC_register_interrupt(&touch_button_isr, QT1081_EIC_EXTINT_IRQ, AVR32_INTC_INT0);
#endif

	  // Init the EIC controller with the options
	  eic_init(&AVR32_EIC, eic_options, 1);
	  // Enable the EIC lines.
	  eic_enable_lines(&AVR32_EIC, (1<<eic_options[0].eic_line));
	  // Enable the interrupt for each EIC line.
	  eic_enable_interrupt_lines(&AVR32_EIC, (1<<eic_options[0].eic_line));

	Enable_global_interrupt();
#endif

	while(true);

	return 0;
}
void boardsupport_init(central_data_t *central_data) 
{
	irq_initialize_vectors();
	cpu_irq_enable();
	Disable_global_interrupt();
		
	// Initialize the sleep manager
	sleepmgr_init();
	sysclk_init();

	board_init();
	delay_init(sysclk_get_cpu_hz());
	time_keeper_init();
		
	INTC_init_interrupts();

	// Switch on the red LED
	LED_On(LED2);

	// servo_pwm_hardware_init();
	pwm_servos_init( CS_ON_SERVO_7_8 );
	
	// Init UART 0 for XBEE communication
	xbee_init(UART0);
				
	// Init UART 4 for wired communication
	//console_init(CONSOLE_UART4);
	// Init USB for wired communication
	console_init(CONSOLE_USB);
		
	// connect abstracted aliases to hardware ports
	central_data->telemetry_down_stream = xbee_get_out_stream();
	central_data->telemetry_up_stream = xbee_get_in_stream();
	central_data->debug_out_stream = console_get_out_stream();
	central_data->debug_in_stream = console_get_in_stream();
	
	// init debug output
	print_util_dbg_print_init(central_data->debug_out_stream);
	print_util_dbg_print("Debug stream initialised\r\n");

	// RC receiver initialization
	spektrum_satellite_init();

	// init imu & compass
	i2c_driver_init(I2C0);
	
	lsm330dlc_init();
	print_util_dbg_print("LSM330 initialised \r\n");
		
	hmc5883l_init_slow();
	print_util_dbg_print("HMC5883 initialised \r\n");
	
	// init radar or ultrasound (not implemented yet)
	//i2c_driver_init(I2C1);
	
	// init 6V enable
	gpio_enable_gpio_pin(AVR32_PIN_PA04);
	gpio_set_gpio_pin(AVR32_PIN_PA04);
	
	Enable_global_interrupt();

	// Init piezo speaker
	piezo_speaker_init_binary();
	
	print_util_dbg_print("Board initialised\r\n");
}
/*************************************************************************************************
 * firmware_backup_and_reboot_task
 *
 * Creates a backup of the current firmware in EEPROM and reboots the device afterwards
 */
static portTASK_FUNCTION( firmware_backup_and_reboot_task, pvParameters )
{
	uint32_t current_flash_address = FIRMWARE_START_ADDRESS;
	uint32_t last_used_flash_address = 0;
	uint8_t buffer[EEPROM_PAGE_SIZE];
	uint32_t buffer_index = 0;
	wdt_opt_t wdt_opt = { .us_timeout_period = 1000000  };

	/* find last used byte in flash */
	for (last_used_flash_address = FIRMWARE_END_ADDRESS;
	     last_used_flash_address > FIRMWARE_START_ADDRESS;
		 last_used_flash_address--)
	{
		if (*((uint8_t *) (last_used_flash_address)) != 0xFF)
		{
			break;
		}
	}

	registry_set_value("Firmware Backup Length", last_used_flash_address - FIRMWARE_START_ADDRESS + 1);

	while (current_flash_address + buffer_index < last_used_flash_address + 1)
	{
		if (buffer_index < EEPROM_PAGE_SIZE)
		{
			buffer[buffer_index] = *((uint8_t *) (current_flash_address + buffer_index));
			buffer_index++;
		}
		else
		{
			/* EEPROM_buffer is full, flush it */
			eeprom_write(FIRMWARE_BACKUP_EEPROM_START + (current_flash_address - FIRMWARE_START_ADDRESS), buffer, buffer_index);
			current_flash_address += buffer_index;

			buffer[0] = *((uint8_t *) current_flash_address);
			buffer_index = 1;
		}
	}

	/* flush remainder of buffer */
	eeprom_write(FIRMWARE_BACKUP_EEPROM_START + (current_flash_address - FIRMWARE_START_ADDRESS), buffer, buffer_index);

	registry_set_value("Firmware Update State", FIRMWARE_STATE_FLASH_NEW_APPLICATION); // new application ready in EEPROM, backup complete

	/* generate reset */
	Disable_global_interrupt();
	cpu_irq_disable();
	wdt_enable(&wdt_opt);
	while (1);

	/* Kill this task (redundant, I know) */
	vTaskDelete(NULL);
}

/*************************************************************************************************
 * firmware_update_init
 *
 * Initializes the firmware update module
 */
void firmware_update_init(void)
{
	registry_initialize_key("Firmware Update State", FIRMWARE_STATE_JUMP_TO_APPLICATION, true);
	registry_initialize_key("Firmware Length", 0, true);
	registry_initialize_key("Firmware Backup Length", 0, true);

	if (registry_get_value("Firmware Update State") == FIRMWARE_STATE_RESTORE_BACKUP)
	{
		/* FIRMWARE_STATE_RESTORE_BACKUP is activated automatically after a new version has been flashed */
		current_firmware_update_status = SUCCESSFUL_ASK_USER_TO_KEEP;
	}
}
Beispiel #20
0
//! This function is the generic control pipe management function.
//! This function is used to send and receive control requests over control pipe.
//!
//! @todo Fix all time-out errors and disconnections in active wait loop.
//!
//! @param data_pointer void *: Pointer to data to transfer
//!
//! @return Status_t: Status
//!
//! @note This function uses the usb_request global structure. Hence, this
//! structure should be filled before calling this function.
//!
Status_t host_transfer_control(void *data_pointer)
{
  int status = CONTROL_GOOD;
  bool sav_int_sof_enable;
  bool sav_glob_int_en;
  U16 data_length;
  U8 c;

  Usb_ack_event(EVT_HOST_SOF);
  sav_int_sof_enable = Is_host_sof_interrupt_enabled();
  Host_enable_sof_interrupt();                // SOF software detection is in interrupt subroutine
  while (!Is_usb_event(EVT_HOST_SOF))         // Wait 1 SOF
  {
    if (Is_host_emergency_exit())
    {
      Host_freeze_pipe(P_CONTROL);
      Host_reset_pipe(P_CONTROL);
      status = CONTROL_TIMEOUT;
      goto host_transfer_control_end;
    }
  }
  Host_configure_pipe_token(P_CONTROL, TOKEN_SETUP);
  Host_ack_setup_ready();
  Host_unfreeze_pipe(P_CONTROL);

  // Build and send the setup request fields
  Host_reset_pipe_fifo_access(P_CONTROL);
  Host_write_pipe_data(P_CONTROL, 8, usb_request.bmRequestType);
  Host_write_pipe_data(P_CONTROL, 8, usb_request.bRequest);
  Host_write_pipe_data(P_CONTROL, 16, usb_format_mcu_to_usb_data(16, usb_request.wValue));
  Host_write_pipe_data(P_CONTROL, 16, usb_format_mcu_to_usb_data(16, usb_request.wIndex));
  Host_write_pipe_data(P_CONTROL, 16, usb_format_mcu_to_usb_data(16, usb_request.wLength));
  Host_send_setup();

  while (!Is_host_setup_ready())  // Wait for SETUP ack
  {
    if (Is_host_emergency_exit())
    {
      Host_freeze_pipe(P_CONTROL);
      Host_reset_pipe(P_CONTROL);
      status = CONTROL_TIMEOUT;
      goto host_transfer_control_end;
    }
    if (Is_host_pipe_error(P_CONTROL))  // Any error?
    {
      c = Host_error_status(P_CONTROL);
      Host_ack_all_errors(P_CONTROL);
      status = c;   // Send error status
      goto host_transfer_control_end;
    }
  }

  // Setup token sent; now send IN or OUT token
  // Before just wait 1 SOF
  Usb_ack_event(EVT_HOST_SOF);
  Host_freeze_pipe(P_CONTROL);
  data_length = usb_request.wLength;
  while (!Is_usb_event(EVT_HOST_SOF))         // Wait 1 SOF
  {
    if (Is_host_emergency_exit())
    {
      Host_freeze_pipe(P_CONTROL);
      Host_reset_pipe(P_CONTROL);
      status = CONTROL_TIMEOUT;
      goto host_transfer_control_end;
    }
  }

  // IN request management ---------------------------------------------
  if (usb_request.bmRequestType & 0x80)       // Data stage IN (bmRequestType.D7 == 1)
  {
    Host_disable_continuous_in_mode(P_CONTROL);
    Host_configure_pipe_token(P_CONTROL, TOKEN_IN);
    Host_ack_control_in_received_free();
    while (data_length)
    {
      Host_unfreeze_pipe(P_CONTROL);
      private_sof_counter = 0;        // Reset the counter in SOF detection subroutine
      while (!Is_host_control_in_received())
      {
        if (Is_host_emergency_exit())
        {
          Host_freeze_pipe(P_CONTROL);
          Host_reset_pipe(P_CONTROL);
          status = CONTROL_TIMEOUT;
          goto host_transfer_control_end;
        }
        if (Is_host_pipe_error(P_CONTROL))  // Any error?
        {
          c = Host_error_status(P_CONTROL);
          Host_ack_all_errors(P_CONTROL);
          status = c;   // Send error status
          goto host_transfer_control_end;
        }
        if (Is_host_stall(P_CONTROL))
        {
          Host_ack_stall(P_CONTROL);
          status = CONTROL_STALL;
          goto host_transfer_control_end;
        }
#if TIMEOUT_DELAY_ENABLE == ENABLE
      if (1000 < host_get_timeout()) // Count 1s
      {
          Host_freeze_pipe(P_CONTROL);
          Host_reset_pipe(P_CONTROL);
          status = CONTROL_TIMEOUT;
          goto host_transfer_control_end;
      }
#endif
      }
      Host_reset_pipe_fifo_access(P_CONTROL);
      c = Host_get_pipe_size(P_CONTROL) - Host_byte_count(P_CONTROL);
      data_length = host_read_p_rxpacket(P_CONTROL, data_pointer, data_length, &data_pointer);
      if (usb_request.incomplete_read || c) data_length = 0;
      Host_freeze_pipe(P_CONTROL);
      Host_ack_control_in_received_free();

      // In low-speed mode, the USB IP may have not yet sent the ACK at this
      // point. The USB IP does not support a new start of transaction request
      // from the firmware if the ACK has not been sent. The only means of
      // making sure the ACK has been sent is to wait for the next Keep-Alive
      // before starting a new transaction.
      if (Is_usb_low_speed_mode())
      {
        Usb_ack_event(EVT_HOST_SOF);
        if ((sav_glob_int_en = Is_global_interrupt_enabled())) Disable_global_interrupt();
        Host_ack_sof();
        (void)Is_host_sof_interrupt_enabled();
        if (sav_glob_int_en) Enable_global_interrupt();
        Host_enable_sof_interrupt();
        while (!Is_usb_event(EVT_HOST_SOF))         // Wait for next Keep-Alive
        {
          if (Is_host_emergency_exit())
          {
            Host_freeze_pipe(P_CONTROL);
            Host_reset_pipe(P_CONTROL);
            status = CONTROL_TIMEOUT;
            goto host_transfer_control_end;
          }
        }
      }
    }                                 // End of IN data stage

    Host_configure_pipe_token(P_CONTROL, TOKEN_OUT);
    Host_ack_control_out_ready_send();
    Host_unfreeze_pipe(P_CONTROL);
    while (!Is_host_control_out_ready())
    {
      if (Is_host_emergency_exit())
      {
        Host_freeze_pipe(P_CONTROL);
        Host_reset_pipe(P_CONTROL);
        status = CONTROL_TIMEOUT;
        goto host_transfer_control_end;
      }
      if (Is_host_pipe_error(P_CONTROL))  // Any error?
      {
        c = Host_error_status(P_CONTROL);
        Host_ack_all_errors(P_CONTROL);
        status = c;   // Send error status
        goto host_transfer_control_end;
      }
      if (Is_host_stall(P_CONTROL))
      {
        Host_ack_stall(P_CONTROL);
        status = CONTROL_STALL;
        goto host_transfer_control_end;
      }
    }
    Host_ack_control_out_ready();
  }

  // OUT request management --------------------------------------------
  else                                        // Data stage OUT (bmRequestType.D7 == 0)
  {
    Host_configure_pipe_token(P_CONTROL, TOKEN_OUT);
    Host_ack_control_out_ready();
    while (data_length)
    {
      Host_unfreeze_pipe(P_CONTROL);
      Host_reset_pipe_fifo_access(P_CONTROL);
      data_length = host_write_p_txpacket(P_CONTROL, data_pointer, data_length, (const void **)&data_pointer);
      Host_send_control_out();
      while (!Is_host_control_out_ready())
      {
        if (Is_host_emergency_exit())
        {
          Host_freeze_pipe(P_CONTROL);
          Host_reset_pipe(P_CONTROL);
          status = CONTROL_TIMEOUT;
          goto host_transfer_control_end;
        }
        if (Is_host_pipe_error(P_CONTROL))  // Any error?
        {
          c = Host_error_status(P_CONTROL);
          Host_ack_all_errors(P_CONTROL);
          status = c;   // Send error status
          goto host_transfer_control_end;
        }
        if (Is_host_stall(P_CONTROL))
        {
          Host_ack_stall(P_CONTROL);
          status = CONTROL_STALL;
          goto host_transfer_control_end;
        }
      }
      Host_ack_control_out_ready();
    }                                 // End of OUT data stage

    Host_freeze_pipe(P_CONTROL);
    Host_configure_pipe_token(P_CONTROL, TOKEN_IN);
    Host_ack_control_in_received_free();
    Host_unfreeze_pipe(P_CONTROL);
    while (!Is_host_control_in_received())
    {
      if (Is_host_emergency_exit())
      {
        Host_freeze_pipe(P_CONTROL);
        Host_reset_pipe(P_CONTROL);
        status = CONTROL_TIMEOUT;
        goto host_transfer_control_end;
      }
      if (Is_host_pipe_error(P_CONTROL))  // Any error?
      {
        c = Host_error_status(P_CONTROL);
        Host_ack_all_errors(P_CONTROL);
        status = c;   // Send error status
        goto host_transfer_control_end;
      }
      if (Is_host_stall(P_CONTROL))
      {
        Host_ack_stall(P_CONTROL);
        status = CONTROL_STALL;
        goto host_transfer_control_end;
      }
    }
    Host_ack_control_in_received();
    Host_freeze_pipe(P_CONTROL);
    Host_free_control_in();
  }

host_transfer_control_end:
  if (!sav_int_sof_enable)                    // Restore SOF interrupt enable
  {
    if ((sav_glob_int_en = Is_global_interrupt_enabled())) Disable_global_interrupt();
    Host_disable_sof_interrupt();
    (void)Is_host_sof_interrupt_enabled();
    if (sav_glob_int_en) Enable_global_interrupt();
  }

  return status;
}
Beispiel #21
0
//! This function checks if the device class is supported.
//! The function looks in all interfaces declared in the received descriptors if
//! one of them matches an entry of the CLASS/SUB_CLASS/PROTOCOL table.
//! If HOST_AUTO_CFG_ENDPOINT is enabled, a pipe is configured for each endpoint
//! of supported interfaces.
//!
//! @return bool: Status
//!
bool host_check_class(void)
{
  U8 *descriptor, *conf_end;
  U8 device_class, device_subclass, device_protocol;
  U8 c;
#if HOST_AUTO_CFG_ENDPOINT == ENABLE
  U8 nb_endpoint_to_configure = 0;
  U8 ep_index = 0;
  U8 physical_pipe = P_1;   // P_1 because physical pipe 0 is reserved for control

  // By default, the host is configured when returning
  Host_set_configured();
#endif

  // First, assume no interface is supported
  nb_interface_supported = 0;

  // Check if configuration descriptor
  if (data_stage[OFFSET_FIELD_DESCRIPTOR_TYPE] != CONFIGURATION_DESCRIPTOR) return false;

  bmattributes = data_stage[OFFSET_FIELD_BMATTRIBUTES];
  maxpower     = data_stage[OFFSET_FIELD_MAXPOWER];

  conf_end = data_stage +
             min(usb_format_usb_to_mcu_data(16, *(U16 *)(data_stage + OFFSET_FIELD_TOTAL_LENGTH)),
                 SIZEOF_DATA_STAGE - OFFSET_FIELD_PROTOCOL);

  // Look in all interfaces declared in the configuration
  for (descriptor = data_stage + data_stage[OFFSET_DESCRIPTOR_LENGTH]; descriptor < conf_end;
       descriptor += descriptor[OFFSET_DESCRIPTOR_LENGTH])
  {
    // Find next interface descriptor
    switch (descriptor[OFFSET_FIELD_DESCRIPTOR_TYPE])
    {
    case INTERFACE_DESCRIPTOR:
      // Check the number of supported interfaces does not exceed the maximum
      if (nb_interface_supported >= MAX_INTERFACE_SUPPORTED) return true;

#if HOST_AUTO_CFG_ENDPOINT == ENABLE
      // If there are still endpoints to configure although a new interface descriptor has been found
      if (nb_endpoint_to_configure)
      {
        // Mark the host as not configured
        Host_clear_configured();

        // Reset the number of endpoints to configure
        nb_endpoint_to_configure = 0;
      }
#endif

      // Found an interface descriptor
      // Get characteristics of this interface
      device_class    = descriptor[OFFSET_FIELD_CLASS];
      device_subclass = descriptor[OFFSET_FIELD_SUB_CLASS];
      device_protocol = descriptor[OFFSET_FIELD_PROTOCOL];

      // Look in registered class table for match
      for (c = 0; c < REG_CLASS_CNT; c += 3)
      {
        if (registered_class[c]     == device_class    &&   // Class is correct
            registered_class[c + 1] == device_subclass &&   // Subclass is correct
            registered_class[c + 2] == device_protocol)     // Protocol is correct
        {
          // Store this interface as supported interface
          // Memorize its interface nb
          interface_supported[nb_interface_supported].interface_nb = descriptor[OFFSET_FIELD_INTERFACE_NB];
          //          its alternate setting
          interface_supported[nb_interface_supported].altset_nb    = descriptor[OFFSET_FIELD_ALT];
          //          its USB class
          interface_supported[nb_interface_supported].uclass        = device_class;
          //          its USB subclass
          interface_supported[nb_interface_supported].subclass     = device_subclass;
          //          its USB protocol
          interface_supported[nb_interface_supported].protocol     = device_protocol;
          //          the number of endpoints associated with this interface
#if HOST_AUTO_CFG_ENDPOINT == ENABLE
          ep_index = 0;
          nb_endpoint_to_configure =
#endif
          interface_supported[nb_interface_supported].nb_ep        = min(descriptor[OFFSET_FIELD_NB_OF_EP], MAX_EP_PER_INTERFACE);

          // Update the number of supported interfaces
          nb_interface_supported++;

          // Class/subclass/protocol is registered, so look for next interface descriptor
          break;
        }
      }
      break;

#if HOST_AUTO_CFG_ENDPOINT == ENABLE
    case ENDPOINT_DESCRIPTOR:
      // If there are still endpoints to configure while there are free pipes
      if (physical_pipe < MAX_PEP_NB && nb_endpoint_to_configure)
      {
        nb_endpoint_to_configure--;

        // Reconfigure the new physical pipe to get rid of any previous configuration
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
        Disable_global_interrupt();
  #endif
        Host_disable_pipe(physical_pipe);
  #if USB_HOST_PIPE_INTERRUPT_TRANSFER == ENABLE
        (void)Is_host_pipe_enabled(physical_pipe);
        Enable_global_interrupt();
  #endif
        Host_unallocate_memory(physical_pipe);
        Host_enable_pipe(physical_pipe);

        // Fix HW, set freq at 0 in case of no interrupt endpoint
        if( TYPE_INTERRUPT != descriptor[OFFSET_FIELD_EP_TYPE] ) descriptor[OFFSET_FIELD_EP_INTERVAL] = 0;

        // Build the pipe configuration according to the endpoint descriptor fields received
        (void)Host_configure_pipe(
                physical_pipe,                                      // Pipe nb in USB interface
                descriptor[OFFSET_FIELD_EP_INTERVAL],               // Interrupt period (for interrupt pipe)
                Get_desc_ep_nbr(descriptor[OFFSET_FIELD_EP_ADDR]),  // Pipe endpoint number
                descriptor[OFFSET_FIELD_EP_TYPE],                   // Pipe type (isochronous/bulk/interrupt)
                Get_pipe_token(descriptor[OFFSET_FIELD_EP_ADDR]),   // Pipe token (IN/OUT)
                descriptor[OFFSET_FIELD_EP_SIZE] |
                descriptor[OFFSET_FIELD_EP_SIZE + 1] << 8,          // Pipe size
                   ((TYPE_ISOCHRONOUS == (descriptor[OFFSET_FIELD_EP_TYPE] & TRANSFER_TYPE_MASK))
                 || (TYPE_BULK        == (descriptor[OFFSET_FIELD_EP_TYPE] & TRANSFER_TYPE_MASK))
                 ? DOUBLE_BANK : SINGLE_BANK)  // Number of banks to allocate for pipe
              );

#if (USB_HIGH_SPEED_SUPPORT==true)
        if( (TYPE_BULK == Host_get_pipe_type(physical_pipe))
        &&  (TOKEN_OUT == Host_get_pipe_token(physical_pipe)) )
        {
           if( !Is_usb_full_speed_mode() )
           {
              // Enable PING management for bulk OUT endpoint each micro frame
              Host_configure_pipe_int_req_freq(physical_pipe,0);
              Host_enable_ping(physical_pipe);
           }
        }
#endif

        // Update endpoint pipe table in supported interface structure
        interface_supported[nb_interface_supported - 1].ep_pipe[ep_index++] = physical_pipe++;
      }
      break;
#endif
    }

    // Call user callback to look more deeply into the configuration descriptor
    Host_user_check_class_action(descriptor);
  }

#if HOST_AUTO_CFG_ENDPOINT == ENABLE
  // If there are still endpoints to configure although all descriptors have been parsed
  if (nb_endpoint_to_configure)
  {
    // Mark the host as not configured
    Host_clear_configured();
  }
#endif

  return (nb_interface_supported > 0);
}
void boardsupport_init(central_data_t *central_data) 
{
	irq_initialize_vectors();
	cpu_irq_enable();
	Disable_global_interrupt();
		
	// Initialize the sleep manager
	sleepmgr_init();
	sysclk_init();

	board_init();
	delay_init(sysclk_get_cpu_hz());
	time_keeper_init();
		
	INTC_init_interrupts();

	// Switch on the red LED
	LED_On(LED2);

	// servo_pwm_hardware_init();
	pwm_servos_init( CS_ON_SERVO_7_8 );
	
	// Init UART 0 for XBEE communication
	xbee_init(UART0);
				
	// Init UART 3 for GPS communication
	gps_ublox_init(&(central_data->gps), UART3);
	
	// Init UART 4 for wired communication
	//console_init(CONSOLE_UART4);
	// Init USB for wired communication
	console_init(CONSOLE_USB);
		
	// connect abstracted aliases to hardware ports
	central_data->telemetry_down_stream = xbee_get_out_stream();
	central_data->telemetry_up_stream = xbee_get_in_stream();
	central_data->debug_out_stream = console_get_out_stream();
	central_data->debug_in_stream = console_get_in_stream();
	
	// init debug output
	print_util_dbg_print_init(central_data->debug_out_stream);
	print_util_dbg_print("Debug stream initialised\r\n");

	// Bind RC receiver with remote
	// spektrum_satellite_bind();

	// RC receiver initialization
	spektrum_satellite_init();

	// Init analog rails
	analog_monitor_conf_t analog_monitor_config = analog_monitor_default_config;
	//analog_monitor_config.conv_factor[ANALOG_RAIL_6] = 0.00023485f * 6.6f;
	//analog_monitor_config.conv_factor[ANALOG_RAIL_7] = 0.00023485f * 6.6f;
	//analog_monitor_config.conv_factor[ANALOG_RAIL_10] = -0.0002409f * 11.0f;
	//analog_monitor_config.conv_factor[ANALOG_RAIL_11] = -0.0002409f * 11.0f;
	analog_monitor_init(&central_data->analog_monitor, &analog_monitor_config);
	
	// init imu & compass
	i2c_driver_init(I2C0);
	
	lsm330dlc_init();
	print_util_dbg_print("LSM330 initialised \r\n");
		
	hmc5883l_init_slow();
	print_util_dbg_print("HMC5883 initialised \r\n");
	
	bmp085_init(&central_data->pressure);
	
	// init radar or ultrasound (not implemented yet)
	//i2c_driver_init(I2C1);
	
	// init 6V enable
	gpio_enable_gpio_pin(AVR32_PIN_PA04);
	gpio_set_gpio_pin(AVR32_PIN_PA04);
	
	Enable_global_interrupt();

	// Init piezo speaker
	piezo_speaker_init_binary();
	
	print_util_dbg_print("Board initialised\r\n");
}
Beispiel #23
0
bool xMACBInit(volatile avr32_macb_t *macb)
{
  bool global_interrupt_enabled = Is_global_interrupt_enabled();
  volatile unsigned long status;

  // generate an hardware reset of the phy
  ethernet_phy_hw_reset();

  // generate a software reset of the phy
  ethernet_phy_sw_reset(macb);

  // set up registers
  macb->ncr = 0;
  macb->tsr = ~0UL;
  macb->rsr = ~0UL;

  if (global_interrupt_enabled) Disable_global_interrupt();
  macb->idr = ~0UL;
  status = macb->isr;
  if (global_interrupt_enabled) Enable_global_interrupt();

#if ETHERNET_CONF_USE_RMII_INTERFACE
  // RMII used, set 0 to the USRIO Register
  macb->usrio &= ~AVR32_MACB_RMII_MASK;
#else
  // RMII not used, set 1 to the USRIO Register
  macb->usrio |= AVR32_MACB_RMII_MASK;
#endif

  // Load our MAC address into the MACB.
  prvSetupMACAddress(macb);

  // Setup the buffers and descriptors.
  prvSetupDescriptors(macb);

#if ETHERNET_CONF_SYSTEM_CLOCK <= 20000000
  macb->ncfgr |= (AVR32_MACB_NCFGR_CLK_DIV8 << AVR32_MACB_NCFGR_CLK_OFFSET);
#elif ETHERNET_CONF_SYSTEM_CLOCK <= 40000000
  macb->ncfgr |= (AVR32_MACB_NCFGR_CLK_DIV16 << AVR32_MACB_NCFGR_CLK_OFFSET);
#elif ETHERNET_CONF_SYSTEM_CLOCK <= 80000000
  macb->ncfgr |= AVR32_MACB_NCFGR_CLK_DIV32 << AVR32_MACB_NCFGR_CLK_OFFSET;
#elif ETHERNET_CONF_SYSTEM_CLOCK <= 160000000
  macb->ncfgr |= AVR32_MACB_NCFGR_CLK_DIV64 << AVR32_MACB_NCFGR_CLK_OFFSET;
#else
# error System clock too fast
#endif

  // Are we connected?
  if( prvProbePHY(macb) == true )
  {
    // Enable the interrupt!
    portENTER_CRITICAL();
    {
      prvSetupMACBInterrupt(macb);
    }
    portEXIT_CRITICAL();
    // Enable Rx and Tx, plus the stats register.
    macb->ncr = AVR32_MACB_NCR_TE_MASK | AVR32_MACB_NCR_RE_MASK;
    return (true);
  }
  return (false);
}
void init_PWM(int velocidad, int direccion){
	int auxiliar;
	switch(velocidad){
		case 9:
			auxiliar = 2;
			break;
		case 8:
			auxiliar = 4;
			break;
		case 7:
			auxiliar = 6;
			break;
		case 6:
			auxiliar = 8;
			break;
		case 5:
			auxiliar = 10;
			break;
		case 4:
			auxiliar = 12;
			break;
		case 3:
			auxiliar = 14;
			break;
		case 2:
			auxiliar = 16;
			break;
		case 1:
			auxiliar = 18;
			break;
	}//SWITCH
	pwm_opt_t pwm_opt =
	{
		.diva = AVR32_PWM_DIVA_CLK_OFF,
		.divb = AVR32_PWM_DIVB_CLK_OFF,
		.prea = AVR32_PWM_PREA_MCK,
		.preb = AVR32_PWM_PREB_MCK
	};
	
	avr32_pwm_channel_t pwm_channel = { .ccnt = 0 };
		pwm_channel.cdty = auxiliar; /* Channel duty cycle, should be < CPRD. */
		pwm_channel.cprd = 20; /* Channel period. */
		pwm_channel.cupd = 0; /* Channel update is not used here. */
		pwm_channel.CMR.calg = PWM_MODE_LEFT_ALIGNED; /* Channel mode. */
		pwm_channel.CMR.cpol = PWM_POLARITY_LOW;      /* Channel polarity. */
		pwm_channel.CMR.cpd = PWM_UPDATE_DUTY;        /* Not used the first time. */
		pwm_channel.CMR.cpre = AVR32_PWM_CPRE_MCK_DIV_256; /* Channel prescaler. */
		
		gpio_enable_module_pin(PWM_PIN_3, PWM_PIN_Function);
		gpio_enable_module_pin(PWM_PIN_1, PWM_PIN_Function);
		pwm_init(&pwm_opt);
		if(direccion == 1){//FORWARD
			pwm_channel_init(PWM_ID_3, &pwm_channel);
			pwm_start_channels(1 << PWM_ID_3);

		}
		if(direccion == 0){//REVERSE
			pwm_channel_init(PWM_ID_1, &pwm_channel);
			pwm_start_channels(1 << PWM_ID_1);
		}
}
void update_PWM(int velocidad, int direccion){
	int auxiliar;
	switch(velocidad){
		case 9:
		auxiliar = 2;
		break;
		case 8:
		auxiliar = 4;
		break;
		case 7:
		auxiliar = 6;
		break;
		case 6:
		auxiliar = 8;
		break;
		case 5:
		auxiliar = 10;
		break;
		case 4:
		auxiliar = 12;
		break;
		case 3:
		auxiliar = 14;
		break;
		case 2:
		auxiliar = 16;
		break;
		case 1:
		auxiliar = 18;
		break;
	}//SWITCH
		avr32_pwm_channel_t pwm_channel = { .ccnt = 0 };
		pwm_channel.cdty = auxiliar; /* Channel duty cycle, should be < CPRD. */
		pwm_channel.cprd = 20; /* Channel period. */
		pwm_channel.cupd = 0; /* Channel update is not used here. */
		pwm_channel.CMR.calg = PWM_MODE_LEFT_ALIGNED; /* Channel mode. */
		pwm_channel.CMR.cpol = PWM_POLARITY_LOW;      /* Channel polarity. */
		pwm_channel.CMR.cpd = PWM_UPDATE_DUTY;        /* Not used the first time. */
		pwm_channel.CMR.cpre = AVR32_PWM_CPRE_MCK_DIV_256; /* Channel prescaler. */
	
	if(direccion == 1){//FORWARD
		pwm_stop_channels(1<<PWM_ID_1);
		pwm_stop_channels(1<<PWM_ID_3);
		pwm_channel_init(PWM_ID_3, &pwm_channel);
		pwm_start_channels(1 << PWM_ID_3);
		
	}
	if(direccion == 0){//REVERSE
		pwm_stop_channels(1<<PWM_ID_1);
		pwm_stop_channels(1<<PWM_ID_3);
		pwm_channel_init(PWM_ID_1, &pwm_channel);
		pwm_start_channels(1 << PWM_ID_1);
	}
	bandera = 0;
}
static void handler_interrupt(void){
	if (gpio_get_pin_interrupt_flag(GPIO_JOYSTICK_UP)){
		direccion = 1;
		gpio_clear_pin_interrupt_flag(GPIO_JOYSTICK_UP);
	}
	if (gpio_get_pin_interrupt_flag(GPIO_JOYSTICK_DOWN)){
		direccion = 0;
		gpio_clear_pin_interrupt_flag(GPIO_JOYSTICK_DOWN);
	}
	bandera = 1;
}
void init_INTC(void){
	gpio_enable_pin_interrupt(GPIO_JOYSTICK_UP , GPIO_FALLING_EDGE);
	gpio_enable_pin_interrupt(GPIO_JOYSTICK_DOWN , GPIO_FALLING_EDGE);
	Disable_global_interrupt();
	INTC_init_interrupts();
	  INTC_register_interrupt( &handler_interrupt, AVR32_GPIO_IRQ_0 + (GPIO_JOYSTICK_UP/8), AVR32_INTC_INT1);
	  INTC_register_interrupt( &handler_interrupt, AVR32_GPIO_IRQ_0 + (GPIO_JOYSTICK_DOWN/8), AVR32_INTC_INT1);
	Enable_global_interrupt();
}
/*! \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 */

}
Beispiel #26
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);
  }
}
Beispiel #27
0
/**
 * \internal
 * \brief Transmit PPLC command to Proxy PLC controller
 *
 *  \param uc_cmd           PPLC command to send
 *  \param us_addr          Address where is the data to apply command
 *  \param us_len           Number of bytes in operation
 *  \param ptr_buf          Pointer to data buffer
 *  \param uc_bytes_rep     Number of repetitions(only use in PPLC_CMD_WRITE_REP
 * command)
 *
 * \retval true if there is no error
 * \retval false if there is an error
 */
static int8_t _pplc_cmd_op(uint8_t uc_cmd, uint16_t us_addr, uint16_t us_len,
		uint8_t *ptr_buf, uint8_t uc_bytes_rep)
{
	uint8_t *ptr_data_buf;
	uint16_t uc_num_tx_bytes;
	uint16_t us_data_len, us_data_len_acc;
	uint16_t us_address;

	Disable_global_interrupt();

	if (!uc_pplc_is_busy) {
		uc_pplc_is_busy = true;
		ptr_data_buf = ptr_buf;
		us_data_len = us_len;
		us_data_len_acc = 0;
		us_address = us_addr;

		while (us_data_len) {
			/* protection to data length */
			if (us_data_len > PDC_PPLC_BUFFER_SIZE) {
				us_data_len = PDC_PPLC_BUFFER_SIZE - 4;
			}

			uc_num_tx_bytes = us_data_len + 4;

			/* Configure PPLC Tx buffer */
			gs_pplc_tx_buffer[0] = uc_cmd;
			gs_pplc_tx_buffer[1] = (uint8_t)(us_address >> 8);
			gs_pplc_tx_buffer[2] = (uint8_t)(us_address);
			if (uc_cmd == PPLC_CMD_WRITE_REP) {
				gs_pplc_tx_buffer[3] = uc_bytes_rep;
			} else {
				gs_pplc_tx_buffer[3] = 0;
			}

			/* Fill data */
			if (uc_cmd == PPLC_CMD_READ) {
				memset(&gs_pplc_tx_buffer[4], 0, us_data_len);
			} else {
				memcpy(&gs_pplc_tx_buffer[4], ptr_data_buf, us_data_len);
			}

			/* Configure DMA channels */
			g_pplc_rx_packet.ul_addr = (uint32_t)gs_pplc_rx_buffer;
			g_pplc_rx_packet.ul_size = uc_num_tx_bytes;
			pdc_rx_init(g_pplc_pdc, &g_pplc_rx_packet, NULL);

			g_pplc_tx_packet.ul_addr = (uint32_t)gs_pplc_tx_buffer;
			g_pplc_tx_packet.ul_size = uc_num_tx_bytes;
			pdc_tx_init(g_pplc_pdc, &g_pplc_tx_packet, NULL);

			/* Enable the RX and TX PDC transfer requests */
			pdc_enable_transfer(g_pplc_pdc,
					PERIPH_PTCR_RXTEN | PERIPH_PTCR_TXTEN);

			/* Waiting transfer done*/
			while ((spi_read_status(PPLC_SPI_MODULE) &
					SPI_SR_RXBUFF) == 0) {
			}

			/* Disable the RX and TX PDC transfer requests */
			pdc_disable_transfer(g_pplc_pdc,
					PERIPH_PTCR_RXTDIS | PERIPH_PTCR_TXTDIS);

			/* copy rcv data */
			if (uc_cmd == PPLC_CMD_READ) {
				memcpy(ptr_data_buf, &gs_pplc_rx_buffer[4], us_data_len);
			}

			/* update buffer pointers */
			ptr_data_buf += us_data_len;
			us_address += us_data_len;
			/* update data length */
			us_data_len_acc += us_data_len;
			us_data_len = us_len - us_data_len_acc;
		}

		uc_pplc_is_busy = false;
		Enable_global_interrupt();
		return true;
	} else {
Beispiel #28
0
void initialise_board(void) {
		int i;
		central_data_t *central_data=central_data_get_pointer_to_struct();
		
		irq_initialize_vectors();
		cpu_irq_enable();
		Disable_global_interrupt();
			
		// Initialize the sleep manager
		sleepmgr_init();
		sysclk_init();
		INTC_init_interrupts();

		delay_init(sysclk_get_cpu_hz());
		time_keeper_init();
		
//		time_keeper_init_synchronisation();

		init_LEDs();
		switch_LED(1, LED_ON);
		switch_LED(0, LED_ON);

		pwm_servos_init(true);
		
		// set up UART for main telemetry
		uart_int_set_usart_conf(0, asv_xbee_uart_conf());
		uart_int_init(0);
		uart_int_register_write_stream(uart_int_get_uart_handle(0), &central_data->xbee_out_stream);
		
		//init_UART_DMA(0);
		//register_write_stream_dma(get_UART_handle(0), &central_data->xbee_out_stream);
		buffer_make_buffered_stream(&(central_data->xbee_in_buffer), &(central_data->xbee_in_stream));
		uart_int_register_read_stream(uart_int_get_uart_handle(0), &(central_data->xbee_in_stream));

		uart_int_set_usart_conf(4, asv_debug_uart_conf());
		uart_int_init(4);
		uart_int_register_write_stream(uart_int_get_uart_handle(4), &central_data->wired_out_stream);
		
		//init_UART_DMA(0);
		//register_write_stream_dma(get_UART_handle(0), &central_data->wired_out_stream);
		buffer_make_buffered_stream(&(central_data->wired_in_buffer), &(central_data->wired_in_stream));
		uart_int_register_read_stream(uart_int_get_uart_handle(4), &(central_data->wired_in_stream));

		// set up UART for GPS
		uart_int_set_usart_conf(3, asv_gps_uart_conf());
		uart_int_init(3);
		uart_int_register_write_stream(uart_int_get_uart_handle(3), &central_data->gps_out_stream);		
		buffer_make_buffered_stream(&(central_data->gps_in_buffer), &(central_data->gps_in_stream));
		uart_int_register_read_stream(uart_int_get_uart_handle(3), &(central_data->gps_in_stream));

		
		multistream_init(&central_data->multi_telemetry_down_stream);
		multistream_init(&central_data->multi_telemetry_up_stream);

		multistream_add_stream(&central_data->multi_telemetry_down_stream, &central_data->wired_out_stream);
		multistream_add_stream(&central_data->multi_telemetry_down_stream, &central_data->xbee_out_stream);

		multistream_add_stream(&central_data->multi_telemetry_up_stream, &central_data->wired_in_stream);
		multistream_add_stream(&central_data->multi_telemetry_up_stream, &central_data->xbee_in_stream);
		
		/*
		can_bus_init(1, asv_can1_conf());
		can_bus_register_write_stream(&central_data->ext_can_out_stream_data, &central_data->ext_can_out_stream, 1, MAVLINK_COMPONENT_ID, 0x3ff);
		can_bus_register_read_stream(&central_data->ext_can_in_stream_data, &central_data->ext_can_in_stream, 1, MAVLINK_COMPONENT_ID, 0x00);
		*/
		
		// set telemetry stream for mavlink
		//central_data->telemetry_down_stream=&(central_data->xbee_out_stream);
		//central_data->telemetry_up_stream  =&(central_data->xbee_in_stream);
		//central_data->telemetry_down_stream=&(central_data->wired_out_stream);
		//central_data->telemetry_up_stream  =&(central_data->wired_in_stream);
		central_data->telemetry_down_stream= multistream_get_stream(&central_data->multi_telemetry_down_stream);
		central_data->telemetry_up_stream  = multistream_get_stream(&central_data->multi_telemetry_up_stream);
		
		central_data->debug_out_stream=&central_data->wired_out_stream;
		central_data->debug_in_stream=&central_data->wired_in_stream;
		//central_data->debug_out_stream = &central_data->xbee_out_stream;
		//central_data->debug_in_stream  = &central_data->xbee_in_stream;
		
		print_util_dbg_print_init(central_data->debug_out_stream);

		// init error handler as plain text until mavlink is configured
		error_handler_init_plaintext(central_data->debug_out_stream);

		// init mavlink
		// Init mavlink communication
		mavlink_communication_conf_t mavlink_config = 
		{	
			.scheduler_config =
			{
				.max_task_count = 30,
				.schedule_strategy = ROUND_ROBIN,
				.debug = true
			},
			.mavlink_stream_config = 
			{
				.rx_stream   = central_data->telemetry_up_stream,
				.tx_stream   = central_data->telemetry_down_stream,
				.sysid       = MAVLINK_SYS_ID,
				.compid      = MAVLINK_COMPONENT_ID,
				.use_dma     = false
			},
			.message_handler_config = 
int main(void)
{



	//-------------------------USART INTERRUPT REGISTRATION.------------//
	// Set Clock: Oscillator needs to initialized once: First
		 pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);

		 // --------------		USART INIT		-----------------------------------------------
		 static const gpio_map_t USART_GPIO_MAP =
		  {
			{AVR32_USART0_RXD_0_0_PIN, AVR32_USART0_RXD_0_0_FUNCTION},
			{AVR32_USART0_TXD_0_0_PIN, AVR32_USART0_TXD_0_0_FUNCTION}
		  };

		  // USART options.
		  static const usart_options_t USART_OPTIONS =
		  {
			.baudrate     = USART_BAUDRATE,
			.charlength   = 8,
			.paritytype   = USART_NO_PARITY,
			.stopbits     = USART_1_STOPBIT,
			.channelmode  = USART_NORMAL_CHMODE
		  };

		// Assign GPIO to USART
		gpio_enable_module(USART_GPIO_MAP, sizeof(USART_GPIO_MAP) / sizeof(USART_GPIO_MAP[0]));

		// Init USART
		usart_init_rs232(USART_0, &USART_OPTIONS, FOSC0);

		Disable_global_interrupt();
		INTC_init_interrupts();			// Init Interrupt Table: Once at first

		// Register USART Interrupt (hinzufügen)
		INTC_register_interrupt(&usart_int_handler, AVR32_USART0_IRQ, AVR32_INTC_INT0);

		USART_0->ier = AVR32_USART_IER_RXRDY_MASK; // Activate ISR on RX Line
		Enable_global_interrupt();
	// -----------------------------------------------------------------------------------

		// --------------------------		Display INIT		----------------------------------
			// Map SPI Pins
			static const gpio_map_t DIP204_SPI_GPIO_MAP =
			  {
				{DIP204_SPI_SCK_PIN,  DIP204_SPI_SCK_FUNCTION },  // SPI Clock.
				{DIP204_SPI_MISO_PIN, DIP204_SPI_MISO_FUNCTION},  // MISO.
				{DIP204_SPI_MOSI_PIN, DIP204_SPI_MOSI_FUNCTION},  // MOSI.
				{DIP204_SPI_NPCS_PIN, DIP204_SPI_NPCS_FUNCTION}   // Chip Select NPCS.
			  };

			// add the spi options driver structure for the LCD DIP204
			  spi_options_t spiOptions =
			  {
				.reg          = DIP204_SPI_NPCS,
				.baudrate     = 1000000,
				.bits         = 8,
				.spck_delay   = 0,
				.trans_delay  = 0,
				.stay_act     = 1,
				.spi_mode     = 0,
				.modfdis      = 1
			  };


			// SPI Inits: Assign I/Os to SPI
			gpio_enable_module(DIP204_SPI_GPIO_MAP,
			                     sizeof(DIP204_SPI_GPIO_MAP) / sizeof(DIP204_SPI_GPIO_MAP[0]));

			// Initialize as master
			spi_initMaster(DIP204_SPI, &spiOptions);

			// Set selection mode: variable_ps, pcs_decode, delay
			spi_selectionMode(DIP204_SPI, 0, 0, 0);

			// Enable SPI
			spi_enable(DIP204_SPI);

			// setup chip registers
			spi_setupChipReg(DIP204_SPI, &spiOptions, FOSC0);

			// initialize delay driver: Muss vor dip204_init() ausgeführt werden
			delay_init( FOSC0 );

			// initialize LCD
			dip204_init(backlight_PWM, TRUE);
			// ---------------------------------------------------------------------------------------

			// -----------------			Timer Counter Init		---------------------------------
				// Timer Configs:  Options for waveform generation.
				static const tc_waveform_opt_t WAVEFORM_OPT =
				{
				.channel  = TC_CHANNEL,                        // Channel selection.

				.bswtrg   = TC_EVT_EFFECT_NOOP,                // Software trigger effect on TIOB.
				.beevt    = TC_EVT_EFFECT_NOOP,                // External event effect on TIOB.
				.bcpc     = TC_EVT_EFFECT_NOOP,                // RC compare effect on TIOB.
				.bcpb     = TC_EVT_EFFECT_NOOP,                // RB compare effect on TIOB.

				.aswtrg   = TC_EVT_EFFECT_NOOP,                // Software trigger effect on TIOA.
				.aeevt    = TC_EVT_EFFECT_NOOP,                // External event effect on TIOA.
				.acpc     = TC_EVT_EFFECT_NOOP,                // RC compare effect on TIOA: toggle.
				.acpa     = TC_EVT_EFFECT_NOOP,                // RA compare effect on TIOA: toggle

				.wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,//  Count till RC and reset (S. 649): Waveform selection
				.enetrg   = FALSE,                             // External event trigger enable.
				.eevt     = 0,                                 // External event selection.
				.eevtedg  = TC_SEL_NO_EDGE,                    // External event edge selection.
				.cpcdis   = FALSE,                             // Counter disable when RC compare.
				.cpcstop  = FALSE,                             // Counter clock stopped with RC compare.

				.burst    = FALSE,                             // Burst signal selection.
				.clki     = FALSE,                             // Clock inversion.
				.tcclks   = TC_CLOCK_SOURCE_TC3                // Internal source clock 3, connected to fPBA / 8.
				};


				// TC Interrupt Enable Register
				static const tc_interrupt_t TC_INTERRUPT =
				{ .etrgs = 0, .ldrbs = 0, .ldras = 0, .cpcs  = 1, .cpbs  = 0, .cpas  = 0, .lovrs = 0, .covfs = 0
				};
				// 0 = No Effect | 1 = Enable ( CPCS = 1 enables the RC Compare Interrupt )

				// *****************   Timer Setup ***********************************************
				// Initialize the timer/counter.
				tc_init_waveform(tc, &WAVEFORM_OPT);         // Initialize the timer/counter waveform.

				// Set the compare triggers.
				tc_write_rc(tc, TC_CHANNEL, RC); // Set RC value.

				tc_configure_interrupts(tc, TC_CHANNEL, &TC_INTERRUPT);

				// Start the timer/counter.
				tc_start(tc, TC_CHANNEL);                    // And start the timer/counter.
				// *******************************************************************************

				Disable_global_interrupt();
				// Register TC Interrupt
				INTC_register_interrupt(&tc_irq, AVR32_TC_IRQ0, AVR32_INTC_INT3);

				Enable_global_interrupt();
				// ---------------------------------------------------------------------------------------



				imu_init();

//-------------------------------TWI R/W ---------------------------------------------------



  sensorDaten imu_data = {0};
  char disp1[30], disp2[30], disp3[30], disp4[30];
  short GX,GY,GZ, AX, AY, AZ;			//shifted comlete Data
  RPY currMoveRPY;
  Quaternion currQuat;
  currQuat.q0 = 1.0;
  currQuat.q1 = 0;
  currQuat.q2 = 0;
  currQuat.q3 = 0;
  Quaternion deltaQuat;
  RotMatrix rot = {0};
  RPY reconverted;


  calibrate_all(&imu_data);


  while(1){
	  if(exe){
		  exe = false;
		  read_sensor(&imu_data);




		  AX = imu_data.acc_x + imu_data.acc_x_bias;
		  AY = imu_data.acc_y + imu_data.acc_y_bias;
		  AZ = imu_data.acc_z + imu_data.acc_z_bias;

		  GX = imu_data.gyro_x + imu_data.gyro_x_bias;
		  GY = imu_data.gyro_y + imu_data.gyro_y_bias;
		  GZ = imu_data.gyro_z + imu_data.gyro_z_bias;




		  //convert to 1G
		  float ax = (float)AX * (-4.0);
		  float ay = (float)AY * (-4.0); //wegen 2^11= 2048, /2 = 1024 entspricht 4G -> 1G = (1024/4)
		  float az = (float)AZ * (-4.0);


		  //convert to 1°/s
		  gx = ((float)GX/ 14.375); // in °/s
		  gy = ((float)GY/ 14.375);
		  gz = ((float)GZ/ 14.375);

		  //Integration over time
		  dGx = (gx*0.03);
		  dGy = (gy*0.03);
		  dGz = (gz*0.03);

		  currMoveRPY.pitch = -dGx;
		  currMoveRPY.roll = dGy;
		  currMoveRPY.yaw = dGz;


		  //aufaddieren auf den aktuellen Winkel IN GRAD
			gxDeg += dGx;
			gyDeg += dGy;
			gzDeg += dGz;


			//RPY in Quaternion umwandeln
			RPYtoQuat(&deltaQuat, &currMoveRPY);


			//normieren
			normQuat(&deltaQuat);


			//aufmultiplizeiren
			quatMultiplication(&deltaQuat, &currQuat, &currQuat);



			//nochmal normieren
			normQuat(&currQuat);

			//rücktransformation nicht nötig!!


			char send[80];
			sprintf(send,"$,%f,%f,%f,%f,#", currQuat.q0, currQuat.q1, currQuat.q2, currQuat.q3);
		 	usart_write_line(USART_0,send);



		   sprintf(disp1,"q0:%.3f, GX:%3.0f",currQuat.q0,gxDeg);
		   sprintf(disp2,"q1:%.3f, GY:%3.0f",currQuat.q1, gyDeg);
		   sprintf(disp3,"q2:%.3f, GZ:%3.0f",currQuat.q2, gzDeg);
		   sprintf(disp4,"q3:%.3f",currQuat.q3);



		   dip204_clear_display();

		   dip204_set_cursor_position(1,1);
		   dip204_write_string(disp1);
		   dip204_set_cursor_position(1,2);
		   dip204_write_string(disp2);
		   dip204_set_cursor_position(1,3);
		   dip204_write_string(disp3);
		   dip204_set_cursor_position(1,4);
		   dip204_write_string(disp4);











			//sprintf(data,"TEST:%s",high);
		   //print_dbg(data);
	  }

  }
}
Beispiel #30
0
/**
 ** PDCA Init.
 **/
void init_pdca(void)
{
  // PDCA channel 0/1 options
  static const pdca_channel_options_t PDCA_CH_OPTIONS =
  {
    .addr = (void *)aDataTransfered,          // memory address
    .pid = AVR32_PDCA_PID_USART2_TX,          // select peripheral - data are transmit on USART TX line.
    .size = 0,                                // transfer counter
    .r_addr = (void *)aDataTransfered,        // next memory address
    .r_size = sizeof(aDataTransfered),        // next transfer counter
    .transfer_size = PDCA_TRANSFER_SIZE_BYTE, // select size of one data packet
    .etrig = true                          // Trigger transfer on event.
  };

  Disable_global_interrupt();

  // Initialize interrupt vectors.
  INTC_init_interrupts();

  // Register the PDCA interrupt handler to the interrupt controller.
  INTC_register_interrupt(&pdca_int_handler, PDCA_CHANNEL_IRQ, AVR32_INTC_INT0);

  Enable_global_interrupt();

  // Init PDCA channel with the pdca_options.
  pdca_init_channel(PDCA_CHANNEL_USART, &PDCA_CH_OPTIONS);
  pdca_channel = pdca_get_handler(PDCA_CHANNEL_USART); // For use in the pdca interrupt handler.

  // Enable pdca transfer error interrupt & transfer complete interrupt.
  pdca_enable_interrupt_transfer_error(PDCA_CHANNEL_USART);
  pdca_enable_interrupt_transfer_complete(PDCA_CHANNEL_USART);

  // Enable the PEVC channel "PDCA CHANNEL 0/1 ONE-ITEM-TRANSFER"
  PEVC_CHANNELS_ENABLE(ppevc, 1<<PEVC_PDCA_SOT_USER);

  // Enable the PDCA.
  pdca_enable(PDCA_CHANNEL_USART);
}

/**
 ** AST Init.
 **/
void init_ast(void)
{

  avr32_ast_pir0_t pir = {
    .insel = 14 // Set a event every second
  };

  ast_calendar_t ast_calendar;
  ast_calendar.FIELD.sec  = 30;
  ast_calendar.FIELD.min  = 45;
  ast_calendar.FIELD.hour = 12;
  ast_calendar.FIELD.day  = 7;
  ast_calendar.FIELD.month= 10;
  ast_calendar.FIELD.year = 9;

  scif_osc32_opt_t opt;
  opt.mode = SCIF_OSC_MODE_2PIN_CRYSTAL;
  opt.startup = AVR32_SCIF_OSCCTRL32_STARTUP_0_RCOSC;

  // Start OSC_32KHZ
  scif_start_osc32(&opt,true);

  // Initialize the AST
  if (!ast_init_calendar(&AVR32_AST, AST_OSC_32KHZ, AST_PSEL_32KHZ_1HZ, ast_calendar))
  {
    print_dbg("Error initializing the AST\r\n");
    while(1);
  }

  ast_set_periodic0_value(&AVR32_AST,pir);

  ast_enable_periodic0(&AVR32_AST);

  // Clear All Interrupt
  AVR32_AST.scr=0xFFFFFFFF;

  // Enable the AST
  ast_enable(&AVR32_AST);
}

/*! \brief Initializes the MCU system clocks.
*/
static void init_sys_clocks(void)
{

  /*! \name System Clock Frequencies
   */
  //! @{
  static pcl_freq_param_t pcl_freq_param =
  {
    .cpu_f        = FCPU_HZ,
    .pba_f        = FPBA_HZ,
    .osc0_f       = FOSC0,
    .osc0_startup = OSC0_STARTUP
  };
  //! @}

  // Configure system clocks.
  if (pcl_configure_clocks(&pcl_freq_param) != PASS) {
    while(1);
  }
}

/*! \brief This example show a DMA transfer to USART controlled by the AST
    periodic alarm using the PEVC.
 */
int main(void)
{
  int i;

  // Init the string with a simple recognizable pattern.
  for(i=0;i<sizeof(aDataTransfered);i++)
    aDataTransfered[i] = '0' + (i%36);

  init_sys_clocks();

  init_usart();

  gpio_clr_gpio_pin(LED0_GPIO);

  init_pevc();

  init_ast();

  init_pdca();

  while(1)
  {
    gpio_tgl_gpio_pin(LED1_GPIO);
    delay_ms(500); //Wait 500ms
  }
}