void main(void) { /*--------------initialization-----------*/ Set_System(); NVIC_Configuration(); GPIO_Config(); SD_Card_Check(); USB_Init(); ADC_Configuration(); Timer_Configuration(); LCD_Initial(); Clear_Screen(BLACK); Display_Logo(110,150); /*----------Power ON Information----------*/ Display_Str(80, 87, GRN, PRN, "System Initializing"); Display_Str(102, 71, GRN, PRN, "Please Wait"); Display_Str(8, 39, WHITE, PRN, "DSO FW Copyright (c) BenF 2010-2011"); Display_Str(8, 23, YEL, PRN, "LIB ver 3.13"); //WaitForKey(); // check for presence of APP and jump to start pApp = (APP_Interface *)*(u32 *)(APP_VECTORS + 7 * 4); if (pApp->Signature == APP_SIGNATURE) pApp->APP_Start(); Display_Str(150, 23, RED, PRN, "No APP found"); while (1); }
void ADC_Handler(char *pcInsert) { /* We have only one SSI handler iIndex = 0 */ char Digit1=0, Digit2=0, Digit3=0, Digit4=0; uint32_t ADCVal = 0; if (ADC_not_configured ==1) { ADC_Configuration(); ADC_not_configured=0; } /* get ADC conversion value */ ADCVal = ADC_GetConversionValue(ADC1); /* convert to Voltage, step = 0.8 mV */ ADCVal = (uint32_t)(ADCVal * 0.8); /* get digits to display */ Digit1= ADCVal/1000; Digit2= (ADCVal-(Digit1*1000))/100 ; Digit3= (ADCVal-((Digit1*1000)+(Digit2*100)))/10; Digit4= ADCVal -((Digit1*1000)+(Digit2*100)+ (Digit3*10)); /* prepare data to be inserted in html */ *pcInsert = (char)(Digit1+0x30); *(pcInsert + 1) = (char)(Digit2+0x30); *(pcInsert + 2) = (char)(Digit3+0x30); *(pcInsert + 3) = (char)(Digit4+0x30); *(pcInsert + 4) = 0; }
/** * @brief Main program. * @param None * @retval None */ int main(void) { /* Configure System clocks -----------------------------------------------*/ RCC_Configuration(); /* Configure GPIO ports --------------------------------------------------*/ GPIO_Configuration(); USART_Configuration(); /* Output a message on Hyperterminal using printf function */ printf("\n\rADC different test: \n\r"); ADC_Configuration(); while(ADC_GetBitState(ADC_FLAG_EOC) != SET); ADCConvertedValue = ADC_GetConversionValue(); printf("\n\rThe original data %d\n\r",ADCConvertedValue); ADC_DeInit(&ADC_InitStructure); ADC_OVERConfiguration(); while(ADC_GetBitState(ADC_FLAG_EOC) != SET); ADCConvertedValue_OVER = ADC_GetConversionValue(); printf("\n\rOversampling data %d\n\r",ADCConvertedValue_OVER); while (1) { } }
void adc_hw_init(void) { GPIO_Configuration(); TIM_Configuration(); DMA_Configuration(); ADC_Configuration(); NVIC_Configuration(); }
/** * @brief Initialize the correspond device. * @param Device_Init: specifies the devices which will be initalized * This parameter can be any combination of the following values: * @arg GPIO_INIT, RTC_INIT, USART_INIT, FLASH_INIT, * FSCM_INIT, RCC_INIT * @retval : None */ void SystemResourcesInit(uint32_t Device_Init) { if(Device_Init & RCC_INIT) { /* System Clocks Configuration */ RCC_Configuration(); //RCC_Internal_Configuration(); } if(Device_Init & FSCM_INIT) { FSCM_Configuration(); } if(Device_Init & FLASH_INIT) { Flash_Configuration(FALSE); } if(Device_Init & NVIC_INIT) { /* NVIC configuration */ NVIC_Configuration(); } if(Device_Init & GPIO_INIT) { /* Configure the GPIO */ GPIO_Configuration(); } if(Device_Init & USART_INIT) { /* Configure the USART */ USARTx_Configuration(); } if(Device_Init & SYSTICK_INIT) { /* SysTick Configuration */ SysTick_Configuration(); } if(Device_Init & TIMER_INIT) { /* Timer Configuration */ Timer_Configuration(); } if(Device_Init & SPI_INIT) { SPIx_Configuration(); } if(Device_Init & DAC_INIT) { DAC_VOLTAGE_Configuration(); } if(Device_Init & ADC_INIT) { ADC_Configuration(); } }
/* The core is running at 72MHz */ int main(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Set the Vector Table base adress at 0x8004000 */ NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x4000); RCC_APB2PeriphClockCmd (RCC_APB2Periph_GPIOB|RCC_APB2Periph_GPIOA , ENABLE); /* Full SWJ Disabled (JTAG-DP + SW-DP) */ GPIO_PinRemapConfig (GPIO_Remap_SWJ_Disable, ENABLE); //LED0 -> PB0, LED1 -> PB1 // Reset GPIO init structure GPIO_StructInit(&GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOB, &GPIO_InitStructure); // Configure PA1 as input floating // Reset GPIO init structure GPIO_StructInit(&GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//GPIO_Mode_IPD; GPIO_Init(GPIOA, &GPIO_InitStructure); USART1_Init(); ADC_Configuration(); while (1) { /* LED0-ON LED1-OFF */ GPIO_SetBits(GPIOB , GPIO_Pin_0); GPIO_ResetBits(GPIOB , GPIO_Pin_1); Delay(0xfffff); /* LED0-OFF LED1-ON */ GPIO_ResetBits(GPIOB , GPIO_Pin_0); GPIO_SetBits(GPIOB , GPIO_Pin_1); Delay(0xfffff); /* Print the ADC PA1 DIP Switch value to USART */ USART1_Print_Int(readDIPSwitch()); if (GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_1) == 1) USART1_Print(", ON\n"); else USART1_Print(", OFF\n"); } }
//各个外设的初始化 void Peripheral_Init(void) { // 中断向量表配置 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); PS_Init(); KEY_Init(); STATU_Init(); LED_Init(); BEEP_Init(); CAN1_Init(); CAN2_Init(); OLED_Init(); ADC_Configuration(); }
//------------------------------------------------------------------------------ // === Initialize Function === //------------------------------------------------------------------------------ void Init_Main(void) { RCC_Configuration(); // RCC_GetClocksFreq(&rcc_clocks); GPIO_Configuration(); NVIC_Configuration(); DMA_Configuration(); ADC_Configuration(); // TIM_Configuration(); EXTI_Configuration(); nRF24_init(); // nRF24_ClearIRQFlags(); USART1_Init(57600); // in 36mhz error 0% }
/******************************************************************************** * sampleAcquisitionInit * * Init the sampling routine. * Blocking function. * * @param Void * @return 0 if working *******************************************************************************/ void sampleAcquisitionInit( void ) { /***************** * SYSTEM CLOCKS * *****************/ RCC_Configuration(); /******** * GPIO * ********/ GPIO_Configuration(); /******* * DMA * *******/ DMA_Configuration(); /******* * ADC * *******/ ADC_Configuration(); /********* * TIMER * *********/ TIMER_Configuration(); /******** * NVIC * ********/ IT_Configuration(); /********* * START * *********/ }
//------------------------------------------------------------------------------ // === Initialize Function === //------------------------------------------------------------------------------ void Init_Main(void) { RCC_Configuration(); //RCC_GetClocksFreq(&rcc_clocks); GPIO_Configuration(); NVIC_Configuration(); DMA_Configuration(); ADC_Configuration(); TIM_Configuration(); EXTI_Configuration(); Tim_Encoder_initial(); USART1_Init(57600); // in 36mhz error 0% USART3_Init(115200);// in 72mhz error 0% //if (SysTick_Config(rcc_clocks.SYSCLK_Frequency / 1000)) //{ /* Capture error */ // while (1); //} }
int main(void) { //设置NVIC中断分组2位抢占优先级,2位响应优先级 NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2) ; Ticker_Configuration(); LED_Configuration(); USART2_Configuration(); delay_init(); //Do_Loop_LED_Test(); //Do_Loop_Motor_Test(); //DISABLE_FOLLOWING_CODE(1); //主控通信控制器初始化 Maincontrol_Configuration(); Encoder_Configuration(); Encoder_Start(); //速度采样控制器初始化 TIM2_Configuration(5); TIM2_Start(); //电流检测 ADC_Configuration(); //电机初始化 Motor_Init(); while (1) { delay_ms(200); LED_RED_TOGGLE(); LED_GREEN_TOGGLE(); } }
/** * @brief ADC_Handler : SSI handler for ADC page */ u16_t ADC_Handler(int iIndex, char *pcInsert, int iInsertLen) { /* We have only one SSI handler iIndex = 0 */ if (iIndex ==0) { char Digit1=0, Digit2=0, Digit3=0, Digit4=0; uint32_t ADCVal = 0; /* configure ADC if not yet configured */ if (ADC_not_configured ==1) { ADC_Configuration(); ADC_not_configured=0; } HAL_ADC_PollForConversion(&hadc, 10); /* get ADC conversion value */ ADCVal = HAL_ADC_GetValue(&hadc); /* convert to Voltage, step = 0.8 mV */ ADCVal = (uint32_t)(ADCVal * 0.8); /* get digits to display */ Digit1= ADCVal/1000; Digit2= (ADCVal-(Digit1*1000))/100; Digit3= (ADCVal-((Digit1*1000)+(Digit2*100)))/10; Digit4= ADCVal -((Digit1*1000)+(Digit2*100)+ (Digit3*10)); /* prepare data to be inserted in html */ *pcInsert = (char)(Digit1+0x30); *(pcInsert + 1) = (char)(Digit2+0x30); *(pcInsert + 2) = (char)(Digit3+0x30); *(pcInsert + 3) = (char)(Digit4+0x30); /* 4 characters need to be inserted in html*/ return 4; } return 0; }
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 } }
void init(void) { SystemInit(); //Setup SystickTimer if (SysTick_Config(SystemCoreClock / 1000)){ColorfulRingOfDeath();} GPIO_Configuration(); #ifdef USE_MICROUSB USBD_Init(&USB_OTG_dev, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_CDC_cb, &USR_cb); #endif #ifdef USE_SDIO UB_Fatfs_Init(); #endif #ifdef USE_ADC ADC_Configuration(); #endif #ifdef USE_I2C I2C_Configuration(); #endif #ifdef USE_SPI SPI_Configuration(); #endif #ifdef USE_ENCODER TIM_encoder_Configuration(); #endif #ifdef USE_USART1 USART1_Configuration(); #endif #ifdef USE_USART2 USART2_Configuration(); #endif #ifdef USE_USART3 USART3_Configuration(); #endif #ifdef USE_CAN CAN_Configuration(); #endif #ifdef USE_PWM TIM_pwm_Configuration(); #endif #ifdef USE_EXTI EXTI_Configuration(); #endif NVIC_Configuration(); }
/** * @brief Setup STM32 system (clocks, Ethernet, GPIO, NVIC) and STM3210C-EVAL resources. * @param None * @retval None */ void System_Setup(void) { RCC_ClocksTypeDef RCC_Clocks; /* Setup STM32 clock, PLL and Flash configuration) */ SystemInit(); /* Enable USART2 clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); /* Enable ETHERNET clock */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_ETH_MAC | RCC_AHBPeriph_ETH_MAC_Tx | RCC_AHBPeriph_ETH_MAC_Rx, ENABLE); /* Enable GPIOs and ADC1 clocks */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE | RCC_APB2Periph_AFIO | RCC_APB2Periph_ADC1, ENABLE); /* NVIC configuration */ NVIC_Configuration(); /* ADC configuration */ ADC_Configuration(); /* Configure the GPIO ports */ GPIO_Configuration(); /* Initialize the STM3210C-EVAL's LCD */ STM3210C_LCD_Init(); /* Initialize STM3210C-EVAL's LEDs */ STM_EVAL_LEDInit(LED1); STM_EVAL_LEDInit(LED2); STM_EVAL_LEDInit(LED3); STM_EVAL_LEDInit(LED4); /* Turn on leds available on STM3210X-EVAL */ STM_EVAL_LEDOn(LED1); STM_EVAL_LEDOn(LED2); STM_EVAL_LEDOn(LED3); STM_EVAL_LEDOn(LED4); /* Clear the LCD */ LCD_Clear(Blue); /* Set the LCD Back Color */ LCD_SetBackColor(Blue); /* Set the LCD Text Color */ LCD_SetTextColor(White); /* Display message on the LCD*/ LCD_DisplayStringLine(Line0, MESSAGE1); LCD_DisplayStringLine(Line1, MESSAGE2); LCD_DisplayStringLine(Line2, MESSAGE3); LCD_DisplayStringLine(Line3, MESSAGE4); /* Configure the Ethernet peripheral */ Ethernet_Configuration(); /* SystTick configuration: an interrupt every 10ms */ RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(RCC_Clocks.SYSCLK_Frequency / 100); /* Update the SysTick IRQ priority should be higher than the Ethernet IRQ */ /* The Localtime should be updated during the Ethernet packets processing */ NVIC_SetPriority (SysTick_IRQn, 1); /* Configure the Key button */ STM_EVAL_PBInit(Button_KEY, Mode_GPIO); }
/* *@功能 主函数入口 *@参数 空 *@返回 空 */ int main(void) { /*测试变量部分*/ /*******************************************/ uint8_t t=' '; uint8_t usb_code[6]={0x55,0x7A,0xBB,0x01,0x00,0x01};//下位机反复的向上位机发送此命令,用以建立初始化连接 uint8_t p[6]={0x30,0x31,0x32,0x33,0x34,0x35}; uint8_t hanzi[11]; uint8_t *phz; uint32_t flash_data; uint8_t flash_temp[4]; uint8_t status; uint32_t addr; uint8_t nChar; // uint8_t char_buf[50]; // uint8_t count; uint32_t batt_test=0; /*********************************************/ //设置中断向量表的位置在 0x5000,即内部flash的前20K NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x5000); SystemTick_Init(); NVIC_Configuration(); //按键初始化 Init_Sw_Key_Io(); Exit_Line_Init(); EXTILine_Mask(EXTI_Line5); EXTILine_Mask(EXTI_Line8); EXTILine_Mask(EXTI_Line15); //长按开机,如果长按不够3m则继续保持关机状态,如果长按3m,则退出停机模式,开机 WKUP_Init(); EXTILine_Unmask(EXTI_Line5); EXTILine_Unmask(EXTI_Line8); EXTILine_Unmask(EXTI_Line15); //如果没有进入停机模式,则开启显示 OLED_WR_Byte(0xAF,OLED_CMD); //开启显示 longpress=0; stop_flag=0; SPI_FLASH_Init(); //正常运行后,显示logo OLED_Init(); SPI_FLASH_Init(); OLED_Clear(); OLED_DrawBMP(32,2,48,4,hui); OLED_ShowUnite(48,2,"合科技"); //delay_ms(800); USB_BIT_Init(); //为降低功耗的控制位 /****************************************/ bluetooth_control_Init(); max232_control_Init(); oled_control_Init(); OLED_ON; buzzer_control_Init(); BUZZER_OFF; coil_control_Init(); COIL_NO_ACTUATE; /****************************************/ Init_Timer(); //实时时钟初始化 RTC_init(); //初始化并启动看门狗 //iwdg_init(); //串口1 USB初始化及配置 Uart1_Init(); USART1_Configuration(); //串口2 RFID初始化及配置 Uart2_Init(); USART2_Configuration(); //串口3 bluetooth初始化及配置 Uart3_Init(); USART3_Configuration(); bluetooth_Configuration(); //蓝牙的EN和BRST配置 CLR_BT_EN; //开启蓝牙 ADC_GPIO_Configuration(); ADC_Configuration(); //flash区域指针初始化 //SPI_FLASH_WriteWord(INIT_FLAG,1); //此次下载清flash SPI_FLASH_WriteWord(INIT_FLAG,0); //此次下载不清flash if(SPI_FLASH_ReadWord(INIT_FLAG) ==0x01) //当初始化标志等于1,就初始化POINT和ROW { mykey_init(); //初始化钥匙操作的头指针 ---如何设定在什么情况下重新设置 } // OLED_ClearArea(0,4,128,6); // OLED_ShowUnite(24,4,"初始化蓝牙"); // mac_query_result=bluetooth_mac(); /*延时函数测试*/ /**********************************************/ // GPIO_Configuration(); // while(1) // { // GPIO_SetBits(GPIOB,GPIO_Pin_0); // delay_ms(1000); // GPIO_ResetBits(GPIOB,GPIO_Pin_0); // delay_ms(3000); // } /**********************************************/ /*OLED测试*/ /**********************************************/ // while(1) // { // OLED_Clear(); // OLED_ShowChinese(0,0,0); //中 // OLED_ShowChinese(18,0,1); //景 // OLED_ShowChinese(36,0,2); //园 // OLED_ShowChinese(54,0,3); //电 // OLED_ShowChinese(72,0,4); //子 // OLED_ShowChinese(90,0,5); //科 // OLED_ShowChinese(108,0,6);//技 // OLED_ShowString(0,3,"1.3' OLED TEST"); // //OLED_ShowString(8,2,"ZHONGJINGYUAN"); // //OLED_ShowString(20,4,"2014/05/01"); // OLED_ShowString(0,6,"ASCII:"); // OLED_ShowString(63,6,"CODE:"); // OLED_ShowChar(48,6,t);//显示ASCII字符 // t++; // if(t>'~') // t=' '; // OLED_ShowNum(103,6,t,3,16);//显示ASCII字符的码值 // // delay_ms(8000); // //OLED_Clear(); // // OLED_DrawBMP(0,0,128,8,BMP1); //图片显示(图片显示慎用,生成的字表较大,会占用较多空间,FLASH空间8K以下慎用) // delay_ms(800); // // //OLED_Display_On(); // //delay_ms(800); // // OLED_DrawBMP(0,0,128,8,BMP2); // delay_ms(800); // // //OLED_Display_Off(); // //delay_ms(800); // } /**********************************************/ /*OLED+字库测试*/ /**********************************************/ // phz="字库"; // hanzi[0]=*phz; // hanzi[1]=*(phz+1); // hanzi[2]=*(phz+2); // hanzi[3]=*(phz+3); // hanzi[4]=*(phz+4); // // // OLED_ShowChinese(0,0,"汉"); // OLED_ShowChinese(16,0,"字"); // // OLED_ShowUnite(0,2,"你很不错"); // OLED_ShowUnite(0,4,"ABCDEF"); // OLED_ShowUnite(0,6,"123456"); /**********************************************/ /* STM32F103C8串口有3个 串口1通过USB接充电器,与上位机PC通信 串口2通过串口读RFID的数据 串口3通过蓝牙与PDA通信 */ /*串口1 USB测试*/ /**********************************************/ // while(1) // { // UART1nSendChar(1,"12345",5); // delay_ms(1000); // } //UART1nSendChar(1,usb_code,6); //USB_Cheak_init(); //Test_Usb_Data(); // UART1SendwordHex(1, 0x123456); // UART1nSendChar(1,"汉字",5); // while(1); /**********************************************/ /*串口2 RFID测试*/ /**********************************************/ // while(1) // { // OLED_ShowUnite(32,2,"RFID"); // delay_ms(1000); // UART1nSendChar(1,"12345",5); // //OLED_Clear(); //清屏 // nChar =Read_RfidData(2,Rfid_Buff,0xff); // m_UB2; // if(nChar ==5) // { // if(Rfid_Buff[0]==0&&Rfid_Buff[1]==0&&Rfid_Buff[2]==0&&Rfid_Buff[3]==0) // ; // else //至少有一个不为零 // { // UART1nSendChar(1,Rfid_Buff,5); // OLED_ShowNumHex(32,4,Rfid_Buff[0],2,16); // OLED_ShowNumHex(48,4,Rfid_Buff[1],2,16); // OLED_ShowNumHex(64,4,Rfid_Buff[2],2,16); // OLED_ShowNumHex(80,4,Rfid_Buff[3],2,16); // delay_ms(1000); // break; // } // } // } // while(1); /**********************************************/ /*串口3 bluetooth测试*/ /**********************************************/ // CLR_BT_EN; // CLR_BT_BRTS; // // while(1) // { // UART3nSendChar(3,"012345",6); // delay_ms(1000); // } // while(1) // { // UART3nSendChar(3,"TTM:MAC-?",9); // count=UART3GetCount(3); // UART3nReadChar(3,char_buf,count); // // // // // UART1nSendChar(1,char_buf,count); // delay_ms(1000); // } /**********************************************/ /*flash测试*/ /**********************************************/ // SPI_FLASH_WriteWord(AUTHOR_ROW,0x456789); // // SPI_FLASH_BufferRead(flash_temp,AUTHOR_ROW,4); // // flash_data=SPI_FLASH_ReadWord(AUTHOR_ROW); // UART1nSendChar(1,flash_temp,4); // // OLED_ShowNum(0,6,flash_data,8,16); // // //SPI_FLASH_WriteEnable(); // status=SPI_FLASH_ReadStatusReg(); // OLED_ShowNum(112,6,status,1,16); // SPI_FLASH_BulkErase(); // SPI_FLASH_BufferWrite("98765",0x100002,6); // SPI_FLASH_BufferRead(p,0x100002,6); // SPI_FLASH_Write("98765",0x1f0005,6); // SPI_FLASH_Read(p,0x1f0005,6); // while(1) // { // UART1nSendChar(1,p,6); // delay_ms(1000); // } /**********************************************/ //菜单测试 /**********************************************/ //Main_Lcd_Show(); //主界面显示 //Main_Lcd_Show2(); // mode=1; // // OLED_ShowChar(0,0,'A'); // // OLED_ShowChinese(0,2,"我"); // // OLED_ShowUnite(0,4,"你很不错"); // // while(1); // // mode=0; // delay_ms(1000); //ShowMenu(HsMenu); // Choose_MenuOp1(); // Choose_MenuOp4(); // Choose_MenuOp4_1(); // Choose_MenuOp4_2(); // Choose_MenuOp4_22(); // Choose_MenuOp4_3(); // Choose_MenuOp4_4(); // Choose_MenuOp5(); // Choose_MenuOp5_1(); // Choose_MenuOp5_3(); // Choose_MenuOp5_4(); // while(1) // { // Main_Oled_Time(); // Main_Oled_Power(); // delay_ms(1000); // } // while(1); /**********************************************/ //蜂鸣器测试 /**********************************************/ // while(1) // { // BUZZER_OFF; // delay_ms(1000); // // BUZZER_ON; // delay_ms(1500); // } /**********************************************/ //协议测试 /**********************************************/ //OLED_Clear(); // OLED_ShowUnite(32,2,"通信中.."); // OLED_ShowUnite(0,4,"你很不错"); // delay_ms(1000); // addr=0xFFFF; // OLED_ShowNumHex(0,6,addr,8,16); //USB_Cheak_init(); //USB_transmit(); // bluetooth_uart_switch=1; // Test_Usb_Data(); // while(1); // SPI_FLASH_WriteWord(AUTHOR_POINT,AUTHOR_START); // addr= SPI_FLASH_ReadWord(AUTHOR_POINT); // OLED_ShowNum(0,0,addr,8,16); /**********************************************/ //ADC测试 /**********************************************/ // while(1) // { // OLED_Clear(); // batt_test=ADC_GetConversionValue(ADC1); // OLED_ShowNum(24,2,batt_test,8,16); // delay_ms(1000); // } // /**********************************************/ //定时器2测试 /**********************************************/ // GPIO_Configuration(); // GPIO_ResetBits(GPIOB,GPIO_Pin_6); // delay_ms(10); // GPIO_SetBits(GPIOB,GPIO_Pin_6); // g_WaitTimeOut = 0; // SetTimer(TIMER_TIMEOUT,1,Do_TimeOut,THREE_MIN); // while(g_WaitTimeOut == 0) // { // GPIO_ResetBits(GPIOB,GPIO_Pin_6); // } // KillTimer(TIMER_TIMEOUT); // GPIO_SetBits(GPIOB,GPIO_Pin_6); // g_WaitTimeOut = 0; // SetTimer(TIMER_TIMEOUT,10,Do_TimeOut,THREE_MIN); // while(g_WaitTimeOut == 0) // { // nChar =Read_RfidData(2,Rfid_Buff,0xff); // if(nChar ==5) // { // OLED_ShowUnite(32,80,Rfid_Buff); // ++rfidrow; // delay_ms(1000); // for(i=0;i<4;i++) // { // for(k =0;k<40;k++) // msDelay(500); // WritEDAta(CAIMA_START+8*rfidrow+4+i,Rfid_Buff[i]); // } // break; // } // } // KillTimer(TIMER_TIMEOUT); /**********************************************/ // OLED_ClearArea(0,4,128,6); // OLED_ShowUnite(24,4,"初始化完成"); // delay_ms(100); //bluetooth_uart_switch=0; // for(int iter=0;iter<3;iter++) // Power_Cheak(); //主循环测试 g_State=ST_IDLE; while(1) { switch (g_State) //g_State是一个全局函数 { case ST_IDLE: //#define ST_IDLE 0XFF ST_Idle(); //空闲时做状态检测,可改变g_State break; case ST_USB: //#define ST_USB 0XFD USB_transmit(); //USB传输 break; // case ST_KEY: // Key_Trismit(); //读钥匙的RFID,判断是否已经连接上 // break; case ST_LCDMENU: //#define ST_LCDMENU 0XFA 多选择菜单操作 Choose_MenuOp1(); break; default:break; } } }
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) { 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
/** * @brief Main program * @param None * @retval None */ 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_stm32f10x_xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f10x.c file */ uint32_t delay; uint8_t sendFlag_Ai = 0; SOE_Struct soe; uint32_t start = 0; /* System clocks configuration ---------------------------------------------*/ SystemInit(); RCC_ClocksTypeDef clock; RCC_GetClocksFreq(&clock); RCC_Configuration(); GPIO_Configuration(); ADC_Configuration(); COM3_Configuration(9600); DMA_Configuration(); TIM_UART_Config(); //uart3-rx FREQ_MEA_Init(); //freq采样 TIM2_Configuration(); //adc采样 SysTick_Configuration(); //DI采样 RTC_Init(); NVIC_Configuration(); DataBase_Init(); //memset(DiStatus_DI, 0, sizeof(DiStatus_Type)*DI_NUM); //初始化DI内存列表 GetComAddr(); SetCurrent.ChannelCoef[0] =1050;//1#:1029;2#:1028 SetCurrent.ChannelCoef[1] =1029;//1#:1029;2#:1027 SetCurrent.ChannelCoef[2] =1050;//1#:1030;2#:1028 SetCurrent.ChannelCoef[3] =1028;//1#:1033;2#:1028 SetCurrent.ChannelCoef[4] =1029;//1#:1033;2#:1029 SetCurrent.ChannelCoef[5] =1028;//1#:1033;2#:1028 SetCurrent.ChannelCoef[6] =1025;//1#:1029;2#:1028 SetCurrent.ChannelCoef[7] =1026;//1#:1029;2#:1027 SetCurrent.ChannelCoef[8] =1027;//1#:1030;2#:1028 #ifdef WATCHDOG IWDG_Configuration(); #endif DMA_Cmd(DMA1_Channel3, ENABLE); // Emable TIM3, 使能串口接收通道 TIM_Cmd(TIM3, ENABLE); //UART3接收,使能 while (1) { Di_PostWork(); if(63==PeriodCycle_Index) { TOTAL_MEASURE(&meas); SequenceFilter_2(&meas); SequenceFilter_0(&meas); ValueScaling(MeaTab,&meas); //tyh:20150629 添加遥测数据上送 if(Begin_AI_Send) { if(Is_new_soe()) { get_soe(&soe, 1); SoeResponse(soe); } else { if((sendFlag_Ai%3)==0) AiResponse(0); else { if((sendFlag_Ai%5)==0) //tyh:20150803 增加遥信数据上送 DiResponse(0); } sendFlag_Ai++; } } } if(Flag_Uart_Recv) BusCalling_Process(Flag_Uart_Recv); //处理数据 #ifdef WATCHDOG WDGFeeding(); #endif } }
void System_Configuration(void) { __disable_interrupt(); /* System Clocks Configuration */ RCC_Configuration(); /* NVIC configuration */ NVIC_Configuration(); /* Configure the GPIO ports */ GPIO_Configuration(); /* Unlock the Flash Program Erase controller */ FLASH_Unlock(); /* USART Configuration */ USART_Configuration(USART_DXL,Baudrate_DXL); //dxl_initialize(USART_DXL,Baudrate_DXL); zgb_initialize(0); //USART_Configuration(USART_ZIGBEE,Baudrate_ZIGBEE); //USART_Configuration(USART_PC,1000000); //USART_Configuration(USART_PC,3000000); USART_Configuration(USART_PC,Baudrate_PC); /* ADC Configuration */ ADC_Configuration(); SysTick_Configuration(); Timer_Configuration(); SPI_Configuration(); Buzzer_Configuration(); GPIO_ResetBits(PORT_ENABLE_TXD, PIN_ENABLE_TXD); // TX Disable GPIO_SetBits(PORT_ENABLE_RXD, PIN_ENABLE_RXD); // RX Enable GPIO_SetBits(PORT_SIG_ACC_CS,PIN_SIG_ACC_CS); GPIO_SetBits(PORT_SIG_GYRO_CS,PIN_SIG_GYRO_CS); __enable_interrupt(); Gyro_Configuration(); ACC_Configuration(); }
/** * @brief Configures the ADC. * @param None * @retval None */ static void ADC_Configuration(void) { MappingGpio_s PinConfig; // Lecture de la configuration de la pin PinConfig = GPIO_GetPinConfiguration(PORT_TRIM); // Execution de la fonction ADC1_ChannelConf_t ADC_Channel = { .ADCx = (ADC_TypeDef*) PinConfig.PERIPH, .ADC_Channel = PinConfig.PARAM, .pStoreValue_mV = NULL, .pFct_CallbackEOC = NULL, }; ADC_IdChannel = ADC1_ChannelConfigure(ADC_Channel); ADC1_ConversionContinue_Activer(ADC_IdChannel); } /** * @brief ADC_Handler : SSI handler for ADC page */ u16_t ADC_Handler(int iIndex, char *pcInsert, int iInsertLen) { /* We have only one SSI handler iIndex = 0 */ if (iIndex == 0) { char Digit1 = 0, Digit2 = 0, Digit3 = 0, Digit4 = 0; uint32_t ADCVal = 0; /* configure ADC if not yet configured */ if (ADC_not_configured == 1) { ADC_Configuration(); ADC_not_configured = 0; } /* get ADC conversion value */ ADCVal = ADC1_Get_mV(ADC_IdChannel); /* get digits to display */ Digit1 = ADCVal / 1000; Digit2 = (ADCVal - (Digit1 * 1000)) / 100; Digit3 = (ADCVal - ((Digit1 * 1000) + (Digit2 * 100))) / 10; Digit4 = ADCVal - ((Digit1 * 1000) + (Digit2 * 100) + (Digit3 * 10)); /* prepare data to be inserted in html */ *pcInsert = (char) (Digit1 + 0x30); *(pcInsert + 1) = (char) (Digit2 + 0x30); *(pcInsert + 2) = (char) (Digit3 + 0x30); *(pcInsert + 3) = (char) (Digit4 + 0x30); /* 4 characters need to be inserted in html*/ return 4; } return 0; } /** * @brief CGI handler for LEDs control */ const char * LEDS_CGI_Handler(int iIndex, int iNumParams, char *pcParam[], char *pcValue[]) { uint32_t i = 0; if (iIndex == 0) { /* All leds off */ GPIO_Set(PORT_STAT1, Etat_INACTIF); GPIO_Set(PORT_STAT2, Etat_INACTIF); GPIO_Set(PORT_STAT4, Etat_INACTIF); /* Check cgi parameter : example GET /leds.cgi?led=2&led=4 */ for (i = 0; i < iNumParams; i++) { /* check parameter "led" */ if (strcmp(pcParam[i], "led") == 0) { /* switch led1 ON if 1 */ if (strcmp(pcValue[i], "1") == 0) GPIO_Set(PORT_STAT1, Etat_ACTIF); /* switch led2 ON if 2 */ else if (strcmp(pcValue[i], "2") == 0) GPIO_Set(PORT_STAT2, Etat_ACTIF); /* switch led3 ON if 3 */ else if (strcmp(pcValue[i], "3") == 0) __NOP(); /* switch led4 ON if 4 */ else if (strcmp(pcValue[i], "4") == 0) GPIO_Set(PORT_STAT4, Etat_ACTIF); } } } /* uri to send after cgi call*/ return "/index.shtml"; }
/** ******************************************************************************* * @brief Initialization task * @param[in] pdata A pointer to parameter passed to task. * @param[out] None * @retval None * * @details This task is called to initial hardware and created tasks. ******************************************************************************* */ void task_init(void *pdata) { uart_printf (" [OK]. \n\r\n\r"); uart_printf ("\r \"task_init\" task enter. \n\r\n\r "); pdata = pdata; /* Initiate Time buffer for LCD display */ chart[0] = time[2]/10 + '0'; chart[1] = time[2]%10 + '0'; chart[3] = time[1]/10 + '0'; chart[4] = time[1]%10 + '0'; chart[6] = time[0]/10 + '0'; chart[7] = time[0]%10 + '0'; uart_printf ("\r Create the \"mut_uart\" mutex... "); mut_uart = CoCreateMutex(); if(mut_uart != E_CREATE_FAIL) uart_printf (" [OK]. \n"); else uart_printf (" [Fail]. \n"); uart_printf ("\r Create the \"mut_lcd\" mutex... "); mut_lcd = CoCreateMutex(); if(mut_lcd != E_CREATE_FAIL) uart_printf (" [OK]. \n"); else uart_printf (" [Fail]. \n"); uart_printf ("\r Create the \"button_sel_flg\" flag... "); /*!< Manual reset flag,initial state:0 */ button_sel_flg = CoCreateFlag(Co_FALSE,0); if(button_sel_flg != E_CREATE_FAIL) uart_printf (" [OK]. \n"); else uart_printf (" [Fail]. \n"); uart_printf ("\r Create the \"button_add_flag\" flag..."); /*!< Manual reset flag,initial state:0 */ button_add_flg = CoCreateFlag(Co_FALSE,0); if(button_add_flg != E_CREATE_FAIL) uart_printf (" [OK]. \n\n"); else uart_printf (" [Fail]. \n\n"); uart_printf ("\r Create the \"lcd_blink_flg\" flag... "); lcd_blink_flg = CoCreateFlag(Co_FALSE,0); /*!< Manual reset flag,initial state:0 */ if(lcd_blink_flg != E_CREATE_FAIL) uart_printf (" [OK]. \n"); else uart_printf (" [Fail]. \n"); uart_printf ("\r Create the \"time_display_flg\" flag..."); /*!< Manual reset flag,initial state:0 */ time_display_flg = CoCreateFlag(Co_FALSE,0); if(time_display_flg != E_CREATE_FAIL) uart_printf (" [OK]. \n"); else uart_printf (" [Fail]. \n"); /*!< Set flag to allow "time_display_flg" task run. */ CoSetFlag(time_display_flg); uart_printf ("\r Create the first mailbox... "); mbox0 = CoCreateMbox(EVENT_SORT_TYPE_FIFO); if(mbox0 == E_CREATE_FAIL) uart_printf (" [Fail]. \n\n"); else uart_printf (" [OK]. \n\n"); /* Configure Peripheral */ uart_printf ("\r Initial hardware in Board : \n\r"); uart_printf ("\r ADC initial... "); ADC_Configuration (); uart_printf (" [OK]. \n"); uart_printf ("\r RTC initial... "); RTC_Configuration (); uart_printf (" [OK]. \n"); uart_printf ("\r GPIO initial... "); GPIO_Configuration (); uart_printf (" [OK]. \n"); uart_printf ("\r External interrupt initial... "); EXIT_Configuration (); uart_printf (" [OK]. \n"); uart_printf ("\r LCD initial... "); LCD_Configuration (); uart_printf (" [OK]. \n\n"); /* Create Tasks */ CoCreateTask( lcd_display_adc, (void *)0 , LCD_DISPLAY_PRI , &lcd_display_adc_Stk[TASK_STK_SIZE-1] , TASK_STK_SIZE ); CoCreateTask( uart_print , (void *)0 , UART_PRINT_PRI , &uart_print_Stk[TASK_STK_SIZE-1], TASK_STK_SIZE ); CoCreateTask( led_blink , (void *)0 , LCD_BLINK_PRI , &led_display_Stk[TASK_STK_SIZE-1], TASK_STK_SIZE ); time_display_id = CoCreateTask( time_display, (void *)0, TIME_DISRPLAY_PRI, &time_display_Stk[TASK_STK_SIZE - 1], TASK_STK_SIZE ); CoCreateTask( time_set , (void *)0 , TIME_SET_PRI , &time_set_Stk[TASK_STK_SIZE-1], TASK_STK_SIZE ); CoExitTask(); /*!< Delete 'task_init' task. */ }