Exemple #1
0
/*! \brief Main function. Execution starts here.
 *
 * \retval 42 Fatal error.
 */
int main(void)
{
  // Configure system clocks.
  if (pcl_configure_clocks(&pcl_freq_param) != PASS)
    return 42;

  // Initialize USB clock (on PLL1)
  pcl_configure_usb_clock();

  // Initialize usart comm
  init_dbg_rs232(pcl_freq_param.pba_f);

  // Initialize USB task
  usb_task_init();

#if USB_DEVICE_FEATURE == true
  // Initialize device generic USB task
  device_generic_hid_task_init();
#endif

  // No OS here. Need to call each task in round-robin mode.
  while (true)
  {
    usb_task();
  #if USB_DEVICE_FEATURE == true
    device_generic_hid_task();
  #endif
  }

}
Exemple #2
0
/*! \brief Main function. Execution starts here.
 *
 * \retval No return value.
 */
int main(void)
{
#ifdef __GNUC__
	// Initialize the INTC sw driver.
	INTC_init_interrupts();
#endif

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

	// Initialize USB clock (on PLL1)
	pcl_configure_usb_clock();

	// Initialize USB task
	usb_task_init();

#if USB_DEVICE_FEATURE == true
	// Initialize device generic USB task
	device_generic_hid_task_init();
#endif

	// No OS here. Need to call each task in round-robin mode.
	while (true) {
		usb_task();
	#if USB_DEVICE_FEATURE == true
		device_generic_hid_task();
	#endif
	}
}
Exemple #3
0
//!
//! \fn     main
//! \brief  start the software here
//!         1) Initialize the microcontroller and the shared hardware resources
//!         of the board.
//!         2) Launch the IP modules.
//!         3) Start FreeRTOS.
//! \return 42, which should never occur.
//! \note
//!
int main( void )
{
        static pcl_freq_param_t pcl_freq_param =
        {
          .cpu_f        = configCPU_CLOCK_HZ,
          .pba_f        = configPBA_CLOCK_HZ,
          .osc0_f       = FOSC0,
          .osc0_startup = OSC0_STARTUP
        };

        // Configure system clock
        if (pcl_configure_clocks(&pcl_freq_param) != PASS)
          return 42;

	/* Setup the LED's for output. */
	vParTestInitialise();

	/* Start the flash tasks just to provide visual feedback that the demo is
	executing. */
	vStartLEDFlashTasks( mainLED_TASK_PRIORITY );

	/* 2) Start the ethernet tasks launcher. */
	vStartEthernetTaskLauncher( configMAX_PRIORITIES );

	/* 3) Start FreeRTOS. */
	vTaskStartScheduler();

	/* Will only reach here if there was insufficient memory to create the idle task. */

	return 0;
}
Exemple #4
0
/*! \brief Main function. Execution starts here.
 *
 * \retval 42 Fatal error.
 */
int main(void)
{
  // Configure system clocks.
  if (pcl_configure_clocks(&pcl_freq_param) != PASS)
    return 42;

  // Initialize USB clock (on PLL1)
  pcl_configure_usb_clock();

  // Initialize usart comm
  init_dbg_rs232(pcl_freq_param.pba_f);

#if BOARD == EVK1105
  Disable_global_interrupt();
  /* 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);
  /* all gpios between PB23 - PB31) */
  INTC_register_interrupt(&touch_button_isr, AVR32_GPIO_IRQ_7, 0);
  Enable_global_interrupt();
#endif

  // Initialize USB task
  usb_task_init();

#if USB_DEVICE_FEATURE == true
  // Initialize device mouse USB task
  device_mouse_hid_task_init();
#endif
#if USB_HOST_FEATURE == true
  //host_keyboard_hid_task_init();

  // Initialize host mouse USB task
  host_mouse_hid_task_init();
#endif

#ifdef FREERTOS_USED
  // Start OS scheduler
  vTaskStartScheduler();
  portDBG_TRACE("FreeRTOS returned.");
  return 42;
#else
  // No OS here. Need to call each task in round-robin mode.
  while (true)
  {
    usb_task();
  #if USB_DEVICE_FEATURE == true
    device_mouse_hid_task();
  #endif
  #if USB_HOST_FEATURE == true
    //host_keyboard_hid_task();
    host_mouse_hid_task();
  #endif
  }
#endif  // FREERTOS_USED
}
/*! \brief Initialize Clock.
 */
static unsigned long
init_clock (void)
{
  unsigned long ret_val = 0u;

  /*Configure the DFLL and switch the main clock source to the DFLL. */
  ret_val |= pcl_configure_clocks (&pcl_dfll_freq_param);

  return (ret_val);
}
Exemple #6
0
static void init_sys_clocks(void)
{
	pcl_freq_param.cpu_f        = FCPU_HZ;
	pcl_freq_param.pba_f        = FPBA_HZ;
	pcl_freq_param.osc0_f       = FOSC0;
	pcl_freq_param.osc0_startup = OSC0_STARTUP;
	// Configure system clocks.
	if (pcl_configure_clocks(&pcl_freq_param) != PASS)
	while(1);
}
Exemple #7
0
/*! \brief Main function running the example on both the flash array and the
 *         User page.
 */
int main(void)
{
#if 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.
#else
	// 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);
#endif

	// Initialize the debug USART module.
	init_dbg_rs232(EXAMPLE_TARGET_PBACLK_FREQ_HZ);

	// Apply the example to the flash array.
	flash_rw_example("\x0C=== Using a piece of the flash array as NVRAM ===\r\n",
			&flash_nvram_data);

	// Apply the example to the User page.
	flash_rw_example("\r\n\r\n=== Using a piece of the User page as NVRAM ===\r\n",
			&user_nvram_data);

	//*** Sleep mode
	// This program won't be doing anything else from now on, so it might as well
	// sleep.
	// Modules communicating with external circuits should normally be disabled
	// before entering a sleep mode that will stop the module operation.
	// For this application, we must disable the USART module that the DEBUG
	// software module is using.
	pcl_disable_module(DBG_USART_CLOCK_MASK);

	// Since we're going into a sleep mode deeper than IDLE, all HSB masters must
	// be stopped before entering the sleep mode.
	pcl_disable_module(AVR32_PDCA_CLK_HSB);
	pcl_disable_module(AVR32_PDCA_CLK_PBA);

	// 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 STATIC sleep mode.
	SLEEP(AVR32_PM_SMODE_STATIC);

	while (true);
}
Exemple #8
0
static unsigned long init_clock( unsigned long cpuclk_hz )
{
  unsigned long ret_val = 0u;

  // Program the DFLL and switch the main clock source to the DFLL.
  pcl_configure_clocks(&pcl_dfll_freq_param);

#if DEF_TOUCH_QMATRIX == 1
  /* Set up the GCLK_CAT for proper QMatrix operation.  The GCLK_CAT is not
     required to be setup for Autonomous Touch and QTouch Group A/B operation.
     Note: for UC3L devices, the generic clock configurations are handled by the
     SCIF module. Setup gc to use the DFLL0 as source clock, divisor enabled, apply
     a division factor. */
  ret_val |= scif_gc_setup(AVR32_SCIF_GCLK_CAT, SCIF_GCCTRL_DFLL0, AVR32_GC_DIV_CLOCK, QM_GCLK_CAT_DIV);

  /* Now enable the generic clock */
  ret_val |= scif_gc_enable(AVR32_SCIF_GCLK_CAT);
#endif

  return (ret_val);
}
Exemple #9
0
extern void mcu_init_clocks()
	{
	/* Set reguired changes for flash wait state and readmode */
	flashcdw_set_flash_waitstate_and_readmode(MCU_CPU_F);
		
	/* We will use Atmels power_clocks_lib to configure clocks in MCU. This library supports
	 * high level of abstraction over settings. */
	static scif_gclk_opt_t gc_dfllif_ref_opt = { SCIF_GCCTRL_SLOWCLOCK, 0, false };
	static pcl_freq_param_t pcl_dfll_freq_param =
		{
		.main_clk_src = PCL_MC_DFLL0,
		.cpu_f        = MCU_CPU_F,
		.pba_f        = MCU_PBA_F,
		.pbb_f        = MCU_PBB_F,
		.dfll_f       = MCU_DFLL_F,
		.pextra_params = &gc_dfllif_ref_opt
		};

	/* Configure core clocks (MCU, PBA, PBB, DFFL */
	pcl_configure_clocks(&pcl_dfll_freq_param);
	}
Exemple #10
0
void init()
{
	// board init
	board_init();
	
#if UC3L
	// clock frequencies
	#define EXAMPLE_TARGET_DFLL_FREQ_HZ     96000000  // DFLL target frequency, in Hz
	#define EXAMPLE_TARGET_MCUCLK_FREQ_HZ   12000000  // MCU clock target frequency, in Hz
	#define EXAMPLE_TARGET_PBACLK_FREQ_HZ   12000000  // PBA clock target frequency, in Hz

	// parameters to pcl_configure_clocks().
	static scif_gclk_opt_t gc_dfllif_ref_opt = { SCIF_GCCTRL_SLOWCLOCK, 0, false};
	static pcl_freq_param_t pcl_dfll_freq_param = {
		.main_clk_src = PCL_MC_DFLL0,
		.cpu_f        = EXAMPLE_TARGET_MCUCLK_FREQ_HZ,
		.pba_f        = EXAMPLE_TARGET_PBACLK_FREQ_HZ,
		.pbb_f        = EXAMPLE_TARGET_PBACLK_FREQ_HZ,
		.dfll_f       = EXAMPLE_TARGET_DFLL_FREQ_HZ,
		.pextra_params = &gc_dfllif_ref_opt
	};
	pcl_configure_clocks(&pcl_dfll_freq_param);
#else
	pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);
#endif	
	
	// stdio init
	stdio_usb_init(&CONFIG_USART_IF);

	// Specify that stdout and stdin should not be buffered.

#if defined(__GNUC__) && defined(__AVR32__)
	setbuf(stdout, NULL);
	setbuf(stdin,  NULL);
#endif
}
Exemple #11
0
//! @{
static void init_sys_clocks (void)
{
	if (pcl_configure_clocks (&pcl_freq_param) != PASS) {
		while (1);
	}
}
Exemple #12
0
/*! \brief Main function. Execution starts here.
 *
 * \retval 42 Fatal error.
 */
int main(void)
{
  // Configure system clocks.
  if (pcl_configure_clocks(&pcl_freq_param) != PASS)
    return 42;

  // Initialize usart comm
  init_dbg_rs232(pcl_freq_param.pba_f);

#ifndef FREERTOS_USED
# if (defined __GNUC__)
  // Give the used CPU clock frequency to Newlib, so it can work properly.
  set_cpu_hz(pcl_freq_param.pba_f);
# endif
#endif

  // Initialize USB clock.
  pcl_configure_usb_clock();

  // Initialize USB task
  usb_task_init();

  // Display a welcome banner on USART
  printf("                                                       ......       ......     \r\n");
  printf("       IIIIII  IIIII        IIII   IIIIIIIIIII      IIIIIIIIIII. .IIIIIIIIII.  \r\n");
  printf("      IIIIIII   IIIII      IIIII  IIIIIIIIIIIII     IIIIIIIIIIII..IIIIIIIIIII. \r\n");
  printf("     IIIIIIIII  IIIII     IIIII   IIIII   IIIII     I.      IIIII.:.     IIIII \r\n");
  printf("     IIII IIIII  IIIII    IIII   IIIII    IIIII            .IIII.        IIIII \r\n");
  printf("    IIIII  IIII   IIII   IIIII  IIIIIIIIIIIIII         IIIIIIII          IIII. \r\n");
  printf("    IIII   IIIII  IIIII IIIII   IIIIIIIIIIIII          IIIIIIII.       .IIII:  \r\n");
  printf("   IIIII    IIIII  IIIIIIIII   IIIIIIIIIII                 .IIIII     IIIII.   \r\n");
  printf("  IIIIIIIIIIIIIII   IIIIIIII   IIIII IIIII                  .IIII   .IIII:     \r\n");
  printf("  IIIIIIIIIIIIIIII  IIIIIII   IIIII   IIII         II:.    .IIIII .IIIII.      \r\n");
  printf(" IIIII        IIIII  IIIIII  IIIII    IIIII        IIIIIIIIIIIII.IIIIIIIIIIIIII\r\n");
  printf(" IIIII        IIIII  IIIII   IIIII    IIIII        :IIIIIIIIII.  IIIIIIIIIIIIII\r\n");
  printf("                      III                                                      \r\n");
  printf("                       II                                                      \r\n");

#if USB_DEVICE_FEATURE == true
  // Initialize device CDC USB task
  device_cdc_task_init();
#endif
#if USB_HOST_FEATURE == true
  // Initialize host CDC USB task
  host_cdc_task_init();
#endif

#ifdef FREERTOS_USED
  // Start OS scheduler
  vTaskStartScheduler();
  portDBG_TRACE("FreeRTOS returned.");
  return 42;
#else
  // No OS here. Need to call each task in round-robin mode.
  while (true)
  {
    usb_task();
  #if USB_DEVICE_FEATURE == true
    device_cdc_task();
  #endif
  #if USB_HOST_FEATURE == true
    host_cdc_task();
  #endif
  }
#endif  // FREERTOS_USED
}
Exemple #13
0
int main( void )
{
#if UC3L
	/*! \name Clock frequencies
	 */
	//! @{
	#define EXAMPLE_TARGET_DFLL_FREQ_HZ     96000000  // DFLL target frequency, in Hz
	#define EXAMPLE_TARGET_MCUCLK_FREQ_HZ   12000000  // MCU clock target frequency, in Hz
	#define EXAMPLE_TARGET_PBACLK_FREQ_HZ   12000000  // PBA clock target frequency, in Hz
	//! @}

	/*! \name Parameters to pcl_configure_clocks().
	 */
	//! @{
	static scif_gclk_opt_t gc_dfllif_ref_opt = { SCIF_GCCTRL_SLOWCLOCK, 0, false};
	static pcl_freq_param_t pcl_dfll_freq_param = {
		.main_clk_src = PCL_MC_DFLL0,
		.cpu_f        = EXAMPLE_TARGET_MCUCLK_FREQ_HZ,
		.pba_f        = EXAMPLE_TARGET_PBACLK_FREQ_HZ,
		.pbb_f        = EXAMPLE_TARGET_PBACLK_FREQ_HZ,
		.dfll_f       = EXAMPLE_TARGET_DFLL_FREQ_HZ,
		.pextra_params = &gc_dfllif_ref_opt
	};
	//! @}

	// Note: on the AT32UC3L-EK and UC3-L0-Xplained board, there are 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.

#else
	// 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);
#endif

	portDBG_TRACE("Starting the FreeRTOS AVR32 UC3 Demo...");

	/* Setup the LED's for output. */
	vParTestInitialise();

	/* Start the standard demo tasks.  See the WEB documentation for more
	information.
	Note that the UC3L and UC3B parts do not have enough internal RAM to launch all the tasks of this example.
	That's why some of them are commented out using respectively #if (BOARD != UC3L_EK) or #if (BOARD != EVK1101)
	compiler directives. */
	vStartLEDFlashTasks( mainLED_TASK_PRIORITY );
	vAltStartComTestTasks( mainCOM_TEST_PRIORITY, mainCOM_TEST_BAUD_RATE, mainCOM_TEST_LED );
	vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY );
	#if (BOARD != UC3L_EK)
		vStartIntegerMathTasks( tskIDLE_PRIORITY );
		vStartSemaphoreTasks( mainSEM_TEST_PRIORITY );
		vStartDynamicPriorityTasks();
	#endif

	#if (BOARD != EVK1101) && (BOARD != UC3L_EK)
		vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY );
		vStartMathTasks( tskIDLE_PRIORITY );
	#endif

	/* Start the demo tasks defined within this file, specifically the check
	task as described at the top of this file. */
	xTaskCreate(
		vErrorChecks
		,  (const signed portCHAR *)"ErrCheck"
		,  configMINIMAL_STACK_SIZE
		,  NULL
		,  mainCHECK_TASK_PRIORITY
		,  NULL );

	/* Start the scheduler. */
	vTaskStartScheduler();

	/* Will only get here if there was insufficient memory to create the idle
	task. */

	return 0;
}
int main (void)
{
    pcl_freq_param_t local_pcl_freq_param;

    /*
       USART_Int_Test ();

       return (0); */

    // Configure system clocks.
    local_pcl_freq_param = pcl_freq_param;

    if (pcl_configure_clocks (&local_pcl_freq_param) != PASS)
    {
        return 42;
    }

    /* Load the Exception Vector Base Address in the corresponding system register. */
    Set_system_register (AVR32_EVBA, (int) &_evba);

    /* Enable exceptions. */
    ENABLE_ALL_EXCEPTIONS ();

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

#if ((defined SD_MMC_MCI_0_MEM) && (SD_MMC_MCI_0_MEM == ENABLE)) || ((defined SD_MMC_MCI_1_MEM) && (SD_MMC_MCI_1_MEM == ENABLE))
    sd_mmc_mci_resources_init ();
#endif


#ifdef FREERTOS_USED
    if (!ctrl_access_init ())
    {
        return 42;
    }
#endif // FREERTOS_USED

    // Init Hmatrix bus
    init_hmatrix ();

    // Initialize USB clock.
    pcl_configure_usb_clock ();

    /*
       SmartCard_test (); return 42;

       Test_ALL_Pins ();

       Test_MCI_Pins ();

       Test_LEDs_Pins ();

       TestUart0 ();

       while (1); return (0); */

#ifdef TIME_MEASURING_ENABLE
    TIME_MEASURING_Init ();
#endif


    // For debugging
    BUFFERED_SIO_Init ();

#ifdef INTERPRETER_ENABLE
    IDF_task_init ();
#endif

    // Internal work task - FAT Access
    IW_task_init ();

    // Initialize USB tasks.
    usb_task_init ();




#if USB_DEVICE_FEATURE == ENABLED
#ifdef  USB_MSD
    device_mass_storage_task_init ();
#endif // USB_MSD
#endif


    // CCID_Test_task_init ();
#ifdef  USB_CCID
    USB_CCID_task_init ();
#endif

    DFU_DisableFirmwareUpdate ();   // Stick always starts in application mode

     /**/
        // Protect bootloader
#ifdef STICK_20_A_MUSTER_PROD   //
        flashc_set_bootloader_protected_size (0x2000);
//        flashc_activate_security_bit ();    // Debugging disabled, only chip erase works (bootloader is save) , AES storage keys and setup
                                        // are erased
        flashc_lock_external_privileged_fetch (TRUE);     // Disable external instruction fetch
#endif

    // DFU_FirmwareResetUserpage ();


    // Set BOD33 detection reset to 3.06 Volt
    pm_bod33_ResetDisable ();
    pm_bod33_set_level (AVR32_PM_BOD33_LEVEL_306_VOLT);
    pm_bod33_ResetEnable ();

    // ushell_task_init(pcl_freq_param.pba_f);


    // Create the semaphore
    vSemaphoreCreateBinary (AES_semphr);


    // Wait for the semaphore
    while (!xSemaphoreTake (AES_semphr, portMAX_DELAY));

    // Release the semaphore in order to start a new device/host task
    portBASE_TYPE task_woken = pdFALSE;
/*
    taskENTER_CRITICAL ();
    xSemaphoreGiveFromISR (AES_semphr, &task_woken);
    taskEXIT_CRITICAL ();
*/
    taskENTER_CRITICAL ();
    xSemaphoreGive (AES_semphr);
    taskEXIT_CRITICAL ();


    // Start stick
    vTaskStartScheduler ();

    // It never gets to this point
    return 42;
}
Exemple #15
0
static void tc_init_fast(volatile avr32_tc_t *tc)
{
	// Options for waveform generation.
	static const tc_waveform_opt_t waveform_opt_1 = {

		.channel  = FAST_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.
		.acpa     = TC_EVT_EFFECT_NOOP,	//RA compare effect on TIOA. 
		.wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,	//Waveform selection: Up mode with automatic trigger(reset)
		.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.
	};

	// Options for enabling TC interrupts
	static const tc_interrupt_t tc_interrupt = {
		.etrgs = 0,
		.ldrbs = 0,
		.ldras = 0,
		.cpcs  = 1, // Enable interrupt on RC compare alone
		.cpbs  = 0,
		.cpas  = 0,
		.lovrs = 0,
		.covfs = 0
	};
	// Initialize the timer/counter.
	tc_init_waveform(tc, &waveform_opt_1);

	tc_write_rc(tc, FAST_TC_CHANNEL, 10);
	// configure the timer interrupt
	tc_configure_interrupts(tc, FAST_TC_CHANNEL, &tc_interrupt);
}

static void tc_init_slow(volatile avr32_tc_t *tc)
{
	// Options for waveform generation.
	static const tc_waveform_opt_t waveform_opt_2 = {
		.channel  = SLOW_TC_fast_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_CLEAR,	// RC compare effect on TIOA.
		.acpa     = TC_EVT_EFFECT_SET,	// RA compare effect on TIOA. 
		.wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,	//Waveform selection: Up mode with automatic trigger(reset)
		.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.
	};

	// Initialize the timer/counter.
	tc_init_waveform(tc, &waveform_opt_2);
	tc_write_rc(tc, SLOW_TC_fast_CHANNEL, 7500); //counter will count milliseconds
	tc_write_ra(tc, SLOW_TC_fast_CHANNEL, 3500); //configure ra so that TIOA0 is toggled
	
	static const tc_waveform_opt_t waveform_opt_3 = {
		.channel  = SLOW_TC_slow_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.
		.acpa     = TC_EVT_EFFECT_NOOP,	//RA compare effect on TIOA. 
		.wavsel   = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER,	//Waveform selection: Up mode with automatic trigger(reset)
		.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_XC0	// Use XC1 as clock source.  Must configure TIOA0 to be XC1
	};
	
	tc_init_waveform(tc, &waveform_opt_3);
	tc_write_rc(tc, SLOW_TC_slow_CHANNEL, 100); //
	tc_select_external_clock(tc,SLOW_TC_slow_CHANNEL,AVR32_TC_BMR_TC0XC0S_TIOA1); //use TIOA1 as XC0
}


	static void configure_hmatrix(uint32_t mode)
{
	// Configure all Slave in Last Default Master
#if (defined AVR32_HMATRIX) 
	for(uint32_t i = 0; i < AVR32_HMATRIX_SLAVE_NUM; i++) {
		AVR32_HMATRIX.SCFG[i].defmstr_type = mode;
	}
#endif
#if (defined AVR32_HMATRIXB)
	for(uint32_t i = 0;i < AVR32_HMATRIXB_SLAVE_NUM; i++) {
		AVR32_HMATRIXB.SCFG[i].defmstr_type = mode;
	}
#endif 
}

void board_init(void)
{
	/* This function is meant to contain board-specific initialization code
	 * for, e.g., the I/O pins. The initialization can rely on application-
	 * specific board configuration, found in conf_board.h.
	 */
	gpio_local_init();
	
	static pcl_freq_param_t pcl_freq_param =
{
	.cpu_f        = CPU_SPEED,
	.pba_f        = PBA_SPEED,
	.osc0_f       = FOSC0,
	.osc0_startup = OSC0_STARTUP
};

	if (pcl_configure_clocks(&pcl_freq_param) != PASS)
	while (true);
	
	configure_hmatrix(AVR32_HMATRIXB_DEFMSTR_TYPE_NO_DEFAULT);
	
	AVR32_LowLevelInit();
	
	//configure all GPIO
	gpio_local_enable_pin_output_driver(ADC_CONV_pin);
	gpio_local_clr_gpio_pin(ADC_CONV_pin);
	gpio_local_enable_pin_output_driver(DDS_IOUD_pin);
	gpio_local_clr_gpio_pin(DDS_IOUD_pin);
	gpio_local_enable_pin_output_driver(DDS_RESET_pin);
	gpio_local_clr_gpio_pin(DDS_RESET_pin);
	gpio_local_enable_pin_output_driver(DDS_PDN_pin);
	gpio_local_set_gpio_pin(DDS_PDN_pin);
	
	gpio_local_enable_pin_output_driver(DDS_P0_pin);
	gpio_local_clr_gpio_pin(DDS_P0_pin);
	gpio_local_enable_pin_output_driver(DDS_P1_pin);
	gpio_local_clr_gpio_pin(DDS_P1_pin);
	gpio_local_enable_pin_output_driver(DDS_P2_pin);
	gpio_local_clr_gpio_pin(DDS_P2_pin);
	gpio_local_enable_pin_output_driver(DDS_P3_pin);
	gpio_local_clr_gpio_pin(DDS_P3_pin);
	
	gpio_local_enable_pin_output_driver(RXSW_pin);
	gpio_local_clr_gpio_pin(RXSW_pin);
	gpio_local_enable_pin_output_driver(TXSW_pin);
	gpio_local_clr_gpio_pin(TXSW_pin);
	gpio_local_enable_pin_output_driver(TPAbias_pin);
	gpio_local_clr_gpio_pin(TPAbias_pin);
	gpio_local_enable_pin_output_driver(GEN1_pin);
	gpio_local_clr_gpio_pin(GEN1_pin);
	gpio_local_enable_pin_output_driver(GEN2_pin);
	gpio_local_clr_gpio_pin(GEN2_pin);
	
	gpio_local_enable_pin_output_driver(PWM0_pin);
	gpio_local_clr_gpio_pin(PWM0_pin);
	
	gpio_local_disable_pin_output_driver(SD_detect_pin);
	
	//configure all peripheral IO
	
	static const gpio_map_t GCLK_GPIO_MAP =
	{
		{AVR32_SCIF_GCLK_0_1_PIN, AVR32_SCIF_GCLK_0_1_FUNCTION}
	};
	
	gpio_enable_module(GCLK_GPIO_MAP,
			sizeof(GCLK_GPIO_MAP) / sizeof(GCLK_GPIO_MAP[0]));
	
	genclk_enable_config(9, GENCLK_SRC_CLK_CPU, 2);
	
	static const gpio_map_t SPI_GPIO_MAP =
	{
		{SPI1_SCK_PIN, SPI1_SCK_FUNCTION},
		{SPI1_MOSI_PIN, SPI1_MOSI_FUNCTION},
		{SPI1_MISO_PIN, SPI1_MISO_FUNCTION},
		{SPI1_NPCS2_PIN, SPI1_NPCS2_FUNCTION}
	};
	
	gpio_enable_module(SPI_GPIO_MAP,
			sizeof(SPI_GPIO_MAP) / sizeof(SPI_GPIO_MAP[0]));


spi_options_t SPI1_OPTIONS_0 = 
{
  .reg			= 0,		//! The SPI channel to set up.
  .baudrate		= 30000000,	//! Preferred baudrate for the SPI.
  .bits			=16,	//! Number of bits in each character (8 to 16).
  .spck_delay	=0,	//! Delay before first clock pulse after selecting slave (in PBA clock periods). 
  .trans_delay	=0,	//! Delay between each transfer/character (in PBA clock periods).
  .stay_act		=0,	 //! Sets this chip to stay active after last transfer to it.
  .spi_mode		=1,	//! Which SPI mode to use when transmitting.
  .modfdis		=1	 //! Disables the mode fault detection.
};

spi_options_t SPI1_OPTIONS_3 = 
{
  .reg			= 3,		//! The SPI channel to set up.
  .baudrate		= 30000000,	//! Preferred baudrate for the SPI.
  .bits			=8,	//! Number of bits in each character (8 to 16).
  .spck_delay	=0,	//! Delay before first clock pulse after selecting slave (in PBA clock periods).
  .trans_delay	=0,	//! Delay between each transfer/character (in PBA clock periods).
  .stay_act		=1,	//! Sets this chip to stay active after last transfer to it.
  .spi_mode		=0,	//! Which SPI mode to use when transmitting.
  .modfdis		=1	//! Disables the mode fault detection.
};

	spi_initMaster(SPI1, &SPI1_OPTIONS_0); 
	spi_selectionMode(SPI1,1,0,0);
	spi_enable(SPI1);
	spi_setupChipReg(SPI1,&SPI1_OPTIONS_0,PBA_SPEED);
	spi_setupChipReg(SPI1,&SPI1_OPTIONS_3,PBA_SPEED);
	spi_selectChip(SPI1, 3);
	
	static const gpio_map_t USB_USART_GPIO_MAP =
	{
		{USB_USART_RX_PIN, USB_USART_RX_FUNCTION},
		{USB_USART_TX_PIN, USB_USART_TX_FUNCTION},
		{USB_USART_RTS_PIN, USB_USART_RTS_FUNCTION},
		{USB_USART_CTS_PIN, USB_USART_CTS_FUNCTION}
	};
	
	gpio_enable_module(USB_USART_GPIO_MAP,
			sizeof(USB_USART_GPIO_MAP) / sizeof(USB_USART_GPIO_MAP[0]));
			
	static const usart_options_t USB_USART_OPTIONS =
	{
		.baudrate     = 3000000,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = USART_NORMAL_CHMODE
	};
			
	usart_init_hw_handshaking(USB_USART, &USB_USART_OPTIONS, PBA_SPEED);
	
	static const gpio_map_t LCD_USART_GPIO_MAP =
	{
		{LCD_USART_RX_PIN, LCD_USART_RX_FUNCTION},
		{LCD_USART_TX_PIN, LCD_USART_TX_FUNCTION}
	};
	
	gpio_enable_module(LCD_USART_GPIO_MAP,
			sizeof(LCD_USART_GPIO_MAP) / sizeof(LCD_USART_GPIO_MAP[0]));
			
	static const usart_options_t LCD_USART_OPTIONS =
	{
		.baudrate     = 115200,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = USART_NORMAL_CHMODE
	};
			
	usart_init_rs232(LCD_USART, &LCD_USART_OPTIONS, PBA_SPEED);
	LCD_USART->cr|=AVR32_USART_CR_STTTO_MASK; //set timeout to stop until new character is received
	LCD_USART->rtor=230;	//set to timeout in 2ms
	
	
	my_pdca_init_channel(LCD_USART_RX_PDCA_CHANNEL, (uint32_t)(&LCD_USART_buffer),(uint32_t)(sizeof(LCD_USART_buffer)),LCD_USART_RX_PDCA_PID,0,0, PDCA_TRANSFER_SIZE_BYTE);
	pdca_disable(LCD_USART_RX_PDCA_CHANNEL);
	
	my_pdca_init_channel(USB_USART_RX_PDCA_CHANNEL, (uint32_t)(&host_USART_buffer),(uint32_t)(sizeof(host_USART_buffer)),USB_USART_RX_PDCA_PID,0,0, PDCA_TRANSFER_SIZE_BYTE);
	pdca_disable(USB_USART_RX_PDCA_CHANNEL);
	
	USB_USART->cr|=AVR32_USART_CR_STTTO_MASK; //set timeout to stop until new character is received
	USB_USART->rtor=15000;	//set to timeout in 1ms
	
	// GPIO pins used for SD/MMC interface
  static const gpio_map_t SD_MMC_SPI_GPIO_MAP =
  {
    {SPI0_SCK_PIN,  SPI0_SCK_FUNCTION },  // SPI Clock.
    {SPI0_MISO_PIN, SPI0_MISO_FUNCTION},  // MISO.
    {SPI0_MOSI_PIN, SPI0_MOSI_FUNCTION},  // MOSI.
    {SPI0_NPCS0_PIN, SPI0_NPCS0_FUNCTION}   // Chip Select NPCS.
  };

   //SPI options.
  spi_options_t SD_spiOptions =
  {
    .reg          = SD_MMC_SPI_NPCS,
    .baudrate     = SD_SPI_SPEED,  // Defined in conf_sd_mmc_spi.h.
    .bits         = 8,          // Defined in conf_sd_mmc_spi.h.
    .spck_delay   = 0,
    .trans_delay  = 0,
    .stay_act     = 1,
    .spi_mode     = 0,
    .modfdis      = 1
  };

  // Assign I/Os to SPI.
  gpio_enable_module(SD_MMC_SPI_GPIO_MAP,sizeof(SD_MMC_SPI_GPIO_MAP) / sizeof(SD_MMC_SPI_GPIO_MAP[0]));
  // Initialize as master.
  spi_initMaster(SPI0, &SD_spiOptions);
  // Set SPI selection mode: variable_ps, pcs_decode, delay.
  spi_selectionMode(SPI0, 0, 0, 0);
  // Enable SPI module.
  spi_enable(SPI0);
  // Initialize SD/MMC driver with SPI clock (PBA).
  sd_mmc_spi_init(SD_spiOptions, PBA_SPEED);
  
  tc_init_fast(FAST_TC);
  tc_init_slow(SLOW_TC);
  
  static const gpio_map_t DACIFB_GPIO_MAP =
  {
    {AVR32_DACREF_PIN,AVR32_DACREF_FUNCTION},
    {AVR32_ADCREFP_PIN,AVR32_ADCREFP_FUNCTION},
    {AVR32_ADCREFN_PIN,AVR32_ADCREFN_FUNCTION},
    {DAC0A_pin, DAC0A_FUNCTION},
	{DAC1A_pin, DAC1A_FUNCTION}
  };
  
  gpio_enable_module(DACIFB_GPIO_MAP, sizeof(DACIFB_GPIO_MAP) / sizeof(DACIFB_GPIO_MAP[0]));
  
  dacifb_opt_t dacifb_opt = {
    .reference                  = DACIFB_REFERENCE_EXT ,        // VDDANA Reference
    .channel_selection          = DACIFB_CHANNEL_SELECTION_A,     // Selection Channels A&B
    .low_power                  = false,                          // Low Power Mode
    .dual                       = false,                          // Dual Mode
    .prescaler_clock_hz         = DAC_PRESCALER_CLK     // Prescaler Clock (Should be 500Khz)
};

// DAC Channel Configuration
dacifb_channel_opt_t dacifb_channel_opt = {
    .auto_refresh_mode    = true,                      // Auto Refresh Mode
    .trigger_mode         = DACIFB_TRIGGER_MODE_MANUAL, // Trigger selection
    .left_adjustment      = false,                      // Right Adjustment
    .data_shift           = 0,                          // Number of Data Shift
    .data_round_enable    = false                       // Data Rouding Mode                                              };
};

volatile avr32_dacifb_t *dacifb0 = &AVR32_DACIFB0; // DACIFB IP registers address
volatile avr32_dacifb_t *dacifb1 = &AVR32_DACIFB1; // DACIFB IP registers address

//The factory calibration for DADIFB is broken, so use manual calibration
//dacifb_get_calibration_data(DAC0,&dacifb_opt,0);

dacifb_opt.gain_calibration_value=0x0090;
dacifb_opt.offset_calibration_value=0x0153;

  // configure DACIFB0
dacifb_configure(DAC0,&dacifb_opt,PBA_SPEED);

dacifb_configure_channel(DAC0,DACIFB_CHANNEL_SELECTION_A,&dacifb_channel_opt,DAC_PRESCALER_CLK);

dacifb_start_channel(DAC0,DACIFB_CHANNEL_SELECTION_A,PBA_SPEED);

//The factory calibration for DADIFB is broken, so use manual calibration					
dacifb_set_value(DAC0,DACIFB_CHANNEL_SELECTION_A,false,1024);					   
					   				 
//dacifb_get_calibration_data(DAC1, &dacifb_opt,1);
							
dacifb_opt.gain_calibration_value=0x0084;
dacifb_opt.offset_calibration_value=0x0102;							

  // configure DACIFB1
dacifb_configure(DAC1,&dacifb_opt,PBA_SPEED);
				   
dacifb_configure_channel(DAC1,DACIFB_CHANNEL_SELECTION_A,&dacifb_channel_opt,DAC_PRESCALER_CLK);

dacifb_start_channel(DAC1,DACIFB_CHANNEL_SELECTION_A,PBA_SPEED);
					   
dacifb_set_value(DAC1,DACIFB_CHANNEL_SELECTION_A,false,1024);					   				   				 

DAC0->dr0=2048;
DAC1->dr0=4095;
}
Exemple #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++;		

	}
	
}
/**
 * \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.
		 */
	}
}
Exemple #18
0
/*! \brief Main function. Execution starts here.
 */
int main(void)
{
  // Options for QDEC timer Mode
  static const qdec_timer_opt_t QUADRATURE_TIMER_OPT =
  {
    .upd      = false,             // Up/Down Mode Timer Disabled.
    .tsdir    = QDEC_TSIR_DOWN,       // Count Down Timer.
    .filten   = false,                // Disable filtering.
    .evtrge   = false,                // Disable event triggering.
    .rcce     = true,                 // Enable Position Compare.
    .pcce     = true,                 // Enable Revolution Compare.
  };
  // Options for QDEC Interrupt Management
  static const qdec_interrupt_t QDEC_INTERRUPT =
  {
    .cmp    = 1,                      // Enable Compare Interrupt.
    .cap    = 0,                      // Disable Capture Interrupt.
    .pcro   = 0,                      // Disable Position Roll-over Interrupt.
    .rcro   = 0                       // Disable Counter Roll-over Interrupt.
  };

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

  // Setup the generic clock for QDEC
  scif_gc_setup(AVR32_SCIF_GCLK_QDEC0,
                SCIF_GCCTRL_OSC0,
                AVR32_SCIF_GC_NO_DIV_CLOCK,
                0);
  // Now enable the generic clock
  scif_gc_enable(AVR32_SCIF_GCLK_QDEC0);

  Disable_global_interrupt();

  // Initialize interrupt vectors.
  INTC_init_interrupts();

  // Register the QDEC interrupt handler to the interrupt controller.
  INTC_register_interrupt(&qdec_int_handler, AVR32_QDEC0_IRQ, AVR32_INTC_INT0);

  Enable_global_interrupt();

  // Initialization of counter value as a 32-bit counter to 0x0000FFFF (Rc=0x0000/Pc=0xFFFF)
  qdec_write_rc_cnt(qdec,0x0000);
  qdec_write_pc_cnt(qdec,0xffff);
  // Initialization of compare value to 0x0 as the interrupt will be generated when the counter value will be equal to 0
  qdec_write_rc_cmp(qdec,0);
  qdec_write_pc_cmp(qdec,0);

  // Initialize the QDEC in quadrature decoder mode.
  qdec_init_timer_mode(qdec,&QUADRATURE_TIMER_OPT);

  // Configure the QDEC interrupts.
  qdec_configure_interrupts(qdec,&QDEC_INTERRUPT);

   // Start the QDEC.
  qdec_software_trigger(qdec);

  unsigned int pc_cmp = 0;
  while(1)
  {
    // Compare Interrupt Flag
    if(flag_qdec == 1)
    {
        gpio_tgl_gpio_pin(LED0_GPIO);           // Check signal on oscilloscope.
        if (pc_cmp < 0xffff ) pc_cmp +=  0x100; // Increase PC CMP
        else pc_cmp = 0;                        // Start the signal pattern over.
        qdec_write_pc_cmp(qdec,pc_cmp);         // Reload Compare Flag
        flag_qdec = 0;                          // Reset Interrupt Flag
    }
  }
}
Exemple #19
0
/*!
 * \brief main function : do init and loop (poll if configured so)
 */
int main(void)
{
	char temp[20];
	char *ptemp;
	uint32_t ast_alarm;

	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     = 57600,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = 0
	};

#if BOARD == UC3L_EK
	scif_osc32_opt_t opt = {
		/* 2-pin Crystal connected to XIN32/XOUT32 and high current
		 * mode. */
		SCIF_OSC_MODE_2PIN_CRYSTAL_HICUR,
		/* oscillator startup time */
		AVR32_SCIF_OSCCTRL32_STARTUP_0_RCOSC,
		/* select alternate xin32_2 and xout32_2 for 32kHz crystal
		 * oscillator */
		true,
		/* disable the 1kHz output */
		false,
		/* enable the 32kHz output */
		true
	};
#else
	scif_osc32_opt_t opt;
	opt.mode = SCIF_OSC_MODE_2PIN_CRYSTAL;
	opt.startup = AVR32_SCIF_OSCCTRL32_STARTUP_0_RCOSC;
#endif

#if 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.
	 */
#else
	pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);
#endif

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

	/* Assign GPIO pins to USART0. */
	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, FPBA);

	/* Welcome sentence // 2-pin Crystal and high current mode. */
	/* Crystal is connected to XIN32/XOUT32. */
	usart_write_line(EXAMPLE_USART, "\x1B[2J\x1B[H\r\nATMEL\r\n");
	usart_write_line(EXAMPLE_USART, "AVR32 UC3 - AST example 2\r\n");
	usart_write_line(EXAMPLE_USART,
			"AST 32 KHz oscillator counter example.\r\n");
	usart_write_line(EXAMPLE_USART,
			"Alarm0 wakeup from static sleep mode every second.\r\n");

	/* Using counter mode and set it to 0 */
	unsigned long ast_counter = 0;

	/* Initialize the AST */
	if (!ast_init_counter(&AVR32_AST,
			AST_OSC_32KHZ, AST_PSEL_32KHZ_1HZ, ast_counter)) {
		usart_write_line(EXAMPLE_USART,
				"Error initializing the AST\r\n");
		while (1) {
		}
	}

	/* Alarm 0 sends a wakeup signal to the Power manager */
	ast_enable_alarm_async_wakeup(&AVR32_AST, 0);

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

	while (1) {
		/* disable alarm 0 */
		ast_disable_alarm0(&AVR32_AST);

		/* ast_init_counter Set Alarm to current time+30 seconds */
		ast_alarm = ast_counter + 1;
		ast_set_alarm0_value(&AVR32_AST, ast_alarm);

		/* Enable alarm 0 */
		ast_enable_alarm0(&AVR32_AST);

		/*
		 * Precautions when entering a sleep mode
		 * Modules communicating with external circuits should normally
		 * be disabled before entering a sleep mode that will stop the
		 * module operation.
		 * Make sure the USART dumps the last message completely before
		 * turning it off.
		 */
		while (!usart_tx_empty(EXAMPLE_USART)) {
		}
		pcl_disable_module(EXAMPLE_USART_CLOCK_MASK);

		/*
		 * Since we're going into a sleep mode deeper than IDLE, all HSB
		 * masters must be stopped before entering the sleep mode.
		 * Note: since we're not using the PDCA, we don't have to stop
		 *it.
		 */

		/*
		 * 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 into static sleep mode */
		SLEEP(AVR32_PM_SMODE_STATIC);

		/* We're out of the static sleep mode now => re-enable the USART
		 * module */
		pcl_enable_module(EXAMPLE_USART_CLOCK_MASK);

		/* After wake up, clear the Alarm0 */
		ast_clear_alarm_status_flag(&AVR32_AST, 0);

		/* Toggle Led0 */
		gpio_tgl_gpio_pin(LED0_GPIO);

		/* Set cursor to the position (1; 6) */
		usart_write_line(EXAMPLE_USART, "\x1B[6;1H");
		ast_counter = ast_get_counter_value(&AVR32_AST);
		usart_write_line(EXAMPLE_USART, "Timer: ");
		ptemp = print_i(temp, ast_counter);
		usart_write_line(EXAMPLE_USART, ptemp);
		usart_write_line(EXAMPLE_USART, " sec ");
	}
}
Exemple #20
0
/**
 * \brief Main function.
 */
int main(void)
{

	/*
	 * Initialize basic features for the AVR UC3 family.
	 *  - Sysclk init for configuring clock speed.
	 *  - Configure and enable LCD Display.
	 */
	pcl_configure_clocks(&pcl_freq_param);
	et024006_Init( pcl_freq_param.cpu_f, pcl_freq_param.cpu_f );
	gpio_set_gpio_pin(ET024006DHU_BL_PIN);
	et024006_DrawFilledRect(0 , 0, ET024006_WIDTH, ET024006_HEIGHT, BLACK );
        et024006_PrintString("With FPU ", (const unsigned char *)&FONT8x16, 40, 0, WHITE, BLACK);
        et024006_PrintString("Without FPU ", (const unsigned char *)&FONT8x16, 200, 0, WHITE, BLACK);

	/*
	 * Initialize local variables for fractal algorithm with FPU optimization.
	 */
	xstep_wfpu = (xend_wfpu-xstart_wfpu)/WIDTH;
	ystep_wfpu = (yend_wfpu-ystart_wfpu)/HEIGHT;
	x_wfpu = xstart_wfpu;
	y_wfpu = ystart_wfpu;


	/*
	 * Initialize local variables for fractal algorithm without FPU optimization.
	 */
	xstep_wofpu = (xend_wofpu-xstart_wofpu)/WIDTH;
	ystep_wofpu = (yend_wofpu-ystart_wofpu)/HEIGHT;
	x_wofpu = xstart_wofpu;
	y_wofpu = ystart_wofpu;

	/*the main loop */
	do
	{
	draw_mandel_with_fpu();
	draw_mandel_without_fpu();
        if (i_wofpu == 121){
          et024006_DrawFilledRect(0 , 0, ET024006_WIDTH, ET024006_HEIGHT, BLACK );
          /*
           * Initialize local variables for fractal algorithm with FPU optimization.
           */
          xstep_wfpu = (xend_wfpu-xstart_wfpu)/WIDTH;
          ystep_wfpu = (yend_wfpu-ystart_wfpu)/HEIGHT;
          x_wfpu = xstart_wfpu;
          y_wfpu = ystart_wfpu;


          /*
           * Initialize local variables for fractal algorithm without FPU optimization.
           */
          xstep_wofpu = (xend_wofpu-xstart_wofpu)/WIDTH;
          ystep_wofpu = (yend_wofpu-ystart_wofpu)/HEIGHT;
          x_wofpu = xstart_wofpu;
          y_wofpu = ystart_wofpu;
          iter_wfpu =40;
          xstart_wfpu = -2.0;
          xend_wfpu    = 1.0;
          ystart_wfpu = -1.35;
          yend_wfpu   = 1.35;
          i_wfpu=0,j_wfpu=0,k_wfpu=0;
          iter_wofpu =40;
          xstart_wofpu = -2.0;
          xend_wofpu    = 1.0;
          ystart_wofpu = -1.35;
          yend_wofpu   = 1.35;
          i_wofpu=0,j_wofpu=0,k_wofpu=0;
          et024006_PrintString("With FPU ", (const unsigned char *)&FONT8x16, 40, 0, WHITE, BLACK);
          et024006_PrintString("Without FPU ", (const unsigned char *)&FONT8x16, 200, 0, WHITE, BLACK);
        }

	}while(true);
}
Exemple #21
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
  }
}
static void clockfrequencies_configure(void)
{
#if UC3L
    static scif_gclk_opt_t gc_dfllif_ref_opt = { SCIF_GCCTRL_SLOWCLOCK, 0, false };
    static pcl_freq_param_t pcl_dfll_freq_param =
    {
      .main_clk_src = PCL_MC_DFLL0,
      .cpu_f        = EXAMPLE_MCUCLK_HZ,
      .pba_f        = EXAMPLE_MCUCLK_HZ,
      .pbb_f        = EXAMPLE_MCUCLK_HZ,
      .dfll_f       = EXAMPLE_FDFLL_HZ,
      .pextra_params = &gc_dfllif_ref_opt
    };
// Implementation for UC3L
    // 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.
#elif UC3C
    // Configure OSC0 in crystal mode, external crystal with a FOSC0 Hz frequency.
    scif_configure_osc_crystalmode(SCIF_OSC0, FOSC0);
    // Enable the OSC0
    scif_enable_osc(SCIF_OSC0, OSC0_STARTUP, true);
    // Set the main clock source as being OSC0.
    pm_set_mclk_source(PM_CLK_SRC_OSC0);

    scif_pll_opt_t opt;

    // Setup PLL0 on Osc0, mul=7 ,no divisor, lockcount=16: (16Mhzx8)/2 = 64MHz output
    opt.osc = SCIF_OSC0;     // Sel Osc0 or Osc1
    opt.lockcount = 16;      // lockcount in main clock for the PLL wait lock
    opt.div = 1;             // DIV=1 in the formula
    opt.mul = 7;             // MUL=7 in the formula
    opt.pll_div2 = 1;        // pll_div2 Divide the PLL output frequency by 2 (this settings does not change the FVCO value)
    opt.pll_wbwdisable = 0;  //pll_wbwdisable 1 Disable the Wide-Bandith Mode (Wide-Bandwith mode allow a faster startup time and out-of-lock time). 0 to enable the Wide-Bandith Mode.
    opt.pll_freq = 1;        // Set to 1 for VCO frequency range 80-180MHz, set to 0 for VCO frequency range 160-240Mhz.

    scif_pll_setup(SCIF_PLL0, &opt); // lockcount in main clock for the PLL wait lock

    /* Enable PLL0 */
    scif_pll_enable(SCIF_PLL0);

    /* Wait for PLL0 locked */
    scif_wait_for_pll_locked(SCIF_PLL0) ;

    // Divide PLL0 output by 2 for CPU, HSB and PBx clocks = 32MHz
    pm_set_clk_domain_div(PM_CLK_DOMAIN_0, (pm_divratio_t) 0); // CPU
    pm_set_clk_domain_div(PM_CLK_DOMAIN_1, (pm_divratio_t) 0); // HSB
    pm_set_clk_domain_div(PM_CLK_DOMAIN_3, (pm_divratio_t) 0); // PBB
    pm_set_clk_domain_div(PM_CLK_DOMAIN_2, (pm_divratio_t) 0); // PBA
    pm_set_clk_domain_div(PM_CLK_DOMAIN_4, (pm_divratio_t) 0); // PBC

    /* Set the main clock source as being PLL0. */
    pm_set_mclk_source(PM_CLK_SRC_PLL0);

#elif UC3D
    // Configure OSC0 in crystal mode, external crystal with a FOSC0 Hz frequency.
    scif_configure_osc_crystalmode(SCIF_OSC0, FOSC0);
    // Enable the OSC0
    scif_enable_osc(SCIF_OSC0, OSC0_STARTUP, true);
    // Set the main clock source as being OSC0.
    pm_set_mclk_source(PM_CLK_SRC_OSC0);

    scif_pll_opt_t opt;

    // Setup PLL0 on Osc0, mul=10 ,no divisor, lockcount=16: (12Mhzx11)/2 = 66MHz output
    opt.osc = SCIF_OSC0;     // Sel Osc0 or Osc1
    opt.lockcount = 16;      // lockcount in main clock for the PLL wait lock
    opt.div = 1;             // DIV=1 in the formula
    opt.mul = 10;            // MUL=10 in the formula
    opt.pll_div2 = 1;        // pll_div2 Divide the PLL output frequency by 2 (this settings does not change the FVCO value)
    opt.pll_wbwdisable = 0;  // pll_wbwdisable 1 Disable the Wide-Bandith Mode (Wide-Bandwith mode allow a faster startup time and out-of-lock time). 0 to enable the Wide-Bandith Mode.
    opt.pll_freq = 1;        // Set to 1 for VCO frequency range 80-180MHz, set to 0 for VCO frequency range 160-240Mhz.

    scif_pll_setup(SCIF_PLL0, &opt); // lockcount in main clock for the PLL wait lock

    /* Enable PLL0 */
    scif_pll_enable(SCIF_PLL0);

    /* Wait for PLL0 locked */
    scif_wait_for_pll_locked(SCIF_PLL0) ;

    // Divide PLL0 output by 2 for CPU, HSB and PBx clocks = 33MHz
    pm_set_clk_domain_div(PM_CLK_DOMAIN_0, (pm_divratio_t) 0); // CPU
    pm_set_clk_domain_div(PM_CLK_DOMAIN_1, (pm_divratio_t) 0); // HSB
    pm_set_clk_domain_div(PM_CLK_DOMAIN_3, (pm_divratio_t) 0); // PBB
    pm_set_clk_domain_div(PM_CLK_DOMAIN_2, (pm_divratio_t) 0); // PBA

    /* Set the main clock source as being PLL0. */
    pm_set_mclk_source(PM_CLK_SRC_PLL0);

#else // UC3A and UC3B series
  // Switch the main clock source to Osc0.
  pm_switch_to_osc0(&AVR32_PM, FOSC0, OSC0_STARTUP);

  // Setup PLL0 on Osc0, mul=10 ,no divisor, lockcount=16: 12Mhzx11 = 132MHz output
  pm_pll_setup(&AVR32_PM, 0,  // pll.
               10,  // mul.
               1,   // div.
               0,   // osc.
               16); // lockcount.
  // PLL output VCO frequency is 132MHz.
  // We divide it by 2 with the pll_div2=1 to get a main clock at 66MHz.
  pm_pll_set_option(&AVR32_PM, 0, // pll.
                    1,  // pll_freq.
                    1,  // pll_div2.
                    0); // pll_wbwdisable.
  // Enable the PLL.
  pm_pll_enable(&AVR32_PM, 0);
  // Wait until the PLL output is stable.
  pm_wait_for_pll0_locked(&AVR32_PM);
  // Configure each clock domain to use the main clock divided by 2
  // => fCPU = fPBA = fPBB = 33MHz.
  pm_cksel(&AVR32_PM,
           1,   // pbadiv.
           0,   // pbasel.
           1,   // pbbdiv.
           0,   // pbbsel.
           1,   // hsbdiv=cpudiv
           0);  // hsbsel=cpusel
  // Switch the main clock source to PLL0.
  pm_switch_to_clock(&AVR32_PM, AVR32_PM_MCCTRL_MCSEL_PLL0);
#endif
}
/*! \brief The main function.
 */
int main(void)
{
	int32_t result;

#if UC3L /* UC3L series only */
	// 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.
#else // else for all other series
	// 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);
#endif

	const gpio_map_t usart_gpio_map =
	{
		{EXAMPLE_USART_RX_PIN, EXAMPLE_USART_RX_FUNCTION},
		{EXAMPLE_USART_TX_PIN, EXAMPLE_USART_TX_FUNCTION}
	};

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

	static const usart_options_t usart_options =
	{
		.baudrate     = 57600,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = 0
	};

	// Initialize USART in RS232 mode.
	usart_init_rs232(EXAMPLE_USART, &usart_options, FPBA);

	usart_write_line(EXAMPLE_USART, "\x1B[2J\x1B[H\r\nATMEL\r\n");
	usart_write_line(EXAMPLE_USART, "AVR UC3 - HMATRIX example\r\n\r\n");

	// First test with AVR32_HMATRIX_DEFMSTR_TYPE_NO_DEFAULT
	print(EXAMPLE_USART, "- Test 1 ----------------------------------------\r\n");
	print(EXAMPLE_USART, "------ All Slave Default Master Types are:  ------\r\n");
	print(EXAMPLE_USART, "       - No Default Master\r\n");
	print(EXAMPLE_USART, "       - leds Toggle: ");
	print_ulong(EXAMPLE_USART,  NB_TOGGLE);
	print(EXAMPLE_USART, " times\r\n");

#if defined(AVR32_HMATRIX)
	configure_hmatrix(AVR32_HMATRIX_DEFMSTR_TYPE_NO_DEFAULT);
#elif defined(AVR32_HMATRIXB)
	configure_hmatrix(AVR32_HMATRIXB_DEFMSTR_TYPE_NO_DEFAULT);
#endif

	result = toggle_led(NB_TOGGLE);

	// Second test with AVR32_HMATRIX_DEFMSTR_TYPE_LAST_DEFAULT
	print(EXAMPLE_USART, "- Test 2 ----------------------------------------\r\n");
	print(EXAMPLE_USART, "------ All Slave Default Master Types are:  ------\r\n");
	print(EXAMPLE_USART, "       - Last Default Master\r\n");
	print(EXAMPLE_USART, "       - No Default Master\r\n");
	print(EXAMPLE_USART, "       - leds Toggle: ");
	print_ulong(EXAMPLE_USART,  NB_TOGGLE);
	print(EXAMPLE_USART, " times\r\n");

#if defined(AVR32_HMATRIX)
	configure_hmatrix(AVR32_HMATRIX_DEFMSTR_TYPE_LAST_DEFAULT);
#elif defined(AVR32_HMATRIXB)
	configure_hmatrix(AVR32_HMATRIXB_DEFMSTR_TYPE_LAST_DEFAULT);
#endif

	result -= toggle_led(NB_TOGGLE);

	print(EXAMPLE_USART, "--------------------------------------------------\r\n");

	print_ulong(EXAMPLE_USART, result);
	print(EXAMPLE_USART, " Cycles saved between test 1 and test 2\r\nDone!");

	//*** Sleep mode
	// This program won't be doing anything else from now on, so it might as well
	// sleep.
	// Modules communicating with external circuits should normally be disabled
	// before entering a sleep mode that will stop the module operation.
	// Make sure the USART dumps the last message completely before turning it off.
	while(!usart_tx_empty(EXAMPLE_USART));
	pcl_disable_module(EXAMPLE_USART_CLOCK_MASK);

	// Since we're going into a sleep mode deeper than IDLE, all HSB masters must
	// be stopped before entering the sleep mode: none is acting currently in this
	// example so nothing to do for this example.

	// 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 STATIC sleep mode.
	SLEEP(AVR32_PM_SMODE_STATIC);

	while (true);
}
/*!
 * \brief main function : do init and loop (poll if configured so)
 */
int main(void)
{
	char temp[20];
	char *ptemp;

	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     = 57600,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = 0
	};

#if BOARD == UC3L_EK
	scif_osc32_opt_t opt = {
		/* 
		 * 2-pin Crystal connected to XIN32/XOUT32 and high current
		 * mode.
		 */
		SCIF_OSC_MODE_2PIN_CRYSTAL_HICUR,
		/* oscillator startup time */
		AVR32_SCIF_OSCCTRL32_STARTUP_0_RCOSC,
		/* 
		 * select alternate xin32_2 and xout32_2 for 32kHz crystal
		 * oscillator 
		 */
		true,
		/* disable the 1kHz output */
		false,
		/* enable the 32kHz output */
		true
	};

#else
	scif_osc32_opt_t opt;
	opt.mode = SCIF_OSC_MODE_2PIN_CRYSTAL;
	opt.startup = AVR32_SCIF_OSCCTRL32_STARTUP_0_RCOSC;
#endif

#if 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.
	 */
#else
	pcl_switch_to_osc(PCL_OSC0, FOSC0, OSC0_STARTUP);
#endif

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

	/* Assign GPIO pins to USART0. */
	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, FPBA);

	/* Welcome message */
	usart_write_line(EXAMPLE_USART, "\x1B[2J\x1B[H\r\nATMEL\r\n");
	usart_write_line(EXAMPLE_USART, "AVR32 UC3 - AST example\r\n");

	usart_write_line(EXAMPLE_USART,
			"AST 32 KHz oscillator program test.\r\n");

	ast_calendar_t ast_calendar;
	ast_calendar.FIELD.sec  = 0;
	ast_calendar.FIELD.min  = 15;
	ast_calendar.FIELD.hour = 12;
	ast_calendar.FIELD.day  = 5;
	ast_calendar.FIELD.month = 6;
	ast_calendar.FIELD.year = 9;

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

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

	volatile int i;
	while (1) {
		/* slow down operations */
		for (i = 0; i < 10000; i++) {
		}
		gpio_tgl_gpio_pin(LED0_GPIO);

		/* Set cursor to the position (1; 5) */
		usart_write_line(EXAMPLE_USART, "\x1B[5;1H");
		ast_calendar = ast_get_calendar_value(&AVR32_AST);
		usart_write_line(EXAMPLE_USART, "Timer: ");
		ptemp = print_i(temp, ast_calendar.FIELD.sec);
		usart_write_line(EXAMPLE_USART, ptemp);
		usart_write_line(EXAMPLE_USART, " sec ");
	}
}
Exemple #25
0
/*! \brief Initializes the MCU system clocks.
*/
static void init_sys_clocks(void)
{
  // Configure system clocks.
  if (pcl_configure_clocks(&pcl_freq_param) != PASS)
    return 42;
}