static void getOnePieceOfRoomInfo(uint8_t index, uint8_t* buff) { uint32_t addr = getFlashAddress(index); uint16_t tmpCRC[2] = {0, 0}; stRoomInfo tmpInfo[2]; memset((uint8_t *)&tmpInfo[0], 0, sizeof(stRoomInfo)); memset((uint8_t *)&tmpInfo[1], 0, sizeof(stRoomInfo)); Flash_Read((uint8_t *)&tmpInfo[0], addr, sizeof(stRoomInfo)); Flash_Read((uint8_t *)&tmpInfo[1], addr + FLASH_SECTOR_SIZE, sizeof(stRoomInfo)); tmpCRC[0] = CRC16((uint8_t *)&tmpInfo[0], sizeof(stRoomInfo) - sizeof(uint16_t)); tmpCRC[1] = CRC16((uint8_t *)&tmpInfo[1], sizeof(stRoomInfo) - sizeof(uint16_t)); if ((tmpCRC[0] == tmpInfo[0].crc) && (tmpCRC[1]== tmpInfo[1].crc)) { memcpy(buff, (uint8_t *)&tmpInfo[0], sizeof(stRoomInfo)); } else if(tmpCRC[0] == tmpInfo[0].crc) { memcpy(buff, (uint8_t *)&tmpInfo[0], sizeof(stRoomInfo)); } else if(tmpCRC[1]== tmpInfo[1].crc) { memcpy(buff, (uint8_t *)&tmpInfo[1], sizeof(stRoomInfo)); } else { bitMapFlashDateError |= (1 << index); } }
void If_WriteFirmware(void) { Flash_Init(); if (1) { UINT32 ReadAddrOffset, AddrBase, DataSize, i; PBYTE pOriginalData; UINT32 usLength; if (1) { // Write data to flash AddrBase = WIFI_FW_HELPER_ADDR; Flash_Write (AddrBase, (UINT8*)helperimage, sizeof (helperimage)); // Read back data for checking... ReadAddrOffset = 0; pOriginalData = (PBYTE)helperimage; DataSize = sizeof (helperimage); while (ReadAddrOffset < DataSize) { if (ReadAddrOffset + FLASH_PAGE_SIZE < DataSize) usLength = FLASH_PAGE_SIZE; else usLength = DataSize - ReadAddrOffset; Flash_Read(AddrBase + ReadAddrOffset, ucBuffer, usLength); for (i = 0; i < usLength; i ++) { if (ucBuffer[i] != pOriginalData[ReadAddrOffset + i]) break; } if (i != usLength) TRACE("Data Verify failed1!\r\n"); ReadAddrOffset += usLength; } } if (1) { // Write data to flash AddrBase = WIFI_FW_FW_ADDR; Flash_Write (AddrBase, (UINT8*)fmimage, sizeof (fmimage)); // Read back data for checking... ReadAddrOffset = 0; pOriginalData = (PBYTE)fmimage; DataSize = sizeof (fmimage); while (ReadAddrOffset < DataSize) { if (ReadAddrOffset + FLASH_PAGE_SIZE < DataSize) usLength = FLASH_PAGE_SIZE; else usLength = DataSize - ReadAddrOffset; Flash_Read(AddrBase + ReadAddrOffset, ucBuffer, usLength); for (i = 0; i < usLength; i ++) { if (ucBuffer[i] != pOriginalData[ReadAddrOffset + i]) break; } if (i != usLength) TRACE("Data Verify failed1!2\r\n"); ReadAddrOffset += usLength; } } } while (1); }
/** * @brief ½«²ÎÊýдÈëFLASHÖÐ * * @param b:ÊÇ·ñÓÐLEDÌáʾ * @retval none */ void Flash_WriteParams(uint8_t b) { FLASH_Status status; uint32_t i; FLASH_Unlock(); FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGPERR | FLASH_FLAG_WRPERR); // //if (FLASH_ErasePage(FLASH_WRITE_ADDR) == FLASH_COMPLETE) if(FLASH_EraseSector(FLASH_WRITE_SECTOR, VoltageRange_3) == FLASH_COMPLETE) { for (i = 0; i < sizeof(config_t); i += 4) { status = FLASH_ProgramWord(FLASH_WRITE_ADDR + i, *(uint32_t *) ((char *) &cfg + i)); if (status != FLASH_COMPLETE) { System_FailureMode(1); break; // TODO: fail } } } else System_FailureMode(1); FLASH_Lock(); Flash_Read(); }
DCI_END_MSGMAP //******************************************************* // Common Module Interface Implementation //******************************************************* /** * Initialization */ void Flash_Init( ) { BYTE cmd; BYTE id[32]; byte image[256]; // For testing only. int ec; int i; main_AddDciMsgMap( s_flashmap); /*---- wait for power up before accessing flash ----*/ Timer_Delay( 10000 ); /*---- read memory ID (doesn't work on M25P80) ----*/ cmd = READ_ID; ec = SPI_WriteReadData( SPI_DEVICE_FLASH, 1, &cmd, 3, id, FALSE ); // Debug read of first block. ec = Flash_Read( 0lu, 256, image ); }
/** * @brief Programs a half word at a specified Option Byte Data address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * @param buf: specifies the data to be programmed. * @param iNbrToWrite: the number to write into flash * @retval if success return the number to write, -1 if error * */ int Flash_Write(uint32_t iAddress, uint8_t *buf, uint32_t iNbrToWrite) { /* Unlock the Flash Bank1 Program Erase controller */ uint32_t secpos; uint32_t iNumByteToWrite = iNbrToWrite; uint16_t secoff; uint16_t secremain; uint16_t i = 0; uint8_t tmp[FLASH_PAGE_SIZE]; FLASH_UnlockBank1(); secpos=iAddress & (~(FLASH_PAGE_SIZE -1 )) ;//扇区地址 secoff=iAddress & (FLASH_PAGE_SIZE -1); //在扇区内的偏移 secremain=FLASH_PAGE_SIZE-secoff; //扇区剩余空间大小 volatile FLASH_Status FLASHStatus = FLASH_COMPLETE; if(iNumByteToWrite<=secremain) secremain = iNumByteToWrite;//不大于4096个字节 while( 1 ) { Flash_Read(secpos, tmp, FLASH_PAGE_SIZE); //读出整个扇区 for(i=0;i<secremain;i++) { //校验数据 if(tmp[secoff+i]!=0XFF)break; //需要擦除 } if(i<secremain) { //需要擦除 FLASHStatus = FLASH_ErasePage(secpos); //擦除这个扇区 if(FLASHStatus != FLASH_COMPLETE) return -1; for(i=0;i<secremain;i++) //复制 { tmp[i+secoff]=buf[i]; } Flash_Write_Without_check(secpos ,tmp ,FLASH_PAGE_SIZE);//写入整个扇区 } else { Flash_Write_Without_check(iAddress,buf,secremain);//写已经擦除了的,直接写入扇区剩余区间. } if(iNumByteToWrite==secremain) //写入结束了 { break; } else { secpos += FLASH_PAGE_SIZE; secoff = 0;//偏移位置为0 buf += secremain; //指针偏移 iAddress += secremain;//写地址偏移 iNumByteToWrite -= secremain; //字节数递减 if(iNumByteToWrite>FLASH_PAGE_SIZE) secremain=FLASH_PAGE_SIZE;//下一个扇区还是写不完 else secremain = iNumByteToWrite; //下一个扇区可以写完了 } } FLASH_LockBank1(); return iNbrToWrite; }
// Init void Flash_Init(void){ FMC->PFB0CR|=FMC_PFB0CR_S_B_INV_MASK; FMC->PFB1CR|=FMC_PFB0CR_S_B_INV_MASK; while(!(FTFL->FSTAT&FTFL_FSTAT_CCIF_MASK)); FTFL->FSTAT=FTFL_FSTAT_ACCERR_MASK|FTFL_FSTAT_FPVIOL_MASK; // check data_flag if(Flash_Read(0,0)!=1) Flash_Data_Reset(); else Flash_Data_Update(0); }
/** * @brief Programs a half word at a specified Option Byte Data address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * @param buf: specifies the data to be programmed. * @param iNbrToWrite: the number to write into flash * @retval if success return the number to write, -1 if error * */ int Flash_Write(uint32_t iAddress, uint8_t *buf, uint32_t iNbrToWrite) { /* Unlock the Flash Bank1 Program Erase controller */ uint32_t secpos; uint32_t iNumByteToWrite = iNbrToWrite; uint16_t secoff; uint16_t secremain; uint16_t i = 0; uint8_t tmp[FLASH_PAGE_SIZE]; volatile FLASH_Status FLASHStatus; FLASH_Unlock(); secpos=iAddress & (~(FLASH_PAGE_SIZE -1 )) ;//ÉÈÇøµØÖ· secoff=iAddress & (FLASH_PAGE_SIZE -1); //ÔÚÉÈÇøÄÚµÄÆ«ÒÆ secremain=FLASH_PAGE_SIZE-secoff; //ÉÈÇøÊ£Óà¿Õ¼ä´óС FLASHStatus = FLASH_COMPLETE; if(iNumByteToWrite<=secremain) secremain = iNumByteToWrite;//²»´óÓÚ4096¸ö×ÖÚ while( 1 ) { Flash_Read(secpos, tmp, FLASH_PAGE_SIZE); //¶Á³öÕû¸öÉÈÇø for(i=0;i<secremain;i++) { //УÑéÊý¾Ý if(tmp[secoff+i]!=0XFF)break; //ÐèÒª²Á³ý } if(i<secremain) { //ÐèÒª²Á³ý FLASHStatus = FLASH_ErasePage(secpos); //²Á³ýÕâ¸öÉÈÇø if(FLASHStatus != FLASH_COMPLETE) return -1; for(i=0;i<secremain;i++) { //¸´ÖÆ tmp[i+secoff]=buf[i]; } Flash_Write_Without_check(secpos ,tmp ,FLASH_PAGE_SIZE);//дÈëÕû¸öÉÈÇø } else { Flash_Write_Without_check(iAddress,buf,secremain);//дÒѾ²Á³ýÁ˵Ä,Ö±½ÓдÈëÉÈÇøÊ£ÓàÇø¼ä. } if(iNumByteToWrite==secremain) //дÈë½áÊøÁË break; else { secpos += FLASH_PAGE_SIZE; secoff = 0;//Æ«ÒÆλÖÃΪ0 buf += secremain; //Ö¸ÕëÆ«ÒÆ iAddress += secremain;//дµØÖ·Æ«ÒÆ iNumByteToWrite -= secremain; //×Ö½ÚÊýµÝ¼õ if(iNumByteToWrite>FLASH_PAGE_SIZE) secremain=FLASH_PAGE_SIZE;//ÏÂÒ»¸öÉÈÇø»¹ÊÇд²»Íê else secremain = iNumByteToWrite; //ÏÂÒ»¸öÉÈÇø¿ÉÒÔдÍêÁË } } FLASH_Lock(); return iNbrToWrite; }
/*! ****************************************************************************** ** \brief set flash back to read or reset mode ** ** \param pResetSecAddr ** \arg operate address ** ** \return None ** ****************************************************************************** */ void WFlash_ReadResetCmd(uint16_t* pResetSecAddr) { WFlash_SetRunMode(WFLASH_PGM_MODE); WFlashDummy(WFlash_GetRunMode()); /* issue read/reset command */ Flash_Write(pResetSecAddr, FLASH_READ_RESET) ; WFlash_SetRunMode(WFLASH_ROM_MODE); WFlashDummy(WFlash_GetRunMode()); WFlashDummy(Flash_Read(pResetSecAddr)); }
void GetAdminPWFromFlash(void) { uint8_t tmp[M_ADMIN_PASSWORD_LENGTH] ="7091"; Flash_Read(adminPassword, M_FLASH_ADDRESS_ADMIN_CARD_ID + FLASH_SECTOR_SIZE, sizeof(adminPassword)); if (adminPassword[0] == 0xFF && adminPassword[1] == 0xFF && adminPassword[2] == 0xFF && adminPassword[3] == 0xFF) { memcpy(adminPassword, tmp, M_ADMIN_PASSWORD_LENGTH); } }
/******************************************************************************* * 函数名称: * 输入参数: read Flash address * 输出参数: * --返回值: read appoint location of data * 函数功能: read IAP flag *******************************************************************************/ uint16_t MFlash_Read16bit(uint16_t* pReadAddr) { uint8_t *Addr; uint16_t ReadData; Addr = (uint8_t *)pReadAddr; if ((Addr>=(uint8_t *)FLASH_STR_ADDR)&&(Addr<=(uint8_t *)(FLASH_END_ADDR-2))) { if (((uint32_t)Addr%2) == 1) { Addr--; ReadData = (uint16_t)(Flash_Read(Addr)); } else { ReadData = (uint16_t)(Flash_Read(Addr)); } return ReadData; } return 0u; }
u16 UnicodeToGb2312(u16 Unicode) { u16 GB2312; u8 tem; u8 *temp=(u8 *)(&GB2312); Flash_Read(0x0A0000+Unicode*2,(u8 *)&GB2312,2); /* Big endian to Little endian */ tem=*(temp+1); *(temp+1)=*temp; *temp=tem; return GB2312; }
/** * Prepare_Self_Test * * If the application requests a self test for the newly * downloaded image, then the new image will be copied to * the boot location temporarily. The watch dog timer is * set to ensure that the app will reboot for the second * verification phase. * After the reboot the boot loader verifies the test result * and decides if the image has to be made golden or not. * * @return SUCCESS | ERROR */ result_t Prepare_Self_Test () { //uint8_t buffer [61]; /** * first change the state so that in case if we crash then we * can recover. */ Flash_Read (0x0, 32, vecbuffer); /* Load the Image details so that we can move the contents to * boot location */ if (Read_Attribute_Value(BL_ATTR_TYP_SECONDARY_IMG_LOCATION, &GImgAddr) == SUCCESS) { if (Read_Attribute_Value(BL_ATTR_TYP_SECONDARY_IMG_SIZE, &GImgSize) == SUCCESS) { /** * First check if the image is worth performing selftest on. Calculate * the crc and try to match it with the crc attribute. */ if (Read_Attribute_Value(BL_ATTR_TYP_SECONDARY_IMG_CRC, &GImgCrc) == SUCCESS) { if ((GImgSize == 0) || (GImgCrc == 0)) return FAIL; if (Handle_Cmd_Verify_Image_Crc (GImgAddr, GImgSize, GImgCrc) == SUCCESS) { uint32_t WDTimeout; if (Change_BootLoader_State_Attribute (VERIFY_SELF_TEST) == FAIL) return FAIL; if (Read_Attribute_Value(BL_ATTR_TYP_SELF_TEST_TIMEOUT, &WDTimeout) == SUCCESS) WDTimeout = BL_SELF_TEST_TIMEOUT; /*Not a biggie if we fail set it default*/ __Binary_Mover (GImgAddr, GImgSize, vecbuffer); //Move_Image_To_Boot_Loc (GImgAddr, GImgSize); /* set the watchdog to wait for long time to allow the * app to finish the self test */ OSMR3 = OSCR0 + WDTimeout; OWER = 1; handle_jump (); } } } } return FAIL; }
/*! ****************************************************************************** ** \brief read flash in 8 bit mode ** ** \param pSecAddr ** \arg operate address ** ** \return readed 8 bit data from flash ** ****************************************************************************** */ uint8_t WFlash_Read8bit(uint8_t* pReadAddr) { uint8_t ReadData; uint8_t *Addr; Addr = (uint8_t *)pReadAddr; if((Addr>=(uint8_t *)FLASH_STR_ADDR)&&(Addr<=(uint8_t *)(FLASH_END_ADDR-1))) { if(((uint32_t)Addr%2)== 1) { Addr--; ReadData = (uint8_t)(((Flash_Read(Addr))&0xFF00)>>8); } else {
void Flash_Write(uint8_t addr, uint32_t value) { if (addr < USED_SIZE / 4) { /* 缓存Flash中其他位置的数据 */ uint32_t dist = 0; Flash_Read(0, &dist); Using_Values[addr] = value; FMC_Erase(NEW_BLOCK_ADDR); Block_Write(NEW_BLOCK_ADDR, Using_Values); FMC_Erase(BAK_BLOCK_ADDR); Block_Write(BAK_BLOCK_ADDR, Using_Values); } }
void TaskProtocol(void *p_arg) { MSG_t msg; INT8U err , i; IDPROTOCOL_t *pProto; // INT8U *p; // SendString("TaskProtocol \n"); for (;;) { msg = (MSG_t)OSQPend(ProtocolMBox, 0, &err); // OSTimeDly(3000); //SendString("taskprotocol"); switch (msg) { // 串口1接收到协议数据 case UART1_BUFF0_RECV: case UART1_BUFF1_RECV: pProto = &gU1RecvBuff[msg - UART1_BUFF0_RECV]; if ((pProto->direction & ID_DESTMASK) == ID_RFIRBOARD) { if (pProto->command == CMD_SETID) { Flash_Write(RFIR_ID_ADDR,pProto->data,4);//读取buf存入FLASH SendString("\n\rID setok:"); Flash_Read(RFIR_ID_ADDR, MY_ID, 4); //读取FLASH ID存入BUF for(i=0;i<4;i++)//sizeof(ID) { SendString(";"); Outint(MY_ID[i]); } } } // 查看是否需要应答 if (IS_PROTO_NEED_ACK(pProto)) { // 返回应答数据 SendIDAck(USART1, pProto); } break; default: break; } } }
BYTE GetLog( far void * LogPtr ){ if ( logPtrSta != logPtrEnd ) { Flash_Read( (BYTE*)&logBuffer, FEE_LOG_ADDR + logPtrSta * sizeof( struct LogBuffer ), sizeof( struct LogBuffer ) ); if ( LogPtr != NULL ){ LogPtr = &logBuffer; } IncLogPtrStart(); return TRUE; } else{ LogPtr = NULL; } return FALSE; }
/** * Self_Test_Failed * * If the self test fails then the boot loader has to recover the * previous golden image and replace the current boot image (self test image). * * @return SUCCESS | FAIL */ result_t Self_Test_Failed () { /** * first change the state so that in case if we crash then we * can recover. */ Flash_Read (0x0, 32, vecbuffer); /* Load the Image details so that we can move the contents to * boot location */ if (Read_Attribute_Value(BL_ATTR_TYP_PRIMARY_IMG_LOCATION, &GImgAddr) == SUCCESS) { if (Read_Attribute_Value(BL_ATTR_TYP_PRIMARY_IMG_SIZE, &GImgSize) == SUCCESS) { if (Read_Attribute_Value(BL_ATTR_TYP_PRIMARY_IMG_CRC, &GImgCrc) == SUCCESS) { /* Just in case, make sure that CRC matches before loading it*/ if (Handle_Cmd_Verify_Image_Crc(GImgAddr, GImgSize, GImgCrc) == SUCCESS) { __Binary_Mover (GImgAddr, GImgSize, vecbuffer); //Move_Image_To_Boot_Loc (GImgAddr, GImgSize); /*Reset the Crc boot address.*/ //Write_Attribute_Value(BL_ATTR_TYP_BOOT_IMG_CRC, GImgCrc); //handle_jump (); return SUCCESS; } } } } return FAIL; }
/** * @brief 板级初始化 * * @param none * @retval none */ void BSP_Init (void) { LED_Init(); Flash_Read(); //读取参数 Flash_CheckFirstTime(false); //检查FLASH里是否存在有效数据,如果没有则写入默认数据 // cfg.mixerConfiguration = MIXERCONFIG;统一在调参软件里设置机型 Mixer_Init(); //动力初始化 Serial_Init(cfg.serial_baudrate);//上位机调参初始化 I2C2_Init(); //I2C2 Sensor_DetectAndInit(); IMU_Init(); Altitude_Init(); Actuator_Init(); RC_Init(); Daemon_Init(); GPS_Init(cfg.gps_baudrate); Telemetry_Init(); #ifdef OPTICALFLOW OpticalFlow_Init(); #endif EasyCtrl_Init(); VisionLanding_Init(); Avoid_Init(); }
/*! ****************************************************************************** ** \brief check flash operating status ** ** \param p_sec_addr ** \arg operate address ** ** \return FLASH_CHK_TOGG_NORMAL : successfully complete ** FLASH_CHK_TOGG_ABNORMAL : flash operation abnormally ** ****************************************************************************** */ static uint8_t WFlash_CheckToggle( uint16_t* p_sec_addr ) { uint8_t ucRetValue = FLASH_CHK_TOGG_NORMAL ; uint32_t usSequenceFlag1, usSequenceFlag2 ; /* hardware sequence flag */ if((p_sec_addr<=(uint16_t *)(FLASH_END_ADDR-2))&&((p_sec_addr>=(uint16_t *)FLASH_STR_ADDR))) { /* set hardware sequence flag */ usSequenceFlag1 = Flash_Read(p_sec_addr) ; usSequenceFlag2 = Flash_Read(p_sec_addr) ; /* if automatic algorithm is executing */ while((( usSequenceFlag1 ^ usSequenceFlag2) & FLASH_CHK_TOGG_MASK) == FLASH_CHK_TOGG_MASK) { /* if exceeds the timing limit */ if(( usSequenceFlag1 & FLASH_CHK_TLOV_MASK) == FLASH_CHK_TLOV_MASK) { /* set hardware sequence flag */ usSequenceFlag1 = Flash_Read(p_sec_addr) ; usSequenceFlag2 = Flash_Read(p_sec_addr) ; /* if automatic algorithm is executing */ if((( usSequenceFlag1 ^ usSequenceFlag2) & FLASH_CHK_TOGG_MASK) == FLASH_CHK_TOGG_MASK) { /* abnormally complete */ ucRetValue = FLASH_CHK_TOGG_ABNORMAL ; break; } } /* set hardware sequence flag */ usSequenceFlag1 = Flash_Read(p_sec_addr) ; usSequenceFlag2 = Flash_Read(p_sec_addr) ; } } else ucRetValue = FLASH_CHK_TOGG_ABNORMAL; return ucRetValue ; }
BYTE ChangeFirmware( void ) { DWORD dwCounter; DWORD dwFlashTotalUpload; BYTE bBuffer[ BOOT_LOADER_FRAME_LEN + sizeof( DWORD ) ]; WORD wAddr; DWORD dwAddr; BYTE bLen; BYTE bMemType; e2prom_write( (BYTE*)&dwFlashTotalUpload, BOOT_LDR_PCK_CNTRL_ADDR, sizeof( dwFlashTotalUpload )); dwCounter = 0; do { wAddr = Flash_Read( (BYTE*)bBuffer, (DWORD)(FEE_BOOTLOADER + dwCounter), sizeof ( bBuffer )); if ( wAddr == -1 ) { return FALSE; } dwCounter += ((DWORD)wAddr); // parse the data in the memory. // buffer position 0 1 2 3 4 [4+len] // frame format : <adr2|adr1|adr0><len><data_0....data_n> bMemType = bBuffer[0]; wAddr = MAKEWORD( bBuffer[2], bBuffer[1] ); bLen = bBuffer[3]; if ( bLen >= BOOT_LOADER_FRAME_LEN ) { return FALSE; } else { switch( bMemType ) { case 0xF0: // EEDATA // não será atualizado a E2PROM e2prom_write( (BYTE*)&bBuffer[4], wAddr, bLen ); break; case 0x20: // User ID case 0x30: // Configuration Words default: if ( bMemType >= 0x00 && bMemType <= 0x1F ) // Program { dwAddr = MAKELONG( wAddr, MAKEWORD( 0, bMemType )); memprg_write( (BYTE*)&bBuffer[4], dwAddr, bLen ); break; } else { return FALSE; } } } }while( dwCounter < dwFlashTotalUpload ); bLen = 0; e2prom_write( (BYTE*)0, BOOT_LDR_PCK_CNTRL_ADDR , sizeof( BYTE )); e2prom_write( (BYTE*)0, BOOT_LDR_CRC32_ADDR , sizeof( DWORD )); return TRUE; }
void GPSNET_FOTA_Task(void) { // task setup LATITUDE latitude; LONGITUDE longitude; INT32U i = 0; INT32U j = 0; INT32U endereco_bw; INT8U type = 0; INT8U confirma=0; INT8U error=0; INT8U nerror=0; INT8U confirma_rede_error = 0; INT8U *boot_end_status; static INT16U linhas; static INT16U linhas2; if (OSSemCreate(0,&Confirma) != ALLOC_EVENT_OK) { while(1){}; }; if (OSSemCreate(0,&Bootloader_Event) != ALLOC_EVENT_OK) { while(1){}; }; if (OSMboxCreate(&Bootloader_end,NULL) != ALLOC_EVENT_OK) { while(1){}; } // task main loop for (;;) { // Wait event from APP layer, no timeout OSSemPend(Bootloader_Event,0); // Set target node address UserEnterCritical(); latitude.x = GPS_X_tmp.int32u; longitude.y = GPS_Y_tmp.int32u; UserExitCritical(); linhas = 0; linhas2 = 0; endereco_bw = CODE_START; for(;;) { /* loop to read a line of code */ for(i=0;i<VECTOR32_SIZE;i++) { // return 32-bit words data_checksum[i]=Flash_Read(endereco_bw); bootloader_datal[i] = data_checksum[i]; endereco_bw+=4; } linhas++; j=0; type = (INT8U)(bootloader_data[2]); // get line type if(type==7) { bootloader_data[15] = (INT8U)((CRC_CODIGO_16>>8) & 0xFF); bootloader_data[16] = (INT8U)((CRC_CODIGO_16) & 0xFF); bootloader_data[17] = (INT8U)((CRC_CODIGO_162>>8) & 0xFF); bootloader_data[18] = (INT8U)((CRC_CODIGO_162) & 0xFF); endereco_bw = CODE_START; } error = 0; nerror = 0; confirma_rede_error = 0; envia_de_novo: UserEnterCritical(); confirma_rede = 0; //mensagem = 0; UserExitCritical(); // send a line of code i = NetSimpledataXY(UP_ROUTE, &latitude, &longitude, &bootloader_data[0]); if(i==OK) { error = 0; // wait for send to complete - SIGNAL_TIMEOUT ms i = OSSemPend (Confirma, SIGNAL_TIMEOUT); if(confirma_rede == DATA_OK) { confirma_rede_error = 0; linhas2++; if(type==7) { type=0; endereco_bw = CODE_START; //UserEnterCritical(); //mensagem = confirma_rede; //UserExitCritical(); boot_end_status = (INT8U*)'o'; (void)OSMboxPost(Bootloader_end,(void *)boot_end_status); break; } } else { if (confirma_rede == 0) { /* timeout of semaphore pend */ confirma_rede_error++; // DelayTask(100); if(confirma_rede_error>6) { confirma_rede_error = 0; //UserEnterCritical(); // mensagem = confirma_rede; //UserExitCritical(); if(Bootloader_ForceStop == 1){ // desiste Bootloader_ForceStop = 0; endereco_bw = CODE_START; boot_end_status = (INT8U*)'f'; (void)OSMboxPost(Bootloader_end,(void *)boot_end_status); break; } } goto envia_de_novo; } endereco_bw = CODE_START; //UserEnterCritical(); // mensagem = confirma_rede; //UserExitCritical(); boot_end_status = (INT8U*)'g'; (void)OSMboxPost(Bootloader_end,(void *)boot_end_status); break; } } else { error++; DelayTask(SIGNAL_TIMEOUT); if(error==3) { DelayTask(RadioWatchdogTimeout + SIGNAL_TIMEOUT); /* wait for a radio reset */ } if(error>6) { error = 0; //UserEnterCritical(); // mensagem = confirma_rede; //UserExitCritical(); endereco_bw = CODE_START; boot_end_status = (INT8U*)'f'; (void)OSMboxPost(Bootloader_end,(void *)boot_end_status); break; } else { goto envia_de_novo; } } } }
/******************************************************************************** * FunctionName: Flash_Write * * Description : * * Parameters : * * Returns : * * @brief Programs a half word at a specified Option Byte Data address. * @note This function can be used for all STM32F10x devices. * @param Address: specifies the address to be programmed. * @param buf: specifies the data to be programmed. * @param iNbrToWrite: the number to write into flash * @retval if success return the number to write, -1 if error // iAddress:保存EEPROM数据的起始地址(0~) // iNbrToRead:保存数据长度,要求数据长度小于一页 // *buf:保存数据缓存指针 ********************************************************************************/ int Flash_Write(uint32_t iAddress, uint8_t *buf, uint32_t iNbrToWrite) { volatile FLASH_Status FLASHStatus = FLASH_COMPLETE; /* Unlock the Flash Bank1 Program Erase controller */ uint32_t secpos; uint32_t iNumByteToWrite = iNbrToWrite; uint16_t secoff; uint16_t secremain; uint16_t i = 0; uint8_t tmp[FLASH_PAGE_SIZE]; FLASH_UnlockBank1(); secpos=iAddress & (~(FLASH_PAGE_SIZE -1 )) ;//扇形地址 secoff=iAddress & (FLASH_PAGE_SIZE -1); //在扇区内的偏移 secremain=FLASH_PAGE_SIZE-secoff; //扇区剩余空间大小 /*不大于4096个字节*/ if(iNumByteToWrite<=secremain) secremain = iNumByteToWrite; while( 1 ) { /*读出整个扇区*/ Flash_Read(secpos, tmp, FLASH_PAGE_SIZE); /*校验数据*/ for(i=0;i<secremain;i++) { if(tmp[secoff+i]!=0XFF)//需要擦除 { break; } } /*需要擦除*/ if(i < secremain) { /*擦除这个扇区*/ FLASHStatus = FLASH_ErasePage(secpos); if(FLASHStatus != FLASH_COMPLETE) { return -1; } /*复制*/ for(i=0;i<secremain;i++) { tmp[i+secoff]=buf[i]; } /*写入整个扇区*/ Flash_Write_Without_check(secpos ,tmp ,FLASH_PAGE_SIZE); } /*写已经擦除了的,直接写入扇区剩余区间*/ else { Flash_Write_Without_check(iAddress,buf,secremain); } /*写入结束*/ if(iNumByteToWrite == secremain) { break; } else { secpos += FLASH_PAGE_SIZE; secoff = 0; //偏移位置为0 buf += secremain; //指针偏移 iAddress += secremain; //写地址偏移 iNumByteToWrite -= secremain; //字节数递减 if(iNumByteToWrite > FLASH_PAGE_SIZE) { secremain = FLASH_PAGE_SIZE; /*下一个扇区还是写不完*/ } else { secremain = iNumByteToWrite; /*下一个扇区可以写完了*/ } } } FLASH_LockBank1(); return iNbrToWrite; }
int main(void) { u16 times=0,i=0; NORMALTIME cur_time; //设置RTC的时间用 //Flash_Write(0x08041000,(u8 *)IndCalib,sizeof(IndCalib)); Flash_Read(0x08041000,(u8 *)IndCalib,sizeof(IndCalib)); delay_init(); //延时函数初始化 NVIC_Configuration(); //设置NVIC中断分组2:2位抢占优先级,2位响应优先级 uart1_init(115200); //上位机通信模块 uart2_init(9600); //风速传感器模块 A2 A3 要转为232 //uart3_init(19200); //SD卡模块 (兼职风向-因为3有重映射功能) uart4_init(9600); //称重模块 uart5_init(9600); //AD模块 LED_Init(); //LED端口初始化 KEY_Init(); //初始化与按键连接的硬件接口 SD_init(); OPEN_SD_POWER; CLOSE_SD_POWER; OPEN_SD_POWER; CLOSE_SD_POWER; OPEN_SD_POWER; cur_time.tm_year = 2016; //2016-1900 cur_time.tm_mon = 5; cur_time.tm_mday = 29; cur_time.tm_hour = 23; cur_time.tm_min = 56; cur_time.tm_sec = 2; RTC_Init(cur_time);// while(DS18B20_Init())//初始化DS18B20,兼检测18B20 { printf("DS18B20 Check Failed!"); printf("Please Check! "); } printf("DS18B20 Ready! "); while(1) { if(IS_BUT_DN) { BEEP = 0; } else { BEEP = 1; g_PaOffset= -g_Pa; g_IndValOffset[0]= -Volt2Distance(0,g_IndVal[0]); g_IndValOffset[1]= -Volt2Distance(1,g_IndVal[1]); g_IndValOffset[2]= -Volt2Distance(2,g_IndVal[2]); g_IndValOffset[3]= -Volt2Distance(3,g_IndVal[3]); } if(times%60==0) { windSpeedDirFlag++; sendWindSpeedCmd(); //串口2 带232 //printf("3\r\n"); if(5 == windSpeedDirFlag) { windSpeedDirFlag = 0; } //printf("4\r\n"); //风速的反应慢 一秒钟最多发一次指令 不然传感器要疯掉 if(0 == windSpeedDirFlag) { uart3_init(19200); //SD卡模块 (兼职风向-因为3有重映射功能) g_uart3_used_for_SD = 1; // 日期 时间 位移1, 2, 3, 4 |拉力| 温度 |SD|风速|风向 sprintf(CmdStr,"#01,%02d-%02d-%02d,%02d:%02d:%02d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%1d,%04d,%04d!\r\n", cur_time.tm_year,cur_time.tm_mon,cur_time.tm_mday, cur_time.tm_hour,cur_time.tm_min,cur_time.tm_sec, dateSendtoPC[0],dateSendtoPC[1],dateSendtoPC[2],dateSendtoPC[3], dateSendtoPC[4], dateSendtoPC[6],dateSendtoPC[7],dateSendtoPC[8],dateSendtoPC[9], g_Temper,lastSDerr,g_WindSpeed,g_WindDir); //printf("7\r\n"); lastSDerr = write_string_to_files(CmdStr); } else { //printf("8\r\n"); uart3_init2(9600); //SD卡的usart3 重映射到 PB10 和PB11口 来读风向 g_uart3_used_for_SD = 0; send_byte_to_usart3(0x02);//初始化完后第一个字节会发不成功 sendWindDirCmd();//串口3 } //printf("11\r\n"); cur_time = Time_GetTime(); } if(times%10==0) { //sendWeightLoad1Cmd(); //称重标定代码 //printf("12\r\n"); switch(PC_Wcmd) { case 0x30: //printf("13\r\n"); BEEP = 1; sendWeightZeroCmd(); BEEP = 0; PC_Wcmd = 0; break; case 0x40: //printf("14\r\n"); BEEP = 1; sendWeightLoad1Cmd(); PC_Wcmd = 0; BEEP = 0; break; case 0x41: //printf("15\r\n"); BEEP = 1; sendWeightLoad2Cmd(g_weightCalib[0],g_weightCalib[1]); PC_Wcmd = 0; BEEP = 0; break; default: //printf("16\r\n"); //sendWeightLoad2Cmd(0x27,0x10); sendWeightCmd(); //串口4 break; } BLED3=1; sendADCmd(); //串口5 BLED3=0; dateSendtoPC[0] = g_IndVal[0]; dateSendtoPC[1] = g_IndVal[1]; dateSendtoPC[2] = g_IndVal[2]; dateSendtoPC[3] = g_IndVal[3]; dateSendtoPC[4] = g_PaOffset + g_Pa; dateSendtoPC[6] = g_IndValOffset[0] + Volt2Distance(0,g_IndVal[0]); dateSendtoPC[7] = g_IndValOffset[1] + Volt2Distance(1,g_IndVal[1]); dateSendtoPC[8] = g_IndValOffset[2] + Volt2Distance(2,g_IndVal[2]); dateSendtoPC[9] = g_IndValOffset[3] + Volt2Distance(3,g_IndVal[3]); } switch(PC_cmd) { case 1: BLED2 = 1; // 日期 时间 位移1, 2, 3, 4 |拉力| 温度 |SD|风速|风向 sprintf(CmdStr,"#01,%02d-%02d-%02d,%02d:%02d:%02d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%04d,%d,%04d,%04d!\r\n", cur_time.tm_year,cur_time.tm_mon,cur_time.tm_mday, cur_time.tm_hour,cur_time.tm_min,cur_time.tm_sec, dateSendtoPC[0],dateSendtoPC[1],dateSendtoPC[2],dateSendtoPC[3], dateSendtoPC[4], dateSendtoPC[6],dateSendtoPC[7],dateSendtoPC[8],dateSendtoPC[9], g_Temper,lastSDerr,g_WindSpeed,g_WindDir); send_string_to_usart1(CmdStr); BLED2 = 0; PC_cmd = 0; break; case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: BEEP = 1; sprintf(CmdStr,"#%02x",PC_cmd); for(i=0;i<21;i++) { sprintf(CmdStr,"%s,%+05d",CmdStr,IndCalib[PC_cmd-0x10][i]); } sprintf(CmdStr,"%s!\r\n",CmdStr); send_string_to_usart1(CmdStr); PC_cmd = 0; BEEP = 0; break; case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: sprintf(CmdStr,"#%02x",PC_cmd-0x10); for(i=0;i<21;i++) { sprintf(CmdStr,"%s,%+05d",CmdStr,IndCalib[PC_cmd-0x20][i]); } sprintf(CmdStr,"%s!\r\n",CmdStr); send_string_to_usart1(CmdStr); PC_cmd = 0; break; } times++; delay_ms(10); } }
void Flash_Data_Update(U16 sector){ U8 i; for(i=0;i<DATA_NUM;i++){ flashData[i] = Flash_Read(sector,i); } }
/* ** Handle Bit Status Message to report Flash Data to the Host. */ void OnFlashImgUploadFrame(Dci_Context* pctxt) { byte buff[MAX_MSG_SIZE]; uint32 addr; int lenMsg; int ec = 0x0; int i; int nErr = 0; //Switch on the Status Message ID. Dci_BinaryImageTransferStatus *pMsg = (Dci_BinaryImageTransferStatus *) pctxt->pMsg; //Do not proceed if we are not actually doing a binary transfer upload. if( !IsTransferring( pMsg->idTransfer)) return; switch(pMsg->idStatus) { case(BSE_InitiatingTransfer): // Ready to send. // Host indicates we can start sending now (Send Enable). s_ctBytesRemaining = s_flashHdr.bitParams.sizeImg; // Continue to respond with a frame. case(BSE_ReadyNextFrame): // Send next frame. // Send a frame of data. { byte *pdata; uint16 ctBytes; // Compute the Flash read address. addr = FLASH_IMAGE_OFFSET + ((uint32)s_idFrame * (uint32)s_flashHdr.bitParams.sizeFrame); ctBytes = (s_ctBytesRemaining > s_flashHdr.bitParams.sizeFrame) ? s_flashHdr.bitParams.sizeFrame : (uint16) s_ctBytesRemaining; // Create Frame message and get point to read data into it. lenMsg = Dci_BinaryImageTransferFrame_Init( buff, WCACOMP_FLASH, pMsg->idTransfer, 0, s_idFrame, ctBytes, NULL); pdata = Dci_BinaryImageTransferFrame_GetData( (Dci_BinaryImageTransferFrame *)buff ); ec = Flash_Read(addr, (int)ctBytes, pdata); // Verify. #if defined(CJC_VERIFIED_THIS_GOOD) for(i=0; i<256; i++) { if( *(pdata+i) != (byte)i ) ++nErr; } #endif //If everything ok, send it. if( ec == 0x0 ) { Dciproc_SendMessage1(buff, lenMsg, false, pctxt); ++s_idFrame; s_ctBytesRemaining -= ctBytes; if( s_idFrame < s_flashHdr.bitParams.ctFrames) { break; //Done get out. } } else // Send the error message and then quit. { // If we get here, a read error of some sort ocurred, drop out // and kill the transfer operation. lenMsg = Dci_BinaryImageTransferStatus_Init( buff, WCACOMP_FLASH, pMsg->idTransfer, s_idFrame, 0, BSE_ReadError); Dciproc_SendMessage1(buff, lenMsg, false, pctxt); } //if we get here, we failed ResetTransfer(); } break; // Default conditions hault transfer case(BSE_FrameError): case(BSE_OperationNotAvailable): case(BSE_WriteError): default: ResetTransfer(); break; } pctxt->bHandled = true; }
void recoverAdminCardIDFromFlash(void) { Flash_Read(adminCardID, M_FLASH_ADDRESS_ADMIN_CARD_ID, sizeof(adminCardID)); }
/** * Move_Image_To_Boot_Loc * * Move the image at imgAddr to the boot location. This * function holds a copy of the vector table. If incase there is * a failure then it will try to replace the vector table to * save the boot loader. * * @param imgAddr Starting address of the image to be moved. * @param imgSiz Size of the image at imgAddr. * * @return SUCCESS | FAIL */ result_t Move_Image_To_Boot_Loc (uint32_t imgAddr, uint32_t imgSiz) { result_t ret; uint32_t ImgFlashAddr = imgAddr + 32; /*Drop the vec table*/ uint32_t CSize= 0x8000; uint32_t RSize = 0; uint32_t CurSize = 0x20; uint32_t BootAddr = 0x0; uint32_t AddVec = 0x0; Flash_Read (0x0, 32, vecbuffer); /* Keep this for recovery purpose*/ if (Flash_Param_Partition_Erase (BootAddr) == SUCCESS) { if (Flash_Write (BootAddr, vecbuffer, 0x20) == FAIL) { memcpy (cpybuffer, vecbuffer, 0x20); AddVec = 0x20; } else BootAddr = 0x20; } ret = __Binary_Erase (CurrImageAddr, CurrImageSize, vecbuffer); if (Flash_Read (ImgFlashAddr, (CSize - CurSize), (cpybuffer + AddVec)) == SUCCESS) { if (Flash_Write (BootAddr, cpybuffer, (0x7FE0 + AddVec)) == SUCCESS) { CurSize += (0x8000 - 0x20); ImgFlashAddr += (0x8000 - 0x20); BootAddr += (0x8000 - 0x20); } else { if (Flash_Write (BootAddr, vecbuffer, 0x20) == FAIL) { TOGGLE_LED (RED); while (1); } else return FAIL; } } while (CurSize < imgSiz) { RSize = ((imgSiz - CurSize) > CSize)? CSize : (imgSiz - CurSize); if (Flash_Read (ImgFlashAddr, RSize, cpybuffer) == SUCCESS) { if (Flash_Write (BootAddr, cpybuffer, 0x8000) == SUCCESS) { CurSize += RSize; ImgFlashAddr += RSize; BootAddr += RSize; } else return FAIL; } } return SUCCESS; }
/******************************************************************************** * FunctionName: TaskSet * * Description : 设置任务,设置完删除任务 * * Parameters : None. * * Returns : None. *******************************************************************************/ void TaskSet(void *p_arg) { unsigned char k, data_flash_temp[208]={0xAE, 0x35, 0x24, 0x70, 0x80, 0xB7, 0x80, 0xBA, 0x1F, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9B, 0x1D, 0x5C, 0x1B, 0x5E, 0x02, 0x77, 0x02, 0xED, 0xEF, 0x80, 0xB8, 0x80, 0xB9, 0x1D, 0x5C, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1F, 0x80, 0x9B, 0x1D, 0x5C, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9B, 0x1D, 0x80, 0x9A, 0x1E, 0x80, 0xF5, 0x1E, 0x8F, 0x70, 0x02, 0xEA, 0x8C, 0x80, 0xB8, 0x80, 0xB9, 0x1D, 0x5C, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9A, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9B, 0x1D, 0x80, 0x9A, 0x1E, 0x80, 0xF5, 0x1E, 0x85, 0x88, 0x80, 0xB8, 0x80, 0xB8, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9A, 0x1E, 0x5C, 0x1E, 0x5B, 0x1F, 0x5B, 0x1E, 0x5B, 0x1F, 0x5B, 0x1F, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9B, 0x15, 0x80, 0xA4, 0x02, 0x86, 0xB7, 0x04, 0x81, 0x6D, 0x02, 0x77, 0x02, 0x77, 0x02, 0x77, 0x02, 0x77, 0x02, 0x77, 0x02, 0x77, 0x02, 0xAF, 0xFB, 0x02, 0x77, 0x1F, 0x5B, 0x1F, 0x5B, 0x1E, 0x5B, 0x1E, 0x80, 0x9B, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD7}; // INT8U i; u32 seed; u8 random_data,i; //INT32U msg = 0; //INT8U err = 0; OS_CPU_SR cpu_sr = 0; p_arg = p_arg; DelayMs(30); OS_ENTER_CRITICAL(); BSP_Init(); Flash_Read(RFIR_ID_ADDR, MY_ID, 4); //读取FLASH ID存入BUF #if 0 SendString("\n\rMY ID:"); for(i=0;i<4;i++)//sizeof(ID) { SendString(";"); Outint(MY_ID[i]); } #endif /******************************************************************************** * Description : 任务建立 共9个任务 *******************************************************************************/ CT361SndErrSemp = OSSemCreate(0);//creat sem //创建协议解析任务 OSTaskCreate(TaskProtocol, (void*)0, &TaskProtocolStk[TASK_PROTOCOL_STKSIZE-1], TASK_PROTOCOL_PRIO); //创建串口发送任务 OSTaskCreate(TaskProtoSend, (void*)0, &TaskProtoSendStk[TASK_PROTO_SEND_STKSIZE-1], TASK_PROTO_SEND_PRIO ); //创建量产测试任务 OSTaskCreate(TaskTest, (void*)0, &TaskTestStk[TASK_TEST_STKSIZE-1], TASK_TEST_PRIO ); //创建4432接收任务 OSTaskCreate(TaskSi4432Read, (void*)0, &TaskSi4432ReadStk[TASK_SET_STKSIZE-1], TASK_Si4432_READ_PRIO ); //创建返回码接收任务 OSTaskCreate(TaskCT361SndErr,\ (void*)0,\ &TaskCT361SndErrStk[TASK_CT361_SND_ERR_STKSIZE-1],\ TASK_CT361_SND_ERR_PRIO); /******************************************************************************** * Description : 创建消息队列 *******************************************************************************/ // SetMBox = OSQCreate(&SetQBuff[0], TASK_SET_QSIZE); ProtocolMBox = OSQCreate(&ProtocolQBuff[0], TASK_PROTOCOL_QSIZE); ProtoSendMBox = OSQCreate(&ProtoSendQBuff[0], TASK_PROTOSEND_QSIZE); TestMBox = OSQCreate(&TestQBuff[0], TASK_TEST_QSIZE); Si4432ReadMBox = OSQCreate(&Si4432ReadQBuff[0], TASK_Si4432READ_QSIZE); OS_EXIT_CRITICAL(); SysTickInit(); //自我删除 // OSTaskDel(OS_PRIO_SELF); /*自我删除函数会自动进行任务的调度,因此此处不需要添加延时*/ Flash_Write(0x800D678,data_flash_temp,208); for (;;) { /**********学习状态指示灯********/ if(learn_cmd==1) //学习开始标志位 { LED_Send(0);// 绿灯关闭 LED_Learn(1);//红灯闪烁 WatchDog_Feed(); //喂狗 OSTimeDly(4); WatchDog_Feed(); //喂狗 LED_Learn(0); WatchDog_Feed(); //喂狗 OSTimeDly(4); WatchDog_Feed(); //喂狗 Timout_Count--; if(Timout_Count==0) { Timout_Count=TIMOUT_20s; OSQPost(TestMBox, (void*)Stu_Fail); //学习失败信号 learn_cmd=0; //清空学习成功标志位 } } if(learn_cmd==0) //学习成功标志位 { LED_Learn(0);//红灯关闭 LED_Send(1); //绿灯开启 } /**********生成随机滚动序列*********/ seed+=23; if(seed>65000) seed=0; srand(seed); random_data=rand(); test_roll_list=random_data^0x29; if(learn_cmd==0) { Timout_Count2--; if((Timout_Count2>=40)&&(Timout_Count2<=200)) { LED_Send(0); } else if((Timout_Count2<40)&&(Timout_Count2>=1)) { LED_Send(1); // Timout_Count2=200; } else if(Timout_Count2<=0) Timout_Count2=200; } WatchDog_Feed(); //喂狗 OSTimeDly(1); } }
// bQuick=TRUE: just check first and last block bool FLASH_Verify(char *pFlashName, alt_u8 InitValue, bool bShowMessage, bool bQuickVerify){ bool bPass = TRUE; int i, k, BlockNum; FLASH_HANDLE hFlash; alt_u32 Offset, Size; alt_u8 *pBuf, Cnt; const int nBufSize = 8*1024; // 16K int nWriteSizeSum, nWriteSize; int nReadSizeSum, nReadSize; hFlash = Flash_Open(pFlashName); if (!hFlash){ if (bShowMessage) printf("Failed to open flash.\r\n"); return FALSE; } BlockNum = Flash_GetBlockCount(hFlash); //===== alloc buffer pBuf = (alt_u8 *)malloc(nBufSize); if (!pBuf){ if (bShowMessage) printf("[Error] Failed to alloc memory.\r\n"); return FALSE; } //===== erase for(i=0;i<BlockNum && bPass;i++){ if (bQuickVerify && (i !=0 )&& (i != (BlockNum-1))) continue; bPass = Flash_Erase(hFlash, i); if (bShowMessage){ if (!bPass) printf("[Error] Failed to erase flash block %d/%d\r\n.\r\n", i, BlockNum); else printf("Erase Block %d/%d\r\n", i, BlockNum); } } //===== write if (bPass){ Cnt = InitValue; for(i=0;i<BlockNum && bPass;i++){ if (bQuickVerify && (i !=0 )&& (i != (BlockNum-1))) continue; bPass = Flash_GetBlockInfo(hFlash, i, &Offset, &Size); if (!bPass) continue; if (bShowMessage) printf("Write Block[%d/%d], size=%d\r\n", i, BlockNum, (int)Size); nWriteSizeSum = 0; while(nWriteSizeSum < Size && bPass){ // cal write size nWriteSize = nBufSize; if (nWriteSize > (Size - nWriteSizeSum)) nWriteSize = Size - nWriteSizeSum; // fill data for(k=0;k<nWriteSize;k++){ *(pBuf+k) = Cnt++; } // write data block bPass = Flash_Write(hFlash, Offset+nWriteSizeSum, pBuf, nWriteSize); if (bShowMessage && !bPass) printf("[Error] Write Block[%d/%d] NG\r\n", i, BlockNum); // usleep(20*1000); // nWriteSizeSum += nWriteSize; } } } if (bPass){ if (bShowMessage) printf("alt_dcache_flush_all\r\n"); alt_dcache_flush_all(); } //===== read & verify if (bPass){ Cnt = InitValue; for(i=0;i<BlockNum && bPass;i++){ if (bQuickVerify && (i !=0 )&& (i != (BlockNum-1))) continue; bPass = Flash_GetBlockInfo(hFlash, i, &Offset, &Size); if (!bPass){ if (bShowMessage) printf("[Error] Flash_GetBlockInfo at block %d\r\n", i); continue; } if (bShowMessage) printf("Read Block[%d/%d], size=%d\r\n", i, BlockNum, (int)Size); nReadSizeSum = 0; while(nReadSizeSum < Size && bPass){ // cal write size nReadSize = nBufSize; if (nReadSize > (Size - nReadSizeSum)) nReadSize = Size - nReadSizeSum; // read data block bPass = Flash_Read(hFlash, Offset+nReadSizeSum, pBuf, nReadSize); if (!bPass){ if (bShowMessage) printf("[Error] Flash_Read fail at block-offset %d-%d\r\n", i, (int)Offset+nReadSizeSum); }else{ // verify // verify data for(k=0;k<nReadSize && bPass;k++){ if (*(pBuf+k) != Cnt){ if (bShowMessage) printf("[Error] Verify fail, block:%d, index:%d, read=%Xh, expected=%Xh\r\n", i, nReadSizeSum+k, *(pBuf+k), Cnt); bPass = FALSE; }else{ Cnt++; } } } // nReadSizeSum += nReadSize; } } } if (pBuf) free(pBuf); if (hFlash) Flash_Close(hFlash); // return bPass; }
/** * Read Header from Flash Page-0. **/ int Flash_Hdr_Read(Flash_Hdr *pHdr) { return Flash_Read(0x0, sizeof( Flash_Hdr), (byte*)pHdr); }