Exemplo n.º 1
0
/**
 * \brief Application entry point for tc_capture_waveform example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint8_t key;
	uint16_t frequence, dutycycle;

	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

	/* Output example information */
	printf("-- TC capture waveform Example --\r\n");
	printf("-- %s\n\r", BOARD_NAME);
	printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);

	/* Configure PIO Pins for TC */
#if (SAM4L || SAM4E)
	ioport_set_pin_mode(PIN_TC_WAVEFORM, PIN_TC_WAVEFORM_FLAGS);
	ioport_disable_pin(PIN_TC_WAVEFORM); // Disable IO (but enable peripheral mode)
	ioport_set_pin_mode(PIN_TC_CAPTURE, PIN_TC_CAPTURE_FLAGS);
	ioport_disable_pin(PIN_TC_CAPTURE); // Disable IO (but enable peripheral mode)
#else
	gpio_configure_pin(PIN_TC_WAVEFORM, PIN_TC_WAVEFORM_FLAGS);
	gpio_configure_pin(PIN_TC_CAPTURE, PIN_TC_CAPTURE_FLAGS);
#endif

	/* Configure TC TC_CHANNEL_WAVEFORM as waveform operating mode */
	printf("Configure TC%d channel %d as waveform operating mode \n\r",
			TC_PERIPHERAL, TC_CHANNEL_WAVEFORM);
	tc_waveform_initialize();
	/* Configure TC TC_CHANNEL_CAPTURE as capture operating mode */
	printf("Configure TC%d channel %d as capture operating mode \n\r",
			TC_PERIPHERAL, TC_CHANNEL_CAPTURE);
	tc_capture_initialize();

	/* Configure TC interrupts for TC TC_CHANNEL_CAPTURE only */
	NVIC_DisableIRQ(TC_IRQn);
	NVIC_ClearPendingIRQ(TC_IRQn);
	NVIC_SetPriority(TC_IRQn, 0);
	NVIC_EnableIRQ(TC_IRQn);

	/* Display menu */
	display_menu();

	while (1) {
		scanf("%c", (char *)&key);

		switch (key) {
		case 'h':
			display_menu();
			break;

		case 's':
			if (gs_ul_captured_pulses) {
				tc_disable_interrupt(TC, TC_CHANNEL_CAPTURE, TC_IDR_LDRBS);
				printf("Captured %u pulses from TC%d channel %d, RA = %u, RB = %u \n\r",
						gs_ul_captured_pulses, TC_PERIPHERAL,
						TC_CHANNEL_CAPTURE,	gs_ul_captured_ra,
						gs_ul_captured_rb);
#if (SAM4L)
				frequence = (sysclk_get_peripheral_bus_hz(TC) /
						divisors[TC_CAPTURE_TIMER_SELECTION]) /
						gs_ul_captured_rb;
#else
				frequence = (sysclk_get_peripheral_hz() /
						divisors[TC_CAPTURE_TIMER_SELECTION]) /
						gs_ul_captured_rb;
#endif
				dutycycle
					= (gs_ul_captured_rb - gs_ul_captured_ra) * 100 /
						gs_ul_captured_rb;
				printf("Captured wave frequency = %d Hz, Duty cycle = %d%% \n\r",
						frequence, dutycycle);

				gs_ul_captured_pulses = 0;
				gs_ul_captured_ra = 0;
				gs_ul_captured_rb = 0;
			} else {
				puts("No waveform has been captured\r");
			}

			puts("\n\rPress 'h' to display menu\r");
			break;

		case 'c':
			puts("Start capture, press 's' to stop \r");
			tc_enable_interrupt(TC, TC_CHANNEL_CAPTURE, TC_IER_LDRBS);
			/* Start the timer counter on TC TC_CHANNEL_CAPTURE */
			tc_start(TC, TC_CHANNEL_CAPTURE);
			break;

		default:
			/* Set waveform configuration #n */
			if ((key >= '0') && (key <= ('0' + gc_uc_nbconfig - 1))) {
				if (!gs_ul_captured_pulses) {
					gs_uc_configuration = key - '0';
					tc_waveform_initialize();
				} else {
					puts("Capturing ... , press 's' to stop capture first \r");
				}
			}

			break;
		}
	}
}
Exemplo n.º 2
0
int main(void)
{
	board_init();
	sysclk_init();
	adc_init();
	
	//Offset is stored in EEPROM
	int adc_offset = 0;
	if (nvm_eeprom_read_byte(EEPROM_ADDR_ID) == EEPROM_ID){
		adc_offset = nvm_eeprom_read_byte(EEPROM_ADDR_OFFSET_POS) - nvm_eeprom_read_byte(EEPROM_ADDR_OFFSET_NEG);
	}

	
    PORTE_DIRSET = MASK_DIGIT012;
	PORTD_DIRSET = 0xFF;
	
	int32_t i = 0;	
	uint8_t disp = 0;
	uint8_t adccnt = 0;
	
	unsigned int adc_readings[AVG_READINGS];
	
	//Setup ADC hardware
	adc_init();
	
	//Main loop...measure VCC-INT
	while(1){	
		// Vref = 2.048V
		// 4096 count ADC (12-bit)
		// 2.048V / 4096count = 0.0005 V/Count
		// We want i to be result in mV
		// = 0.5 mV/count
		//So divide count by 2 to get mV reading		
		if (adccnt < AVG_READINGS){
			adc_readings[adccnt] = adc_get_unsigned_result(&MY_ADC, MY_ADC_CH);
		
			if (adc_readings[adccnt] < 0){
				adc_readings[adccnt] = 0;
			}			
			adccnt++;
		} else {
			int32_t adctemp = 0;
			for (adccnt = 0; adccnt < AVG_READINGS; adccnt++){
				adctemp += (int32_t)(adc_readings[adccnt] + adc_offset);
			}
			i = adctemp / AVG_READINGS;
			//Limit negative values to 0
			//i = i - 2048;
			if (i < 0) i = 0;
			i = i / 2;
			
			adccnt = 0;
		}
		
		//Switch between mV and V ranges
		if (i > 999){
			if (disp == 0){
				display((i / 10)%10, 0, 2);
				_delay_ms(2);
			} else if (disp == 1){
				display((i / 100) % 10, 0, 1);
				_delay_ms(2);
			} else {
				display(i / 1000, 1, 0);
				_delay_ms(2);
			}
		} else {
			if (disp == 0){
				display(i % 10, 0, 2);
				_delay_ms(2);
			} else if (disp == 1){
				display((i / 10) % 10, 0, 1);
				_delay_ms(2);
			} else {
				display(i / 100, 0, 0);
				_delay_ms(2);
			}
		}
		
		disp++;
		if (disp > 2){
			disp = 0;		
		}
		
		adc_start_conversion(&MY_ADC, MY_ADC_CH);
	}
}
Exemplo n.º 3
0
/**
 *  \brief ACC example application entry point.
 *
 *  \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint8_t uc_key;
	int16_t s_volt = 0;
	uint32_t ul_value = 0;
	volatile uint32_t ul_status = 0x0;
	int32_t l_volt_dac0 = 0;

	/* Initialize the system */
	sysclk_init();
	board_init();

	/* Initialize debug console */
	configure_console();

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

	/* Initialize DACC */
	/* Enable clock for DACC */
	pmc_enable_periph_clk(ID_DACC);
	/* Reset DACC registers */
	dacc_reset(DACC);
	/* External trigger mode disabled. DACC in free running mode. */
	dacc_disable_trigger(DACC);
	/* Half word transfer mode */
	dacc_set_transfer_mode(DACC, 0);
	/* Power save:
	 * sleep mode  - 0 (disabled)
	 * fast wake-up - 0 (disabled)
	 */
	dacc_set_power_save(DACC, 0, 0);
	/* Timing:
	 * refresh        - 0x08 (1024*8 dacc clocks)
	 * max speed mode -    0 (disabled)
	 * startup time   - 0xf (960 dacc clocks)
	 */
	dacc_set_timing(DACC, 0x08, 0, 0xf);
	/* Disable TAG and select output channel DACC_CHANNEL */
	dacc_set_channel_selection(DACC, DACC_CHANNEL_0);
	/* Enable output channel DACC_CHANNEL */
	dacc_enable_channel(DACC, DACC_CHANNEL_0);
	/* Setup analog current */
	dacc_set_analog_control(DACC, DACC_ANALOG_CONTROL);

	/* Set DAC0 output at ADVREF/2. The DAC formula is:
	 *
	 * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
	 * ----------------------------------- = --------------------------
	 *              MAX_DIGITAL                       digit
	 *
	 * Here, digit = MAX_DIGITAL/2
	 */
	dacc_write_conversion_data(DACC, MAX_DIGITAL / 2);
	l_volt_dac0 = (MAX_DIGITAL / 2) * (2 * VOLT_REF / 3) / MAX_DIGITAL +
			VOLT_REF / 6;

	/* Initialize ADC */
	/* Enable clock for ADC */
	pmc_enable_periph_clk(ID_ADC);
	/*
	 * Formula: ADCClock = MCK / ( (PRESCAL+1) * 2 )
	 * For example, MCK = 64MHZ, PRESCAL = 4, then:
	 *     ADCClock = 64 / ((4+1) * 2) = 6.4MHz;
	 */
	adc_init(ADC, sysclk_get_cpu_hz(), ADC_CLOCK, ADC_STARTUP_TIME_SETTING);

	/* Formula:
	 *     Startup  Time = startup value / ADCClock
	 *     Transfer Time = (TRANSFER * 2 + 3) / ADCClock
	 *     Tracking Time = (TRACKTIM + 1) / ADCClock
	 *     Settling Time = settling value / ADCClock
	 * For example, ADC clock = 6MHz (166.7 ns)
	 *     Startup time = 512 / 6MHz = 85.3 us
	 *     Transfer Time = (1 * 2 + 3) / 6MHz = 833.3 ns
	 *     Tracking Time = (0 + 1) / 6MHz = 166.7 ns
	 *     Settling Time = 3 / 6MHz = 500 ns
	 */
	/* Set ADC timing */
	adc_configure_timing(ADC, ADC_TRACK_SETTING, ADC_SETTLING_TIME_3,
			ADC_TRANSFER_SETTING);

	/* Channel 5 has to be compared */
	adc_enable_channel(ADC, ADC_CHANNEL_5);

	//! [acc_enable_clock]
	/** Enable clock for ACC */
	pmc_enable_periph_clk(ID_ACC);
	//! [acc_enable_clock]

	//! [acc_init]
	/** Initialize ACC */
	acc_init(ACC, ACC_MR_SELPLUS_AD5, ACC_MR_SELMINUS_DAC0,
			ACC_MR_EDGETYP_ANY, ACC_MR_INV_DIS);
	//! [acc_init]

	//! [acc_irq_enable]
	/** Enable ACC interrupt */
	NVIC_EnableIRQ(ACC_IRQn);

	/** Enable */
	acc_enable_interrupt(ACC);
	//! [acc_irq_enable]

	dsplay_menu();

	while (1) {
		while (uart_read(CONSOLE_UART, &uc_key)) {
		}

		printf("input: %c\r\n", uc_key);

		switch (uc_key) {
		case 's':
		case 'S':
			printf("Input DAC0 output voltage (%d~%d mv): ",
					(VOLT_REF / 6), (VOLT_REF * 5 / 6));
			s_volt = get_input_voltage();
			puts("\r");

			if (s_volt > 0) {
				l_volt_dac0 = s_volt;
				/* The DAC formula is:
				 *
				 * (5/6 * VOLT_REF) - (1/6 * VOLT_REF)     volt - (1/6 * VOLT_REF)
				 * ----------------------------------- = --------------------------
				 *              MAX_DIGITAL                       digit
				 *
				 */
				ul_value = ((s_volt - (VOLT_REF / 6))
					* (MAX_DIGITAL * 6) / 4) / VOLT_REF;
				dacc_write_conversion_data(DACC, ul_value);
				puts("-I- Set ok\r");
			} else {
				puts("-I- Input voltage is invalid\r");
			}
			break;
		case 'v':
		case 'V':
			/* Start conversion */
			adc_start(ADC);
			ul_status = adc_get_status(ADC);
			while ((ul_status & ADC_ISR_EOC5) != ADC_ISR_EOC5) {
				ul_status = adc_get_status(ADC);
			}
			/* Conversion is done */
			ul_value = adc_get_channel_value(ADC, ADC_CHANNEL_5);

			/*
			 * Convert ADC sample data to voltage value:
			 * voltage value = (sample data / max. resolution) * reference voltage
			 */
			s_volt = (ul_value * VOLT_REF) / MAX_DIGITAL;
			printf("-I- Voltage on potentiometer(AD5) is %d mv\n\r", s_volt);
			printf("-I- Voltage on DAC0 is %ld mv \n\r", (long)l_volt_dac0);
			break;
			
		case 'm':
		case 'M':
			dsplay_menu();
			break;
		}
	}
}
Exemplo n.º 4
0
/**
 * \brief Application entry point for PARC example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint32_t uc_key;

	/* Initialize the SAM system. */
	sysclk_init();
	board_init();

	/* Configure UART for debug message output. */
	configure_console();
	parc_port_source_simulation_config();

	//! [parc_variables]	
	struct parc_module module_inst;
	struct parc_config config;
	//! [parc_variables]	

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

	/* Configure TC. */
	configure_tc();
	/* Start timer. */
	tc_start(TC0, 0);

	//! [parc_get_defaults]	
	// Get default configuration
	parc_get_config_defaults(&config);
	//! [parc_get_defaults]	
	printf("Press y to sample the data when both data enable pins are enabled.\r\n");
	printf("Press n to sample the data, don't care the status of the data enable pins.\r\n");
	uc_key = 0;
	while ((uc_key != 'y') && (uc_key != 'n')) {
		usart_read(CONF_UART, &uc_key);
	}
	if (uc_key == 'y') {
		/* Sample the data when both data enable pins are enabled. */
		config.smode = PARC_SMODE_PCEN1_AND_PCEN2_H;
		ioport_set_pin_level(PIN_PCEN1_INPUT, IOPORT_PIN_LEVEL_HIGH);
		ioport_set_pin_level(PIN_PCEN2_INPUT, IOPORT_PIN_LEVEL_HIGH);
		printf("Receive data when both data enable pins are enabled.\r\n");
	} else {
		/* Sample the data, don't care the status of the data enable pins. */
		config.smode = PARC_SMODE_ALWAYS;
		printf("Receive data, don't care the status of the data enable pins.\r\n");
	}

	printf("Press y to sample all the data.\r\n");
	printf("Press n to sample the data only one out of two.\r\n");
	uc_key = 0;
	while ((uc_key != 'y') && (uc_key != 'n')) {
		usart_read(CONF_UART, &uc_key);
	}
	if (uc_key == 'y') {
			/* Sample all the data. */
		config.capture_mode = PARC_BOTH_CAPTURE;
		printf("All data are sampled.\r\n");
	} else {
		/* Sample the data only one out of two. */
		config.capture_mode = PARC_EVEN_CAPTURE;
		printf("Only one out of two data is sampled, with an even index.\r\n");
	}

	//! [parc_init_enable_and_start]
	//! [parc_init_enable_and_start_1]
	// Initialize PARC.
	parc_init(&module_inst, PARC, &config);
	//! [parc_init_enable_and_start_1]
	
	//! [parc_init_enable_and_start_2]
	// Enable the PARC
	parc_enable(&module_inst);
	
	// Start capture.
	parc_start_capture(&module_inst);
	//! [parc_init_enable_and_start_2]
	//! [parc_init_enable_and_start]

	/* Enable PDCA module clock */
	pdca_enable(PDCA);
	/* Init PDCA channel with the pdca_options.*/
	pdca_channel_set_config(PDCA_PARC_CHANNEL, &PDCA_PARC_OPTIONS);

	/* Set callback for PDCA interrupt. */
	pdca_channel_set_callback(PDCA_PARC_CHANNEL,
			pdca_parc_callback,PDCA_0_IRQn,1,PDCA_IER_RCZ);

	/* Enable PDCA channel, start receiving data. */
	pdca_channel_enable(PDCA_PARC_CHANNEL);
	/* Start read PARC data capture via PDCA. */
	pdca_channel_write_load(PDCA_PARC_CHANNEL,
			(void *)gs_puc_buffer, BUFFER_SIZE);
	/* Main loop. */
	while(1) {
	}
}
Exemplo n.º 5
0
/**
 * \brief Run usb device cdc unit tests
 *
 * Initializes the clock system, board and serial output, then sets up the
 * usb unit test suite and runs it.
 */
int main(void)
{
    const usart_serial_options_t usart_serial_options = {
        .baudrate   = CONF_TEST_BAUDRATE,
        .charlength = CONF_TEST_CHARLENGTH,
        .paritytype = CONF_TEST_PARITY,
        .stopbits   = CONF_TEST_STOPBITS,
    };

    sysclk_init();
    irq_initialize_vectors();
    cpu_irq_enable();

    // Initialize the sleep manager
    sleepmgr_init();

    board_init();
    stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

    // Define all the timestamp to date test cases
    DEFINE_TEST_CASE(usb_cdc_test, NULL,
                     run_usb_cdc_test, NULL,
                     "USB Device cdc enumeration test");
    DEFINE_TEST_CASE(usb_cdc_config_test, NULL,
                     run_usb_cdc_config_test, NULL,
                     "USB CDC configuration test");
    DEFINE_TEST_CASE(usb_vbus_test, NULL,
                     run_usb_vbus_test, NULL,
                     "USB vbus event test");
    DEFINE_TEST_CASE(usb_resume_test, NULL,
                     run_usb_resume_test, NULL,
                     "USB resume event test");
    DEFINE_TEST_CASE(usb_suspend_test, NULL,
                     run_usb_suspend_test, NULL,
                     "USB suspend event test");
    DEFINE_TEST_CASE(usb_sof_test, NULL,
                     run_usb_sof_test, NULL,
                     "USB sof event test");

    // Put test case addresses in an array
    DEFINE_TEST_ARRAY(usb_cdc_tests) = {
        &usb_cdc_test,
        &usb_cdc_config_test,
        &usb_vbus_test,
        &usb_resume_test,
        &usb_suspend_test,
        &usb_sof_test,
    };

    // Define the test suite
    DEFINE_TEST_SUITE(usb_cdc_suite, usb_cdc_tests,
                      "Common usb CDC service with test suite");

    // The unit test prints message via UART which does not support deep sleep mode.
#if SAM
    sleepmgr_lock_mode(SLEEPMGR_ACTIVE);
#else
    sleepmgr_lock_mode(SLEEPMGR_IDLE);
#endif

    // Run all tests in the suite
    test_suite_run(&usb_cdc_suite);

    while (1) {
        // Intentionally left empty.
    }
}
Exemplo n.º 6
0
int main(void)
{
	sysclk_init();
	board_init();

	/* Enable one wait state for flash access */
	flashcalw_set_wait_state(1);

	/*
	 * Configure systick for 200ms (CPU frequency / 5) at startup time.
	 *
	 * Note: CPU frequency will be changed with below clock switching.
	 */
	if (SysTick_Config(sysclk_get_cpu_hz() / 5)) {
		while (1) { /* Capture error */
		}
	}

	while (1) {
		struct dfll_config dcfg;
		struct pll_config pcfg;
		/* avoid Cppcheck Warning */
		UNUSED(pcfg);

		/*
		 * Initial state: Running from RC80M with all
		 * prescalers set to 2 (Divide frequency by 4).
		 */
		wait_for_switches();

		/*
		 * Divide CPU frequency by 8. This will make the LED
		 * blink half as fast.
		 */
		sysclk_set_prescalers(3, 3, 3, 3, 3);
		wait_for_switches();

		/*
		 * Switch to the DFLL running at ~48 MHz in Open Loop
		 * mode, with the CPU running at ~48 MHz.
		 */
		dfll_config_init_open_loop_mode(&dcfg);
		dfll_config_tune_for_target_hz(&dcfg, 48000000);
		dfll_enable_open_loop(&dcfg, 0);
		sysclk_set_prescalers(1, 1, 1, 1, 1);
		sysclk_set_source(SYSCLK_SRC_DFLL);
		osc_disable(OSC_ID_RC80M);
		wait_for_switches();

		/*
		 * Switch to the slow clock with all prescalers
		 * disabled.
		 */
		sysclk_set_source(SYSCLK_SRC_RCSYS);
		sysclk_set_prescalers(0, 0, 0, 0, 0);
		dfll_disable_open_loop(0);
		wait_for_switches();

		/*
		 * Switch to the RCFAST clock with all prescalers
		 * disabled.
		 */
		osc_enable(OSC_ID_RCFAST);
		sysclk_set_prescalers(0, 0, 0, 0, 0);
		osc_wait_ready(OSC_ID_RCFAST);
		sysclk_set_source(SYSCLK_SRC_RCFAST);
		wait_for_switches();

		/*
		 * Switch to the RC1M clock with all prescalers
		 * disabled.
		 */
		osc_enable(OSC_ID_RC1M);
		sysclk_set_prescalers(0, 0, 0, 0, 0);
		osc_wait_ready(OSC_ID_RC1M);
		sysclk_set_source(SYSCLK_SRC_RC1M);
		osc_disable(OSC_ID_RCFAST);
		wait_for_switches();

		/*
		 * Switch to external OSC0, if available.
		 */
#ifdef BOARD_OSC0_HZ
		osc_enable(OSC_ID_OSC0);
		osc_wait_ready(OSC_ID_OSC0);
		sysclk_set_source(SYSCLK_SRC_OSC0);
		osc_disable(OSC_ID_RC1M);
		wait_for_switches();

		/*
		 * Switch to PLL0 running at 96 MHz. Use OSC0 as the
		 * source
		 */
		pll_config_init(&pcfg, PLL_SRC_OSC0, 1, 96000000 /
				BOARD_OSC0_HZ);
		pll_enable(&pcfg, 0);
		sysclk_set_prescalers(2, 2, 2, 2, 2);
		pll_wait_for_lock(0);
		sysclk_set_source(SYSCLK_SRC_PLL0);
		wait_for_switches();
#endif

		/*
		 * Switch to the DFLL, using the 32 kHz oscillator as a
		 * reference if available, or failing that, the 115 kHz
		 * RCSYS oscillator.
		 */
#ifdef BOARD_OSC32_HZ
		osc_enable(OSC_ID_OSC32);
		dfll_config_init_closed_loop_mode(&dcfg,
				GENCLK_SRC_OSC32K, 1,
				CONFIG_DFLL0_FREQ / BOARD_OSC32_HZ);
		osc_wait_ready(OSC_ID_OSC32);
#else
		dfll_config_init_closed_loop_mode(&dcfg,
				GENCLK_SRC_RCSYS, 1,
				CONFIG_DFLL0_FREQ / OSC_RCSYS_NOMINAL_HZ);
#endif
		dfll_enable_closed_loop(&dcfg, 0);
		sysclk_set_prescalers(1, 1, 1, 1, 1);
		dfll_wait_for_fine_lock(0);
		sysclk_set_source(SYSCLK_SRC_DFLL);
#ifdef BOARD_OSC0_HZ
		osc_disable(OSC_ID_OSC0);
#endif
		wait_for_switches();

		/*
		 * Go back to the initial state and start over.
		 */
		osc_enable(OSC_ID_RC80M);
		sysclk_set_prescalers(2, 2, 2, 2, 2);
		osc_wait_ready(OSC_ID_RC80M);
		sysclk_set_source(SYSCLK_SRC_RC80M);
		dfll_disable_closed_loop(0);
#ifdef BOARD_OSC32_HZ
		osc_disable(OSC_ID_OSC32);
#endif
	}
}
int main(void)
{
	enum sleepmgr_mode current_sleep_mode = SLEEPMGR_ACTIVE;
	uint32_t ast_counter = 0;

	/*
	 * Initialize the synchronous clock system to the default configuration
	 * set in conf_clock.h.
	 * \note All non-essential peripheral clocks are initially disabled.
	 */
	sysclk_init();

	/*
	 * Initialize the resources used by this example to the default
	 * configuration set in conf_board.h
	 */
	board_init();

	/*
	 * Turn the activity status LED on to inform the user that the device
	 * is active.
	 */
	ioport_set_pin_level(LED_ACTIVITY_STATUS_PIN, LED_STATUS_ON);

	osc_priv_enable_osc32();

	/* Enable the AST clock. */
	sysclk_enable_pba_module(SYSCLK_AST);
	/* Initialize the AST in Counter mode. */
	ast_init_counter(AST, AST_OSC_1KHZ, AST_PSEL_32KHZ_1HZ - 6,
			ast_counter);

	/*
	 * Configure the AST to wake up the CPU when the counter reaches the
	 * selected periodic0 value.
	 */
	ast_set_periodic0_value(AST,AST_PSEL_32KHZ_1HZ - 3);
	ast_enable_periodic_interrupt(AST,0);
	ast_enable_periodic_async_wakeup(AST,0);
	ast_enable_periodic0(AST);
	ast_clear_periodic_status_flag(AST,0);

	NVIC_ClearPendingIRQ(AST_PER_IRQn);
	NVIC_EnableIRQ(AST_PER_IRQn);

	/* Enable the AST. */
	ast_enable(AST);

	/* AST can wakeup the device */
	bpm_enable_wakeup_source(BPM, (1 << BPM_BKUPWEN_AST));

	// Initialize the sleep manager, lock initial mode.
	sleepmgr_init();
	sleepmgr_lock_mode(current_sleep_mode);

	while (1) {
		/*
		 * Turn the activity status LED off to inform the user that the
		 * device is in a sleep mode.
		 */
		ioport_set_pin_level(LED_ACTIVITY_STATUS_PIN, LED_STATUS_OFF);

		/*
		 * Go to sleep in the deepest allowed sleep mode (i.e. no
		 * deeper than the currently locked sleep mode).
		 */
		sleepmgr_enter_sleep();

		/*
		 * Turn the activity status LED on to inform the user that the
		 * device is active.
		 */
		ioport_set_pin_level(LED_ACTIVITY_STATUS_PIN, LED_STATUS_ON);

		/* Unlock the current sleep mode. */
		sleepmgr_unlock_mode(current_sleep_mode);

		/* Add a 3s delay. */
		delay_s(3);

		/* Lock the next sleep mode. */
		++current_sleep_mode;
		if ((current_sleep_mode >= SLEEPMGR_NR_OF_MODES)) {
			current_sleep_mode = SLEEPMGR_ACTIVE;
		}

		sleepmgr_lock_mode(current_sleep_mode);
	}
}
Exemplo n.º 8
0
int main (void)
{

	/**
	* Inicializando o clock do uP
	*/
	sysclk_init();
	
	/** 
	*  Desabilitando o WathDog do uP
	*/
	WDT->WDT_MR = WDT_MR_WDDIS;
		
	/**
	* Ativa clock nos periféricos
	*/
	_pmc_enable_clock_periferico(ID_LED_BLUE);
	_pmc_enable_clock_periferico(ID_LED_GREEN);		// Redundante mas não tem problema !
	_pmc_enable_clock_periferico(ID_LED_RED);
	_pmc_enable_clock_periferico(ID_BUT_2);
				
	/**
	*	Configura saída
	*/
	pio_set_output(PORT_LED_BLUE  , MASK_LED_BLUE	,1,0,0);
	pio_set_output(PORT_LED_GREEN , MASK_LED_GREEN  ,1,0,0);
	pio_set_output(PORT_LED_RED	  , MASK_LED_RED	,1,0,0);
	


	
	/**
	* Configura entrada
	*/ 
	pio_set_input(PORT_BUT_2, MASK_BUT_2, PIO_PULLUP | PIO_DEBOUNCE);
	
	/*
	 * Configura divisor do clock para debounce
	 */
	pio_set_debounce_filter(PORT_BUT_2, MASK_BUT_2, 100);
	

	
	/* 
	*	Configura interrupção para acontecer em borda de descida.
	*/
	pio_handler_set(PIOB, ID_BUT_2, MASK_BUT_2, PIO_IT_FALL_EDGE, push_button_handle);
				
	/*
	*	Ativa interrupção no periférico B porta do botão
	*/	
	pio_enable_interrupt(PORT_BUT_2, MASK_BUT_2);	
	/*
	*	Configura a prioridade da interrupção no pORTB
	*/
	NVIC_SetPriority((IRQn_Type)PIOB_IRQn, 0);
	
	/*
	*	Ativa interrupção no port B
	*/
	NVIC_EnableIRQ((IRQn_Type)PIOB_IRQn);
	
	/**
	*	Loop infinito
	*/
	while(1){
	    /*
		pio_set(PIOA, (1 << PIN_LED_BLUE));
		delay_ms(500);
		pio_clear(PIOA, (1 << PIN_LED_BLUE));
		delay_ms(500);
		*/
	}
}
Exemplo n.º 9
0
/**
 * \brief Initialize the PDCA transfer for the example.
 */
static void init_pdca(void)
{
	/* PDCA channel options */
	static const pdca_channel_config_t pdca_tx_configs = {
		.addr = (void *)event_string,
		.pid = CONF_PDCA_PID_USART_TX,
		.size = sizeof(event_string),
		.r_addr = 0,
		.r_size = 0,
		.ring = false,
		.etrig = true,
		.transfer_size = PDCA_MR_SIZE_BYTE
	};

	/* Enable PDCA module */
	pdca_enable(PDCA);

	/* Init PDCA channel with the pdca_options.*/
	pdca_channel_set_config(PEVC_ID_USER_PDCA_0, &pdca_tx_configs);

	/* Set callback for PDCA channel */
	pdca_channel_set_callback(PEVC_ID_USER_PDCA_0, pdca_tranfer_done,
			PDCA_0_IRQn, 1, PDCA_IER_TRC | PDCA_IER_TERR);

	/* Enable PDCA channel */
	pdca_channel_enable(PEVC_ID_USER_PDCA_0);
}

/**
 *  \brief Configure serial console.
 */
static void configure_console(void)
{
	const usart_serial_options_t uart_serial_options = {
		.baudrate = CONF_UART_BAUDRATE,
#ifdef CONF_UART_CHAR_LENGTH
		.charlength = CONF_UART_CHAR_LENGTH,
#endif /* CONF_UART_CHAR_LENGTH */
		.paritytype = CONF_UART_PARITY,
#ifdef CONF_UART_STOP_BITS
		.stopbits = CONF_UART_STOP_BITS,
#endif /* CONF_UART_STOP_BITS */
	};

	/* Configure console. */
	stdio_serial_init(CONF_UART, &uart_serial_options);
}

/**
 * \brief Main entry point for event example.
 */
int main(void)
{
	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

	/* Output example information */
	printf("\r\n\r\n-- Events example 1 --\r\n");
	printf("-- %s\r\n", BOARD_NAME);
	printf("-- Compiled: %s %s --\r\n", __DATE__, __TIME__);

	//! [quick_start_init_all_basic_use]
	/* Initialize AST as event generator. */
	//! [quick_start_init_ast_basic_use]
	init_ast();
	//! [quick_start_init_ast_basic_use]

	/* Initialise events for this example. */
	//! [quick_start_init_events_basic_use]
	init_events();
	//! [quick_start_init_events_basic_use]

	/* Initialize the PDCA as event user */
	//! [quick_start_init_pdca_basic_use]
	init_pdca();
	//! [quick_start_init_pdca_basic_use]
	//! [quick_start_init_all_basic_use]

	while (1) {
		/* Toggle LED0 every 500 ms */
		LED_Toggle(LED0);
		delay_ms(500);
	}
}
Exemplo n.º 10
0
static void prvSetupHardware( void )
{
	sysclk_init();
	board_init();
}
Exemplo n.º 11
0
// [main]
int main(void)
{
//! [main_step_sys_init]
	/* Initialize the SAM system */
	sysclk_init();
	board_init();
//! [main_step_sys_init]

#ifndef BOARD_NO_PUSHBUTTON_2
#if (SAMV71 || SAMV70 || SAMS70 || SAME70)
	if (GPIO_PUSH_BUTTON_2 == PIO_PB12_IDX) {
		matrix_set_system_io(matrix_get_system_io() | CCFG_SYSIO_SYSIO12);
	}
	ioport_set_pin_dir(GPIO_PUSH_BUTTON_2, IOPORT_DIR_INPUT);
	ioport_set_pin_mode(GPIO_PUSH_BUTTON_2, GPIO_PUSH_BUTTON_2_FLAGS);
	ioport_set_pin_sense_mode(GPIO_PUSH_BUTTON_2, GPIO_PUSH_BUTTON_2_SENSE);
#endif
#endif
//! [main_step_console_init]
	/* Initialize the console uart */
	configure_console();
//! [main_step_console_init]

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

	/* Configure systick for 1 ms */
	puts("Configure system tick to get 1ms tick period.\r");
//! [main_step_systick_init]
	if (SysTick_Config(sysclk_get_cpu_hz() / 1000)) {
		puts("-F- Systick configuration error\r");
		while (1);
	}
//! [main_step_systick_init]

#ifndef BOARD_NO_LED_1
	puts("Configure TC.\r");
//! [main_step_tc_init]
	configure_tc();
//! [main_step_tc_init]
#endif

	puts("Configure buttons with debouncing.\r");
//! [main_step_btn_init]
	configure_buttons();
//! [main_step_btn_init]

	printf("Press %s to Start/Stop the %s blinking.\r\n",
			PUSHBUTTON_1_NAME, LED_0_NAME);

#ifndef BOARD_NO_PUSHBUTTON_2
	printf("Press %s to Start/Stop the %s blinking.\r\n",
			PUSHBUTTON_2_NAME, LED_1_NAME);
#endif

//! [main_step_loop]
	while (1) {
		/* Wait for LED to be active */
		while (!g_b_led0_active);

		/* Toggle LED state if active */
		if (g_b_led0_active) {
			ioport_toggle_pin_level(LED0_GPIO);
			printf("1 ");
		}

		/* Wait for 500ms */
		mdelay(500);
	}
//! [main_step_loop]
}
Exemplo n.º 12
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");
}
Exemplo n.º 13
0
/**
 * @brief Main function of the coordinator application
 *
 * This function initializes the MAC, initiates a MLME reset request
 * (@ref wpan_mlme_reset_req()), and implements a the main loop.
 */
int main(void)
{	
	irq_initialize_vectors();
	#if SAMD20
	system_init();
	delay_init();
	#else
	sysclk_init();

	/* Initialize the board.
	 * The board-specific conf_board.h file contains the configuration of
	 * the board initialization.
	 */
	board_init();
	#endif
	#ifdef SIO_HUB
		sio2host_init();
	#endif
	sw_timer_init();

	if (MAC_SUCCESS != wpan_init()) {
		app_alert();
	}

	/* Initialize LEDs. */
	LED_On(LED_START);     /* indicating application is started */
	LED_Off(LED_NWK_SETUP); /* indicating network is started */
	LED_Off(LED_DATA);     /* indicating data transmission */

	cpu_irq_enable();

#ifdef SIO_HUB
	/* Initialize the serial interface used for communication with terminal
	 *program. */

	/* To make sure the Hyper Terminal Connected to the system*/
	sio2host_getchar();

#ifdef BEACON_SUPPORT
printf("\nBeacon_Application\r\n\n");
#else
printf("\nNO Beacon_Application\r\n\n");
#endif
	printf("\nCoordinator\r\n\n");
	print_stack_app_build_features();
#endif /* SIO_HUB */

	sw_timer_get_id(&APP_TIMER_INDIRECT_DATA);
	sw_timer_get_id(&APP_TIMER_BCN_PAYLOAD_UPDATE);
	sw_timer_get_id(&APP_TIMER_BC_DATA);
	#ifdef GTS_SUPPORT
	sw_timer_get_id(&APP_TIMER_GTS_DATA);
    #endif
	/*
	 * Reset the MAC layer to the default values.
	 * This request will cause a mlme reset confirm message ->
	 * usr_mlme_reset_conf
	 */
	wpan_mlme_reset_req(true);

#ifdef GPIO_PUSH_BUTTON_0
	dst_addr.AddrMode = 2;
	dst_addr.PANId = DEFAULT_PAN_ID;
#endif /* GPIO_PUSH_BUTTON_0 */

	while (true) {
		wpan_task();
#ifdef GPIO_PUSH_BUTTON_0
		if (!ioport_get_pin_level(GPIO_PUSH_BUTTON_0)) {
			delay_ms(DEBOUNCE_DELAY_MS);
			if (!ioport_get_pin_level(GPIO_PUSH_BUTTON_0)) {
				dst_addr.Addr.short_address = BROADCAST;
				wpan_mcps_data_req(FCF_SHORT_ADDR, &dst_addr,
						strlen(broadcast_payload),
						(uint8_t *)&broadcast_payload, 1,
						WPAN_TXOPT_OFF);
			}
		}

#endif /* GPIO_PUSH_BUTTON_0 */
	}
}
Exemplo n.º 14
0
/**
 * \brief Run QDEC unit tests
 *
 * Initializes the clock system, board and serial output, then sets up the
 * QDEC unit test suite and runs it.
 */
int main(void)
{
	const usart_serial_options_t usart_serial_options = {
		.baudrate   = CONF_TEST_BAUDRATE,
		.charlength = CONF_TEST_CHARLENGTH,
		.paritytype = CONF_TEST_PARITY,
		.stopbits   = CONF_TEST_STOPBITS,
	};
	sysclk_init();
	board_init();
	sleepmgr_init();

	main_delay_init();

	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

	DEFINE_TEST_CASE(qdec_common_mode, NULL,
			run_qdec_common_mode, NULL,
			"QDEC Common mode Test");
#if XMEGA_E
	DEFINE_TEST_CASE(qdec_rotary_mode, NULL,
			run_qdec_rotary_mode, NULL,
			"QDEC Rotary mode Test");
#endif
	DEFINE_TEST_CASE(qdec_index1_mode, NULL,
			run_qdec_index1_mode, NULL,
			"QDEC Index (step 1) mode Test");
	DEFINE_TEST_CASE(qdec_index2_mode, NULL,
			run_qdec_index2_mode, NULL,
			"QDEC Index (step 2) mode Test");
	DEFINE_TEST_CASE(qdec_index3_mode, NULL,
			run_qdec_index3_mode, NULL,
			"QDEC Index (step 3) mode Test");
	DEFINE_TEST_CASE(qdec_index4_mode, NULL,
			run_qdec_index4_mode, NULL,
			"QDEC Index (step 4) mode Test");
	DEFINE_TEST_CASE(qdec_freq1_mode, NULL,
			run_qdec_freq1_mode, NULL,
			"QDEC Frequency mode Test1");
	DEFINE_TEST_CASE(qdec_freq2_mode, NULL,
			run_qdec_freq2_mode, NULL,
			"QDEC Frequency mode Test2");
	DEFINE_TEST_CASE(qdec_freq3_mode, NULL,
			run_qdec_freq3_mode, NULL,
			"QDEC Frequency mode Test3");

	/* Put test case addresses in an array */
	DEFINE_TEST_ARRAY(qdec_tests) = {
		&qdec_common_mode,
#if XMEGA_E
		&qdec_rotary_mode,
#endif
		&qdec_index1_mode,
		&qdec_index2_mode,
		&qdec_index3_mode,
		&qdec_index4_mode,
		&qdec_freq1_mode,
		&qdec_freq2_mode,
		&qdec_freq3_mode,
	};

	/* Define the test suite */
	DEFINE_TEST_SUITE(qdec_suite, qdec_tests,
			"XMEGA QDEC driver test suite");

	/* Run all tests in the suite */
	test_suite_run(&qdec_suite);

	while (1) {
		/* Intentionally left empty. */
	}
}
Exemplo n.º 15
0
int main(void)
{
	struct adc_config         adc_conf;
	struct adc_channel_config adcch_conf;

	board_init();
	sysclk_init();
	sleepmgr_init();
	irq_initialize_vectors();
	cpu_irq_enable();

	// Initialize configuration structures.
	adc_read_configuration(&ADCA, &adc_conf);
	adcch_read_configuration(&ADCA, ADC_CH0, &adcch_conf);

	/* Configure the ADC module:
	 * - unsigned, 12-bit results
	 * - bandgap (1 V) voltage reference
	 * - 200 kHz maximum clock rate
	 * - manual conversion triggering
	 */
	adc_set_conversion_parameters(&adc_conf, ADC_SIGN_OFF, ADC_RES_12,
			ADC_REF_BANDGAP);
	adc_set_clock_rate(&adc_conf, 200000UL);
	adc_set_conversion_trigger(&adc_conf, ADC_TRIG_MANUAL, 1, 0);

	adc_write_configuration(&ADCA, &adc_conf);

	/* Configure ADC channel 0:
	 * - single-ended measurement from configured input pin
	 * - interrupt flag set on completed conversion
	 */
	adcch_set_input(&adcch_conf, INPUT_PIN, ADCCH_NEG_NONE,
			1);
	adcch_set_interrupt_mode(&adcch_conf, ADCCH_MODE_COMPLETE);
	adcch_disable_interrupt(&adcch_conf);

	adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);

	// Enable the ADC and do one dummy conversion.
	adc_enable(&ADCA);
	adc_start_conversion(&ADCA, ADC_CH0);
	adc_wait_for_interrupt_flag(&ADCA, ADC_CH0);

	// Light up LED 1, wait for button press.
	ioport_set_pin_low(LED1_PIN);
	wait_for_button();

	// Perform oversampling of offset.
	cal_data.offset = get_mean_sample_value();

	// Light up LED 2, wait for button press.
	ioport_set_pin_low(LED2_PIN);
	wait_for_button();

	// Perform oversampling of 0.9 V for gain calibration.
	cal_data.gain = get_mean_sample_value() - cal_data.offset;

	// Turn off LEDs.
	ioport_set_pin_high(LED1_PIN);
	ioport_set_pin_high(LED2_PIN);

	// Enable interrupts on ADC channel, then trigger first conversion.
	adcch_enable_interrupt(&adcch_conf);
	adcch_write_configuration(&ADCA, ADC_CH0, &adcch_conf);
	adc_start_conversion(&ADCA, ADC_CH0);

	do {
		// Sleep until ADC interrupt triggers.
		sleepmgr_enter_sleep();
	} while (1);
}
Exemplo n.º 16
0
/**
 * \brief Application entry point.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	char test_file_name[] = "0:sd_mmc_test.txt";
	Ctrl_status status;
	FRESULT res;
	FATFS fs;
	FIL file_object;

	const usart_serial_options_t usart_serial_options = {
		.baudrate   = CONF_TEST_BAUDRATE,
		.charlength = CONF_TEST_CHARLENGTH,
		.paritytype = CONF_TEST_PARITY,
		.stopbits   = CONF_TEST_STOPBITS,
	};

	irq_initialize_vectors();
	cpu_irq_enable();

	sysclk_init();
	board_init();
	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

	/* Initialize SD MMC stack */
	sd_mmc_init();

	printf("\x0C\n\r-- SD/MMC/SDIO Card Example on FatFs --\n\r");
	printf("-- Compiled: %s %s --\n\r", __DATE__, __TIME__);
	while (1) {
		printf("Please plug an SD, MMC or SDIO card in slot.\n\r");

		/* Wait card present and ready */
		do {
			status = sd_mmc_test_unit_ready(0);
			if (CTRL_FAIL == status) {
				printf("Card install FAIL\n\r");
				printf("Please unplug and re-plug the card.\n\r");
				while (CTRL_NO_PRESENT != sd_mmc_check(0)) {
				}
			}
		} while (CTRL_GOOD != status);

		printf("Mount disk (f_mount)...\r\n");
		memset(&fs, 0, sizeof(FATFS));
		res = f_mount(LUN_ID_SD_MMC_0_MEM, &fs);
		if (FR_INVALID_DRIVE == res) {
			printf("[FAIL] res %d\r\n", res);
			goto main_end_of_test;
		}
		printf("[OK]\r\n");

		printf("Create a file (f_open)...\r\n");
		test_file_name[0] = LUN_ID_SD_MMC_0_MEM + '0';
		res = f_open(&file_object,
				(char const *)test_file_name,
				FA_CREATE_ALWAYS | FA_WRITE);
		if (res != FR_OK) {
			printf("[FAIL] res %d\r\n", res);
			goto main_end_of_test;
		}
		printf("[OK]\r\n");

		printf("Write to test file (f_puts)...\r\n");
		if (0 == f_puts("Test SD/MMC stack\n", &file_object)) {
			f_close(&file_object);
			printf("[FAIL]\r\n");
			goto main_end_of_test;
		}
		printf("[OK]\r\n");
		f_close(&file_object);
		printf("Test successfull.\n\r");

main_end_of_test:
		printf("Please unplug the card.\n\r");
		while (CTRL_NO_PRESENT != sd_mmc_check(0)) {
		}
	}
}
Exemplo n.º 17
0
/**
 * \brief Initialize ADC driver to read the board temperature sensor.
 *
 * Initializes the board's ADC driver module and configures the ADC channel
 * connected to the onboard NTC temperature sensor ready for conversions.
 */
static void init_adc(void)
{
	// Assign and enable GPIO pin to the ADC function.
	gpio_enable_module_pin(ADC_TEMPERATURE_PIN, ADC_TEMPERATURE_FUNCTION);

	const adcifb_opt_t adcifb_opt = {
		.resolution             = AVR32_ADCIFB_ACR_RES_12BIT,
		.shtim                  = 15,
		.ratio_clkadcifb_clkadc = 2,
		.startup                = 3,
		.sleep_mode_enable      = false
	};

	// Enable and configure the ADCIFB module
	sysclk_enable_peripheral_clock(&AVR32_ADCIFB);
	adcifb_configure(&AVR32_ADCIFB, &adcifb_opt);

	// Configure the trigger (No trigger, only software trigger)
	adcifb_configure_trigger(&AVR32_ADCIFB, AVR32_ADCIFB_TRGMOD_NT, 0);

	// Enable the ADCIFB channel to NTC temperature sensor
	adcifb_channels_enable(&AVR32_ADCIFB, ADC_TEMPERATURE_CHANNEL);
}

/**
 * \brief Initializes the USART.
 *
 * Initializes the board USART ready for serial data to be transmitted and
 * received.
 */
static void init_usart(void)
{
	const usart_options_t usart_options = {
		.baudrate     = 57600,
		.charlength   = 8,
		.paritytype   = USART_NO_PARITY,
		.stopbits     = USART_1_STOPBIT,
		.channelmode  = USART_NORMAL_CHMODE
	};

	// Initialize USART in RS232 mode with the requested settings.
	sysclk_enable_peripheral_clock(USART);
	usart_init_rs232(USART, &usart_options, sysclk_get_pba_hz());
}

/**
 * \brief Initializes the PWM subsystem ready to generate the RGB LED PWM
 * waves.
 *
 * Initializes the on-chip PWM module and configures the RGB LED PWM outputs so
 * the the brightness of the three individual channels can be adjusted.
 */
static void init_pwm(void)
{
	// GPIO pin/function map for the RGB LEDs.
	gpio_enable_module_pin(LED_RED_PWMA,   LED_PWMA_FUNCTION);
	gpio_enable_module_pin(LED_GREEN_PWMA, LED_PWMA_FUNCTION);
	gpio_enable_module_pin(LED_BLUE_PWMA,  LED_PWMA_FUNCTION);

	const scif_gclk_opt_t genclk3_opt = {
		.clock_source = SCIF_GCCTRL_CPUCLOCK,
		.divider      = 8,
		.diven        = true,
	};

	// Start generic clock 3 for the PWM outputs.
	scif_start_gclk(AVR32_PM_GCLK_GCLK3, &genclk3_opt);

	// Enable RGB LED PWM.
	sysclk_enable_peripheral_clock(&AVR32_PWMA);
	pwma_config_enable(&AVR32_PWMA,EXAMPLE_PWMA_FREQUENCY,EXAMPLE_PWMA_GCLK_FREQUENCY,0); 
	pwma_set_channels_value(&AVR32_PWMA,PWM_CHANNEL_RED | PWM_CHANNEL_BLUE| PWM_CHANNEL_GREEN,255);

}

/**
 * \brief Application main loop.
 */
int main(void)
{
	board_init();
	sysclk_init();

	sysclk_enable_peripheral_clock(USART);

	// Initialize touch, ADC, USART and PWM
	init_adc();
	init_usart();
	init_pwm();
	init_touch();

	while (true) {
		uint32_t adc_data;

		// Read slider and button and update RGB led
		touch_handler();

		// Wait until the ADC is ready to perform a conversion.
		do { } while (!adcifb_is_ready(&AVR32_ADCIFB));

		// Start an ADCIFB conversion sequence.
		adcifb_start_conversion_sequence(&AVR32_ADCIFB);

		// Wait until the converted data is available.
		do { } while (!adcifb_is_drdy(&AVR32_ADCIFB));

		// Get the last converted data.
		adc_data = (adcifb_get_last_data(&AVR32_ADCIFB) & 0x3FF);

		// Write temperature data to USART
		do { } while (!usart_tx_empty(USART));
		usart_write_char(USART, (adc_data >> 8));
		do { } while (!usart_tx_empty(USART));
		usart_write_char(USART, (adc_data & 0xFF));
	}
}
Exemplo n.º 18
0
/**
 * \brief Initialize the PDCA transfer for the example.
 */
static void init_pdca(void)
{
	/* PDCA channel options */
	static const pdca_channel_config_t pdca_tx_configs = {
		.addr = (void *)event_string,
		.pid = CONF_PDCA_PID_USART_TX,
		.size = sizeof(event_string),
		.r_addr = 0,
		.r_size = 0,
		.ring = false,
		.etrig = true,
		.transfer_size = PDCA_MR_SIZE_BYTE
	};

	/* Enable PDCA module */
	pdca_enable(PDCA);

	/* Init PDCA channel with the pdca_options.*/
	pdca_channel_set_config(PEVC_ID_USER_PDCA_0, &pdca_tx_configs);

	/* Set callback for PDCA channel */
	pdca_channel_set_callback(PEVC_ID_USER_PDCA_0, pdca_tranfer_done,
			PDCA_0_IRQn, 1, PDCA_IER_TRC | PDCA_IER_TERR);

	/* Enable PDCA channel */
	pdca_channel_enable(PEVC_ID_USER_PDCA_0);
}

/**
 *  \brief Configure serial console.
 */
static void configure_console(void)
{
	const usart_serial_options_t uart_serial_options = {
		.baudrate = CONF_UART_BAUDRATE,
#ifdef CONF_UART_CHAR_LENGTH
		.charlength = CONF_UART_CHAR_LENGTH,
#endif /* CONF_UART_CHAR_LENGTH */
		.paritytype = CONF_UART_PARITY,
#ifdef CONF_UART_STOP_BITS
		.stopbits = CONF_UART_STOP_BITS,
#endif /* CONF_UART_STOP_BITS */
	};

	/* Configure console. */
	stdio_serial_init(CONF_UART, &uart_serial_options);
}

/**
 * \brief Main entry point for event example.
 */
int main(void)
{
	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

	/* Output example information */
	printf("\r\n\r\n-- Events example 2 --\r\n");
	printf("-- %s\r\n", BOARD_NAME);
	printf("-- Compiled: %s %s --\r\n", __DATE__, __TIME__);

	/* Configure pin to trigger an enent on falling edge */
	ioport_set_pin_mode(CONF_EXAMPLE_PIN_EVENT, IOPORT_MODE_PULLUP |
			IOPORT_MODE_MUX_C);
	ioport_disable_pin(CONF_EXAMPLE_PIN_EVENT);
	ioport_set_pin_sense_mode(CONF_EXAMPLE_PIN_EVENT, IOPORT_SENSE_FALLING);
	gpio_enable_pin_periph_event(CONF_EXAMPLE_PIN_EVENT);
	printf(CONF_EXAMPLE_EVENT_MSG);

	init_events();

	init_pdca();

	while (1) {
		/* Toggle LED0 every 500 ms */
		LED_Toggle(LED0);
		delay_ms(500);
	}
}
Exemplo n.º 19
0
 */
int main(void)
{
	sysclk_init();
	board_init();

	/** Initialize debug console */
	configure_console();
	
	/** Configura o timer */
	configure_tc();
	
	/* Configura os botões */
	configure_buttons();

	/** Enable peripheral clock */
	pmc_enable_periph_clk(ID_SMC);

	/** Configure SMC interface for Lcd */
	smc_set_setup_timing(SMC, ILI93XX_LCD_CS, SMC_SETUP_NWE_SETUP(2)
			| SMC_SETUP_NCS_WR_SETUP(2)
			| SMC_SETUP_NRD_SETUP(2)
			| SMC_SETUP_NCS_RD_SETUP(2));
	smc_set_pulse_timing(SMC, ILI93XX_LCD_CS, SMC_PULSE_NWE_PULSE(4)
			| SMC_PULSE_NCS_WR_PULSE(4)
			| SMC_PULSE_NRD_PULSE(10)
			| SMC_PULSE_NCS_RD_PULSE(10));
	smc_set_cycle_timing(SMC, ILI93XX_LCD_CS, SMC_CYCLE_NWE_CYCLE(10)
			| SMC_CYCLE_NRD_CYCLE(22));
#if ((!defined(SAM4S)) && (!defined(SAM4E)))
	smc_set_mode(SMC, ILI93XX_LCD_CS, SMC_MODE_READ_MODE
			| SMC_MODE_WRITE_MODE
			| SMC_MODE_DBW_8_BIT);
#else
	smc_set_mode(SMC, ILI93XX_LCD_CS, SMC_MODE_READ_MODE
			| SMC_MODE_WRITE_MODE);
#endif
	/** Initialize display parameter */
	g_ili93xx_display_opt.ul_width = ILI93XX_LCD_WIDTH;
	g_ili93xx_display_opt.ul_height = ILI93XX_LCD_HEIGHT;
	g_ili93xx_display_opt.foreground_color = COLOR_BLACK;
	g_ili93xx_display_opt.background_color = COLOR_WHITE;

	/** Switch off backlight */
	aat31xx_disable_backlight();

	/** Initialize LCD */
	ili93xx_init(&g_ili93xx_display_opt);

	/** Set backlight level */
	aat31xx_set_backlight(AAT31XX_AVG_BACKLIGHT_LEVEL);

	ili93xx_set_foreground_color(COLOR_WHITE);
	ili93xx_draw_filled_rectangle(0, 0, ILI93XX_LCD_WIDTH,
			ILI93XX_LCD_HEIGHT);
	/** Turn on LCD */
	ili93xx_display_on();
	ili93xx_set_cursor_position(0, 0);

	/** Draw text, image and basic shapes on the LCD */
	ili93xx_set_foreground_color(COLOR_BLACK);
	ili93xx_draw_string(80, 10, (uint8_t *)"13 - LCD");
	ili93xx_draw_string(10, 40, (uint8_t *)"Andre");
	ili93xx_draw_string(10, 60, (uint8_t *)"Thales");
	ili93xx_draw_string(10, 80, (uint8_t *)"Tete");
	ili93xx_set_foreground_color(COLOR_ORANGE);
	ili93xx_draw_filled_rectangle(0, 100, ILI93XX_LCD_WIDTH,105);
	ili93xx_set_foreground_color(COLOR_GREEN);
	ili93xx_draw_filled_rectangle(0, 106, ILI93XX_LCD_WIDTH,111);
	
	while (1) {
		/* Entra em modo sleep */
		pmc_sleep(SAM_PM_SMODE_SLEEP_WFI);
	}
Exemplo n.º 20
0
/**
 * \brief Application entry point for spi_touchscreen example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
    uint8_t uc_result;

    sysclk_init();
    board_init();

    configure_console();

    /* Enable clocks for push buttons management */
    pmc_enable_periph_clk(ID_PIOA);
    pmc_enable_periph_clk(ID_PIOB);
    pmc_enable_periph_clk(ID_PIOC);

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

    /* Configure systick for 1 ms. */
    puts("Configure system tick to get 1ms tick period.\r");
    if (SysTick_Config(sysclk_get_cpu_hz() / 1000)) {
        puts("Systick configuration error\r");
        while (1);
    }

    /* Switch off backlight */
    aat31xx_disable_backlight();

    lcd_init();

    lcd_set_foreground_color(UNI_COLOR_WHITE);
    lcd_draw_filled_rectangle(0, 0, LCD_WIDTH, LCD_HEIGHT);

    /* Turn on LCD */
    lcd_display_on();

    /* Switch on backlight */
    aat31xx_set_backlight(AAT31XX_MAX_BACKLIGHT_LEVEL);

    /* Initializes the PIO interrupt management for touchscreen driver */
    pio_handler_set_priority(PIOA, PIOA_IRQn, IRQ_PRIOR_PIO);
    pio_handler_set_priority(PIOB, PIOB_IRQn, IRQ_PRIOR_PIO);
    pio_handler_set_priority(PIOC, PIOC_IRQn, IRQ_PRIOR_PIO);

    /* Initialize touchscreen without calibration */
    rtouch_init(LCD_WIDTH, LCD_HEIGHT);
    rtouch_enable();
    rtouch_set_event_handler(event_handler);

    while (1) {
        uc_result = rtouch_calibrate();
        if (uc_result == 0) {
            puts("Calibration successful !\r");
            break;
        } else {
            puts("Calibration failed; error delta is too big ! Please retry calibration procedure...\r");
        }
    }

    while (1) {
    }
}
Exemplo n.º 21
0
/**
 * \brief Application entry point for PWM PDC example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{

	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Configure the console uart for debug infomation */
	configure_console();

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

/* Enable PWM peripheral clock */
	pmc_enable_periph_clk(ID_PWM);
	
	/*A Disable PWM channels
	- Register: PWM_DIS (PWM Disable)
	- Kanal 0: Motor1_X
	- Kanal 1: Motor1_Y	
	- Kanal 2: Motor1_Z
	- Kanal 3: Referenzsignals 
	*/
	pwm_channel_disable(PWM, PWM_CHANNEL_0);
	pwm_channel_disable(PWM, PWM_CHANNEL_1);
	pwm_channel_disable(PWM, PWM_CHANNEL_2);
	pwm_channel_disable(PWM, PWM_CHANNEL_3);
	
	/*A PWM-Leitungen (C.2 - C.9) im Prozessor vom
	PIO-Controller trennen und auf peripheral Funktion B setzen */

	for (int pinId = 2; pinId <= 9; pinId++) { 
		pio_set_peripheral(PIOC, PIO_TYPE_PIO_PERIPH_B, (1u << pinId));
	}
	
	/*A Clock einstellen
	- Set PWM clock A for all channels, clock B not used
	 */
	pwm_clock_t clock_setting = {
			.ul_clka = PWM_FREQUENCY * PERIOD_VALUE,
			.ul_clkb = 0,
			.ul_mck = sysclk_get_cpu_hz() // diese Funktion gibt 84 Mhz zurück!
		};
	pwm_init(PWM, &clock_setting);
	
	/*A Kanäle 0,1,2 als synchron festlegen
	*/
	// zunächst die generellen Eigenschaften der synchronen Channels initialisieren 
	pwm_channel_t sync_channel = {
		/* die Motor Kanäle sollen alle Center aligned sein */
		.alignment = PWM_ALIGN_CENTER,
		/* die Motor Kanäle sollen mit Low Polarität starten */
		.polarity = PWM_LOW,
		/* Alle Motor Kanäle sollen Clock A verwenden, da sie mit doppelter Basisfrequenz getaktet werden müssen wegen Center aligned */
		.ul_prescaler = PWM_CMR_CPRE_CLKA,
		/* Periode einstellen */
		.ul_period = PERIOD_VALUE,
		/* Duty cycle initial setzen */
		.ul_duty = INIT_DUTY_VALUE,
		/* der channel soll synchron sein */
		.b_sync_ch = true,
		 
		 .b_deadtime_generator = true,
		 
		 .us_deadtime_pwmh = 1,
		 
		 .us_deadtime_pwml = 1 
	};

	/* als erstes dann den Channel 0 initialisieren, indem nur das Channel Attribut in der Struktur von oben neu gesetzt wird,
	der REst bleibt gleich...
	*/
	sync_channel.channel = PWM_CHANNEL_0;
	pwm_channel_init(PWM, &sync_channel);
	// das gleiche dann mit den beiden anderen zu synchronisierenden Channels
	sync_channel.channel = PWM_CHANNEL_1;
	pwm_channel_init(PWM, &sync_channel);
	sync_channel.channel = PWM_CHANNEL_2;
	pwm_channel_init(PWM, &sync_channel);

	/*
	 * Initialize PWM synchronous channels
	 * Synchronous Update Mode: Automatic update duty cycle value by the PDC
	 * and automatic update of synchronous channels. The update occurs when
	 * the Update Period elapses (MODE 2 --> Vorsicht vor Verwirrung: dies entspricht der "Methode 3" aus dem Datasheet!).
	 * Synchronous Update Period = MAX_SYNC_UPDATE_PERIOD.
	 */
	pwm_sync_init(PWM, PWM_SYNC_UPDATE_MODE_2, MAX_SYNC_UPDATE_PERIOD);

	/*
	 * Request PDC transfer as soon as the synchronous update period elapses
	 */
	pwm_pdc_set_request_mode(PWM, PWM_PDC_UPDATE_PERIOD_ELAPSED, (1 << 0));
	
	/* Aktiviere alle synchronen channel durch aktivieren von channel 0, channel 1 und 2 werden automatisch synchron mit gestartet 
	zusätzlich noch den Refernzchannel "synchron" mitstarten
	die ASF funktion channel_enable erlaubt leider nur die Übergabe eines Kanals, also müssen wir hier wohl mit direktem Zugriff auf das Register arbeiten */
	pwm_channel_enable(PWM, PWM_CHANNEL_0);
  // ref channel funktioniert noch nicht, muss noch debugged werden  pwm_channel_enable(PWM, PWM_CHANNEL_3);
  
  pmc_enable_periph_clk(ID_PIOA);
  pio_set_output(PIOA, PIO_PA23, LOW, DISABLE, ENABLE);
  
  int angle = 0;
  int up = 1;
  float sinus = 0;
  float a;
  
	while (1) {
		
		pio_set(PIOA, PIO_PA23);
		for (int i = 0; i < 1000; i++)
		{
			sinus = sin(0.343543);
			a = sinus;
		}
		
		pio_clear(PIOA, PIO_PA23);
		delay_us(4);
		
		
		/*display_menu();
		uint32_t angle = get_num_value();
		struct SV pwm = get_vector_for_angle(angle);
		SVPWM(pwm.u, pwm.v, pwm.w);
		printf("The angle is %i degrees.", angle);
		
		for (int i = 0; i <= 360; i++) {
			struct SV pwm = get_vector_for_angle(i);
			SVPWM(pwm.u, pwm.v, pwm.w);
			printf("%i Grad\r\n", i);
			delay_ms(40);
			
		}
		for (int i = 360; i >= 0; i--) {
			struct SV pwm = get_vector_for_angle(i);
			SVPWM(pwm.u, pwm.v, pwm.w);
			printf("%i Grad\r\n", i);
			delay_ms(40);
			
		}*/
	}
}
Exemplo n.º 22
0
/*! \brief Main function. Execution starts here.
 */
int main(void)
{
#if SAMD21 || SAML21
	system_init();
#else
	sysclk_init();
	board_init();
#endif
	irq_initialize_vectors();
	cpu_irq_enable();

	// Initialize the sleep manager
	sleepmgr_init();

	ui_init();

	// Start USB host stack
	uhc_start();

	// The USB management is entirely managed by interrupts.
	// As a consequence, the user application does only have :
	// - to play with the power modes
	// - to create a file on each new LUN connected
	while (true) {
		//sleepmgr_enter_sleep();
		if (main_usb_sof_counter > 2000) {
			main_usb_sof_counter = 0;
			volatile uint8_t lun;
			FRESULT res;

			for (lun = LUN_ID_USB; (lun < LUN_ID_USB +
					uhi_msc_mem_get_lun()) &&
					(lun < MAX_DRIVE); lun++) {
				// Check if LUN has been already tested
				if (TEST_OK == lun_states[lun] ||
						TEST_ERROR == lun_states[lun]) {
					continue;
				}
				// Mount drive
				memset(&fs, 0, sizeof(FATFS));
				res = f_mount(lun, &fs);
				if (FR_INVALID_DRIVE == res) {
					// LUN is not present
					lun_states[lun] = TEST_NO_PRESENT;
					continue;
				}
				// Create a test file on the disk
				test_file_name[0] = lun + '0';
				res = f_open(&file_object,
						(char const *)test_file_name,
						FA_CREATE_ALWAYS | FA_WRITE);
				if (res == FR_NOT_READY) {
					// LUN not ready
					lun_states[lun] = TEST_NO_PRESENT;
					f_close(&file_object);
					continue;
				}
				if (res != FR_OK) {
					// LUN test error
					lun_states[lun] = TEST_ERROR;
					f_close(&file_object);
					continue;
				}
				// Write to test file
				f_puts(MSG_TEST, &file_object);
				// LUN test OK
				lun_states[lun] = TEST_OK;
				f_close(&file_object);
			}
			if (main_count_states(TEST_NO_PRESENT) == MAX_DRIVE) {
				ui_test_finish(false); // Test fail
			} else if (MAX_DRIVE != main_count_states(TEST_NULL)) {
				if (main_count_states(TEST_ERROR)) {
					ui_test_finish(false); // Test fail
				} else if (main_count_states(TEST_OK)) {
					ui_test_flag_reset();
					ui_test_finish(true); // Test OK
				}
			} else {
				ui_test_flag_reset();
			}
		}
	}
}
Exemplo n.º 23
0
/**
 * \brief Application entry point for ABDAC example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint8_t key;
	uint32_t i, count;
	status_code_t status;

	/* Initialize the SAM system. */
	sysclk_init();
	board_init();

	/* Initialize the UART console. */
	configure_console();

	/* Output example information */
	printf("-- ABDAC Example --\r\n");
	printf("-- %s\r\n", BOARD_NAME);
	printf("-- Compiled: %s %s --\r\n", __DATE__, __TIME__);

	/* Config the push button. */
	config_buttons();

	/* Config the ABDAC. */
	abdac_get_config_defaults(&g_abdac_cfg);
	g_abdac_cfg.sample_rate_hz = ABDAC_SAMPLE_RATE_11025;
	g_abdac_cfg.data_word_format = ABDAC_DATE_16BIT;
	g_abdac_cfg.mono = false;
	g_abdac_cfg.cmoc = false;
	status = abdac_init(&g_abdac_inst, ABDACB, &g_abdac_cfg);
	if (status != STATUS_OK) {
		printf("-- Initialization fails! --\r\n");
		while (1) {
		}
	}
	abdac_enable(&g_abdac_inst);
	abdac_clear_interrupt_flag(&g_abdac_inst, ABDAC_INTERRUPT_TXRDY);
	abdac_clear_interrupt_flag(&g_abdac_inst, ABDAC_INTERRUPT_TXUR);

	/* Config PDCA module */
	pdca_enable(PDCA);
	pdca_channel_set_config(PDCA_ABDAC_CHANNEL0, &pdca_abdac_config0);
	pdca_channel_enable(PDCA_ABDAC_CHANNEL0);
	pdca_channel_set_config(PDCA_ABDAC_CHANNEL1, &pdca_abdac_config1);
	pdca_channel_enable(PDCA_ABDAC_CHANNEL1);

	/* Display menu. */
	display_menu();

	while (1) {
		scanf("%c", (char *)&key);

		switch (key) {
		case 'h':
			display_menu();
			break;

		case 's':
			printf("--Looped output audio, use push button to exit--\r\n");
			abdac_set_volume0(&g_abdac_inst, false, 0x7FFF);
			abdac_set_volume1(&g_abdac_inst, false, 0x7FFF);
			i = 0;
			/* output sample from the sound_table array */
			while(!exit_flag) {
				count = 0;
				// Store sample from the sound_table array
				while(count < (SOUND_SAMPLES)){
					samples_left[count] = ((uint8_t)sound_table[i]) << 8;
					samples_right[count] = ((uint8_t)sound_table[i]) << 8;
					i++;
					count++;
					if (i >= sizeof(sound_table)) i = 0;
				}

				pdca_channel_write_reload(PDCA_ABDAC_CHANNEL0,
						(void *)samples_left, SOUND_SAMPLES);
				pdca_channel_write_reload(PDCA_ABDAC_CHANNEL1,
						(void *)samples_right, SOUND_SAMPLES);
				/**
				 * Wait until the reload register is empty. This means that
				 * one transmission is still ongoing but we are already able
				 * to set up the next transmission.
				 */
				while(!(pdca_get_channel_status(PDCA_ABDAC_CHANNEL1)
					== PDCA_CH_COUNTER_RELOAD_IS_ZERO));
			}
			exit_flag = false;
			printf("--Exit the audio output--\r\n\r\n");
			/* Mute the volume */
			abdac_set_volume0(&g_abdac_inst, true, 0x7FFF);
			abdac_set_volume1(&g_abdac_inst, true, 0x7FFF);
			break;

		default:
			break;
		}
	}
}
Exemplo n.º 24
0
/**
 * \brief Application entry point for RTC tamper example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	uint32_t ul_read_value[8] = {0, 0 ,0, 0, 0, 0, 0, 0};
	uint32_t ul_hour0, ul_minute0, ul_second0;
	uint32_t ul_year0, ul_month0, ul_day0, ul_week0;
	uint32_t ul_hour1, ul_minute1, ul_second1;
	uint32_t ul_year1, ul_month1, ul_day1, ul_week1;
	uint32_t tmp_src0, tmp_src1, tmp_cnt;
	uint8_t uc_key;

	/* Initialize the SAM system */
	sysclk_init();
	board_init();

	/* Initialize the console uart */
	configure_console();

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

	/* Default RTC configuration, 24-hour mode */
	rtc_set_hour_mode(RTC, 0);
	rtc_set_waveform(RTC, RTC_OUT_CHN, RTC_OUT_SRC);

	if(rstc_get_reset_cause(RSTC) == RSTC_SR_RSTTYP_BackupReset) {
		/* Read the data from GPBR0 ~ 7 */
		ul_read_value[0] = gpbr_read(GPBR0);
		ul_read_value[1] = gpbr_read(GPBR1);
		ul_read_value[2] = gpbr_read(GPBR2);
		ul_read_value[3] = gpbr_read(GPBR3);
		ul_read_value[4] = gpbr_read(GPBR4);
		ul_read_value[5] = gpbr_read(GPBR5);
		ul_read_value[6] = gpbr_read(GPBR6);
		ul_read_value[7] = gpbr_read(GPBR7);

		if((ul_read_value[0] == 0) &&
				(ul_read_value[1] == 0) &&
				(ul_read_value[2] == 0) &&
				(ul_read_value[3] == 0) &&
				(ul_read_value[4] == 0) &&
				(ul_read_value[5] == 0) &&
				(ul_read_value[6] == 0) &&
				(ul_read_value[7] == 0)) {
			printf("The backup register is cleared when tamper event happen!\r\n");
		} else {
			printf("The backup register is not cleared when tamper event happen!\r\n");
		}

		/* Retrieve tamper date and time */
		rtc_get_tamper_time(RTC, &ul_hour0, &ul_minute0, &ul_second0, 0);
		rtc_get_tamper_date(RTC, &ul_year0, &ul_month0, &ul_day0, &ul_week0, 0);
		rtc_get_tamper_time(RTC, &ul_hour1, &ul_minute1, &ul_second1, 1);
		rtc_get_tamper_date(RTC, &ul_year1, &ul_month1, &ul_day1, &ul_week1, 1);
		tmp_cnt = rtc_get_tamper_event_counter(RTC);
		tmp_src0 = rtc_get_tamper_source(RTC, 0);
		tmp_src1 = rtc_get_tamper_source(RTC, 1);
		printf("The first tamper event TMP%u happen in %02u:%02u:%02u,%02u/%02u/%04u\r\n",
				(unsigned int)tmp_src0, (unsigned int)ul_hour0, (unsigned int)ul_minute0,
				(unsigned int)ul_second0, (unsigned int)ul_month0, (unsigned int)ul_day0,
				(unsigned int)ul_year0);
		printf("The last tamper event TMP%u happen in %02u:%02u:%02u,%02u/%02u/%04u\r\n",
				(unsigned int)tmp_src1, (unsigned int)ul_hour1, (unsigned int)ul_minute1,
				(unsigned int)ul_second1, (unsigned int)ul_month1, (unsigned int)ul_day1,
				(unsigned int)ul_year1);
		printf("The tamper event counter is %u \r\n", (unsigned int)tmp_cnt);
	}

	printf("Press any key to Enter Backup Mode!\r\n");

	while (uart_read(CONSOLE_UART, &uc_key));

	/* Write the data to the backup register GPBR0 ~ 7 */
	gpbr_write(GPBR0, GPBR_CONST_DATA);
	gpbr_write(GPBR1, GPBR_CONST_DATA);
	gpbr_write(GPBR2, GPBR_CONST_DATA);
	gpbr_write(GPBR3, GPBR_CONST_DATA);
	gpbr_write(GPBR4, GPBR_CONST_DATA);
	gpbr_write(GPBR5, GPBR_CONST_DATA);
	gpbr_write(GPBR6, GPBR_CONST_DATA);
	gpbr_write(GPBR7, GPBR_CONST_DATA);

	/* Enable TMP0 and TMP2 low power debouncer and clear GPBR when event happen */
	supc_set_wakeup_mode(SUPC, SUPC_WUMR_LPDBCEN0_ENABLE |
			SUPC_WUMR_LPDBCCLR_ENABLE | SUPC_WUMR_LPDBCEN2_ENABLE |
			SUPC_WUMR_LPDBC_2_RTCOUT0);
	/* Enable TMP0 and TMP2 wake-up input and set input type*/
	supc_set_wakeup_inputs(SUPC, SUPC_WUIR_WKUPEN0_ENABLE |
			SUPC_WUIR_WKUPEN14_ENABLE,
			SUPC_WUIR_WKUPT0_LOW | SUPC_WUIR_WKUPT14_LOW);

	printf("Enter Backup Mode!\r\n");
	printf("Please press button TMP0 or TMP2 to wake up!\r\n\r\n");

	/* Ensure TX is done before enter backup mode */
	while (!uart_is_tx_empty(CONSOLE_UART)) {
	}

	/* Enter backup mode */
	pmc_enable_backupmode();

	while (1) {
	}
}
Exemplo n.º 25
0
/** \brief This function is the entry function for an example application that
           uses the SHA204 ASF component.
 * \return result (0: success, otherwise failure)
 */
int main(void)
{
	static uint8_t tx_buffer_command[CHECKMAC_COUNT]; // biggest command in this example
	static uint8_t rx_buffer[SHA204_RSP_SIZE_MAX];
	static uint8_t challenge[MAC_CHALLENGE_SIZE];
	static uint8_t other_data[CHECKMAC_OTHER_DATA_SIZE];
	uint8_t sha204_lib_return = SHA204_SUCCESS;
	uint32_t loop_count = 0;
	uint8_t i2c_address_index = 0;
	uint8_t twi_address_client;
	uint8_t twi_address_host;

    // Initialize system clock.
	sysclk_init();

	// Initialize board.
	board_init();

	// Initialize logging (USART).
	log_init();

	// Initialize interrupt vectors.
	irq_initialize_vectors();

	// Send example info.
	log_sha204_title("ATSHA204 Mac / CheckMac Example\r\n");

	// Indicate entering main loop.
	led_display_number(0xFF);
	sha204h_delay_ms(1000);

	// The main loop wakes up all four devices, sends a Mac command to one serving
	// as a client, and subsequently a CheckMac command with the Mac challenge and response data
	// to another SHA204 serving as a host. At the end of the loop, all four devices
	// are put back to sleep by sending a Sleep command to every one of them.
	while (true) {
		// Indicate success or error for some time.
		led_display_number(sha204_lib_return);
		sha204h_delay_ms(1000);

		log_sha204_title("----------------------");
		sprintf((char *) tx_buffer_command, "loop count = %lu", loop_count++);
		log_sha204_title((char *) tx_buffer_command);

		// Indicate that Mac / CheckMac command sequence is running.
		led_display_number(0xFF);

		// Generate Wakeup pulse. All SHA204 devices that share SDA will wake up.
		log_sha204_title("generating 60 us Wakeup low pulse on TWI SDA");
		sha204_lib_return = sha204p_wakeup();
	    if (sha204_lib_return != SHA204_SUCCESS) {
			// todo Indicate Wakeup failure.
			continue;		 
	    }
		// Exercise all four devices.
		twi_address_client = sha204_i2c_address(i2c_address_index % 4);
		i2c_address_index++;
		twi_address_host = sha204_i2c_address(i2c_address_index % 4);
		i2c_address_index++;

		// ---------------------------------------------------------------------------------
		// Now let's send a Mac to one SHA204, and verify the generated Mac with a second
		// SHA204 serving as a host device. In this example, we are not using the Nonce
		// command but the least secure and simplest mode.

		// Let host generate a random number to use as Mac challenge. An unlocked SHA204
		// will always generate "FFFF0000FFFF0000...".
		struct sha204_random_parameters random;
		random.mode = 0;
		random.tx_buffer = tx_buffer_command;
		random.rx_buffer = rx_buffer;
		sha204p_set_device_id(twi_address_host);
		log_sha204_title("sending Random command to host");
		sha204_lib_return = sha204m_random(&random);
		log_sha204(random.tx_buffer[SHA204_COUNT_IDX], random.tx_buffer, false);
	    if (sha204_lib_return != SHA204_SUCCESS) {
			sha204_sleep_all();
			continue;
	    }
		log_sha204(random.rx_buffer[SHA204_COUNT_IDX], random.rx_buffer, true);

		// Save challenge for subsequent CheckMac command.
		memcpy(challenge, &random.rx_buffer[SHA204_BUFFER_POS_DATA], sizeof(challenge));

		// Send Mac command to client.
		struct sha204_mac_parameters mac;
		mac.mode = 0;
		mac.key_id = 0;
		mac.challenge = challenge;
		mac.tx_buffer = tx_buffer_command;
		mac.rx_buffer = rx_buffer;
		sha204p_set_device_id(twi_address_client);
		log_sha204_title("sending Mac command to client");
		sha204_lib_return = sha204m_mac(&mac);
		log_sha204(mac.tx_buffer[SHA204_COUNT_IDX], mac.tx_buffer, false);
	    if (sha204_lib_return != SHA204_SUCCESS) {
			sha204_sleep_all();
			continue;
	    }
		log_sha204(mac.rx_buffer[SHA204_COUNT_IDX], mac.rx_buffer, true);

		// Save first four bytes of Mac command for subsequent CheckMac command.
		memset(other_data, 0, CHECKMAC_OTHER_DATA_SIZE);
		memcpy(other_data, &tx_buffer_command[SHA204_OPCODE_IDX], CHECKMAC_CLIENT_COMMAND_SIZE);

		// Send CheckMac command to host.
		struct sha204_check_mac_parameters check_mac;
		check_mac.mode = 0;
		check_mac.key_id = 0;
		check_mac.client_challenge = challenge;
		check_mac.client_response = &rx_buffer[SHA204_BUFFER_POS_DATA];
		check_mac.other_data = other_data;
		check_mac.tx_buffer = tx_buffer_command;
		check_mac.rx_buffer = rx_buffer;
		sha204p_set_device_id(twi_address_host);
		log_sha204_title("sending CheckMac command to host");
		sha204_lib_return = sha204m_check_mac(&check_mac);
		log_sha204(check_mac.tx_buffer[SHA204_COUNT_IDX], check_mac.tx_buffer, false);
	    if (sha204_lib_return != SHA204_SUCCESS) {
			sha204_sleep_all();
			continue;
	    }
		log_sha204(check_mac.rx_buffer[SHA204_COUNT_IDX], check_mac.rx_buffer, true);

		log_sha204_title("sending a Sleep command to all devices");
		sha204_sleep_all();
		
		// Display response status byte.
		sha204_lib_return = check_mac.rx_buffer[SHA204_BUFFER_POS_STATUS];
	}	

	return sha204_lib_return;
}
Exemplo n.º 26
0
/* ! \brief Set up and run the test suite */
int main(void)
{
	const usart_serial_options_t usart_serial_options = {
		.baudrate     = CONF_TEST_BAUDRATE,
		.charlength   = CONF_TEST_CHARLENGTH,
		.paritytype   = CONF_TEST_PARITY,
		.stopbits     = CONF_TEST_STOPBITS,
	};

	sysclk_init();
	board_init();
	pmic_init();
	sleepmgr_init();
	stdio_serial_init(CONF_TEST_USART, &usart_serial_options);

	/* Enable low level interrupts */
	pmic_enable_level(PMIC_LVL_LOW);

	/* Enable interrupt requests */
	cpu_irq_enable();

	DEFINE_TEST_CASE(memory_copy_burst_length_test,
			NULL, run_edma_memory_copy_burst_length_test, NULL,
			"Memory copy and burst lengths");

	DEFINE_TEST_CASE(standard_config_interface_test,
			NULL, run_edma_standard_config_interface_test, NULL,
			"Write and read conf param for stdCH");

	DEFINE_TEST_CASE(peripheral_config_interface_test,
			NULL, run_edma_peripheral_config_interface_test, NULL,
			"Write and read conf param for perCH");

	DEFINE_TEST_CASE(trigger_callback_test,
			NULL, run_edma_triggered_with_callback, NULL,
			"External trigger and EDMA callback");

	DEFINE_TEST_CASE(error_handling_test,
			NULL, run_edma_error_handling_test, NULL,
			"Error handling by the module");

	DEFINE_TEST_CASE(search_and_double_buffer_test,
			NULL, run_edma_search_dbuf_test, NULL,
			"SEARCH and DOUBLE BUFFER modes");

	DEFINE_TEST_ARRAY(edma_tests) = {
		&memory_copy_burst_length_test,
		&standard_config_interface_test,
		&peripheral_config_interface_test,
		&trigger_callback_test,
		&error_handling_test,
		&search_and_double_buffer_test
	};

	DEFINE_TEST_SUITE(edma_suite,
			edma_tests,
			"XMEGA EDMA driver test suite");

	test_suite_run(&edma_suite);

	while (1) {
		/* Intentionally left empty */
	}
}
Exemplo n.º 27
0
/**
 * \brief Main function.
 */
int main(void)
{
	enum ac_status_t status;

	pmic_init();
	board_init();
	sysclk_init();
	sleepmgr_init();

	ac_set_interrupt_callback(&ACA, example_aca_interrupt_callback);


	/* Setup the analog comparator B in window mode. */
	ac_set_mode(&aca_config, AC_MODE_WINDOW);
	ac_set_voltage_scaler(&aca_config, 11);
	ac_set_hysteresis(&aca_config, AC_HYSMODE_LARGE_gc);
	ac_set_negative_reference(&aca_config, AC_MUXNEG_SCALER_gc);
	ac_set_positive_reference(&aca_config, AC_MUXPOS_PIN1_gc);
	ac_set_interrupt_mode(&aca_config, AC_INT_MODE_INSIDE_WINDOW);
	ac_set_interrupt_level(&aca_config, AC_INT_LVL_MED);

	/*
	 * Write configuration of analog comparator B channel 0, half of window
	 * configuration.
	 */
	ac_write_config(&ACA, 0, &aca_config);

	/* Set the lower reference of the compare window. */
	ac_set_negative_reference(&aca_config, AC_MUXNEG_BANDGAP_gc);

	/*
	 * Write configuration of analog comparator B channel 1, other half of
	 * window configuration.
	 */
	ac_write_config(&ACA, 1, &aca_config);

	/* Enable all the analog comparator channels. */
	ac_enable(&ACA, 0);
	ac_enable(&ACA, 1);

	/*
	 * Wait for analog comparator to stabilize (muxing, voltage scaler,
	 * bandgap voltage, etc).
	 */
	mdelay(1);

	/* Check comparator status and initialize the LEDs. */
	status = ac_get_status(&ACA, 0);
	example_ac_update_window_leds(status);

	/*
	 * Read back analog comparator channel 0 configuration, to be used when
	 * updating the window interrupt mode in the interrupt callback
	 * function.
	 */
	ac_read_config(&ACA, 0, &aca_config);

	cpu_irq_enable();

	for (;;) {
		/* Go to sleep, everything is handled by interrupts. */
		sleepmgr_enter_sleep();
	}
}
Exemplo n.º 28
0
//! The main function
int main(int argc, char *argv[])
{
	dsp32_t number, result;
	int cycle_count;
	char sin_result[50], cos_result[50], asin_result[50], acos_result[50],
			rand_result[50], sqrt_result[50], abs_result[50], ln_result[50],
			log2_result[50], log10_result[50], exp_result[50], pow_result[50];
	/**
	 * \note the call to sysclk_init() will disable all non-vital
	 * peripheral clocks, except for the peripheral clocks explicitly
	 * enabled in conf_clock.h.
	 */
	sysclk_init();

	// Initialize the DSP debug USART module when running in external board
#if BOARD != AVR_SIMULATOR_UC3
	dsp_debug_initialization(FOSC0);
#endif

	number = DSP32_Q(NUMBER_TO_COMPUTE);
	/*
	 * Place a breakpoint on sprintf and check the ASCII output in
	 * %operator%_result in Watch Window or Memory Window.
	 * Note: Edit the variable name in Watch Window and append
	 * "&" at the start and ",s" at the end for displaying string.
	 * Read Watch Window Format Specifiers for more info.
	 */
	// 32-bit fixed point cosine
	cycle_count = Get_sys_count();
	result = dsp32_op_cos(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(cos_result, "cos(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point sine
	cycle_count = Get_sys_count();
	result = dsp32_op_sin(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(sin_result, "sin(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point arc cosine
	cycle_count = Get_sys_count();
	result = dsp32_op_acos(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(acos_result, "acos(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point arc sine
	cycle_count = Get_sys_count();
	result = dsp32_op_asin(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(asin_result, "asin(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point random
	dsp_op_srand(number);
	cycle_count = Get_sys_count();
	result = dsp32_op_rand();
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(rand_result, "rand() %f (%i cycles)\n", result,
			cycle_count);

	// 32-bit fixed point square root
	cycle_count = Get_sys_count();
	result = dsp32_op_sqrt(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(sqrt_result, "sqrt(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point absolute
	cycle_count = Get_sys_count();
	result = dsp32_op_abs(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(abs_result, "abs(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point natural logarithm
	cycle_count = Get_sys_count();
	result = dsp32_op_ln(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(ln_result, "ln(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point binary logarithm
	cycle_count = Get_sys_count();
	result = dsp32_op_log2(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(log2_result, "log2(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point common logarithm
	cycle_count = Get_sys_count();
	result = dsp32_op_log10(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(log10_result, "log10(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point exponential
	cycle_count = Get_sys_count();
	result = dsp32_op_exp(number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(exp_result, "exp(%f) %f (%i cycles)\n", number,
			result, cycle_count);

	// 32-bit fixed point power
	cycle_count = Get_sys_count();
	result = dsp32_op_pow(DSP32_Q(0.), number);
	cycle_count = Get_sys_count() - cycle_count;
	dsp32_debug_sprintf(pow_result, "pow(0.5, %f) %f (%i cycles)\n", number,
			result, cycle_count);

	while (1) {
		// Intentionally left blank.
	}
}
Exemplo n.º 29
0
int main(void)
{
		/*Status flags to indicate the re-burst for library */
	uint16_t status_flag = 0u;
	uint16_t burst_flag = 0u;

	uint8_t lft_pressed = 0;
	uint8_t rgt_pressed = 0;

	static uint8_t old_position = 0;

	uint8_t uc_char;
	uint8_t uc_flag;
	sysclk_init();
	board_init();
	configure_buttons();
	configure_hall();

	wdt_disable(WDT);
	pmc_enable_periph_clk(ID_PIOC);
	qt_reset_sensing();
	config_sensors();
	qt_init_sensing();
	/* Set the parameters like recalibration threshold, Max_On_Duration etc in this function by the user */
	qt_set_parameters();
	init_timer_isr();
	qt_filter_callback = 0;

	configure_console();
	printf(STRING_HEADER);
	
	configure_lcd();
	g_pwm_channel = configure_pwm();

	/* Cabeçalho do lcd */
	pos_lcd_x = 20;
	pos_lcd_y = 40;
	start_lcd(pos_lcd_x, pos_lcd_y, ul_duty, hall_1, hall_2, hall_3, phase);

	/* Infinite loop */
	while (1) {
		static uint8_t phase_aux;
		static uint32_t hall_1_aux, hall_2_aux, hall_3_aux, ul_duty_aux;

		/* Atualiza o display somente quando houver alteração nas variáveis que serão apresentadas */
		
		if(ul_duty_aux != ul_duty)
		{
			escreve_int_lcd("dc = ", ul_duty*100/PERIOD_VALUE, pos_lcd_x, 40);
			ul_duty_aux = ul_duty;
		}
		
		if(phase_aux != phase || hall_1_aux != hall_1 || hall_2_aux != hall_2 || hall_3_aux != hall_3)
		{
			escreve_int_lcd("hall1 = ", hall_1, pos_lcd_x, 60);
			escreve_int_lcd("hall2 = ", hall_2, pos_lcd_x, 80);
			escreve_int_lcd("hall3 = ", hall_3, pos_lcd_x, 100);
			escreve_int_lcd("phase = ", phase, pos_lcd_x, 120);

			phase_aux = phase;
			hall_1_aux = hall_1;
			hall_2_aux = hall_2;
			hall_3_aux = hall_3;
		}
		
		if(motor_run == 0 && ul_duty != 0)
			Hall_Phase();
		
		uc_char = 0;
		uc_flag = uart_read(CONSOLE_UART, &uc_char);
		if (!uc_flag) {
			if (uc_char == 't') {
				printf("   duty cicle = %lu \r\n",ul_duty*100/PERIOD_VALUE);
				printf("   hall1 = %lu \r\n", hall_1);
				printf("   hall2 = %lu \r\n", hall_2);
				printf("   hall3 = %lu \r\n", hall_3);
				printf("   phase = %u \r\n\n", phase);
			}
			if (uc_char == 'a'){				
				if(ul_duty < PERIOD_VALUE) ul_duty++;
				printf("   duty cicle = %lu \r\n",ul_duty*100/PERIOD_VALUE);
			}
			if (uc_char == 's'){
				if(ul_duty > INIT_DUTY_VALUE) ul_duty--;
				printf("   duty cicle = %lu \r\n",ul_duty*100/PERIOD_VALUE);
			}
			if (uc_char == 'd')
			{
				ensaio = 1;
				printf("   Ensaio de rampa\r\n");
				printf("   para parar pressione a letra 'P'\r\n");	
			}
			if (uc_char == 'f')
			{
				ensaio = 2;
				printf("   Ensaio de degrau\r\n");
				printf("   para parar pressione a letra 'P'\r\n");
			}
			if (uc_char == 'p')
			{
				ensaio = 0;
				ul_duty = 0;
			}
			if (uc_char == 'i')
			{
				sel_rot = !sel_rot;
				printf("   Rotacao invertida\r\n");
				printf("   para parar pressione a letra 'P'\r\n");
			}
		}
		
		if (time_to_measure_touch) {

			/* Clear flag: it's time to measure touch */
			time_to_measure_touch = 0u;

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

				burst_flag = status_flag & QTLIB_BURST_AGAIN;

				/*Time critical host application code goes here */

			} while (burst_flag);
		}

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


		if ((GET_SENSOR_STATE(BOARD_LEFT_KEY_ID) != 0)
		&& (lft_pressed == 0)) {
			lft_pressed = 1;
			if(ul_duty > INIT_DUTY_VALUE) ul_duty--;
			printf("  duty cicle = %lu \r\n",ul_duty*100/PERIOD_VALUE);
			} else {
			if ((GET_SENSOR_STATE(BOARD_LEFT_KEY_ID) == 0)
			&& (lft_pressed == 1)) {
				lft_pressed = 0;
			}
		}
		if ((GET_SENSOR_STATE(BOARD_RIGHT_KEY_ID) != 0)
		&& (rgt_pressed == 0)) {
			rgt_pressed = 1;
			if(ul_duty < PERIOD_VALUE) ul_duty++;
			printf("  duty cicle = %lu \r\n",ul_duty*100/PERIOD_VALUE);
			} else {
			if ((GET_SENSOR_STATE(BOARD_RIGHT_KEY_ID) == 0)
			&& (rgt_pressed == 1)) {
				rgt_pressed = 0;
			}
		}


		if (GET_ROTOR_SLIDER_POSITION(0) != old_position) {
			old_position = GET_ROTOR_SLIDER_POSITION(0);
			if (motor_run==0) flag_hab_m = 1;
			ul_duty = old_position*PERIOD_VALUE/255;
		}
	}
}
Exemplo n.º 30
0
/**
 * \brief Main Application Routine
 *  - Initialize the system clocks
 *  - Initialize the sleep manager
 *  - Initialize the power save measures
 *  - Initialize the ACIFB module
 *  - Initialize the AST to trigger ACIFB at regular intervals
 *  - Go to STATIC sleep mode and wake up on a touch status change
 */
int main(void)
{
	/* Switch on the STATUS LED */
	gpio_clr_gpio_pin(STATUS_LED);
	/* Switch off the error LED. */
	gpio_set_gpio_pin(ERROR_LED);

	/*
	 * Initialize the system clock.
	 * Note: Clock settings are specified in conf_clock.h
	 */
	sysclk_init();

	/*
	 * Initialize the sleep manager.
	 * Note: CONFIG_SLEEPMGR_ENABLE should have been defined in conf_sleepmgr.h
	 */
	sleepmgr_init();
	/* Lock required sleep mode. */
	sleepmgr_lock_mode(SLEEPMGR_STATIC);

	/* Initialize the delay routines */
	delay_init(sysclk_get_cpu_hz());

	/* Initialize the power saving features */
	power_save_measures_init();

	/* Switch off the error LED. */
	gpio_set_gpio_pin(ERROR_LED);

#if DEBUG_MESSAGES
	/* Enable the clock to USART interface */
	sysclk_enable_peripheral_clock(DBG_USART);
	/* Initialize the USART interface to print trace messages */
	init_dbg_rs232(sysclk_get_pba_hz());

	print_dbg("\r Sleepwalking with ACIFB Module in UC3L \n");
	print_dbg("\r Initializing ACIFB Module..... \n");
#endif

	/* Initialize the Analog Comparator peripheral */
	if (ac_init() != STATUS_OK) {
#if DEBUG_MESSAGES
		/* Error initializing the ACIFB peripheral */
		print_dbg("\r Error initializing Analog Comparator module \n");
#endif
		while (1) {
			delay_ms(LED_DELAY);
			gpio_tgl_gpio_pin(ERROR_LED);
		}
	}

#if DEBUG_MESSAGES
	print_dbg("\r ACIFB Module initialized. \n");
	print_dbg("\r Initializing AST Module..... \n");
#endif

	/* Initialize the AST peripheral */
	if (ast_init() != STATUS_OK) {
#if DEBUG_MESSAGES
		print_dbg("\r Error initializing AST module \n");
#endif
		/* Error initializing the AST peripheral */
		while (1) {
			delay_ms(LED_DELAY);
			gpio_tgl_gpio_pin(ERROR_LED);
		}
	}

#if DEBUG_MESSAGES
	print_dbg("\r AST Module initialized. \n");
#endif

	/* Application routine */
	while (1) {
		/* Enable Asynchronous wake-up for ACIFB */
		pm_asyn_wake_up_enable(AVR32_PM_AWEN_ACIFBWEN_MASK);

#if DEBUG_MESSAGES
		print_dbg("\r Going to STATIC sleep mode \n");
		print_dbg(
				"\r Wake up only when input is higher than threshold \n");
#endif

		/* Switch off the status LED */
		gpio_set_gpio_pin(STATUS_LED);
		/* Disable GPIO clock before entering sleep mode */
		sysclk_disable_pba_module(SYSCLK_GPIO);
		AVR32_INTC.ipr[0];
		/* Enter STATIC sleep mode */
		sleepmgr_enter_sleep();
		/* Enable GPIO clock after waking from sleep mode */
		sysclk_enable_pba_module(SYSCLK_GPIO);
		/* Switch on the status LED */
		gpio_clr_gpio_pin(STATUS_LED);

#if DEBUG_MESSAGES
		print_dbg("\r Output higher than threshold \n");
		print_dbg("\n");
#else
		/* LED on for few ms */
		delay_ms(LED_DELAY);
#endif

		/* Clear the wake up & enable it to enter sleep mode again */
		pm_asyn_wake_up_disable(AVR32_PM_AWEN_ACIFBWEN_MASK);
		/* Clear All AST Interrupt request and clear SR */
		ast_clear_all_status_flags(&AVR32_AST);
	}

	return 0;
} /* End of main() */