Example #1
0
/***************************************************************************//**
 * MSS_SPI_init()
 * See "mss_spi.h" for details of how to use this function.
 */
void MSS_SPI_init
(
	mss_spi_instance_t * this_spi
)
{
    uint16_t i;
    
    ASSERT((this_spi == &g_mss_spi0) || (this_spi == &g_mss_spi1));
    
    if(this_spi == &g_mss_spi0)
    {
        this_spi->hw_reg = ((SPI_REVB_TypeDef *) SPI0_BASE);
        this_spi->irqn = SPI0_IRQn;

        /* reset SPI0 */
        SYSREG->SOFT_RST_CR |= SYSREG_SPI0_SOFTRESET_MASK;
        /* Clear any previously pended SPI0 interrupt */
        NVIC_ClearPendingIRQ(SPI0_IRQn);
        /* Take SPI0 out of reset. */
        SYSREG->SOFT_RST_CR &= ~SYSREG_SPI0_SOFTRESET_MASK;
    }
    else
    {
        this_spi->hw_reg = ((SPI_REVB_TypeDef *) SPI1_BASE);
        this_spi->irqn = SPI1_IRQn;
        
        /* reset SPI1 */
        SYSREG->SOFT_RST_CR |= SYSREG_SPI1_SOFTRESET_MASK;
        /* Clear any previously pended SPI1 interrupt */
        NVIC_ClearPendingIRQ(SPI1_IRQn);
        /* Take SPI1 out of reset. */
        SYSREG->SOFT_RST_CR &= ~SYSREG_SPI1_SOFTRESET_MASK;
    }
    
    /* De-assert reset bit. */
    this_spi->hw_reg->CONTROL &= ~CTRL_REG_RESET_MASK;
    
    /* Initialize SPI driver instance data. */
    this_spi->frame_rx_handler = 0u;
    this_spi->slave_tx_frame = 0u;
    
    this_spi->block_rx_handler = 0u;
    
    this_spi->slave_tx_buffer = 0u;
    this_spi->slave_tx_size = 0u;
    this_spi->slave_tx_idx = 0u;

    this_spi->resp_tx_buffer = 0u;
    this_spi->resp_buff_size = 0u;
    this_spi->resp_buff_tx_idx = 0u;
    
    this_spi->cmd_handler = 0;
    
    this_spi->slave_rx_buffer = 0;
    this_spi->slave_rx_size = 0u;
    this_spi->slave_rx_idx = 0u;
    
    for(i = 0u; i < (uint16_t)MSS_SPI_MAX_NB_OF_SLAVES; ++i)
    {
        this_spi->slaves_cfg[i].ctrl_reg = NOT_CONFIGURED;
    }
}
Example #2
0
/**
 * \brief Application entry point for PWM with LED example.
 * Output PWM waves on LEDs to make them fade in and out.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	/* Initialize the SAM system */
	sysclk_init();
	board_init();

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

	/* Output example information */
	puts(STRING_HEADER);
	
	/* Enable PWM peripheral clock */
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pmc_enable_periph_clk(ID_PWM0);
#else
	pmc_enable_periph_clk(ID_PWM);
#endif

	/* Disable PWM channels for LEDs */
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pwm_channel_disable(PWM0, PIN_PWM_LED0_CHANNEL);
	pwm_channel_disable(PWM0, PIN_PWM_LED1_CHANNEL);
#else
	pwm_channel_disable(PWM, PIN_PWM_LED0_CHANNEL);
	pwm_channel_disable(PWM, PIN_PWM_LED1_CHANNEL);
#endif

	/* Set PWM clock A as PWM_FREQUENCY*PERIOD_VALUE (clock B is not used) */
	pwm_clock_t clock_setting = {
		.ul_clka = PWM_FREQUENCY * PERIOD_VALUE,
		.ul_clkb = 0,
		.ul_mck = sysclk_get_cpu_hz()
	};
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pwm_init(PWM0, &clock_setting);
#else
	pwm_init(PWM, &clock_setting);
#endif

	/* Initialize PWM channel for LED0 */
	/* Period is left-aligned */
	g_pwm_channel_led.alignment = PWM_ALIGN_LEFT;
	/* Output waveform starts at a low level */
	g_pwm_channel_led.polarity = PWM_LOW;
	/* Use PWM clock A as source clock */
	g_pwm_channel_led.ul_prescaler = PWM_CMR_CPRE_CLKA;
	/* Period value of output waveform */
	g_pwm_channel_led.ul_period = PERIOD_VALUE;
	/* Duty cycle value of output waveform */
	g_pwm_channel_led.ul_duty = INIT_DUTY_VALUE;
	g_pwm_channel_led.channel = PIN_PWM_LED0_CHANNEL;
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pwm_channel_init(PWM0, &g_pwm_channel_led);
#else
	pwm_channel_init(PWM, &g_pwm_channel_led);
#endif

	/* Enable channel counter event interrupt */
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pwm_channel_enable_interrupt(PWM0, PIN_PWM_LED0_CHANNEL, 0);
#else
	pwm_channel_enable_interrupt(PWM, PIN_PWM_LED0_CHANNEL, 0);
#endif

	/* Initialize PWM channel for LED1 */
	/* Period is center-aligned */
	g_pwm_channel_led.alignment = PWM_ALIGN_CENTER;
	/* Output waveform starts at a high level */
	g_pwm_channel_led.polarity = PWM_HIGH;
	/* Use PWM clock A as source clock */
	g_pwm_channel_led.ul_prescaler = PWM_CMR_CPRE_CLKA;
	/* Period value of output waveform */
	g_pwm_channel_led.ul_period = PERIOD_VALUE;
	/* Duty cycle value of output waveform */
	g_pwm_channel_led.ul_duty = INIT_DUTY_VALUE;
	g_pwm_channel_led.channel = PIN_PWM_LED1_CHANNEL;
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	pwm_channel_init(PWM0, &g_pwm_channel_led);

	/* Disable channel counter event interrupt */
	pwm_channel_disable_interrupt(PWM0, PIN_PWM_LED1_CHANNEL, 0);
#else
	pwm_channel_init(PWM, &g_pwm_channel_led);

	/* Disable channel counter event interrupt */
	pwm_channel_disable_interrupt(PWM, PIN_PWM_LED1_CHANNEL, 0);
#endif

	/* Configure interrupt and enable PWM interrupt */
#if (SAMV70 || SAMV71 || SAME70 || SAMS70)
	NVIC_DisableIRQ(PWM0_IRQn);
	NVIC_ClearPendingIRQ(PWM0_IRQn);
	NVIC_SetPriority(PWM0_IRQn, 0);
	NVIC_EnableIRQ(PWM0_IRQn);
	
	/* Enable PWM channels for LEDs */
	pwm_channel_enable(PWM0, PIN_PWM_LED0_CHANNEL);
	pwm_channel_enable(PWM0, PIN_PWM_LED1_CHANNEL);
#else
	NVIC_DisableIRQ(PWM_IRQn);
	NVIC_ClearPendingIRQ(PWM_IRQn);
	NVIC_SetPriority(PWM_IRQn, 0);
	NVIC_EnableIRQ(PWM_IRQn);
	
	/* Enable PWM channels for LEDs */
	pwm_channel_enable(PWM, PIN_PWM_LED0_CHANNEL);
	pwm_channel_enable(PWM, PIN_PWM_LED1_CHANNEL);
#endif


	/* Infinite loop */
	while (1) {
	}
}
Example #3
0
/**
  * @brief  This function handles EXTI Handler.
  * @param  None
  * @retval None
  */
void EXTI_Handler(void)
{
		LED_Toggle(GPIOC,GPIO_Pin_0);
    NVIC_ClearPendingIRQ(EXTI_IRQn);
}
Example #4
0
void rtc_init(void) {
    RCC_OscInitTypeDef RCC_OscInitStruct;

#if RTC_LSI
    if (rtc_inited) return;
    rtc_inited = 1;
#endif

    RtcHandle.Instance = RTC;

#if !RTC_LSI
    // Enable LSE Oscillator
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE;
    RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured!
    RCC_OscInitStruct.LSEState       = RCC_LSE_ON; // External 32.768 kHz clock on OSC_IN/OSC_OUT
    RCC_OscInitStruct.LSIState       = RCC_LSI_OFF;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { // Check if LSE has started correctly
        // Connect LSE to RTC
        __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE);
    } else {
	    error("Cannot initialize RTC with LSE\n");
    }
#else
    // Enable Power clock
    __PWR_CLK_ENABLE();

    // Enable access to Backup domain
    HAL_PWR_EnableBkUpAccess();

    // Reset Backup domain
    __HAL_RCC_BACKUPRESET_FORCE();
    __HAL_RCC_BACKUPRESET_RELEASE();
	
    // Enable LSI clock
    RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE;
    RCC_OscInitStruct.PLL.PLLState   = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured!
    RCC_OscInitStruct.LSEState       = RCC_LSE_OFF;
    RCC_OscInitStruct.LSIState       = RCC_LSI_ON;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) {
        error("Cannot initialize RTC with LSI\n");
    }
    // Connect LSI to RTC
    __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI);
#endif

    // Enable RTC
    __HAL_RCC_RTC_ENABLE();

    RtcHandle.Init.HourFormat     = RTC_HOURFORMAT_24;
    RtcHandle.Init.AsynchPrediv   = RTC_ASYNCH_PREDIV;
    RtcHandle.Init.SynchPrediv    = RTC_SYNCH_PREDIV;
    RtcHandle.Init.OutPut         = RTC_OUTPUT_DISABLE;
    RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH;
    RtcHandle.Init.OutPutType     = RTC_OUTPUT_TYPE_OPENDRAIN;

    if (HAL_RTC_Init(&RtcHandle) != HAL_OK) {
        error("RTC error: RTC initialization failed.");
    }

#if DEVICE_LOWPOWERTIMER
#if RTC_LSI
    rtc_write(0);
#else
    if (!rtc_isenabled()) {
        rtc_write(0);
    }
#endif
    NVIC_ClearPendingIRQ(RTC_IRQn);
    NVIC_DisableIRQ(RTC_IRQn);
    NVIC_SetVector(RTC_IRQn, (uint32_t)RTC_IRQHandler);
    NVIC_EnableIRQ(RTC_IRQn);
#endif
}
uint32_t app_uart_init(const app_uart_comm_params_t * p_comm_params,
                             app_uart_buffers_t *     p_buffers,
                             app_uart_event_handler_t event_handler,
                             app_irq_priority_t       irq_priority)
{
    uint32_t err_code;
    uint32_t gpiote_high_pins;
    uint32_t gpiote_pin_low_high_mask = 0;
    uint32_t gpiote_pin_high_low_mask = 0;

    m_current_state = UART_OFF;
    m_event_handler = event_handler;

    // Configure buffer RX buffer.
    err_code = app_fifo_init(&m_rx_fifo, p_buffers->rx_buf, p_buffers->rx_buf_size);
    if (err_code != NRF_SUCCESS)
    {
        // Propagate error code.
        return err_code;
    }

    // Configure buffer TX buffer.
    err_code = app_fifo_init(&m_tx_fifo, p_buffers->tx_buf, p_buffers->tx_buf_size);
    if (err_code != NRF_SUCCESS)
    {
        // Propagate error code.
        return err_code;
    }

    // Configure RX and TX pins.
    nrf_gpio_cfg_output(p_comm_params->tx_pin_no);
    nrf_gpio_cfg_input(p_comm_params->rx_pin_no, NRF_GPIO_PIN_NOPULL);

    NRF_UART0->PSELTXD = p_comm_params->tx_pin_no;
    NRF_UART0->PSELRXD = p_comm_params->rx_pin_no;

    // Configure baud rate and parity.
    NRF_UART0->BAUDRATE = (p_comm_params->baud_rate << UART_BAUDRATE_BAUDRATE_Pos);
    if (p_comm_params->use_parity)
    {
        NRF_UART0->CONFIG = (UART_CONFIG_PARITY_Included << UART_CONFIG_PARITY_Pos);
    }
    else
    {
        NRF_UART0->CONFIG = (UART_CONFIG_PARITY_Excluded << UART_CONFIG_PARITY_Pos);
    }

    if (p_comm_params->use_hardware_flow_control)
    {
        // Configure hardware flow control.
        nrf_gpio_cfg_output(p_comm_params->rts_pin_no);
        NRF_GPIO->OUT = 1 << p_comm_params->rts_pin_no;

        NRF_UART0->PSELCTS  = UART_PIN_DISCONNECTED;
        NRF_UART0->PSELRTS  = p_comm_params->rts_pin_no;
        NRF_UART0->CONFIG  |= (UART_CONFIG_HWFC_Enabled << UART_CONFIG_HWFC_Pos);

        // Setup the gpiote to handle pin events on cts-pin.
        // For the UART we want to detect both low->high and high->low transistions in order to
        // know when to activate/deactivate the TX/RX in the UART.
        // Configure pin.
        m_pin_cts_mask = (1 << p_comm_params->cts_pin_no);
        GPIO_PIN_CONFIG(p_comm_params->cts_pin_no,
                        GPIO_PIN_CNF_DIR_Input,
                        GPIO_PIN_CNF_INPUT_Connect,
                        GPIO_PIN_CNF_PULL_Disabled,
                        GPIO_PIN_CNF_DRIVE_S0S1,
                        GPIO_PIN_CNF_SENSE_Low);

        gpiote_pin_low_high_mask = (1 << p_comm_params->cts_pin_no);
        gpiote_pin_high_low_mask = (1 << p_comm_params->cts_pin_no);

        err_code = app_gpiote_user_register(&m_gpiote_uid,
                                            gpiote_pin_low_high_mask,
                                            gpiote_pin_high_low_mask,
                                            gpiote_uart_event_handler);
        if (err_code != NRF_SUCCESS)
        {
            return err_code;
        }

        err_code = app_gpiote_pins_state_get(m_gpiote_uid, &gpiote_high_pins);
        if (err_code != NRF_SUCCESS)
        {
            return err_code;
        }

        err_code = app_gpiote_user_enable(m_gpiote_uid);
        if (err_code != NRF_SUCCESS)
        {
            return err_code;
        }

        // UART CTS pin is active when low.
        if ((gpiote_high_pins & (1 << p_comm_params->cts_pin_no)) == 0)
        {
            on_uart_event(ON_CTS_LOW);
        }
        else
        {
            on_uart_event(ON_CTS_HIGH);
        }
    }
    else
    {
        uart_no_flow_control_init();
        m_current_state = UART_READY;
    }

    // Enable UART interrupt
    NRF_UART0->INTENCLR = 0xffffffffUL;
    NRF_UART0->INTENSET = (UART_INTENSET_RXDRDY_Set << UART_INTENSET_RXDRDY_Pos) |
                          (UART_INTENSET_TXDRDY_Set << UART_INTENSET_TXDRDY_Pos) |
                          (UART_INTENSET_ERROR_Set << UART_INTENSET_ERROR_Pos);

    NVIC_ClearPendingIRQ(UART0_IRQn);
    NVIC_SetPriority(UART0_IRQn, irq_priority);
    NVIC_EnableIRQ(UART0_IRQn);

    return NRF_SUCCESS;
}
Example #6
0
OSStatus host_platform_bus_init( void )
{
#ifndef USE_OWN_SPI_DRV 
	struct spi_master_vec_config spi; 
#else
	pdc_packet_t pdc_spi_packet;
#endif
    OSStatus result;

    platform_mcu_powersave_disable();

	spi_disable_interrupt(SPI_MASTER_BASE, 0xffffffff);
    //Disable_global_interrupt();//TBD!

    result = mico_rtos_init_semaphore( &spi_transfer_finished_semaphore, 1 );
    if ( result != kNoErr )
    {
        return result;
    }
    
    MicoGpioInitialize( (mico_gpio_t)MICO_GPIO_9, INPUT_PULL_UP );
    //ioport_port_mask_t ul_mask = ioport_pin_to_mask(CREATE_IOPORT_PIN(PORTA,24));
    //pio_set_input(PIOA,ul_mask, PIO_PULLUP|PIO_DEBOUNCE);
    MicoGpioEnableIRQ( (mico_gpio_t)MICO_GPIO_9, IRQ_TRIGGER_RISING_EDGE, spi_irq_handler, NULL );
#ifndef HARD_CS_NSS0	
    MicoGpioInitialize( MICO_GPIO_15, OUTPUT_PUSH_PULL);//spi ss/cs 
	MicoGpioOutputHigh( MICO_GPIO_15 );//MICO_GPIO_15 TBD!
#else
	ioport_set_pin_peripheral_mode(SPI_NPCS0_GPIO, SPI_NPCS0_FLAGS);//TBD!
#endif
    /* set PORTB 01 to high to put WLAN module into g_SPI mode */
    MicoGpioInitialize( (mico_gpio_t)WL_GPIO0, OUTPUT_PUSH_PULL );
    MicoGpioOutputHigh( (mico_gpio_t)WL_GPIO0 );
#ifdef USE_OWN_SPI_DRV 
#if (SAMG55)
	/* Enable the peripheral and set SPI mode. */
	flexcom_enable(BOARD_FLEXCOM_SPI);
	flexcom_set_opmode(BOARD_FLEXCOM_SPI, FLEXCOM_SPI);
#else
	/* Configure an SPI peripheral. */
	pmc_enable_periph_clk(SPI_ID);
#endif
    //Init pdc, and clear RX TX.
    spi_m_pdc = spi_get_pdc_base(SPI_MASTER_BASE);

	pdc_spi_packet.ul_addr = NULL;
	pdc_spi_packet.ul_size = 3;
	pdc_tx_init(spi_m_pdc, &pdc_spi_packet, NULL);
	pdc_rx_init(spi_m_pdc, &pdc_spi_packet, NULL);

	spi_disable(SPI_MASTER_BASE);
	spi_reset(SPI_MASTER_BASE);
	spi_set_lastxfer(SPI_MASTER_BASE);
	spi_set_master_mode(SPI_MASTER_BASE);
	spi_disable_mode_fault_detect(SPI_MASTER_BASE);
#ifdef HARD_CS_NSS0
	//spi_enable_peripheral_select_decode(SPI_MASTER_BASE);
	//spi_set_peripheral_chip_select_value(SPI_MASTER_BASE, SPI_CHIP_SEL);
	spi_set_peripheral_chip_select_value(SPI_MASTER_BASE, SPI_CHIP_PCS); //use soft nss comment here
#endif
	spi_set_clock_polarity(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CLK_POLARITY);
	spi_set_clock_phase(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CLK_PHASE);
	spi_set_bits_per_transfer(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_CSR_BITS_8_BIT);
	spi_set_baudrate_div(SPI_MASTER_BASE, SPI_CHIP_SEL, (sysclk_get_cpu_hz() / SPI_BAUD_RATE));
	spi_set_transfer_delay(SPI_MASTER_BASE, SPI_CHIP_SEL, SPI_DLYBS, SPI_DLYBCT);

    /* Must be lower priority than the value of configMAX_SYSCALL_INTERRUPT_PRIORITY */
    /* otherwise FreeRTOS will not be able to mask the interrupt */
    /* keep in mind that ARMCM3 interrupt priority logic is inverted, the highest value */
    /* is the lowest priority */
	/* Configure SPI interrupts . */
    spi_enable_interrupt(SPI_MASTER_BASE, SPI_IER_RXBUFF);
    //spi_enable_interrupt(SPI_MASTER_BASE, SPI_IER_NSSR | SPI_IER_RXBUFF);
	
	NVIC_DisableIRQ(SPI_IRQn);
    //irq_register_handler(SPI_IRQn, 3);
	NVIC_ClearPendingIRQ(SPI_IRQn);
	NVIC_SetPriority(SPI_IRQn, 3);
	NVIC_EnableIRQ(SPI_IRQn);

    spi_enable(SPI_MASTER_BASE);
#else
    spi.baudrate = SPI_BAUD_RATE;
	if (STATUS_OK != spi_master_vec_init(&spi_master, SPI_MASTER_BASE, &spi)) {
		return -1;
	}

	spi_master_vec_enable(&spi_master);
#endif
    //if (!Is_global_interrupt_enabled())
    //    Enable_global_interrupt();
    platform_mcu_powersave_enable();

    return kNoErr;
}
Example #7
0
/**
 * \brief pio_capture Application entry point.
 *
 * \return Unused (ANSI-C compatibility).
 *
 */
int main(void)
{
	uint8_t uc_i;
	uint8_t uc_flag;
	uint32_t ul_mode;
	uint8_t uc_key;
	static uint8_t uc_rx_even_only;
	static uint8_t uc_tx_without_en;

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

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

	/* Configure PIOA clock. */
	pmc_enable_periph_clk(ID_PIOA);

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

	printf("Frequency: %d MHz.\r\n",
			(uint8_t) (sysclk_get_cpu_hz() / 1000000));

	puts("Press r to Receive data on PIO Parallel Capture.\r\n");
	puts("Press s to Send data on PIO Parallel Capture.\r\n");
	uc_key = 0;
	while ((uc_key != 'r') && (uc_key != 's')) {
		uart_read(CONSOLE_UART, &uc_key);
	}
	if (uc_key == 'r') {
		puts("** RECEIVE mode **\r\n");

		/* Set up PDC receive buffer, waiting for 64 bytes. */
		packet_t.ul_addr = (uint32_t) pio_rx_buffer;
		packet_t.ul_size = SIZE_BUFF_RECEPT;
		p_pdc = pio_capture_get_pdc_base(PIOA);
		pdc_rx_init(p_pdc, &packet_t, NULL);

		/* Disable all PIOA I/O line interrupt. */
		pio_disable_interrupt(PIOA, 0xFFFFFFFF);

		/* Configure and enable interrupt of PIO. */
		NVIC_DisableIRQ(PIOA_IRQn);
		NVIC_ClearPendingIRQ(PIOA_IRQn);
		NVIC_SetPriority(PIOA_IRQn, PIO_IRQ_PRI);
		NVIC_EnableIRQ(PIOA_IRQn);

		/* Configure the PIO capture interrupt mask. */
		pio_capture_enable_interrupt(PIOA,
				(PIO_PCIER_ENDRX | PIO_PCIER_RXBUFF));

		/* Enable PDC transfer. */
		pdc_enable_transfer(p_pdc, PERIPH_PTCR_RXTEN);

		/* Clear Receive buffer. */
		for (uc_i = 0; uc_i < SIZE_BUFF_RECEPT; uc_i++) {
			pio_rx_buffer[uc_i] = 0;
		}
		/* Initialize PIO capture mode value. */
		ul_mode = 0;
		/* Set up the parallel capture mode data size as 8 bits. */
		ul_mode |= 0 << PIO_PCMR_DSIZE_Pos;

		puts("Press y to sample the data when both data enable pins are enabled.\r\n");
		puts("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')) {
			uart_read(CONSOLE_UART, &uc_key);
		}
		if (uc_key == 'y') {
			/* Sample the data when both data enable pins are enabled. */
			ul_mode &= ~PIO_PCMR_ALWYS;
			puts("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. */
			ul_mode |= PIO_PCMR_ALWYS;
			puts("Receive data, don't care the status of the data enable pins.\r\n");
		}
		puts("Press y to sample all the data\r\n");
		puts("Press n to sample the data only one out of two.\r\n");
		uc_key = 0;
		while ((uc_key != 'y') && (uc_key != 'n')) {
			uart_read(CONSOLE_UART, &uc_key);
		}
		if (uc_key == 'y') {
			/* Sample all the data. */
			ul_mode &= ~PIO_PCMR_HALFS;
			puts("All data are sampled.\r\n");
		} else {
			/* Sample the data only one out of two. */
			ul_mode |= PIO_PCMR_HALFS;
			/* Only if half-Sampling is set, data with an even index are sampled. */
			ul_mode &= ~PIO_PCMR_FRSTS;
			puts("Only one out of two data is sampled, with an even index.\r\n");
		}

		while (1) {
			/* Initialize PIO Parallel Capture function. */
			g_uc_cbk_received = 0;
			pio_capture_set_mode(PIOA, ul_mode);
			pio_capture_enable(PIOA);
			puts("Waiting...\r\n");
			while (g_uc_cbk_received == 0) {
			}
		}
	} else if (uc_key == 's') {
		puts("** SEND mode **\r\n");
		puts("This is for debug purpose only !\r\n");
		puts("Frequency of PIO controller clock must be strictly superior");
		puts("to 2 times the frequency of the clock of the device which");
		puts(" generates the parallel data.\r\n");
		puts("\r\nPlease connect the second board, ");
		puts("and put it in receive mode.\r\n");

		/* Configure PIO Parallel Capture pins which simulate as a sensor. */
		pio_configure_pin_group(PIOA, PIO_CAPTURE_ALL_PIN_MSK,
			PIO_CAPTURE_PIN_FLAGS);

		/* Enable sync. output data. */
		pio_enable_output_write(PIOA, PIO_CAPTURE_DATA_PINS_MASK);

		/* Initialize the capture data line. */
		pio_sync_output_write(PIOA, 0);

		puts("Press y to send data with data enable pins.\r\n");
		puts("Press n to send data without data enable pins.\r\n");

		uc_key = 0;
		while ((uc_key != 'y') && (uc_key != 'n')) {
			uart_read(CONSOLE_UART, &uc_key);
		}
		if (uc_key == 'y') {
			uc_tx_without_en = 0;
			puts("Send data with both data enable pins enabled.\r\n");
		} else {
			uc_tx_without_en = 1;
			puts("Send data without enabling the data enable pins.\r\n");
		}

		puts("Press y to indicate that receiver samples all data.\r\n");
		puts("Press n to indicate that receiver samples data with an even index.\r\n");
		uc_key = 0;
		while ((uc_key != 'y') && (uc_key != 'n')) {
			uart_read(CONSOLE_UART, &uc_key);
		}
		if (uc_key == 'y') {
			uc_rx_even_only = 0;
			puts("Receiver samples all data.\r\n");
		} else {
			uc_rx_even_only = 1;
			puts("Receiver samples data with an even index.\r\n");
		}

		uc_flag = 0;
		while (1) {
			if (uc_tx_without_en) {
				puts("\r\nSend data without enabling the data enable pins.\r\n");
			} else {
				puts("\r\nSend data with both data enable pins enabled.\r\n");
			}
			if (!uc_tx_without_en) {
				/* Set enable pins. */
				pio_set_pin_high(PIO_CAPTURE_EN1_IDX);
				pio_set_pin_high(PIO_CAPTURE_EN2_IDX);
			}
			for (uc_i = 0; uc_i < SIZE_BUFF_RECEPT;) {
				/* Send data. */
				pio_sync_output_write(PIOA,
						(uc_i << PIO_CAPTURE_DATA_POS));
				/* Set clock. */
				pio_set_pin_high(PIO_CAPTURE_CCLK_IDX);
				wait(50);
				/* Clear clock. */
				pio_set_pin_low(PIO_CAPTURE_CCLK_IDX);
				wait(50);
				if (uc_rx_even_only) {
					if (!uc_flag) {
						uc_flag = 1;
					} else {
						uc_i++;
						uc_flag = 0;
					}
				} else {
					uc_i++;
				}
			}
			if (!uc_tx_without_en) {
				/* Clear enable pins. */
				pio_set_pin_low(PIO_CAPTURE_EN1_IDX);
				pio_set_pin_low(PIO_CAPTURE_EN2_IDX);
			}
			puts("Press a key.\r\n");
			while (uart_read(CONSOLE_UART, &uc_key)) {
			}
		}
	}

	return 0;
}
void radio_init (uint8_t channel)
{
  /* Enable power to RADIO */
  NRF_RADIO->POWER = 1;

  /* Set radio transmit power to 0dBm */
  NRF_RADIO->TXPOWER = (RADIO_TXPOWER_TXPOWER_0dBm << RADIO_TXPOWER_TXPOWER_Pos);

  /* Set radio mode to 1Mbit/s Bluetooth Low Energy */
  NRF_RADIO->MODE = (RADIO_MODE_MODE_Ble_1Mbit << RADIO_MODE_MODE_Pos);

  /* Set the requested channel */
  NRF_RADIO->FREQUENCY = channel_resolver_get_frequency(channel);

  /* This value needs to correspond to the channel being used */
  NRF_RADIO->DATAWHITEIV = channel;

  /* Configure Access Address according to the BLE standard */
  NRF_RADIO->PREFIX0 = 0x8e;
  NRF_RADIO->BASE0 = 0x89bed600;
  
  /* Use logical address 0 (prefix0 + base0) = 0x8E89BED6 when transmitting and receiving */
  NRF_RADIO->TXADDRESS = 0x00;
  NRF_RADIO->RXADDRESSES = 0x01;

  /* PCNF-> Packet Configuration. 
   * We now need to configure the sizes S0, S1 and length field to match the
   * datapacket format of the advertisement packets.
   */
  NRF_RADIO->PCNF0 = (
    (((1UL) << RADIO_PCNF0_S0LEN_Pos) & RADIO_PCNF0_S0LEN_Msk) |  /* Length of S0 field in bytes 0-1.    */
    (((2UL) << RADIO_PCNF0_S1LEN_Pos) & RADIO_PCNF0_S1LEN_Msk) |  /* Length of S1 field in bits 0-8.     */
    (((6UL) << RADIO_PCNF0_LFLEN_Pos) & RADIO_PCNF0_LFLEN_Msk)    /* Length of length field in bits 0-8. */
  );

  /* Packet configuration */
  NRF_RADIO->PCNF1 = (
    (((37UL) << RADIO_PCNF1_MAXLEN_Pos) & RADIO_PCNF1_MAXLEN_Msk)   |                      /* Maximum length of payload in bytes [0-255] */
    (((0UL) << RADIO_PCNF1_STATLEN_Pos) & RADIO_PCNF1_STATLEN_Msk)   |                      /* Expand the payload with N bytes in addition to LENGTH [0-255] */
    (((3UL) << RADIO_PCNF1_BALEN_Pos) & RADIO_PCNF1_BALEN_Msk)       |                      /* Base address length in number of bytes. */
    (((RADIO_PCNF1_ENDIAN_Little) << RADIO_PCNF1_ENDIAN_Pos) & RADIO_PCNF1_ENDIAN_Msk) |  /* Endianess of the S0, LENGTH, S1 and PAYLOAD fields. */
    (((1UL) << RADIO_PCNF1_WHITEEN_Pos) & RADIO_PCNF1_WHITEEN_Msk)                         /* Enable packet whitening */
  );

  /* CRC config */
  NRF_RADIO->CRCCNF  = (RADIO_CRCCNF_LEN_Three << RADIO_CRCCNF_LEN_Pos) |
                       (RADIO_CRCCNF_SKIPADDR_Skip << RADIO_CRCCNF_SKIPADDR_Pos); /* Skip Address when computing CRC */
  NRF_RADIO->CRCINIT = 0x555555;                                                  /* Initial value of CRC */
  NRF_RADIO->CRCPOLY = 0x00065B;                                                  /* CRC polynomial function */

  /* Clear events */
  NRF_RADIO->EVENTS_DISABLED = 0;
  NRF_RADIO->EVENTS_END = 0;
  NRF_RADIO->EVENTS_READY = 0;
  NRF_RADIO->EVENTS_ADDRESS = 0;
  
  /* Enable interrupt on events */
  NRF_RADIO->INTENSET = RADIO_INTENSET_ADDRESS_Msk | RADIO_INTENSET_DISABLED_Msk;
  
  /* Enable RADIO interrupts */
  NVIC_ClearPendingIRQ(RADIO_IRQn);
  NVIC_EnableIRQ(RADIO_IRQn);
  
  m_radio_dir = RADIO_DIR_NONE;
}
Example #9
0
platform_result_t platform_uart_init( platform_uart_driver_t* driver, const platform_uart_t* interface, const platform_uart_config_t* config, wiced_ring_buffer_t* optional_ring_buffer )
{
    uint32_t           uart_number;
    UART_FIFO_CFG_T    UARTFIFOConfigStruct;
    config_uart_data_t config_uart_data;

    wiced_assert( "bad argument", ( driver != NULL ) && ( interface != NULL ) && ( config != NULL ) );
    Chip_Clock_EnablePeriphClock( SYSCTL_CLOCK_UART0 );

    uart_number = platform_uart_get_port_number(interface->uart_base);
    driver->rx_size              = 0;
    driver->tx_size              = 0;
    driver->last_transmit_result = PLATFORM_SUCCESS;
    driver->last_receive_result  = PLATFORM_SUCCESS;
    driver->interface            = (platform_uart_t*)interface;
    host_rtos_init_semaphore( &driver->tx_complete );
    host_rtos_init_semaphore( &driver->rx_complete );

    platform_gpio_set_alternate_function( &driver->interface->tx_pin);
    platform_gpio_set_alternate_function( &driver->interface->rx_pin);

    /* Initialise USART peripheral */
    Chip_UART_FIFOConfigStructInit( driver->interface->uart_base, &UARTFIFOConfigStruct );
    Chip_UART_Init( driver->interface->uart_base );
    Chip_UART_SetBaud( driver->interface->uart_base, config->baud_rate );
    config_uart_data.databits = ( ( config->data_width == DATA_WIDTH_8BIT ) || ( ( config->data_width == DATA_WIDTH_7BIT ) && ( config->parity != NO_PARITY ) ) ) ? UART_DATABIT_8 : UART_DATABIT_7;
    config_uart_data.stopbits = ( config->stop_bits == STOP_BITS_1 ) ? UART_STOPBIT_1 : UART_STOPBIT_2;
    switch ( config->parity )
    {
        case NO_PARITY:
            config_uart_data.parity = UART_PARITY_NONE;
            break;

        case EVEN_PARITY:
            config_uart_data.parity = UART_PARITY_EVEN;
            break;

        case ODD_PARITY:
            config_uart_data.parity = UART_PARITY_ODD;
            break;

        default:
            return WICED_BADARG;
    }

    Chip_UART_ConfigData( driver->interface->uart_base, config_uart_data.databits, config_uart_data.parity, config_uart_data.stopbits );
    Chip_UART_TxCmd( driver->interface->uart_base, ENABLE );
    /* Enable receive data and line status interrupt */
    /* Initialize FIFO for UART0 peripheral */
    Chip_UART_FIFOConfig( driver->interface->uart_base, &UARTFIFOConfigStruct );
    /* Enable UART Rx interrupt */
    Chip_UART_IntConfig( driver->interface->uart_base, UART_INTCFG_RBR, ENABLE );
    /* Enable UART line status interrupt */
    Chip_UART_IntConfig( driver->interface->uart_base, UART_INTCFG_RLS, ENABLE );

    /* Enable Interrupt for UART channel */
    NVIC_DisableIRQ( uart_irq_vectors[ uart_number ] );
    NVIC_ClearPendingIRQ( uart_irq_vectors[ uart_number ] );
    /*Note the LPC uses 5 bits for interrupt priority levels*/
    NVIC_EnableIRQ( uart_irq_vectors[ uart_number ] );
    if ( optional_ring_buffer != NULL )
    {
        /* Note that the ring_buffer should've been initialised first */
        driver->rx_buffer = optional_ring_buffer;
        driver->rx_size = 0;
    }

    return PLATFORM_SUCCESS;
}
Example #10
0
int wifi_init(void){
  uint32_t BUF_SIZE = MD_BUF_SIZE;
  uint8_t tmp;  //dummy var for flushing UART
  int r; //return value from wifi_send_cmd (length of resp)
  char *buf;
  char *tx_buf;

  //allocate static buffers if they are not NULL
  if(resp_buf==NULL){
    resp_buf=core_malloc(RESP_BUF_SIZE);
  }
  if(resp_complete_buf==NULL){
    resp_complete_buf=core_malloc(RESP_COMPLETE_BUF_SIZE);
  }
  if(wifi_rx_buf==NULL){
    wifi_rx_buf = core_malloc(WIFI_RX_BUF_SIZE);
  }
  //if we are standalone, don't do anything
  if(wemo_config.standalone){
    printf("warning: wifi_init called in standalone mode\n");
    return 0; 
  }
  //initialize the memory
  buf = core_malloc(BUF_SIZE);
  tx_buf = core_malloc(BUF_SIZE);

  //set up the UART
  static usart_serial_options_t usart_options = {
    .baudrate = WIFI_UART_BAUDRATE,
    .charlength = WIFI_UART_CHAR_LENGTH,
    .paritytype = WIFI_UART_PARITY,
    .stopbits = WIFI_UART_STOP_BITS
  };
  gpio_configure_pin(PIO_PA9_IDX, (PIO_PERIPH_A | PIO_DEFAULT));
  gpio_configure_pin(PIO_PA10_IDX, (PIO_PERIPH_A | PIO_DEFAULT));
  pmc_enable_periph_clk(ID_WIFI_UART);
  sysclk_enable_peripheral_clock(ID_WIFI_UART);
  usart_serial_init(WIFI_UART,&usart_options);
  //flush any existing data
  while(usart_serial_is_rx_ready(WIFI_UART)){
    usart_serial_getchar(WIFI_UART,&tmp);
  }
  // Trigger from timer 0
  pmc_enable_periph_clk(ID_TC0);
  tc_init(TC0, 0,                        // channel 0
	  TC_CMR_TCCLKS_TIMER_CLOCK5     // source clock (CLOCK5 = Slow Clock)
	  | TC_CMR_CPCTRG                // up mode with automatic reset on RC match
	  | TC_CMR_WAVE                  // waveform mode
	  | TC_CMR_ACPA_CLEAR            // RA compare effect: clear
	  | TC_CMR_ACPC_SET              // RC compare effect: set
	  );
  TC0->TC_CHANNEL[0].TC_RA = 0;  // doesn't matter
  TC0->TC_CHANNEL[0].TC_RC = 64000;  // sets frequency: 32kHz/32000 = 1 Hz
  NVIC_ClearPendingIRQ(TC0_IRQn);
  NVIC_SetPriority(TC0_IRQn,1);//high priority
  NVIC_EnableIRQ(TC0_IRQn);
  tc_enable_interrupt(TC0, 0, TC_IER_CPCS);
  //reset the module
  if(wifi_send_cmd("AT+RST","ready",buf,BUF_SIZE,8)==0){
    printf("Error reseting ESP8266\n");
    //free memory
    core_free(buf);
    core_free(tx_buf);
    return -1;
  }
  //set to mode STA
  if(wifi_send_cmd("AT+CWMODE=1","OK",buf,BUF_SIZE,8)==0){
    printf("Error setting ESP8266 mode\n");
    core_free(buf);
    core_free(tx_buf);
    return 0;
  }
  //try to join the specified network  
  snprintf(tx_buf,BUF_SIZE,"AT+CWJAP=\"%s\",\"%s\"",
	   wemo_config.wifi_ssid,wemo_config.wifi_pwd);
  if((r=wifi_send_cmd(tx_buf,"OK",buf,BUF_SIZE,10))==0){
    printf("no response to CWJAP\n");
    //free memory
    core_free(buf);
    core_free(tx_buf);
    return -1;
  }
  //check for errors
  if( (r<1) || (strcmp(&buf[r-1],"OK")!=0)){
    snprintf(tx_buf,BUF_SIZE,"failed to join network [%s]: [%s]\n",wemo_config.wifi_ssid, buf);
    printf(tx_buf);
    core_log(tx_buf);
    //free memory
    core_free(buf);
    core_free(tx_buf);
    return -1;
  }
  //see if we have an IP address
  wifi_send_cmd("AT+CIFSR","OK",buf,BUF_SIZE,5);
  if(strstr(buf,"ERROR")==buf){
    printf("error getting IP address\n");
    //free the memory
    core_free(tx_buf);
    core_free(buf);
    return -1;
  }
  //try to parse the response into an IP address
  //expect 4 octets but *not* 0.0.0.0
  int a1,a2,a3,a4;
  if(!(sscanf(buf,"+CIFSR:STAIP,\"%d.%d.%d.%d\"",&a1,&a2,&a3,&a4)==4 && a1!=0)){
    printf("error, bad address: %s\n",buf);
    //free the memory
    core_free(tx_buf);
    core_free(buf);
    return -1;
  }
  //save the IP to our config
  snprintf(buf,BUF_SIZE,"%d.%d.%d.%d",a1,a2,a3,a4);
  memset(wemo_config.ip_addr,0x0,MAX_CONFIG_LEN);
  strcpy(wemo_config.ip_addr,buf);
  //set the mode to multiple connection
  wifi_send_cmd("AT+CIPMUX=1","OK",buf,BUF_SIZE,2);
  //start a server on port 1336
  wifi_send_cmd("AT+CIPSERVER=1,1336","OK",buf,BUF_SIZE,2);

  //if we know the NILM IP address, send it our IP
  if(strlen(wemo_config.nilm_ip_addr)!=0){
    if(wifi_send_ip()==TX_ERR_MODULE_RESET){
      return TX_ERR_MODULE_RESET;
    }
  } 
  else {
     //get the NILM IP address from the manager
     //once we know the NILM address we send it ours
     core_get_nilm_ip_addr();
  }

  //log the event
  snprintf(buf,BUF_SIZE,"Joined [%s] with IP [%s]",
	   wemo_config.wifi_ssid,wemo_config.ip_addr);
  printf("\n%s\n",buf);
  core_log(buf);
  //free the memory
  core_free(tx_buf);
  core_free(buf);
  return 0;
}
Example #11
0
/***************************************************************************//**
 * @brief
 *   Initializes USB device hardware and internal protocol stack data structures,
 *   then connects the data-line (D+ or D-) pullup resistor to signal host that
 *   enumeration can begin.
 *
 * @note
 *   You may later use @ref USBD_Disconnect() and @ref USBD_Connect() to force
 *   reenumeration.
 *
 * @param[in] p
 *   Pointer to device initialization struct. See @ref USBD_Init_TypeDef.
 *
 * @return
 *   @ref USB_STATUS_OK on success, else an appropriate error code.
 ******************************************************************************/
int USBD_Init( const USBD_Init_TypeDef *p )
{
  int numEps;
  USBD_Ep_TypeDef *ep;
  uint8_t txFifoNum;
  uint8_t *conf, *confEnd;
  USB_EndpointDescriptor_TypeDef *epd;
  uint32_t totalRxFifoSize, totalTxFifoSize, numInEps, numOutEps;

  CMU_ClockSelectSet( cmuClock_HF, cmuSelect_HFXO );
#if ( USB_USBC_32kHz_CLK == USB_USBC_32kHz_CLK_LFXO )
  CMU_OscillatorEnable( cmuOsc_LFXO, true, false );
#else
  CMU_OscillatorEnable( cmuOsc_LFRCO, true, false );
#endif
  USBTIMER_Init();

  memset( dev, 0, sizeof( USBD_Device_TypeDef ) );

  dev->setup                = dev->setupPkt;
  dev->deviceDescriptor     = p->deviceDescriptor;
  dev->configDescriptor     = (USB_ConfigurationDescriptor_TypeDef*)
                              p->configDescriptor;
  dev->stringDescriptors    = p->stringDescriptors;
  dev->numberOfStrings      = p->numberOfStrings;
  dev->state                = USBD_STATE_LASTMARKER;
  dev->savedState           = USBD_STATE_NONE;
  dev->lastState            = USBD_STATE_NONE;
  dev->callbacks            = p->callbacks;
  dev->remoteWakeupEnabled  = false;

  /* Initialize EP0 */

  ep                 = &dev->ep[ 0 ];
  ep->in             = false;
  ep->buf            = NULL;
  ep->num            = 0;
  ep->mask           = 1;
  ep->addr           = 0;
  ep->type           = USB_EPTYPE_CTRL;
  ep->txFifoNum      = 0;
  ep->packetSize     = USB_EP0_SIZE;
  ep->remaining      = 0;
  ep->xferred        = 0;
  ep->state          = D_EP_IDLE;
  ep->xferCompleteCb = NULL;
  ep->fifoSize       = USB_EP0_SIZE / 4;

  totalTxFifoSize = ep->fifoSize * p->bufferingMultiplier[ 0 ];
  totalRxFifoSize = (ep->fifoSize + 1) * p->bufferingMultiplier[ 0 ];

#if defined( DEBUG_USB_API )
  /* Do a sanity check on the configuration descriptor */
  {
    int i;

    /* Check if bLength's adds up exactly to wTotalLength */
    i = 0;
    conf = (uint8_t*)dev->configDescriptor;
    confEnd = conf + dev->configDescriptor->wTotalLength;

    while ( conf < confEnd )
    {
      if ( *conf == 0 )
        break;

      i += *conf;
      conf += *conf;
    }

    if ( ( conf != confEnd                          ) ||
         ( i != dev->configDescriptor->wTotalLength )    )
    {
      DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal configuration descriptor" );
      EFM_ASSERT( false );
      return USB_STATUS_ILLEGAL;
    }
  }
#endif /* defined( DEBUG_USB_API ) */

  /* Parse configuration decriptor */
  numEps = 0;
  numInEps  = 0;
  numOutEps = 0;
  conf = (uint8_t*)dev->configDescriptor;
  confEnd = conf + dev->configDescriptor->wTotalLength;

  txFifoNum = 1;
  while ( conf < confEnd )
  {
    if ( *conf == 0 )
    {
      DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal configuration descriptor" );
      EFM_ASSERT( false );
      return USB_STATUS_ILLEGAL;
    }

    if ( *(conf + 1) == USB_ENDPOINT_DESCRIPTOR )
    {
      numEps++;
      epd = (USB_EndpointDescriptor_TypeDef*)conf;

      ep                 = &dev->ep[ numEps ];
      ep->in             = ( epd->bEndpointAddress & USB_SETUP_DIR_MASK ) != 0;
      ep->buf            = NULL;
      ep->addr           = epd->bEndpointAddress;
      ep->num            = ep->addr & USB_EPNUM_MASK;
      ep->mask           = 1 << ep->num;
      ep->type           = epd->bmAttributes & CONFIG_DESC_BM_TRANSFERTYPE;
      ep->packetSize     = epd->wMaxPacketSize;
      ep->remaining      = 0;
      ep->xferred        = 0;
      ep->state          = D_EP_IDLE;
      ep->xferCompleteCb = NULL;
      if ( ep->in )
      {
        numInEps++;
        ep->txFifoNum = txFifoNum++;
        ep->fifoSize = (ep->packetSize/4) * p->bufferingMultiplier[ numEps ];
        dev->inEpAddr2EpIndex[ ep->num ] = numEps;
        totalTxFifoSize += ep->fifoSize;
        if ( ep->num > MAX_NUM_IN_EPS )
        {
          DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal IN EP address" );
          EFM_ASSERT( false );
          return USB_STATUS_ILLEGAL;
        }
      }
      else
      {
        numOutEps++;
        ep->fifoSize = (ep->packetSize/4 + 1) * p->bufferingMultiplier[ numEps ];
        dev->outEpAddr2EpIndex[ ep->num ] = numEps;
        totalRxFifoSize += ep->fifoSize;
        if ( ep->num > MAX_NUM_OUT_EPS )
        {
          DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal OUT EP address" );
          EFM_ASSERT( false );
          return USB_STATUS_ILLEGAL;
        }
      }
    }
    conf += *conf;
  }

  /* Rx-FIFO size: SETUP packets : 4*n + 6    n=#CTRL EP's
   *               GOTNAK        : 1
   *               Status info   : 2*n        n=#OUT EP's (EP0 included) in HW
   */
  totalRxFifoSize += 10 + 1 + ( 2 * (MAX_NUM_OUT_EPS + 1) );

  if ( numEps != NUM_EP_USED )
  {
    DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal EP count" );
    EFM_ASSERT( false );
    return USB_STATUS_ILLEGAL;
  }

  if ( numInEps > MAX_NUM_IN_EPS )
  {
    DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal IN EP count" );
    EFM_ASSERT( false );
    return USB_STATUS_ILLEGAL;
  }

  if ( numOutEps > MAX_NUM_OUT_EPS )
  {
    DEBUG_USB_API_PUTS( "\nUSBD_Init(), Illegal OUT EP count" );
    EFM_ASSERT( false );
    return USB_STATUS_ILLEGAL;
  }

  INT_Disable();

  /* Enable USB clock */
  CMU->HFCORECLKEN0 |= CMU_HFCORECLKEN0_USB | CMU_HFCORECLKEN0_USBC;
  CMU_ClockSelectSet( cmuClock_USBC, cmuSelect_HFCLK );

  USBHAL_DisableGlobalInt();

  if ( USBDHAL_CoreInit( totalRxFifoSize, totalTxFifoSize ) == USB_STATUS_OK )
  {
    USBDHAL_EnableUsbResetInt();
    USBHAL_EnableGlobalInt();
    NVIC_ClearPendingIRQ( USB_IRQn );
    NVIC_EnableIRQ( USB_IRQn );
  }
  else
  {
    INT_Enable();
    DEBUG_USB_API_PUTS( "\nUSBD_Init(), FIFO setup error" );
    EFM_ASSERT( false );
    return USB_STATUS_ILLEGAL;
  }

#if ( USB_PWRSAVE_MODE & USB_PWRSAVE_MODE_ONVBUSOFF )
  if ( USBHAL_VbusIsOn() )
  {
    USBD_SetUsbState( USBD_STATE_POWERED );
  }
  else
#endif
  {
    USBD_SetUsbState( USBD_STATE_NONE );
  }

  INT_Enable();
  return USB_STATUS_OK;
}
void Board_Attach_Interrupt(uint32_t ulPin, void (*callback)(void), uint32_t mode)
{
    uint8_t port = 1;
    uint8_t pin = 24;
    uint8_t pinIntChannel = 0;
    LPC1347_IRQn_Type pinIntIRQ = PIN_INT0_IRQn;

    port = APIN_PORT(ulPin);
    pin = APIN_PIN(ulPin);

    pinIntChannel = APIN_INT(ulPin);

    if(pinIntChannel == EXT_INT_0)
    {
        pinIntIRQ = PIN_INT0_IRQn;
        callbackPinIntA = callback;
    }
    else if(pinIntChannel == EXT_INT_1)
    {
        pinIntIRQ = PIN_INT1_IRQn;
        callbackPinIntB = callback;
    }
    else if(pinIntChannel == EXT_INT_2)
    {
        pinIntIRQ = PIN_INT2_IRQn;
        callbackPinIntC = callback;
    }
    else if(pinIntChannel == EXT_INT_3)
    {
        pinIntIRQ = PIN_INT3_IRQn;
        callbackPinIntD = callback;
    }

    /* Configure GPIO pin as input */
    Chip_GPIO_SetPinDIRInput(LPC_GPIO_PORT, port, pin);

    /* Configure pin as GPIO with pulldown */
    // All digital pins are selected such that GPIO is on IOCON_FUNC0
    Chip_IOCON_PinMuxSet(LPC_IOCON, port, pin, (IOCON_FUNC0 | IOCON_MODE_PULLDOWN));

    /* Enable PININT clock */
    Chip_Clock_EnablePeriphClock(SYSCTL_CLOCK_PINT);

    /* Configure interrupt channel for the GPIO pin in SysCon block */
    Chip_SYSCTL_SetPinInterrupt(pinIntChannel, port, pin);

    /* Configure channel interrupt as edge sensitive and falling edge interrupt */
    Chip_PININT_ClearIntStatus(LPC_PININT, PININTCH(pinIntChannel));

    if(mode == HIGH)
    {
        Chip_PININT_SetPinModeLevel(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntHigh(LPC_PININT, PININTCH(pinIntChannel));
    }
    else if(mode == LOW)
    {
        Chip_PININT_SetPinModeLevel(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntLow(LPC_PININT, PININTCH(pinIntChannel));
    }
    else if(mode == RISING)
    {
        Chip_PININT_SetPinModeEdge(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntHigh(LPC_PININT, PININTCH(pinIntChannel));
    }
    else if(mode == FALLING)
    {
        Chip_PININT_SetPinModeEdge(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntLow(LPC_PININT, PININTCH(pinIntChannel));
    }
    else if(mode == CHANGE)
    {
        Chip_PININT_SetPinModeEdge(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntHigh(LPC_PININT, PININTCH(pinIntChannel));
        Chip_PININT_EnableIntLow(LPC_PININT, PININTCH(pinIntChannel));
    }

    /* Enable interrupt in the NVIC */
    NVIC_ClearPendingIRQ(pinIntIRQ);
    NVIC_EnableIRQ(pinIntIRQ);
}
Example #13
0
void SPI1_IRQHandler(void)
#endif
{
    mss_spi_isr(&g_mss_spi1);
    NVIC_ClearPendingIRQ(SPI1_IRQn);
}
Example #14
0
/***************************************************************************//**
 * This function works around SAR28498 where receive overflows were not cleared
 * properly. This is due to the receive FIFO counters getting out of synch when
 * a receive overflow occurs. This can only be cleared on the A2F200 by
 * resetting the SPI block.
 */
static void recover_from_rx_overflow
(
    mss_spi_instance_t * this_spi
)
{
    uint32_t control_reg;
    uint32_t clk_gen;
    uint32_t frame_size;
    uint32_t control2;
    uint32_t packet_size;
    uint32_t cmd_size;
    uint32_t slave_select;
    
    /*
     * Read current SPI hardware block configuration.
     */
    control_reg = this_spi->hw_reg->CONTROL;
    clk_gen = this_spi->hw_reg->CLK_GEN;
    frame_size = this_spi->hw_reg->TXRXDF_SIZE;
    control2 = this_spi->hw_reg->CONTROL2;
    packet_size = this_spi->hw_reg->PKTSIZE;
    cmd_size = this_spi->hw_reg->CMDSIZE;
    slave_select = this_spi->hw_reg->SLAVE_SELECT;
     
    /*
     * Reset the SPI hardware block.
     */
    if(this_spi == &g_mss_spi0)
    {
        this_spi->hw_reg = ((SPI_REVB_TypeDef *) SPI0_BASE);
        this_spi->irqn = SPI0_IRQn;

        /* reset SPI0 */
        SYSREG->SOFT_RST_CR |= SYSREG_SPI0_SOFTRESET_MASK;
        /* Clear any previously pended SPI0 interrupt */
        NVIC_ClearPendingIRQ(SPI0_IRQn);
        /* Take SPI0 out of reset. */
        SYSREG->SOFT_RST_CR &= ~SYSREG_SPI0_SOFTRESET_MASK;

        this_spi->hw_reg->CONTROL &= ~CTRL_REG_RESET_MASK;
    }
    else
    {
        this_spi->hw_reg = ((SPI_REVB_TypeDef *) SPI1_BASE);
        this_spi->irqn = SPI1_IRQn;
        
        /* reset SPI1 */
        SYSREG->SOFT_RST_CR |= SYSREG_SPI1_SOFTRESET_MASK;
        /* Clear any previously pended SPI1 interrupt */
        NVIC_ClearPendingIRQ(SPI1_IRQn);
        /* Take SPI1 out of reset. */
        SYSREG->SOFT_RST_CR &= ~SYSREG_SPI1_SOFTRESET_MASK;
        
        this_spi->hw_reg->CONTROL &= ~CTRL_REG_RESET_MASK;
    }
    
    /*
     * Restore SPI hardware block configuration.
     */
    this_spi->hw_reg->CONTROL &= ~(uint32_t)CTRL_ENABLE_MASK;
    this_spi->hw_reg->CONTROL = control_reg;
    this_spi->hw_reg->CLK_GEN = clk_gen;
    this_spi->hw_reg->TXRXDF_SIZE = frame_size;
    this_spi->hw_reg->CONTROL |= CTRL_ENABLE_MASK;
    this_spi->hw_reg->CONTROL2 = control2;
    this_spi->hw_reg->PKTSIZE = packet_size;
    this_spi->hw_reg->CMDSIZE = cmd_size;
    this_spi->hw_reg->SLAVE_SELECT = slave_select;
}
Example #15
0
void ADCSampler::begin(unsigned int samplingRate)
{
  this->sampleingRate = sampleingRate;
  // Turning devices Timer on.
  pmc_enable_periph_clk(ID_TC0); 


  // Configure timer
  TC_Configure(TC0, 0, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_ACPA_CLEAR | TC_CMR_ACPC_SET | TC_CMR_ASWTRG_CLEAR | TC_CMR_TCCLKS_TIMER_CLOCK1);

  // It is good to have the timer 0 on PIN2, good for Debugging 
  //int result = PIO_Configure( PIOB, PIO_PERIPH_B, PIO_PB25B_TIOA0, PIO_DEFAULT);

  // Configure ADC pin A7
  //  the below code is taken from adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);

  ADC->ADC_CR = ADC_CR_SWRST;                            // Reset the controller.
  ADC->ADC_MR = 0;                                       // Reset Mode Register.
  ADC->ADC_PTCR = (ADC_PTCR_RXTDIS | ADC_PTCR_TXTDIS);   // Reset PDC transfer.
  ADC->ADC_MR |= ADC_MR_PRESCAL(3);                      // ADC clock = MSCK/((PRESCAL+1)*2), 13 -> 750000 Sps
  ADC->ADC_MR |= ADC_MR_STARTUP_SUT0;                    // What is this by the way?
  ADC->ADC_MR |= ADC_MR_TRACKTIM(15);
  ADC->ADC_MR |= ADC_MR_TRANSFER(1);
  ADC->ADC_MR |= ADC_MR_TRGEN_EN;                         // Hardware trigger selected by TRGSEL field is enabled. Включен аппаратный триггер, выбранный по полю TRGSEL.
  ADC->ADC_MR |= ADC_MR_TRGSEL_ADC_TRIG1;                 // selecting TIOA0 as trigger.
  ADC->ADC_MR |= ADC_MR_LOWRES_BITS_12;                   // brief (ADC_MR) 12-bit resolution 
  //ADC->ADC_ACR |= ADC_ACR_TSON;                         // Включить датчик температуры    
 
  ADC->ADC_CHER = ADC_CHANNELS;                           // Записать контролируемые входа
  ADC->ADC_CHDR = ADC_CHANNELS_DIS;                       // Отключить не используемые входа
  ADC->ADC_EMR = ADC_EMR_CMPMODE_IN                       // Генерирует событие, когда преобразованные данные пересекают окно сравнения.
	//  | ADC_EMR_CMPSEL(4)                               // Compare channel 4 = A3
	  | ADC_EMR_CMPALL                                    // Compare ALL channel
	  | ADC_EMR_CMPFILTER(0);                             // Количество последовательных событий сравнения, необходимых для повышения флага = CMPFILTER + 1
														  // При запрограммированном значении 0 флаг увеличивается, как только происходит событие.

  ADC->ADC_CWR = ADC_CWR_LOWTHRES(_compare_Low) | ADC_CWR_HIGHTHRES(_compare_High); // Установить высокий и низкий порог компаратора АЦП

  //ADC->ADC_SEQR1 = 0x01234567;                            // использовать A0 до A7 в порядке в массив
  //ADC->ADC_SEQR2 = 0x00dcba00;                            // использовать для А8 А11 следующие действия по порядку в массив  

  /* Interupts */
  ADC->ADC_IDR = ~ADC_IDR_ENDRX;                        // сбросить регистры прерывания по готовности данных.
  ADC->ADC_IDR = ~ADC_IDR_COMPE;                        // сбросить регистры копаратора.
  ADC->ADC_IER =  ADC_IER_ENDRX;                        // Включить прерывание по готовности данных.
 // ADC->ADC_IER =  ADC_IER_COMPE;                        // Прерывание по совпадению сравнения компаратором
  ADC->ADC_ISR = ~ADC_ISR_COMPE;                        // ADC Interrupt Status Register Обнулить ошибку сравнения с момента последнего чтения ADC_ISR.
  /* Waiting for ENDRX as end of the transfer is set
    when the current DMA transfer is done (RCR = 0), i.e. it doesn't include the
    next DMA transfer.

    If we trigger on RXBUFF This flag is set if there is no more DMA transfer in
    progress (RCR = RNCR = 0). Hence we may miss samples.

	Ожидание окончания ENDRX в конце передачи
	когда выполняется текущая передача DMA (RCR = 0), то есть она не включает следующая передача DMA.
    Если мы запускаем RXBUFF, этот флаг устанавливается, если больше нет передачи DMA в прогресс (RCR = RNCR = 0). 
	Следовательно, мы можем пропустить образцы.
  */

  
  unsigned int cycles = 42000000 / samplingRate;

  /*  timing of ADC */
  TC_SetRC(TC0, 0, cycles);                             // TIOA0 goes HIGH on RC.
  TC_SetRA(TC0, 0, cycles / 2);                         // TIOA0 goes LOW  on RA.

  // We have to reinitalise just in case the Sampler is stopped and restarted...
  // Мы должны приступить к реинициализировать на случай, если Sampler остановлен и перезапущен ...
  dataReady = false;
  dataHigh = false;                       // Признак срабатывания компаратора
  adcDMAIndex = 0;
  adcTransferIndex = 0;
  for (int i = 0; i < NUMBER_OF_BUFFERS; i++)
  {
    memset((void *)adcBuffer[i], 0, BUFFER_SIZE);
  }

  ADC->ADC_RPR  = (unsigned long) adcBuffer[adcDMAIndex];         // DMA buffer
  ADC->ADC_RCR  = (unsigned int)  BUFFER_SIZE;                    // ADC works in half-word mode.
  ADC->ADC_RNPR = (unsigned long) adcBuffer[(adcDMAIndex + 1)];   // next DMA buffer
  ADC->ADC_RNCR = (unsigned int)  BUFFER_SIZE;

  // Enable interrupts
  NVIC_SetPriorityGrouping(NVIC_PriorityGroup_1);
  NVIC_DisableIRQ(ADC_IRQn);
  NVIC_ClearPendingIRQ(ADC_IRQn);  
  NVIC_SetPriority(ADC_IRQn, 6);  
  NVIC_EnableIRQ(ADC_IRQn);
  ADC->ADC_PTCR  =  ADC_PTCR_RXTEN;                               // Enable receiving data.
  ADC->ADC_CR   |=  ADC_CR_START;                                 // start waiting for trigger.

  // Start timer
  TC0->TC_CHANNEL[0].TC_SR;
  TC0->TC_CHANNEL[0].TC_CCR = TC_CCR_CLKEN;
  TC_Start(TC0, 0);
}
Example #16
0
/**************************************************************************//**
 * @brief  Main function
 *****************************************************************************/
int main(void)
{
  unsigned char pucMACArray[8];
  uint32_t      temp;

  /* Chip revision alignment and errata fixes */
  CHIP_Init();

  /* Ensure core frequency has been updated */
  SystemCoreClockUpdate();
  CMU_ClockEnable(cmuClock_ADC0, true);

  /* Setup SysTick Timer for 1 msec interrupts  */
  if (SysTick_Config(SystemCoreClock / 1000)) while (1) ;

  /* Setup ADC for sampling internal temperature sensor. */
  setupSensor();

  /* Spi init*/
  spiInit();


#if LWIP_DHCP
  /* Initialze the lwIP library, using DHCP.*/
  lwIPInit(pucMACArray, 0, 0, 0, IPADDR_USE_DHCP);
#else
  /* Initialze the lwIP library, using Static IP.*/
  lwIPInit(pucMACArray, IPADDR(192, 168, 79, 160), IPADDR(255, 255, 255, 0), \
           IPADDR(192, 168, 79, 1), IPADDR_USE_STATIC);
#endif

  /* Initialize a sample httpd server.*/
  httpd_init();

  /* Start one ADC sample */
  ADC_Start(ADC0, adcStartSingle);

  /* Enable board control interrupts */
  gpioSetup();

  axspi_write_reg(~IMR_RXPKT, P0_IMR);

  /* Start LCD  without boost */
  SegmentLCD_Init(false);

  CMU_ClockEnable(cmuClock_RTC, true);
  /* RTC configuration structure */
  RTC_Init_TypeDef rtcInit = {
    .enable   = false,
    .debugRun = false,
    .comp0Top = true
  };

  /* Initialize RTC */
  RTC_Init(&rtcInit);

  /* Set COMP0 value which will be the top value as well */
  RTC_CompareSet(RTC_COMP, RTC_COMP_VALUE);

  /* Clear all pending interrupts */
  RTC_IntClear(0x7);

  /* Enable COMP0 interrupts */
  RTC_IntEnable(0x2);

  /* Enable interrupts */
  NVIC_ClearPendingIRQ(RTC_IRQn);
  NVIC_EnableIRQ(RTC_IRQn);

  RTC_Enable(true);

  while (1)
  {
    /* check temperature flag*/
    if (read_temperature)
    {
      temp = ADC_DataSingleGet(ADC0);

      /* Show Celsius on numeric part of display */
      temperature = (int)(convertToCelsius(temp));

      /* Start a new conversion */
      ADC_Start(ADC0, adcStartSingle);

      /* Reset temperature flag */
      read_temperature = 0;
    }

    if (updateIpFlag)
    {
      switch (ip_field)
      {
      case 1:
      {
        SegmentLCD_Write(IP_ADDR_FIRST_TEXT);
        SegmentLCD_Number(IP_ADDR_FIRST_NUM(lwip_netif.ip_addr.addr));
        ip_field++;
      }
      break;

      case 2:
      {
        SegmentLCD_Write(IP_ADDR_SECOND_TEXT);
        SegmentLCD_Number(IP_ADDR_SECOND_NUM(lwip_netif.ip_addr.addr));
        ip_field++;
      }
      break;

      case 3:
      {
        SegmentLCD_Write(IP_ADDR_THIRD_TEXT);
        SegmentLCD_Number(IP_ADDR_THIRD_NUM(lwip_netif.ip_addr.addr));
        ip_field++;
      }
      break;

      case 4:
      {
        SegmentLCD_Write(IP_ADDR_FOURTH_TEXT);
        SegmentLCD_Number(IP_ADDR_FOURTH_NUM(lwip_netif.ip_addr.addr));
        ip_field = 1;
      }
      break;

      default: break;
      }

      updateIpFlag = false;
    }
  }
}
Example #17
0
int16_t radio_init(void)
{
    if (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0UL) {
        NRF_CLOCK->TASKS_HFCLKSTART = 1UL;
        while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0UL);
    }

    /* nRF51 Series Reference Manual v2.1, section 6.1.1, page 18
     * PCN-083 rev.1.1
     *
     * Fine tune BLE deviation parameters.
     */
    if ((NRF_FICR->OVERRIDEEN & FICR_OVERRIDEEN_BLE_1MBIT_Msk)
            == (FICR_OVERRIDEEN_BLE_1MBIT_Override
                << FICR_OVERRIDEEN_BLE_1MBIT_Pos)) {
        NRF_RADIO->OVERRIDE0 = NRF_FICR->BLE_1MBIT[0];
        NRF_RADIO->OVERRIDE1 = NRF_FICR->BLE_1MBIT[1];
        NRF_RADIO->OVERRIDE2 = NRF_FICR->BLE_1MBIT[2];
        NRF_RADIO->OVERRIDE3 = NRF_FICR->BLE_1MBIT[3];
        NRF_RADIO->OVERRIDE4 = NRF_FICR->BLE_1MBIT[4] | 0x80000000;
    }

    /* nRF51 Series Reference Manual v2.1, section 16.2.7, page 86 */
    NRF_RADIO->MODE = RADIO_MODE_MODE_Ble_1Mbit << RADIO_MODE_MODE_Pos;

    /* Link Layer specification section 4.1, Core 4.1, page 2524
     * nRF51 Series Reference Manual v2.1, section 16.2.7, page 92
     *
     * Set the inter frame space (T_IFS) to 150 us.
     */
    NRF_RADIO->TIFS = 150;

    /* nRF51 Series Reference Manual v2.1, section 16.2.9, page 88
     *
     * Enable data whitening, set the maximum payload length and set the
     * access address size (3 + 1 octets).
     */
    NRF_RADIO->PCNF1 =
        (RADIO_PCNF1_WHITEEN_Enabled << RADIO_PCNF1_WHITEEN_Pos) |
        (MAX_PAYLOAD_LEN << RADIO_PCNF1_MAXLEN_Pos) |
        (3UL << RADIO_PCNF1_BALEN_Pos);

    /* nRF51 Series Reference Manual v2.1, section 16.1.4, page 74
     * nRF51 Series Reference Manual v2.1, section 16.2.14-15, pages 89-90
     *
     * Preset the address to use when receive and transmit packets (logical
     * address 0, which is assembled by base address BASE0 and prefix byte
     * PREFIX0.AP0.
     */
    NRF_RADIO->RXADDRESSES = 1UL;
    NRF_RADIO->TXADDRESS = 0UL;

    /* nRF51 Series Reference Manual v2.1, section 16.1.7, page 76
     * nRF51 Series Reference Manual v2.1, sections 16.1.16-17, page 90
     *
     * Configure the CRC length (3 octets), polynominal and set it to
     * ignore the access address when calculate the CRC.
     */
    NRF_RADIO->CRCCNF =
        (RADIO_CRCCNF_LEN_Three << RADIO_CRCCNF_LEN_Pos) |
        (RADIO_CRCCNF_SKIP_ADDR_Skip << RADIO_CRCCNF_SKIP_ADDR_Pos);
    NRF_RADIO->CRCPOLY = 0x100065B;

    /* nRF51 Series Reference Manual v2.1, section 16.1.2, page 74
     * nRF51 Series Reference Manual v2.1, sections 16.1.8, page 87
     * Link Layer specification section 2.3, Core 4.1, page 2504
     * Link Layer specification section 2.4, Core 4.1, page 2511
     *
     * Configure the header size. The nRF51822 has 3 fields before the
     * payload field: S0, LENGTH and S1. These fields can be used to store
     * the PDU header.
     */
    NRF_RADIO->PCNF0 = (1UL << RADIO_PCNF0_S0LEN_Pos)
                       | (8UL << RADIO_PCNF0_LFLEN_Pos)
                       | (0UL << RADIO_PCNF0_S1LEN_Pos);

    /* nRF51 Series Reference Manual v2.1, section 16.1.8, page 76
     * nRF51 Series Reference Manual v2.1, section 16.1.10-11, pages 78-80
     * nRF51 Series Reference Manual v2.1, section 16.2.1, page 85
     *
     * Enable READY_START short: when the READY event happens, initialize
     * the START task.
     *
     * Enable END_DISABLE short: when the END event happens, initialize the
     * DISABLE task.
     */
    NRF_RADIO->SHORTS = BASE_SHORTS;

    /* Trigger RADIO interruption when an END event happens */
    NRF_RADIO->INTENSET = RADIO_INTENSET_END_Msk;

    NVIC_SetPriority(RADIO_IRQn, IRQ_PRIORITY_HIGH);
    NVIC_ClearPendingIRQ(RADIO_IRQn);
    NVIC_EnableIRQ(RADIO_IRQn);

    radio_set_callbacks(NULL, NULL);
    radio_set_tx_power(RADIO_POWER_0_DBM);
    radio_set_out_buffer(NULL);

    NRF_RADIO->PACKETPTR = (uint32_t) inbuf;
    memset(inbuf, 0, sizeof(inbuf));

    status = STATUS_INITIALIZED;

    return 0;
}
Example #18
0
/*****************************************************************************
** Function name:		GPIOSetGroupedInterrupt
**
** Descriptions:		Set interrupt logic, sense, eventPattern, etc.
**						logic: AND or OR, 0 is OR, 1 is AND 
**						sensePattern: edge or level, 0 is edge, 1 is level 
**						event/polarity: 0 is active low/falling, 1 is high/rising.
**
** parameters:			group #, bit pattern, logic, sense, event(polarity) pattern
** 						
** Returned value:		None
** 
*****************************************************************************/
void GPIOSetGroupedInterrupt( uint32_t groupNum, uint32_t *bitPattern, uint32_t logic,
		uint32_t sense, uint32_t *eventPattern )
{
  switch ( groupNum )
  {
	case GROUP0:
	  if ( sense == 0 )
	  {
		LPC_GPIO_GROUP_INT0->CTRL &= ~(0x1<<2);	/* Edge trigger */
	  }
	  else
	  {
		LPC_GPIO_GROUP_INT0->CTRL |= (0x1<<2);	/* Level trigger. */
	  }
	  if ( logic == 0 )
	  {
		LPC_GPIO_GROUP_INT0->CTRL &= ~(0x1<<1);	/* OR */
	  }
	  else
	  {
		LPC_GPIO_GROUP_INT0->CTRL |= (0x1<<1);	/* AND */
	  }
	  LPC_GPIO_GROUP_INT0->PORT_POL[0] = *((uint32_t *)(eventPattern + 0));
	  LPC_GPIO_GROUP_INT0->PORT_POL[1] = *((uint32_t *)(eventPattern + 1));
	  LPC_GPIO_GROUP_INT0->PORT_ENA[0] = *((uint32_t *)(bitPattern + 0));
	  LPC_GPIO_GROUP_INT0->PORT_ENA[1] = *((uint32_t *)(bitPattern + 1));
      /* as soon as enabled, an edge may be generated       */
	  /* clear interrupt flag and NVIC pending interrupt to */
	  /* workaround the potential edge generated as enabled */
	  LPC_GPIO_GROUP_INT0->CTRL |= (1<<0);
	  NVIC_ClearPendingIRQ(GINT0_IRQn);
	  NVIC_EnableIRQ(GINT0_IRQn);
	break;
	case GROUP1:
	  if ( sense == 0 )
	  {
		LPC_GPIO_GROUP_INT1->CTRL &= ~(0x1<<2);	/* Edge trigger */
	  }
	  else
	  {
		LPC_GPIO_GROUP_INT1->CTRL |= (0x1<<2);	/* Level trigger. */
	  }
	  if ( logic == 0 )
	  {
		LPC_GPIO_GROUP_INT1->CTRL &= ~(0x1<<1);	/* OR */
	  }
	  else
	  {
		LPC_GPIO_GROUP_INT1->CTRL |= (0x1<<1);	/* AND */
	  }
	  LPC_GPIO_GROUP_INT1->PORT_POL[0] = *((uint32_t *)(eventPattern + 0));
	  LPC_GPIO_GROUP_INT1->PORT_POL[1] = *((uint32_t *)(eventPattern + 1));
	  LPC_GPIO_GROUP_INT1->PORT_ENA[0] = *((uint32_t *)(bitPattern + 0));
	  LPC_GPIO_GROUP_INT1->PORT_ENA[1] = *((uint32_t *)(bitPattern + 1));
      /* as soon as enabled, an edge may be generated       */
	  /* clear interrupt flag and NVIC pending interrupt to */
	  /* workaround the potential edge generated as enabled */
	  LPC_GPIO_GROUP_INT1->CTRL |= (1<<0);
	  NVIC_ClearPendingIRQ(GINT1_IRQn);
	  NVIC_EnableIRQ(GINT1_IRQn);
	break;
	default:
	  break;
  }

  return;
}
int GPIO_IRQ(void)
{
  uint32_t err_code = 0, return_val = 0;
  int i = 0;
  int irq_counter = 0;

  puts("Stage 3 - GPIO Pin IRQ Test\n");

  puts("- Stage 3a - GPIO High Level IRQ Test\n");

  CMSDK_GPIO0->DATAOUT = 0x0000;                         //set data out to 0 to test high level IRQ
  CMSDK_gpio_SetOutEnable(CMSDK_GPIO0, 0xFFFF);         //set output enable to output on all ports of GPIO 0

  for(i = 0; i < 16; i++)
  {
    CMSDK_gpio_SetIntHighLevel(CMSDK_GPIO0, i);         //set all pins to high level interrupt and clear any
    CMSDK_gpio_IntClear(CMSDK_GPIO0, i);                //outstanding set interrupts
  }

  NVIC_ClearPendingIRQ(PORT0_ALL_IRQn);                   //clear all global NVIC PORT0 pending interrupts

  NVIC_EnableIRQ(PORT0_ALL_IRQn);                         //enable NVIC interrupts on PORT0

  for(i = 0; i < 16; i++){

    CMSDK_gpio_SetIntEnable(CMSDK_GPIO0, i);            //enable interrupt for the pin to be tested

    if(!((CMSDK_GPIO0->INTENSET) & (1 << i))) err_code = (1 << (2*i));//check to see if the interrupt enable register is
                                                                      //set for the pin which it should have just been
    N = i;

    CMSDK_GPIO0->DATAOUT = (0x0001 << i);                //set data out on pin0 high to cause a high level interrupt
                                                          //repeat for all other pins 0001 -> 0010 -> 0100 -> 1000
    CMSDK_gpio_ClrIntEnable(CMSDK_GPIO0, i );           /*clear interrupt enable*/

    if((CMSDK_GPIO0->INTENSET) & ~(1 << i)) err_code = (1 << (2*i +1));//check to see if the interrupt enable register is
                                                                        //clear for the pin which it should have just been

    /* check to see whether intstatus, for the specified pin, is 2, which corresponds to a high level interrupt */

    if(intstatus[i] == 2) irq_counter++;
    else err_code |= (1 << i);
  }

  if((irq_counter == 16) && (err_code == 0)) puts("High Level IRQ Tests Passed Successfully\n");
  else{
    printf("\nHigh Level IRQ Tests Failed, Error Code: (0x%x)\n", err_code);
    err_code = 0;       /*if the port did not have 1 HL IRQ for each pin as expected then display error*/
    return_val = 8;
  }

  puts("- Stage 3b - GPIO Rising Edge IRQ Test\n");

  irq_counter = 0;

  CMSDK_GPIO0->DATAOUT = 0x0000;   //set data out to 0 to test rising edge IRQ

  for(i = 0; i < 16; i++) CMSDK_gpio_SetIntRisingEdge(CMSDK_GPIO0, i); //set all pins to rising edge interrupts

  for(i = 0; i < 16; i++){

    CMSDK_gpio_SetIntEnable(CMSDK_GPIO0, i);    //enable interrupts on specified pin then set data out to 1
                                                  //for pin 0 then repeat for all subsequent pins whilst still

    if(!((CMSDK_GPIO0->INTENSET) & (1 << i))) err_code = (1 <<(2*i));//check to see if the interrupt enable register is
                                                                      //set for the pin which it should have just been
    N = i;

    CMSDK_GPIO0->DATAOUT = (0x0001 << i) | CMSDK_GPIO0->DATA; //keeping all other pins high 0000->0001->0011->0111->1111

    CMSDK_gpio_ClrIntEnable(CMSDK_GPIO0, i);                     //clear interrupt enable for specified pin

    if((CMSDK_GPIO0->INTENSET) & ~(1 << i)) err_code = (1 <<(2*i + 1));//check to see if the interrupt enable register is
                                                                        //clear for the pin which it should have just been

    /* check to see whether intstatus, for the specified pin, is 1, which corresponds to a rising edge interrupt */

    if(intstatus[i] == 1) irq_counter++;
    else err_code |= (1 << i);
  }

  if((irq_counter == 16) && (err_code == 0)) puts("Rising Edge IRQ Tests Passed Successfully\n");
  else{
    printf("\nRising Edge IRQ Tests Failed, Error Code: (0x%x\n", err_code);
    err_code = 0;     /*if the port did not have 1 RE IRQ for each pin as expected then display error*/
    return_val = 16;
  }

  puts("- Stage 3c - GPIO Falling Edge IRQ Test\n");

  irq_counter = 0;

  CMSDK_GPIO0->DATAOUT = 0xFFFF;

  for(i = 0; i < 16; i++) CMSDK_gpio_SetIntFallingEdge(CMSDK_GPIO0, i);   //set all pins to falling edge interrupts

  for(i = 0; i  < 16; i++){

    /* Counter change from 0->1->2 ...15 */

    CMSDK_gpio_SetIntEnable(CMSDK_GPIO0, i);    //enable interrupts on specified pin then set data out to
                                                  //0xFFFF and shiftright to cause a falling edge on
                                                  //pin 15 and then shift each time to cause a falling
                                                  // edge on pins 14 -> 0 1111 >> 0111 >> 0011 >> 0001 >> 0000

    if(!((CMSDK_GPIO0->INTENSET) & (1 << i)))    //check to see if the interrupt enable register is
      err_code = (1 << 2*i);                      //set for the pin which it should have just been

    N = i;

    CMSDK_GPIO0->DATAOUT = (CMSDK_GPIO0->DATA  & ~(1 << i));

    CMSDK_gpio_ClrIntEnable(CMSDK_GPIO0, i);    //disable interrupts on specified pin

    if((CMSDK_GPIO0->INTENSET) & ~(1 << i))      //check to see if the interrupt enable register is
      err_code = (1 << (2*i + 1));                //clear for the pin which it should have just been

    /* check to see whether intstatus, for the specified pin, is 3, which corresponds to a falling edge interrupt */

    if(intstatus[i] == 3) irq_counter++;
    else err_code |= (1 << i);
  }

  if((irq_counter == 16) && (err_code == 0)) puts("Falling Edge IRQ Tests Passed Successfully\n");
  else{
    printf("\nFalling Edge IRQ Tests Failed, Error Code: (0x%x)\n", err_code);
    err_code = 0; /*if the port did not have 1 FE IRQ for each pin as expected then display error*/
    return_val = 32;
  }

  puts("- Stage 3d - GPIO Low Level IRQ Test\n");

  irq_counter = 0;
  data = 0xFFFE;

  CMSDK_GPIO0->DATAOUT = 0xFFFF;           //set dataout to all ones ready to test low level interrupts

  for(i = 0; i < 16; i++) CMSDK_gpio_SetIntLowLevel(CMSDK_GPIO0, i);            //set all pins to low level interrupts

  for(i = 0; i < 16; i++){

    CMSDK_gpio_SetIntEnable(CMSDK_GPIO0, i);                          //enable interrupts on specified pin and set the
                                                                        //data output to 0xFFFF XOR with 1 shifted to the
    if(!((CMSDK_GPIO0->INTENSET) & (1 << i))) err_code = (1 << (2*i)); //pins position so that just the desired pin is
                                                                        //set to 0 1111 -> 1110 -> 1101 -> 1011 -> 1111
    N = i;

    CMSDK_GPIO0->DATAOUT = (0x0001 << i) ^ 0xFFFF;

    CMSDK_gpio_ClrIntEnable(CMSDK_GPIO0, i);                                    //disable interrupts on specified pin

    if((CMSDK_GPIO0->INTENSET) & ~(1 << i))                      //check to see if the interrupt enable register is
      err_code = (1 << (2*i + 1));                                //clear for the pin which it should have just been

    /* check to see whether intstatus, for the specified pin, is 4, which corresponds to a low level interrupt */

    if(intstatus[i] == 4) irq_counter++;
    else err_code |= (1 << i);
  }

  if((irq_counter == 16) && (err_code == 0)) puts("Low Level IRQ Tests Passed Successfully\n");
  else{
    printf("\nLow Level IRQ Tests Failed, Error Code: (0x%x)\n\n", err_code);
    /*if the port did not have 1 LL IRQ for each pin as expected then display error*/
    return_val = 64;
  }

  irq_counter = 0;

  NVIC_DisableIRQ(PORT0_ALL_IRQn);                                       //disable all GPIO interrupts on PORT 0

  NVIC_ClearPendingIRQ(PORT0_ALL_IRQn);                                  //clear any outstanding GPIO interrupts

  for(i = 0; i < 16; i++) CMSDK_gpio_IntClear(CMSDK_GPIO0, i);         //clear any outstanding GPIO interrupts

  return return_val;
}
Example #20
0
/**
 * Initialization for GMAC device.
 * Should be called at the beginning of the program to set up the
 * network interface.
 */
void gmac_tapdev_init(void)
{
    sGmacd    *pGmacd = &gGmacd;
    GMacb      *pGmacb = &gGmacb;
    sGmacInit Que0, Que;
//    uint32_t  dwErrCount = 0 ;

    /* Init GMAC driver structure */
    memset(&Que0, 0, sizeof(Que0));
    Que0.bIsGem = 1;
    Que0.bDmaBurstLength = 4;
    Que0.pRxBuffer =pRxBuffer;
    Que0.pRxD = gRxDs;
    Que0.wRxBufferSize = BUFFER_SIZE;
    Que0.wRxSize = RX_BUFFERS;
    Que0.pTxBuffer = pTxBuffer;
    Que0.pTxD = gTxDs;
    Que0.wTxBufferSize = BUFFER_SIZE;
    Que0.wTxSize = TX_BUFFERS;
    Que0.pTxCb = gTxCbs;



    memset(&Que, 0, sizeof(Que));
    Que.bIsGem = 1;
    Que.bDmaBurstLength = 4;
    Que.pRxBuffer =pRxDummyBuffer;
    Que.pRxD = gDummyRxDs;
    Que.wRxBufferSize = DUMMY_BUFF_SIZE;
    Que.wRxSize = DUMMY_SIZE;
    Que.pTxBuffer = pTxDummyBuffer;
    Que.pTxD = gDummyTxDs;
    Que.wTxBufferSize = DUMMY_BUFF_SIZE;
    Que.wTxSize = DUMMY_SIZE;
    Que.pTxCb = gDummyTxCbs;

    /* Init GMAC driver structure */
    GMACD_Init(pGmacd, GMAC, ID_GMAC, GMAC_CAF_ENABLE, GMAC_NBC_DISABLE);
    GMACD_InitTransfer(pGmacd, &Que, GMAC_QUE_2);

    GMACD_InitTransfer(pGmacd, &Que, GMAC_QUE_1);

    GMACD_InitTransfer(pGmacd, &Que0, GMAC_QUE_0);
    GMAC_SetAddress(gGmacd.pHw, 0, gGMacAddress);

    /* Setup GMAC buffers and interrupts */
    /* Configure and enable interrupt on RC compare */
    NVIC_ClearPendingIRQ(GMAC_IRQn);
    NVIC_EnableIRQ(GMAC_IRQn);

    /* Init GMACB driver */
    GMACB_Init(pGmacb, pGmacd, BOARD_GMAC_PHY_ADDR);

    /* PHY initialize */
    if (!GMACB_InitPhy(pGmacb, BOARD_MCK,  gmacResetPins, 1,  gmacPins, PIO_LISTSIZE( gmacPins )))
    {
        printf( "P: PHY Initialize ERROR!\n\r" ) ;
        return;
    }

    /* Auto Negotiate, work in RMII mode */
    if (!GMACB_AutoNegotiate(pGmacb))
    {
        printf( "P: Auto Negotiate ERROR!\n\r" ) ;
        return;
    }


    printf( "P: Link detected \n\r" ) ;
}
int main(void)
{
	enum sleepmgr_mode current_sleep_mode = SLEEPMGR_ACTIVE;

	/*
	 * 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);

	rtt_init(RTT, 32768);

	/* Enable RTT interrupt */
	NVIC_DisableIRQ(RTT_IRQn);
	NVIC_ClearPendingIRQ(RTT_IRQn);
	NVIC_SetPriority(RTT_IRQn, 0);
	NVIC_EnableIRQ(RTT_IRQn);
	rtt_enable_interrupt(RTT, RTT_MR_ALMIEN);

	/* Set wakeup source to rtt_alarm */
	pmc_set_fast_startup_input(PMC_FSMR_RTTAL);
#if (!(SAMG51 || SAMG53 || SAMG54))
	supc_set_wakeup_mode(SUPC, SUPC_WUMR_RTTEN_ENABLE);
#endif
	/* Initialize the sleep manager, lock initial mode. */
	sleepmgr_init();
	sleepmgr_lock_mode(current_sleep_mode);

	while (1) {

		rtt_write_alarm_time(RTT, rtt_read_timer_value(RTT) + SLEEP_TIME);
		/*
		 * 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(ACTIVE_TIME);

		/* 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);
	}
}
Example #22
0
void RIT_IRQHandler(void) {
  LPC_RIT->RICTRL = BV(RITINT);
  NVIC_ClearPendingIRQ(RIT_IRQn);
  wokefromrit = 1;
  RIT_Hook();
}
/**
  * @brief  Clears the pending bit of an external interrupt.
  * @param  IRQn External interrupt number
  *         This parameter can be an enumerator of IRQn_Type enumeration
  *         (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f3xxxx.h))
  * @retval None
  */
void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
  /* Clear pending interrupt */
  NVIC_ClearPendingIRQ(IRQn);
}
Example #24
0
 /**
 ****************************************************************************************
 * @brief ADC interrupt handler
 ****************************************************************************************
 */
void ADC_IRQHandler(void)
{
    uint32_t status, data;

    status = adc_adc_GetSR(QN_ADC);
    if (status & ADC_MASK_DAT_RDY_IF)
    {
        while (adc_adc_GetSR(QN_ADC) & ADC_MASK_DAT_RDY_IF)
        {
            /* clear interrupt flag by read data */
            data = adc_adc_GetDATA(QN_ADC);
            if (adc_env.samples > 0) {
                *adc_env.bufptr++ = data;
                adc_env.samples--;

                if (adc_env.samples == 0) {
                    adc_enable(MASK_DISABLE); // disable ADC
                    adc_clean_fifo();
                    NVIC_ClearPendingIRQ(ADC_IRQn);

#if ADC_CALLBACK_EN==TRUE
                    if (adc_env.callback != NULL)
                    {
                        adc_env.callback();
                    }
#endif
                }
                else {

                    // single mode enable, software trigger
                    if ((adc_env.trig_src == ADC_TRIG_SOFT) && ((adc_env.mode == SINGLE_SCAN_MOD)||(adc_env.mode == SINGLE_MOD))) {

                        scan_ch_num--;
                        if (scan_ch_num == 0) {

                            // SFT_START 0->1 trigger ADC conversion
                            adc_adc_SetADC0WithMask(QN_ADC, ADC_MASK_SFT_START, MASK_DISABLE);
                            adc_adc_SetADC0WithMask(QN_ADC, ADC_MASK_SFT_START, MASK_ENABLE);

                            // restore scan_ch_num
                            if (adc_env.mode == SINGLE_SCAN_MOD) {
                                scan_ch_num = adc_env.end_ch - adc_env.start_ch + 1;
                            }
                            else {
                                scan_ch_num = 1;
                            }
                        }
                    }
                }
            }
        }
    }

    if (status & ADC_MASK_FIFO_OF_IF)
    {
        adc_clean_fifo();

        /* clear interrupt flag */
        adc_adc_ClrSR(QN_ADC, ADC_MASK_FIFO_OF_IF);
    }


    if (status & ADC_MASK_WCMP_IF)
    {
        /* clear interrupt flag */
        adc_adc_ClrSR(QN_ADC, ADC_MASK_WCMP_IF);

#if ADC_WCMP_CALLBACK_EN==TRUE
        if (adc_env.wcmp_callback != NULL)
        {
            adc_env.wcmp_callback();
        }
#endif
    }
}
uint32_t app_timer_init(uint32_t                      prescaler,
                        uint8_t                       max_timers,
                        uint8_t                       op_queues_size,
                        void *                        p_buffer,
                        app_timer_evt_schedule_func_t evt_schedule_func)
{
    int i;

    // Check that buffer is correctly aligned
    if (!is_word_aligned(p_buffer))
    {
        return NRF_ERROR_INVALID_PARAM;
    }
    // Check for NULL buffer
    if (p_buffer == NULL)
    {
        return NRF_ERROR_INVALID_PARAM;
    }
    
    // Stop RTC to prevent any running timers from expiring (in case of reinitialization)
    rtc1_stop();
    
    m_evt_schedule_func = evt_schedule_func;

    // Initialize timer node array
    m_node_array_size = max_timers;
    mp_nodes          = p_buffer;
    
    for (i = 0; i < max_timers; i++)
    {
        mp_nodes[i].state      = STATE_FREE;
        mp_nodes[i].is_running = false;
    }
    
    // Skip timer node array
    p_buffer = &((uint8_t *)p_buffer)[max_timers * sizeof(timer_node_t)];
    
    // Initialize users array
    m_user_array_size = APP_TIMER_INT_LEVELS;
    mp_users          = p_buffer;
    
    // Skip user array
    p_buffer = &((uint8_t *)p_buffer)[APP_TIMER_INT_LEVELS * sizeof(timer_user_t)];

    // Initialize operation queues
    for (i = 0; i < APP_TIMER_INT_LEVELS; i++)
    {
        timer_user_t * p_user = &mp_users[i];
        
        p_user->first              = 0;
        p_user->last               = 0;
        p_user->user_op_queue_size = op_queues_size;
        p_user->p_user_op_queue    = p_buffer;
    
        // Skip operation queue
        p_buffer = &((uint8_t *)p_buffer)[op_queues_size * sizeof(timer_user_op_t)];
    }

    m_timer_id_head             = TIMER_NULL;
    m_ticks_elapsed_q_read_ind  = 0;
    m_ticks_elapsed_q_write_ind = 0;

    NVIC_ClearPendingIRQ(SWI0_IRQn);
    NVIC_SetPriority(SWI0_IRQn, SWI0_IRQ_PRI);
    NVIC_EnableIRQ(SWI0_IRQn);

    rtc1_init(prescaler);

    m_ticks_latest = rtc1_counter_get();
    
    return NRF_SUCCESS;
}
Example #26
0
/**
 * \brief Application entry point for PWM with PDC example.
 *
 * Outputs a PWM on LED1 & LED2 & LED3 to makes it fade in repeatedly.
 * Channel #0, #1, #2 are linked together as synchronous channels, so they have
 * the same source clock, the same period, the same alignment and
 * are started together. The update of the duty cycle values is made
 * automatically by the Peripheral DMA Controller (PDC).
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
    uint32_t i;
    uint8_t key;
    int32_t numkey;

    /* Disable watchdog */
    WDT_Disable( WDT ) ;

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

    /* PIO configuration */
    PIO_Configure(pins, PIO_LISTSIZE(pins));

    /* Enable PWMC peripheral clock */
    PMC_EnablePeripheral(ID_PWM);

    /* Set clock A to run at PWM_FREQUENCY * MAX_DUTY_CYCLE (clock B is not used) */
    PWMC_ConfigureClocks(PWM_FREQUENCY * MAX_DUTY_CYCLE, 0, BOARD_MCK);

    /* Configure PWMC channel for LED0 (left-aligned, enable dead time generator) */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED0,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              PWM_CMR_DTE,       /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED0, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED0, MIN_DUTY_CYCLE);
    PWMC_SetDeadTime(PWM, CHANNEL_PWM_LED0, 5, 5);

    /* Configure PWMC channel for LED1 */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED1,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              0,                 /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED1, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED1, MIN_DUTY_CYCLE);

    /* Configure PWMC channel for LED2 */
    PWMC_ConfigureChannelExt( PWM,
                              CHANNEL_PWM_LED2,  /* channel */
                              PWM_CMR_CPRE_CKA,  /* prescaler */
                              0,                 /* alignment */
                              0,                 /* polarity */
                              0,                 /* countEventSelect */
                              0,                 /* DTEnable */
                              0,                 /* DTHInverte */
                              0 );               /* DTLInverte */

    PWMC_SetPeriod(PWM, CHANNEL_PWM_LED2, MAX_DUTY_CYCLE);
    PWMC_SetDutyCycle(PWM, CHANNEL_PWM_LED2, MIN_DUTY_CYCLE);

    /* Set synchronous channels, update mode = 2 */
    PWMC_ConfigureSyncChannel(PWM,
                              (1 << CHANNEL_PWM_LED0) |
                              (1 << CHANNEL_PWM_LED1) |
                              (1 << CHANNEL_PWM_LED2),
                              PWM_SCM_UPDM_MODE2, //  (PWMC) Automatic write of data and automatic trigger of the update
                              0,
                              0);

    /* Set Synchronous channel update period value */
    PWMC_SetSyncChannelUpdatePeriod(PWM, PWM_SCUP_UPR(0xF));

    /* Configure interrupt for PDC transfer */
    NVIC_DisableIRQ(PWM_IRQn);
    NVIC_ClearPendingIRQ(PWM_IRQn);
    NVIC_SetPriority(PWM_IRQn, 0);
    NVIC_EnableIRQ(PWM_IRQn);
    PWMC_EnableIt(PWM, 0, PWM_IER2_ENDTX);

    /* Set override value to 1 on PWMH0, others is 0. */
    PWMC_SetOverrideValue(PWM, PWM_OOV_OOVH0);

    /* Fill duty cycle buffer for channel #0, #1 and #2 */
    /* For Channel #0, #1, #2 duty cycle are from MIN_DUTY_CYCLE to MAX_DUTY_CYCLE */
    for (i = 0; i < DUTY_BUFFER_LENGTH/3; i++) {
        dutyBuffer[i*3]   = (i + MIN_DUTY_CYCLE);
        dutyBuffer[i*3+1] = (i + MIN_DUTY_CYCLE);
        dutyBuffer[i*3+2] = (i + MIN_DUTY_CYCLE);
    }

    /* Define the PDC transfer */
    PWMC_WriteBuffer(PWM, dutyBuffer, DUTY_BUFFER_LENGTH);

    /* Enable syncronous channels by enable channel #0 */
    PWMC_EnableChannel(PWM, CHANNEL_PWM_LED0);

    while (1) {
        _DisplayMenu();
        key = UART_GetChar();

        switch (key) {
            case 'u':
                printf("Input update period between %d to %d.\n\r", 0, PWM_SCUP_UPR_Msk);
                numkey = _GetNumkey2Digit();
                if(numkey <= PWM_SCUP_UPR_Msk) {

                    /* Set synchronous channel update period value */
                    PWMC_SetSyncChannelUpdatePeriod(PWM, numkey);
                    printf("Done\n\r");
                } else {

                    printf("Invalid input\n\r");
                }
                break;
            case 'd':
                printf("Input dead time for channel #0 between %d to %d.\n\r",
                    MIN_DUTY_CYCLE, MAX_DUTY_CYCLE);
                numkey = _GetNumkey2Digit();
                if(numkey >= MIN_DUTY_CYCLE && numkey <= MAX_DUTY_CYCLE) {

                    /* Set synchronous channel update period value */
                    PWMC_SetDeadTime(PWM, CHANNEL_PWM_LED0, numkey, numkey);
                    /* Update synchronous channel */
                    PWMC_SetSyncChannelUpdateUnlock(PWM);
                    printf("Done\n\r");
                } else {

                    printf("Invalid input\n\r");
                }
                break;
            case 'o':
                printf("0: Disable override output on channel #0\n\r");
                printf("1: Enable override output on channel #0\n\r");
                key = UART_GetChar();

                if (key == '1') {

                    PWMC_EnableOverrideOutput(PWM, PWM_OSSUPD_OSSUPH0 | PWM_OSSUPD_OSSUPL0, 1);
                    printf("Done\n\r");
                } else if (key == '0') {

                    PWMC_DisableOverrideOutput(PWM, PWM_OSSUPD_OSSUPH0 | PWM_OSSUPD_OSSUPL0, 1);
                    printf("Done\n\r");
                }
                break;
            default:
                printf("Invalid input\n\r");
                break;
        }
    }
}
Example #27
0
/**
 * \brief Application entry point for RTC example.
 *
 * \return Unused (ANSI-C compatibility).
 */
int main(void)
{
	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);

	/* Configure RTC interrupts */
	NVIC_DisableIRQ(RTC_IRQn);
	NVIC_ClearPendingIRQ(RTC_IRQn);
	NVIC_SetPriority(RTC_IRQn, 0);
	NVIC_EnableIRQ(RTC_IRQn);
	rtc_enable_interrupt(RTC, RTC_IER_SECEN | RTC_IER_ALREN);

	/* Refresh display once */
	refresh_display();

	/* Handle keypresses */
	while (1) {

		while (uart_read(CONSOLE_UART, &uc_key));

		/* Set time */
		if (uc_key == 't') {
			gs_ul_state = STATE_SET_TIME;

			do {
				puts("\n\r\n\r Set time(hh:mm:ss): ");
			} while (get_new_time());

			/* If valid input, none of the variables for time is 0xff. */
			if (gs_ul_new_hour != 0xFFFFFFFF && (gs_uc_rtc_time[2] == ':')
					&& (gs_uc_rtc_time[5] == ':')) {
				if (rtc_set_time(RTC, gs_ul_new_hour, gs_ul_new_minute,
						gs_ul_new_second)) {
					puts("\n\r Time not set, invalid input!\r");
				}
			} else {
				gs_uc_rtc_time[2] = ':';
				gs_uc_rtc_time[5] = ':';
				puts("\n\r Time not set, invalid input!\r");
			}

			gs_ul_state = STATE_MENU;
			gs_ul_menu_shown = 0;
			refresh_display();
		}

		/* Set date */
		if (uc_key == 'd') {
			gs_ul_state = STATE_SET_DATE;

			do {
				puts("\n\r\n\r Set date(mm/dd/yyyy): ");
			} while (get_new_date());

			/* If valid input, none of the variables for date is 0xff(ff). */
			if (gs_ul_new_year != 0xFFFFFFFF && (gs_uc_date[2] == '/')
					&& (gs_uc_date[5] == '/')) {
				if (rtc_set_date(RTC, gs_ul_new_year, gs_ul_new_month,
						gs_ul_new_day, gs_ul_new_week)) {
					puts("\n\r Date not set, invalid input!\r");
				}
			} else {
				gs_uc_date[2] = '/';
				gs_uc_date[5] = '/';
				puts("\n\r Time not set, invalid input!\r");
			}

			/* Only 'mm/dd' is input. */
			if (gs_ul_new_month != 0xFFFFFFFF &&
						gs_ul_new_year == 0xFFFFFFFF) {
				puts("\n\r Not Set for no year field!\r");
			}

			gs_ul_state = STATE_MENU;
			gs_ul_menu_shown = 0;
			refresh_display();
		}

		/* Set time alarm */
		if (uc_key == 'i') {
			gs_ul_state = STATE_SET_TIME_ALARM;

			rtc_clear_date_alarm(RTC);

			do {
				puts("\n\r\n\r Set time alarm(hh:mm:ss): ");
			} while (get_new_time());

			if (gs_ul_new_hour != 0xFFFFFFFF && (gs_uc_rtc_time[2] == ':')
					&& (gs_uc_rtc_time[5] == ':')) {
				if (rtc_set_time_alarm(RTC, 1, gs_ul_new_hour,
						1, gs_ul_new_minute, 1, gs_ul_new_second)) {
					puts("\n\r Time alarm not set, invalid input!\r");
				} else {
					printf("\n\r Time alarm is set at %02u:%02u:%02u!",
						(unsigned int)gs_ul_new_hour, (unsigned int)gs_ul_new_minute,
						(unsigned int)gs_ul_new_second);
				}
			} else {
				gs_uc_rtc_time[2] = ':';
				gs_uc_rtc_time[5] = ':';
				puts("\n\r Time not set, invalid input!\r");
			}
			gs_ul_state = STATE_MENU;
			gs_ul_menu_shown = 0;
			gs_ul_alarm_triggered = 0;
			refresh_display();
		}

		/* Set date alarm */
		if (uc_key == 'm') {
			gs_ul_state = STATE_SET_DATE_ALARM;

			rtc_clear_time_alarm(RTC);

			do {
				puts("\n\r\n\r Set date alarm(mm/dd/yyyy): ");
			} while (get_new_date());

			if (gs_ul_new_year != 0xFFFFFFFF && (gs_uc_date[2] == '/')
					&& (gs_uc_date[5] == '/')) {
				if (rtc_set_date_alarm(RTC, 1, gs_ul_new_month, 1,
						gs_ul_new_day)) {
					puts("\n\r Date alarm not set, invalid input!\r");
				} else {
					printf("\n\r Date alarm is set on %02u/%02u/%4u!",
							(unsigned int)gs_ul_new_month, (unsigned int)gs_ul_new_day,
							(unsigned int)gs_ul_new_year);
				}
			} else {
				gs_uc_date[2] = '/';
				gs_uc_date[5] = '/';
				puts("\n\r Date alarm not set, invalid input!\r");
			}
			gs_ul_state = STATE_MENU;
			gs_ul_menu_shown = 0;
			gs_ul_alarm_triggered = 0;
			refresh_display();
		}

#if ((SAM3S8) || (SAM3SD8) || (SAM4S) || (SAM4C) || (SAM4CP) || (SAM4CM))
		/* Generate Waveform */
		if (uc_key == 'w') {
			gs_ul_state = STATE_WAVEFORM;
			puts("\n\rMenu:\n\r"
					"  0 - No Waveform\n\r"
					"  1 - 1 Hz square wave\n\r"
					"  2 - 32 Hz square wave\n\r"
					"  3 - 64 Hz square wave\n\r"
					"  4 - 512 Hz square wave\n\r"
					"  5 - Toggles when alarm flag rise\n\r"
					"  6 - Copy of the alarm flag\n\r"
					"  7 - Duty cycle programmable pulse\n\r"
					"  8 - Quit\r");

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

				if ((uc_key >= '0') && (uc_key <= '7')) {
					rtc_set_waveform(RTC, 0, char_to_digit(uc_key));
				}

				if (uc_key == '8') {
					gs_ul_state = STATE_MENU;
					gs_ul_menu_shown = 0;
					refresh_display();
					break;
				}
			}
		}
#endif
		/* Clear trigger flag */
		if (uc_key == 'c') {
			gs_ul_alarm_triggered = 0;
			gs_ul_menu_shown = 0;
			refresh_display();
		}

	}

}
Example #28
0
/*!
 * \brief UART 1 interrupt control.
 *
 * \param cmd   Control command.
 *              - NUT_IRQCTL_INIT Initialize and disable interrupt.
 *              - NUT_IRQCTL_STATUS Query interrupt status.
 *              - NUT_IRQCTL_ENABLE Enable interrupt.
 *              - NUT_IRQCTL_DISABLE Disable interrupt.
 *              - NUT_IRQCTL_GETMODE Query interrupt mode.
 *              - NUT_IRQCTL_SETMODE Set interrupt mode (NUT_IRQMODE_LEVEL or NUT_IRQMODE_EDGE).
 *              - NUT_IRQCTL_GETPRIO Query interrupt priority.
 *              - NUT_IRQCTL_SETPRIO Set interrupt priority.
 *              - NUT_IRQCTL_GETCOUNT Query and clear interrupt counter.
 * \param param Pointer to optional parameter.
 *
 * \return 0 on success, -1 otherwise.
 */
static int Uart6IrqCtl(int cmd, void *param)
{
    int rc = 0;
    uint32_t *ival = (uint32_t *)param;
    int enabled = NVIC_GetEnableIRQ(USART6_IRQn);

    /* Disable interrupt. */
    if (enabled) {
        NVIC_DisableIRQ(USART6_IRQn);
    }

    switch(cmd) {
    case NUT_IRQCTL_INIT:
        /* Set the vector. */
        Cortex_RegisterInt(USART6_IRQn, Uart6IrqEntry);
        /* Initialize with defined priority. */
        NVIC_SetPriority(USART6_IRQn, NUT_IRQPRI_UART6);
        /* Clear interrupt */
        NVIC_ClearPendingIRQ(USART6_IRQn);
        break;
    case NUT_IRQCTL_STATUS:
        if (enabled) {
            *ival |= 1;
        }
        else {
            *ival &= ~1;
        }
        break;
    case NUT_IRQCTL_ENABLE:
        enabled = 1;
        break;
    case NUT_IRQCTL_DISABLE:
        enabled = 0;
        break;
    case NUT_IRQCTL_GETMODE:
            *ival = NUT_IRQMODE_EDGE;
        break;
    case NUT_IRQCTL_SETMODE:
            rc = -1;
        break;
    case NUT_IRQCTL_GETPRIO:
        *ival = NVIC_GetPriority(USART6_IRQn);
        break;
    case NUT_IRQCTL_SETPRIO:
        NVIC_SetPriority(USART6_IRQn,*ival);
        break;
#ifdef NUT_PERFMON
    case NUT_IRQCTL_GETCOUNT:
        *ival = (uint32_t)sig_USART6.ir_count;
        sig_USART6.ir_count = 0;
        break;
#endif
    default:
        rc = -1;
        break;
    }

    /* Enable interrupt. */
    if (enabled) {
        NVIC_EnableIRQ(USART6_IRQn);
    }
    return rc;
}
Example #29
0
void lp_ticker_clear_interrupt(void)
{
    NVIC_ClearPendingIRQ(TICKER_COUNTER_IRQn2);
}
Example #30
0
void tone (uint32_t outputPin, uint32_t frequency, uint32_t duration)
{
  // Configure interrupt request
  NVIC_DisableIRQ(TONE_TC_IRQn);
  NVIC_ClearPendingIRQ(TONE_TC_IRQn);
  
  if(!firstTimeRunning)
  {
    firstTimeRunning = true;
    
    NVIC_SetPriority(TONE_TC_IRQn, 0);
    
    // Enable GCLK for timer used
#if defined(__SAMD11D14AM__) || defined(__SAMD11C14A__) || defined(__SAMD11D14AS__)
    GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TC1_TC2));
#else
    GCLK->CLKCTRL.reg = (uint16_t) (GCLK_CLKCTRL_CLKEN | GCLK_CLKCTRL_GEN_GCLK0 | GCLK_CLKCTRL_ID(GCM_TC4_TC5));
#endif
    while (GCLK->STATUS.bit.SYNCBUSY);
  }
  
  if (toneIsActive && (outputPin != lastOutputPin))
    noTone(lastOutputPin);

  //
  // Calculate best prescaler divider and comparator value for a 16 bit TC peripheral
  //

  uint32_t prescalerConfigBits;
  uint32_t ccValue;

  ccValue = toneMaxFrequency / frequency - 1;
  prescalerConfigBits = TC_CTRLA_PRESCALER_DIV1;
  
  uint8_t i = 0;
  
  while(ccValue > TONE_TC_TOP)
  {
    ccValue = toneMaxFrequency / frequency / (2<<i) - 1;
    i++;
    if(i == 4 || i == 6 || i == 8) //DIV32 DIV128 and DIV512 are not available
     i++;
  }
  
  switch(i-1)
  {
    case 0: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV2; break;
    
    case 1: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV4; break;
    
    case 2: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV8; break;
    
    case 3: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV16; break;
    
    case 5: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV64; break;
      
    case 7: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV256; break;
    
    case 9: prescalerConfigBits = TC_CTRLA_PRESCALER_DIV1024; break;
    
    default: break;
  }

  toggleCount = (duration > 0 ? frequency * duration * 2 / 1000UL : -1);

  resetTC(TONE_TC);

  uint16_t tmpReg = 0;
  tmpReg |= TC_CTRLA_MODE_COUNT16;  // Set Timer counter Mode to 16 bits
  tmpReg |= TC_CTRLA_WAVEGEN_MFRQ;  // Set TONE_TC mode as match frequency
  tmpReg |= prescalerConfigBits;
  TONE_TC->COUNT16.CTRLA.reg |= tmpReg;
  WAIT_TC16_REGS_SYNC(TONE_TC)

  TONE_TC->COUNT16.CC[TONE_TC_CHANNEL].reg = (uint16_t) ccValue;
  WAIT_TC16_REGS_SYNC(TONE_TC)

  portToggleRegister = &(PORT->Group[g_APinDescription[outputPin].ulPort].OUTTGL.reg);
  portClearRegister = &(PORT->Group[g_APinDescription[outputPin].ulPort].OUTCLR.reg);
  portBitMask = (1ul << g_APinDescription[outputPin].ulPin);

  // Enable the TONE_TC interrupt request
  TONE_TC->COUNT16.INTENSET.bit.MC0 = 1;
  
  if (outputPin != lastOutputPin)
  {
    lastOutputPin = outputPin;
    digitalWrite(outputPin, LOW);
    pinMode(outputPin, OUTPUT);
    toneIsActive = true;
  }

  // Enable TONE_TC
  TONE_TC->COUNT16.CTRLA.reg |= TC_CTRLA_ENABLE;
  WAIT_TC16_REGS_SYNC(TONE_TC)
  
  NVIC_EnableIRQ(TONE_TC_IRQn);
}