首页 > 其他分享 >STM32F407+IAP+Ymodem协议

STM32F407+IAP+Ymodem协议

时间:2024-09-28 09:45:25浏览次数:7  
标签:SECTOR FLASH packet IAP file STM32F407 data uint32 Ymodem

首先硬件,

 BOOT的接线方式是选择方式1,当stm32软件复位可以0x08000000重新启动程序重新加载bootloader程序

移植官方的ymodem协议

common.c
  1 /**
  2   ******************************************************************************
  3   * @file    STM32F4xx_IAP/src/flash_if.c 
  4   * @author  MCD Application Team
  5   * @version V1.0.0
  6   * @date    10-October-2011
  7   * @brief   This file provides all the memory related operation functions.
  8   ******************************************************************************
  9   * @attention
 10   *
 11   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
 12   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
 13   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
 14   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
 15   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
 16   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
 17   *
 18   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
 19   ******************************************************************************
 20   */ 
 21 
 22 /** @addtogroup STM32F4xx_IAP
 23   * @{
 24   */
 25 
 26 /* Includes ------------------------------------------------------------------*/
 27 #include "flash_if.h"
 28 
 29 /* Private typedef -----------------------------------------------------------*/
 30 /* Private define ------------------------------------------------------------*/
 31 /* Private macro -------------------------------------------------------------*/
 32 /* Private variables ---------------------------------------------------------*/
 33 /* Private function prototypes -----------------------------------------------*/
 34 static uint32_t GetSector(uint32_t Address);
 35 
 36 /* Private functions ---------------------------------------------------------*/
 37 
 38 /**
 39   * @brief  Unlocks Flash for write access
 40   * @param  None
 41   * @retval None
 42   */
 43 void FLASH_If_Init(void)
 44 {
 45     // 解锁Flash
 46     HAL_FLASH_Unlock();
 47 
 48     // 清除待处理标志(如果有)
 49     __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR |
 50                            FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);
 51 }
 52 
 53 /**
 54   * @brief  This function does an erase of all user flash area
 55   * @param  StartSector: start of user flash area
 56   * @retval 0: user flash area successfully erased
 57   *         1: error occurred
 58   */
 59 uint32_t FLASH_If_Erase(uint32_t StartSector)
 60 {
 61     uint32_t UserStartSector = FLASH_SECTOR_1;
 62     uint32_t endSector = FLASH_SECTOR_11;
 63     uint32_t i;
 64 
 65     // 获取用户Flash区域的起始扇区
 66     UserStartSector = GetSector(APPLICATION_ADDRESS);
 67 
 68     // 初始化Flash擦除结构体
 69     FLASH_EraseInitTypeDef EraseInitStruct;
 70     EraseInitStruct.TypeErase = FLASH_TYPEERASE_SECTORS;
 71     EraseInitStruct.VoltageRange = FLASH_VOLTAGE_RANGE_3;  // 假设电压范围为2.7V到3.6V
 72     EraseInitStruct.Sector = UserStartSector;
 73     EraseInitStruct.NbSectors = (endSector - UserStartSector) / 8 + 1;
 74 
 75     // 擦除Flash扇区
 76     uint32_t sectorError = 0;
 77     if (HAL_FLASHEx_Erase(&EraseInitStruct, &sectorError) != HAL_OK)
 78     {
 79         // 错误处理:Flash扇区擦除失败
 80         return 1;
 81     }
 82 
 83     return 0;
 84 }
 85 
 86 /**
 87   * @brief  This function writes a data buffer in flash (data are 32-bit aligned).
 88   * @note   After writing data buffer, the flash content is checked.
 89   * @param  FlashAddress: start address for writing data buffer
 90   * @param  Data: pointer on data buffer
 91   * @param  DataLength: length of data buffer (unit is 32-bit word)   
 92   * @retval 0: Data successfully written to Flash memory
 93   *         1: Error occurred while writing data in Flash memory
 94   *         2: Written Data in flash memory is different from expected one
 95   */
 96 uint32_t FLASH_If_Write(__IO uint32_t* FlashAddress, uint32_t* Data, uint32_t DataLength)
 97 {
 98     uint32_t i = 0;
 99 
100     for (i = 0; (i < DataLength) && (*FlashAddress <= (USER_FLASH_END_ADDRESS - 4)); i++)
101     {
102         /* Device voltage range supposed to be [2.7V to 3.6V], the operation will
103            be done by word */
104         if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, *FlashAddress, *(Data + i)) == HAL_OK)
105         {
106             /* Check the written value */
107             if (*(uint32_t*)*FlashAddress != *(Data + i))
108             {
109                 /* Flash content doesn't match SRAM content */
110                 return 2;
111             }
112             /* Increment FLASH destination address */
113             *FlashAddress += 4;
114         }
115         else
116         {
117             /* Error occurred while writing data in Flash memory */
118             return 1;
119         }
120     }
121 
122     return 0;
123 }
124 
125 /**
126   * @brief  Returns the write protection status of user flash area.
127   * @param  None
128   * @retval 0: No write protected sectors inside the user flash area
129   *         1: Some sectors inside the user flash area are write protected
130   */
131 uint16_t FLASH_If_GetWriteProtectionStatus(void)
132 {
133     uint32_t UserStartSector = FLASH_SECTOR_1;
134     uint32_t wrpStatus = 0;
135 
136     // 获取用户Flash区域的起始扇区
137     UserStartSector = GetSector(APPLICATION_ADDRESS);
138 
139     // 初始化选项字节配置结构体
140     FLASH_OBProgramInitTypeDef obInit;
141     HAL_FLASHEx_OBGetConfig(&obInit);
142 
143     // 获取写保护状态
144     wrpStatus = obInit.WRPSector;
145 
146     // 检查是否有写保护的扇区
147     if (((wrpStatus >> (UserStartSector / 8)) & 0xFF) == (0xFF >> (UserStartSector / 8)))
148     {
149         // 没有写保护的扇区
150         return 1;
151     }
152     else
153     {
154         // 有些扇区被写保护
155         return 0;
156     }
157 }
158 
159 /**
160   * @brief  Disables the write protection of user flash area.
161   * @param  None
162   * @retval 1: Write Protection successfully disabled
163   *         2: Error: Flash write unprotection failed
164   */
165 uint32_t FLASH_If_DisableWriteProtection(void)
166 {
167     uint32_t UserStartSector = 1;  // 假设用户Flash区域从第1个扇区开始
168     uint32_t UserWrpSectors = 0;
169 
170     // 获取用户Flash区域的起始扇区
171     UserStartSector = GetSector(APPLICATION_ADDRESS);
172 
173     // 计算需要取消写保护的扇区掩码
174     // 0xFFFFFFFF 是一个32位全1的掩码,减去 (1 << (UserStartSector / 8)) - 1 得到需要取消保护的扇区
175     UserWrpSectors = 0xFFFFFFFF - ((1 << (UserStartSector / 8)) - 1);
176 
177     // 解锁Flash
178     HAL_FLASH_Unlock();
179 
180     // 解锁选项字节
181     HAL_FLASH_OB_Unlock();
182 
183     // 初始化选项字节编程结构体
184     FLASH_OBProgramInitTypeDef obInit;
185     obInit.OptionType = OPTIONBYTE_WRP;  // 选择写保护选项
186     obInit.WRPState = OB_WRPSTATE_DISABLE;  // 设置写保护状态为禁用
187     obInit.WRPSector = UserWrpSectors;   // 设置需要取消保护的扇区
188     obInit.Banks = FLASH_BANK_1;         // 选择Bank1(假设只使用Bank1)
189     obInit.RDPLevel = OB_RDP_LEVEL_1;    // 设置读保护级别
190     obInit.BORLevel = OB_BOR_LEVEL3;     // 设置BOR(Brown-Out Reset)级别
191     // 编程选项字节
192     if (HAL_FLASHEx_OBProgram(&obInit) != HAL_OK)
193     {
194         // 错误处理:Flash写保护禁用失败
195         HAL_FLASH_Lock();              // 锁定Flash
196         HAL_FLASH_OB_Lock();           // 锁定选项字节
197         return 2;                      // 返回错误代码2
198     }
199 
200     // 重新锁定Flash
201     HAL_FLASH_Lock();
202 
203     // 重新锁定选项字节
204     HAL_FLASH_OB_Lock();
205 
206     // 写保护成功禁用
207     return 1;                          // 返回成功代码1
208 }
209 
210 /**
211   * @brief  Gets the sector of a given address
212   * @param  Address: Flash address
213   * @retval The sector of a given address
214   */
215 static uint32_t GetSector(uint32_t Address)
216 {
217   uint32_t sector = 0;
218 
219   if((Address < ADDR_FLASH_SECTOR_1) && (Address >= ADDR_FLASH_SECTOR_0))
220   {
221     sector = FLASH_SECTOR_0;
222   }
223   else if((Address < ADDR_FLASH_SECTOR_2) && (Address >= ADDR_FLASH_SECTOR_1))
224   {
225     sector = FLASH_SECTOR_1;
226   }
227   else if((Address < ADDR_FLASH_SECTOR_3) && (Address >= ADDR_FLASH_SECTOR_2))
228   {
229     sector = FLASH_SECTOR_2;
230   }
231   else if((Address < ADDR_FLASH_SECTOR_4) && (Address >= ADDR_FLASH_SECTOR_3))
232   {
233     sector = FLASH_SECTOR_3;
234   }
235   else if((Address < ADDR_FLASH_SECTOR_5) && (Address >= ADDR_FLASH_SECTOR_4))
236   {
237     sector = FLASH_SECTOR_4;
238   }
239   else if((Address < ADDR_FLASH_SECTOR_6) && (Address >= ADDR_FLASH_SECTOR_5))
240   {
241     sector = FLASH_SECTOR_5;
242   }
243   else if((Address < ADDR_FLASH_SECTOR_7) && (Address >= ADDR_FLASH_SECTOR_6))
244   {
245     sector = FLASH_SECTOR_6;
246   }
247   else if((Address < ADDR_FLASH_SECTOR_8) && (Address >= ADDR_FLASH_SECTOR_7))
248   {
249     sector = FLASH_SECTOR_7;
250   }
251   else if((Address < ADDR_FLASH_SECTOR_9) && (Address >= ADDR_FLASH_SECTOR_8))
252   {
253     sector = FLASH_SECTOR_8;
254   }
255   else if((Address < ADDR_FLASH_SECTOR_10) && (Address >= ADDR_FLASH_SECTOR_9))
256   {
257     sector = FLASH_SECTOR_9;
258   }
259   else if((Address < ADDR_FLASH_SECTOR_11) && (Address >= ADDR_FLASH_SECTOR_10))
260   {
261     sector = FLASH_SECTOR_10;
262   }
263   else/*(Address < FLASH_END_ADDR) && (Address >= ADDR_FLASH_SECTOR_11))*/
264   {
265     sector = FLASH_SECTOR_11;
266   }
267     return sector;
268 }
269 
270 /**
271   * @}
272   */
273 
274 /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
flash_if.c
  1 /**
  2   ******************************************************************************
  3   * @file    STM32F4xx_IAP/src/menu.c 
  4   * @author  MCD Application Team
  5   * @version V1.0.0
  6   * @date    10-October-2011
  7   * @brief   This file provides the software which contains the main menu routine.
  8   *          The main menu gives the options of:
  9   *             - downloading a new binary file, 
 10   *             - uploading internal flash memory,
 11   *             - executing the binary file already loaded 
 12   *             - disabling the write protection of the Flash sectors where the 
 13   *               user loads his binary file.
 14   ******************************************************************************
 15   * @attention
 16   *
 17   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
 18   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
 19   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
 20   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
 21   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
 22   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
 23   *
 24   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
 25   ******************************************************************************
 26   */ 
 27 
 28 /** @addtogroup STM32F4xx_IAP
 29   * @{
 30   */
 31 
 32 /* Includes ------------------------------------------------------------------*/
 33 #include "common.h"
 34 #include "flash_if.h"
 35 #include "menu.h"
 36 #include "ymodem.h"
 37 #include "gpio.h"
 38 /* Private typedef -----------------------------------------------------------*/
 39 /* Private define ------------------------------------------------------------*/
 40 /* Private macro -------------------------------------------------------------*/
 41 /* Private variables ---------------------------------------------------------*/
 42 pFunction Jump_To_Application;
 43 uint32_t JumpAddress;
 44 __IO uint32_t FlashProtection = 0;
 45 uint8_t tab_1024[1024] =
 46   {
 47     0
 48   };
 49 uint8_t FileName[FILE_NAME_LENGTH];
 50 
 51 /* Private function prototypes -----------------------------------------------*/
 52 void SerialDownload(void);
 53 void SerialUpload(void);
 54 
 55 /* Private functions ---------------------------------------------------------*/
 56 
 57 /**
 58   * @brief  Download a file via serial port
 59   * @param  None
 60   * @retval None
 61   */
 62 void SerialDownload(void)
 63 {
 64   uint8_t Number[10] = "          ";
 65   int32_t Size = 0;
 66 
 67   SerialPutString("Waiting for the file to be sent ... (press 'a' to abort)\n\r");
 68   Size = Ymodem_Receive(&tab_1024[0]);
 69   if (Size > 0)
 70   {
 71     SerialPutString("\n\n\r Programming Completed Successfully!\n\r--------------------------------\r\n Name: ");
 72     SerialPutString(FileName);
 73     Int2Str(Number, Size);
 74     SerialPutString("\n\r Size: ");
 75     SerialPutString(Number);
 76     SerialPutString(" Bytes\r\n");
 77     SerialPutString("-------------------\n");
 78   }
 79   else if (Size == -1)
 80   {
 81     SerialPutString("\n\n\rThe image size is higher than the allowed space memory!\n\r");
 82   }
 83   else if (Size == -2)
 84   {
 85     SerialPutString("\n\n\rVerification failed!\n\r");
 86   }
 87   else if (Size == -3)
 88   {
 89     SerialPutString("\r\n\nAborted by user.\n\r");
 90   }
 91   else
 92   {
 93     SerialPutString("\n\rFailed to receive the file!\n\r");
 94   }
 95 }
 96 
 97 /**
 98   * @brief  Upload a file via serial port.
 99   * @param  None
100   * @retval None
101   */
102 void SerialUpload(void)
103 {
104   uint8_t status = 0 ; 
105 
106   SerialPutString("\n\n\rSelect Receive File\n\r");
107 
108   if (GetKey() == CRC16)
109   {
110     /* Transmit the flash image through ymodem protocol */
111     status = Ymodem_Transmit((uint8_t*)APPLICATION_ADDRESS, (const uint8_t*)"UploadedFlashImage.bin", USER_FLASH_SIZE);
112 
113     if (status != 0) 
114     {
115       SerialPutString("\n\rError Occurred while Transmitting File\n\r");
116     }
117     else
118     {
119       SerialPutString("\n\rFile uploaded successfully \n\r");
120     }
121   }
122 }
123 
124 /**
125   * @brief  Display the Main Menu on HyperTerminal
126   * @param  None
127   * @retval None
128   */
129 void Main_Menu(void)
130 {
131   uint8_t key = 0;
132   HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
133   SerialPutString("\r\n======================================================================");
134   SerialPutString("\r\n=              (C) COPYRIGHT 2011 STMicroelectronics                 =");
135   SerialPutString("\r\n=                                                                    =");
136   SerialPutString("\r\n=  STM32F4xx In-Application Programming Application  (Version 1.0.0) =");
137   SerialPutString("\r\n=                                                                    =");
138   SerialPutString("\r\n=                                   By MCD Application Team          =");
139   SerialPutString("\r\n======================================================================");
140   SerialPutString("\r\n\r\n");
141 
142   /* Test if any sector of Flash memory where user application will be loaded is write protected */
143   if (FLASH_If_GetWriteProtectionStatus() == 0)   //判断是不是写保护
144   {
145     FlashProtection = 1;
146   }
147   else
148   {
149     FlashProtection = 0;
150   }
151 
152   while (1)
153   {
154     SerialPutString("\r\n================== Main Menu ============================\r\n\n");
155     SerialPutString("  Download Image To the STM32F4xx Internal Flash ------- 1\r\n\n");
156     SerialPutString("  Upload Image From the STM32F4xx Internal Flash ------- 2\r\n\n");
157     SerialPutString("  Execute The New Program ------------------------------ 3\r\n\n");
158 
159     if(FlashProtection != 0)
160     {
161       SerialPutString("  Disable the write protection ------------------------- 4\r\n\n");
162     }
163 
164     SerialPutString("==========================================================\r\n\n");
165 
166     /* Receive key */
167     key = GetKey();//接收读到命令
168 
169     if (key == 0x31)
170     {
171       /* Download user application in the Flash */
172       SerialDownload();
173     }
174     else if (key == 0x32)
175     {
176       /* Upload user application from the Flash */
177       SerialUpload();
178     }
179     else if (key == 0x33) /* execute the new program */
180     {
181       JumpAddress = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
182       /* Jump to user application */
183       Jump_To_Application = (pFunction) JumpAddress;
184       /* Initialize user application's Stack Pointer */
185       __set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
186       Jump_To_Application();
187     }
188     else if ((key == 0x34) && (FlashProtection == 1))
189     {
190       /* Disable the write protection */
191       switch (FLASH_If_DisableWriteProtection())
192       {
193         case 1:
194         {
195           SerialPutString("Write Protection disabled...\r\n");
196           FlashProtection = 0;
197           break;
198         }
199         case 2:
200         {
201           SerialPutString("Error: Flash write unprotection failed...\r\n");
202           break;
203         }
204         default:
205         {
206         }
207       }
208     }
209     else
210     {
211       if (FlashProtection == 0)
212       {
213         SerialPutString("Invalid Number ! ==> The number should be either 1, 2 or 3\r");
214       }
215       else
216       {
217         SerialPutString("Invalid Number ! ==> The number should be either 1, 2, 3 or 4\r");
218       }
219     }
220   }
221 }
222 
223 /**
224   * @}
225   */
226 
227 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE******/
menu.c
  1 /**
  2   ******************************************************************************
  3   * @file    STM32F4xx_IAP/src/ymodem.c 
  4   * @author  MCD Application Team
  5   * @version V1.0.0
  6   * @date    10-October-2011
  7   * @brief   This file provides all the software functions related to the ymodem 
  8   *          protocol.
  9   ******************************************************************************
 10   * @attention
 11   *
 12   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
 13   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
 14   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
 15   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
 16   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
 17   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
 18   *
 19   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
 20   ******************************************************************************
 21   */
 22 
 23 /** @addtogroup STM32F4xx_IAP
 24   * @{
 25   */ 
 26   
 27 /* Includes ------------------------------------------------------------------*/
 28 #include "flash_if.h"
 29 #include "common.h"
 30 #include "ymodem.h"
 31 #include "string.h"
 32 
 33 /* Private typedef -----------------------------------------------------------*/
 34 /* Private define ------------------------------------------------------------*/
 35 /* Private macro -------------------------------------------------------------*/
 36 /* Private variables ---------------------------------------------------------*/
 37 extern uint8_t FileName[];
 38 
 39 /* Private function prototypes -----------------------------------------------*/
 40 /* Private functions ---------------------------------------------------------*/
 41 
 42 /**
 43   * @brief  Receive byte from sender
 44   * @param  c: Character
 45   * @param  timeout: Timeout
 46   * @retval 0: Byte received
 47   *        -1: Timeout
 48   */
 49 static  int32_t Receive_Byte (uint8_t *c, uint32_t timeout)
 50 {
 51   while (timeout-- > 0)
 52   {
 53     if (SerialKeyPressed(c) == 1)
 54     {
 55       return 0;
 56     }
 57   }
 58   return -1;
 59 }
 60 
 61 /**
 62   * @brief  Send a byte
 63   * @param  c: Character
 64   * @retval 0: Byte sent
 65   */
 66 static uint32_t Send_Byte (uint8_t c)
 67 {
 68   SerialPutChar(c);
 69   return 0;
 70 }
 71 
 72 /**
 73   * @brief  Receive a packet from sender
 74   * @param  data
 75   * @param  length
 76   * @param  timeout
 77   *     0: end of transmission
 78   *    -1: abort by sender
 79   *    >0: packet length
 80   * @retval 0: normally return
 81   *        -1: timeout or packet error
 82   *         1: abort by user
 83   */
 84 static int32_t Receive_Packet (uint8_t *data, int32_t *length, uint32_t timeout)
 85 {
 86   uint16_t i, packet_size;
 87   uint8_t c;
 88   *length = 0;
 89   if (Receive_Byte(&c, timeout) != 0)
 90   {
 91     return -1;
 92   }
 93   switch (c)
 94   {
 95     case SOH:
 96       packet_size = PACKET_SIZE;
 97       break;
 98     case STX:
 99       packet_size = PACKET_1K_SIZE;
100       break;
101     case EOT:
102       return 0;
103     case CA:
104       if ((Receive_Byte(&c, timeout) == 0) && (c == CA))
105       {
106         *length = -1;
107         return 0;
108       }
109       else
110       {
111         return -1;
112       }
113     case ABORT1:
114     case ABORT2:
115       return 1;
116     default:
117       return -1;
118   }
119   *data = c;
120   for (i = 1; i < (packet_size + PACKET_OVERHEAD); i ++)
121   {
122     if (Receive_Byte(data + i, timeout) != 0)
123     {
124       return -1;
125     }
126   }
127   if (data[PACKET_SEQNO_INDEX] != ((data[PACKET_SEQNO_COMP_INDEX] ^ 0xff) & 0xff))
128   {
129     return -1;
130   }
131   *length = packet_size;
132   return 0;
133 }
134 
135 /**
136   * @brief  Receive a file using the ymodem protocol.
137   * @param  buf: Address of the first byte.
138   * @retval The size of the file.
139   */
140 int32_t Ymodem_Receive (uint8_t *buf)
141 {
142   uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD], file_size[FILE_SIZE_LENGTH], *file_ptr, *buf_ptr;
143   int32_t i, packet_length, session_done, file_done, packets_received, errors, session_begin, size = 0;
144   uint32_t flashdestination, ramsource;
145 
146   /* Initialize flashdestination variable */
147   flashdestination = APPLICATION_ADDRESS;
148 
149   for (session_done = 0, errors = 0, session_begin = 0; ;)
150   {
151     for (packets_received = 0, file_done = 0, buf_ptr = buf; ;)
152     {
153       switch (Receive_Packet(packet_data, &packet_length, NAK_TIMEOUT))
154       {
155         case 0:
156           errors = 0;
157           switch (packet_length)
158           {
159             /* Abort by sender */
160             case - 1:
161               Send_Byte(ACK);
162               return 0;
163             /* End of transmission */
164             case 0:
165               Send_Byte(ACK);
166               file_done = 1;
167               break;
168             /* Normal packet */
169             default:
170               if ((packet_data[PACKET_SEQNO_INDEX] & 0xff) != (packets_received & 0xff))
171               {
172                 Send_Byte(NAK);
173               }
174               else
175               {
176                 if (packets_received == 0)
177                 {
178                   /* Filename packet */
179                   if (packet_data[PACKET_HEADER] != 0)
180                   {
181                     /* Filename packet has valid data */
182                     for (i = 0, file_ptr = packet_data + PACKET_HEADER; (*file_ptr != 0) && (i < FILE_NAME_LENGTH);)
183                     {
184                       FileName[i++] = *file_ptr++;
185                     }
186                     FileName[i++] = '\0';
187                     for (i = 0, file_ptr ++; (*file_ptr != ' ') && (i < FILE_SIZE_LENGTH);)
188                     {
189                       file_size[i++] = *file_ptr++;
190                     }
191                     file_size[i++] = '\0';
192                     Str2Int(file_size, &size);
193 
194                     /* Test the size of the image to be sent */
195                     /* Image size is greater than Flash size */
196                     if (size > (USER_FLASH_SIZE + 1))
197                     {
198                       /* End session */
199                       Send_Byte(CA);
200                       Send_Byte(CA);
201                       return -1;
202                     }
203                     /* erase user application area */
204                     FLASH_If_Erase(APPLICATION_ADDRESS);
205                     Send_Byte(ACK);
206                     Send_Byte(CRC16);
207                   }
208                   /* Filename packet is empty, end session */
209                   else
210                   {
211                     Send_Byte(ACK);
212                     file_done = 1;
213                     session_done = 1;
214                     break;
215                   }
216                 }
217                 /* Data packet */
218                 else
219                 {
220                     if(packet_length>=1024)
221                     {
222                         SerialPutString("\r\n----------------1024---------------\r\n");
223                     }
224                     else
225                     {
226                          memcpy(buf_ptr, (&packet_data[0] + PACKET_HEADER), packet_length);
227                     }
228 
229 
230                   ramsource = (uint32_t)buf;
231 
232                   /* Write received data in Flash */
233                   if (FLASH_If_Write(&flashdestination, (uint32_t*) ramsource, (uint16_t) packet_length/4)  == 0)
234                   {
235                     Send_Byte(ACK);
236                   }
237                   else /* An error occurred while writing to Flash memory */
238                   {
239                     /* End session */
240                     Send_Byte(CA);
241                     Send_Byte(CA);
242                     return -2;
243                   }
244                 }
245                 packets_received ++;
246                 session_begin = 1;
247               }
248           }
249           break;
250         case 1:
251           Send_Byte(CA);
252           Send_Byte(CA);
253           return -3;
254         default:
255           if (session_begin > 0)
256           {
257             errors ++;
258           }
259           if (errors > MAX_ERRORS)
260           {
261             Send_Byte(CA);
262             Send_Byte(CA);
263             return 0;
264           }
265           Send_Byte(CRC16);
266           break;
267       }
268       if (file_done != 0)
269       {
270         break;
271       }
272     }
273     if (session_done != 0)
274     {
275       break;
276     }
277   }
278   return (int32_t)size;
279 }
280 
281 /**
282   * @brief  check response using the ymodem protocol
283   * @param  buf: Address of the first byte
284   * @retval The size of the file
285   */
286 int32_t Ymodem_CheckResponse(uint8_t c)
287 {
288   return 0;
289 }
290 
291 /**
292   * @brief  Prepare the first block
293   * @param  timeout
294   *     0: end of transmission
295   * @retval None
296   */
297 void Ymodem_PrepareIntialPacket(uint8_t *data, const uint8_t* fileName, uint32_t *length)
298 {
299   uint16_t i, j;
300   uint8_t file_ptr[10];
301   
302   /* Make first three packet */
303   data[0] = SOH;
304   data[1] = 0x00;
305   data[2] = 0xff;
306   
307   /* Filename packet has valid data */
308   for (i = 0; (fileName[i] != '\0') && (i < FILE_NAME_LENGTH);i++)
309   {
310      data[i + PACKET_HEADER] = fileName[i];
311   }
312 
313   data[i + PACKET_HEADER] = 0x00;
314   
315   Int2Str (file_ptr, *length);
316   for (j =0, i = i + PACKET_HEADER + 1; file_ptr[j] != '\0' ; )
317   {
318      data[i++] = file_ptr[j++];
319   }
320   
321   for (j = i; j < PACKET_SIZE + PACKET_HEADER; j++)
322   {
323     data[j] = 0;
324   }
325 }
326 
327 /**
328   * @brief  Prepare the data packet
329   * @param  timeout
330   *     0: end of transmission
331   * @retval None
332   */
333 void Ymodem_PreparePacket(uint8_t *SourceBuf, uint8_t *data, uint8_t pktNo, uint32_t sizeBlk)
334 {
335   uint16_t i, size, packetSize;
336   uint8_t* file_ptr;
337   
338   /* Make first three packet */
339   packetSize = sizeBlk >= PACKET_1K_SIZE ? PACKET_1K_SIZE : PACKET_SIZE;
340   size = sizeBlk < packetSize ? sizeBlk :packetSize;
341   if (packetSize == PACKET_1K_SIZE)
342   {
343      data[0] = STX;
344   }
345   else
346   {
347      data[0] = SOH;
348   }
349   data[1] = pktNo;
350   data[2] = (~pktNo);
351   file_ptr = SourceBuf;
352   
353   /* Filename packet has valid data */
354   for (i = PACKET_HEADER; i < size + PACKET_HEADER;i++)
355   {
356      data[i] = *file_ptr++;
357   }
358   if ( size  <= packetSize)
359   {
360     for (i = size + PACKET_HEADER; i < packetSize + PACKET_HEADER; i++)
361     {
362       data[i] = 0x1A; /* EOF (0x1A) or 0x00 */
363     }
364   }
365 }
366 
367 /**
368   * @brief  Update CRC16 for input byte
369   * @param  CRC input value 
370   * @param  input byte
371   * @retval None
372   */
373 uint16_t UpdateCRC16(uint16_t crcIn, uint8_t byte)
374 {
375   uint32_t crc = crcIn;
376   uint32_t in = byte | 0x100;
377 
378   do
379   {
380     crc <<= 1;
381     in <<= 1;
382     if(in & 0x100)
383       ++crc;
384     if(crc & 0x10000)
385       crc ^= 0x1021;
386   }
387   
388   while(!(in & 0x10000));
389 
390   return crc & 0xffffu;
391 }
392 
393 
394 /**
395   * @brief  Cal CRC16 for YModem Packet
396   * @param  data
397   * @param  length
398   * @retval None
399   */
400 uint16_t Cal_CRC16(const uint8_t* data, uint32_t size)
401 {
402   uint32_t crc = 0;
403   const uint8_t* dataEnd = data+size;
404 
405   while(data < dataEnd)
406     crc = UpdateCRC16(crc, *data++);
407  
408   crc = UpdateCRC16(crc, 0);
409   crc = UpdateCRC16(crc, 0);
410 
411   return crc&0xffffu;
412 }
413 
414 /**
415   * @brief  Cal Check sum for YModem Packet
416   * @param  data
417   * @param  length
418   * @retval None
419   */
420 uint8_t CalChecksum(const uint8_t* data, uint32_t size)
421 {
422   uint32_t sum = 0;
423   const uint8_t* dataEnd = data+size;
424 
425   while(data < dataEnd )
426     sum += *data++;
427 
428   return (sum & 0xffu);
429 }
430 
431 /**
432   * @brief  Transmit a data packet using the ymodem protocol
433   * @param  data
434   * @param  length
435   * @retval None
436   */
437 void Ymodem_SendPacket(uint8_t *data, uint16_t length)
438 {
439   uint16_t i;
440   i = 0;
441   while (i < length)
442   {
443     Send_Byte(data[i]);
444     i++;
445   }
446 }
447 
448 /**
449   * @brief  Transmit a file using the ymodem protocol
450   * @param  buf: Address of the first byte
451   * @retval The size of the file
452   */
453 uint8_t Ymodem_Transmit (uint8_t *buf, const uint8_t* sendFileName, uint32_t sizeFile)
454 {
455   
456   uint8_t packet_data[PACKET_1K_SIZE + PACKET_OVERHEAD];
457   uint8_t filename[FILE_NAME_LENGTH];
458   uint8_t *buf_ptr, tempCheckSum;
459   uint16_t tempCRC;
460   uint16_t blkNumber;
461   uint8_t receivedC[2], CRC16_F = 0, i;
462   uint32_t errors, ackReceived, size = 0, pktSize;
463 
464   errors = 0;
465   ackReceived = 0;
466   for (i = 0; i < (FILE_NAME_LENGTH - 1); i++)
467   {
468     filename[i] = sendFileName[i];
469   }
470   CRC16_F = 1;
471     
472   /* Prepare first block */
473   Ymodem_PrepareIntialPacket(&packet_data[0], filename, &sizeFile);
474   
475   do 
476   {
477     /* Send Packet */
478     Ymodem_SendPacket(packet_data, PACKET_SIZE + PACKET_HEADER);
479 
480     /* Send CRC or Check Sum based on CRC16_F */
481     if (CRC16_F)
482     {
483        tempCRC = Cal_CRC16(&packet_data[3], PACKET_SIZE);
484        Send_Byte(tempCRC >> 8);
485        Send_Byte(tempCRC & 0xFF);
486     }
487     else
488     {
489        tempCheckSum = CalChecksum (&packet_data[3], PACKET_SIZE);
490        Send_Byte(tempCheckSum);
491     }
492   
493     /* Wait for Ack and 'C' */
494     if (Receive_Byte(&receivedC[0], 10000) == 0)  
495     {
496       if (receivedC[0] == ACK)
497       { 
498         /* Packet transferred correctly */
499         ackReceived = 1;
500       }
501     }
502     else
503     {
504         errors++;
505     }
506   }while (!ackReceived && (errors < 0x0A));
507   
508   if (errors >=  0x0A)
509   {
510     return errors;
511   }
512   buf_ptr = buf;
513   size = sizeFile;
514   blkNumber = 0x01;
515   /* Here 1024 bytes package is used to send the packets */
516   
517   
518   /* Resend packet if NAK  for a count of 10 else end of communication */
519   while (size)
520   {
521     /* Prepare next packet */
522     Ymodem_PreparePacket(buf_ptr, &packet_data[0], blkNumber, size);
523     ackReceived = 0;
524     receivedC[0]= 0;
525     errors = 0;
526     do
527     {
528       /* Send next packet */
529       if (size >= PACKET_1K_SIZE)
530       {
531         pktSize = PACKET_1K_SIZE;
532        
533       }
534       else
535       {
536         pktSize = PACKET_SIZE;
537       }
538       Ymodem_SendPacket(packet_data, pktSize + PACKET_HEADER);
539       /* Send CRC or Check Sum based on CRC16_F */
540       /* Send CRC or Check Sum based on CRC16_F */
541       if (CRC16_F)
542       {
543          tempCRC = Cal_CRC16(&packet_data[3], pktSize);
544          Send_Byte(tempCRC >> 8);
545          Send_Byte(tempCRC & 0xFF);
546       }
547       else
548       {
549         tempCheckSum = CalChecksum (&packet_data[3], pktSize);
550         Send_Byte(tempCheckSum);
551       }
552       
553       /* Wait for Ack */
554       if ((Receive_Byte(&receivedC[0], 100000) == 0)  && (receivedC[0] == ACK))
555       {
556         ackReceived = 1;  
557         if (size > pktSize)
558         {
559            buf_ptr += pktSize;  
560            size -= pktSize;
561            if (blkNumber == (USER_FLASH_SIZE/1024))
562            {
563              return 0xFF; /*  error */
564            }
565            else
566            {
567               blkNumber++;
568            }
569         }
570         else
571         {
572           buf_ptr += pktSize;
573           size = 0;
574         }
575       }
576       else
577       {
578         errors++;
579       }
580     }while(!ackReceived && (errors < 0x0A));
581     /* Resend packet if NAK  for a count of 10 else end of communication */
582     
583     if (errors >=  0x0A)
584     {
585       return errors;
586     }
587     
588   }
589   ackReceived = 0;
590   receivedC[0] = 0x00;
591   errors = 0;
592   do 
593   {
594     Send_Byte(EOT);
595     /* Send (EOT); */
596     /* Wait for Ack */
597     if ((Receive_Byte(&receivedC[0], 10000) == 0)  && receivedC[0] == ACK)
598     {
599       ackReceived = 1;  
600     }
601     else
602     {
603       errors++;
604     }
605   }while (!ackReceived && (errors < 0x0A));
606     
607   if (errors >=  0x0A)
608   {
609     return errors;
610   }
611   
612   /* Last packet preparation */
613   ackReceived = 0;
614   receivedC[0] = 0x00;
615   errors = 0;
616 
617   packet_data[0] = SOH;
618   packet_data[1] = 0;
619   packet_data [2] = 0xFF;
620 
621   for (i = PACKET_HEADER; i < (PACKET_SIZE + PACKET_HEADER); i++)
622   {
623      packet_data [i] = 0x00;
624   }
625   
626   do 
627   {
628     /* Send Packet */
629     Ymodem_SendPacket(packet_data, PACKET_SIZE + PACKET_HEADER);
630 
631     /* Send CRC or Check Sum based on CRC16_F */
632     tempCRC = Cal_CRC16(&packet_data[3], PACKET_SIZE);
633     Send_Byte(tempCRC >> 8);
634     Send_Byte(tempCRC & 0xFF);
635   
636     /* Wait for Ack and 'C' */
637     if (Receive_Byte(&receivedC[0], 10000) == 0)  
638     {
639       if (receivedC[0] == ACK)
640       { 
641         /* Packet transferred correctly */
642         ackReceived = 1;
643       }
644     }
645     else
646     {
647         errors++;
648     }
649   }while (!ackReceived && (errors < 0x0A));
650 
651   /* Resend packet if NAK  for a count of 10  else end of communication */
652   if (errors >=  0x0A)
653   {
654     return errors;
655   }  
656   
657   do 
658   {
659     Send_Byte(EOT);
660     /* Send (EOT); */
661     /* Wait for Ack */
662     if ((Receive_Byte(&receivedC[0], 10000) == 0)  && receivedC[0] == ACK)
663     {
664       ackReceived = 1;  
665     }
666     else
667     {
668       errors++;
669     }
670   }while (!ackReceived && (errors < 0x0A));
671 
672   if (errors >=  0x0A)
673   {
674     return errors;
675   }
676   return 0; /* file transmitted successfully */
677 }
678 
679 /**
680   * @}
681   */
682 
683 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
ymodem.c

 

 

 1  while( HAL_GetTick()-tick<5*1000)
 2    {
 3       FLASH_If_Init();//初始化flash清除中断标志
 4      /* Execute the IAP driver in order to reprogram the Flash */
 5           // IAP_Init();
 6      /* Display main menu */
 7      Main_Menu ();//进入ymodem函数�??
 8 
 9    }
10    if(HAL_GetTick()-tick>5*1000)
11   {
12       /* Keep the user application running */
13            /* Test if user code is programmed starting from address "APPLICATION_ADDRESS" */
14      if (((*(__IO uint32_t*)APPLICATION_ADDRESS) & 0x2FFE0000 ) == 0x20000000)
15      {
16        /* Jump to user application */
17        JumpAddress = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
18        Jump_To_Application = (pFunction) JumpAddress;
19        /* Initialize user application's Stack Pointer */
20        __set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
21        Jump_To_Application();
22      }
23   }
main.c

主程序可以做一些改动

 1 /**
 2   ******************************************************************************
 3   * @file    STM32F4xx_IAP/inc/common.h 
 4   * @author  MCD Application Team
 5   * @version V1.0.0
 6   * @date    10-October-2011
 7   * @brief   This file provides all the headers of the common functions.
 8   ******************************************************************************
 9   * @attention
10   *
11   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
12   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
13   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
14   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
15   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
16   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
17   *
18   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
19   ******************************************************************************
20   */ 
21 
22 /* Define to prevent recursive inclusion -------------------------------------*/
23 #ifndef __COMMON_H
24 #define __COMMON_H
25 
26 /* Includes ------------------------------------------------------------------*/
27 #include "stm32f4xx.h"
28 
29 
30 /* Exported types ------------------------------------------------------------*/
31 /* Exported constants --------------------------------------------------------*/
32 /* Exported macro ------------------------------------------------------------*/
33 /* Constants used by Serial Command Line Mode */
34 #define CMD_STRING_SIZE       128
35 
36 /* Common routines */
37 #define IS_AF(c)  ((c >= 'A') && (c <= 'F'))
38 #define IS_af(c)  ((c >= 'a') && (c <= 'f'))
39 #define IS_09(c)  ((c >= '0') && (c <= '9'))
40 #define ISVALIDHEX(c)  IS_AF(c) || IS_af(c) || IS_09(c)
41 #define ISVALIDDEC(c)  IS_09(c)
42 #define CONVERTDEC(c)  (c - '0')
43 
44 #define CONVERTHEX_alpha(c)  (IS_AF(c) ? (c - 'A'+10) : (c - 'a'+10))
45 #define CONVERTHEX(c)   (IS_09(c) ? (c - '0') : CONVERTHEX_alpha(c))
46 
47 #define SerialPutString(x) Serial_PutString((uint8_t*)(x))
48 
49 /* Exported functions ------------------------------------------------------- */
50 void Int2Str(uint8_t* str,int32_t intnum);
51 uint32_t Str2Int(uint8_t *inputstr,int32_t *intnum);
52 uint32_t GetIntegerInput(int32_t * num);
53 uint32_t SerialKeyPressed(uint8_t *key);
54 uint8_t GetKey(void);
55 void SerialPutChar(uint8_t c);
56 void Serial_PutString(uint8_t *s);
57 void GetInputString(uint8_t * buffP);
58 
59 #endif  /* __COMMON_H */
60 
61 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE******/
common.h
 1 /**
 2   ******************************************************************************
 3   * @file    STM32F4xx_IAP/inc/flash_if.h 
 4   * @author  MCD Application Team
 5   * @version V1.0.0
 6   * @date    10-October-2011
 7   * @brief   This file provides all the headers of the flash_if functions.
 8   ******************************************************************************
 9   * @attention
10   *
11   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
12   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
13   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
14   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
15   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
16   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
17   *
18   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
19   ******************************************************************************
20   */ 
21 
22 /* Define to prevent recursive inclusion -------------------------------------*/
23 #ifndef __FLASH_IF_H
24 #define __FLASH_IF_H
25 
26 /* Includes ------------------------------------------------------------------*/
27 #include "stm32f4xx.h"
28 
29 /* Exported types ------------------------------------------------------------*/
30 /* Exported constants --------------------------------------------------------*/
31 /* Base address of the Flash sectors */
32 #define ADDR_FLASH_SECTOR_0     ((uint32_t)0x08000000) /* Base @ of Sector 0, 16 Kbyte */
33 #define ADDR_FLASH_SECTOR_1     ((uint32_t)0x08004000) /* Base @ of Sector 1, 16 Kbyte */
34 #define ADDR_FLASH_SECTOR_2     ((uint32_t)0x08008000) /* Base @ of Sector 2, 16 Kbyte */
35 #define ADDR_FLASH_SECTOR_3     ((uint32_t)0x0800C000) /* Base @ of Sector 3, 16 Kbyte */
36 #define ADDR_FLASH_SECTOR_4     ((uint32_t)0x08010000) /* Base @ of Sector 4, 64 Kbyte */
37 #define ADDR_FLASH_SECTOR_5     ((uint32_t)0x08020000) /* Base @ of Sector 5, 128 Kbyte */
38 #define ADDR_FLASH_SECTOR_6     ((uint32_t)0x08040000) /* Base @ of Sector 6, 128 Kbyte */
39 #define ADDR_FLASH_SECTOR_7     ((uint32_t)0x08060000) /* Base @ of Sector 7, 128 Kbyte */
40 #define ADDR_FLASH_SECTOR_8     ((uint32_t)0x08080000) /* Base @ of Sector 8, 128 Kbyte */
41 #define ADDR_FLASH_SECTOR_9     ((uint32_t)0x080A0000) /* Base @ of Sector 9, 128 Kbyte */
42 #define ADDR_FLASH_SECTOR_10    ((uint32_t)0x080C0000) /* Base @ of Sector 10, 128 Kbyte */
43 #define ADDR_FLASH_SECTOR_11    ((uint32_t)0x080E0000) /* Base @ of Sector 11, 128 Kbyte */
44 
45 /* End of the Flash address */
46 #define USER_FLASH_END_ADDRESS        0x080FFFFF
47 /* Define the user application size */
48 #define USER_FLASH_SIZE   (USER_FLASH_END_ADDRESS - APPLICATION_ADDRESS + 1)
49 
50 /* Define the address from where user application will be loaded.
51    Note: the 1st sector 0x08000000-0x08003FFF is reserved for the IAP code */
52 #define APPLICATION_ADDRESS   (uint32_t)0x08008000
53 
54 /* Exported macro ------------------------------------------------------------*/
55 /* Exported functions ------------------------------------------------------- */
56 void FLASH_If_Init(void);
57 uint32_t FLASH_If_Erase(uint32_t StartSector);
58 uint32_t FLASH_If_Write(__IO uint32_t* FlashAddress, uint32_t* Data, uint32_t DataLength);
59 uint16_t FLASH_If_GetWriteProtectionStatus(void);
60 uint32_t FLASH_If_DisableWriteProtection(void);
61 
62 #endif  /* __FLASH_IF_H */
63 
64 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE******/
flash_if.h
 1 /**
 2   ******************************************************************************
 3   * @file    STM32F4xx_IAP/inc/menu.h 
 4   * @author  MCD Application Team
 5   * @version V1.0.0
 6   * @date    10-October-2011
 7   * @brief   This file provides all the headers of the menu functions.
 8   ******************************************************************************
 9   * @attention
10   *
11   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
12   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
13   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
14   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
15   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
16   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
17   *
18   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
19   ******************************************************************************
20   */ 
21 
22 /* Define to prevent recursive inclusion -------------------------------------*/
23 #ifndef __MENU_H
24 #define __MENU_H
25 
26 /* Includes ------------------------------------------------------------------*/
27 #include "flash_if.h"
28 
29 /* Private variables ---------------------------------------------------------*/
30 typedef  void (*pFunction)(void);
31 extern pFunction Jump_To_Application;
32 extern uint32_t JumpAddress;
33 /* Exported types ------------------------------------------------------------*/
34 /* Exported constants --------------------------------------------------------*/
35 /* Exported macro ------------------------------------------------------------*/
36 /* Exported functions ------------------------------------------------------- */
37 void Main_Menu(void);
38 
39 #endif  /* __MENU_H */
40 
41 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE******/
menu.h
 1 /**
 2   ******************************************************************************
 3   * @file    STM32F4xx_IAP/inc/ymodem.h 
 4   * @author  MCD Application Team
 5   * @version V1.0.0
 6   * @date    10-October-2011
 7   * @brief   This file provides all the software function headers of the ymodem.c 
 8   *          file.
 9   ******************************************************************************
10   * @attention
11   *
12   * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
13   * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE
14   * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY
15   * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING
16   * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE
17   * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
18   *
19   * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2>
20   ******************************************************************************
21   */
22 
23 /* Define to prevent recursive inclusion -------------------------------------*/
24 #ifndef __YMODEM_H_
25 #define __YMODEM_H_
26 
27 /* Includes ------------------------------------------------------------------*/
28 /* Exported types ------------------------------------------------------------*/
29 /* Exported constants --------------------------------------------------------*/
30 /* Exported macro ------------------------------------------------------------*/
31 #define PACKET_SEQNO_INDEX      (1)
32 #define PACKET_SEQNO_COMP_INDEX (2)
33 
34 #define PACKET_HEADER           (3)
35 #define PACKET_TRAILER          (2)
36 #define PACKET_OVERHEAD         (PACKET_HEADER + PACKET_TRAILER)
37 #define PACKET_SIZE             (128)
38 #define PACKET_1K_SIZE          (1024)
39 
40 #define FILE_NAME_LENGTH        (256)
41 #define FILE_SIZE_LENGTH        (16)
42 
43 #define SOH                     (0x01)  /* start of 128-byte data packet */
44 #define STX                     (0x02)  /* start of 1024-byte data packet */
45 #define EOT                     (0x04)  /* end of transmission */
46 #define ACK                     (0x06)  /* acknowledge */
47 #define NAK                     (0x15)  /* negative acknowledge */
48 #define CA                      (0x18)  /* two of these in succession aborts transfer */
49 #define CRC16                   (0x43)  /* 'C' == 0x43, request 16-bit CRC */
50 
51 #define ABORT1                  (0x41)  /* 'A' == 0x41, abort by user */
52 #define ABORT2                  (0x61)  /* 'a' == 0x61, abort by user */
53 
54 #define NAK_TIMEOUT             (0x100000)
55 #define MAX_ERRORS              (5)
56 
57 /* Exported functions ------------------------------------------------------- */
58 int32_t Ymodem_Receive (uint8_t *);
59 uint8_t Ymodem_Transmit (uint8_t *,const  uint8_t* , uint32_t );
60 
61 #endif  /* __YMODEM_H_ */
62 
63 
64 /*******************(C)COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
ymodem.h

bootloader最好不要加操作系统,给bootloader的size是0x8000,栈大小0x400加上操作系统会造成栈溢出

App 更改Resethandle的地址,让它从0x08008000开始

当需要重新更新程序需要让单片机重启,重新回到bootloader开始运行

__set_FAULTMASK(1);//关闭总中断
NVIC_SystemReset();//请求单片机软件重启

加入这两句话让单片机重启

 

ymodem协议发送和接收的是app的bin文件可以使用secureCRT这个超级终端进行发送ymodem,

 

标签:SECTOR,FLASH,packet,IAP,file,STM32F407,data,uint32,Ymodem
From: https://www.cnblogs.com/mokongking/p/18437020

相关文章