Microcontroller firmware online upgrade method and system
Patent Information
- Application Number
- CN202611368835.1
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-04
- Publication Date
- 2026-10-23
AI Technical Summary
一种微控制器固件在线升级方法及系统,通过主动时序锚定、初始化依赖链保障、通信窗口期自适应等待三项技术手段的协同作用,从根本上解决现有技术中蓝牙OTA升级可靠性差、存在因初始化顺序错误导致系统崩溃的风险、无法在升级开始前确认通信链路处于稳定状态等问题,实现在任意上电条件下均能稳定完成固件升级的技术目标
1、本发明采用主动时序锚定的方案改变蓝牙串口透传模块的上电方式,在微控制器UART外设初始化完成后再触发蓝牙串口透传模块上电,以UART就绪时刻作为蓝牙串口透传模块启动的确定性时间基准,将不可控的异步启动转变为可控的同步启动。
Smart Images

Figure CN122963594A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of system upgrade technology, and specifically to a method and system for online firmware upgrade of a microcontroller. Background Technology
[0002] With the rapid development of IoT technology, the demand for remote maintenance and firmware upgrades of embedded devices is becoming increasingly urgent. Traditional firmware upgrade methods require physical contact with the device, such as firmware burning via JTAG debugging interface, SWD interface, or wired serial port. This method is extremely inconvenient to operate and has high maintenance costs after the device has been deployed in the field.
[0003] Bluetooth wireless communication technology has become an important means of near-field firmware online upgrades due to its advantages such as low power consumption, no need for licensed frequency bands, and low hardware cost. OTA upgrade solutions based on Bluetooth serial port pass-through modules (such as HC-06) are widely used in industrial control, consumer electronics, smart homes, and other fields.
[0004] However, existing technical solutions generally suffer from instability during the upgrade process in engineering practice. Specifically, Bluetooth communication sometimes works normally and sometimes malfunctions after the device is powered on, and this malfunction is random and difficult to eliminate by simply adjusting parameters. These problems seriously affect product reliability and user experience, and are one of the key obstacles restricting the large-scale application of Bluetooth OTA technology.
[0005] For example, the most common initialization scheme for Bluetooth serial port pass-through modules in existing technology is as follows: after the microcontroller is powered on, it performs a fixed-duration delay, and then directly starts UART communication after the delay. This scheme has the following drawbacks: Defect 1: The startup time of the Bluetooth serial port pass-through module is uncertain: After power-on, the Bluetooth serial port pass-through module has a baud rate adaptive window period. During this window, the module samples the bus signal to lock the communication baud rate. The duration of this window period is affected by factors such as internal crystal oscillator deviation, power supply voltage fluctuations, and ambient temperature, and varies significantly between different batches and under different temperature conditions, typically fluctuating between 600 milliseconds and 1200 milliseconds. A fixed delay scheme cannot adapt to these variations; when the fixed delay is less than the actual window period, communication will inevitably fail.
[0006] Second, the fixed delay duration is difficult to determine accurately: If the fixed delay is set too long, a longer waiting time will be required each time the device is powered on, affecting the device's startup speed and user experience; if it is set too short, communication failures may still occur under certain conditions. Engineers often set delay parameters based on experience, lacking scientific basis and failing to guarantee reliable operation in all usage scenarios.
[0007] Thirdly, the communication link quality cannot be detected: The fixed delay scheme uses a blind waiting strategy, and does not verify the communication link quality after the delay ends, directly starting firmware data transmission. If the Bluetooth serial port pass-through module is still in the startup window at this time, the transmitted firmware data will experience bit offsets or frame errors. This may result in upgrade failure or, in severe cases, write erroneous data to Flash, causing permanent damage to the device.
[0008] Another common approach is to rely on the application program to re-execute UART initialization to correct the communication state after communication failure during the BootLoader phase. This approach has the following drawbacks: Defect 1: Upgrade task cannot be completed during the BootLoader stage: If Bluetooth communication is unreliable during the BootLoader stage, firmware upgrades can only be performed after the application starts, thus losing the core value of the BootLoader in preventing upgrades from failing due to application corruption.
[0009] Defect 2: System crashes due to abnormal delay functions: During the BootLoader phase, if developers do not strictly follow the dependency order for initialization, such as calling the delay function before assigning a value to the delay baseline factor (fac_ms), the SysTick timer will be loaded with a value of zero, resulting in abnormal system behavior. Specifically, the program may crash or enter an infinite loop, failing to execute subsequent processes normally. This problem is insidious, triggering only under a specific initialization order, and is difficult to reproduce in regular testing.
[0010] Deficiency 3: The root cause of the problem has not been eliminated: The re-initialization solution only repairs the communication anomaly at the superficial level and does not fundamentally solve the problem of the uncertainty of the Bluetooth serial port pass-through module's startup timing, so the system reliability still cannot be guaranteed.
[0011] Based on the above analysis, the existing technology has the following three fundamental shortcomings: First, there is a lack of proactive control over the startup timing of the Bluetooth serial port pass-through module; the timing depends entirely on the internal state of the module and is unpredictable. Second, the lack of dependency management for the microcontroller initialization order poses a risk of system crash due to incorrect initialization order. Third, the lack of a dynamic detection mechanism for communication link quality makes it impossible to confirm that the communication link is in a stable state before the upgrade begins.
[0012] The above three shortcomings are interconnected and work together. Solving any one aspect alone cannot completely eliminate the instability of the system. Therefore, a synergistic solution needs to be designed. Summary of the Invention
[0013] The purpose of this invention is to provide: A method and system for online firmware upgrade of microcontrollers fundamentally solves the problems of poor reliability of Bluetooth OTA upgrades, the risk of system crash due to incorrect initialization sequence, and the inability to confirm that the communication link is in a stable state before the upgrade begins, through the synergistic effect of three technical means: active timing anchoring, initialization dependency chain guarantee, and adaptive waiting of communication window period. It achieves the technical goal of stable firmware upgrade under any power-on conditions.
[0014] Terminology Explanation: Unless otherwise defined, all technical terms herein have the same meaning as commonly understood by one of ordinary skill in the art to which this invention pertains.
[0015] It should be understood that the above brief description and the following detailed description are exemplary and for illustrative purposes only, and do not limit the subject matter of the invention in any way. In this invention, the singular is used in conjunction with the plural unless otherwise specifically stated. It should also be noted that, unless otherwise stated, the use of “or” or “or” means “and / or”. Furthermore, the use of the term “comprising” and other forms such as “including,” “containing,” and “contains” are not limiting.
[0016] Unless otherwise stated, conventional methods within the scope of the art shall be used.
[0017] Unless specifically defined herein, the use of all commercially available products herein employs standard techniques. For example, it may be carried out using the manufacturer's instructions for use with the kit, or in accordance with methods known in the art or the description of this invention. The techniques and methods described herein can generally be implemented according to conventional methods well known in the art, based on the descriptions in the various summary and more specific documents cited and discussed in this specification.
[0018] The terms “optional / arbitrary” or “optionally / arbitrarily” mean that the event or situation described below may or may not occur, including both the occurrence and non-occurrence of the event or situation.
[0019] The term "host computer" as used in this article refers to an intermediate application that runs on a PC or industrial control computer and is used to monitor, control, and manage lower-level hardware, enabling command issuance, data acquisition, visualization, and storage analysis.
[0020] The term "microcontroller" as used in this article refers to a single-chip microcomputer that integrates the main components of a microcomputer onto a single chip.
[0021] The term "Bluetooth OTA" as used in this article refers to the technology of remotely transmitting and updating device firmware via Bluetooth wireless connection.
[0022] In a first aspect, the present invention provides a method for online firmware upgrade of a microcontroller, comprising the following steps: S1. Initialize the dependency chain; S2. Perform the active timing anchoring process based on the initialization dependency chain; S3. After completing the active timing anchoring, execute the adaptive waiting communication window period; S4. After confirming the stable communication link in step S3, transmit and write firmware data. S5. After the firmware data transmission and writing are completed, a state isolation jump action is performed to complete the online upgrade.
[0023] Based on further solutions to the technical problems of the present invention, or simultaneous solutions to multiple technical problems, the preferred solution in the technical solution provided in the first aspect of the present invention includes: First preferred option: In S1, the rules for ensuring the initialization of the dependency chain include: Rule 1: System clock initialization must be the first of all initialization operations; no other initialization operation may be performed before it. Rule 2: Delay base initialization must be performed before any delay function call and after system clock initialization to ensure that the delay base factor is calculated based on the correct clock frequency; Rule 3: UART peripheral initialization must be performed after delay reference initialization and before the Bluetooth serial port pass-through module enable pin is set high; Rule 4: The operation of setting the enable pin of the Bluetooth serial port pass-through module to high must be performed after the UART peripheral is initialized.
[0024] Second preferred option: The active timing anchoring process in S2 includes the following steps: S21. After the microcontroller is powered on, set the enable pin of the Bluetooth serial port pass-through module to a low level, so that the Bluetooth serial port pass-through module is in a reset or disabled state, preventing the Bluetooth serial port pass-through module from sensing bus signals during the microcontroller initialization process. S22. The microcontroller completes the system clock initialization, delay reference initialization and UART peripheral initialization, so that the UART bus is in a stable idle state or high level; S23. The microcontroller sets the Bluetooth serial port pass-through module enable pin to a high level, and the Bluetooth serial port pass-through module starts up from this moment; the baud rate parameter is locked.
[0025] Furthermore, the coordination relationship between steps S1 and S2: the active timing anchoring process relies on the initialization dependency chain guarantee process to provide the correct initialization order as a prerequisite; if the initialization dependency chain is not guaranteed, the delay_ms call in the active timing anchoring process will fail because fac_ms is zero, which will cause the entire scheme to fail.
[0026] Third preferred option: The steps to implement S3 are as follows: S31. After the microcontroller triggers the Bluetooth serial port pass-through module to power on, it enters a handshake waiting loop and sets the total waiting timeout. S32. In the loop, the microcontroller periodically sends probe data frames in a fixed format via UART, with the probe frame format predefined. S33: The microcontroller waits for the response frame returned by the host computer via the Bluetooth serial port transparent transmission module, and sets the timeout for a single response. S34. Compare the received response data with the expected response frame byte by byte. If the comparison results are consistent, it is determined that the communication link is in a stable state, the Bluetooth serial port transparent transmission module has exited the startup window period, exited the handshake loop, and started firmware transmission. If the comparison results are inconsistent, it is determined that the Bluetooth serial port transparent transmission module is still in the startup window period or the communication link is still unstable. Continue to wait and retry. S35. If no correct response is received within the total timeout period, it is determined that the Bluetooth serial port pass-through module has failed to start or that there is a fault in the communication link. The error status is recorded, and firmware transmission is not performed to prevent erroneous data from being written to Flash.
[0027] Fourth preferred option: Once step S3 confirms that the communication link is stable, firmware data from the host computer is received via the Bluetooth serial port pass-through module. The received firmware data is verified, and once the verification is successful, it is written into the application area of the microcontroller's Flash memory.
[0028] Furthermore, the adaptive waiting scheme for the communication window period further enhances reliability based on the active timing anchoring scheme. The active timing anchoring scheme eliminates the risk of the Bluetooth serial port pass-through module locking into an incorrect baud rate due to noise perception, while the adaptive waiting scheme for the communication window period further confirms that the Bluetooth serial port pass-through module has completed all internal initializations; both are indispensable. If the adaptive waiting scheme for the communication window period is used alone without the active timing anchoring scheme, the handshake mechanism may still receive garbled data caused by baud rate errors and misjudge it as "module not ready," resulting in indefinite waiting and an inability to distinguish between the "module starting up" and "module baud rate error" states, ultimately leading to timeout failure. Through the overall coordination between steps S1 to S3, the uncertainty problem of the Bluetooth serial port pass-through module startup timing is eliminated.
[0029] Fifth preferred option: The state isolation process includes the following steps: S51. Disable global interrupts; S52. Turn off and reset the SysTick timer, and clear all SysTick control registers, load registers and current value registers to zero; S53. Clear all NVIC interrupt enable and suspend flags; S54. Set the interrupt vector table offset register to the starting address of the application so that the application can respond to interrupts correctly; S55. Read the initial value of the main stack pointer from the application's starting address, set the MSP register, then read the reset vector 4 bytes off the application's starting address and execute the jump.
[0030] In a first aspect, the present invention provides a microcontroller firmware online upgrade system, including a host computer, a microcontroller, a Bluetooth serial port transparent transmission module, a timing control unit, an initialization sequence management unit, a communication quality detection unit, a firmware transmission and writing unit, and a state isolation jump unit. The Bluetooth serial port pass-through module connects to the microcontroller via a UART interface. The host computer, running on a PC or industrial control computer, is used to receive the detection data frame sent by the communication quality detection unit through the Bluetooth serial port transparent transmission module and return the response data frame, as well as send the firmware data to be upgraded to the firmware transmission and writing unit through the Bluetooth serial port transparent transmission module. The timing control unit, which runs on the microcontroller, is used to put the enable pin low before the UART peripheral initialization is complete and to put the enable pin high after the UART peripheral initialization is complete. The initialization sequence management unit runs on the microcontroller and is used to execute each initialization operation in a forced order of system clock initialization, delay reference factor assignment, and UART peripheral initialization, so that the delay reference factor is assigned before any delay function call; The communication quality detection unit, which runs on the microcontroller, is used to periodically send probe data frames, receive and verify response data frames, and use the actual quality of the communication link as the standard for judging whether the Bluetooth serial port pass-through module is ready. The firmware transmission and writing unit, which runs on the microcontroller, is used to receive firmware data after the communication quality detection unit confirms that the communication link is stable, verify the firmware data, and write it to the Flash application area. The state isolation jump unit, which runs on the microcontroller, is used to perform state isolation operations and jump to the application area after firmware transmission and writing are completed.
[0031] First preferred option: The microcontroller's Flash storage space is divided into two independent areas: the BootLoader area and the application area. The BootLoader area starts at the lowest address of the Flash and is responsible for firmware reception, verification, and writing; the application area is located in the higher address range of the Flash and stores the running application programs.
[0032] Second preferred option: The timing control unit, initialization sequence management unit, communication quality detection unit, firmware transmission and writing unit, and state isolation jump unit are all stored in the BootLoader area.
[0033] Third preferred option: The address allocation scheme of the Flash is as follows: the starting address of the BootLoader area is 0x08000000, and the allocated space does not exceed 16KB; the starting address of the application area is 0x08004000, and the remaining Flash space is allocated.
[0034] Fourth preferred option: The microcontroller has the following conditions: Condition 1: The microcontroller must have at least one UART serial port peripheral; Condition 2: The microcontroller has at least one controllable general-purpose output pin for controlling the enable signal of the Bluetooth serial port pass-through module; Condition 3: When the Bluetooth serial port pass-through module has an enable control pin and the pin is active low, the Bluetooth serial port pass-through module is in a reset or disabled state. Condition 4: The microcontroller's Flash space must have at least two independently programmable sectors, one for storing the BootLoader and the other for storing the application program.
[0035] Compared with the prior art, the present invention has at least the following beneficial effects: 1. This invention adopts an active timing anchoring scheme to change the power-on method of the Bluetooth serial port pass-through module. The Bluetooth serial port pass-through module is triggered to power on after the microcontroller UART peripheral initialization is completed. The UART ready time is used as the deterministic time reference for the start of the Bluetooth serial port pass-through module, transforming the uncontrollable asynchronous start into a controllable synchronous start.
[0036] 2. The present invention adopts an initialization dependency chain guarantee scheme to clearly define the initialization order of each component of the microcontroller and forces the delay reference factor to be initialized before any delay function call, thereby eliminating the risk of system crash due to incorrect initialization order.
[0037] 3. The present invention adopts a communication window period adaptive waiting scheme to replace the fixed duration waiting with the actual state of the communication link quality. Through a handshake mechanism that periodically sends probe frames and verifies the response, it dynamically determines whether the Bluetooth serial port pass-through module has exited the startup window period, ensuring that firmware transmission only begins after the communication link is completely stable.
[0038] 4. This invention solves the problem of uncertainty in the startup of Bluetooth serial port pass-through modules that cannot be completely eliminated by using any one of these methods alone, through collaborative active timing anchoring, initialization dependency chain guarantee, and adaptive waiting scheme for communication window period. Attached Figure Description
[0039] Figure 1 This is a flowchart of the method of the present invention. Detailed Implementation
[0040] The following non-limiting embodiments are intended to enable those skilled in the art to gain a more comprehensive understanding of the present invention, but do not limit the invention in any way. The following content is merely an exemplary description of the scope of protection claimed by the present invention, and those skilled in the art can make various changes and modifications to the present invention based on the disclosed content, and such changes should also fall within the scope of protection claimed by the present invention.
[0041] The present invention will be further described below by way of specific embodiments. Unless otherwise specified, all instruments, systems, devices, products, etc., used in the embodiments of the present invention are obtained through conventional commercial means.
[0042] Example 1 This embodiment provides a method for online firmware upgrade of a microcontroller. It should be noted that "system" in "system clock initialization" and "system clock frequency" refers to the hardware system clock of the microcontroller (MCU), which is the internal clock source of the MCU and not the entire upgrade system; it is a standard term in the embedded technology field. "System after system power-on" refers to the entire device hardware system, i.e., the complete embedded device including the microcontroller, Bluetooth module, power supply, etc.
[0043] Reference Figure 1 As shown, the specific steps include: S1. Initialize the dependency chain: Before the UART peripheral is initialized, each initialization operation is executed in the order of system clock initialization, delay reference factor calculation and assignment, and UART peripheral initialization. The delay reference factor is dynamically calculated from the current system clock frequency, and the assignment operation of the delay reference factor is completed before any delay function call. Specifically, the technical principle for ensuring the initialization dependency chain is as follows: In the delay function implemented based on the SysTick timer, the calculation of the delay duration depends on a pre-calculated delay reference factor fac_ms. This delay reference factor fac_ms is determined by the system clock frequency, and its calculation formula is as follows: fac_ms = SystemCoreClock / SysTick divider coefficient / 1000; When the delay function is called, it obtains the load value of the SysTick timer by multiplying the target delay duration (in milliseconds) by fac_ms, thereby generating an accurate delay; If the assignment operation of fac_ms (i.e., the call to the delay_init function) is not executed before the delay function is called, the value of fac_ms is zero, which is the default initial value of the global variable. At this time, the SysTick load value calculated by the delay function is also zero. The SysTick timer will count down with the load value of zero. Its behavior varies depending on the microcontroller model. It usually manifests as the timer triggering immediately, producing a very short invalid delay, or causing an unexpected interrupt, which eventually causes the program to crash.
[0044] However, the problem is insidious because in application programs, the initialization order is usually quite standardized, and the delay_init function is called before other initializations, making the problem difficult to expose. In contrast, in the BootLoader program, due to the small code size and fewer initialization steps, developers are likely to overlook the dependencies in the initialization order, causing the problem to be triggered in the BootLoader stage and manifesting as random system crashes, which are extremely difficult to locate.
[0045] Furthermore, in this embodiment, the correctness of the initialization dependency chain is ensured by the following rules: Rule 1: System clock initialization (SystemInit) must be the first initialization operation to be executed; no other initialization operation may be executed before it. Rule 2: Delay base initialization (delay_init, which completes the assignment of fac_ms) must be performed before any delay function call and after the system clock initialization to ensure that fac_ms is calculated based on the correct clock frequency; Rule 3: UART peripheral initialization must be performed after delay reference initialization and before the Bluetooth serial port pass-through module enable pin is set high; Rule 4: The operation of setting the enable pin of the Bluetooth serial port pass-through module high must be performed after the UART peripheral is initialized; Furthermore, rules one through four constitute a complete initialization dependency chain, with the following interdependencies: Executes system clock initialization (SystemInit); prerequisites: configures and provides an accurate system clock frequency. Perform delay baseline initialization (delay_init) and assign a value to the parameter fac_ms; prerequisite: system clock initialization is complete, which can provide accurate hardware delay baseline capabilities; Execute serial port 1 peripheral initialization uart1_init; prerequisites: delay function initialization completed, system clock stable, UART hardware bus enters configurable stable state; The corresponding GPIO pin outputs a high level to complete the power-on startup operation of the Bluetooth serial port transparent transmission module; prerequisites: UART serial port peripheral initialization is complete, and the serial communication hardware channel is ready; Call the millisecond-level delay function delay_ms to reserve the waiting time for the Bluetooth serial port pass-through module to complete the power-on startup; prerequisite: the power supply pin of the Bluetooth serial port pass-through module is set high, and the hardware power-on process of the Bluetooth serial port pass-through module begins. Execute the device communication handshake verification process; prerequisites: the Bluetooth serial port transparent transmission module is powered on and running stably, and the serial port transmit and receive links are smooth and stable. The firmware data transfer process has officially begun; By following the dependency chain described above, the risk of system crashes due to incorrect initialization order can be eliminated.
[0046] S2. Active timing anchoring: After the microcontroller is powered on, before performing UART peripheral initialization, the enable pin of the Bluetooth serial port pass-through module is set to low level, so that the Bluetooth serial port pass-through module is in a reset state; after the UART peripheral initialization is completed, the enable pin of the Bluetooth serial port pass-through module is set to high level, triggering the Bluetooth serial port pass-through module to power on and start. Specifically, the technical principle of active timing anchoring is as follows: After power-on, the Bluetooth serial port pass-through module has a baud rate adaptive window period. During this window, the module continuously monitors the signals on the UART bus, infers the communication baud rate by detecting the start bit width, and latches the inferred result. If the microcontroller's UART peripheral has not yet completed initialization during the window, there may be level transition noise or incomplete data frames on the bus. The Bluetooth serial port pass-through module may misinterpret the noise as a valid communication signal, thereby locking in an incorrect baud rate parameter, leading to subsequent communication failure.
[0047] In this embodiment, the specific process of active timing anchoring includes the following steps: S21. After the microcontroller is powered on, immediately set the enable pin of the Bluetooth serial port pass-through module to a low level, so that the Bluetooth serial port pass-through module is in a reset or disabled state, preventing the Bluetooth serial port pass-through module from sensing bus signals during the microcontroller initialization process; it should be noted that the enable pin refers to the EN pin. S22. The microcontroller completes system clock initialization, delay reference initialization and UART peripheral initialization to ensure that the UART bus is in a stable idle state or high level. S23. The microcontroller sets the enable pin of the Bluetooth serial port transparent transmission module to a high level, and the Bluetooth serial port transparent transmission module starts up from this moment. Since the UART bus is in a stable idle state at this time, the Bluetooth serial port transparent transmission module senses a stable bus signal within the baud rate adaptive window period and can correctly lock the baud rate parameter. Through steps S21-S23, the startup time of the Bluetooth serial port pass-through module is actively controlled by the microcontroller, forming a deterministic sequential relationship with the completion time of UART initialization, eliminating the competition conditions between the two, and realizing complete controllability of timing.
[0048] An example implementation of the above steps is shown below: c / S21: Before all initializations, first put the Bluetooth serial port pass-through module into the reset state. / GPIO_ResetBits(BT_EN_PORT, BT_EN_PIN); / Setting the BT_EN pin low disables the Bluetooth serial port pass-through module. / / S22: Complete the microcontroller initialization in the correct order. / SystemInit(); System clock initialization / delay_init(); Delay base initialization (assigning a value to fac_ms) / uart1_init(9600); / UART peripheral initialization, bus enters stable idle state. / delay_ms(100); Waiting for UART to become fully stable / / S23: Release the Bluetooth serial port pass-through module reset and start from a determined time. / GPIO_SetBits(BT_EN_PORT, BT_EN_PIN); / When the BT_EN pin is set high, the Bluetooth serial port pass-through module starts up. / In this embodiment, the coordination relationship between steps S1 and S2 is as follows: the active timing anchoring process relies on the initialization dependency chain guarantee process to provide the correct initialization order as a prerequisite; if the initialization dependency chain is not guaranteed, the delay_ms call in the active timing anchoring process will fail because fac_ms is zero, which will cause the entire scheme to fail.
[0049] S3. Adaptive waiting communication window period: After the Bluetooth serial port transparent transmission module is powered on, it periodically sends a probe data frame of a predetermined format to the host computer via UART within the preset total timeout period, and waits to receive a response data frame; the received response data frame is compared with the expected response frame. If the comparison is consistent, the communication link is determined to be stable and the waiting is exited; if the comparison is inconsistent or no response is received, the waiting continues to be retried; if no correct response is received after the total timeout period, the firmware transmission is refused to start. Preferably, the preset total timeout is 2000 milliseconds to 5000 milliseconds; the periodic transmission interval is 50 milliseconds to 200 milliseconds; the probe data frame is a predefined fixed byte sequence, and the expected response frame is a fixed byte sequence corresponding to the probe data frame, and the two are different; the comparison operation is a byte-by-byte full comparison, and any inconsistency of any byte is judged as a comparison failure.
[0050] Specifically, the technical principle of adaptive waiting for communication windows is as follows: Even after active timing anchoring is completed, the Bluetooth serial port pass-through module still requires a certain amount of time to complete internal initialization. This time varies depending on factors such as module batch, power supply conditions, and temperature. A fixed delay approach cannot accommodate these variations. This invention proposes using the actual quality of the communication link as the standard for judging whether the Bluetooth serial port pass-through module is ready, and dynamically determining the waiting time through a handshake mechanism. The specific implementation steps are as follows: S31. After the microcontroller triggers the Bluetooth serial port pass-through module to power on, it enters a handshake waiting loop and sets the total waiting timeout (e.g., 3000 milliseconds).
[0051] S32. In the loop, the microcontroller periodically sends probe data frames in a fixed format via UART. The probe frame format is predefined by the host computer, for example, {0xAF, 0x25, 0x52, 0x04}. The frame content is designed to have an extremely low probability of misjudging random noise.
[0052] S33: The microcontroller waits for the response frame returned by the host computer via the Bluetooth serial port pass-through module and sets the single response wait timeout (e.g., 100 milliseconds).
[0053] S34. Perform a byte-by-byte comparison between the received response data and the expected response frame (e.g., {0xAF, 0x25, 0x52, 0x05}). If the comparison results match, it is determined that the communication link is in a stable state, the Bluetooth serial port pass-through module has exited the startup window, exited the handshake loop, and started firmware transmission. If the comparison results do not match (e.g., receiving erroneous data with bit offset), it is determined that the Bluetooth serial port pass-through module is still in the startup window or the communication link is still unstable, and it continues to wait and retry.
[0054] S35. If no correct response is received within the total timeout period, it is determined that the Bluetooth serial port pass-through module has failed to start or that there is a fault in the communication link. The error status is recorded, and firmware transmission is not performed to prevent erroneous data from being written to Flash.
[0055] An example implementation of the handshake mechanism described above is shown below: c #define PROBE_FRAME_LEN4 #define PROBE_TOTAL_TIMEOUT3000U / Total timeout: 3000 milliseconds / #define PROBE_RETRY_INTERVAL 100U / Retry interval: 100 milliseconds / / Probe frames and expected response frames / static const uint8_t probe_frame[PROBE_FRAME_LEN] = {0xAF, 0x25,0x52, 0x04}; static const uint8_t ack_frame[PROBE_FRAME_LEN]= {0xAF, 0x25, 0x52,0x05}; uint8_t BT_WaitReady(void) { uint8_trx_buf[PROBE_FRAME_LEN]; uint32_t total_start = GetTick(); while ((GetTick() - total_start) <PROBE_TOTAL_TIMEOUT) { / Send probe frames / UART_SendBytes(probe_frame, PROBE_FRAME_LEN); / Waiting for a response / uint32_t retry_start = GetTick(); while ((GetTick() - retry_start) <PROBE_RETRY_INTERVAL) { if (UART_DataReady()>= PROBE_FRAME_LEN) { UART_ReceiveBytes(rx_buf, PROBE_FRAME_LEN); / Byte-by-byte comparison of response frames / if (memcmp(rx_buf, ack_frame, PROBE_FRAME_LEN) == 0) { return 1; The communication link is stable; the upgrade can begin. / } /
[0056] Error data received (e.g., 0xB0 0x5D 0x32 0xXX due to bit offset). This indicates that the Bluetooth serial port pass-through module is still in the startup window. Continue waiting, do not perform firmware transfer. / } } } return 0; Timeout occurred; the Bluetooth serial port pass-through module is not ready, upgrade refused. / } Compared with existing fixed delay schemes, the adaptive waiting scheme has the following advantages: when the Bluetooth serial port pass-through module starts up quickly, the waiting can end early, shortening the upgrade preparation time; when the Bluetooth serial port pass-through module starts up slowly, the waiting time can be extended to ensure stable communication; and when there is a fault in the communication link, the upgrade can be actively rejected to prevent the Flash from being damaged by erroneous data.
[0057] It should be noted that the adaptive waiting scheme for the communication window period further improves reliability based on the active timing anchoring scheme. The active timing anchoring scheme eliminates the risk of the Bluetooth serial port pass-through module locking into an incorrect baud rate due to noise perception, while the adaptive waiting scheme for the communication window period further confirms that the Bluetooth serial port pass-through module has completed all internal initializations. Both are indispensable. If the adaptive waiting scheme for the communication window period is used alone without the active timing anchoring scheme, the handshake mechanism may still receive garbled data caused by the baud rate error and misjudge it as "module not ready," resulting in indefinite waiting. It cannot distinguish between the two states of "module startup" and "module baud rate error," ultimately leading to timeout failure. Through the overall coordination between steps S1 to S3, the uncertainty problem of the Bluetooth serial port pass-through module startup timing is eliminated.
[0058] S4. Transmitting and writing firmware: After confirming the stability of the communication link in step S3, the firmware data from the host computer is received through the Bluetooth serial port transparent transmission module. The received firmware data is verified, and after the verification is successful, it is written into the application area of the microcontroller Flash. S5. State Isolation Jump to Complete Online Upgrade: After firmware transmission and writing are completed, global interrupts are disabled, SysTick timer is reset, all interrupt enable and pending flags are cleared, interrupt vector table offset is reset, and then the application area is jumped to execute the new firmware. Among them, resetting SysTick timer includes setting all SysTick control register, load register and current value register to zero; clearing all interrupt enable and pending flags includes writing all 1 values to all registers in NVIC interrupt clear enable register group and interrupt clear pending register group.
[0059] Specifically, to prevent the hardware state during the BootLoader phase from affecting the normal operation of the application program, the state isolation process when the BootLoader jumps to the application includes the following steps: S51. Disable global interrupts to prevent interrupt service routines from being triggered during jumps, which could disrupt the program execution flow. S52. Disable and reset the SysTick timer, clearing all SysTick control registers, load registers, and current value registers to eliminate the impact of the timer state left by the BootLoader on the application. S53. Clear all NVIC interrupt enable and suspend flags to ensure that the application starts running from a clean interrupt state; S54. Set the interrupt vector table offset register (SCB->VTOR) to the starting address of the application program so that the application program can respond to interrupts correctly; S55. Read the initial value of the main stack pointer from the application's starting address, set the MSP register, then read the reset vector 4 bytes off the application's starting address and execute the jump; After the application program starts, it will begin execution from its own reset handling function, and re-complete the entire initialization process, including re-calling delay_init to assign the value to fac_ms, to ensure that the application runtime environment is completely isolated from the BootLoader and that the communication status is corrected.
[0060] The following is an example implementation code for the above jump process: c void JumpToApplication(uint32_t Application_start_addr) { typedef void ( Application EntryFunc)(void); Application EntryFunc application_entry; uint32_t application_reset_vector; / S51: Disable global interrupts / __disable_irq(); / S52: Reset SysTick timer / SysTick->CTRL = 0x00000000; SysTick->LOAD = 0x00000000; SysTick->VAL = 0x00000000; / S53: Clear all NVIC interrupt enable and suspend flags. / for (uint8_t i = 0; i<8; i++) { NVIC->ICER[i] = 0xFFFFFFFF; / Turn off all interrupts. / NVIC->ICPR[i] = 0xFFFFFFFF; / Clear all hanging signs / } / S54: Set interrupt vector table offset / SCB->VTOR = application_start_addr; / S55: Read the application reset vector and jump. / application_reset_vector = (__IO uint32_t (application_start_addr + 4); application_entry = (applicationEntryFunc)application_reset_vector; / Set the main stack pointer / __set_MSP( (__IO uint32_t (Application_start_addr); / Execute jump / application_entry(); }
[0061] Example 2 Based on the method described in Embodiment 1, this embodiment provides a microcontroller firmware online upgrade system, which includes a microcontroller, a Bluetooth serial port transparent transmission module, a timing control unit, an initialization sequence management unit, a communication quality detection unit, a firmware transmission and writing unit, and a state isolation jump unit. The host computer, running on a PC or industrial computer, is used to manage firmware upgrade data, respond to probe frames from the communication quality detection unit, send firmware data packets to the firmware transmission and writing unit, and receive upgrade completion confirmations returned by the status isolation jump unit; the host computer communicates wirelessly with the microcontroller via a Bluetooth serial port pass-through module. The Bluetooth serial port pass-through module connects to the microcontroller via a UART interface, and its enable pin is connected to a general-purpose output pin of the microcontroller. It should be noted that existing Bluetooth serial port pass-through modules are typically directly connected to the power supply and start simultaneously with the entire device hardware system. The microcontroller cannot control the startup time of the Bluetooth serial port pass-through module. However, in this embodiment, the Bluetooth serial port pass-through module connects to the microcontroller via a UART interface, and its enable pin is connected to a general-purpose output pin of the microcontroller, allowing the microcontroller to actively control the power-on and reset of the Bluetooth serial port pass-through module. It should also be noted that this Bluetooth serial port pass-through module can be replaced with a Bluetooth module, Zigbee module, LoRa module, NFC near-field communication module, etc. The timing control unit, which runs on the microcontroller, is used to set the enable pin low before the UART peripheral initialization is completed and set the enable pin high after the UART peripheral initialization is completed, thereby realizing active control of the startup timing of the Bluetooth serial port pass-through module. The initialization sequence management unit runs on the microcontroller and is used to execute each initialization operation in a forced order of system clock initialization, delay reference factor assignment, and UART peripheral initialization, ensuring that the delay reference factor is assigned before any delay function call. The communication quality detection unit, which runs on the microcontroller, is used to periodically send probe data frames, receive and verify response data frames, and use the actual quality of the communication link as the standard for judging whether the Bluetooth serial port pass-through module is ready. The firmware transmission and writing unit, which runs on the microcontroller, is used to receive firmware data after the communication quality detection unit confirms that the communication link is stable, verify the firmware data, and write it to the Flash application area. The state isolation jump unit runs on the microcontroller and is used to perform state isolation operations such as interrupt disabling, SysTick reset, interrupt flag clearing, and vector table resetting after firmware transmission and writing are completed, and then jump to the application area.
[0062] The microcontroller's Flash storage space is divided into two independent areas: a BootLoader area and an application area. The BootLoader area starts at the lowest address of the Flash memory and is responsible for firmware reception, verification, and writing. The timing control unit, initialization sequence management unit, communication quality detection unit, firmware transmission and writing unit, and state isolation jump unit are all stored in the BootLoader area. It should be noted that the microcontroller platform can be selected from series such as GD32, ESP32, and nRF52. The application area is located in the high address range of Flash and stores the normally running application. The specific Flash address allocation scheme is as follows: the BootLoader area starts at address 0x08000000 and is allocated no more than 16KB; the application area starts at address 0x08004000 and is allocated the remaining Flash space. After the system powers on, the BootLoader runs first. The BootLoader determines whether an upgrade operation is needed. If so, it receives the new firmware via Bluetooth and writes it to the application area. After the upgrade is complete, it jumps to the application area for execution; otherwise, it directly jumps to the application area for execution.
[0063] This embodiment can be implemented on any microcontroller platform that meets the following conditions: Condition 1: The microcontroller must have at least one UART serial port peripheral; Condition 2: The microcontroller has at least one controllable general-purpose output pin for controlling the enable signal of the Bluetooth serial port pass-through module; Condition 3: When the Bluetooth serial port pass-through module has an enable control pin and the pin is active low, the Bluetooth serial port pass-through module is in a reset or disabled state. Condition 4: The microcontroller's Flash space must have at least two independently programmable sectors, one for storing the BootLoader and the other for storing the application program.
[0064] For example, a typical hardware implementation platform is the STM32F103C8T6 microcontroller, which is used in conjunction with the HC-06 Bluetooth serial port pass-through module. However, it is not limited to this. Any microcontroller platform that meets the above four conditions can implement this invention.
[0065] It should be noted that in this embodiment, the BootLoader program is deployed in the low address region of the microcontroller's Flash memory, with its starting address being the Flash base address. The application program is deployed in the high address region of the Flash memory, and its starting address must be aligned with the ending address of the BootLoader area. The interrupt vector table address of the application program must be consistent with its actual starting address in the Flash memory; the default Flash base address cannot be used, otherwise interrupts will not respond correctly after a jump.
[0066] It should be further noted that the upgrade system in this embodiment can be integrated into PC-based host computer software, mobile APP upgrade client, cloud-based OTA management platform, firmware encryption and signing tools, etc., or it can be integrated into smart home devices (such as smart door locks, smart lighting control, etc.), wearable devices (such as smartwatches, health monitoring bracelets, etc.), industrial sensor nodes, medical monitoring equipment, and automotive electronic control units.
[0067] Detection Example 1 On the same hardware platform (STM32F103C8T6, main frequency 72MHz, HC-06 Bluetooth serial port pass-through module, communication baud rate 9600bps), the solution was compared with the existing fixed delay solution. The test environment temperature range was 20 degrees Celsius to 45 degrees Celsius, and the test sample size was 100 power-on cycles. The comparison data is shown in Table 1 below. Table 1
[0068] Finally, it should be noted that the above content is only used to illustrate the technical solution of the present invention, and is not intended to limit the scope of protection of the present invention. Simple modifications or equivalent substitutions made by those skilled in the art to the technical solution of the present invention do not depart from the essence and scope of the technical solution of the present invention.
Claims
1. A method for online firmware upgrade of a microcontroller, characterized in that, Includes the following steps: S1. Initialize the dependency chain; S2. Perform the active timing anchoring process based on the initialization dependency chain; S3. After completing the active timing anchoring, execute the adaptive waiting communication window period; S4. After confirming the stable communication link in step S3, transmit and write firmware data. S5. After the firmware data transmission and writing are completed, a state isolation jump action is performed to complete the online upgrade.
2. The microcontroller firmware online upgrade method according to claim 1, characterized in that, In S1, the rules for ensuring the initialization of the dependency chain include: Rule 1: System clock initialization must be the first of all initialization operations; no other initialization operation may be performed before it. Rule 2: Delay base initialization must be performed before any delay function call and after system clock initialization to ensure that the delay base factor is calculated based on the correct clock frequency; Rule 3: UART peripheral initialization must be performed after delay reference initialization and before the Bluetooth serial port pass-through module enable pin is set high; Rule 4: The operation of setting the enable pin of the Bluetooth serial port pass-through module to high must be performed after the UART peripheral is initialized.
3. The microcontroller firmware online upgrade method according to claim 2, characterized in that, The active timing anchoring process in S2 includes the following steps: S21. After the microcontroller is powered on, set the enable pin of the Bluetooth serial port pass-through module to a low level, so that the Bluetooth serial port pass-through module is in a reset or disabled state, preventing the Bluetooth serial port pass-through module from sensing bus signals during the microcontroller initialization process. S22. The microcontroller completes the system clock initialization, delay reference initialization and UART peripheral initialization, so that the UART bus is in a stable idle state or high level; S23. The microcontroller sets the Bluetooth serial port pass-through module enable pin to a high level, and the Bluetooth serial port pass-through module starts up from this moment; the baud rate parameter is locked.
4. The microcontroller firmware online upgrade method according to claim 2, characterized in that, The steps to implement S3 are as follows: S31. After the microcontroller triggers the Bluetooth serial port pass-through module to power on, it enters a handshake waiting loop and sets the total waiting timeout. S32. In the loop, the microcontroller periodically sends probe data frames in a fixed format via UART, with the probe frame format predefined. S33: The microcontroller waits for the response frame returned by the host computer via the Bluetooth serial port transparent transmission module, and sets the timeout for a single response. S34. Compare the received response data with the expected response frame byte by byte. If the comparison results are consistent, it is determined that the communication link is in a stable state, the Bluetooth serial port transparent transmission module has exited the startup window period, exited the handshake loop, and started firmware transmission. If the comparison results are inconsistent, it is determined that the Bluetooth serial port transparent transmission module is still in the startup window period or the communication link is still unstable. Continue to wait and retry. S35. If no correct response is received within the total timeout period, it is determined that the Bluetooth serial port pass-through module has failed to start or that there is a fault in the communication link. The error status is recorded, and firmware transmission is not performed to prevent erroneous data from being written to Flash.
5. The microcontroller firmware online upgrade method according to claim 1, characterized in that, Once step S3 confirms that the communication link is stable, firmware data from the host computer is received via the Bluetooth serial port pass-through module. The received firmware data is verified, and once the verification is successful, it is written into the application area of the microcontroller's Flash memory.
6. The microcontroller firmware online upgrade method according to claim 1, characterized in that, The state isolation process includes the following steps: S51. Disable global interrupts; S52. Turn off and reset the SysTick timer, clearing all of the SysTick timer's control register, load register, and current value register to zero. S53. Clear all NVIC interrupt enable and suspend flags; S54. Set the interrupt vector table offset register to the starting address of the application so that the application can respond to interrupts correctly; S55. Read the initial value of the main stack pointer from the application's starting address, set the MSP register, then read the reset vector 4 bytes off the application's starting address and execute the jump.
7. A microcontroller firmware online upgrade system, characterized in that, The microcontroller firmware online upgrade method according to any one of claims 1-6 includes a host computer, a microcontroller, a Bluetooth serial port transparent transmission module, a timing control unit, an initialization sequence management unit, a communication quality detection unit, a firmware transmission and writing unit, and a state isolation jump unit. The Bluetooth serial port pass-through module connects to the microcontroller via a UART interface. The host computer, running on a PC or industrial control computer, is used to receive the probe data frames sent by the communication quality detection unit through the Bluetooth serial port transparent transmission module and return the response data frames, as well as send the firmware data to be upgraded to the firmware transmission and writing unit through the Bluetooth serial port transparent transmission module. The timing control unit, which runs on the microcontroller, is used to put the enable pin low before the UART peripheral initialization is complete and to put the enable pin high after the UART peripheral initialization is complete. The initialization sequence management unit runs on the microcontroller and is used to execute each initialization operation in a forced order of system clock initialization, delay reference factor assignment, and UART peripheral initialization, so that the delay reference factor is assigned before any delay function call; The communication quality detection unit, which runs on the microcontroller, is used to periodically send probe data frames, receive and verify response data frames, and use the actual quality of the communication link as the standard for judging whether the Bluetooth serial port pass-through module is ready. The firmware transmission and writing unit, which runs on the microcontroller, is used to receive firmware data after the communication quality detection unit confirms that the communication link is stable, verify the firmware data, and write it to the Flash application area. The state isolation jump unit, which runs on the microcontroller, is used to perform state isolation operations and jump to the application area after firmware transmission and writing are completed.
8. A microcontroller firmware online upgrade system according to claim 7, characterized in that, The microcontroller's Flash storage space is divided into two independent areas: the BootLoader area and the application area. The BootLoader area starts at the lowest address of the Flash and is responsible for firmware reception, verification, and writing; the application area is located in the higher address range of the Flash and stores the running application programs.
9. A microcontroller firmware online upgrade system according to claim 8, characterized in that, The timing control unit, initialization sequence management unit, communication quality detection unit, firmware transmission and writing unit, and state isolation jump unit are all stored in the BootLoader area.
10. A microcontroller firmware online upgrade system according to claim 8, characterized in that, The address allocation scheme for the Flash memory is as follows: The BootLoader area starts at address 0x08000000 and is allocated a space of no more than 16KB. The application area starts at address 0x08004000, and the remaining Flash space is allocated.
11. A microcontroller firmware online upgrade system according to claim 8, characterized in that, The microcontroller has the following conditions: Condition 1: The microcontroller must have at least one UART interface peripheral; Condition 2: The microcontroller has at least one controllable general-purpose output pin for controlling the enable signal of the Bluetooth serial port pass-through module; Condition 3: When the Bluetooth serial port pass-through module has an enable control pin and the pin is active low, the Bluetooth serial port pass-through module is in a reset or disabled state. Condition 4: The microcontroller's Flash space must have at least two independently programmable sectors, one for storing the BootLoader and the other for storing the application program.