Signal period measurement method, microcontroller, storage medium and program product
By combining the counting of timer overflow events and capture events in the microcontroller with differentiated processing of DMA peripherals, the problem of the MCU timer bit limit is solved, realizing high-precision and wide-period frequency signal acquisition, and improving the system stability and measurement accuracy.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-11-17
- Publication Date
- 2026-04-03
AI Technical Summary
In the prior art, microcontrollers (MCUs) are limited by the number of bits in the timer, making it impossible to achieve both high sampling accuracy and wide sampling period at the same time, resulting in insufficient frequency acquisition accuracy and period coverage.
By responding to timer capture or overflow events, the CPU interrupt service routine is executed. Combining the accumulated count of timer overflow events and the period value calculation of capture events, the DMA peripheral is used to employ different processing methods in high and low frequency bands to achieve accurate measurement of the signal period.
This solves the problem of timer bit limitation and realizes high-precision, wide-period frequency signal acquisition on low-performance MCUs, while taking into account the signal period measurement accuracy and system stability across the entire frequency band.
Smart Images

Figure CN121784366A_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of signal frequency detection technology, and in particular to a signal period measurement method, a microcontroller, a storage medium, and a program product. Background Technology
[0002] Engine controllers have strict accuracy requirements for acquiring engine speed, and the raw speed data is obtained by capturing the frequency through a microcontroller (MCU). However, in many scenarios, due to MCU resource limitations and the limitation of timer bit width, it is impossible to simultaneously obtain high sampling accuracy and a wide sampling period. Summary of the Invention
[0003] This application provides a signal period measurement method, a microcontroller, a storage medium, and a program product to alleviate or solve one or more technical problems existing in the prior art.
[0004] In a first aspect, embodiments of this application provide a signal period measurement method, the method being applied to a signal period measurement device, the signal period measurement device including a central processing unit and a timer, the method comprising executing the following signal period measurement program: In response to a timer capture event or a timer overflow event, the interrupt service routine of the central processing unit is executed; the timer capture event is the event in which the timer generates a capture period value because it detects the target edge type of the measured signal, and the timer overflow event is the event in which the timer count value reaches the overflow period value; The execution of the interrupt service routine of the central processing unit includes: If it is determined that the interrupt service routine is invoked in response to the timer overflow event, the number of times the timer overflow event occurs is cumulatively counted to obtain the cumulative overflow count; If it is determined that the interrupt service routine is invoked in response to the timer capture event, the actual period value of the measured signal is calculated based on the current cumulative overflow count and the capture period value, and the cumulative overflow count is cleared to zero.
[0005] In some embodiments of this application, the signal period measurement device further includes a direct memory access (DMA) peripheral, and the method further includes executing the following scheduler at preset intervals: Obtain the actual cycle value measured within the preset time period; If the actual period value measured within the preset duration is lower than the first threshold, the interrupt call function of the timer calling the interrupt service routine due to the timer capture event is disabled, and the DMA peripheral is enabled to respond to the timer capture event by moving the capture period value to a specified memory space. The first threshold is less than the overflow period value. If the actual cycle value measured within the preset time period is higher than the second threshold, the interrupt call function is re-enabled, and the transfer action of the DMA peripheral is disabled, wherein the second threshold is greater than the first threshold.
[0006] In some embodiments of this application, the method further includes executing a scheduler as described below: If the DMA peripheral is currently in an enabled state, the statistical values of the multiple capture cycle values stored in the specified memory space are calculated to obtain the filtered value of the actual cycle value.
[0007] In some embodiments of this application, before executing the signal period measurement procedure, the following initialization configuration procedure is executed: Configure the address range of the specified memory space.
[0008] In some embodiments of this application, the method further includes executing a scheduler as described below: If the interrupt call function is currently disabled, obtain the stop duration of the tested signal and the cumulative number of overflows. The stop duration is the duration after the last edge of the tested signal is received without receiving an edge. If the stop duration exceeds the third threshold and the cumulative overflow count exceeds the fourth threshold, then the signal period measurement program is stopped.
[0009] In some embodiments of this application, before accumulating the number of times the timer overflow event occurs to obtain the cumulative overflow count, the execution of the interrupt service routine of the central processing unit further includes: Detect whether the current cumulative overflow count exceeds the fourth threshold; If so, set the overflow count valid flag to an invalid status flag; If not, then perform a cumulative count of the number of times the timer overflow event occurs to obtain the cumulative overflow count, specifically including: incrementing the cumulative overflow count by 1; The process of acquiring the stop duration of the measured signal and the cumulative number of overflows includes: Obtain the stop duration of the measured signal; Obtain the valid flag bit of the overflow count.
[0010] In some embodiments of this application, the execution of the interrupt service routine of the central processing unit further includes: Detect the overflow interrupt flag; wherein the overflow interrupt flag is set to a valid status indicator when the timer overflow event occurs; Based on the overflow interrupt flag being the valid status identifier, it is determined that the interrupt service routine is invoked in response to the timer overflow event; If it is determined that the interrupt service routine is invoked in response to the timer overflow event, the overflow interrupt flag is set to an invalid status indicator; Detect the capture interrupt flag; wherein the capture interrupt flag is set to the valid status identifier when the timer capture event occurs; Based on the capture interrupt flag being the valid status identifier, it is determined that the interrupt service routine is invoked in response to the timer capture event; If it is determined that the interrupt service routine is invoked in response to the timer capture event, the capture interrupt flag is set to the invalid status identifier.
[0011] Secondly, embodiments of this application provide a microcontroller, including a timer, a memory, a central processing unit, and a computer program stored in the memory, wherein the central processing unit implements any of the methods of embodiments of this application when executing the computer program.
[0012] Thirdly, embodiments of this application provide a computer-readable storage medium storing a computer program, which, when executed by a processor, implements the method of any one of the embodiments of this application.
[0013] Fourthly, embodiments of this application provide a computer program product, including a computer program, which, when executed by a processor, implements any of the methods described in the embodiments of this application.
[0014] Based on the above-described signal period measurement method, microcontroller, storage medium, and program product, this application has at least the following beneficial effects or advantages: In this embodiment, in response to a timer capture event or a timer overflow event, an interrupt service routine of the central processing unit is executed. A timer capture event is an event where the timer generates a capture period value due to detecting the target edge type of the measured signal; a timer overflow event is an event where the timer's count value reaches the overflow period value. Executing the interrupt service routine of the central processing unit includes: if it is determined that the interrupt service routine is invoked in response to a timer overflow event, accumulating a count of the number of timer overflow events to obtain an accumulated overflow count; if it is determined that the interrupt service routine is invoked in response to a timer capture event, calculating the actual period value of the measured signal based on the current accumulated overflow count and the capture period value, and resetting the accumulated overflow count to zero. This embodiment solves the problem that timers, limited by bit width, cannot simultaneously achieve wide period coverage and measurement accuracy in the low-frequency range by combining the accumulated count of timer overflow events and the count of timer capture events to calculate the period.
[0015] The above description is only an overview of the technical solution of this application. In order to better understand the technical means of this application, it can be implemented according to the contents of the specification. In order to make the above and other objects, features and advantages of this application more obvious and understandable, specific embodiments of this application are given below. Attached Figure Description
[0016] In the accompanying drawings, unless otherwise specified, the same reference numerals throughout the various drawings denote the same or similar parts or elements. These drawings are not necessarily drawn to scale. It should be understood that these drawings depict only some embodiments according to this application and should not be construed as limiting the scope of this application.
[0017] Figure 1 The flowchart of a signal period measurement method provided in an embodiment of this application is shown. Figure 1 ; Figure 2 The flowchart of a signal period measurement method provided in an embodiment of this application is shown. Figure 2 ; Figure 3 The flowchart of a signal period measurement method provided in an embodiment of this application is shown. Figure 3 ; Figure 4 The flowchart of a signal period measurement method provided in an embodiment of this application is shown. Figure 4 ; Figure 5 A block diagram of an electronic device provided in an embodiment of this application is shown. Detailed Implementation
[0018] In the following description, only certain exemplary embodiments are briefly described. As those skilled in the art will recognize, the described embodiments can be modified in various ways without departing from the concept or scope of this application. Therefore, the drawings and description are considered to be exemplary in nature and not restrictive.
[0019] To facilitate understanding of the technical solutions of the embodiments of this application, the relevant technologies of the embodiments of this application are described below. The following related technologies are optional solutions and can be arbitrarily combined with the technical solutions of the embodiments of this application, all of which fall within the protection scope of the embodiments of this application. It should be noted that the application scenarios or application examples provided in this application are for ease of understanding, and the embodiments of this application do not specifically limit the application of the technical solutions.
[0020] Currently, the commonly used frequency acquisition schemes typically fall into the following two categories: One method is to collect the number of pulses N over a period of time (time T1) and calculate the frequency f = N / T1; this method requires collecting data over a period of time and the number of pulses, so the response is relatively slow. Another method is to sample the time of one pulse cycle, which is the time T2 between the two rising edges or two falling edges of the pulse, with a frequency f = 1 / T2. This method samples the time of a single pulse cycle and has a faster response. However, it has a drawback: it is affected by the number of bits in the MCU's timer peripheral, and the timer overflow value is the longest time within the period sampling range. If the accuracy of the period sampling is increased, the timer will overflow earlier, resulting in a shorter sampling period; if the period sampling range is increased, the sampling accuracy will decrease.
[0021] Based on this, embodiments of this application provide a signal period measurement method, a microcontroller, a storage medium, and a program product. In response to a timer capture event or a timer overflow event, an interrupt service routine of the central processing unit is executed. A timer capture event is an event where the timer generates a capture period value upon detecting the target edge type of the measured signal; a timer overflow event is an event where the timer's count value reaches the overflow period value. Executing the interrupt service routine of the central processing unit includes: when it is determined that the interrupt service routine is invoked in response to a timer overflow event, accumulating and counting the number of timer overflow events to obtain an accumulated overflow count; when it is determined that the interrupt service routine is invoked in response to a timer capture event, calculating the actual period value of the measured signal based on the current accumulated overflow count and the capture period value, and resetting the accumulated overflow count to zero. Embodiments of this application solve the problem that timers, limited by bit width, cannot simultaneously achieve wide period coverage and measurement accuracy in the low-frequency range by combining the accumulated count of timer overflow events and the count of timer capture events to calculate the period.
[0022] The following is an explanation of some of the terms used in the embodiments of this application.
[0023] MCU: Microcontroller.
[0024] Interrupt: An interrupt refers to an unexpected situation that occurs during the operation of the MCU, which allows the machine to automatically stop the running program and immediately switch to a program (interrupt service function) to handle the new situation.
[0025] DMA: Microcontroller DMA (Direct Memory Access) is a technology that enables high-speed data transfer between peripherals and memory or between memory without CPU intervention.
[0026] The technical solution of this application and how it solves the aforementioned technical problems are described in detail below with specific embodiments. The listed specific embodiments can be combined with each other, and the same or similar concepts or processes may not be described again in some embodiments. The embodiments of this application will be described in detail below with reference to the accompanying drawings.
[0027] See Figure 1 The flowchart shown illustrates a signal period measurement method. This method is applied to a signal period measurement device, which includes a central processing unit and a timer. Specifically, the method includes step 1, executing the following signal period measurement program: Step 11: In response to a timer capture event or a timer overflow event, execute the CPU's interrupt service routine.
[0028] Step 12: Execute the interrupt service routine of the central processing unit, including: Step 121: If it is determined that the interrupt service routine is invoked in response to the timer overflow event, the number of times the timer overflow event occurs is accumulated to obtain the cumulative overflow count; Step 122: If it is determined that the interrupt service routine is called in response to the timer capture event, calculate the actual period value of the measured signal based on the current cumulative overflow count and capture period value, and clear the cumulative overflow count to zero.
[0029] The signal period measurement device can be a microcontroller (MCU) or similar device. The signal period measurement device includes a central processing unit (CPU). The CPU can respond to interrupt events and execute a preset interrupt service routine. In this application embodiment, a new interrupt service routine is designed. The interrupt service routine is called and executed in response to a timer capture event or a timer overflow event as an interrupt event.
[0030] A timer capture event is an event in which the timer generates a capture period value when it detects the target edge type of the measured signal. The target edge type is either a rising edge or a falling edge. After the timer is powered on and initialized, it continuously counts. In response to the triggering of a rising edge (or falling edge), the timer captures the current time, which can be latched, for example, in the timer's internal memory. When the next rising edge (or falling edge) arrives, the timer capture event is triggered again. The timer captures the current time and subtracts it from the previously latched capture time to obtain the period value between the two captured rising edges (or two falling edges). It can be understood that since the signal period and the signal frequency are reciprocals, measuring the signal period is equivalent to measuring the signal frequency. Knowing the period value allows the calculation of the frequency value. This embodiment can be applied to application scenarios such as measuring engine speed. Since physical quantities such as engine speed usually change, the timer continuously captures each rising edge (or falling edge) and subtracts it from the previous capture time to obtain the measured period value, thereby determining the current engine speed.
[0031] A timer overflow event occurs when the timer's count reaches its overflow period value. Because timers have a limited number of bits, if the timer reaches the upper limit of the overflow period value corresponding to its bit length, a timer overflow event occurs. The timer then restarts counting from 0 until the next overflow period value is reached. It's important to understand that timer counting is not the same as the timer latch's capture time.
[0032] For example, if the signal being measured is a low-frequency signal (e.g., a period of 100ms), and a 16-bit timer (clock frequency 1MHz, overflow period 65.536ms) is used, then one overflow will occur between two rising edges (capture events), and the cumulative overflow count is 1; the capture period value period_temp is 34464 (corresponding to 34.464ms), and the actual period value is 34464 + 65536×1 = 100000 (corresponding to 100ms), which is consistent with the true period.
[0033] Based on the current cumulative overflow count and capture period value, calculate the actual period value of the measured signal. The specific formula can be: Actual period value period_calculate_temp = Capture period value period_temp + Timer overflow period value (e.g., 65536) × Timer overflow count T_over_cnt. This can be understood as: Capture period value period_temp = Current capture time - Previous capture time. If the current capture time is less than the previous capture time, then capture period value period_temp = Current capture time + Timer overflow period value - Previous capture time.
[0034] This application's embodiments solve the problem that timers, limited by bit width, cannot simultaneously achieve wide period coverage and measurement accuracy in the low-frequency range by combining the cumulative count of timer overflow events and the count of timer capture events to calculate the period.
[0035] refer to Figure 2 In some embodiments of this application, the signal period measurement device further includes a direct memory access (DMA) peripheral, and the method further includes step 2, executing the following scheduler every preset time interval: Step 21: Obtain the actual cycle value measured within the preset time period; Step 22: If the actual period value measured within the preset time is lower than the first threshold, disable the interrupt call function of the timer interrupt service routine due to the timer capture event, and enable the DMA peripheral response to the timer capture event to move the capture period value to the specified memory space. The first threshold is less than the overflow period value. Step 23: If the actual cycle value measured within the preset time period is higher than the second threshold, re-enable the interrupt call function and disable the DMA peripheral transfer action. The second threshold is greater than the first threshold.
[0036] The preset duration is the execution cycle of the scheduler. The scheduler determines whether the current frequency is high or low based on the measured cycle value. If it's high, it disables the call to the interrupt service routine (ISP) for timer capture events; if it's low, it enables the call to the ISP for timer capture events. The boundary between high and low frequencies can be determined by comparing the actual cycle value with the timer's overflow cycle value. At least when the actual cycle value is greater than the timer's overflow cycle value, the call to the ISP for timer capture events is enabled. High-frequency frequencies have shorter cycles and do not trigger timer overflow events, but they frequently trigger timer capture events. Frequent entry into the ISP leads to excessive CPU resource consumption and decreased system stability.
[0037] The condition for disabling interrupt call function is that it is below the first threshold, and the condition for enabling interrupt call function is that it is above the second threshold. The second threshold is greater than the first threshold. Through a threshold difference, the two processing methods can be smoothly switched, avoiding frequent switching caused by signal frequency fluctuations and further improving system stability.
[0038] This application's embodiment balances the accuracy, response speed, and system stability of full-band signal period measurement by employing "differentiated processing for high and low frequency bands + dynamic switching between DMA and interrupts." For high-frequency signals, a timer-triggered DMA transfer action is used to replace interrupt handling, avoiding excessive MCU CPU resource consumption and stuttering caused by frequent interrupts triggered by high-frequency signals. Simultaneously, the high-speed data transfer characteristics of DMA ensure continuous acquisition of high-frequency signal periodic data without data loss.
[0039] refer to Figure 2 In some embodiments of this application, step 2 of executing the scheduler further includes: step 24, if the current DMA peripheral is in an enabled state, calculate the statistical values of the multiple capture cycle values stored in the specified memory space to obtain the filtered value of the actual cycle value.
[0040] After the DMA peripheral transfer operation is enabled by the scheduler (i.e., currently in high-frequency measurement mode), the DMA will continuously transfer the capture period values generated by each timer capture event to a designated memory space (such as period_buffer). This memory space will store multiple consecutive capture period values. These multiple capture period values are read from the designated memory space, and their statistical values are calculated. The specific type of statistical value can be "cumulative average", median, variance filter value, etc. The final statistical value is the filtered value of the actual period value. For example, the filtered value of the actual period value = the cumulative average of all capture period values stored in the DMA transfer memory space.
[0041] This application embodiment effectively reduces data fluctuations and interference in high-frequency signal measurements by statistically filtering multiple capture cycle values in DMA mode, thereby further improving the accuracy of high-frequency measurements.
[0042] In some embodiments of this application, before executing the signal period measurement program in step 1, the following initialization configuration program is executed: configuring the spatial address range of the specified memory space.
[0043] For example, after the microcontroller is powered on, the MCU performs an initialization configuration process, initializes the microcontroller timer, configures rising edge (or falling edge) capture, and configures the transfer position when the capture event triggers DMA transfer, that is, transfers the captured period value to the period data buffer period_buffer. It can also configure the falling edge (or rising edge) capture duty cycle function and configure the capture event triggers DMA transfer memory-to-memory transfer. When the acquisition signal stops accumulating time, the count is cleared to capture_count = 0 immediately.
[0044] By configuring the spatial address range for DMA transfers in advance during the initialization step, the location of DMA transfers can be specified in advance, avoiding data being written to illegal memory areas, which could lead to system crashes or data loss. At the same time, a clear address range also makes it easier for the subsequent scheduler to quickly read the stored capture cycle value, avoiding the time spent on address lookups that could affect the real-time performance of measurements.
[0045] refer to Figure 2 In some embodiments of this application, step 2 of the method executes the following scheduler, and further includes: Step 25: If the current interrupt call function is disabled, obtain the stop duration and cumulative overflow count of the signal under test. The stop duration is the duration after the last edge of the signal under test has been received without receiving an edge. Step 26: If the stop duration exceeds the third threshold and the cumulative number of overflows exceeds the fourth threshold, then stop executing the signal period measurement program in Step 1.
[0046] By detecting the stop duration and cumulative overflow count of the measured signal, it is determined whether the measured signal has stopped. When the measured signal stops, the signal period measurement program is stopped to avoid wasting resources by continuing to measure when the measured signal stops.
[0047] In some embodiments of this application, before executing step 121 to accumulate the number of timer overflow events and obtain the accumulated overflow count, step 12: executing the interrupt service routine of the central processing unit further includes: Check if the current cumulative overflow count exceeds the fourth threshold; If so, set the overflow count valid flag to an invalid status flag; If not, proceed to step 121 to accumulate the number of times the timer overflow event occurs and obtain the cumulative overflow count. Step 121 specifically includes: incrementing the cumulative overflow count by 1. In step 25, the stop duration and cumulative overflow count of the signal under test are obtained, specifically including: obtaining the stop duration of the signal under test and obtaining the valid flag bit of the overflow count.
[0048] Before performing the cumulative count of timer overflow events, the interrupt service routine must first perform a validity check: the first step is to check whether the current cumulative overflow count exceeds the fourth threshold; if it exceeds, the overflow count validity flag is set to an invalid status flag (e.g., 0), indicating that the current overflow count has exceeded the upper limit and cannot be used for period calculation, to avoid data overflow or period calculation errors due to excessive count; if it does not exceed, the cumulative count operation is performed - the cumulative overflow count is incremented by 1, while keeping the overflow count validity flag set to a valid status flag (e.g., 1).
[0049] When acquiring the stop duration and cumulative overflow count of the tested signal, two pieces of information are obtained simultaneously: first, the stop duration counted by `capture_count`; and second, the validity flag for the overflow count. If the flag is invalid, it indicates that the cumulative overflow count has exceeded the upper limit, and this count is unreliable. The stop duration must be considered in conjunction with the count to determine whether the signal has stopped. If the flag is valid, the cumulative overflow count is reliable and can be used as a valid basis for stopping the signal. This application embodiment ensures the reliability of the accumulated overflow count by detecting overflow counts exceeding the threshold and valid flags, thus avoiding interference from invalid counts on period calculation and signal stop determination.
[0050] In some embodiments of this application, step 12: executing the interrupt service routine of the central processing unit further includes: Detect the overflow interrupt flag; the overflow interrupt flag is set to a valid status when a timer overflow event occurs. Based on the overflow interrupt flag being in a valid state, it is determined that the interrupt service routine is invoked in response to the timer overflow event; If it is determined that an interrupt service routine is invoked in response to a timer overflow event, the overflow interrupt flag is set to an invalid status indicator; Detect the capture interrupt flag; the capture interrupt flag is set to a valid status indicator when a timer capture event occurs. Based on the fact that the interrupt capture flag is valid, it is determined that the interrupt service routine is invoked in response to the timer capture event; If it is determined that the interrupt service routine is invoked in response to a timer capture event, the capture interrupt flag is set to an invalid status indicator.
[0051] This application embodiment ensures the accuracy of event response by detecting and clearing interrupt flags. The core prerequisite for interrupt service routine execution is accurately identifying the type of event that triggers the interrupt. This implementation achieves this identification through two types of flags: one is the overflow interrupt flag, which the hardware automatically sets to a valid status when a timer overflow event occurs; the other is the capture interrupt flag, which the hardware automatically sets to a valid status when the timer detects a target edge (capture event).
[0052] If the interrupt service routine detects that the overflow interrupt flag is valid, it determines that the interrupt was called by a timer overflow event. It must first set the flag to invalid status to prevent the overflow event from triggering the interrupt repeatedly. If it detects that the capture interrupt flag is valid, it determines that the interrupt was called by a timer capture event. Similarly, it must set the flag to invalid status to prevent the same capture event from triggering the interrupt multiple times.
[0053] This application's embodiments solve the problem of repeated interrupt triggering by the same event through the logic of interrupt flag detection and clearing, ensuring that the interrupt service routine can accurately and uniquely respond to each timer event, thereby improving the accuracy of period measurement and the reliability of interrupt handling.
[0054] The following is a detailed description of a specific implementation of an embodiment of this application. This embodiment includes two program functions: an interrupt service routine and a scheduler.
[0055] In the interrupt service routine: For timer overflow events, the number of timer overflows is counted and incremented. For low-frequency sampling, the actual period of the entire pulse is calculated based on the timer overflow count and the timer capture period value. A timer overflow event triggers the interrupt service routine, which checks the timer's interrupt flag to determine if it is indeed a timer overflow event. A timer capture event is generated when the pulse signal rises, also triggering the interrupt service routine, which checks the timer interrupt event flag to determine if a rising edge has arrived. The duration between two rising edges is the capture period value.
[0056] For details, please refer to Figure 3Upon entering the interrupt service routine, the system first checks if the overflow interrupt flag T_flag1 is equal to 1. This interrupt flag is a general flag function within the timer. If this condition is met, the timer overflow flag T_flag1 is cleared to 0. Next, it checks if the timer overflow count T_over_cnt > the timer overflow limit T_over_max. If so, meaning the overflow count exceeds the limit, the timer overflow validity flag T_over_flag is set to 0 (invalid). Otherwise, the flag is 1, indicating the overflow count is valid and has not exceeded the limit, and the timer overflow count T_over_cnt is incremented by 1. Then, it checks if the period capture interrupt flag T_flag2 is 1, used to determine if a rising edge has been captured. If so, the timer capture flag T_flag2 is cleared to 0. This interrupt flag is a general flag function within the timer. Finally, it checks if the timer overflow invalid flag T_over_flag is 1 (valid). The timer overflow invalid flag indicates whether the overflow count exceeds the threshold. If the overflow count exceeds the threshold, the signal may have stopped, so the timer overflow invalid flag is set to invalid, and the timer overflow count is no longer counted. If the timer overflow invalidation flag is valid, the capture period value `period_temp` is obtained from the register. When a rising / falling edge of an external frequency signal is detected, the register latches the current count value. This "latch count value" action is triggered by the edge, but the timer itself does not start or stop due to the edge trigger and continues to accumulate. The acquisition period value (interrupt calculation) is calculated as `period_calculate_temp = period_temp + 65536 × T_over_cnt` (where 65536 depends on the number of bits in the microcontroller, and 65536 corresponds to the maximum value of 16 bits in binary). If the condition is not met (the flag is 0, invalid), the acquisition period value (interrupt calculation) is still calculated as `period_calculate_temp = period_temp + 65536 × T_over_cnt` to avoid an empty output result, which could cause system errors. Next, the timer overflow validity flag `T_over_flag` is set to 1 (valid), and the timer overflow count `T_over_cnt` is cleared to zero. Finally, the interrupt service function exits. The above scheme enables frequency calculation during interrupts, which can solve the problem of wide-period sampling not being possible.
[0057] The scheduler primarily configures the interrupt service routines for timer capture events. Based on the actual period value being collected, it determines whether to calculate the frequency within the interrupt service routine. High frequencies and frequent interrupt calls can negatively impact system stability. DMA transfer settings have already been configured during initialization.
[0058] refer to Figure 4 The specific implementation logic of the scheduler is described as follows: Execute once every X ms (optionally, X is less than the overflow period value), for example, it can actually be executed every 10 ms. First, determine whether the actual period value (calculated by the interrupt service routine) is less than the lower value of the hysteresis loop (the first threshold), and obtain the capture interrupt enable status bit. If the interrupt enable status bit Interrupt_enable_flag!= 1 (Interrupt_enable_flag!= 1 indicates the enabled state). If both conditions are met (the period is small and the current interrupt is enabled), then configure the capture interrupt function to be disabled; and configure the timer overflow value validity flag bit T_over_flag = 1 (valid), then configure the capture interrupt enable status bit Interrupt_enable_flag!= 0 (Interrupt_enable_flag!= 0 indicates the disabled state). If both conditions are not fully met (for example, the period is large or the current interrupt is disabled), then determine whether the actual period value period_calculate is greater than the upper value of the hysteresis loop (the second threshold) (the upper value of the hysteresis loop > the lower value of the hysteresis loop). If not met (even if the period value becomes larger, greater than the lower value of the hysteresis loop, but still less than the upper value of the hysteresis loop), then obtain the timer overflow count. If the timer overflow count T_over_cnt!= 0; continue to determine the capture interrupt enable status bit Interrupt_enable_flag!= 0 (indicating the current interrupt disabled state); if the conditions are met (the overflow count is not 0 and the current interrupt is in the disabled state), then execute: configure the capture interrupt function to be enabled, then configure the capture interrupt enable status bit Interrupt_enable_flag!= 1 (the current interrupt is in the enabled state), and clear the timer capture flag T_flag2 = 0. If the timer overflow count = 0, determine the capture interrupt enable status bit Interrupt_enable_flag!= 0 (disabled state). If the conditions are met (the current interrupt is in the disabled state), then determine whether the cumulative time count capture_count of the acquisition signal stop < the upper limit value capture_cnt_MAX of the cumulative time of the signal stop or the timer overflow count T_over_cnt < T_over_max. The cumulative time count capture_count of the acquisition signal stop will trigger the DMA transfer to clear (DMA does not "transfer the cumulative time of the acquisition signal stop", but through "memory-memory data transfer", write the "0 value" to the storage address of capture_count, so as to achieve the clearing of the "cumulative time count of the acquisition signal stop"). If satisfied, calculate the acquisition period value period_calculate = period_calculate_buffer cumulative average; otherwise, if the signal stop duration is too long and the overflow count is too large, then exit. The signal has stopped, and the measurement process is exited without measurement.
[0059] Currently, there are two typical schemes for frequency acquisition, but neither can simultaneously meet the requirements of "high response speed, high sampling accuracy, and wide sampling period": Frequency measurement method: Collect the number of pulses N over a period of time (time T1), and calculate the frequency using the formula f=N / T1. This method requires accumulating data and pulse counts over a period of time, resulting in a slow response and making it unsuitable for scenarios with high real-time requirements. Periodic measurement method: This method acquires the time of a single pulse cycle (i.e., the time T2 between two rising edges or two falling edges of the pulse) and calculates the frequency using the formula f=1 / T2. Because this method only acquires a single cycle, it has a fast response time. However, it is limited by the number of bits in the MCU timer peripheral—the timer overflow value determines the maximum sampling time for the cycle: increasing the cycle sampling accuracy will cause the timer to overflow earlier, resulting in a shorter sampling period; expanding the cycle sampling range will decrease the sampling accuracy, ultimately making it impossible to simultaneously achieve high acquisition accuracy and a wide sampling period.
[0060] To address the shortcomings of related technical solutions, this application provides a control method for improving the frequency acquisition accuracy and sampling width of an MCU. The core of this method combines MCU DMA peripheral handling with frequency capture timer overflow interrupt technology, processing high and low frequency bands independently. Simultaneously, timely frequency stop detection is achieved through dual-edge detection in conjunction with DMA. Specifically, the method is as follows: 1. Differentiated processing logic for high and low frequency bands High-frequency signal processing: Data acquisition is achieved without relying on interrupts, using DMA (Distributed Messaging) to move data. The MCU is configured with edge detection to obtain the counter difference between two cycles. When each high-frequency signal triggers a capture event, a DMA move is directly triggered to transfer the capture cycle value to a specified memory space, thereby acquiring continuous high-frequency capture data. Subsequent filtering processing is applied to multiple capture cycle values in the memory space to balance acquisition accuracy and response speed in high-frequency scenarios.
[0061] Low-frequency signal processing: Data acquisition and calculation are achieved through interrupts. Edge-triggered interrupts and timer overflow-triggered interrupts for the frequency signal are enabled: When a timer overflows, the number of overflow events is accumulated (resulting in a cumulative overflow count); when a signal edge is captured, the total time between the two edges is calculated by combining the current cumulative overflow count, the timer overflow value, and the counter value captured by the edge detection, thus obtaining the frequency acquisition result; after each calculation, the cumulative overflow count is reset to zero to avoid cross-cycle counting interference.
[0062] 2. Interrupt threshold switching mechanism: Based on the results of high and low frequency band acquisition, an interrupt threshold is set: when the acquired period value is lower than the threshold (determined to be a high frequency band), edge-triggered interrupts are disabled, and only DMA transfer is retained; when the period value is higher than another threshold (determined to be a low frequency band), edge-triggered interrupts are re-enabled, and DMA transfer is disabled at the same time to ensure that the optimal processing method is adapted to different frequency bands.
[0063] 3. Frequency Stop Detection Optimization: Double-edge detection using both rising and falling edges of the frequency is adopted, and memory-to-memory data transfer is achieved in conjunction with DMA: When a falling edge of the signal is captured, the DMA will immediately clear the "Accumulated Time Count for Signal Acquisition Stop" to zero; if the signal edge disappears (i.e., the frequency stops), the accumulated time count will continue to accumulate. Combined with the timer overflow situation, the frequency stop state can be identified in a timely manner, solving the problem of data clearing delay after the frequency stops.
[0064] The embodiments of this application achieve multi-dimensional breakthroughs in the field of frequency acquisition through the above technical solutions, specifically manifested in the following technical effects: Reduce MCU dependence and selection costs: High-precision, wide-cycle frequency signal acquisition can be achieved using only a low-bit / low-performance MCU without the need for complex frequency divider modules and multi-counter modules, which greatly reduces dependence on MCU peripheral performance and thus reduces MCU selection costs; Breaking the core contradiction between accuracy and cycle time: By using a combination of "overflow count compensation" and "DMA filter optimization" strategies, the problem of low acquisition accuracy and short acquisition cycle of low bit MCU is completely solved. The sampling accuracy can be improved by tens of times according to the actual scenario and supports flexible adjustment. The sampling cycle can also be infinitely extended according to the needs, breaking the limitation of "high accuracy and wide cycle time cannot be achieved at the same time" in traditional solutions. Balancing acquisition needs and stability across different frequency bands: Adaptive processing methods are adopted for high and low frequency bands: High frequency bands use DMA to transfer captured data, avoiding the impact of frequent interrupts on acquisition and ensuring acquisition accuracy in high-frequency scenarios; Low frequency bands use interrupts in conjunction with overflow accumulation counting to ensure complete acquisition of wide-period signals; This differentiated processing not only overcomes the pain points of acquisition in different frequency bands, but also avoids stability issues caused by frequent interrupts in the MCU. Achieving efficient acquisition across the entire frequency band: By combining the above-mentioned technical means, the goal of acquiring frequencies with "high precision, high sampling width, and high real-time performance" across the entire frequency band is ultimately achieved. At the same time, a threshold switching mechanism is used to achieve smooth switching between high and low frequency band processing methods. The accuracy of frequency stop detection is optimized by combining double-edge detection of rising and falling edges, ensuring that even on low-performance MCUs, the frequency acquisition requirements of "high response speed, high acquisition accuracy, and wide sampling period" can be met, while also taking into account cost and stability.
[0065] This application also provides a microcontroller, including a timer, a memory, a central processing unit, and a computer program stored in the memory. When the central processing unit executes the computer program, it implements the method provided by any of the technical solutions in this application.
[0066] Figure 5 This is a block diagram of an electronic device used to implement embodiments of this application. For example, the electronic device may be a microcontroller, such as... Figure 5 As shown, the electronic device includes a memory 501 and a processor 502. The memory 501 stores a computer program that can run on the processor 502. When the processor 502 executes the computer program, it implements the method described in the above embodiments. The number of memories 501 and processors 502 can be one or more. In a specific implementation, the electronic device may also include a communication interface 503 for communicating with external devices and exchanging data.
[0067] In practical implementation, if the memory 501, processor 502, and communication interface 503 are implemented independently, they can be interconnected via a bus to communicate with each other. This bus can be an Industry Standard Architecture (ISA) bus, a Peripheral Component Interconnect (PCI) bus, or an Extended Industry Standard Architecture (EISA) bus, etc. This bus can be divided into an address bus, a data bus, a control bus, etc. For ease of representation, Figure 5 The bus is represented by a single thick line, but this does not mean that there is only one bus or one type of bus.
[0068] Optionally, in a specific implementation, if the memory 501, processor 502 and communication interface 503 are integrated on a single chip, the memory 501, processor 502 and communication interface 503 can communicate with each other through an internal interface.
[0069] This application provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the method provided in this application.
[0070] This application provides a computer program product, including a computer program that, when executed by a processor, implements the method provided in this application.
[0071] This application also provides a chip including a processor for calling and executing instructions stored in a memory, causing a communication device with the chip installed to perform the method provided in this application.
[0072] This application also provides a chip, including: an input interface, an output interface, a processor, and a memory. The input interface, output interface, processor, and memory are connected through an internal connection path. The processor is used to execute code in the memory. When the code is executed, the processor is used to execute the method provided in the application embodiment.
[0073] It should be understood that the aforementioned processor can be a CPU (Central Processing Unit), or other general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), or other programmable logic devices, discrete gate or transistor logic devices, discrete hardware components, etc. General-purpose processors can be microprocessors or any conventional processor. It is worth noting that the processor can be a processor supporting Advanced Reduced Instruction Set Machines (ARM) architecture.
[0074] Further, optionally, the aforementioned memory may include read-only memory and random access memory. The memory may be volatile memory or non-volatile memory, or may include both. Non-volatile memory may include read-only memory (ROM), programmable read-only memory (PROM), erasable programmable read-only memory (EPROM), electrically erasable programmable read-only memory (EEPROM), or flash memory. Volatile memory may include random access memory (RAM), which serves as an external cache. By way of example, but not limitation, many forms of RAM are available. Examples include Static Random Access Memory (SRAM), Dynamic Random Access Memory (DRAM), Synchronous DRAM (SDRAM), Double Data Rate SDRAM (DDR SDRAM), Enhanced Synchronous DRAM (ESDRAM), Sync Link DRAM (SLDRAM), and Direct Rambus RAM (DR RAM).
[0075] In the above embodiments, implementation can be achieved, in whole or in part, through software, hardware, firmware, or any combination thereof. When implemented in software, it can be implemented, in whole or in part, as a computer program product. A computer program product includes one or more computer instructions. When the computer program instructions are loaded and executed on a computer, all or part of the processes or functions according to this application are generated. The computer can be a general-purpose computer, a special-purpose computer, a computer network, or other programmable device. The computer instructions can be stored in a computer-readable storage medium or transferred from one computer-readable storage medium to another.
[0076] In the description of this specification, the references to terms such as "one embodiment," "some embodiments," "example," "specific example," or "some examples," etc., indicate that a specific feature, structure, material, or characteristic described in connection with that embodiment or example is included in at least one embodiment or example of this application. Furthermore, the specific features, structures, materials, or characteristics described may be combined in any suitable manner in one or more embodiments or examples. Moreover, without contradiction, those skilled in the art can combine and integrate the different embodiments or examples described in this specification, as well as the features of those different embodiments or examples.
[0077] Furthermore, the terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include at least one of that feature. In the description of this application, "a plurality of" means two or more, unless otherwise explicitly specified.
[0078] Any process or method described in the flowchart or otherwise herein can be understood as representing a module, segment, or portion of code comprising one or more executable instructions for implementing a particular logical function or process. Furthermore, the scope of the preferred embodiments of this application includes additional implementations in which functions may be performed not in the order shown or discussed, including substantially simultaneously or in reverse order depending on the functionality involved.
[0079] The logic and / or steps described in the flowchart or otherwise herein, for example, can be considered as a sequenced list of executable instructions for implementing logical functions, and can be embodied in any computer-readable medium for use by, or in conjunction with, an instruction execution system, apparatus or device (such as a computer-based system, a processor-included system or other system that can fetch and execute instructions from, an instruction execution system, apparatus or device).
[0080] It should be understood that various parts of this application can be implemented using hardware, software, firmware, or a combination thereof. In the above embodiments, multiple steps or methods can be implemented using software or firmware stored in memory and executed by a suitable instruction execution system. All or part of the steps of the methods in the above embodiments can be implemented by a program instructing related hardware, the program being stored in a computer-readable storage medium, which, when executed, includes one or a combination of the steps of the method embodiments.
[0081] Furthermore, the functional units in the various embodiments of this application can be integrated into a processing module, or each unit can exist physically separately, or two or more units can be integrated into a module. The integrated module can be implemented in hardware or as a software functional module. If the integrated module is implemented as a software functional module and sold or used as an independent product, it can also be stored in a computer-readable storage medium. This storage medium can be a read-only memory, a disk, or an optical disk, etc.
[0082] The above description is merely an exemplary embodiment of this application, but the scope of protection of this application is not limited thereto. Any person skilled in the art can easily conceive of various variations or substitutions within the technical scope described in this application, and these should all be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.
Claims
1. A method for measuring signal period, characterized in that, The method is applied to a signal period measurement device, which includes a central processing unit and a timer, and the method includes executing the following signal period measurement program: In response to a timer capture event or a timer overflow event, the interrupt service routine of the central processing unit is executed; the timer capture event is the event in which the timer generates a capture period value because it detects the target edge type of the measured signal, and the timer overflow event is the event in which the timer count value reaches the overflow period value; The execution of the interrupt service routine of the central processing unit includes: If it is determined that the interrupt service routine is invoked in response to the timer overflow event, the number of times the timer overflow event occurs is cumulatively counted to obtain the cumulative overflow count; If it is determined that the interrupt service routine is invoked in response to the timer capture event, the actual period value of the measured signal is calculated based on the current cumulative overflow count and the capture period value, and the cumulative overflow count is cleared to zero.
2. The method according to claim 1, characterized in that, The signal period measurement device further includes a direct memory access (DMA) peripheral, and the method further includes executing the following scheduler at preset intervals: Obtain the actual cycle value measured within the preset time period; If the actual period value measured within the preset duration is lower than the first threshold, the interrupt call function of the timer calling the interrupt service routine due to the timer capture event is disabled, and the DMA peripheral is enabled to respond to the timer capture event by moving the capture period value to a specified memory space. The first threshold is less than the overflow period value. If the actual cycle value measured within the preset time period is higher than the second threshold, the interrupt call function is re-enabled, and the transfer action of the DMA peripheral is disabled, wherein the second threshold is greater than the first threshold.
3. The method according to claim 2, characterized in that, The method further includes executing a scheduler as described below: If the DMA peripheral is currently in an enabled state, the statistical values of the multiple capture cycle values stored in the specified memory space are calculated to obtain the filtered value of the actual cycle value.
4. The method according to claim 2, characterized in that, Before executing the signal period measurement procedure, execute the following initialization configuration procedure: Configure the address range of the specified memory space.
5. The method according to claim 2, characterized in that, The method further includes executing a scheduler as described below: If the interrupt call function is currently disabled, obtain the stop duration of the tested signal and the cumulative number of overflows. The stop duration is the duration after the last edge of the tested signal is received without receiving an edge. If the stop duration exceeds the third threshold and the cumulative overflow count exceeds the fourth threshold, then the signal period measurement program is stopped.
6. The method according to claim 5, characterized in that, Before accumulating the number of timer overflow events to obtain the cumulative overflow count, the execution of the central processing unit's interrupt service routine further includes: Detect whether the current cumulative overflow count exceeds the fourth threshold; If so, set the overflow count valid flag to an invalid status flag; If not, then perform a cumulative count of the number of times the timer overflow event occurs to obtain the cumulative overflow count, specifically including: incrementing the cumulative overflow count by 1; The process of acquiring the stop duration of the measured signal and the cumulative number of overflows includes: Obtain the stop duration of the measured signal; Obtain the valid flag bit of the overflow count.
7. The method according to claim 1, characterized in that, The interrupt service routine for executing the central processing unit further includes: Detect the overflow interrupt flag; wherein the overflow interrupt flag is set to a valid status indicator when the timer overflow event occurs; Based on the overflow interrupt flag being the valid status identifier, it is determined that the interrupt service routine is invoked in response to the timer overflow event; If it is determined that the interrupt service routine is invoked in response to the timer overflow event, the overflow interrupt flag is set to an invalid status indicator; Detect the capture interrupt flag; wherein the capture interrupt flag is set to the valid status identifier when the timer capture event occurs; Based on the capture interrupt flag being the valid status identifier, it is determined that the interrupt service routine is invoked in response to the timer capture event; If it is determined that the interrupt service routine is invoked in response to the timer capture event, the capture interrupt flag is set to the invalid status identifier.
8. A microcontroller, characterized in that, It includes a timer, a memory, a central processing unit, and a computer program stored in the memory, wherein the central processing unit, when executing the computer program, implements the method of any one of claims 1-7.
9. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, implements the method of any one of claims 1-7.
10. A computer program product, characterized in that, Includes a computer program that, when executed by a processor, implements the method according to any one of claims 1-7.