/** * @brief Enters Sleep mode. * * @note In Sleep mode, all I/O pins keep the same state as in Run mode. * * @note In Sleep mode, the systick is stopped to avoid exit from this mode with * systick interrupt when used as time base for Timeout * * @param Regulator: Specifies the regulator state in SLEEP mode. * This parameter can be one of the following values: * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON * @note This parameter is not used for the STM32F4 family and is kept as parameter * just to maintain compatibility with the lower power families. * @param SLEEPEntry: Specifies if SLEEP mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction * @retval None */ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) { /* Check the parameters */ assert_param(IS_PWR_REGULATOR(Regulator)); assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); /* Disable SysTick Timer */ SysTick->CTRL &= 0xFE; /* Select SLEEP mode entry -------------------------------------------------*/ if(SLEEPEntry == PWR_SLEEPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __WFE(); } /* Enable SysTick Timer */ SysTick->CTRL |= 0x01; }
/** * @brief Enters Sleep mode. * * @note In Sleep mode, all I/O pins keep the same state as in Run mode. * * @note In Sleep mode, the systick is stopped to avoid exit from this mode with * systick interrupt when used as time base for Timeout * * @param Regulator: Specifies the regulator state in SLEEP mode. * This parameter can be one of the following values: * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON * @note This parameter is not used for the STM32F4 family and is kept as parameter * just to maintain compatibility with the lower power families. * @param SLEEPEntry: Specifies if SLEEP mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction * @retval None */ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) { (void)Regulator; /* Check the parameters */ assert_param(IS_PWR_REGULATOR(Regulator)); assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); /* Clear SLEEPDEEP bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, ((uint32_t)SCB_SCR_SLEEPDEEP_Msk)); /* Select SLEEP mode entry -------------------------------------------------*/ if(SLEEPEntry == PWR_SLEEPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } }
/**@brief Function for application main entry. Does not return. */ int main(void) { utils_setup(); softdevice_setup(); ant_channel_rx_broadcast_setup(); // Main loop. for (;;) { #ifdef CPU_LOAD_TRACE // Disabling interrupts in this way is highly not recommended. It has an impact on the work // of the SoftDevice and is used only to show CPU load. __disable_irq(); LEDS_OFF(BSP_LED_0_MASK); __WFI(); LEDS_ON(BSP_LED_0_MASK); __enable_irq(); #else // Put CPU in sleep if possible. uint32_t err_code = sd_app_evt_wait(); APP_ERROR_CHECK(err_code); #endif // CPU_LOAD_TRACE } }
int main(void) { uint32_t nextBlink; uint32_t blinkState = 0; init(); nextBlink = tickMs + BLINK_DELAY_MS; for(;;) { if(tickMs > nextBlink) { nextBlink = tickMs + BLINK_DELAY_MS; if(blinkState) { GPIO_SetBits(GPIOA, GPIO_Pin_15); } else { GPIO_ResetBits(GPIOA, GPIO_Pin_15); } blinkState ^= 1; } __WFI(); } return 0; }
/** * @brief Funcion principal. * Se encarga de las inicializaciones y queda esperando a la interrupcion. * @return 0 */ int main(void) { //Cuando incializa tenemos que tomar el valor incial de Reload_Ticks /* Generic Initialization */ SystemCoreClockUpdate(); /* Board_Init calls Chip_GPIO_Init and enables GPIO clock if needed, Chip_GPIO_Init is not called again */ Board_Init(); Board_LED_Set(0, false); GPIO_Config(); Setup_SysTick(); Incializacion_Reload_Ticks(); /* Wait for interrupts - LED will toggle on each wakeup event */ while (1) { __WFI(); } return 0; }
/*********************************************************************************************************//** * @brief Enters DEEP-SLEEP Mode 2. * @param SleepEntry : Enters sleep mode instruction that is used to WFI or WFE. * This parameter can be one of the following values: * @arg PWRCU_SLEEP_ENTRY_WFE: Enters SLEEP mode via WFE instruction. * @arg PWRCU_SLEEP_ENTRY_WFI: Enters SLEEP mode via WFI instruction. * @retval None ************************************************************************************************************/ void PWRCU_DeepSleep2(PWRCU_SLEEP_ENTRY_Enum SleepEntry) { u32 uRTCStatus = 0; u32 uADCStatus = 0; Assert_Param(IS_PWRCU_SLEEP_ENTRY(SleepEntry)); uRTCStatus = BB_RTCEN; uADCStatus = BB_ADCEN; BB_RTCEN = 1; BB_ADCEN = 0; if (BB_DMOSSTS == 0) { BB_DMOSON = 0x0; BB_DMOSON = 0x1; } BB_LDOOFF = 0x0; BB_RTCEN = uRTCStatus; /* Sets SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR |= SLEEPDEEP_SET; if (SleepEntry == PWRCU_SLEEP_ENTRY_WFE) { /* Wait for event */ __WFE(); } else { /* Wait for interrupt */ __WFI(); } BB_ADCEN = uADCStatus; }
/** * @brief Enters Sleep mode. * @note In Sleep mode, all I/O pins keep the same state as in Run mode. * @param Regulator: Specifies the regulator state in SLEEP mode. * This parameter can be one of the following values: * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON * @param SLEEPEntry: Specifies if SLEEP mode is entered with WFI or WFE instruction. * When WFI entry is used, tick interrupt have to be disabled if not desired as * the interrupt wake up source. * This parameter can be one of the following values: * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction * @retval None */ void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) { uint32_t tmpreg = 0U; /* Check the parameters */ assert_param(IS_PWR_REGULATOR(Regulator)); assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); /* Select the regulator state in Sleep mode ---------------------------------*/ tmpreg = PWR->CR; /* Clear PDDS and LPDS bits */ CLEAR_BIT(tmpreg, (PWR_CR_PDDS | PWR_CR_LPSDSR)); /* Set LPSDSR bit according to PWR_Regulator value */ SET_BIT(tmpreg, Regulator); /* Store the new value */ PWR->CR = tmpreg; /* Clear SLEEPDEEP bit of Cortex System Control Register */ CLEAR_BIT(SCB->SCR, SCB_SCR_SLEEPDEEP_Msk); /* Select SLEEP mode entry -------------------------------------------------*/ if(SLEEPEntry == PWR_SLEEPENTRY_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __SEV(); __WFE(); __WFE(); } }
/** * @brief Enters STOP mode. * @note In Stop mode, all I/O pins keep the same state as in Run mode. * @note When exiting Stop mode by issuing an interrupt or a wakeup event, * the HSI RC oscillator is selected as system clock. * @note When the voltage regulator operates in low power mode, an additional * startup delay is incurred when waking up from Stop mode. * By keeping the internal regulator ON during Stop mode, the consumption * is higher although the startup time is reduced. * @param PWR_Regulator: specifies the regulator state in STOP mode. * This parameter can be one of the following values: * @arg PWR_Regulator_ON: STOP mode with regulator ON * @arg PWR_Regulator_LowPower: STOP mode with regulator in low power mode * @param PWR_STOPEntry: specifies if STOP mode in entered with WFI or WFE instruction. * This parameter can be one of the following values: * @arg PWR_STOPEntry_WFI: enter STOP mode with WFI instruction * @arg PWR_STOPEntry_WFE: enter STOP mode with WFE instruction * @retval None */ void PWR_EnterSTOPMode(uint32_t PWR_Regulator, uint8_t PWR_STOPEntry) { uint32_t tmpreg = 0; /* Check the parameters */ assert_param(IS_PWR_REGULATOR(PWR_Regulator)); assert_param(IS_PWR_STOP_ENTRY(PWR_STOPEntry)); /* Select the regulator state in STOP mode ---------------------------------*/ tmpreg = PWR->CR; /* Clear PDDS and LPDSR bits */ tmpreg &= CR_DS_MASK; /* Set LPDSR bit according to PWR_Regulator value */ tmpreg |= PWR_Regulator; /* Store the new value */ PWR->CR = tmpreg; /* Set SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; /* Select STOP mode entry --------------------------------------------------*/ if(PWR_STOPEntry == PWR_STOPEntry_WFI) { /* Request Wait For Interrupt */ __WFI(); } else { /* Request Wait For Event */ __WFE(); } /* Reset SLEEPDEEP bit of Cortex System Control Register */ SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); }
void HAL_Delay(uint32_t Delay) { /* Delay for amount of milliseconds */ /* Check if we are called from ISR */ if (__get_IPSR() == 0) { /* Called from thread mode */ uint32_t tickstart = HAL_GetTick(); /* Count interrupts */ while ((HAL_GetTick() - tickstart) < Delay) { #ifdef DELAY_SLEEP /* Go sleep, wait systick interrupt */ __WFI(); #endif } } else { /* Called from interrupt mode */ while (Delay) { /* Check if timer reached zero after we last checked COUNTFLAG bit */ if (SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) { Delay--; } } } }
socket_error_t blocking_resolve(const socket_stack_t stack, const socket_address_family_t af, const char* server, struct socket_addr * addr) { struct socket s; const struct socket_api *api = socket_get_api(stack); (void) af; blocking_resolve_socket = &s; s.stack = stack; s.handler = blocking_resolve_cb; s.api = api; blocking_resolve_done = false; socket_error_t err = api->resolve(&s, server); if(!TEST_EQ(err, SOCKET_ERROR_NONE)) { return err; } while (!blocking_resolve_done) { __WFI(); } if(!TEST_EQ(blocking_resolve_err, SOCKET_ERROR_NONE)) { return blocking_resolve_err; } int rc = strcmp(server, (char *)blocking_resolve_domain); TEST_EQ(rc,0); memcpy(addr, (const void*)&blocking_resolve_addr, sizeof(struct socket_addr)); return SOCKET_ERROR_NONE; }
/* Handle interrupt from GPIO pin or GPIO pin mapped to PININT */ static void ProcessPowerState(CHIP_PMU_MCUPOWER_T crntPowerSetting) { volatile uint32_t tempTimeout; /* Output power status message, add separating space */ DEBUGSTR("\r\n"); /* Switch on current selected power setting */ switch (crntPowerSetting) { case PMU_MCU_SLEEP: default: DEBUGSTR("-----------------------------------------------------------------\r\n"); DEBUGSTR(" Entering SLEEP power setting\r\n"); DEBUGOUT(" (System will exit SLEEP in %d seconds)\r\n", POWER_CYCLE_SEC_DELAY); DEBUGSTR("-----------------------------------------------------------------\r\n\r\n"); /* Wait for all serial characters to be output */ DelayForSerialOutput(); /* Enter MCU Sleep mode */ LPC_PWRD_API->power_mode_configure(PMU_SLEEP, (PMU_PD_WDOSC | PMU_PD_BOD | PMU_PD_ACMP0 | PMU_PD_ACMP1 | PMU_PD_ACMP2 |PMU_PD_ACMP3 | PMU_PD_IREF | PMU_PD_TS)); __WFI(); break; case PMU_MCU_DEEP_SLEEP: DEBUGSTR("-----------------------------------------------------------------\r\n"); DEBUGSTR(" Entering DEEP SLEEP power setting\r\n"); DEBUGOUT(" (System will exit DEEP SLEEP in %d seconds)\r\n", POWER_CYCLE_SEC_DELAY); DEBUGSTR("-----------------------------------------------------------------\r\n\r\n"); /* Wait for all serial characters to be output */ DelayForSerialOutput(); /* We should call Chip_SYSCTL_SetWakeup() to setup any peripherals we want to power back up on wakeup. For this example, we'll power back up the IRC, FLASH, the system oscillator, and the PLL */ Chip_SYSCTL_SetWakeup(~(SYSCTL_SLPWAKE_IRCOUT_PD | SYSCTL_SLPWAKE_IRC_PD | SYSCTL_SLPWAKE_FLASH_PD | SYSCTL_SLPWAKE_SYSOSC_PD | SYSCTL_SLPWAKE_SYSPLL_PD)); Chip_SYSCTL_EnableERP1PeriphWakeup(SYSCTL_ERP1_WAKEUP_RTCALARMINT); /* Enter MCU Deep Sleep mode */ LPC_PWRD_API->power_mode_configure(PMU_DEEP_SLEEP, (PMU_PD_WDOSC | PMU_PD_BOD | PMU_PD_ACMP0 | PMU_PD_ACMP1 | PMU_PD_ACMP2 |PMU_PD_ACMP3 | PMU_PD_IREF | PMU_PD_TS)); __WFI(); break; case PMU_MCU_POWER_DOWN: DEBUGSTR("-----------------------------------------------------------------\r\n"); DEBUGSTR(" Entering POWER DOWN power setting\r\n"); DEBUGOUT(" (System will exit POWER DOWN in %d seconds)\r\n", POWER_CYCLE_SEC_DELAY); DEBUGSTR("-----------------------------------------------------------------\r\n\r\n"); /* Wait for all serial characters to be output */ DelayForSerialOutput(); /* We should call Chip_SYSCTL_SetWakeup() to setup any peripherals we want to power back up on wakeup. For this example, we'll power back up the IRC, FLASH, the system oscillator, and the PLL */ Chip_SYSCTL_SetWakeup(~(SYSCTL_SLPWAKE_IRCOUT_PD | SYSCTL_SLPWAKE_IRC_PD | SYSCTL_SLPWAKE_FLASH_PD | SYSCTL_SLPWAKE_SYSOSC_PD | SYSCTL_SLPWAKE_SYSPLL_PD)); Chip_SYSCTL_EnableERP1PeriphWakeup(SYSCTL_ERP1_WAKEUP_RTCALARMINT); /* Enter MCU Power down mode */ LPC_PWRD_API->power_mode_configure(PMU_POWERDOWN, (PMU_PD_WDOSC | PMU_PD_BOD | PMU_PD_ACMP0 | PMU_PD_ACMP1 | PMU_PD_ACMP2 |PMU_PD_ACMP3 | PMU_PD_IREF | PMU_PD_TS)); __WFI(); break; case PMU_MCU_DEEP_PWRDOWN: DEBUGSTR("-----------------------------------------------------------------\r\n"); DEBUGSTR(" Entering DEEP POWER DOWN power setting\r\n"); DEBUGOUT(" (System will exit DEEP POWER DOWN in %d seconds)\r\n", POWER_CYCLE_SEC_DELAY); DEBUGSTR("-----------------------------------------------------------------\r\n\r\n"); /* Wait for all serial characters to be output */ DelayForSerialOutput(); /* Enable wakeup from deep power down mode due to RTC Alarm Match */ Chip_RTC_EnableWakeup(LPC_RTC, RTC_CTRL_ALARMDPD_EN); /* Enter MCU Deep Power down mode */ LPC_PWRD_API->power_mode_configure(PMU_DEEP_POWERDOWN, (PMU_PD_WDOSC | PMU_PD_BOD | PMU_PD_ACMP0 | PMU_PD_ACMP1 | PMU_PD_ACMP2 |PMU_PD_ACMP3 | PMU_PD_IREF | PMU_PD_TS)); __WFI(); break; } }
/** * @brief main routine for blinky example * @return Function should not exit. */ int main(void) { int i; /* Generic Initialization */ SystemCoreClockUpdate(); Board_Init(); Board_LED_Set(0, false); /* Enable SysTick Timer */ SysTick_Config(SystemCoreClock / TICKRATE_HZ); /* Initialize the array data to be written to FLASH */ for (i = 0; i < WRITECOUNT; i++) { array_data[i] = 0x11223340 + i; } /* Read Part Identification Number*/ command[0] = IAP_REPID_CMD; /* Read ID command code */ iap_entry(command, result); /* Reinvoke ISP mode so that reprogamming of Flash possible */ __disable_irq(); command[0] = IAP_REPID_CMD; iap_entry(command, result); /* Prepare to write/erase the last sector */ command[0] = IAP_PREWRRITE_CMD; /* Prepare to write/erase command code */ command[1] = IAP_LAST_SECTOR; /* Start Sector Number */ command[2] = IAP_LAST_SECTOR; /* End Sector Number */ iap_entry(command, result); /* Erase the last sector */ command[0] = IAP_ERSSECTOR_CMD; /* Erase command code*/ command[1] = IAP_LAST_SECTOR; /* Start Sector Number */ command[2] = IAP_LAST_SECTOR; /* Start Sector Number */ iap_entry(command, result); /* Prepare to write/erase the last sector */ command[0] = IAP_PREWRRITE_CMD; /* Prepare to write/erase command code */ command[1] = IAP_LAST_SECTOR; /* Start Sector Number */ command[2] = IAP_LAST_SECTOR; /* Start Sector Number */ iap_entry(command, result); /* Write to the last sector */ command[0] = IAP_WRISECTOR_CMD; /* Write command code */ command[1] = (uint32_t) last_sector_flash; /* Destination Flash Address */ command[2] = (uint32_t) &array_data; /* Source RAM Address */ command[3] = IAP_NUM_BYTES_TO_WRITE; /* Number of Bytes to be written */ command[4] = SystemCoreClock / 1000; /* System clock frequency */ iap_entry(command, result); /* Re-enable interrupt mode */ __enable_irq(); while (1) { __WFI(); } return 0; }
/** * @brief Main routine for SPI example * @return Does not return */ int main(void) { uint16_t seed = 0; SystemCoreClockUpdate(); Board_Init(); /* SPI initialization */ Init_SPI_PinMux(); /* Initialize stopwatch driver so some event times can be measured */ StopWatch_Init(); /* Setup SPI controllers */ setupMaster(); setupSlave(); /* Enable SPI controller interrupts */ NVIC_EnableIRQ(LPC_SPIMASTERIRQNUM); NVIC_EnableIRQ(LPC_SPISLAVEIRQNUM); DEBUGSTR("SPI master/slave combined example\r\n"); /* If you enable loopback mode and connect the master and slave controller's clock and SSEL lines together, the master and slave will wrap data to each other */ // Chip_SPIM_EnableLoopBack(LPC_SPIMASTERPORT); /* Loop forever */ while (1) { /* Setup some data for transmit from master to slave and slave to master */ seed = bufferInit(seed); /* Set slave transfer, this is only the initial transfer, the callbacks can change this later */ spiSlaveXfer.pTXData16 = slaveTXBuffer16; spiSlaveXfer.txCount = sizeof(slaveTXBuffer16) / sizeof(uint16_t); /* Count is in transfer size */ spiSlaveXfer.pRXData16 = slaveRXBuffer16; spiSlaveXfer.rxCount = sizeof(slaveRXBuffer16) / sizeof(uint16_t); /* Count is in transfer size */ /* Set master transfer, this is only the initial transfer, the callbacks can change this later */ spiMasterXfer.pTXData16 = masterTXBuffer16; /* Use NULL to send 0x0 */ spiMasterXfer.txCount = sizeof(masterTXBuffer16) / sizeof(uint16_t);/* Count is in transfer size */ spiMasterXfer.pRXData16 = masterRXBuffer16; spiMasterXfer.rxCount = sizeof(masterRXBuffer16) / sizeof(uint16_t);/* Count is in transfer size */ /* Setup master transfer options - 16 data bits per transfer, EOT, EOF */ spiMasterXfer.options = SPI_TXCTL_FLEN(16) | /* This must be enabled as a minimum, use 16 data bits */ // SPI_TXCTL_EOT | /* Enable this to assert and deassert SSEL for each individual byte/word, current slave functions for this example do not support this */ // SPI_TXCTL_EOF | /* Insert a delay between bytes/words as defined by frame delay time */ // SPI_TXCTL_RXIGNORE | /* Enable this to ignore incoming data, or set spiMasterXfer.pRXData16 to NULL to ignore RX data */ 0; /* Transfer will terminate after current buffer is sent. If terminate is not set, the buffers must be setup by the callbacks */ spiMasterXfer.terminate = true; /* Use SPI select 0 */ spiMasterXfer.sselNum = 0; /* Time master and slave transfers */ masterTime = StopWatch_Start(); /* Limitation: The call below 'pre-buffers' the initial slave transmit datum. If this isn't pre-buffered, a slave transmit underflow will always occur at slave assertion time for the initial transmit datum. The datum sent to the master will be 0. This is ok as we are only using a single slave, but with multiple slaves pre-buffering is not always an option and the master might need to toss the first byte. */ Chip_SPI_FlushFifos(LPC_SPIMASTERPORT); Chip_SPI_FlushFifos(LPC_SPISLAVEPORT); Chip_SPIS_PreBuffSlave(LPC_SPISLAVEPORT, &spiSlaveXfer); /* Start master transfer */ Chip_SPIM_Xfer(LPC_SPIMASTERPORT, &spiMasterXfer); /* Sleep until transfers are complete */ mEnd = sEnd = false; while ((mEnd == false) || (sEnd == false)) { __WFI(); } /* Toggle LED */ Board_LED_Toggle(0); /* Display some information about the transfer */ Print_Val("\r\nTRANSFER COMPLETE: errors = 0x", errors); errors = 0; Print_Val("Master total transfer time in uS: 0x", StopWatch_TicksToUs(StopWatch_Elapsed(masterTime))); /* Show data */ showData("Master TX data", masterTXBuffer16); showData("Master RX data", masterRXBuffer16); showData("Slave TX data", slaveTXBuffer16); showData("Slave RX data", slaveRXBuffer16); } }
/** * @brief Main program. * @param None * @retval None */ int main(void) { /* Configure the system clocks */ RCC_Configuration(); /* Initialize Leds and Key Button mounted on STM3210X-EVAL board */ STM_EVAL_LEDInit(LED1); STM_EVAL_LEDInit(LED2); STM_EVAL_LEDInit(LED3); STM_EVAL_LEDInit(LED4); STM_EVAL_PBInit(Button_KEY, Mode_EXTI); /* Configures the DMA Channel */ DMA_Configuration(); /* EVAL_COM1 configuration ---------------------------------------------------*/ /* EVAL_COM1 configured as follow: - BaudRate = 115200 baud - Word Length = 8 Bits - One Stop Bit - No parity - Hardware flow control disabled (RTS and CTS signals) - Receive and transmit enabled */ USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; STM_EVAL_COMInit(COM1, &USART_InitStructure); USART_DMACmd(EVAL_COM1, USART_DMAReq_Rx, ENABLE); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); /* Enable the USARTy_DMA1_IRQn Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = USARTy_DMA1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the EXTI9_5 Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = EXTI9_5_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; NVIC_Init(&NVIC_InitStructure); while (1) { if(LowPowerMode == 1) { STM_EVAL_LEDOff(LED2); STM_EVAL_LEDOff(LED3); /* Request to enter WFI mode */ __WFI(); LowPowerMode = 0; } Delay(0xFFFFF); STM_EVAL_LEDToggle(LED1); } }
void setMcuToSleep(SLEEPMODE mode) { if(SLEEP_DEFAULT==mode) { // Sleep mode: // PCON.DPDEN bit 1 = 0 // SCR.SLEEDEEP bit 2 = 0 // WFI // Sleep mode exit: any IRQ enabled CLRBIT(LPC_PMU->PCON,1); //PCON.DPDEN bit 1 = 0 SETBIT(LPC_PMU->PCON,11); //Clear the Deep power-down flag CLRBIT(SCB->SCR,2); __WFI(); } else if(SLEEP_DEEP==mode) { // Deep-sleep mode: // PCON.DPDEN bit 1 = 0 // set MAINCLKSEL to IRC // set PDAWAKECFG for wakeup // external pins used: see start logic register and enable start logic IRQ // pin: PIO0_0 to PIO0_11, PIO1_0 to PIO1_11 and PIO2_0 to PIO2_7 // Enable register pin : STARTERP0 // // disable all peripherals SYSAHBCLKCTRL // SCR.SLEEPDEEP bit 2 = 1 // WFI // Deep-sleep mode exit: GPIO IRQ, RTC alarm, Watchdog timeout, USB // Use internal clock for the main clock LPC_SYSCON->MAINCLKSEL = 0; // Update main clock selection LPC_SYSCON->MAINCLKUEN = 1; LPC_SYSCON->MAINCLKUEN = 0; LPC_SYSCON->MAINCLKUEN = 1; // Wait main clock while ( !(LPC_SYSCON->MAINCLKUEN & BIT(0)) ); // Clear deep sleep flag // SETBIT(LPC_PMU->PCON,8); // Clear the deep power down flag SETBIT(LPC_PMU->PCON,11); CLRBIT(LPC_PMU->PCON,1); // Turn off Watchdog and brown out detector (decrease consumption) LPC_SYSCON->PDSLEEPCFG |= 0x00000FFF; // Select the peripheral to be powered when wakeup LPC_SYSCON->PDAWAKECFG = LPC_SYSCON->PDRUNCFG; // Initialize the wakeup source initWakeUp(); // Set Deep Sleep mode SETBIT(SCB->SCR,2); __WFI(); } else if(SLEEP_DEEP_POWERDOWN==mode) { // We can wakeup only on the Wakeup pin AD5 // bref j'ai pas vu de difference de consommation // entre le slee deep et le sleep deep powerdown // todo trouver le machin qui consomme ? SETBIT(LPC_PMU->PCON,1); //setIOInLowPowerMode(); // set IRCOUT_PD & IRC_PD bits to 0 (PDRUNCFG Register) // Set bits in PDRUNCFG to power down all perihphics except Flash and BOD powered LPC_SYSCON->PDRUNCFG=0xEDFC; LPC_SYSCON->SYSAHBCLKCTRL = 0; CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,5); CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,6); CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,7); CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,11); CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,13); CLRBIT(LPC_SYSCON->SYSAHBCLKCTRL,14); //Write 1 to SLEEPDEEP bit SCR Register SETBIT(SCB->SCR,2); __WFI(); } }
int socket_api_test_echo_server_stream(socket_stack_t stack, socket_address_family_t af, const char* local_addr, uint16_t port) { struct socket s; struct socket cs; struct socket_addr addr; socket_error_t err; const struct socket_api *api = socket_get_api(stack); server_socket = &s; client_socket = &cs; mbed::Timeout to; mbed::Ticker ticker; // Create the socket TEST_CLEAR(); if (!TEST_NEQ(api, NULL)) { // Test cannot continue without API. TEST_RETURN(); } err = api->init(); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } // Zero the socket implementation s.impl = NULL; // Create a socket err = api->create(&s, af, SOCKET_STREAM, &server_cb); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } err = api->str2addr(&s, &addr, local_addr); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } // start the TCP timer uint32_t interval_ms = api->periodic_interval(&s); TEST_NEQ(interval_ms, 0); uint32_t interval_us = interval_ms * 1000; socket_api_handler_t periodic_task = api->periodic_task(&s); if (TEST_NEQ(periodic_task, NULL)) { ticker.attach_us(periodic_task, interval_us); } err = api->bind(&s, &addr, port); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } void *data = malloc(SOCKET_SENDBUF_MAXSIZE); if(!TEST_NEQ(data, NULL)) { TEST_RETURN(); } // Tell the host test to try and connect TEST_PRINT(">>> EC,%s,%d\r\n", local_addr, port); bool quit = false; // For several iterations while (!quit) { timedout = false; server_event_done = false; incoming = false; to.attach(onTimeout, SOCKET_TEST_SERVER_TIMEOUT); // Listen for incoming connections err = api->start_listen(&s, 0); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_EXIT(); } // Reset the state of client_rx_done client_rx_done = false; // Wait for a connect event while (!timedout && !incoming) { __WFI(); } if (TEST_EQ(timedout,0)) { to.detach(); } else { TEST_EXIT(); } if(!TEST_EQ(server_event.event, SOCKET_EVENT_ACCEPT)) { TEST_PRINT("Event: %d\r\n",(int)client_event.event); continue; } // Stop listening server_event_done = false; // err = api->stop_listen(&s); // TEST_EQ(err, SOCKET_ERROR_NONE); // Accept an incoming connection cs.impl = server_event.i.a.newimpl; cs.family = s.family; cs.stack = s.stack; err = api->accept(&cs, client_cb); if(!TEST_EQ(err, SOCKET_ERROR_NONE)) { continue; } to.attach(onTimeout, SOCKET_TEST_SERVER_TIMEOUT); // Client should test for successive connections being rejected // Until Client disconnects while (client_event.event != SOCKET_EVENT_ERROR && client_event.event != SOCKET_EVENT_DISCONNECT) { // Wait for a read event while (!client_event_done && !client_rx_done && !timedout) { __WFI(); } if (!TEST_EQ(client_event_done, false)) { client_event_done = false; continue; } // Reset the state of client_rx_done client_rx_done = false; // Receive some data size_t len = SOCKET_SENDBUF_MAXSIZE; err = api->recv(&cs, data, &len); if (!TEST_NEQ(err, SOCKET_ERROR_WOULD_BLOCK)) { TEST_PRINT("Rx Would Block\r\n"); continue; } if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_PRINT("err: (%d) %s\r\n", err, socket_strerror(err)); break; } // Check if the server should halt if (strncmp((const char *)data, "quit", 4) == 0) { quit = true; break; } // Send some data err = api->send(&cs, data, len); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { break; } } to.detach(); TEST_NEQ(timedout, true); // Close client socket err = api->close(&cs); TEST_EQ(err, SOCKET_ERROR_NONE); } err = api->stop_listen(&s); TEST_EQ(err, SOCKET_ERROR_NONE); test_exit: ticker.detach(); TEST_PRINT(">>> KILL,EC\r\n"); free(data); // Destroy server socket TEST_RETURN(); }
int socket_api_test_connect_close(socket_stack_t stack, socket_address_family_t af, const char* server, uint16_t port) { struct socket s; int pfi; socket_error_t err; const struct socket_api * api = socket_get_api(stack); struct socket_addr addr; ConnectCloseSock = &s; TEST_CLEAR(); if (!TEST_NEQ(api, NULL)) { // Test cannot continue without API. TEST_RETURN(); } err = api->init(); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } // Create a socket for each protocol family for (pfi = SOCKET_PROTO_UNINIT+1; pfi < SOCKET_PROTO_MAX; pfi++) { socket_proto_family_t pf = static_cast<socket_proto_family_t>(pfi); // Zero the implementation s.impl = NULL; err = api->create(&s, af, pf, &connect_close_handler); // catch expected failing cases TEST_EQ(err, SOCKET_ERROR_NONE); if (!TEST_NEQ(s.impl, NULL)) { continue; } // Tell the host launch a server TEST_PRINT(">>> ES,%d\r\n", pf); // connect to a remote host err = api->str2addr(&s, &addr, server); TEST_EQ(err, SOCKET_ERROR_NONE); timedout = 0; connected = 0; mbed::Timeout to; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); err = api->connect(&s, &addr, port); TEST_EQ(err, SOCKET_ERROR_NONE); if (err!=SOCKET_ERROR_NONE) { printf("err = %d\r\n", err); } switch (pf) { case SOCKET_DGRAM: while ((!api->is_connected(&s)) && (!timedout)) { __WFI(); } break; case SOCKET_STREAM: while (!connected && !timedout) { __WFI(); } break; default: break; } to.detach(); TEST_EQ(timedout, 0); // close the connection timedout = 0; closed = 0; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); err = api->close(&s); TEST_EQ(err, SOCKET_ERROR_NONE); if (err!=SOCKET_ERROR_NONE) { printf("err = %d\r\n", err); } switch (pf) { case SOCKET_DGRAM: while ((api->is_connected(&s)) && (!timedout)) { __WFI(); } break; case SOCKET_STREAM: while (!closed && !timedout) { __WFI(); } break; default: break; } to.detach(); TEST_EQ(timedout, 0); // Tell the host to kill the server TEST_PRINT(">>> KILL ES\r\n"); // Destroy the socket err = api->destroy(&s); TEST_EQ(err, SOCKET_ERROR_NONE); } TEST_RETURN(); }
/** * @brief This function let system enter to Power-down mode. * @return None */ void CLK_PowerDown(void) { SCB->SCR = SCB_SCR_SLEEPDEEP_Msk; CLK->PWRCTL |= (CLK_PWRCTL_PD_EN_Msk | CLK_PWRCTL_WK_DLY_Msk ); __WFI(); }
/** * @brief This function let system enter to Idle mode * @return None */ void CLK_Idle(void) { CLK->PWRCTL |= (CLK_PWRCTL_PD_EN_Msk ); __WFI(); }
/** **************************************************************************************** * @brief Start a data reception. * @param[in] saddr slave device address (7bits, without R/W bit) * @description * This function is used to complete an I2C read transaction from start to stop. All the intermittent steps * are handled in the interrupt handler while the interrupt is enabled. * Before this function is called, the read length, write length, I2C master buffer, * and I2C state need to be filled. Please refer to I2C_BYTE_READ(). * As soon as the end of the data transfer is detected, the callback function is called. ***************************************************************************************** */ void i2c_read(uint8_t saddr) { uint32_t reg; uint32_t timeout = 0; if (i2c_bus_check() == I2C_BUS_BUSY) { return; } if (i2c_env.i2cTxCount) { i2c_env.i2cOpFsm = I2C_OP_SETADDR; // start write slave address with write bit reg = I2C_MASK_WR_EN | I2C_MASK_START | ((saddr << 1) & 0xFE); i2c_i2c_SetTXD(QN_I2C, reg); #ifdef SLP_TEST_EN // Wait For Interrupt __WFI(); // Enter sleep mode // Wakeup when I2C interrupt is triggered #endif do { timeout++; if (timeout > I2C_MAX_TIMEOUT) { break; } #if CONFIG_I2C_ENABLE_INTERRUPT==FALSE i2c_polling(); #endif } while ((i2c_env.i2cOpFsm != I2C_OP_RDDATA)&&(i2c_env.i2cOpFsm != I2C_OP_ABORT)); } else { // does not need write address, directly read data from device i2c_env.i2cOpFsm = I2C_OP_RDDATA; } // start write slave address with read bit reg = I2C_MASK_WR_EN | I2C_MASK_START | ((saddr << 1) | 0x01); i2c_i2c_SetTXD(QN_I2C, reg); timeout = 0; do { timeout++; if (timeout > I2C_MAX_TIMEOUT){ break; } #if CONFIG_I2C_ENABLE_INTERRUPT==FALSE i2c_polling(); #endif } while (i2c_env.i2cOpFsm != I2C_OP_FINISH); #if I2C_CALLBACK_EN==TRUE // Call end of reception callback if ((i2c_env.i2cOpFsm == I2C_OP_FINISH) && (i2c_env.callback != NULL)) { i2c_env.callback(); } #endif }
int socket_api_test_echo_client_connected(socket_stack_t stack, socket_address_family_t af, socket_proto_family_t pf, bool connect, const char* server, uint16_t port) { struct socket s; socket_error_t err; const struct socket_api *api = socket_get_api(stack); client_socket = &s; mbed::Timeout to; // Create the socket TEST_CLEAR(); TEST_PRINT("\r\n%s af: %d, pf: %d, connect: %d, server: %s:%d\r\n",__func__, (int) af, (int) pf, (int) connect, server, (int) port); if (!TEST_NEQ(api, NULL)) { // Test cannot continue without API. TEST_RETURN(); } err = api->init(); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } struct socket_addr addr; // Resolve the host address err = blocking_resolve(stack, af, server, &addr); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_RETURN(); } // Tell the host launch a server TEST_PRINT(">>> ES,%d\r\n", pf); // Allocate a data buffer for tx/rx void *data = malloc(SOCKET_SENDBUF_MAXSIZE); // Zero the socket implementation s.impl = NULL; // Create a socket err = api->create(&s, af, pf, &client_cb); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_EXIT(); } // Connect to a host if (connect) { client_event_done = false; timedout = 0; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); err = api->connect(&s, &addr, port); if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_EXIT(); } // Override event for dgrams. if (pf == SOCKET_DGRAM) { client_event.event = SOCKET_EVENT_CONNECT; client_event_done = true; } // Wait for onConnect while (!timedout && !client_event_done) { __WFI(); } // Make sure that the correct event occurred if (!TEST_EQ(client_event.event, SOCKET_EVENT_CONNECT)) { TEST_EXIT(); } to.detach(); } // For several iterations for (size_t i = 0; i < SOCKET_SENDBUF_ITERATIONS; i++) { // Fill some data into a buffer const size_t nWords = SOCKET_SENDBUF_BLOCKSIZE * (1 << i) / sizeof(uint16_t); for (size_t j = 0; j < nWords; j++) { *((uint16_t*) data + j) = j; } // Send the data client_tx_done = false; client_rx_done = false; timedout = 0; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); if(connect) { err = api->send(&s, data, nWords * sizeof(uint16_t)); } else { err = api->send_to(&s, data, nWords * sizeof(uint16_t), &addr, port); } if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { TEST_PRINT("Failed to send %u bytes\r\n", nWords * sizeof(uint16_t)); } else { size_t tx_bytes = 0; do { // Wait for the onSent callback while (!timedout && !client_tx_done) { __WFI(); } if (!TEST_EQ(timedout,0)) { break; } if (!TEST_NEQ(client_tx_info.sentbytes, 0)) { break; } tx_bytes += client_tx_info.sentbytes; if (tx_bytes < nWords * sizeof(uint16_t)) { client_tx_done = false; continue; } to.detach(); TEST_EQ(tx_bytes, nWords * sizeof(uint16_t)); break; } while (1); } timedout = 0; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); memset(data, 0, nWords * sizeof(uint16_t)); // Wait for the onReadable callback size_t rx_bytes = 0; do { while (!timedout && !client_rx_done) { __WFI(); } if (!TEST_EQ(timedout,0)) { break; } size_t len = SOCKET_SENDBUF_MAXSIZE - rx_bytes; // Receive data if (connect) { err = api->recv(&s, (void*) ((uintptr_t) data + rx_bytes), &len); } else { struct socket_addr rxaddr; uint16_t rxport = 0; // addr may contain unused data in the storage element. memcpy(&rxaddr, &addr, sizeof(rxaddr)); // Receive from... err = api->recv_from(&s, (void*) ((uintptr_t) data + rx_bytes), &len, &rxaddr, &rxport); int rc = memcmp(&rxaddr.ipv6be, &addr.ipv6be, sizeof(rxaddr.ipv6be)); if(!TEST_EQ(rc, 0)) { TEST_PRINT("Spurious receive packet\r\n"); } TEST_EQ(rxport, port); } if (!TEST_EQ(err, SOCKET_ERROR_NONE)) { break; } rx_bytes += len; if (rx_bytes < nWords * sizeof(uint16_t)) { client_rx_done = false; continue; } to.detach(); break; } while (1); if(!TEST_EQ(rx_bytes, nWords * sizeof(uint16_t))) { TEST_PRINT("Expected %u, got %u\r\n", nWords * sizeof(uint16_t), rx_bytes); } // Validate that the two buffers are the same bool match = true; size_t j; for (j = 0; match && j < nWords; j++) { match = (*((uint16_t*) data + j) == j); } if(!TEST_EQ(match, true)) { TEST_PRINT("Mismatch in %u byte packet at offset %u\r\n", nWords * sizeof(uint16_t), j * sizeof(uint16_t)); } } if (connect) { // close the socket client_event_done = false; timedout = 0; to.attach(onTimeout, SOCKET_TEST_TIMEOUT); err = api->close(&s); TEST_EQ(err, SOCKET_ERROR_NONE); // Override event for dgrams. if (pf == SOCKET_DGRAM) { client_event.event = SOCKET_EVENT_DISCONNECT; client_event_done = true; } // wait for onClose while (!timedout && !client_event_done) { __WFI(); } if (TEST_EQ(timedout,0)) { to.detach(); } // Make sure that the correct event occurred TEST_EQ(client_event.event, SOCKET_EVENT_DISCONNECT); } // destroy the socket err = api->destroy(&s); TEST_EQ(err, SOCKET_ERROR_NONE); test_exit: TEST_PRINT(">>> KILL,ES\r\n"); free(data); TEST_RETURN(); }
/*********************************************************************//** * @brief Enter Sleep mode with co-operated instruction by the Cortex-M3. * @param[in] None * @return None **********************************************************************/ void CLKPWR_Sleep(void) { LPC_SC->PCON = 0x00; /* Sleep Mode*/ __WFI(); }
void work_queue(void){ __WFI(); return; }
/** * \brief Switch off the voltage regulator to put the device in backup mode. * * \param p_supc Pointer to a SUPC instance. */ void supc_enable_backup_mode(Supc *p_supc) { p_supc->SUPC_CR = SUPC_CR_KEY_PASSWD | SUPC_CR_VROFF; __WFE(); __WFI(); }
int main(void) { uint8_t system_state=0, i2c_resets=0, si446x_resets=0;//used to track button press functionality and any errors uint8_t sensors=0; uint32_t repetition_counter=0; //Used to detect any I2C lockup uint8_t L3GD20_Data_Buffer_old[8]; //Used to test for noise in the gyro data (indicating that it is working) uint8_t UplinkFlags=0,CutFlags=0; uint16_t UplinkBytes=0; //Counters and flags for telemetry uint32_t last_telemetry=0,cutofftime=0,indtest=0,badgyro=0,permission_time=0,countdown_time=0,last_cuttest=0; uint16_t sentence_counter=0; uint8_t silab; //Cutdown config stuff here, atm uses hardcoded polygon defined in polygon.h static const int32_t Geofence[UK_GEOFENCE_POINTS*2]=UK_GEOFENCE; RTC_t RTC_time; _REENT_INIT_PTR(&my_reent); _impure_ptr = &my_reent; SystemInit(); //Sets up the clk setup_gpio(); //Initialised pins, and detects boot source DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); //Watchdog stopped during JTAG halt RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);/* Enable PWR and BKP clocks */ PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */ uint16_t shutdown_lock=BKP_ReadBackupRegister(BKP_DR3); //Holds the shutdown lock setting uint16_t reset_counter=BKP_ReadBackupRegister(BKP_DR2); //The number of consecutive failed reboot cycles PWR_BackupAccessCmd(DISABLE); if(RCC->CSR&RCC_CSR_IWDGRSTF && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Watchdog reset, turn off RCC->CSR|=RCC_CSR_RMVF; //Reset the reset flags shutdown(); } if(USB_SOURCE==bootsource) { RCC->CFGR &= ~(uint32_t)RCC_CFGR_PPRE1_DIV16; RCC->CFGR |= (uint32_t)RCC_CFGR_PPRE1_DIV4;//Swap the ABP1 bus to run at 12mhz rather than 4 if we booted from USB, makes USB fast enough } SysTick_Configuration(); //Start up system timer at 100Hz for uSD card functionality Watchdog_Config(WATCHDOG_TIMEOUT); //Set the watchdog Watchdog_Reset(); //Reset watchdog as soon as possible incase it is still running at power on rtc_init(); //Real time clock initialise - (keeps time unchanged if set) Usarts_Init(); ISR_Config(); rprintfInit(__usart_send_char); //Printf over the bluetooth if(USB_SOURCE==bootsource) { Set_System(); //This actually just inits the storage layer Set_USBClock(); USB_Interrupts_Config(); USB_Init(); uint32_t nojack=0x000FFFFF; //Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown while (bDeviceState != CONFIGURED) { //Wait for USB config - timeout causes shutdown if((Millis>10000 && bDeviceState == UNCONNECTED)|| !nojack) //No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb) shutdown(); if(GET_VBUS_STATE) //Jack detect resets the countdown nojack=0x0FFFFF; nojack--; Watchdog_Reset(); //Reset watchdog here, if we are stalled here the Millis timeout should catch us } PWR_BackupAccessCmd(ENABLE); /* Allow access to BKP Domain */ BKP_WriteBackupRegister(BKP_DR3,0x0000);//Wipe the shutdown lock setting PWR_BackupAccessCmd(DISABLE); while(1) { if(!(Millis%1000) && bDeviceState == SUSPENDED) { Delay(100); if(!GET_VBUS_STATE) shutdown(); } Watchdog_Reset(); __WFI(); //Sleep mode } } if(!GET_PWR_STATE && !(CoreDebug->DHCSR&0x00000001) && shutdown_lock!=SHUTDOWNLOCK_MAGIC) {//Check here to make sure the power button is still pressed, if not, sleep if no debug and not in always on flight mode shutdown(); //This means a glitch on the supply line, or a power glitch results in sleep } // check to see if battery has enough charge to start ADC_Configuration(); //We leave this a bit later to allow stabilisation { uint32_t t=Millis; while(Millis<(t+100)){__WFI();} //Sensor+inst amplifier takes about 100ms to stabilise after power on } if(Battery_Voltage<BATTERY_STARTUP_LIMIT) { //We will have to turn off if(reset_counter<10) shutdown(); } Watchdog_Reset(); //Card Init can take a second or two // system has passed battery level check and so file can be opened {//Context uint8_t silabs_header[5]={}; uint8_t* silabs_header_=NULL; //Pointer to the array (if all goes ok) if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error else { //FATFS initialised ok, try init the card, this also sets up the SPI1 if(!(f_err_code=f_open(&FATFS_logfile,(const TCHAR*)"time.txt",FA_OPEN_EXISTING|FA_READ|FA_WRITE))){//Try to open time file get system time if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info if(FATFS_info.fsize<5) { //Empty file RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0) RTC_time.month=(FATFS_info.fdate>>5)&0x000F; RTC_time.mday=FATFS_info.fdate&0x001F; RTC_time.hour=(FATFS_info.ftime>>11)&0x001F; RTC_time.min=(FATFS_info.ftime>>5)&0x003F; RTC_time.sec=(FATFS_info.ftime<<1)&0x003E; rtc_settime(&RTC_time); rprintfInit(__fat_print_char);//printf to the open file printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\ RTC_time.hour,RTC_time.min,RTC_time.sec); } } f_close(&FATFS_logfile); //Close the time.txt file } // load settings if file exists Watchdog_Reset(); //Card Init can take a second or two if(!f_open(&FATFS_logfile,(const TCHAR *)"settings.dat",FA_OPEN_EXISTING | FA_READ)) { UINT br; int8_t rtc_correction; f_read(&FATFS_logfile, (void*)(&rtc_correction),sizeof(rtc_correction),&br); //Use the setting to apply correction to the RTC if(br && (rtc_correction<30) && (rtc_correction>-92) && rtc_correction ) { PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */ uint16_t tweaked_prescale = (0x0001<<15)-2;/* Try to run the RTC slightly too fast so it can be corrected either way */ RTC_WaitForSynchro(); /* Wait for RTC registers synchronization */ if( RTC->PRLL != tweaked_prescale ) {/*Note that there is a 0.5ppm offset here (correction 0==0.5ppm slow)*/ RTC_SetPrescaler(tweaked_prescale); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767-2+1) */ RTC_WaitForLastTask(); } BKP_SetRTCCalibrationValue((uint8_t) ((int16_t)31-(21*(int16_t)rtc_correction)/(int16_t)20) ); BKP_RTCOutputConfig(BKP_RTCOutputSource_None);/* Ensure any output is disabled here */ /* Lock access to BKP Domain */ PWR_BackupAccessCmd(DISABLE); } else if(br && ((uint8_t)rtc_correction==0x91) ) {/* 0x91 magic flag sets the RTC clock output on */ PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */ BKP_RTCOutputConfig(BKP_RTCOutputSource_CalibClock);/* Output a 512Hz reference clock on the TAMPER pin*/ PWR_BackupAccessCmd(DISABLE); } if(br) { f_read(&FATFS_logfile, (void*)(&shutdown_lock),sizeof(shutdown_lock),&br);/*This needs to be set with the same magic flag value*/ if(br==2) { PWR_BackupAccessCmd(ENABLE);/* Allow access to BKP Domain */ BKP_WriteBackupRegister(BKP_DR3,shutdown_lock);//Wipe the shutdown lock setting PWR_BackupAccessCmd(DISABLE); } } if(br==2) { //Read was successful, next try to read 5 bytes of packet header f_read(&FATFS_logfile, (void*)(silabs_header),5,&br); if(br!=5) silabs_header_=silabs_header; } f_close(&FATFS_logfile); //Close the settings.dat file } #ifndef SINGLE_LOGFILE rtc_gettime(&RTC_time); //Get the RTC time and put a timestamp on the start of the file rprintfInit(__str_print_char); //Print to the string printf("%02d-%02d-%02dT%02d-%02d-%02d-%s.csv",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec,"Log");//Timestamp name rprintfInit(__usart_send_char); //Printf over the bluetooth #endif Watchdog_Reset(); //Card Init can take a second or two if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present Delay(10000); if((f_err_code=f_open(&FATFS_logfile,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Try again printf("FatFs drive error %d\r\n",f_err_code); if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY) Usart_Send_Str((char*)"No uSD card inserted?\r\n"); } } else { Watchdog_Reset(); //Card Init can take a second or two print_string[strlen(print_string)-4]=0x00;//Wipe the .csv off the string strcat(print_string,"_gyro.wav"); if((f_err_code=f_open(&FATFS_wavfile_gyro,(TCHAR*)LOGFILE_NAME,FA_CREATE_ALWAYS | FA_WRITE))) {//Present printf("FatFs drive error %d\r\n",f_err_code); if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY) Usart_Send_Str((char*)"No uSD card inserted?\r\n"); } else { //We have a mounted card f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); else rprintfInit(__str_print_char);//Printf to the logfile } if(f_err_code) f_close(&FATFS_logfile);//Close the already opened file on error else file_opened=1; //So we know to close the file properly on shutdown if(file_opened==1) { Watchdog_Reset(); //Card Init can take a second or two if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); else rprintfInit(__str_print_char);//Printf to the logfile } if(f_err_code) f_close(&FATFS_wavfile_gyro);//Close the already opened file on error else file_opened|=2; //So we know to close the file properly on shutdown } } } } f_err_code|=write_wave_header(&FATFS_wavfile_gyro, 4, 100, 16);//4 channels, last channel is for the current rpm Watchdog_Reset(); //Card Init can take a second or two //Setup and test the silabs radio silab=si446x_setup(silabs_header_); if(silab!=0x44) { //Should return the device code print_string[0]=0x00; printf("Silabs: %02x\n",silab); f_puts("Silabs detect error, got:",&FATFS_logfile); f_puts(print_string,&FATFS_logfile); shutdown_filesystem(ERR, file_opened);//So we log that something went wrong in the logfile shutdown(); } }//Context
int main(void) { uint32_t data_counter=0; //used as data timestamp uint8_t deadly_flashes=0,system_state=0,repetition_counter=0; int16_t sensor_data, sensor_raw_data[3]={}; //used for handling data passed back from sensors int16_t sfe_sensor_ref_buff[2][3],sfe_sensor_ref_buff_old[2][3];//used to detect and fix I2C bus lockup RTC_t RTC_time; wave_stuffer Gyro_wav_stuffer={0,0},Accel_wav_stuffer={0,0};//Used to controlling wav file bit packing SystemInit(); //Sets up the clk setup_gpio(); //Initialised pins, and detects boot source DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); //Watchdog stopped during JTAG halt if(RCC->CSR&RCC_CSR_IWDGRSTF) { //Watchdog reset, turn off RCC->CSR|=RCC_CSR_RMVF; //Reset the reset flags shutdown(); } SysTick_Configuration(); //Start up system timer at 100Hz for uSD card functionality Watchdog_Config(WATCHDOG_TIMEOUT); //Set the watchdog Watchdog_Reset(); //Reset watchdog as soon as possible incase it is still running at power on rtc_init(); //Real time clock initialise - (keeps time unchanged if set) Usarts_Init(); ISR_Config(); rprintfInit(__usart_send_char); //Printf over the bluetooth if(USB_SOURCE==bootsource) { Set_System(); //This actually just inits the storage layer Set_USBClock(); USB_Interrupts_Config(); USB_Init(); uint32_t nojack=0x000FFFFF; //Countdown timer - a few hundered ms of 0v on jack detect forces a shutdown while (bDeviceState != CONFIGURED) { //Wait for USB config - timeout causes shutdown if(Millis>10000 || !nojack) //No USB cable - shutdown (Charger pin will be set to open drain, cant be disabled without usb) shutdown(); if(GET_CHRG_STATE) //Jack detect resets the countdown nojack=0x0FFFFF; nojack--; Watchdog_Reset(); //Reset watchdog here, if we are stalled here the Millis timeout should catch us } USB_Configured_LED(); EXTI_ONOFF_EN(); //Enable the off interrupt - allow some time for debouncing while(1) { //If running off USB (mounted as mass storage), stay in this loop - dont turn on anything if(Millis%1000>500) //1Hz on/off flashing switch_leds_on(); //Flash the LED(s) else switch_leds_off(); Watchdog_Reset(); __WFI(); //Sleep until something arrives } } else { if(!GET_PWR_STATE) //Check here to make sure the power button is still pressed, if not, sleep shutdown(); //This means a glitch on the supply line, or a power glitch results in sleep EXTI_ONOFF_EN(); //Enable the off interrupt - allow some time for debouncing ADC_Configuration(); //At present this is purely here to detect low battery do { battery_voltage=Battery_Voltage;//Have to flush adc for some reason Delay(25000); } while(fabs(Battery_Voltage-battery_voltage)>0.01 || !battery_voltage); I2C_Config(); //Setup the I2C bus Sensors=detect_sensors(0); //Search for connected sensors if(battery_voltage<BATTERY_STARTUP_LIMIT) deadly_flashes=1; if(!(Sensors&(1<<FOREHEAD_ACCEL))) //Check for any missing sensors deadly_flashes=2; if(!(Sensors&(1<<(FOREHEAD_GYRO-1)))) deadly_flashes=3; if(!(Sensors&(1<<(SFE_1_ACCEL-1)))) deadly_flashes=4; if(!(Sensors&(1<<(SFE_1_MAGNO-1)))) deadly_flashes=5; if(!(Sensors&(1<<(SFE_1_GYRO-1)))) deadly_flashes=6; if(!(Sensors&(1<<(SFE_2_ACCEL-3)))) deadly_flashes=7; if(!(Sensors&(1<<(SFE_2_MAGNO-3)))) deadly_flashes=8; if(!(Sensors&(1<<(SFE_2_GYRO-3)))) deadly_flashes=9; if((f_err_code = f_mount(0, &FATFS_Obj)))Usart_Send_Str((char*)"FatFs mount error\r\n");//This should only error if internal error else if(!deadly_flashes){ //FATFS and the I2C initialised ok, try init the card, this also sets up the SPI1 if(!f_open(&FATFS_logfile,"time.txt",FA_OPEN_EXISTING | FA_READ | FA_WRITE)) {//Try and open a time file to get the system time if(!f_stat((const TCHAR *)"time.txt",&FATFS_info)) {//Get file info if(!FATFS_info.fsize) {//Empty file RTC_time.year=(FATFS_info.fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0) RTC_time.month=(FATFS_info.fdate>>5)&0x000F; RTC_time.mday=FATFS_info.fdate&0x001F; RTC_time.hour=(FATFS_info.ftime>>11)&0x001F; RTC_time.min=(FATFS_info.ftime>>5)&0x003F; RTC_time.sec=(FATFS_info.ftime<<1)&0x003E; rtc_settime(&RTC_time); rprintfInit(__fat_print_char);//printf to the open file printf("RTC set to %d/%d/%d %d:%d:%d\n",RTC_time.mday,RTC_time.month,RTC_time.year,\ RTC_time.hour,RTC_time.min,RTC_time.sec); } } f_close(&FATFS_logfile);//Close the time.txt file } rtc_gettime(&RTC_time); //Get the RTC time and put a timestamp on the start of the file rprintfInit(__str_print_char); //Print to the string //timestamp name printf("%d-%02d-%02dT%02d-%02d-%02d",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec); rprintfInit(__usart_send_char); //Printf over the bluetooth f_err_code = f_mkdir(print_string); //Try to make a directory where the logfiles will live if(f_err_code) { printf("FatFs drive error %d\r\n",f_err_code); if(f_err_code==FR_DISK_ERR || f_err_code==FR_NOT_READY) Usart_Send_Str((char*)"No uSD card inserted?\r\n"); repetition_counter=1; } else f_err_code=f_chdir(print_string);//enter our new directory if(f_err_code) { if(!repetition_counter) printf("FatFs drive error entering direcotry %d\r\n",f_err_code); repetition_counter=1; } else { strcat(print_string,".csv"); f_err_code=f_open(&FATFS_logfile,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the main 100sps csv logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating logfile %d\r\n",f_err_code); repetition_counter=1; } else { print_string[strlen(print_string)-4]=0x00; //Wipe the .csv off the string strcat(print_string,"_accel.wav"); f_err_code=f_open(&FATFS_wavfile_accel,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the accel wav logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating accel wav file %d\r\n",f_err_code); repetition_counter=1; } else { print_string[strlen(print_string)-9]=0x00; //Wipe the accel.wav off the string strcat(print_string,"gyro.wav"); f_err_code=f_open(&FATFS_wavfile_gyro,print_string,FA_CREATE_ALWAYS | FA_WRITE);//Try to open the gyro wav logfile } if(f_err_code) { if(!repetition_counter) printf("FatFs drive error creating gyro wav file %d\r\n",f_err_code); } else { //We have a mounted card print_string[0]=0x00; //Wipe the string f_err_code=f_lseek(&FATFS_logfile, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_logfile) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_logfile, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); else rprintfInit(__str_print_char);//Printf to the logfile } if(f_err_code) f_close(&FATFS_logfile);//Close the already opened file on error else file_opened=0x01;//So we know to close the file properly on shutdown - bit mask for the files if(!f_err_code) { f_err_code=f_lseek(&FATFS_wavfile_accel, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_wavfile_accel) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_wavfile_accel, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); } if(f_err_code) f_close(&FATFS_wavfile_accel);//Close the already opened file on error else file_opened|=0x02;//So we know to close the file properly on shutdown - bit mask for the files } if(!f_err_code) { f_err_code=f_lseek(&FATFS_wavfile_gyro, PRE_SIZE);// Pre-allocate clusters if (f_err_code || f_tell(&FATFS_wavfile_gyro) != PRE_SIZE)// Check if the file size has been increased correctly Usart_Send_Str((char*)"Pre-Allocation error\r\n"); else { if((f_err_code=f_lseek(&FATFS_wavfile_gyro, 0)))//Seek back to start of file to start writing Usart_Send_Str((char*)"Seek error\r\n"); } if(f_err_code) f_close(&FATFS_wavfile_gyro);//Close the already opened file on error else file_opened|=0x04;//So we know to close the file properly on shutdown - bit mask for the files } } } repetition_counter=0; //Reset this here //We die, but flash out a number of flashes first if(f_err_code || deadly_flashes) { //There was an init error for(;deadly_flashes;deadly_flashes--) { RED_LED_ON; Delay(200000); RED_LED_OFF; Delay(200000); Watchdog_Reset(); } RED_LED_ON; Delay(400000); shutdown(); //Abort after a (further )single red flash } }
/// \function select(rlist, wlist, xlist[, timeout]) STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { // get array data from tuple/list arguments mp_uint_t rwx_len[3]; mp_obj_t *r_array, *w_array, *x_array; mp_obj_get_array(args[0], &rwx_len[0], &r_array); mp_obj_get_array(args[1], &rwx_len[1], &w_array); mp_obj_get_array(args[2], &rwx_len[2], &x_array); // get timeout mp_uint_t timeout = -1; if (n_args == 4) { if (args[3] != mp_const_none) { #if MICROPY_PY_BUILTINS_FLOAT float timeout_f = mp_obj_get_float(args[3]); if (timeout_f >= 0) { timeout = (mp_uint_t)(timeout_f * 1000); } #else timeout = mp_obj_get_int(args[3]) * 1000; #endif } } // merge separate lists and get the ioctl function for each object mp_map_t poll_map; mp_map_init(&poll_map, rwx_len[0] + rwx_len[1] + rwx_len[2]); poll_map_add(&poll_map, r_array, rwx_len[0], MP_IOCTL_POLL_RD, true); poll_map_add(&poll_map, w_array, rwx_len[1], MP_IOCTL_POLL_WR, true); poll_map_add(&poll_map, x_array, rwx_len[2], MP_IOCTL_POLL_ERR | MP_IOCTL_POLL_HUP, true); mp_uint_t start_tick = HAL_GetTick(); rwx_len[0] = rwx_len[1] = rwx_len[2] = 0; for (;;) { // poll the objects mp_uint_t n_ready = poll_map_poll(&poll_map, rwx_len); if (n_ready > 0 || (timeout != -1 && HAL_GetTick() - start_tick >= timeout)) { // one or more objects are ready, or we had a timeout mp_obj_t list_array[3]; list_array[0] = mp_obj_new_list(rwx_len[0], NULL); list_array[1] = mp_obj_new_list(rwx_len[1], NULL); list_array[2] = mp_obj_new_list(rwx_len[2], NULL); rwx_len[0] = rwx_len[1] = rwx_len[2] = 0; for (mp_uint_t i = 0; i < poll_map.alloc; ++i) { if (!MP_MAP_SLOT_IS_FILLED(&poll_map, i)) { continue; } poll_obj_t *poll_obj = (poll_obj_t*)poll_map.table[i].value; if (poll_obj->flags_ret & MP_IOCTL_POLL_RD) { ((mp_obj_list_t*)list_array[0])->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_IOCTL_POLL_WR) { ((mp_obj_list_t*)list_array[1])->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_IOCTL_POLL_RD | MP_IOCTL_POLL_WR)) != 0) { ((mp_obj_list_t*)list_array[2])->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); return mp_obj_new_tuple(3, list_array); } __WFI(); } }
/* * The main processing loop. */ void loop() { __WFI(); // sleep until the next interrupt occurs }
/******************************************************************************* * Function Name : Suspend * Description : sets suspend mode operating conditions * Input : None. * Output : None. * Return : USB_SUCCESS. *******************************************************************************/ void Suspend(void) { uint32_t i =0; uint16_t wCNTR; uint32_t tmpreg = 0; __IO uint32_t savePWR_CR=0; /* suspend preparation */ /* ... */ /*Store CNTR value */ wCNTR = _GetCNTR(); /* This a sequence to apply a force RESET to handle a robustness case */ /*Store endpoints registers status */ for (i=0;i<8;i++) EP[i] = _GetENDPOINT(i); /* unmask RESET flag */ wCNTR|=CNTR_RESETM; _SetCNTR(wCNTR); /*apply FRES */ wCNTR|=CNTR_FRES; _SetCNTR(wCNTR); /*clear FRES*/ wCNTR&=~CNTR_FRES; _SetCNTR(wCNTR); /*poll for RESET flag in ISTR*/ while((_GetISTR()&ISTR_RESET) == 0); /* clear RESET flag in ISTR */ _SetISTR((uint16_t)CLR_RESET); /*restore Enpoints*/ for (i=0;i<8;i++) _SetENDPOINT(i, EP[i]); /* Now it is safe to enter macrocell in suspend mode */ wCNTR |= CNTR_FSUSP; _SetCNTR(wCNTR); /* force low-power mode in the macrocell */ wCNTR = _GetCNTR(); wCNTR |= CNTR_LPMODE; _SetCNTR(wCNTR); /*prepare entry in low power mode (STOP mode)*/ /* Select the regulator state in STOP mode*/ savePWR_CR = PWR->CR; tmpreg = PWR->CR; /* Clear PDDS and LPDS bits */ tmpreg &= ((uint32_t)0xFFFFFFFC); /* Set LPDS bit according to PWR_Regulator value */ tmpreg |= PWR_Regulator_LowPower; /* Store the new value */ PWR->CR = tmpreg; /* Set SLEEPDEEP bit of Cortex System Control Register */ #if defined (STM32F30X) || defined (STM32F37X) SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; #else SCB->SCR |= SCB_SCR_SLEEPDEEP; #endif /* enter system in STOP mode, only when wakeup flag in not set */ if((_GetISTR()&ISTR_WKUP)==0) { __WFI(); /* Reset SLEEPDEEP bit of Cortex System Control Register */ #if defined (STM32F30X) || defined (STM32F37X) SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); #else SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP); #endif } else { /* Clear Wakeup flag */ _SetISTR(CLR_WKUP); /* clear FSUSP to abort entry in suspend mode */ wCNTR = _GetCNTR(); wCNTR&=~CNTR_FSUSP; _SetCNTR(wCNTR); /*restore sleep mode configuration */ /* restore Power regulator config in sleep mode*/ PWR->CR = savePWR_CR; /* Reset SLEEPDEEP bit of Cortex System Control Register */ #if defined (STM32F30X) || defined (STM32F37X) SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); #else SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP); #endif } }
void mbed_enter_sleep(sleep_t *obj) { (void)obj; __WFI(); }