/** * @brief Initialize the watchdog timer for a specified timeout * * It is important to note that this function returns the achieved timeout * for this hardware. For hardware independence this should be checked when * scheduling updates. Other hardware dependent details may need to be * considered such as a window time which sets a minimum update time, * and this function should return a recommended delay for clearing. * * For the STM32 nominal clock rate is 32 khz, but for the maximum clock rate of * 60 khz and a prescaler of 4 yields a clock rate of 15 khz. The delay that is * set in the watchdog assumes the nominal clock rate, but the delay for FreeRTOS * to use is 75% of the minimal delay. * * @returns Maximum recommended delay between updates based on PIOS_WATCHDOG_TIMEOUT constant */ uint16_t PIOS_WDG_Init() { uint16_t delay = ((uint32_t) PIOS_WATCHDOG_TIMEOUT * 60) / 16; if (delay > 0x0fff) delay = 0x0fff; #if defined(PIOS_INCLUDE_WDG) DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); // make the watchdog stop counting in debug mode IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); IWDG_SetPrescaler(IWDG_Prescaler_16); IWDG_SetReload(delay); IWDG_ReloadCounter(); IWDG_Enable(); // watchdog flags now stored in backup registers PWR_BackupAccessCmd(ENABLE); wdg_configuration.bootup_flags = RTC_ReadBackupRegister(PIOS_WDG_REGISTER); /* * Start from an empty set of registered flags so previous boots * can't influence the current one */ RTC_WriteBackupRegister(PIOS_WDG_REGISTER, 0); #endif return delay; }
void Mclib_API_init(void) { ENC_Init(); SVPWM_3ShuntInit(); TB_Init(); //#ifdef BRAKE_RESISTOR // MCL_Brake_Init(); //#endif /* TIM1 Counter Clock stopped when the core is halted */ DBGMCU_Config(DBGMCU_TIM1_STOP, ENABLE); // Init Bus voltage and Temperature average MCL_Init_Arrays(); Res_f=1; }
// setup the hardware independent watchdog uint16_t runIWDGInit(int ms) { #ifndef RUN_ENABLE_IWDG return 0; #else uint16_t prevReloadVal; int reloadVal; IWDG_ReloadCounter();//feed dog DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE);//stop watch dog when use jtag to debug // IWDG timeout equal to 10 ms (the timeout may varies due to LSI frequency dispersion) // Enable write access to IWDG_PR and IWDG_RLR registers IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); // IWDG counter clock: LSI/4 IWDG_SetPrescaler(IWDG_Prescaler_4); reloadVal = RUN_LSI_FREQ*ms/4000; if (reloadVal < 1) reloadVal = 1; else if (reloadVal > 0xfff) reloadVal = 0xfff; prevReloadVal = IWDG->RLR; IWDG_SetReload(reloadVal); // Reload IWDG counter IWDG_ReloadCounter(); // Enable IWDG (the LSI oscillator will be enabled by hardware) IWDG_Enable(); return (prevReloadVal*4000/RUN_LSI_FREQ); #endif }
void initUsecTimer(void) { usecTimerHighCount = 0; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; NVIC_InitTypeDef NVIC_InitStructure; //Enable the Timer RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM7, ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = 0xFFFF; // APB1 clock is /4, but APB clock inputs to timers are doubled when // the APB clock runs slower than /1, so APB1 timers see a /2 clock TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / (1000 * 1000) / 2; TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM7, &TIM_TimeBaseStructure); NVIC_InitStructure.NVIC_IRQChannel = TIM7_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_TRACE_TIM_PRI; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); DBGMCU_Config(DBGMCU_TIM7_STOP, ENABLE); TIM_ITConfig(TIM7, TIM_IT_Update, ENABLE); TIM_Cmd(TIM7, ENABLE); }
void initUsecTimer(void) { //TODO #if 0 usecTimerHighCount = 0; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; NVIC_InitTypeDef NVIC_InitStructure; //Enable the Timer RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = 0xFFFF; TIM_TimeBaseStructure.TIM_Prescaler = 72; TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_TRACE_TIM_PRI; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); DBGMCU_Config(DBGMCU_TIM1_STOP, ENABLE); TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); TIM_Cmd(TIM1, ENABLE); #endif }
void board_stopmode() { DBGMCU_Config(DBGMCU_STOP, ENABLE); // Enable PWR and BKP clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); // Desable the SRAM and FLITF clock in Stop mode RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SRAM | RCC_AHBPeriph_FLITF, DISABLE); PWR_EnterSTOPMode(PWR_Regulator_ON,PWR_STOPEntry_WFI); }
/** * @brief Initialize the watchdog timer for a specified timeout * * It is important to note that this function returns the achieved timeout * for this hardware. For hardware indendence this should be checked when * scheduling updates. Other hardware dependent details may need to be * considered such as a window time which sets a minimum update time, * and this function should return a recommended delay for clearing. * * For the STM32 nominal clock rate is 32 khz, but for the maximum clock rate of * 60 khz and a prescalar of 4 yields a clock rate of 15 khz. The delay that is * set in the watchdog assumes the nominal clock rate, but the delay for FreeRTOS * to use is 75% of the minimal delay. * * @param[in] delayMs The delay period in ms * @returns Maximum recommended delay between updates */ uint16_t PIOS_WDG_Init(uint16_t delayMs) { uint16_t delay = ((uint32_t)delayMs * 60) / 16; if (delay > 0x0fff) delay = 0x0fff; DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); // make the watchdog stop counting in debug mode IWDG_WriteAccessCmd( IWDG_WriteAccess_Enable ); IWDG_SetPrescaler( IWDG_Prescaler_16 ); IWDG_SetReload( delay ); IWDG_ReloadCounter(); IWDG_Enable(); return ((((uint32_t)delay * 16) / 60) * .75f); }
/*---------------------------------------------------------------------------*/ int main(void) { DBGMCU_Config(DBGMCU_SLEEP | DBGMCU_STOP | DBGMCU_STANDBY, ENABLE); leds_init(); //printf("\rStarting Contiki on STM32VL Discovery...\n\r"); clock_init(); process_init(); uip_init(); uip_fw_init(); process_start(&tcpip_process, NULL); process_start(&uip_fw_process, NULL); uip_ipaddr(&hostaddr, 172, 16, 0, 3); uip_sethostaddr(&hostaddr); uip_ipaddr(&netmask, 255, 255, 0, 0); uip_setnetmask(&netmask); uip_ipaddr(&netmask, 172, 16, 0, 1); uip_setdraddr(&draddr); process_start(&etimer_process, NULL); ctimer_init(); /* Networking stack. */ NETSTACK_RADIO.init(); NETSTACK_RDC.init(); NETSTACK_MAC.init(); NETSTACK_NETWORK.init(); { rimeaddr_t rimeaddr; rimeaddr.u8[0] = 0x02; rimeaddr.u8[1] = 0x00; rimeaddr_set_node_addr(&rimeaddr); } autostart_start(autostart_processes); while (1) { process_run(); } return 0; }
void board_sleep() { #if 0 uint16_t sleepTime = radiotimer_getPeriod() - radiotimer_getCapturedTime(); DBGMCU_Config(DBGMCU_STOP, ENABLE); // Enable PWR and BKP clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); // Desable the SRAM and FLITF clock in Stop mode RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SRAM | RCC_AHBPeriph_FLITF, DISABLE); PWR_EnterSTOPMode(PWR_Regulator_ON,PWR_STOPEntry_WFI); if(sleepTime > 0) opentimers_sleepTimeCompesation(sleepTime*2); #endif }
// setup the hardware independent watchdog uint16_t runIWDGInit(int ms) { uint16_t prevReloadVal; int reloadVal; #ifndef RUN_ENABLE_IWDG return 0; #endif IWDG_ReloadCounter(); DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); // IWDG timeout equal to 10 ms (the timeout may varies due to LSI frequency dispersion) // Enable write access to IWDG_PR and IWDG_RLR registers IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); // IWDG counter clock: LSI/4 IWDG_SetPrescaler(IWDG_Prescaler_4); // Set counter reload value to obtain 10ms IWDG TimeOut. // Counter Reload Value = 10ms/IWDG counter clock period // = 10ms / (RUN_LSI_FREQ/4) // = 0.01s / (RUN_LSI_FREQ/4) // = RUN_LSI_FREQ/(4 * 100) // = RUN_LSI_FREQ/400 reloadVal = RUN_LSI_FREQ*ms/4000; if (reloadVal < 1) reloadVal = 1; else if (reloadVal > 0xfff) reloadVal = 0xfff; prevReloadVal = IWDG->RLR; IWDG_SetReload(reloadVal); // Reload IWDG counter IWDG_ReloadCounter(); // Enable IWDG (the LSI oscillator will be enabled by hardware) IWDG_Enable(); return (prevReloadVal*4000/RUN_LSI_FREQ); }
int main(void) { #if ZOTTAOS_TIMER == OS_IO_TIM14 DBGMCU_APB1PeriphConfig(DBGMCU_TIM14_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM13 DBGMCU_APB1PeriphConfig(DBGMCU_TIM13_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM12 DBGMCU_APB1PeriphConfig(DBGMCU_TIM12_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM11 DBGMCU_APB2PeriphConfig(DBGMCU_TIM11_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM10 DBGMCU_APB2PeriphConfig(DBGMCU_TIM10_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM9 DBGMCU_APB2PeriphConfig(DBGMCU_TIM9_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM8 DBGMCU_APB2PeriphConfig(DBGMCU_TIM8_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM5 DBGMCU_APB1PeriphConfig(DBGMCU_TIM5_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM4 DBGMCU_APB1PeriphConfig(DBGMCU_TIM4_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM3 DBGMCU_APB1PeriphConfig(DBGMCU_TIM3_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM2 DBGMCU_APB1PeriphConfig(DBGMCU_TIM2_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM1 DBGMCU_APB2PeriphConfig(DBGMCU_TIM1_STOP,ENABLE); #endif /* Keep debugger connection during sleep mode */ DBGMCU_Config(DBGMCU_SLEEP,ENABLE); /* Initialize Hardware */ SystemInit(); /* Initialize ZottaOS I/O UART drivers */ OSInitUART(UART_TRANSMIT_FIFO_NB_NODE,UART_TRANSMIT_FIFO_NODE_SIZE, UARTUserReceiveInterruptHandler,UART_VECTOR); /* Initialize USART2 hardware */ InitializeUART2Hardware(); /* Start the OS so that it runs the idle task, which puts the processor to sleep when ** there are no interrupts. */ return OSStartMultitasking(NULL,NULL); } /* end of main */
/* TIM Configure */ static void TIM_Configuration(void) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; // Enable TIM2 clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = (uint16_t)ADC_TRIG_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = ADC_TRIG_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); // TIM2 channel2 configuration in PWM mode TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 1; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC2Init(TIM2, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable); // Halt timer 2 during debug halt. DBGMCU_Config(DBGMCU_TIM2_STOP, ENABLE); }
int main(void) { TaskParametersDef *TaskParameters; /* Stop timer during debugger connection */ #if ZOTTAOS_TIMER == OS_IO_TIM17 DBGMCU_Config(DBGMCU_TIM17_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM16 DBGMCU_Config(DBGMCU_TIM16_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM15 DBGMCU_Config(DBGMCU_TIM15_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM14 DBGMCU_Config(DBGMCU_TIM14_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM13 DBGMCU_Config(DBGMCU_TIM13_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM12 DBGMCU_Config(DBGMCU_TIM12_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM11 DBGMCU_Config(DBGMCU_TIM11_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM10 DBGMCU_Config(DBGMCU_TIM10_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM9 DBGMCU_Config(DBGMCU_TIM9_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM8 DBGMCU_Config(DBGMCU_TIM8_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM5 DBGMCU_Config(DBGMCU_TIM5_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM4 DBGMCU_Config(DBGMCU_TIM4_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM3 DBGMCU_Config(DBGMCU_TIM3_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM2 DBGMCU_Config(DBGMCU_TIM2_STOP,ENABLE); #elif ZOTTAOS_TIMER == OS_IO_TIM1 DBGMCU_Config(DBGMCU_TIM1_STOP,ENABLE); #endif /* Keep debugger connection during sleep mode */ DBGMCU_Config(DBGMCU_SLEEP,ENABLE); /* Initialize Hardware */ SystemInit(); InitializeFlags(FLAG1_PIN | FLAG2_PIN | FLAG3_PIN); /* Create the 3 tasks. Notice that each particular task receives a private set of para- ** meters that it inherits from the main program and that it is the only task that can ** later access. */ #if defined(ZOTTAOS_VERSION_HARD) TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG1_PIN; TaskParameters->Delay = 150; OSCreateTask(FixedDelayTask,0,700,699,TaskParameters); TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG2_PIN; TaskParameters->Delay = 150; OSCreateTask(FixedDelayTask,0,700,700,TaskParameters); TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG3_PIN; TaskParameters->Delay = 7000; OSCreateTask(VariableDelayTask,0,2100,2100,TaskParameters); #elif defined(ZOTTAOS_VERSION_SOFT) TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG1_PIN; TaskParameters->Delay = 600; OSCreateTask(FixedDelayTask,200,0,700,250,1,3,0,TaskParameters); TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG2_PIN; TaskParameters->Delay = 600; OSCreateTask(FixedDelayTask,200,0,700,700,1,3,0,TaskParameters); TaskParameters = (TaskParametersDef *)OSMalloc(sizeof(TaskParametersDef)); TaskParameters->GPIOx = FLAG_PORT; TaskParameters->GPIO_Pin = FLAG3_PIN; TaskParameters->Delay = 7000; OSCreateTask(VariableDelayTask,1600,0,2100,2100,1,1,0,TaskParameters); #endif /* Start the OS so that it starts scheduling the user tasks */ return OSStartMultitasking(); } /* end of main */
void fetInit(void){ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Pin = FET_A_L_PIN; GPIO_Init(FET_A_L_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_A_L_PORT, FET_A_L_PIN, 0); GPIO_InitStructure.GPIO_Pin = FET_B_L_PIN; GPIO_Init(FET_B_L_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_B_L_PORT, FET_B_L_PIN, 0); GPIO_InitStructure.GPIO_Pin = FET_C_L_PIN; GPIO_Init(FET_C_L_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_C_L_PORT, FET_C_L_PIN, 0); GPIO_InitStructure.GPIO_Pin = FET_A_H_PIN; GPIO_Init(FET_A_H_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_A_H_PORT, FET_A_H_PIN, 0); GPIO_InitStructure.GPIO_Pin = FET_B_H_PIN; GPIO_Init(FET_B_H_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_B_H_PORT, FET_B_H_PIN, 0); GPIO_InitStructure.GPIO_Pin = FET_C_H_PIN; GPIO_Init(FET_C_H_PORT, &GPIO_InitStructure); GPIO_WriteBit(FET_C_H_PORT, FET_C_H_PIN, 0); TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_TimeBaseInitStructure.TIM_Period = (uint16_t)(F_CPU / 2000)-1; TIM_TimeBaseInitStructure.TIM_Prescaler = 0; TIM_TimeBaseInitStructure.TIM_ClockDivision = 0; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1; TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); TIM_TimeBaseInit(TIM4, &TIM_TimeBaseInitStructure); TIM_OCInitTypeDef TIM_OCInitStructure; TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC2Init(TIM3, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC1Init(TIM4, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC3Init(TIM3, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC2Init(TIM4, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC4Init(TIM3, &TIM_OCInitStructure); TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC3Init(TIM4, &TIM_OCInitStructure); TIM_SelectMasterSlaveMode(TIM3, TIM_MasterSlaveMode_Enable); TIM_SelectOutputTrigger(TIM3, TIM_TRGOSource_Enable); TIM_SelectSlaveMode(TIM4, TIM_SlaveMode_Gated); TIM_SelectInputTrigger(TIM4, TIM_TS_ITR2); DBGMCU_Config(DBGMCU_TIM3_STOP, DISABLE); DBGMCU_Config(DBGMCU_TIM4_STOP, DISABLE); TIM_Cmd(TIM4, ENABLE); TIM_Cmd(TIM3, ENABLE); TIM_SetCompare2(TIM3, 1000); TIM_SetCompare1(TIM4, 1000); TIM_SetCompare3(TIM3, 20000); TIM_SetCompare2(TIM4, 20000); TIM_SetCompare4(TIM3, 19000); TIM_SetCompare3(TIM4, 19000); TIM_GenerateEvent(TIM3, TIM_EventSource_COM); }
int main(void) { /*!< At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup file (startup_stm32f4xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f4xx.c file */ SystemInit(); GPIO_InitTypeDef GPIO_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12|GPIO_Pin_13|GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOF, &GPIO_InitStructure); NVIC_PriorityGroupConfig( NVIC_PriorityGroup_4 ); #ifdef USB_MS_ENABLED RCC_AHB1PeriphClockCmd( RCC_AHB1Periph_GPIOA , ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN ; GPIO_Init(GPIOA, &GPIO_InitStructure); delay(1000); //wait for pin initialisation to take effect ~125ms if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_8)) //if USB is plugged in { uint32_t i = 0; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE); //Activate USB line-pull up GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_ResetBits(GPIOB, GPIO_Pin_2); USBD_Init(&USB_OTG_dev, #ifdef USE_USB_OTG_HS USB_OTG_HS_CORE_ID, #else USB_OTG_FS_CORE_ID, #endif &USR_desc, &USBD_MSC_cb, &USR_cb); while(1) //stay in infinite loop, datalogger is not operational in USB mode { if (i++ == 0x100000) { GPIOF->ODR ^= GPIO_Pin_11; GPIOF->ODR ^= GPIO_Pin_12; GPIOF->ODR ^= GPIO_Pin_13; i = 0; } } } #endif //////////////////////////****************************////////////////////////////// IWDT_config(); //Comment the watchdog timer when debugging //////////////////////////****************************////////////////////////////// DBGMCU_Config(DBGMCU_IWDG_STOP, ENABLE); DBGMCU_Config(DBGMCU_I2C1_SMBUS_TIMEOUT, ENABLE); restore_offsets(); if (RCC_GetFlagStatus(RCC_FLAG_IWDGRST) != RESET) { GPIO_WriteBit(GPIOF, GPIO_Pin_11, Bit_SET); RCC_ClearFlag(); } xTaskCreate( vmisc_tasks, (const signed char*)"Manage misc tasks", STACK_SIZE_MIN, NULL, tskIDLE_PRIORITY, NULL ); xTaskCreate( vIMU_tasks, (const signed char*)"Manage IMU tasks", STACK_SIZE_MIN*5, NULL, 2, NULL ); vTaskStartScheduler(); while(1) { GPIOD->ODR ^= GPIO_Pin_12; } }
int main(void) { /*!< At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup file (startup_stm32l1xx_md.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32l1xx.c file */ /* Configure Clocks for Application need */ RCC_Configuration(); uint8_t rxBuf[4]; uint8_t txBuf[16]; uint8_t chByte[2]; uint8_t chMainStep=MAIN_STEP_IDLE; int16_t* iCurentAdcValue=(int16_t*)chByte; // теперь тут будет лежать последнее измеренное число /* Configure RTC Clocks */ RTC_Configuration(); /* Enable debug features in low power modes (Sleep, STOP and STANDBY) */ #ifdef DEBUG_SWD_PIN DBGMCU_Config(DBGMCU_SLEEP | DBGMCU_STOP | DBGMCU_STANDBY, ENABLE); #endif /* Configure SysTick IRQ and SysTick Timer to generate interrupts */ RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(RCC_Clocks.HCLK_Frequency / 500); /* Init I/O ports */ conf_analog_all_GPIOS(); /* configure all GPIOs as analog input */ InitButton(); MesureCurInit(); LCD_GLASS_Init();/* Initializes the LCD glass */ // RCC_AHBPeriphClockCmd(LD_GPIO_PORT_CLK , ENABLE); //RCC_AHBPeriphClockCmd(LD_GPIO_PORT_CLK | P_GATE1_GPIO_PORT_CLK | /// P_GATE2_GPIO_PORT_CLK | N_GATE1_GPIO_PORT_CLK | // N_GATE2_GPIO_PORT_CLK , ENABLE); Delay.Init(); DbgUART.UART_Init(USART3); i2cMgr.SetDbgUART(&DbgUART); i2cMgr.Init(); calipers.Init(); calipers.Callback=CallBackCalipers; // Setup i2cCmd to write config data to ADC txBuf[0]=0x88; //Bits 3 and 2 control the ADS1100Тs data rate "1 0"= 16SPS I2C_command.Address=0x48; I2C_command.DataToRead.Length = 0; I2C_command.DataToRead.Buf=rxBuf; I2C_command.DataToWrite.Buf = txBuf; I2C_command.DataToWrite.Length = 1; I2C_command.Callback=CallBackI2C; i2cMgr.AddCmd(I2C_command); // Setup i2cCmd to read data from ADC I2C_command.Address=0x48; I2C_command.DataToRead.Length = 4; I2C_command.DataToRead.Buf=rxBuf; I2C_command.DataToWrite.Buf = txBuf; I2C_command.DataToWrite.Length = 0; I2C_command.Callback=CallBackI2C; /* Display Welcome message */ // LCD_GLASS_ScrollSentence((uint8_t*)" CELESTIA ONLINE ",1,SCROLL_SPEED); Delay.Reset(&TimeDelay); Delay.Reset(&DbgDelay); MesureCurStop(); char chI2cCounter=0; MesureCurUpward(); chflagI2C=1; while(1){ i2cMgr.Task(); calipers.Task(); switch (chMainStep) { case MAIN_STEP_IDLE: if (calipers.GetState()==SPI_END_RX) //при выходе из холостго режима пропускаем первый отсчет со штангена, чтобы ток в датчике { chMainStep=MAIN_STEP_WAIT_CALIPERS_START; DbgUART.SendPrintF("OUT IDLE \n"); MesureCurUpward(); // включаем ток chflagI2C=0; } break; case MAIN_STEP_WAIT_CALIPERS_START: if (calipers.GetState()==SPI_IDLE) // давно небыло посылок с штангена, { DbgUART.SendPrintF("IN IDLE \n"); chMainStep=MAIN_STEP_IDLE; // переходим в холостой режим MesureCurStop(); //отключаем ток в датчике. } if (calipers.GetState()==SPI_START_RX) // начало приема данных со штангена { //DbgUART.SendPrintF("IN I2C \n"); chMainStep=MAIN_STEP_WAIT_I2C; i2cMgr.AddCmd(I2C_command); } break; case MAIN_STEP_WAIT_I2C: if (chflagI2C==1) // закончилась работа с I2C { chMainStep=MAIN_STEP_WAIT_CALIPERS_END; MesureCurToggle(); // переключаем направление тока } break; case MAIN_STEP_WAIT_CALIPERS_END: if (calipers.GetState()==SPI_END_RX) // закончилcz прием данных о штангена { chByte[0]=rxBuf[1]; chByte[1]=rxBuf[0]; DbgUART.SendPrintF("ACD_VAL=%d \n",*iCurentAdcValue); LCD_GLASS_Clear(); tiny_sprintf(strDisp, " %d ", calipers.iSpiDataRx ); LCD_GLASS_DisplayString( (unsigned char *) strDisp ); DbgUART.SendPrintF("CALIPERS_VAL=%d \n",calipers.iSpiDataRx); DbgUART.SendPrintF("OUT I2CE \n"); chMainStep=MAIN_STEP_WAIT_CALIPERS_START; } break; } //switch // if (Delay.Elapsed(&DbgDelay,100)) DbgUART.SendPrintF("i2c flag=%d main_state=%d \n ",chflagI2C, chMainStep) ; /* if (chflagI2C==1) // закончилась работа с I2C { MesureCurToggle(); chflagI2C=0; } if (Delay.Elapsed(&DbgDelay,250)) { if (chI2cCounter<=10) { //MesureCurToggle(); chByte[0]=rxBuf[1]; chByte[1]=rxBuf[0]; DbgUART.SendPrintF("ACD_VAL=%d \n",*iCurentAdcValue); rxBuf[0]=0; rxBuf[1]=0; chI2cCounter++; //chflagI2C=0; i2cMgr.AddCmd(I2C_command); } } */ if (flag_UserButton == TRUE) { clearUserButtonFlag(); chI2cCounter=0; } } }
void adcInit(void) { if(isInit) return; ADC_InitTypeDef ADC_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; NVIC_InitTypeDef NVIC_InitStructure; // Enable TIM2, GPIOA and ADC1 clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 | RCC_APB2Periph_ADC2 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = ADC_TRIG_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = ADC_TRIG_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); // TIM2 channel2 configuration in PWM mode TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 1; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC2Init(TIM2, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable); // Halt timer 2 during debug halt. DBGMCU_Config(DBGMCU_TIM2_STOP, ENABLE); adcDmaInit(); // ADC1 configuration ADC_DeInit(ADC1); ADC_InitStructure.ADC_Mode = ADC_Mode_RegSimult; ADC_InitStructure.ADC_ScanConvMode = ENABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T2_CC2; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = NBR_OF_ADC_CHANNELS; ADC_Init(ADC1, &ADC_InitStructure); // ADC1 channel sequence ADC_RegularChannelConfig(ADC1, CH_VREF, 1, ADC_SampleTime_28Cycles5); // ADC2 configuration ADC_DeInit(ADC2); ADC_InitStructure.ADC_Mode = ADC_Mode_RegSimult; ADC_InitStructure.ADC_ScanConvMode = ENABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfChannel = NBR_OF_ADC_CHANNELS; ADC_Init(ADC2, &ADC_InitStructure); // ADC2 channel sequence ADC_RegularChannelConfig(ADC2, CH_VBAT, 1, ADC_SampleTime_28Cycles5); // Enable ADC1 ADC_Cmd(ADC1, ENABLE); // Calibrate ADC1 ADC_ResetCalibration(ADC1); while(ADC_GetResetCalibrationStatus(ADC1)); ADC_StartCalibration(ADC1); while(ADC_GetCalibrationStatus(ADC1)); // Enable ADC1 external trigger ADC_ExternalTrigConvCmd(ADC1, ENABLE); ADC_TempSensorVrefintCmd(ENABLE); // Enable ADC2 ADC_Cmd(ADC2, ENABLE); // Calibrate ADC2 ADC_ResetCalibration(ADC2); while(ADC_GetResetCalibrationStatus(ADC2)); ADC_StartCalibration(ADC2); while(ADC_GetCalibrationStatus(ADC2)); // Enable ADC2 external trigger ADC_ExternalTrigConvCmd(ADC2, ENABLE); // Enable the DMA1 channel1 Interrupt NVIC_InitStructure.NVIC_IRQChannel = DMA1_Channel1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_ADC_PRI; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); adcQueue = xQueueCreate(1, sizeof(AdcGroup*)); xTaskCreate(adcTask, (const signed char *)"ADC", configMINIMAL_STACK_SIZE, NULL, /*priority*/3, NULL); isInit = true; }
//Initialization. Will set all motors ratio to 0% void motorsInit() { if (isInit) return; //Init structures GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; //Enable gpio and the timer RCC_APB2PeriphClockCmd( RCC_APB2Periph_AFIO | MOTOR1_GPIO_PERIF | MOTOR2_GPIO_PERIF | MOTOR3_GPIO_PERIF | MOTOR4_GPIO_PERIF, ENABLE); RCC_APB1PeriphClockCmd( MOTOR1_TIM_PERIF | MOTOR2_TIM_PERIF | MOTOR3_TIM_PERIF | MOTOR4_TIM_PERIF, ENABLE); GPIO_AFIODeInit(); //Remap MOTO3 TIM GPIO_PinRemapConfig(MOTOR3_TIM_REMAP, ENABLE); //Remap MOTO4 TIM GPIO_PinRemapConfig(MOTOR4_TIM_REMAP, ENABLE); // Configure the GPIO for the MOTO1 output GPIO_InitStructure.GPIO_Pin = MOTOR1_GPIO_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(MOTOR1_GPIO_PORT, &GPIO_InitStructure); // Configure the GPIO for the MOTO2 output GPIO_InitStructure.GPIO_Pin = MOTOR2_GPIO_PIN; GPIO_Init(MOTOR2_GPIO_PORT, &GPIO_InitStructure); // Configure the GPIO for the MOTO3 output GPIO_InitStructure.GPIO_Pin = MOTOR3_GPIO_PIN; GPIO_Init(MOTOR3_GPIO_PORT, &GPIO_InitStructure); // Configure the GPIO for the MOTO2 output GPIO_InitStructure.GPIO_Pin = MOTOR4_GPIO_PIN; GPIO_Init(MOTOR4_GPIO_PORT, &GPIO_InitStructure); //Timer configuration TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTOR1_TIM, &TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTOR2_TIM, &TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTOR3_TIM, &TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTOR4_TIM, &TIM_TimeBaseStructure); //PWM channels configuration (All identical!) TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCPolarity = MOTORS_POLARITY; TIM_OC4Init(MOTOR1_TIM, &TIM_OCInitStructure); TIM_OC4PreloadConfig(MOTOR1_TIM, TIM_OCPreload_Enable); TIM_OC4Init(MOTOR2_TIM, &TIM_OCInitStructure); TIM_OC4PreloadConfig(MOTOR2_TIM, TIM_OCPreload_Enable); TIM_OC4Init(MOTOR3_TIM, &TIM_OCInitStructure); TIM_OC4PreloadConfig(MOTOR3_TIM, TIM_OCPreload_Enable); TIM_OC3Init(MOTOR4_TIM, &TIM_OCInitStructure); TIM_OC3PreloadConfig(MOTOR4_TIM, TIM_OCPreload_Enable); //Enable the timer TIM_Cmd(MOTOR1_TIM, ENABLE); TIM_Cmd(MOTOR2_TIM, ENABLE); TIM_Cmd(MOTOR3_TIM, ENABLE); TIM_Cmd(MOTOR4_TIM, ENABLE); //Enable the timer PWM outputs //TIM_CtrlPWMOutputs(MOTOR1_TIM, ENABLE); //TIM_CtrlPWMOutputs(MOTOR2_TIM, ENABLE); //TIM_CtrlPWMOutputs(MOTOR3_TIM, ENABLE); //TIM_CtrlPWMOutputs(MOTOR4_TIM, ENABLE); TIM_ARRPreloadConfig(MOTOR1_TIM, ENABLE); TIM_ARRPreloadConfig(MOTOR2_TIM, ENABLE); TIM_ARRPreloadConfig(MOTOR3_TIM, ENABLE); TIM_ARRPreloadConfig(MOTOR4_TIM, ENABLE); // Halt timer during debug halt. DBGMCU_Config(MOTOR1_TIM_DBG, ENABLE); DBGMCU_Config(MOTOR2_TIM_DBG, ENABLE); DBGMCU_Config(MOTOR3_TIM_DBG, ENABLE); DBGMCU_Config(MOTOR4_TIM_DBG, ENABLE); isInit = RT_TRUE; }
void adcInit(void) { if(isInit) return; ADC_InitTypeDef ADC_InitStructure; ADC_CommonInitTypeDef ADC_CommonInitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; NVIC_InitTypeDef NVIC_InitStructure; // Enable TIM2, GPIOA and ADC1 clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = ADC_TRIG_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = ADC_TRIG_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 4; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure); // TIM2 channel2 configuration in PWM mode TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 1; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low; TIM_OC2Init(TIM2, &TIM_OCInitStructure); TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable); // Halt timer 2 during debug halt. DBGMCU_Config(DBGMCU_TIM2_STOP, ENABLE); adcDmaInit(); // ADC1 configuration ADC_CommonStructInit(&ADC_CommonInitStructure); ADC_CommonInitStructure.ADC_Mode = ADC_Mode_Independent; ADC_CommonInitStructure.ADC_Prescaler = ADC_Prescaler_Div8; ADC_CommonInitStructure.ADC_DMAAccessMode = ADC_DMAAccessMode_Disabled; ADC_CommonInitStructure.ADC_TwoSamplingDelay = ADC_TwoSamplingDelay_5Cycles; ADC_CommonInit(&ADC_CommonInitStructure); ADC_StructInit(&ADC_InitStructure); ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; ADC_InitStructure.ADC_ScanConvMode = ENABLE; ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_Rising; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T2_CC2; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; ADC_InitStructure.ADC_NbrOfConversion = 2; ADC_Init(ADC1, &ADC_InitStructure); // ADC1 channel sequence ADC_RegularChannelConfig(ADC1, CH_VREF, 1, ADC_SampleTime_28Cycles); ADC_RegularChannelConfig(ADC1, CH_VBAT, 2, ADC_SampleTime_28Cycles); ADC_DMARequestAfterLastTransferCmd(ADC1, ENABLE); ADC_VBATCmd(ENABLE); // Enable ADC1 ADC_Cmd(ADC1, ENABLE); // Enable the DMA1 channel Interrupt NVIC_InitStructure.NVIC_IRQChannel = DMA2_Stream0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = NVIC_ADC_PRI; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); adcQueue = xQueueCreate(1, sizeof(AdcGroup)); xTaskCreate(adcTask, "ADC", configMINIMAL_STACK_SIZE, NULL, /*priority*/3, NULL); isInit = true; }
/** * @brief Enters MCU in STOP mode. The wake-up from STOP mode is performed by * an external interrupt. * @param None * @retval None */ void LowPower_EnterSTOPMode_EXTI(void) { NVIC_InitTypeDef NVIC_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; /* Clear the STOPModeStatus variable */ LowPower_Reset_STOPModeStatus(); /* Clear the LCD */ /* Set the LCD Back Color */ /* Set the LCD Text Color */ /* External Interrupt Disable */ //Demo_IntExtOnOffCmd(DISABLE); /* Clear the RTC Alarm flag */ RTC_ClearFlag(RTC_FLAG_ALRAF); /* Save the GPIO pins current configuration then put all GPIO pins in Analog Input mode ...*/ LowPower_SaveGPIOConfig(); /* Enable the debug when the MCU enter in stop mode */ DBGMCU_Config(DBGMCU_STOP, ENABLE); /* Configure Button pin as input */ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_InitStructure.GPIO_Pin = KEY_BUTTON_PIN; GPIO_Init(KEY_BUTTON_GPIO_PORT, &GPIO_InitStructure); /* Connect Button EXTI Line to Button GPIO Pin */ SYSCFG_EXTILineConfig(KEY_BUTTON_EXTI_PORT_SOURCE, KEY_BUTTON_EXTI_PIN_SOURCE); /* Configure the EXTI Line 8 */ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Line = EXTI_Line8; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); /* Enable the EXTI9_5 Interrupt */ //NVIC_InitStructure.NVIC_IRQChannel = EXTI4_15_IRQn; //NVIC_InitStructure.NVIC_IRQChannelPriority = 3; //NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //NVIC_Init(&NVIC_InitStructure); /* Request to enter STOP mode with regulator in low power */ PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); /* Restore the GPIO Configurations*/ LowPower_RestoreGPIOConfig(); /* At this stage the system has resumed from STOP mode ************************/ EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Line = EXTI_Line8; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = DISABLE; EXTI_Init(&EXTI_InitStructure); /* Enable the EXTI9_5 Interrupt */ //NVIC_InitStructure.NVIC_IRQChannel = EXTI4_15_IRQn; //NVIC_InitStructure.NVIC_IRQChannelPriority = 3; //NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //NVIC_Init(&NVIC_InitStructure); /* Configures system clock after wake-up from STOP: enable HSE, PLL and select PLL as system clock source (HSE and PLL are disabled in STOP mode) */ LowPower_SYSCLKConfig_STOP(); if (STOPModeStatus != RESET) { } else { } /* External Interrupt Enable */ //Demo_IntExtOnOffCmd(ENABLE); }
//Initialization. Will set all motors ratio to 0% void motorsInit() { if (isInit) return; //Init structures GPIO_InitTypeDef GPIO_InitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_OCInitTypeDef TIM_OCInitStructure; //Enable gpio and the timer RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO | MOTORS_GPIO_PERIF, ENABLE); RCC_APB1PeriphClockCmd(MOTORS_GPIO_TIM_PERIF | MOTORS_GPIO_TIM_M3_4_PERIF, ENABLE); // Configure the GPIO for the timer output GPIO_InitStructure.GPIO_Pin = (MOTORS_GPIO_M1 | MOTORS_GPIO_M2 | MOTORS_GPIO_M3 | MOTORS_GPIO_M4); GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(MOTORS_GPIO_PORT, &GPIO_InitStructure); //Remap M2-4 GPIO_PinRemapConfig(MOTORS_REMAP , ENABLE); //Timer configuration TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTORS_GPIO_TIM_M1_2, &TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = MOTORS_PWM_PERIOD; TIM_TimeBaseStructure.TIM_Prescaler = MOTORS_PWM_PRESCALE; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(MOTORS_GPIO_TIM_M3_4, &TIM_TimeBaseStructure); //PWM channels configuration (All identical!) TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OC3Init(MOTORS_GPIO_TIM_M3_4, &TIM_OCInitStructure); TIM_OC3PreloadConfig(MOTORS_GPIO_TIM_M3_4, TIM_OCPreload_Enable); TIM_OC4Init(MOTORS_GPIO_TIM_M3_4, &TIM_OCInitStructure); TIM_OC4PreloadConfig(MOTORS_GPIO_TIM_M3_4, TIM_OCPreload_Enable); TIM_OC3Init(MOTORS_GPIO_TIM_M1_2, &TIM_OCInitStructure); TIM_OC3PreloadConfig(MOTORS_GPIO_TIM_M1_2, TIM_OCPreload_Enable); TIM_OC4Init(MOTORS_GPIO_TIM_M1_2, &TIM_OCInitStructure); TIM_OC4PreloadConfig(MOTORS_GPIO_TIM_M1_2, TIM_OCPreload_Enable); //Enable the timer TIM_Cmd(MOTORS_GPIO_TIM_M1_2, ENABLE); TIM_Cmd(MOTORS_GPIO_TIM_M3_4, ENABLE); //Enable the timer PWM outputs TIM_CtrlPWMOutputs(MOTORS_GPIO_TIM_M1_2, ENABLE); TIM_CtrlPWMOutputs(MOTORS_GPIO_TIM_M3_4, ENABLE); // Halt timer during debug halt. DBGMCU_Config(MOTORS_GPIO_TIM_M1_2_DBG, ENABLE); DBGMCU_Config(MOTORS_GPIO_TIM_M3_4_DBG, ENABLE); isInit = true; }
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) { NVIC_SetVectorTable(NVIC_VectTab_FLASH,0x3000); set_msi(); DBGMCU_Config(DBGMCU_SLEEP | DBGMCU_STANDBY | DBGMCU_STOP, DISABLE); set_bor(); Power.sleep_now=DISABLE; DataUpdate.Need_erase_flash=ENABLE; Settings.Geiger_voltage=360; // Напряжение на датчике 360 вольт Settings.Pump_Energy=350; // энергия накачки 350 мТл DataUpdate.current_flash_page=0; io_init(); // Инициализация потров МК eeprom_write_default_settings(); // Проверка, заполнен ли EEPROM eeprom_read_settings(); // Чтение настроек из EEPROM screen=1; Power.USB_active=DISABLE; Power.sleep_time=Settings.Sleep_time; Power.Display_active=ENABLE; ADCData.DAC_voltage_raw=0x610; dac_init(); comp_init(); comp_on(); timer9_Config(); // Конфигурируем таймер накачки timer10_Config(); tim2_Config(); sound_activate(); delay_ms(100); sound_deactivate(); //-------------------------------------------------------------------- RTC_Config(); // Конфигурируем часы //-------------------------------------------------------------------- // инициализация дисплея //-------------------------------------------------------------------- delay_ms(50); // подождать установки напряжения display_on(); LcdInit(); LcdClear(); //-------------------------------------------------------------------- adc_init(); delay_ms(100); adc_calibration(); delay_ms(10); //-------------------------------------------------------------------- EXTI8_Config(); #ifdef version_401 EXTI9_Config(); #endif EXTI3_Config(); EXTI4_Config(); EXTI6_Config(); DataUpdate.Need_batt_voltage_update=ENABLE; if(!GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_6))hidden_menu=ENABLE; // Открытие сервисных пунктов меню delay_ms(500); // подождать установки напряжения while(1) ///////////////////////////////// { if(DataUpdate.Need_fon_update==ENABLE) geiger_calc_fon(); if(key>0) keys_proccessing(); if(DataUpdate.Need_batt_voltage_update) adc_check_event(); //////////////////////////////////////////////////// if((Power.sleep_time>0)&(!Power.Display_active))sleep_mode(DISABLE); // Если дисплей еще выключен, а счетчик сна уже отсчитывает, поднимаем напряжение и включаем дисплей if(Power.Display_active) { if(Power.sleep_time==0 && !Alarm.Alarm_active) sleep_mode(ENABLE); // Счетчик сна досчитал до нуля, а дисплей еще активен, то выключаем его и понижаем напряжение if(Power.led_sleep_time>0) { GPIO_ResetBits(GPIOC,GPIO_Pin_13);// Включаем подсветку } else { GPIO_SetBits(GPIOC,GPIO_Pin_13);// Выключаем подсветку } if(DataUpdate.Need_display_update==ENABLE) { DataUpdate.Need_display_update=DISABLE; LcdClear_massive(); if (screen==1)main_screen(); if (screen==2)menu_screen(); if (screen==3)stat_screen(); } /////////////////////////////////////////////////////////////////////////////// } #ifdef version_401 if((!Power.USB_active) && (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_9))){ usb_activate(0x0); // Если питание USB начало подаваться включаем USB } #endif if(!Power.USB_active) // если USB не активен, можно уходить в сон { if(current_pulse_count<30) // Если счетчик не зашкаливает, то можно уйти в сон { if(!Power.Pump_active && !Power.Sound_active) { PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); // Переходим в сон #ifdef debug Wakeup.total_wakeup++; DataUpdate.Need_display_update=ENABLE; #endif } else { PWR_EnterSleepMode(PWR_Regulator_ON, PWR_SLEEPEntry_WFI); #ifdef debug Wakeup.total_wakeup++; DataUpdate.Need_display_update=ENABLE; #endif } } }else USB_work(); // если USB активен, попробовать передать данные #ifdef debug Wakeup.total_cycle++; DataUpdate.Need_display_update=ENABLE; #endif } /////////////////////////////////////////////////////////////////////////////// }
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 } }
int main(void) { uint32_t ppg; //PPG channel uint32_t data_counter=0; //used as data timestamp uint8_t system_state=0; //used to track button press functionality float sensor_data; //used for handling data passed back from sensors 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 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_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 } 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(); } } 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 for(uint8_t n=0;n<PPG_CHANNELS;n++) init_buffer(&(Buff[n]),PPG_BUFFER_SIZE);//Enough for ~0.25S of data setup_pwm(); //Enable the PWM outputs on all three channels Delay(100000); //Sensor+inst amplifier takes about 100ms to stabilise after power on ADC_Configuration(); //We leave this a bit later to allow stabilisation calibrate_sensor(); //Calibrate the offset on the diff pressure sensor EXTI_ONOFF_EN(); //Enable the off interrupt - allow some time for debouncing I2C_Config(); //Setup the I2C bus uint8_t sensors_=detect_sensors(); //Search for connected sensors sensor_data=GET_BATTERY_VOLTAGE; //Have to flush adc for some reason Delay(10000); if(!(sensors_&~(1<<PRESSURE_HOSE))||GET_BATTERY_VOLTAGE<BATTERY_STARTUP_LIMIT) {//We will have to turn off Watchdog_Reset(); //LED flashing takes a while if(abs(Reported_Pressure)>PRESSURE_MARGIN) Set_Motor(-1); //If the is air backpressure, dump to rapidly drop to zero pressure before turnoff if(file_opened) f_close(&FATFS_logfile); //be sure to terminate file neatly red_flash(); Delay(400000); red_flash(); //Two flashes means battery abort -----------------ABORT 2 if(sensors_&~(1<<PRESSURE_HOSE)) shutdown(); Delay(400000); red_flash(); //Three flashes means no sensors abort ------------ABORT 3 shutdown(); } 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_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 } #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("%d-%d-%dT%d-%d-%d.txt",RTC_time.year,RTC_time.month,RTC_time.mday,RTC_time.hour,RTC_time.min,RTC_time.sec);//Timestamp name rprintfInit(__usart_send_char); //Printf over the bluetooth #endif if((f_err_code=f_open(&FATFS_logfile,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 } }
int main(void) { /*!< At this stage the microcontroller clock setting is already configured, this is done through SystemInit() function which is called from startup file (startup_stm32l1xx_md.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32l1xx.c file */ /* Configure Clocks for Application need */ RCC_Configuration(); /* Configure RTC Clocks */ RTC_Configuration(); /* Set internal voltage regulator to 1.8V */ PWR_VoltageScalingConfig(PWR_VoltageScaling_Range1); /* Wait Until the Voltage Regulator is ready */ while (PWR_GetFlagStatus(PWR_FLAG_VOS) != RESET) ; /* Enable debug features in low power modes (Sleep, STOP and STANDBY) */ #ifdef DEBUG_SWD_PIN DBGMCU_Config(DBGMCU_SLEEP | DBGMCU_STOP | DBGMCU_STANDBY, ENABLE); #endif /* Configure SysTick IRQ and SysTick Timer to generate interrupts */ RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(RCC_Clocks.HCLK_Frequency / 500); /* Init I/O ports */ Init_GPIOs(); /* Initializes the LCD glass */ LCD_GLASS_Configure_GPIO(); LCD_GLASS_Init(); /* Display Welcome message */ LCD_GLASS_ScrollSentence(" ** TEMPERATURE SENSOR EXAMPLE ** ",1,SCROLL_SPEED); /* Disable SysTick IRQ and SysTick Timer */ SysTick->CTRL &= ~ ( SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk ); /* Test user or factory temperature sensor calibration value */ if ( testFactoryCalibData() == SUCCESS ) getFactoryTSCalibData(&calibdata); else if ( testUserCalibData() == SUCCESS ) calibdata = *USER_CALIB_DATA; else { /* User calibration or factory calibration TS data are not available */ calibdata.TS_CAL_1 = DEFAULT_COLD_VAL; calibdata.TS_CAL_2 = DEFAULT_HOT_VAL; writeCalibData(&calibdata); calibdata = *USER_CALIB_DATA; } /* Configure Wakeup from sleep using RTC event*/ configureWakeup(); /* Configure direct memory access for ADC usage*/ configureDMA(); /* Configure ADC for temperature sensor value conversion */ configureADC_Temp(); while(1) { /* Re-enable DMA and ADC conf and start Temperature Data acquisition */ acquireTemperatureData(); /* Stay in SLEEP mode untill the data are acquired by ADC */ __WFI(); /* for DEBUG purpose uncomment the following line and comment the __WFI call to do not enter STOP mode */ // while (!flag_ADCDMA_TransferComplete); /* Disable ADC, DMA and clock*/ powerDownADC_Temper(); /* Process mesured Temperature data - calculate average temperature value in °C */ processTempData(); if (flag_UserButton == TRUE) { clearUserButtonFlag(); if (CurrentlyDisplayed == Display_TemperatureDegC) CurrentlyDisplayed = Display_ADCval; else CurrentlyDisplayed = Display_TemperatureDegC; } if (CurrentlyDisplayed == Display_TemperatureDegC) { /* print average temperature value in °C */ sprintf(strDisp, "%d °C", temperature_C ); } else { /* print result of ADC conversion */ sprintf(strDisp, "> %d", tempAVG ); } LCD_GLASS_Clear(); LCD_GLASS_DisplayString( (unsigned char *) strDisp ); /* Enable RTC Wakeup */ RTC_WakeUpCmd(ENABLE); /* Clear WakeUp flag */ PWR_ClearFlag(PWR_FLAG_WU); /* Enter in wait for interrupt stop mode*/ PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); RCC_Configuration(); // reinitialize clock /* After Wake up : Disable Wake up from RTC*/ RTC_WakeUpCmd(DISABLE); } }
/*! * Init board. */ void BoardInit(void) { SPI_InitTypeDef SPI_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; #ifdef STM32F10X_MD RCC_APB2PeriphClockCmd( 0 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_AFIO , ENABLE); #else #ifdef STM32L1XX_MD RCC_AHBPeriphClockCmd( 0 | RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB , ENABLE); #else #error "Unknown CPU type" #endif #endif DBGMCU_Config( 0 | DBGMCU_TIM2_STOP | DBGMCU_TIM3_STOP | DBGMCU_SLEEP | DBGMCU_STOP | DBGMCU_STANDBY , ENABLE); MAC_TIMER_CLOCK(); DELAY_TIMER_CLOCK(); LED1_OFF(); LED1_INIT(); LED2_OFF(); LED2_INIT(); TimerInit( MAC_TIMER, MAC_TIMER_PRESCALER, MAC_TIMER_IRQn ); TimerInit( DELAY_TIMER, DELAY_TIMER_PRESCALER, 0 ); RF_SDN_HIGH(); RF_SDN_INIT(); RF_NSS_HIGH(); RF_NSS_INIT(); RF_SCLK_INIT(); RF_MISO_INIT(); RF_MOSI_INIT(); RF_IRQ_INIT(); DELAY_uS(10 * DELAY_1MS_TIMER2); RF_SDN_LOW(); DELAY_uS(50 * DELAY_1MS_TIMER2); RF_SPI_CLOCK(); SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_Low; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_32; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(RF_SPI, &SPI_InitStructure); SPI_Cmd(RF_SPI, ENABLE); #ifdef STM32F10X_MD GPIO_EXTILineConfig(RF_IRQ_EXT_PORT, RF_IRQ_EXT_PIN); #else #ifdef STM32L1XX_MD SYSCFG_EXTILineConfig(RF_IRQ_EXT_PORT, RF_IRQ_EXT_PIN); #endif #endif EXTI_InitStructure.EXTI_Line = RF_IRQ_EXT_LINE; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); DISABLE_MAC_EXT_INTERRUPT(); CLEAR_MAC_EXT_INTERRUPT(); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0); NVIC_InitStructure.NVIC_IRQChannel = RF_IRQ_EXT_IRQ; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #ifdef RTC_ENABLED RTC_INIT(); #endif #ifdef UART0_ENABLED Uart0Init(); #endif }
void board_sleep() { #ifdef DEBUG_RUN_MODE // nothing need to do #endif #ifdef DEBUG_SLEEP_MODE DBGMCU_Config(DBGMCU_SLEEP, ENABLE); // Enable PWR and BKP clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); // Desable the SRAM and FLITF clock in sleep mode RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SRAM | RCC_AHBPeriph_FLITF, DISABLE); // enter sleep mode __WFI(); #endif #ifdef DEBUG_STOP_MODE uint16_t sleepTime = radiotimer_getPeriod() - radiotimer_getCapturedTime(); DBGMCU_Config(DBGMCU_STOP, ENABLE); // Enable PWR and BKP clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); // Desable the SRAM and FLITF clock in Stop mode RCC_AHBPeriphClockCmd(RCC_AHBPeriph_SRAM | RCC_AHBPeriph_FLITF, DISABLE); // enter stop mode PWR_EnterSTOPMode(PWR_Regulator_ON,PWR_STOPEntry_WFI); if(sleepTime > 0) opentimers_sleepTimeCompesation(sleepTime); #endif }
/**----------------------------------------------------------------------------- * @brief Initialisation de la carte. */ void BSP_Init() { MappingGpio_e PinId; /* Desactivation des interruptions */ __disable_irq(); /* Initialisation STM32 system (clock, PLL and Flash configuration) */ SystemInit(); SystemCoreClockUpdate(); /* Set the Vector Table base address at 0x08000000 */ NVIC_SetVectorTable(NVIC_VectTab_FLASH, OFFSET); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4 ); /* Configure HCLK clock as SysTick clock source. */ SysTick_CLKSourceConfig( SysTick_CLKSource_HCLK ); /* Initialisation des GPIO */ for (PinId = 0; PinId < NB_PORT_GPIO; PinId++) // Parcours de a table du mapping GPIO_InitPin(PinId); // Configuration du fonctionnement du Debug DBGMCU_Config(DBGMCU_STOP, ENABLE); // Keep debugger connection during STOP mode DBGMCU_APB1PeriphConfig(DBGMCU_WWDG_STOP, ENABLE); // Debug WWDG stopped when Core is halted // Effacement des flags d'erreur d'acces a la flash FLASH_ClearFlag( FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR | FLASH_FLAG_BSY); /* Activation des interruptions */ __enable_irq(); }
void platform_init_busclk() { ///@todo enable RTC Clock # ifdef __DEBUG__ DBGMCU_Config(DBGMCU_SLEEP | DBGMCU_STOP | DBGMCU_STANDBY | DBGMCU_IWDG_STOP | DBGMCU_WWDG_STOP | DBGMCU_TIM2_STOP | DBGMCU_TIM3_STOP , ENABLE); # endif }