uint8_t writeEEPROM(void) { FLASH_Status status; int32_t i; /////////////////////////////////// if (eepromConfig.receiverType == SPEKTRUM) { USART_Cmd(USART6, DISABLE); TIM_Cmd(TIM6, DISABLE); if (eepromConfig.slaveSpektrum == true) USART_Cmd(UART4, DISABLE); } /////////////////////////////////// eepromConfig_t *src = &eepromConfig; uint32_t *dst = (uint32_t*)FLASH_WRITE_EEPROM_ADDR; if ( src->CRCFlags & CRC_HistoryBad ) evrPush(EVR_ConfigBadHistory,0); src->CRCAtEnd = crc32B((uint32_t*)(&eepromConfig), // CRC32B[eepromConfig] (uint32_t*)(&eepromConfig.CRCAtEnd)); /////////////////////////////////// FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); status = FLASH_EraseSector(FLASH_Sector_1, VoltageRange_3); /////////////////////////////////// i = -1; while (FLASH_COMPLETE == status && i++ < eepromConfigSizeUint32) status = FLASH_ProgramWord((uint32_t)&dst[i], ((uint32_t*)src)[i]); if ( FLASH_COMPLETE != status ) evrPush( -1 == i ? EVR_FlashEraseFail : EVR_FlashProgramFail, status); /////////////////////////////////// FLASH_Lock(); readEEPROM(); /////////////////////////////////// if (eepromConfig.receiverType == SPEKTRUM) { primarySpektrumState.reSync = 1; TIM_Cmd(TIM6, ENABLE); USART_Cmd(USART6, ENABLE); if (eepromConfig.slaveSpektrum == true) { slaveSpektrumState.reSync = 1; USART_Cmd(UART4, ENABLE); } } /////////////////////////////////// return status; }
void Board_main(void) { uint8_t i; uint16_t flash_flag = 0; uint16_t copy_file_flag = 0; /* RCC system reset(for debug purpose) */ RCC_DeInit(); /* Enable HSE */ RCC_HSEConfig(RCC_HSE_ON); /* Wait till HSE is ready */ HSEStartUpStatus = RCC_WaitForHSEStartUp(); if(HSEStartUpStatus == SUCCESS) { #if 0 /* Enable Prefetch Buffer */ FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable); FLASH_HalfCycleAccessCmd(FLASH_HalfCycleAccess_Disable); /* Flash 2 wait state */ FLASH_SetLatency(FLASH_Latency_2); #else FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable); FLASH_HalfCycleAccessCmd(FLASH_HalfCycleAccess_Enable); /* Flash 2 wait state */ /*FLASH_SetLatency(FLASH_Latency_2);*/ FLASH_SetLatency(FLASH_Latency_0); /*abin@ */ #endif /* HCLK = SYSCLK */ RCC_HCLKConfig(RCC_SYSCLK_Div1); /* PCLK2 = HCLK */ RCC_PCLK2Config(RCC_HCLK_Div1); /* PCLK1 = HCLK/2 */ RCC_PCLK1Config(RCC_HCLK_Div2); #if 0 /* PLLCLK = 8MHz * 9 = 72 MHz */ /*abin:note*/ RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9); // RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_8); /* Enable PLL */ RCC_PLLCmd(ENABLE); /* Wait till PLL is ready */ while(RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) { } /* Select PLL as system clock source */ RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); /* Wait till PLL is used as system clock source */ while(RCC_GetSYSCLKSource() != 0x08) { } #else RCC_PLLCmd(DISABLE); /* Select HSE as system clock source */ RCC_SYSCLKConfig(RCC_SYSCLKSource_HSE); /* Wait till PLL is used as system clock source */ while(RCC_GetSYSCLKSource() != 0x04) { } #endif } /* Enable GPIOA, GPIOB, and AFIO clocks */ RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA |RCC_APB2Periph_GPIOB| RCC_APB2Periph_AFIO, ENABLE); /* Enable DMA1 ,DMA2 clock */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1|RCC_AHBPeriph_DMA2, ENABLE); /* Enable ADC1 ADC2,and GPIOC clock */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1 |RCC_APB2Periph_ADC2| RCC_APB2Periph_GPIOC, ENABLE); /* Enable PWR and BKP clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); /* Enable write access to Backup domain */ PWR_BackupAccessCmd(ENABLE); /* Clear Tamper pin Event(TE) pending flag */ BKP_ClearFlag(); #if ABIN_DEBUG USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; STM_EVAL_COMInit(COM1, &USART_InitStructure); /* Output a message on Hyperterminal using printf function */ //sys_printf("\n\r abin 8M is ok moify flash latency :USART Init end \n\r"); #endif /*------------------- Resources Initialization -----------------------------*/ /* GPIO Configuration */ GPIO_Config(); //sys_printf("\n\r abin mul2 :GPIO_Config \n\r"); #if ABIN_CPU_UPGRADE2HIGHSPEED_OPTION USB_Plugin_State = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14); if(USB_Plugin_State == 1) { //sys_printf("\n\r abin switch to high speed !!\n\r"); UpgradeToHighSpeed(); } #endif /* Interrupt Configuration */ InterruptConfig(); /* Configure the systick */ SysTick_Configuration(); /*------------------- Drivers Initialization -------------------------------*/ /* Initialize the Low Power application */ LowPower_Init(); /* Enable WKUP pin */ PWR_WakeUpPinCmd(ENABLE); /* Allow access to BKP Domain */ PWR_BackupAccessCmd(ENABLE); RTC_Init(); /* If HSE is not detected at program startup */ if(HSEStartUpStatus == ERROR) { /* Generate NMI exception */ SCB->ICSR |= SCB_ICSR_NMIPENDSET; } USB_Disconnect_Config(); GPIO_SetBits(USB_DISCONNECT, USB_DISCONNECT_PIN);/*???abin@20100714*/ WakupPin_Init(); //sys_printf("\n\r abin before CheckPowerOnReason\n\r"); CheckPowerOnReason(); //sys_printf("\n\r abin after CheckPowerOnReason\n\r"); Board_ADC_Init(); /*init the flag*/ flash_flag = *(uint16_t *)FLASH_READY_ADDRESS; if( flash_flag != FLAG_FLASH_READY) { //sys_printf("\n\r abin ready to erase flash \n\r"); FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); //Erase the 32 page 32K for(i = 0;i< DATA_PAGES;i++) { //sys_printf("\n\r abin ready to erase aa"); FLASH_ErasePage(DATA_LOGGER_ADDRESS_START + i * 1024);/*数据在Page1...page32存放*/ } FLASH_ErasePage(FLASH_READY_ADDRESS); /*abin@20100715 没添加保护*/ FLASH_ProgramHalfWord(FLASH_READY_ADDRESS , FLAG_FLASH_READY); FLASH_ErasePage(REOCRD_COUNT_ADDRESS); FLASH_ProgramHalfWord(REOCRD_COUNT_ADDRESS , 0x0000); FLASH_Lock(); //sys_printf("\n\r abin mul2 :erase flash end!!!\n\r"); } //sys_printf("\n\r abin ready to erase flash end \n\r"); USB_Plugin_State = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14); if(USB_Plugin_State == 0) { record_count = *(uint16_t *)REOCRD_COUNT_ADDRESS; if(record_count >= 15428) { //Write the full flag //Do nothing.... while(1) { //sys_printf("\n\r sample end !!!!!!!!!!!!!!!!!!!!!\n\r"); Led_One_By_One(4); /*应该进入standy 模式 abin@20100715*/ } } else { //sys_printf("\n\r abin ready to add sample count \n\r"); FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); FLASH_ProgramHalfWord(DATA_LOGGER_ADDRESS_START + record_count * 2, GetTemperature()); //Erase first FLASH_ErasePage(REOCRD_COUNT_ADDRESS); //Update the count record_count = record_count + 1; FLASH_ProgramHalfWord(REOCRD_COUNT_ADDRESS , record_count); FLASH_Lock(); //sys_printf("\n\r abin add sample count :end\n\r"); } //sys_printf("\n\r %000\n\r"); GPIO_SetBits(GPIOA, GPIO_Pin_1); #if 0 Delay(25); #else Delay(5); #endif //sys_printf("\n\r %111\n\r"); } else { Enable_SDcard(); /* if there is usb connect, copy the data to sdcard. and start the mass storage */ copy_file_flag = *(uint16_t *)COPY_FILE_ADDRESS; if(copy_file_flag == FLAG_FILE_COPYED) { Write_Copy_File_Flag(FLAG_FILE_NO_COPYED); USB_Disconnect_Config(); GPIO_SetBits(USB_DISCONNECT, USB_DISCONNECT_PIN); Delay(10); GPIO_ResetBits(USB_DISCONNECT, USB_DISCONNECT_PIN); /* Enable and GPIOD clock */ Mass_Storage_Start (); while( bDeviceState != CONFIGURED) { Led_Both(1); } USB_Plugin_State = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14); while( USB_Plugin_State == 1)/* U-DISK success ,then CPU Loop in here*/ { USB_Plugin_State = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14); Led_One_By_One(1); //sys_printf("\n\r abin :mul2 u disk !!!\n\r"); } PowerOff(); Write_Copy_File_Flag(FLAG_FILE_NO_COPYED); } else { Write_Copy_File_Flag(FLAG_FILE_COPYED); Led_Green_Flink(3); NAND_FAT(); CreateDataLoggerFile(); Write_Copy_File_Flag(FLAG_FILE_COPYED); //sys_printf("\n\r abin :mul2 NAND_FAT!!!\n\r"); } //sys_printf("\n\r abin :mul2 Disable_SDcard!!!\n\r"); Disable_SDcard(); BKP_WriteBackupRegister(BKP_POWER_ON, FLAG_POWER_OFF); PWR_EnterSTANDBYMode(); /* Generate a system reset */ //NVIC_SystemReset(); } //sys_printf("\n\r @111 \n\r"); /* Set the RTC Alarm after 60s */ RTC_SetAlarm(RTC_GetCounter()+ 3); //sys_printf("\n\r @222:RTC_GetCounter()=0x%x \n\r",RTC_GetCounter()); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); //sys_printf("\n\r @333\n\r"); PWR_EnterSTANDBYMode(); }
/** * @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_stm32f4xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f4xx.c file */ /* Unlock the Flash to enable the flash control register access *************/ FLASH_Unlock(); /* Erase the user Flash area (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); /* Get the number of the start and end sectors */ StartSector = GetSector(FLASH_USER_START_ADDR); EndSector = GetSector(FLASH_USER_END_ADDR); for (i = StartSector; i < EndSector; i += 8) { /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */ if (FLASH_EraseSector(i, VoltageRange_3) != FLASH_COMPLETE) { /* Error occurred while sector erase. User can add here some code to deal with this error */ while (1) { } } } /* Program the user Flash area word by word (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ Address = FLASH_USER_START_ADDR; while (Address < FLASH_USER_END_ADDR) { if (FLASH_ProgramWord(Address, DATA_32) == FLASH_COMPLETE) { Address = Address + 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { } } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ FLASH_Lock(); /* Check if the programmed data is OK MemoryProgramStatus = 0: data programmed correctly MemoryProgramStatus != 0: number of words not programmed correctly ******/ Address = FLASH_USER_START_ADDR; MemoryProgramStatus = 0x0; while (Address < FLASH_USER_END_ADDR) { data32 = *(__IO uint32_t*)Address; if (data32 != DATA_32) { MemoryProgramStatus++; } Address = Address + 4; } while (1) { } }
u8 PWS_WriteSlot (u8 Slot_u8, typePasswordSafeSlot_st * Slot_st) { u8* WritePointer_pu8; u8* AesKeyPointer_pu8; void* p; CI_LocalPrintf ("PWS_WriteSlot: Slot %d. Name -%s- Loginname -%s- PW -%s-\r\n", Slot_u8, Slot_st->SlotName_au8, Slot_st->SlotLoginName_au8, Slot_st->SlotPassword_au8); if (PWS_SLOT_COUNT <= Slot_u8) { CI_LocalPrintf ("PWS_WriteSlot: Wrong slot nr %d\r\n", Slot_u8); return (FALSE); } if (FALSE == PWS_GetDecryptedPasswordSafeKey (&AesKeyPointer_pu8)) { CI_LocalPrintf ("PWS_WriteSlot: Key not decrypted\r\n"); return (FALSE); } // LED_GreenOn (); // Activate data in slot Slot_st->SlotActiv_u8 = PWS_SLOT_ACTIV_TOKEN; #ifdef ENABLE_IBN_PWS_TESTS_ENCRYPTION CI_LocalPrintf ("PWS_WriteSlot decrypted : "); HexPrint (PWS_SLOT_LENGTH, &Slot_st); CI_LocalPrintf ("\n\r"); #endif // Encrypt data (max 256 byte per encryption) unsigned char Slot_st_encrypted[PWS_SLOT_LENGTH]; aes_context aes_ctx; aes_setkey_enc (&aes_ctx, AesKeyPointer_pu8, 256); int i; for (i = 0; i < PWS_SLOT_LENGTH; i += 16) { aes_crypt_ecb (&aes_ctx, AES_ENCRYPT, &(((unsigned char *) (Slot_st))[i]), &(Slot_st_encrypted[i])); } memcpy (Slot_st, Slot_st_encrypted, PWS_SLOT_LENGTH); #ifdef ENABLE_IBN_PWS_TESTS_ENCRYPTION CI_LocalPrintf ("PWS_WriteSlot encrypted : "); HexPrint (PWS_SLOT_LENGTH, Slot_st_encrypted); CI_LocalPrintf ("\n\r"); #endif // Get write address WritePointer_pu8 = (u8 *) (PWS_FLASH_START_ADDRESS + (PWS_SLOT_LENGTH * Slot_u8)); // Write to flash uint8_t page_buffer[FLASH_PAGE_SIZE]; uint8_t* page = (uint8_t *) PWS_FLASH_START_ADDRESS; memcpy (page_buffer, page, FLASH_PAGE_SIZE); memcpy (page_buffer + (PWS_SLOT_LENGTH * Slot_u8), Slot_st_encrypted, PWS_SLOT_LENGTH); p = (void *) Slot_st_encrypted; FLASH_Unlock (); FLASH_ErasePage (PWS_FLASH_START_ADDRESS); write_data_to_flash (page_buffer, FLASH_PAGE_SIZE, PWS_FLASH_START_ADDRESS); FLASH_Lock (); // LED_GreenOff (); return (TRUE); }
OSStatus internalFlashFinalize( void ) { FLASH_Lock(); return kNoErr; }
/** * @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 files (startup_stm32f40xx.s/startup_stm32f427x.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f4xx.c file */ /* Initialize LEDs on EVAL board ********************************************/ STM_EVAL_LEDInit(LED1); STM_EVAL_LEDInit(LED2); /* Unlock the Flash *********************************************************/ /* Enable the flash control register access */ FLASH_Unlock(); /* Erase the user Flash area ************************************************/ /* area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */ /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); /* Get the number of the start and end sectors */ uwStartSector = GetSector(FLASH_USER_START_ADDR); uwEndSector = GetSector(FLASH_USER_END_ADDR); /* Strat the erase operation */ uwSectorCounter = uwStartSector; while (uwSectorCounter <= uwEndSector) { /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */ if (FLASH_EraseSector(uwSectorCounter, VoltageRange_3) != FLASH_COMPLETE) { /* Error occurred while sector erase. User can add here some code to deal with this error */ while (1) { } } /* jump to the next sector */ if (uwSectorCounter == FLASH_Sector_11) { uwSectorCounter += 40; } else { uwSectorCounter += 8; } } /* Program the user Flash area word by word ********************************/ /* area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */ uwAddress = FLASH_USER_START_ADDR; while (uwAddress < FLASH_USER_END_ADDR) { if (FLASH_ProgramWord(uwAddress, DATA_32) == FLASH_COMPLETE) { uwAddress = uwAddress + 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { } } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) */ FLASH_Lock(); /* Check if the programmed data is OK ***************************************/ /* MemoryProgramStatus = 0: data programmed correctly MemoryProgramStatus != 0: number of words not programmed correctly */ uwAddress = FLASH_USER_START_ADDR; uwMemoryProgramStatus = 0; while (uwAddress < FLASH_USER_END_ADDR) { uwData32 = *(__IO uint32_t*)uwAddress; if (uwData32 != DATA_32) { uwMemoryProgramStatus++; } uwAddress = uwAddress + 4; } /* Check Data correctness */ if(uwMemoryProgramStatus) { /* KO */ /* Turn on LD2 */ STM_EVAL_LEDOn(LED2); } else { /* OK */ /* Turn on LD1 */ STM_EVAL_LEDOn(LED1); } while (1) { } }
//unsigned char sys_flash_write_operate(u32 Address,u16 * buff,u32 len) unsigned char sys_flash_write_operate(u32 Address,u8 * buff,u32 len) { u32 bBeginPage,bEndPage; unsigned char sPageBuf[2048]; u32 nCurAddress,nCurLen,nSize,i,nOffset; //test unsigned char j; int bRet; //if( Address<SysStartAddr || Address+len>SysEndAddr ) if( (Address+len+SysStartAddr)>SysEndAddr ) return ADDRESS_LEN_ERR; bBeginPage = (Address+SysStartAddr)/FLASH_PAGE_SIZE; //if( (Address+SysStartAddr)%FLASH_PAGE_SIZE) // bBeginPage++; bEndPage = (Address+SysStartAddr+len)/FLASH_PAGE_SIZE; if( (Address+SysStartAddr+len)%FLASH_PAGE_SIZE) bEndPage++; nCurAddress = Address+SysStartAddr; nCurLen = len; nOffset = 0; bRet = 0; //13/06/24 FLASH_Unlock(); for(i=bBeginPage;i<bEndPage;i++) { bRet = flash_read_operate(i*FLASH_PAGE_SIZE,sPageBuf,FLASH_PAGE_SIZE); bRet = CrcPageCmp(i-SysStartAddr/FLASH_PAGE_SIZE,sPageBuf); //test trace_debug_printf("CrcPageCmp[%d]\n",bRet); bRet = flash_erase_page(i); //13/07/09 if( (i<(SysStartAddr/FLASH_PAGE_SIZE +4)) && //save key page memcmp(buff,"\x0\x0\x0\x0\x0\x0\x0\x0",8)!=0) //key data bRet = flash_erase_page(i+PCI_BACK_ADDR/FLASH_PAGE_SIZE); //liantest 13/05/31 if(bRet) trace_debug_printf("flash_erase_page[%d]", bRet); //nSize = nCurLen%FLASH_PAGE_SIZE; nSize =FLASH_PAGE_SIZE- ((nCurAddress-SysStartAddr)%FLASH_PAGE_SIZE); if(nSize>nCurLen) nSize =nCurLen; memcpy(&sPageBuf[nCurAddress%FLASH_PAGE_SIZE],(unsigned char *)&buff[nOffset],nSize); j = 0; bRet = CrcPageCalc(i-SysStartAddr/FLASH_PAGE_SIZE,sPageBuf); //test trace_debug_printf("CrcPageCalc[%d]\n",bRet); WRITE: bRet = flash_write_operate(i*FLASH_PAGE_SIZE,(unsigned short *)sPageBuf,FLASH_PAGE_SIZE); //13/07/09 if( (i<(SysStartAddr/FLASH_PAGE_SIZE +4)) &&//save key page memcmp(buff,"\x0\x0\x0\x0\x0\x0\x0\x0",8)!=0) //key data bRet = flash_write_operate(i*FLASH_PAGE_SIZE+PCI_BACK_ADDR,(unsigned short *)sPageBuf,FLASH_PAGE_SIZE); //liantest 13/05/31 if(bRet) { trace_debug_printf("number[%d] flash_write_operate[%d]", j,bRet); delay_ms(50); if(j++<4) goto WRITE; } //13/07/01 bRet = flash_read_operate(i*FLASH_PAGE_SIZE,sPageBuf,FLASH_PAGE_SIZE); bRet = CrcPageCmp(i-SysStartAddr/FLASH_PAGE_SIZE,sPageBuf); //test trace_debug_printf("CrcPageCmp[%d]\n",bRet); //test //bRet = flash_read_operate(i*FLASH_PAGE_SIZE,sPageBuf,FLASH_PAGE_SIZE); nCurLen -= nSize; nCurAddress += nSize; nOffset +=nSize; } //13/06/24 FLASH_Lock(); return bRet;//13/05/31 }
void writeEEPROM(void) { // Generate compile time error if the config does not fit in the reserved area of flash. BUILD_BUG_ON(sizeof(master_t) > FLASH_TO_RESERVE_FOR_CONFIG); FLASH_Status status = 0; uint32_t wordOffset; int8_t attemptsRemaining = 3; suspendRxSignal(); // prepare checksum/version constants masterConfig.version = EEPROM_CONF_VERSION; masterConfig.size = sizeof(master_t); masterConfig.magic_be = 0xBE; masterConfig.magic_ef = 0xEF; masterConfig.chk = 0; // erase checksum before recalculating masterConfig.chk = calculateChecksum((const uint8_t *) &masterConfig, sizeof(master_t)); // write it FLASH_Unlock(); while (attemptsRemaining--) { #ifdef STM32F40_41xxx FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); #endif #ifdef STM32F303 FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); #endif #ifdef STM32F10X FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); #endif for (wordOffset = 0; wordOffset < sizeof(master_t); wordOffset += 4) { if (wordOffset % FLASH_PAGE_SIZE == 0) { #if defined(STM32F40_41xxx) status = FLASH_EraseSector(FLASH_Sector_8, VoltageRange_3); //0x08080000 to 0x080A0000 #elif defined (STM32F411xE) status = FLASH_EraseSector(FLASH_Sector_7, VoltageRange_3); //0x08060000 to 0x08080000 #else status = FLASH_ErasePage(CONFIG_START_FLASH_ADDRESS + wordOffset); #endif if (status != FLASH_COMPLETE) { break; } } status = FLASH_ProgramWord(CONFIG_START_FLASH_ADDRESS + wordOffset, *(uint32_t *) ((char *) &masterConfig + wordOffset)); if (status != FLASH_COMPLETE) { break; } } if (status == FLASH_COMPLETE) { break; } } FLASH_Lock(); // Flash write failed - just die now if (status != FLASH_COMPLETE || !isEEPROMContentValid()) { failureMode(FAILURE_FLASH_WRITE_FAILED); } resumeRxSignal(); }
void main(void) { /*----------IO口设置----------*/ GPIO_Init(ADDR_LOW_PORT, GPIO_Pin_All, GPIO_Mode_Out_PP_Low_Slow); //8位地址 GPIO_Init(ADDR_HIGH_PORT0, ADDR_HIGH_PIN0, GPIO_Mode_Out_PP_Low_Slow); //未使用口设置为输出低电平 //P1.3/mode0 - 模块输入睡眠,stm8输出睡眠 GPIO_Init( MODE0_PORT, MODE0_PIN, GPIO_Mode_Out_PP_Low_Slow); //P1.5/mode1 - 模块输出睡眠,stm8输入睡眠 //Zigbee透传模块输出给stm8的唤醒信号为高电平,并在10ms后开始发送串口信号 //由于stm8输入无内部下拉选项,因此只能设置为浮动输入 //当不接Zigbee模块单独进行stm8程序调试时,浮动输入将可能导致持续发生中断,所以请务必接入Zigbee模块或在不接入模块时改为输入上拉 GPIO_Init( MODE1_PORT, MODE1_PIN, GPIO_Mode_In_FL_IT); EXTI_SetPinSensitivity(EXTI_Pin_3, EXTI_Trigger_Rising); GPIO_Init(SENSOR_DATA_PORT, SENSOR_DATA_PIN, GPIO_Mode_Out_PP_High_Fast); //传感器数据口拉高 //等效为如下配置 //SENSOR_DATA_PORT->ODR |= SENSOR_DATA_PIN; //输出高电平 //SENSOR_DATA_PORT->CR1 |= SENSOR_DATA_PIN; //推挽输出 //SENSOR_DATA_PORT->CR2 &= (uint8_t)(~(SENSOR_DATA_PIN)); //10MHz高速输出 //SENSOR_DATA_PORT->DDR |= SENSOR_DATA_PIN; //设置为输出 //GPIO_Init(SENSOR_DATA_PORT, SENSOR_DATA_PIN, GPIO_Mode_In_PU_No_IT); //传感器数据口输入上拉无中断 //等效为如下配置 //SENSOR_DATA_PORT->ODR |= SENSOR_DATA_PIN; //输出高电平,此项在输入时无关紧要 //SENSOR_DATA_PORT->CR1 |= SENSOR_DATA_PIN; //输入上拉 //SENSOR_DATA_PORT->CR2 &= (uint8_t)(~(SENSOR_DATA_PIN)); //无中断 //SENSOR_DATA_PORT->DDR &= (uint8_t)(~(SENSOR_DATA_PIN)); //设置为输入 //由此可见,当进行18B20的单总线输入输出切换时,只需要最后一行配置DDR即可以高速切换,这样就可以精确控制时间 /*----------系统周期设置与内部模块使能----------*/ CLK_DeInit(); CLK_PeripheralClockConfig(CLK_Peripheral_AWU, ENABLE); //使能唤醒 CLK_MasterPrescalerConfig(CLK_MasterPrescaler_HSIDiv8); //时钟8分频,2MHz /*----------唤醒初始化----------*/ AWU_DeInit(); /*----------串口初始化----------*/ CLK_PeripheralClockConfig(CLK_Peripheral_USART, ENABLE); //使能串口 GPIO_ExternalPullUpConfig(GPIOC,GPIO_Pin_2|GPIO_Pin_3, ENABLE); //拉高电平 USART_DeInit(); USART_Init(115200, //波特率115200 USART_WordLength_8D, //8位数据位 USART_StopBits_1, //1位停止位 USART_Parity_No, //无校验 USART_Mode_Rx | USART_Mode_Tx); //接收和发送使能 //USART_ITConfig(USART_IT_TXE, ENABLE); //使能发送中断 USART_Cmd(ENABLE); //串口开始工作 /*----------看门狗初始化----------*/ //注意!!看门狗的最长喂狗时限仅1~2秒,而本程序中单片机休眠时间最长设置为30秒 //所以需要将Option Byte中的OPT4由默认的0x00改为0x01,以使休眠时看门狗暂停 //Option Byte无法在程序中修改,只能通过烧写软件如STVP在烧写时由SWIM协议外部写入 //因此在调试时看门狗功能无法实现 //由SWIM外部烧写时请自行宏定义WATCHDOG以使看门狗生效 #ifdef WATCHDOG IWDG_Enable(); IWDG_WriteAccessCmd(IWDG_WriteAccess_Enable); IWDG_SetPrescaler(IWDG_Prescaler_256); //看门狗时限设为最长的1724.63ms IWDG_SetReload(0xFF); IWDG_ReloadCounter(); #endif /*----------以下进行Zigbee串口透传模块地址的设置----------*/ //我们以STM8L 96bit唯一序列号中的8bit作为地址低位,地址高3bit放空为0x000,实际应用中可以采用拨码开关等方式进行设定 //注意!如果采用IO口设置地址,IO口电平很大程度将影响设备功耗,为此做如下考虑 //Zigbee串口透传模块的输入为内部下拉,如STM8L长期将IO口置于高电平将有近毫安级的电流损耗 //因此Zigbee模块在开机后1秒时读入IO口设置地址,其余时间应将IO口置于低电平以降低功耗(见模块手册) //对于STM8L而言应在开机时设置地址IO口,并在0.5秒后将IO口恢复低电平 //如采用拨码设置地址的方式,则首先应拨好设置地址,然后上电,并在0.5秒后将开关拨回至0 //如果采用串口设置地址模式,则将地址设置IO口全部下拉,写入串口设置地址值后重启模块即可以完成地址设置 AddrHi=0; //地址高位置0 注意!!本程序放空了模块地址高位设置口,故地址高位为0,如需改为自己的程序请记得设置该地址并在下面的程序中设置对应的地址IO FLASH_SetProgrammingTime(FLASH_ProgramTime_Standard); FLASH_Unlock(FLASH_MemType_Program); //AddrLo=FLASH_ReadByte(0x4926); //采用X-coordinator AddrLo=FLASH_ReadByte(0x4928); //采用Y-coordinator //AddrLo=(FLASH_ReadByte(0x4926)<<4) | (FLASH_ReadByte(0x4928)&0x0F); //X-coordinator和Y-coordinator各占4bit FLASH_Lock(FLASH_MemType_Program); Addr = ((u16)AddrHi<<8) | AddrLo; //将高低位地址组合成完整地址 //等待模块初始化完成以能响应串口设置命令 //注意!!这里 for(u8 i=0; i<6; i++) { Delay(0xFFFF); //每个Delay约200ms,总延时1秒以上,这里要有足量等待时间,因为模块上电一段时间后串口才开始工作接收数据 } #ifndef USE_SEC_ADDR //未定义使用串口设置方案,则采用IO口设置方案 //GPIO_Write(ADDR_HIGH_PORT, AddrHi); //注意!!本程序放空了模块地址高位设置口,所以这里无需再拉IO口,如改为自己的程序请记得设置高位的地址并在此设置IO GPIO_Write(ADDR_LOW_PORT, AddrLo); //写入低8位地址,高3位放空 for(u8 i=0; i<3; i++) { Delay(0xFFFF); //每个Delay约200ms,总延时0.5秒以上,因为在0.5秒时读入地址IO口,之后地址IO口状态不影响地址设置 } //GPIO_Write(ADDR_HIGH_PORT, 0); GPIO_Write(ADDR_LOW_PORT, 0x00); //将地址IO口置回0以降低功耗 #else //定义了串口设置地址方案,采用串口设置地址 //采用串口设置地址方式需下拉所有地址IO口使之为0x0000 //本程序IO口初始化时均为下拉低电平,无需更改电平,注意如果拉高任何地址IO口,则串口地址无效,自动采用IO口所设置的地址 //GPIO_Write(ADDR_LOW_PORT, 0); //地址低位写入低电平,初始化已为低电平,无需写入 //GPIO_Write(ADDR_HIGH_PORT, 0); //地址高位写入低电平,初始化已为低电平,无需写入 //以下将地址转换为串口设置命令字符串,首先输入设置命令UNI_SEC_ADDR和命令与设置值之间的空格 UARTSendDataBuf[0]='U';UARTSendDataBuf[1]='N';UARTSendDataBuf[2]='I';UARTSendDataBuf[3]='_';UARTSendDataBuf[4]='S'; UARTSendDataBuf[5]='E';UARTSendDataBuf[6]='C';UARTSendDataBuf[7]='_';UARTSendDataBuf[8]='A';UARTSendDataBuf[9]='D'; UARTSendDataBuf[10]='D';UARTSendDataBuf[11]='R';UARTSendDataBuf[12]=' '; //然后将13bit地址转换为四字节字符串,如0x0789转化为“1929”,0x0089转化为“0137”,并将值填入UARTSendDataBuf[13]~UARTSendDataBuf[16] SettingTemp=Addr; for(u8 i=0; i<4; i++) { UARTSendDataBuf[16-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //发送设置地址命令 UART_Send_Data(UARTSendDataBuf, 17); Delay(0x3000); //稍作等待 #endif /*----------以下进行其他参数设置,请在35行处取消需要设置值的#define注释并设置相应值----------*/ #ifdef SETTING_PANID //PANID设置,注意设置的PANID要与主机和路由器一致才可正常工作 assert_param(SETTING_PANID>=1 && SETTING_PANID<=65535); UARTSendDataBuf[0]='P';UARTSendDataBuf[1]='A';UARTSendDataBuf[2]='N';UARTSendDataBuf[3]='I';UARTSendDataBuf[4]='D'; UARTSendDataBuf[5]=' '; //然后将两字节PANID转换为五字节字符串,并将值填入UARTSendDataBuf[6]~UARTSendDataBuf[10] SettingTemp=SETTING_PANID; for(u8 i=0; i<5; i++) { UARTSendDataBuf[10-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //发送设置命令 UART_Send_Data(UARTSendDataBuf, 11); Delay(0x3000); //稍作等待 #endif //SETTING_PANID #ifdef SETTING_TX_POWER //TX_POWER发射功率设置 assert_param(SETTING_TX_POWER>=0 && SETTING_TX_POWER<=21); UARTSendDataBuf[0]='T';UARTSendDataBuf[1]='X';UARTSendDataBuf[2]='_';UARTSendDataBuf[3]='P';UARTSendDataBuf[4]='O'; UARTSendDataBuf[5]='W';UARTSendDataBuf[6]='E';UARTSendDataBuf[7]='R';UARTSendDataBuf[8]=' '; //然后将TX_POWER转换为两字节字符串,并将值填入UARTSendDataBuf[9]~UARTSendDataBuf[10] SettingTemp=SETTING_TX_POWER; for(u8 i=0; i<2; i++) { UARTSendDataBuf[10-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //发送设置命令 UART_Send_Data(UARTSendDataBuf, 11); Delay(0x3000); //稍作等待 #endif //SETTING_TX_POWER #ifdef SETTING_CHANNEL //CHANNEL设置,注意设置的CHANNEL要与主机和路由器一致才可正常工作 assert_param(SETTING_CHANNEL>=2048 && SETTING_CHANNEL<=134215680); UARTSendDataBuf[0]='C';UARTSendDataBuf[1]='H';UARTSendDataBuf[2]='A';UARTSendDataBuf[3]='N';UARTSendDataBuf[4]='N'; UARTSendDataBuf[5]='E';UARTSendDataBuf[6]='L';UARTSendDataBuf[7]=' '; //然后将CHANNEL转换为十字节字符串,并将值填入UARTSendDataBuf[8]~UARTSendDataBuf[17] SettingTemp=SETTING_CHANNEL; for(u8 i=0; i<10; i++) { UARTSendDataBuf[17-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //发送设置命令 UART_Send_Data(UARTSendDataBuf, 18); Delay(0x3000); //稍作等待 #endif //SETTING_CHANNEL #ifdef SETTING_POLL_RATE //POLL_RATE终端定期唤醒查询数据时限 assert_param(SETTING_POLL_RATE>=0 && SETTING_POLL_RATE<=65535); UARTSendDataBuf[0]='P';UARTSendDataBuf[1]='O';UARTSendDataBuf[2]='L';UARTSendDataBuf[3]='L';UARTSendDataBuf[4]='_'; UARTSendDataBuf[5]='R';UARTSendDataBuf[6]='A';UARTSendDataBuf[7]='T';UARTSendDataBuf[8]='E';UARTSendDataBuf[9]=' '; //然后将POLL_RATE转换为五字节字符串,并将值填入UARTSendDataBuf[10]~UARTSendDataBuf[14] SettingTemp=SETTING_POLL_RATE; for(u8 i=0; i<5; i++) { UARTSendDataBuf[14-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //发送设置命令 UART_Send_Data(UARTSendDataBuf, 15); Delay(0x3000); //稍作等待 #endif //SETTING_POLL_RATE //写入重启模块命令PW_RESET 1 UARTSendDataBuf[0]='P';UARTSendDataBuf[1]='W';UARTSendDataBuf[2]='_';UARTSendDataBuf[3]='R';UARTSendDataBuf[4]='E'; UARTSendDataBuf[5]='S';UARTSendDataBuf[6]='E';UARTSendDataBuf[7]='T';UARTSendDataBuf[8]=' ';UARTSendDataBuf[9]='1'; //发送重启命令 UART_Send_Data(UARTSendDataBuf, 10); //等待模块重启,重启0.5秒时读入地址设置IO口为0x0000,进入串口设置地址模式,读取刚才我们串口所设置的地址并工作在该地址 for(u8 i=0; i<6; i++) { Delay(0xFFFF); //每个Delay约200ms,总延时1秒以上,这里要有足量等待时间,因为模块上电一段时间后串口才开始工作接收数据 } //以下进行18B20采样精度设置 DS18B20_Init(); DS18B20_Write(0xCC); //跳过ROM操作 DS18B20_Write(0xBE); //读配置 //读出TH,TL值以便设置时将其原样写入不进行改变 Temprature=DS18B20_Read(); //低8位 Temprature=Temprature | (DS18B20_Read()<<8); //高8位 TH=DS18B20_Read(); TL=DS18B20_Read(); Config=DS18B20_Read(); DS18B20_Init(); DS18B20_Write(0xCC); //跳过ROM操作 DS18B20_Write(0x4E); //写配置 DS18B20_Write(TH); //原样写入不改变 DS18B20_Write(TL); //原样写入不改变 DS18B20_Write(0x1F); //采用较低分辨率能大幅降低功耗 1F:9位,93.75ms 3F:10位,187.5ms 5F:11位,375ms 7F:12位,750ms #ifdef UI_STRING //字符串输出界面 //格式 ID:1234 T:+025.0 //0~3,AA XX XX 55,目的地址 //4~6, 3字节头 //7~10, 4字节地址 //11~13, 3字节中 //14,符号位 //15~17,整数位 //18,小数点 //19,小数位 //20,1字节尾 UARTSendDataBuf[0]=0xAA;UARTSendDataBuf[1]=0x00;UARTSendDataBuf[2]=0x00;UARTSendDataBuf[3]=0x55; UARTSendDataBuf[4]='I';UARTSendDataBuf[5]='D';UARTSendDataBuf[6]=':'; //将本机地址转换为十字节字符串,并将值填入UARTSendDataBuf[10]~UARTSendDataBuf[19] SettingTemp=Addr; for(u8 i=0; i<4; i++) { UARTSendDataBuf[10-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } //将头部的所有0替换为空格 i=7; while(UARTSendDataBuf[i]=='0') { UARTSendDataBuf[i++]=' '; } UARTSendDataBuf[11]=' ';UARTSendDataBuf[12]='T';UARTSendDataBuf[13]=':'; UARTSendDataBuf[18]='.'; UARTSendDataBuf[20]=' '; #endif disableInterrupts(); /* Infinite loop */ while (1) { #ifdef WATCHDOG IWDG_ReloadCounter(); //喂狗 #endif if(WakeCount<=0) //每WORK_TO_WAKE_RATIO次唤醒采集一次传感器数据并上传,之所以采用初值-1这里<=0后面++并%WORK_TO_WAKE_RATIO的方式,是为了在开机时能连采两次使传感器工作正常 { DS18B20_Init(); DS18B20_Write(0xCC); //跳过ROM操作 DS18B20_Write(0x44); //温度转换 //9位分辨率93.75ms采样时间情况下,进入睡眠128ms,等待18B20采样完成 //注意!如果提采样高分辨率会延长采样时间,此时应延长睡眠时间使之大于采样时间,否则会出错 enableInterrupts(); AWU_Init(AWU_Timebase_128ms); AWU_ReInitCounter(); AWU_Cmd(ENABLE); halt(); disableInterrupts(); #ifdef WATCHDOG IWDG_ReloadCounter(); //喂狗 #endif while(GPIO_ReadInputDataBit(SENSOR_DATA_PORT, SENSOR_DATA_PIN)==RESET); //如18B20还未采样完成则等待 DS18B20_Init(); DS18B20_Write(0xCC); //跳过ROM操作 DS18B20_Write(0xBE); //读取RAM Temprature=DS18B20_Read(); //低8位 Temprature=Temprature | (DS18B20_Read()<<8); //高8位 TH=DS18B20_Read(); TL=DS18B20_Read(); Config=DS18B20_Read(); DS18B20_Init(); //reset,终止读写其他寄存器 #ifndef UI_STRING //将采集到的温度数据发送到主机 UARTSendDataBuf[0]=0xAA; //4字节目的地址包头,0xAA 目的地址高位 目的地址低位 0x55,主机目的地址高低位均为0x00 UARTSendDataBuf[1]=0x00; UARTSendDataBuf[2]=0x00; UARTSendDataBuf[3]=0x55; UARTSendDataBuf[4]=AddrHi; //发送给主机本机地址以方便主机的寻址,地址高位,这里我们放空了地址高位,模块的3位地址高位默认下拉设置为0 UARTSendDataBuf[5]=AddrLo; //发送给主机本机地址低位 UARTSendDataBuf[6]=(u8)(Temprature>>8); //温度高位 UARTSendDataBuf[7]=(u8)(Temprature&0x00FF); //温度低位 UART_Send_Data(UARTSendDataBuf, 8); //将数据发送到主机 #else //字符串格式 UARTSendDataBuf[14]='+'; if(Temprature & 0x8000) //最高位为1,负的,取反加一 { UARTSendDataBuf[14]='-'; Temprature = (~Temprature)+1; } //小数部分 UARTSendDataBuf[19]='0'; if(Temprature & 0x000F) { UARTSendDataBuf[19]='5'; } //整数部分 SettingTemp=Temprature>>4; for(u8 i=0; i<3; i++) { UARTSendDataBuf[17-i] = '0' + (SettingTemp % 10); SettingTemp /= 10; } UART_Send_Data(UARTSendDataBuf, 21); //将数据发送到主机 #endif } #ifdef WATCHDOG IWDG_ReloadCounter(); //喂狗 #endif WakeCount++; WakeCount = WakeCount % WORK_TO_WAKE_RATIO; //每WORK_TO_WAKE_RATIO次唤醒采集一次传感器数据并上传(约WORK_TO_WAKE_RATIO*30秒采集上传一次) enableInterrupts(); AWU_Init(AWU_Timebase_30s); //30秒睡眠,注意!!实测睡眠时间误差较大 AWU_ReInitCounter(); AWU_Cmd(ENABLE); halt(); disableInterrupts(); }
void flash_inside_erase_all(void) { FLASH_Unlock(); FLASH_ErasePage(FLASH_INSIDE_ADDRESS_START); FLASH_Lock(); FLASH_ClearFlag(FLASH_FLAG_BSY|FLASH_FLAG_EOP|FLASH_FLAG_PGERR|FLASH_FLAG_WRPRTERR); }
/** * @brief Main program. * @param None * @retval None */ int main(void) { //RCC_Config(); //GPIO_Config(); //RCC_MCO1Config(RCC_MCO1Source_PLLCLK,RCC_MCO1Div_1); uint8_t tmpreg; LIS302DL_InitTypeDef LIS302DL_InitStruct; /*!< 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 */ /* SysTick end of count event each 10ms */ RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(RCC_Clocks.HCLK_Frequency / 100); //NVIC_SetPriority(SysTick_IRQn, -1); /* MEMS configuration and set int1/int2 pins*/ LIS302DL_InitStruct.Power_Mode = LIS302DL_LOWPOWERMODE_ACTIVE; LIS302DL_InitStruct.Output_DataRate = LIS302DL_DATARATE_100; LIS302DL_InitStruct.Axes_Enable = LIS302DL_XYZ_ENABLE; LIS302DL_InitStruct.Full_Scale = LIS302DL_FULLSCALE_2_3; LIS302DL_InitStruct.Self_Test = LIS302DL_SELFTEST_NORMAL; LIS302DL_Init(&LIS302DL_InitStruct); //Set INT1/INT2 pins tmpreg = 0x40; LIS302DL_Write(&tmpreg, LIS302DL_CTRL_REG3_ADDR, 1); //Initialize the touchscreen TSC_Init(); /* Initialize LEDs and push-buttons mounted on STM324xG-EVAL board */ STM_EVAL_LEDInit(LED1); STM_EVAL_LEDInit(LED2); //STM_EVAL_LEDInit(LED3); //STM_EVAL_LEDInit(LED4); /* Initialize the LCD */ STM324xG_LCD_Init(); //STM_EVAL_LEDOn(LED1); LCD_Clear(Black); LCD_SetTextColor(White); LCD_LOG_SetHeader("STM32 Camera Demo"); LCD_LOG_SetFooter (" Copyright (c) STMicroelectronics" ); /* ADC configuration */ ADC_Config(); /* Initializes the DCMI interface (I2C and GPIO) used to configure the camera */ //OV9655_HW_Init(); OV9712_HW_Init(); /* Read the OV9655/OV2640 Manufacturer identifier */ //OV9655_ReadID(&OV9655_Camera_ID); OV9712_ReadID(&OV9712_Camera_ID); //while(1); if(OV9655_Camera_ID.PID == 0x96) { Camera = OV9712_CAMERA; sprintf((char*)buffer, "OV9655 Camera ID 0x%x", OV9655_Camera_ID.PID); ValueMax = 2; } else if(OV9712_Camera_ID.PIDH == 0x97) { Camera = OV9712_CAMERA; sprintf((char*)buffer, "OV9712 Camera ID 0x%x", OV9712_Camera_ID.PIDH); ValueMax = 2; } else { LCD_SetTextColor(LCD_COLOR_RED); sprintf((char*)buffer, "OV Camera ID 0x%02x%02x", OV9655_Camera_ID.Version, OV9712_Camera_ID.PIDH); LCD_DisplayStringLine(LINE(4), buffer); while(1); } LCD_SetTextColor(LCD_COLOR_YELLOW); LCD_DisplayStringLine(LINE(4), (uint8_t*)buffer); LCD_SetTextColor(LCD_COLOR_WHITE); Delay(200); /* Initialize demo */ ImageFormat = (ImageFormat_TypeDef)BMP_QVGA; /* Configure the Camera module mounted on STM324xG-EVAL board */ Demo_LCD_Clear(); LCD_DisplayStringLine(LINE(4), "Camera Init.. "); Camera_Config(); sprintf((char*)buffer, " Image selected: %s", ImageForematArray[ImageFormat]); LCD_DisplayStringLine(LINE(4),(uint8_t*)buffer); LCD_ClearLine(LINE(4)); Demo_LCD_Clear(); if(ImageFormat == BMP_QQVGA) { /* LCD Display window */ LCD_SetDisplayWindow(60, 80, 160, 120); ReverseLCD(); LCD_WriteRAM_Prepare(); } else if(ImageFormat == BMP_QVGA) { /* LCD Display window */ LCD_SetDisplayWindow(0, 0, 320, 240); ReverseLCD(); LCD_WriteRAM_Prepare(); } { int i, j; for (j = 0; j < 16; j++) { LCD_SetDisplayWindow(0, (240 / 16) * j, 320, (240 / 16)); LCD_WriteRAM_Prepare(); for (i = 0; i < 320 * 240 / 16; i++) { LCD_WriteRAM(0x0003 << j); } } } /* Enable DMA2 stream 1 and DCMI interface then start image capture */ DMA_Cmd(DMA2_Stream1, ENABLE); DCMI_Cmd(ENABLE); /* Insert 100ms delay: wait 100ms */ //Delay(200); DCMI_CaptureCmd(ENABLE); while(1) { OV9655_BrightnessConfig(0x7F);// //static int step = 0; int i, block, begin; unsigned short *p; if (!bShot) { begin = (datablock - 11 + 48) % 48; for (block = begin; block < begin + 11; block++) { p = (unsigned short *)(0x20000000 + (320 * 240 * 2 / 16) * ((block) % 12)); LCD_SetDisplayWindow(0, (block % 16) * (240 / 16), 320, (240 / 16)); //LCD_SetCursor(0, (block % 16) * (240 / 16)); LCD_WriteRAM_Prepare(); for (i = 0; i < 320 * 240 / 16; i++) { LCD_WriteRAM(*p++); } } } if (TSC_TouchDet()) { int x, y; TP_GetAdXY(&x, &y); if (x > 300 && x < 2800 && y > 300 && y < 2800) { if (x < 1550 && y < 1550) { uint32_t StartSector = 0, EndSector = 0, Address = 0, SectorCounter = 0; int m; //拍照bShot bShot = 1; while(datablock % 16); DMA_Cmd(DMA2_Stream1, DISABLE); DCMI_Cmd(DISABLE); //STM_EVAL_LEDOn(LED2); DMA_ClearFlag(DMA2_Stream1, 0x2F7D0F7D); DMA_ClearFlag(DMA2_Stream1, 0x0F7D0F7D); DMA_ClearITPendingBit(DMA2_Stream1, DMA_IT_TCIF1); datablock = 0; DMA2_Stream1->M0AR = 0x20000000 + 9600 * (datablock % 12); DMA_SetCurrDataCounter(DMA2_Stream1, (320 * 240 * 2 / 4) / 16); DCMI_Cmd(ENABLE); DMA_Cmd(DMA2_Stream1, ENABLE); { unsigned long *p, *q; while(datablock < 4); //等待准备好前4块数据,就将这4块数据导入到0x10000000+0x50000之后。 q = (unsigned long *)(0x20000000); p = (unsigned long *)(0x10000000 + 0x5000); while (q < (unsigned long *)(0x20000000 + 4 * (320 * 240 * 2 / 16))) { *p = *q; p++; q++; } } while(datablock < 16); //等待全部采集完成。 STM_EVAL_LEDOn(LED2); //LED2亮表示采集完成。 LCD_SetDisplayWindow(0, 0, 320, 240); LCD_WriteRAM_Prepare(); LCD_Clear(Black); //RAM位置 /* 序号 地址 大小 1: 0x10005000+9600*0 9600 2: 0x10005000+9600*1 9600 3: 0x10005000+9600*2 9600 4: 0x10005000+9600*3 9600 5: 0x20000000+9600*5 9600 6: 0x20000000+9600*6 9600 7: 0x20000000+9600*7 9600 8: 0x20000000+9600*8 9600 9: 0x20000000+9600*9 9600 10: 0x20000000+9600*10 9600 11: 0x20000000+9600*11 9600 12: 0x20000000+9600*0 9600 13: 0x20000000+9600*1 9600 14: 0x20000000+9600*2 9600 15: 0x20000000+9600*3 9600 */ for (m = 0; m < 16; m++) //显示保存的图片 { unsigned short *q; if (m < 4) { q = (unsigned short *)(0x10000000 + 0x5000 + m * (320 * 240 * 2 / 16)); } else { q = (unsigned short *)(0x20000000 + (m % 12) * (320 * 240 * 2 / 16)); } LCD_SetDisplayWindow(0, m * (240 / 16), 320, (240 / 16)); LCD_WriteRAM_Prepare(); for (i = 0; i < 320 * 240 / 16; i++) { LCD_WriteRAM(*q++); } } /* Erase the user Flash area ***********/ FLASH_Unlock(); /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); /* Get the number of the start and end sectors */ StartSector = GetSector(FLASH_USER_START_ADDR); EndSector = GetSector(FLASH_USER_END_ADDR); for (SectorCounter = StartSector; SectorCounter < EndSector; SectorCounter += 8) { /* Device voltage range supposed to be [2.7V to 3.6V], the operation will be done by word */ if (FLASH_EraseSector(SectorCounter, VoltageRange_3) != FLASH_COMPLETE) { /* Error occurred while sector erase. User can add here some code to deal with this error */ while (1) { } } } for (m = 0; m < 16; m++) //保存图片到flash { unsigned long *q; Address = FLASH_USER_START_ADDR + m * (320 * 240 * 2 / 16); if (m < 4) { q = (unsigned long *)(0x10000000 + 0x5000 + m * (320 * 240 * 2 / 16)); } else { q = (unsigned long *)(0x20000000 + (m % 12) * (320 * 240 * 2 / 16)); } while (Address < FLASH_USER_START_ADDR + (m + 1) *(320 * 240 * 2 / 16)) { if (FLASH_ProgramWord(Address, *q) == FLASH_COMPLETE) { Address = Address + 4; q++; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { } } } } STM_EVAL_LEDOff(LED2); LCD_SetDisplayWindow(0, 0, 320, 240); LCD_WriteRAM_Prepare(); LCD_Clear(Black); for (m = 0; m < 16; m++) //显示flash中的图片 { unsigned short *q; q = (unsigned short *)(FLASH_USER_START_ADDR + m * (320 * 240 * 2 / 16)); LCD_SetDisplayWindow(0, m * (240 / 16), 320, (240 / 16)); LCD_WriteRAM_Prepare(); for (i = 0; i < 320 * 240 / 16; i++) { LCD_WriteRAM(*q++); } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ FLASH_Lock(); } else if (x >= 1550 && y < 1550) { //righttop STM_EVAL_LEDOff(LED1); STM_EVAL_LEDOff(LED2); bShot = 0; datablock = 0; DMA_Cmd(DMA2_Stream1, ENABLE); DCMI_Cmd(ENABLE); } else if (x < 1550 && y >= 1550) { //righttop //DMA_Cmd(DMA2_Stream1, ENABLE); //DCMI_Cmd(ENABLE); } else if (x >= 1550 && y >= 1550) { //righttop //DMA_Cmd(DMA2_Stream1, ENABLE); //DCMI_Cmd(ENABLE); } } } //Delay(10); } }
int main(void) { uint32_t *u32Pt = (uint32_t *)buff; uint8_t *u8pt,u8temp; int32_t i = 10000000,j = 0; uint32_t u32temp; uint16_t u16temp; uint32_t res; uint8_t c; uint32_t timeOut = 3000000; uint8_t tryNum,exit; SysInit(); // RS232_PIN_SET_OUTPUT; // RS232_PIN_CLR; USART3_PutString("\r\n************************AMPM*********************\r\n"); USART3_PutString("\r\nHello!\r\n"); USART3_PutString("\r\nI'm GSM_STM32_BOOTLOADER\r\n"); USART3_PutString("\r\nMy Ver:V1.0\r\n"); USART3_PutString("\r\nhttp://ampm.com.vn\r\n"); USART3_PutString("\r\n************************START MAIN***************\r\n"); DelayMs(1000); InitTimeout(&bootDisTimeout,TIME_SEC(3)); InitTimeout(&bootLoginTimeout,TIME_SEC(1)); InitTimeout(&bootExitTimeout,TIME_SEC(10)); UART_ProtoRecv.dataPt = &USB_rxBuff[4]; UART_parserPacket.state = CFG_CMD_WAITING_SATRT_CODE; UART_parserPacket.lenMax = UART_PACKET_SIZE; FLASH_Unlock(); while((CheckTimeout(&bootDisTimeout) != TIMEOUT || bootMode) && CheckTimeout(&bootExitTimeout) != TIMEOUT ) // while(0) { if(bootMode == 0 && CheckTimeout(&bootLoginTimeout) == TIMEOUT) { USB_txBuff[0] = 0xCA; USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x88; //opcode USB_txBuff[4] = 0xA5; USB_txBuff[5] = 0xA5; USB_txBuff[6] = 0xA5; USB_txBuff[7] = 0xA5; USB_txBuff[USB_txBuff[1] + 4] = CfgCalcCheckSum((uint8_t *)&USB_txBuff[4],USB_txBuff[1]); for(i = 0;i < USB_txBuff[1] + 4 + 1; i++) { USART3_PutChar(USB_txBuff[i]); } USB_rxBuff[0] = 0; InitTimeout(&bootLoginTimeout,TIME_SEC(2)); } while(RINGBUF_Get(&USART3_RxRingBuff,&c) == 0) { if(CfgParserPacket(&UART_parserPacket,&UART_ProtoRecv,c) == 0) { USB_rxBuff[0] = 0xCA; USB_rxBuff[1] = ((uint8_t *)&UART_ProtoRecv.length)[0]; USB_rxBuff[2] = ((uint8_t *)&UART_ProtoRecv.length)[1]; USB_rxBuff[3] = UART_ProtoRecv.opcode; UART_ProtoRecv.dataPt = &USB_rxBuff[4]; UART_parserPacket.state = CFG_CMD_WAITING_SATRT_CODE; UART_parserPacket.lenMax = UART_PACKET_SIZE; break; } } if(USB_rxBuff[0] == 0xCA) { USB_txBuff[1] = 0; USB_txBuff[2] = 0; USB_txBuff[3] = 0; switch(USB_rxBuff[3]) { case 0x12: InitTimeout(&bootExitTimeout,TIME_SEC(60)); u32Pt = (uint32_t *)&USB_rxBuff[4]; packetNo = *u32Pt; if(packetNo == 0xA5A5A5A5) { firmwareFileOffSet = 0; u32Pt = (uint32_t *)&USB_rxBuff[8]; firmwareFileSize = *u32Pt; USB_txBuff[1] = 12; //length USB_txBuff[3] = 0x12; //opcode USB_txBuff[4] = USB_rxBuff[4]; USB_txBuff[5] = USB_rxBuff[5]; USB_txBuff[6] = USB_rxBuff[6]; USB_txBuff[7] = USB_rxBuff[7]; //Max file size USB_txBuff[8] = USB_rxBuff[8]; USB_txBuff[9] = USB_rxBuff[9]; USB_txBuff[10] = USB_rxBuff[10]; USB_txBuff[11] = USB_rxBuff[11]; //Max packet size u16temp = UART_PACKET_SIZE - 4; USB_txBuff[12] = ((uint8_t *)&u16temp)[0]; //max packet size USB_txBuff[13] = ((uint8_t *)&u16temp)[1]; //max packet size USB_txBuff[14] = 0; //max packet size USB_txBuff[15] = 0; //max packet size } else { InitTimeout(&bootExitTimeout,TIME_SEC(10)); if(packetNo == firmwareFileOffSet) { firmwareFileOffSet += (UART_ProtoRecv.length - 4); u32temp = firmwareFileOffSet % FLASH_BUF_SIZE; for(i = 0;i < (UART_ProtoRecv.length - 4);i++) { flashBuff[(packetNo % FLASH_BUF_SIZE) + i] = USB_rxBuff[i + 8]; } if(u32temp == 0) { u32temp = USER_FLASH_START + firmwareFileOffSet - FLASH_BUF_SIZE; phase = 5; u32Pt = (uint32_t *)flashBuff; __disable_irq(); myFMC_Erase(u32temp); FMC_ProgramPage(u32temp,u32Pt); __enable_irq(); phase = 6; for(i = 0;i < FLASH_BUF_SIZE; i++) flashBuff[i] = 0xff; } else if(firmwareFileOffSet >= firmwareFileSize) { i = (firmwareFileOffSet / FLASH_BUF_SIZE)*FLASH_BUF_SIZE; u32temp = USER_FLASH_START + i; u32Pt = (uint32_t *)flashBuff; __disable_irq(); myFMC_Erase(u32temp); FMC_ProgramPage(u32temp,u32Pt); __enable_irq(); } } packetNo = firmwareFileOffSet; if(firmwareFileOffSet >= firmwareFileSize) { firmwareFileOffSet = 0; packetNo = 0x5A5A5A5A; InitTimeout(&bootExitTimeout,TIME_SEC(1)); } u8pt = (uint8_t *)&packetNo; USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x12; //opcode USB_txBuff[4] = u8pt[0]; USB_txBuff[5] = u8pt[1]; USB_txBuff[6] = u8pt[2]; USB_txBuff[7] = u8pt[3]; } break; case 0xA5: FLASH_Lock(); SysDeInit(); execute_user_code(); break; case 0x88: bootMode = 1; break; default: USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x33; //opcode USB_txBuff[4] = 0xA5; USB_txBuff[5] = 0xA5; USB_txBuff[6] = 0xA5; USB_txBuff[7] = 0xA5; break; } if(USB_txBuff[3]) { USB_txBuff[0] = 0xCA; USB_txBuff[USB_txBuff[1] + 4] = CfgCalcCheckSum((uint8_t *)&USB_txBuff[4],USB_txBuff[1]); for(i = 0;i < USB_txBuff[1] + 4 + 1; i++) { USART3_PutChar(USB_txBuff[i]); } } USB_rxBuff[0] = 0; UART_ProtoRecv.opcode = 0; } } u32Pt = (uint32_t *)buff; SST25_Init(); SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_STATUS_OFFSET*4,buff,4); if(*u32Pt != 0x5A5A5A5A) { execute_user_code(); } USART3_PutString("\r\nPROGRAM NEW FIRMWARE*\r\n"); tryNum = 10; exit = 0; while(!exit && tryNum--) { SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_CRC_OFFSET*4,buff,4); fileCrc = *u32Pt; SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_FILE_SIZE_OFFSET*4,buff,4); fileSize = *u32Pt; if(fileSize < FIRMWARE_MAX_SIZE) { flashCheckSum = 0; for(i = 0; i < fileSize;i += PAGE_SIZE) { USART3_PutChar('*'); SST25_Read(i + FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); for(j = 0 ; j < PAGE_SIZE;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } myFMC_Erase(USER_FLASH_START + i); FMC_ProgramPage(USER_FLASH_START + i,u32Pt); SST25_Read(i + FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); memAddr = USER_FLASH_START + i; if(memcmp(buff, (void*)memAddr , PAGE_SIZE) != NULL) break; } if(flashCheckSum == fileCrc) { USART3_PutString("\r\nFINISHED!\r\n"); SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_STATUS_OFFSET*4,buff,4); if(*u32Pt != 0x5A5A5A5A) { tryNum = 10; while(tryNum--) { flashCheckSum = 0; for(i = 0; i < fileSize;i += 256) { SST25_Read(i + FIRMWARE_BASE_ADDR,buff, 256); SST25_Write(i + BASE_FIRMWARE_BASE_ADDR,buff, 256); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,flashBuff, 256); if(memcmp(buff,flashBuff,256) != NULL) { break; } } if(i >= fileSize) for(i = 0; i < fileSize;i += 256) { SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, 256); for(j = 0 ; j < 256;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } } if(flashCheckSum == fileCrc) { SST25_Read(FIRMWARE_INFO_ADDR,buff, 256); SST25_Write(BASE_FIRMWARE_INFO_ADDR,buff, 256); SST25_Read(BASE_FIRMWARE_INFO_ADDR,flashBuff, 256); if(memcmp(buff,flashBuff,256) == NULL) { break; } } } } exit = 1; } } } if(exit == 0 && tryNum == 0xff) { USART3_PutString("\r\nFAIL!\r\n"); USART3_PutString("\r\nDOWNLOAD BACKUP FIRMWARE*\r\n"); tryNum = 10; exit = 0; while(!exit && tryNum--) { SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_CRC_OFFSET*4,buff,4); fileCrc = *u32Pt; SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_FILE_SIZE_OFFSET*4,buff,4); fileSize = *u32Pt; if(fileSize < FIRMWARE_MAX_SIZE) { flashCheckSum = 0; for(i = 0; i < fileSize;i += PAGE_SIZE) { USART3_PutChar('*'); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); for(j = 0 ; j < PAGE_SIZE;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } myFMC_Erase(USER_FLASH_START + i); FMC_ProgramPage(USER_FLASH_START + i,u32Pt); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); memAddr = USER_FLASH_START + i; if(memcmp(buff, (void*)memAddr , PAGE_SIZE) != NULL) break; } if(flashCheckSum == fileCrc) { exit = 1; USART3_PutString("\r\nDOWNLOAD BACKUP FINISHED!\r\n"); } } } } SST25_Erase(FIRMWARE_INFO_ADDR,block4k); execute_user_code(); while(1) { } }
/** * @brief Main program * @param None * @retval None */ ErrorStatus eep_write( const uint8_t *data, uint32_t addr, uint16_t len ) { uint32_t WriteData = 0; const uint8_t *pos = data; uint16_t len_offset = 0; uint8_t i = 0; if (!len) { return SUCCESS; } /* Unlock the Flash *********************************************************/ /* Enable the flash control register access */ FLASH_Unlock(); /* Erase the user Flash area ************************************************/ /* area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */ /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); /* Program the user Flash area word by word ********************************/ /* area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR */ uwAddress = 0; len_offset = len % 4; len -= len_offset; while (uwAddress < len) { WriteData = (pos[0] | (pos[1]<<8) | (pos[2]<<16) | (pos[3]<<24)); if (FLASH_ProgramWord(FLASH_USER_START_ADDR + addr + uwAddress, WriteData) == FLASH_COMPLETE) { uwAddress += 4; pos += 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ FLASH_Lock(); return ERROR; } } if ( len_offset ) { for (i=0; i<len_offset; ++i) { if (FLASH_ProgramByte(FLASH_USER_START_ADDR + addr + uwAddress, *pos) == FLASH_COMPLETE) { uwAddress++; pos++; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ FLASH_Lock(); return ERROR; } } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) */ FLASH_Lock(); return SUCCESS; }
void calibrate_init(void) { float_pack_t pack; bool found_acc_matrix = 0; // Make FLASH writable while initializing the virtual EEPROM FLASH_Unlock(); EE_Init(); FLASH_Lock(); // Set defaults of no change if any of the values are not found if (EE_ReadVariable(EE_GYRO_OFF_X_L, &pack.s[0]) || EE_ReadVariable(EE_GYRO_OFF_X_H, &pack.s[1])) g_cal.gyro_offset[0] = 0.0; else g_cal.gyro_offset[0] = pack.f; if (EE_ReadVariable(EE_GYRO_OFF_Y_L, &pack.s[0]) || EE_ReadVariable(EE_GYRO_OFF_Y_H, &pack.s[1])) g_cal.gyro_offset[1] = 0.0; else g_cal.gyro_offset[1] = pack.f; if (EE_ReadVariable(EE_GYRO_OFF_Z_L, &pack.s[0]) || EE_ReadVariable(EE_GYRO_OFF_Z_H, &pack.s[1])) g_cal.gyro_offset[2] = 0.0; else { g_cal.gyro_offset[2] = pack.f; // mark if we were able to successfully load a gyro offset from EEPROM stored_gyro_offset = 1; } // Read the 3x3 scale and cross axis matrix for (uint8_t i = 0; i < 3; i++) { for (uint8_t j = 0; j < 3; j++) { if (EE_ReadVariable(EE_GYRO_SCALE_START + (i*3 + j)*2, &pack.s[0]) || EE_ReadVariable(EE_GYRO_SCALE_START + (i*3 + j)*2 + 1, &pack.s[1])) // Fill missing values with the identity matrix g_cal.gyro_scale[i][j] = (i == j) ? 1.0 : 0.0; else g_cal.gyro_scale[i][j] = pack.f; } } // Read the 3x3 scale and cross axis matrix for (uint8_t i = 0; i < 3; i++) { for (uint8_t j = 0; j < 3; j++) { if (EE_ReadVariable(EE_ACC_SCALE_START + (i*3 + j)*2, &pack.s[0]) || EE_ReadVariable(EE_ACC_SCALE_START + (i*3 + j)*2 + 1, &pack.s[1])) { // Fill missing values with the identity matrix g_cal.acc_scale[i][j] = (i == j) ? 1.0 : 0.0; } else { g_cal.acc_scale[i][j] = pack.f; found_acc_matrix = 1; } } } if (!found_acc_matrix) init_legacy_acc(); if (EE_ReadVariable(EE_ACC_OFF_X_L, &pack.s[0]) || EE_ReadVariable(EE_ACC_OFF_X_H, &pack.s[1])) g_cal.acc_offset[0] = 0.0; else g_cal.acc_offset[0] = pack.f; if (EE_ReadVariable(EE_ACC_OFF_Y_L, &pack.s[0]) || EE_ReadVariable(EE_ACC_OFF_Y_H, &pack.s[1])) g_cal.acc_offset[1] = 0.0; else g_cal.acc_offset[1] = pack.f; if (EE_ReadVariable(EE_ACC_OFF_Z_L, &pack.s[0]) || EE_ReadVariable(EE_ACC_OFF_Z_H, &pack.s[1])) g_cal.acc_offset[2] = 0.0; else g_cal.acc_offset[2] = pack.f; if (EE_ReadVariable(EE_TEMPERATURE_L, &pack.s[0]) || EE_ReadVariable(EE_TEMPERATURE_H, &pack.s[1])) g_cal.temperature = 0.0; // Just pick a fake temperature else g_cal.temperature = pack.f; // If we have calibration, and the calibration was performed with the cross // axis sign error, fix it if (found_acc_matrix) { uint16_t version = 0; EE_ReadVariable(EE_CAL_VERSION, &version); // CALIBRATE_HD and newer have the fix if (version < CALIBRATE_HD) { fix_cross_axis(); } } // Start at the factory calibrated gyro offset memcpy(current_offset.offset, g_cal.gyro_offset, sizeof(float)*3); current_offset.temperature_actual = g_cal.temperature; // Initialize the gyro offset temperature bins temperature_init(¤t_offset); }
uint8_t Immobiliser::addCard() { uint8_t rfidStatus; //RFID reader status uint8_t cardStatus = AddSuccess; //Card operations status FLASH_Status flashStatus; //FLASH operations status uint8_t buffer[bufferSize]={0}; //card ID buffer rfidStatus = reader->MFRC522_Request(PICC_REQIDL, buffer); if (rfidStatus == MI_OK) { rfidStatus = reader->MFRC522_Anticoll(buffer); if (rfidStatus == MI_OK && cardsNumber != maxCards) cardStatus = writeCardData(buffer); //writing key and data else return AddFailed; if (cardStatus == AddSuccess) { flashStatus = FLASH_COMPLETE; FLASH_Unlock(); //unlocking FLASH for writing //erasing data from FLASH flashStatus = FLASH_EraseSector(flashSector, VoltageRange_3); flashStatus = FLASH_WaitForLastOperation(); if (flashStatus != FLASH_COMPLETE) { FLASH_Lock(); return AddFailed; } //FLASH configuration FLASH->CR &= CR_PSIZE_MASK; FLASH->CR |= FLASH_PSIZE_BYTE; //setting data size to bytes FLASH->CR |= FLASH_CR_PG; //checking if card already exists in FLASH if (checkCard(buffer) != CheckCorrect) { //writing new card to cards array for (uint8_t i=0; i<bufferSize; ++i) cards[cardsNumber][i] = buffer[i]; cardsNumber++; } else cardStatus = AddExists; //writing cards number to FLASH FLASH_AT(0) = cardsNumber; flashStatus = FLASH_WaitForLastOperation(); if (flashStatus != FLASH_COMPLETE) return AddFailed; //writing all cards to FLASH (also empty rows in array) for (uint8_t i=0; i<maxCards; ++i) { for (uint8_t j=0; j<bufferSize; ++j) { FLASH_AT(1 + i * bufferSize + j) = cards[i][j]; flashStatus = FLASH_WaitForLastOperation(); if (flashStatus != FLASH_COMPLETE) return AddFailed; } } FLASH->CR &= (~FLASH_CR_PG); FLASH_Lock(); //locking FLASH for writing return cardStatus; } } return AddFailed; }
void HID_ProcessCommand(uint8_t *request, uint8_t *response) { uint8_t result = DAP_OK; uint16_t data; uint16_t length; uint32_t address; uint8_t *p_address; if ((*request >= HID_Command0) && (*request <= HID_Command7)) { *response++ = *request; switch (*request++) { case HID_Command0: /* Get device info */ address = DBGMCU->IDCODE; *response++ = (address >> 0) & 0xFF; *response++ = (address >> 8) & 0xFF; *response++ = (address >> 16) & 0xFF; *response++ = (address >> 24) & 0xFF; break; case HID_Command1: FLASH_Unlock(); break; case HID_Command2: FLASH_Lock(); break; case HID_Command3: address = PACK_DATA_LONG(0); if (FLASH_ErasePage(address) != FLASH_COMPLETE) result = DAP_ERROR; break; case HID_Command4: /* Check for blank (0xFF) */ { p_address = PACK_DATA_PBYTE(0); length = PACK_DATA_WORD(4); while (length-- != 0) { if (*p_address++ != 0xFF) { result = DAP_ERROR; break; } } } break; case HID_Command5: /* Write to flash */ { address = PACK_DATA_LONG(0); length = PACK_DATA_WORD(4); if (length > (DAP_PACKET_SIZE - (8+2))) // Check for maximum data payload result = DAP_ERROR; else { request += 8; while (length-- != 0) { data = *request++; if (length != 0) { data |= ((uint16_t)(*request++) << 8); length--; } if (FLASH_ProgramHalfWord(address, data) != FLASH_COMPLETE) { result = DAP_ERROR; break; } address += 2; } } } break; case HID_Command6: /* Read from flash */ { p_address = PACK_DATA_PBYTE(0); length = PACK_DATA_WORD(4); if (length > (DAP_PACKET_SIZE - (2))) // Check for maximum data payload result = DAP_ERROR; else while (length-- != 0) *response++ = *p_address++; } break; case HID_Command7: /* Reset device */ NVIC_SystemReset(); break; default: *(--response) = ID_DAP_Invalid; return; } *response++ = result; return; }
/******************************************************************************************************* * * 函数名称: * * 函数功能: * * 入口参数: * * 出口参数: 无 * * 说明: * *******************************************************************************************************/ int16_t DataAreaWRPUnlock(COMM_FRAME *pcf) { uint32_t wrp_state; uint8_t rv_comm_buff[20]; uint16_t wrp_unlock_param[2]; uint8_t i; uint8_t rt; uint8_t buff[20]; FlagStatus RDP_state; wrp_unlock_param[0] = MAKE_HWORD((pcf)->param[2], (pcf)->param[1]); wrp_unlock_param[1] = MAKE_HWORD((pcf)->param[4], (pcf)->param[3]); //加锁命令序列 for(i = 0; i < pcf->len - 5; i++) { rv_comm_buff[i] = pcf->param[5 + i]; } //匹配加锁命令序列 rt = MemoryCmp(rv_comm_buff, UnlockBuff, sizeof(UnlockBuff)); if(rt) { //如果匹配,进行Flash的读写解锁 FLASH_Unlock(); FLASH_OB_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_OPERR|FLASH_FLAG_WRPERR| FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); wrp_state = FLASH_OB_GetWRP(); if(!wrp_state) { do { FLASH_OB_WRPConfig(WRP_Sector_All, DISABLE); //关闭写保护 }while(FLASH_OB_Launch() != FLASH_COMPLETE); buff[1] = 0; } else { buff[1] = 1; } //发送扇区擦除错误 buff[0] = FLASH_WRP_UNLOCK_CW; SendFrame(UNIVER_ACK_CW, (uint8_t *)buff, 4); //2即2个字节,16bit __disable_irq(); if(FLASH_OB_GetRDP() == SET) { do { FLASH_OB_RDPConfig(OB_RDP_Level_0);//关闭读保护 }while(FLASH_OB_Launch() != FLASH_COMPLETE); } else { buff[0] = FLASH_WRP_UNLOCK_CW; buff[1] = 1; SendFrame(UNIVER_ACK_CW, (uint8_t *)buff, 4); //2即2个字节,16bit } //解锁之后Flash全部擦除,RAM调试会执行到下面的程序 __enable_irq(); RDP_state = FLASH_OB_GetRDP(); FLASH_OB_Lock(); FLASH_Lock(); } return 1; }
int main(void) { initHardware(); int flashy = 0; BootloaderState state = BLS_UNDEFINED; char currentCommand = 0; while (1) { if (!jshIsUSBSERIALConnected()) { setLEDs(0b0101); // reset, led off } else { int f = (flashy>>9) & 0x7F; if (f&0x40) f=128-f; setLEDs((((flashy++)&0xFF)<f) ? 4 : 0); // flash led int d = getc(); if (d>=0) { // if we have data if (state==BLS_EXPECT_DATA) { } else if (state==BLS_INITED) { currentCommand = d; state = BLS_COMMAND_FIRST_BYTE; } else if (state==BLS_COMMAND_FIRST_BYTE) { if (currentCommand == d^0xFF) { unsigned int addr,i; char chksum, buffer[256]; unsigned int nBytesMinusOne, nPages; // confirmed switch (currentCommand) { case CMD_GET: // get bootloader info putc(ACK); putc(5); // 6 bytes // now report what we support putc(BOOTLOADER_MAJOR_VERSION<<4 | BOOTLOADER_MINOR_VERSION); // Bootloader version // list supported commands putc(CMD_GET); putc(CMD_GET_ID); putc(CMD_READ); putc(CMD_WRITE); putc(CMD_EXTERASE); // erase putc(ACK); // last byte break; case CMD_GET_ID: // get chip ID putc(ACK); putc(1); // 2 bytes // now report what we support putc(0x04); // 0x30 F1 XL density // 0x14 F1 high density putc(0x30); // TODO: really? putc(ACK); // last byte break; case CMD_READ: // read memory putc(ACK); addr = getc_blocking() << 24; addr |= getc_blocking() << 16; addr |= getc_blocking() << 8; addr |= getc_blocking(); chksum = getc_blocking(); // TODO: check checksum putc(ACK); setLEDs(2); // green = wait for data nBytesMinusOne = getc_blocking(); chksum = getc_blocking(); // TODO: check checksum putc(ACK); for (i=0;i<=nBytesMinusOne;i++) putc(((unsigned char*)addr)[i]); setLEDs(0); // off break; case CMD_WRITE: // write memory putc(ACK); addr = getc_blocking() << 24; addr |= getc_blocking() << 16; addr |= getc_blocking() << 8; addr |= getc_blocking(); chksum = getc_blocking(); // TODO: check checksum and address&3==0 putc(ACK); setLEDs(2); // green = wait for data nBytesMinusOne = getc_blocking(); for (i=0;i<=nBytesMinusOne;i++) buffer[i] = getc_blocking(); chksum = getc_blocking(); // FIXME found to be stalled here setLEDs(1); // red = write // TODO: check checksum and (nBytesMinusOne+1)&3==0 #ifdef STM32API2 FLASH_Unlock(); #else FLASH_UnlockBank1(); #endif #if defined(STM32F2) || defined(STM32F4) FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); #elif defined(STM32F3) FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); #else FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); #endif for (i=0;i<=nBytesMinusOne;i+=4) { unsigned int realaddr = addr+i; if (realaddr >= (FLASH_START+BOOTLOADER_SIZE)) // protect bootloader FLASH_ProgramWord(realaddr, *(unsigned int*)&buffer[i]); } #ifdef STM32API2 FLASH_Lock(); #else FLASH_LockBank1(); #endif setLEDs(0); // off putc(ACK); // TODO - could speed up writes by ACKing beforehand if we have space break; case CMD_EXTERASE: // erase memory putc(ACK); nPages = getc_blocking() << 8; nPages |= getc_blocking(); chksum = getc_blocking(); // TODO: check checksum if (nPages == 0xFFFF) { // all pages (except us!) setLEDs(1); // red = write #ifdef STM32API2 FLASH_Unlock(); #else FLASH_UnlockBank1(); #endif #if defined(STM32F2) || defined(STM32F4) FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); #elif defined(STM32F3) FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); #else FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); #endif for (i=BOOTLOADER_SIZE;i<FLASH_TOTAL;i+=FLASH_PAGE_SIZE) { setLEDs(1 << (i%3)); // R,G,B,etc FLASH_ErasePage((uint32_t)(FLASH_START + i)); } #ifdef STM32API2 FLASH_Lock(); #else FLASH_LockBank1(); #endif setLEDs(0); // off putc(ACK); } else { putc(NACK); // not implemented } break; default: // unknown command putc(NACK); break; } } else { // not correct putc(NACK); } state = BLS_INITED; } else { switch (d) { case 0x7F: // initialisation byte putc(state == BLS_UNDEFINED ? ACK : NACK); state = BLS_INITED; break; } } } } } }
/** * @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_stm32f30x.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32f30x.c file */ /* Unlock the Flash to enable the flash control register access *************/ FLASH_Unlock(); /* Erase the user Flash area (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ /* Clear pending flags (if any) */ FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); /* Define the number of page to be erased */ NbrOfPage = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR) / FLASH_PAGE_SIZE; /* Erase the FLASH pages */ for(EraseCounter = 0; (EraseCounter < NbrOfPage) && (FLASHStatus == FLASH_COMPLETE); EraseCounter++) { if (FLASH_ErasePage(FLASH_USER_START_ADDR + (FLASH_PAGE_SIZE * EraseCounter))!= FLASH_COMPLETE) { /* Error occurred while sector erase. User can add here some code to deal with this error */ while (1) { } } } /* Program the user Flash area word by word (area defined by FLASH_USER_START_ADDR and FLASH_USER_END_ADDR) ***********/ Address = FLASH_USER_START_ADDR; while (Address < FLASH_USER_END_ADDR) { if (FLASH_ProgramWord(Address, DATA_32) == FLASH_COMPLETE) { Address = Address + 4; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ while (1) { } } } /* Lock the Flash to disable the flash control register access (recommended to protect the FLASH memory against possible unwanted operation) *********/ FLASH_Lock(); /* Check if the programmed data is OK MemoryProgramStatus = 0: data programmed correctly MemoryProgramStatus != 0: number of words not programmed correctly ******/ Address = FLASH_USER_START_ADDR; MemoryProgramStatus = PASSED; while (Address < FLASH_USER_END_ADDR) { Data = *(__IO uint32_t *)Address; if (Data != DATA_32) { MemoryProgramStatus = FAILED; } Address = Address + 4; } /* Infinite loop */ while (1) { } }
int loader(void) { uint32_t i, from, to; uint32_t erased_sectors = 0; for (i=0; i < PARAMS_LEN ; i+=4) { // Clear parameters mmio32(PARAMS_ADDR+i) = 0; } FLASH_SetLatency(FLASH_Latency_0); while (1) { asm volatile ("bkpt"); // Halt core after init and before writing to flash. asm volatile ("nop"); PARAMS->STATUS &= ~MASK_STRT; // Clear start bit PARAMS->STATUS &= ~MASK_ERR; // Clear error bit PARAMS->STATUS &= ~MASK_SUCCESS; // Clear success bit PARAMS->STATUS &= ~MASK_DEL; // Clear delete success bit PARAMS->POS = PARAMS->DEST; FLASH_Unlock(); from = PARAMS->DEST; to = from + PARAMS->LEN; uint32_t a; // Erase flash where needed #if defined(STM32F2) || defined(STM32F4) FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); // Get the number of the start and end sectors const uint32_t StartSector = GetSector(from); const uint32_t EndSector = GetSector(to-1); for (a = StartSector ; a <= EndSector ; a+=8) { if (erased_sectors & (1 << a/8)) continue; // Skip sectors already erased if (FLASH_EraseSector(a, VoltageRange_3) != FLASH_COMPLETE) { PARAMS->STATUS |= MASK_ERR; break; } erased_sectors |= 1 << a/8; PARAMS->STATUS |= MASK_DEL; // Set delete success bit } #else FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR); uint32_t NbrOfPage = (to - from - 1) / FLASH_PAGE_SIZE; for (a = 0 ; a <= NbrOfPage ; a++) { if (erased_sectors >= from + (FLASH_PAGE_SIZE * a)) continue; // Skip sectors already erased if (FLASH_ErasePage(from + (FLASH_PAGE_SIZE * a))!= FLASH_COMPLETE) { PARAMS->STATUS |= MASK_ERR; break; } erased_sectors = from + (FLASH_PAGE_SIZE * a); PARAMS->STATUS |= MASK_DEL; // Set delete success bit } #endif if (PARAMS->STATUS & MASK_ERR) { // If error during page delete, go back to breakpoint FLASH_Lock(); continue; } // Flash programming uint32_t i=0; while (i < PARAMS->LEN) { if (FLASH_PGM(PARAMS->DEST+i, mmio32(BUFFER_ADDR+i)) == FLASH_COMPLETE) { i+=FLASH_STEP; PARAMS->STATUS |= MASK_SUCCESS; // Set success bit PARAMS->POS = PARAMS->DEST+i; } else { /* Error occurred while writing data in Flash memory. User can add here some code to deal with this error */ PARAMS->STATUS |= MASK_ERR; // Set error bit break; } } PARAMS->TEST = PARAMS->DEST+i; FLASH_Lock(); // Lock flash after operations are done. } return 0; }
uint8_t writeEEPROM(void) { FLASH_Status status; int32_t i; /////////////////////////////////// if (eepromConfig.receiverType == SPEKTRUM) { USART_Cmd(USART6, DISABLE); TIM_Cmd(TIM6, DISABLE); if (eepromConfig.slaveSpektrum == true) USART_Cmd(UART4, DISABLE); } /////////////////////////////////// eepromConfig_t *src = &eepromConfig; uint32_t *dst = (uint32_t*)FLASH_WRITE_EEPROM_ADDR; // there's no reason to write these values to EEPROM, they'll just be noise zeroPIDintegralError(); zeroPIDstates(); if ( src->CRCFlags & CRC_HistoryBad ) evrPush(EVR_ConfigBadHistory,0); src->CRCAtEnd[0] = crc32B( (uint32_t*)&src[0], src->CRCAtEnd); FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); status = FLASH_EraseSector(FLASH_Sector_1, VoltageRange_3); /////////////////////////////////// i = -1; while ( FLASH_COMPLETE == status && i++ < eepromConfigNUMWORD ) status = FLASH_ProgramWord((uint32_t)&dst[i], ((uint32_t*)src)[i]); if ( FLASH_COMPLETE != status ) evrPush( -1 == i ? EVR_FlashEraseFail : EVR_FlashProgramFail, status); /////////////////////////////////// FLASH_Lock(); readEEPROM(); if (eepromConfig.receiverType == SPEKTRUM) { primarySpektrumState.reSync = 1; TIM_Cmd(TIM6, ENABLE); USART_Cmd(USART6, ENABLE); if (eepromConfig.slaveSpektrum == true) { slaveSpektrumState.reSync = 1; USART_Cmd(UART4, ENABLE); } } /////////////////////////////////// return status; }
/** * @brief lock * @param None * @retval None */ void Flash_PageWriteDone(void) { FLASH_Lock(); }
u8 PWS_EraseSlot (u8 Slot_u8) { u8* WritePointer_pu8; u8* AesKeyPointer_pu8; void* p; #if (defined __GNUC__) && (defined __AVR32__) __attribute__ ((__aligned__ (4))) #elif (defined __ICCAVR32__) #pragma data_alignment = 4 #endif typePasswordSafeSlot_st Slot_st; CI_LocalPrintf ("PWS_EraseSlot: Slot %d\r\n", Slot_u8); if (PWS_SLOT_COUNT <= Slot_u8) { CI_LocalPrintf ("PWS_EraseSlot: Wrong slot nr %d\r\n", Slot_u8); return (FALSE); } // Check for unlock if (FALSE == PWS_GetDecryptedPasswordSafeKey (&AesKeyPointer_pu8)) { CI_LocalPrintf ("PWS_EraseSlot: user password not entered\r\n"); return (FALSE); } // //LED_GreenOn (); // Clear data in slot memset ((char *) &Slot_st, 0, PWS_SLOT_LENGTH); Slot_st.SlotActiv_u8 = PWS_SLOT_INACTIV_TOKEN; #ifdef ENABLE_IBN_PWS_TESTS_ENCRYPTION CI_LocalPrintf ("PWS_EraseSlot decrypted : "); HexPrint (PWS_SLOT_LENGTH, &Slot_st); CI_LocalPrintf ("\n\r"); #endif // Encrypt data (max 256 byte per encryption) unsigned char Slot_st_encrypted[PWS_SLOT_LENGTH]; aes_context aes_ctx; aes_setkey_enc (&aes_ctx, AesKeyPointer_pu8, 256); int i; for (i = 0; i < PWS_SLOT_LENGTH; i += 16) { aes_crypt_ecb (&aes_ctx, AES_ENCRYPT, &(((unsigned char *) (&Slot_st))[i]), &(Slot_st_encrypted[i])); } memcpy ((char *) &Slot_st, Slot_st_encrypted, PWS_SLOT_LENGTH); #ifdef ENABLE_IBN_PWS_TESTS_ENCRYPTION CI_LocalPrintf ("PWS_EraseSlot encrypted : "); HexPrint (PWS_SLOT_LENGTH, Slot_st_encrypted); CI_LocalPrintf ("\n\r"); #endif // Get write address WritePointer_pu8 = (u8 *) (PWS_FLASH_START_ADDRESS + (PWS_SLOT_LENGTH * Slot_u8)); // Write to flash uint8_t page_buffer[FLASH_PAGE_SIZE]; uint8_t* page = (uint8_t *) PWS_FLASH_START_ADDRESS; memcpy (page_buffer, page, FLASH_PAGE_SIZE); memcpy (page_buffer + (PWS_SLOT_LENGTH * Slot_u8), Slot_st_encrypted, PWS_SLOT_LENGTH); p = (void *) Slot_st_encrypted; FLASH_Unlock (); FLASH_ErasePage (PWS_FLASH_START_ADDRESS); write_data_to_flash (page_buffer, FLASH_PAGE_SIZE, PWS_FLASH_START_ADDRESS); FLASH_Lock (); // LED_GreenOff (); return (TRUE); }
int main() { motor_running=0; updateCtr=0; dir=1; FLASH_Unlock(); getConfig(); FLASH_Lock(); initUSART(s.usart_baud); printConfiguration(); initPWM(); initADC(); if( s.commutationMethod == commutationMethod_HALL) { initHALL(); } if(s.inputMethod == inputMethod_stepDir) { initStepDirInput(); } else if (s.inputMethod == inputMethod_pwmVelocity) { initPWMInput(); } if(s.inputMethod == inputMethod_stepDir || s.commutationMethod == commutationMethod_Encoder) { initEncoder(); } if(s.inputMethod == inputMethod_stepDir) { initPid(); } initLeds(); // errorInCommutation=1; uint8_t ena; //check if ENA is on already at start. If it is, start motor. #if ENA_POLARITY == 1 ena = GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5); #else ena = (~(GPIO_ReadInputDataBit(GPIOA, GPIO_Pin_5)))&1; #endif if(ena) { pwm_motorStart(); ENABLE_LED_ON; } //two different types of main loops depending on commutation method if(s.commutationMethod == commutationMethod_Encoder) { while (1) { getEncoderCount(); if(encoder_commutation_pos != encoder_commutation_table[encoder_shaft_pos]) { //usart_sendStr("commutation to "); //usart_sendChar(encoder_commutation_table[encoder_shaft_pos]+48); encoder_commutation_pos = encoder_commutation_table[encoder_shaft_pos]; pwm_Commute(encoder_commutation_pos); // usart_sendStr("\n\r"); } } } else { while(1) { } } }
void Test_Flash() { uint8_t i = 0; uint16_t flash_flag = 0; flash_flag = *(uint16_t *)FLASH_READY_ADDRESS; if( flash_flag != FLAG_FLASH_READY) { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); //Erase the 32 page 32K for(i = 0;i< DATA_PAGES;i++) { FLASH_ErasePage(DATA_LOGGER_ADDRESS_START + i * 1024); } FLASH_ErasePage(FLASH_READY_ADDRESS); FLASH_ProgramHalfWord(FLASH_READY_ADDRESS , FLAG_FLASH_READY); FLASH_ErasePage(REOCRD_COUNT_ADDRESS); FLASH_ProgramHalfWord(REOCRD_COUNT_ADDRESS , 0x0000); FLASH_Lock(); } flash_flag = *(uint16_t *)FLASH_READY_ADDRESS; if( flash_flag != FLAG_FLASH_READY) { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); //Erase the 32 page 32K for(i = 0;i< DATA_PAGES;i++) { FLASH_ErasePage(DATA_LOGGER_ADDRESS_START + i * 1024); } FLASH_ErasePage(FLASH_READY_ADDRESS); FLASH_ProgramHalfWord(FLASH_READY_ADDRESS , FLAG_FLASH_READY); FLASH_ErasePage(REOCRD_COUNT_ADDRESS); FLASH_ProgramHalfWord(REOCRD_COUNT_ADDRESS , 0x0000); FLASH_Lock(); } while(1) { record_count = *(uint16_t *)REOCRD_COUNT_ADDRESS; FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); FLASH_ProgramHalfWord(DATA_LOGGER_ADDRESS_START + record_count * 2, 0xABCD); //Erase first FLASH_ErasePage(REOCRD_COUNT_ADDRESS); //Update the count record_count = record_count + 1; FLASH_ProgramHalfWord(REOCRD_COUNT_ADDRESS , record_count); FLASH_Lock(); Delay(3); } }
/** * @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_stm32l1xx_xx.s) before to branch to application main. To reconfigure the default setting of SystemInit() function, refer to system_stm32l1xx.c file */ /* Set the vector table address */ #if defined(BOOT_FROM_BANK1) /* Set the vector table to the Bank1 start address */ NVIC_SetVectorTable(NVIC_VectTab_FLASH, BANK1_START_ADDRESS); #elif defined(BOOT_FROM_BANK2) /* Set the vector table to the Bank1 start address */ NVIC_SetVectorTable(NVIC_VectTab_FLASH, BANK2_START_ADDRESS); #endif /* BOOT_FROM_BANK1 */ /* Initialize LEDs, Buttons and LCD on STM32L152D-EVAL board ****************/ STM_EVAL_LEDInit(LED1); STM_EVAL_LEDInit(LED2); STM_EVAL_LEDInit(LED3); STM_EVAL_LEDInit(LED4); /* Save the first BANK1 page */ FLASH_SaveBANK1(); /* Save the first BANK2 page */ FLASH_SaveBANK2(); /* SysTick end of count event each 10ms */ RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(RCC_Clocks.HCLK_Frequency / 100); /* Configure the Joystick buttons */ STM_EVAL_PBInit(BUTTON_UP, BUTTON_MODE_GPIO); STM_EVAL_PBInit(BUTTON_SEL, BUTTON_MODE_GPIO); STM_EVAL_PBInit(BUTTON_DOWN, BUTTON_MODE_GPIO); STM_EVAL_PBInit(BUTTON_RIGHT, BUTTON_MODE_GPIO); STM_EVAL_PBInit(BUTTON_LEFT, BUTTON_MODE_GPIO); /* Initialize the LCD */ STM32L152D_LCD_Init(); /* Display message on STM32L152D-EVAL LCD ************************************/ /* Clear the LCD */ LCD_Clear(LCD_COLOR_WHITE); /* Set the LCD Back Color */ #if defined(BOOT_FROM_BANK1) LCD_SetBackColor(LCD_COLOR_BLUE); #elif defined(BOOT_FROM_BANK2) LCD_SetBackColor(LCD_COLOR_RED); #endif /* BOOT_FROM_BANK1 */ /* Set the LCD Text Color */ LCD_SetTextColor(LCD_COLOR_WHITE); LCD_DisplayStringLine(LCD_LINE_0, MESSAGE1); LCD_DisplayStringLine(LCD_LINE_1, MESSAGE2); LCD_DisplayStringLine(LCD_LINE_2, MESSAGE3); LCD_DisplayStringLine(LCD_LINE_4, MESSAGE4); LCD_SetFont(&Font12x12); LCD_SetTextColor(LCD_COLOR_GREEN); LCD_DisplayStringLine(LCD_LINE_10, MESSAGE5); LCD_DisplayStringLine(LCD_LINE_11, MESSAGE6); LCD_SetTextColor(LCD_COLOR_WHITE); LCD_DisplayStringLine(LCD_LINE_12, MESSAGE7); LCD_DisplayStringLine(LCD_LINE_13, MESSAGE8); LCD_SetTextColor(LCD_COLOR_GREEN); LCD_DisplayStringLine(LCD_LINE_14, MESSAGE9); LCD_DisplayStringLine(LCD_LINE_15, MESSAGE10); LCD_SetTextColor(LCD_COLOR_WHITE); LCD_DisplayStringLine(LCD_LINE_16, MESSAGE11); LCD_DisplayStringLine(LCD_LINE_17, MESSAGE12); LCD_SetTextColor(LCD_COLOR_GREEN); LCD_DisplayStringLine(LCD_LINE_18, MESSAGE13); LCD_DisplayStringLine(LCD_LINE_19, MESSAGE14); LCD_SetTextColor(LCD_COLOR_WHITE); LCD_SetFont(&Font16x24); /* Turn on leds available on STM32L152D-EVAL ************************************/ STM_EVAL_LEDOn(LED1); STM_EVAL_LEDOn(LED2); STM_EVAL_LEDOn(LED3); STM_EVAL_LEDOn(LED4); /* Infinite loop */ while (1) { /*--- If Joystick DOWN button is pushed, reset BFB2 bit to enable boot from Bank2 (active after next reset, w/ Boot pins set in Boot from Flash memory position ---*/ if (STM_EVAL_PBGetState(BUTTON_DOWN) == 0) { /* Reset BFB2 bit to enable boot from Flash Bank2 */ FLASH_Unlock(); FLASH_OB_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_OPTVERRUSR); FLASH_OB_UserConfig(OB_IWDG_SW, OB_STOP_NoRST, OB_STDBY_NoRST); FLASH_OB_BORConfig(OB_BOR_LEVEL1); if (FLASH_OB_BootConfig(OB_BOOT_BANK2) == FLASH_COMPLETE) { /* Generate System Reset to load the new option byte values */ FLASH_OB_Launch(); } else { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE15); } } /*--- If Joystick UP button is pushed, set BFB2 bit to enable boot from Bank1 (active after next reset, w/ Boot pins set in Boot from Flash memory position ---*/ if (STM_EVAL_PBGetState(BUTTON_UP) == 0) { /* Set BFB2 bit to enable boot from Flash Bank2 */ FLASH_Unlock(); FLASH_OB_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_OPTVERRUSR); FLASH_OB_UserConfig(OB_IWDG_SW, OB_STOP_NoRST, OB_STDBY_NoRST); FLASH_OB_BORConfig(OB_BOR_LEVEL1); if (FLASH_OB_BootConfig(OB_BOOT_BANK1) == FLASH_COMPLETE) { /* Generate System Reset to load the new option byte values */ FLASH_OB_Launch(); } else { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE15); } } /*--- If Joystick LEFT button is pushed, program the content of address 0x08000000 (base address of Bank1) to 0x00 ---*/ if (STM_EVAL_PBGetState(BUTTON_LEFT) == 0) { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_OPTVERRUSR); /* Erase stack pointer value at Bank 1 start address */ FLASH_ErasePage(0x08000000); FLASH_Lock(); LCD_ClearLine(LCD_LINE_5); LCD_ClearLine(LCD_LINE_7); LCD_ClearLine(LCD_LINE_8); LCD_ClearLine(LCD_LINE_9); /* Check if erase operation is OK */ if ((uint32_t)(*(uint32_t *)BANK1_START_ADDRESS) != 0x00) { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE15); } else { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE16); } } /*--- If Joystick RIGHT button is pushed, program the content of address 0x08030000 (base address of Bank2) to 0x00 ---*/ if (STM_EVAL_PBGetState(BUTTON_RIGHT) == 0) { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_OPTVERRUSR); /* Erase stack pointer value at Bank 2 start address */ FLASH_ErasePage(0x08030000); FLASH_Lock(); LCD_ClearLine(LCD_LINE_5); LCD_ClearLine(LCD_LINE_7); LCD_ClearLine(LCD_LINE_8); LCD_ClearLine(LCD_LINE_9); /* Check if erase operation is OK */ if ((uint32_t)(*(uint32_t *)BANK2_START_ADDRESS) != 0x00) { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE15); } else { /* Display information */ LCD_DisplayStringLine(LCD_LINE_6, MESSAGE16); } } /*--- If Joystick UP button is pushed, copy the program to the cross bank --*/ if (STM_EVAL_PBGetState(BUTTON_SEL) == 0) { FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP|FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR | FLASH_FLAG_OPTVERRUSR); #if defined (BOOT_FROM_BANK1) /* Erase one page in BANK2 to store the first page */ FLASH_ErasePage(0x08030000); for(index = 0; index < 64; index++) { FLASH_FastProgramWord((0x08030000 + (index * 4)), (*(uint32_t *)(0x08020000 + (index * 4)))); } #elif defined (BOOT_FROM_BANK2) /* Erase one page in BANK1 to store the first page */ FLASH_ErasePage(0x08000000); for(index = 0; index < 64; index++) { FLASH_FastProgramWord((0x08000000 + (index * 4)), (*(uint32_t *)(0x08050000 + (index * 4)))); } #endif } /* Toggle LD3 */ STM_EVAL_LEDToggle(LED3); /* Insert 50 ms delay */ Delay(5); /* Toggle LD2 */ STM_EVAL_LEDToggle(LED2); /* Insert 100 ms delay */ Delay(10); } }
int main() { PIOS_SYS_Init(); PIOS_Board_Init(); PIOS_LED_On(PIOS_LED_HEARTBEAT); PIOS_DELAY_WaitmS(3000); PIOS_LED_Off(PIOS_LED_HEARTBEAT); /// Self overwrite check uint32_t base_address = SCB->VTOR; if ((0x08000000 + embedded_image_size) > base_address) error(PIOS_LED_HEARTBEAT, 1); /// /* * Make sure the bootloader we're carrying is for the same * board type and board revision as the one we're running on. * * Assume the bootloader in flash and the bootloader contained in * the updater both carry a board_info_blob at the end of the image. */ /* Calculate how far the board_info_blob is from the beginning of the bootloader */ uint32_t board_info_blob_offset = (uint32_t) &pios_board_info_blob - (uint32_t)0x08000000; /* Use the same offset into our embedded bootloader image */ struct pios_board_info * new_board_info_blob = (struct pios_board_info *) ((uint32_t)embedded_image_start + board_info_blob_offset); /* Compare the two board info blobs to make sure they're for the same HW revision */ if ((pios_board_info_blob.magic != new_board_info_blob->magic) || (pios_board_info_blob.board_type != new_board_info_blob->board_type) || (pios_board_info_blob.board_rev != new_board_info_blob->board_rev)) { error(PIOS_LED_HEARTBEAT, 2); } /* Embedded bootloader looks like it's the right one for this HW, proceed... */ FLASH_Unlock(); /// Bootloader memory space erase uint32_t pageAddress; pageAddress = 0x08000000; bool fail = false; while ((pageAddress < base_address) && (fail == false)) { for (int retry = 0; retry < MAX_DEL_RETRYS; ++retry) { if (FLASH_ErasePage(pageAddress) == FLASH_COMPLETE) { fail = false; break; } else { fail = true; } } #ifdef STM32F10X_HD pageAddress += 2048; #elif defined (STM32F10X_MD) pageAddress += 1024; #endif } if (fail == true) error(PIOS_LED_HEARTBEAT, 3); /// /// Bootloader programing for (uint32_t offset = 0; offset < embedded_image_size / sizeof(uint32_t); ++offset) { bool result = false; PIOS_LED_Toggle(PIOS_LED_HEARTBEAT); for (uint8_t retry = 0; retry < MAX_WRI_RETRYS; ++retry) { if (result == false) { result = (FLASH_ProgramWord(0x08000000 + (offset * 4), embedded_image_start[offset]) == FLASH_COMPLETE) ? true : false; } } if (result == false) error(PIOS_LED_HEARTBEAT, 4); } /// for (uint8_t x = 0; x < 3; ++x) { PIOS_LED_On(PIOS_LED_HEARTBEAT); PIOS_DELAY_WaitmS(1000); PIOS_LED_Off(PIOS_LED_HEARTBEAT); PIOS_DELAY_WaitmS(1000); } /// Invalidate the bootloader updater so we won't run /// the update again on the next power cycle. FLASH_ProgramWord(base_address, 0); FLASH_Lock(); for (;;) { PIOS_DELAY_WaitmS(1000); } }
void FLASH_ProgramDone(void) { FLASH_Lock(); }
/****************************************************************************** * Function Name : STM_Flash_WriteSector * Description : This routine is for writing one or several 512 Bytes Page size. * Input : u8 *pBuffer, DWORD uwSector, u32 ulNumSectorWrite * Output : None * Return : *******************************************************************************/ u32 STM_Flash_WriteSector(u8 *pBuffer, DWORD uwSector, u32 ulNumSectorWrite) { FLASH_Status status = FLASH_COMPLETE; u32 STMFlashStatus = STM_FLASH_SUCCESS; u32 Address; u32 index, data, data32; /* Unlock the Flash Program Erase controller */ FLASH_Unlock(); /* Clear All pending flags */ FLASH_ClearFlag(FLASH_FLAG_BSY | FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); while( (ulNumSectorWrite != 0x00) && (STMFlashStatus != STM_FLASH_INVALID_ADDRESS) ) { Address = STM32_FLASH_ADDR + (STM32_PAGE_SIZE * STM32_START_PAGE) + STM_FLASH_SECTOR_SIZE * uwSector; for(index=0; index < STM_FLASH_SECTOR_SIZE; index++) { data32 = *pBuffer++; switch(index%4) { case 0: data = ( data32 << 0 ) & 0x000000FF; break; case 1: data += ( data32 << 8 ) & 0x0000FF00; break; case 2: data += ( data32 << 16) & 0x00FF0000; break; case 3: data += ( data32 << 24) & 0xFF000000; if(data != 0) { data = data; } status = FLASH_ProgramWord(Address, data); Address += 4; if(status != FLASH_COMPLETE) { FLASH_Lock(); return STM_FLASH_ERROR; } break; default: break; } } ulNumSectorWrite--; if(ulNumSectorWrite != 0) { uwSector++; /* Calculate Next Sector Address */ if(uwSector >= (u32)(STM_FLASH_MAX_ZONE*STM_FLASH_ZONE_SIZE*STM_FLASH_BLOCK_SIZE)) STMFlashStatus = STM_FLASH_INVALID_ADDRESS; } } FLASH_Lock(); return STMFlashStatus; }
/** * @brief Receive a file using the ymodem protocol * @param buf: Address of the first byte * @retval The size of the file */ int32_t Ymodem_Receive (uint8_t *buf) { uint8_t packet_data[PACKET_1KB_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr; int32_t i, j, packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0; /* Initialize FlashDestination variable */ FlashDestination = ApplicationAddress; Send_Byte(CRC16); for (session_done = 0, errors = 0, session_begin = 0; ;) { for (packets_received = 0, file_done = 0, buf_ptr = buf; ;) { switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT)) { case 0://成功收到数据 // errors = 0; switch (packet_length) { /* Abort by sender */ case - 1://接收失败 Send_Byte(ACK); return 0; /* End of transmission */ case 0://本次文件传送结束 Send_Byte(ACK); file_done = 1; break; /* Normal packet */ default://接收成功 if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff)) { Send_Byte(NAK); } else { if (packets_received == 0)//文件信息(首包) { /* Filename packet */ if (packet_data[PACKET_HEADER] != 0)//文件名字 { /* Filename packet has valid data */ for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);) { file_name[i++] = *file_ptr++;//保存文件名字 } file_name[i++] = '\0';//字符串形式 for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);) { file_size[i++] = *file_ptr++;//文件大小 } file_size[i++] = '\0'; Str2Int(file_size, &size); /* Test the size of the image to be sent */ /* Image size is greater than Flash size */ if (size > (FLASH_SIZE - 1)) { /* End session */ Send_Byte(CA); Send_Byte(CA); return -1; } /* Erase the needed pages where the user application will be loaded */ /* Define the number of page to be erased */ if(EraseSomePages(size, 0)) { } else { /* End session */ Send_Byte(CA); Send_Byte(CA); return -1; //Erase failed } Send_Byte(ACK); Send_Byte(CRC16); } /* Filename packet is empty, end session */ else { Send_Byte(ACK); file_done = 1; session_done = 1; break; } } /* Data packet */ else//文件信息保存完之后开始接收数据 { memcpy(buf_ptr, packet_data + PACKET_HEADER, packet_length); RamSource = (uint32_t)buf; for (j = 0;(j < packet_length) && (FlashDestination < ApplicationAddress + size);j += 4) { /* Program the data received into STM32F10x Flash */ FLASH_Unlock(); FLASH_ProgramWord(FlashDestination, *(uint32_t*)RamSource); FLASH_Lock(); if (*(uint32_t*)FlashDestination != *(uint32_t*)RamSource) { /* End session */ Send_Byte(CA); Send_Byte(CA); return -2; } FlashDestination += 4; RamSource += 4; } Send_Byte(ACK); } packets_received ++; session_begin = 1; } } break; case 1://用户按下了'a'或'A' Send_Byte(CA); Send_Byte(CA); return -3; default://检查错误 if (session_begin > 0) { errors ++; } if (errors > MAX_ERRORS) { Send_Byte(CA); Send_Byte(CA); return 0; } Send_Byte(CRC16);//发送校验值 break; } if (file_done != 0) { break; } } if (session_done != 0)//文件发送完成 { break; } } return (int32_t)size; }