Pulse generation method and device based on timer comparison output, equipment and medium
By initializing a fixed execution cycle, determining the target number of pulses, obtaining the current pulse state, dynamically setting timer parameters, and updating the state, the problems of inaccurate pulse output and insufficient phase continuity in the prior art are solved, and high-precision AB phase quadrature pulse generation is achieved.
Patent Information
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- 横川机器人(深圳)有限公司
- Filing Date
- 2026-04-28
- Publication Date
- 2026-07-21
AI Technical Summary
Existing technologies struggle to accurately output AB-phase quadrature pulses that correspond one-to-one with the target number of pulses within a fixed execution cycle. Furthermore, they lack a pulse quantity control mechanism based on timer comparison output and a current pulse state update mechanism, resulting in insufficient output accuracy and phase continuity.
By initializing a fixed execution cycle, determining the target number of pulses, obtaining the current pulse state, dynamically setting the pulse repetition count, timer repetition load value, and comparison value, setting the comparison register, and updating the current state based on the actual number of output pulses, the accurate output and phase continuity of AB phase pulses are achieved.
High-precision quadrature pulse generation was achieved under low-cost conditions, improving the accuracy and phase continuity of pulse output and reducing errors and phase jumps.
Smart Images

Figure CN122437522A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of pulse generator and industrial control technology, and in particular to a pulse generation method, apparatus, device and medium based on timer comparison output. Background Technology
[0002] In existing technologies, AB phase quadrature pulses are typically implemented on general-purpose microcontrollers through GPIO simulation, PWM frequency division, or timer comparison interrupts. GPIO simulation requires frequent CPU involvement in I / O toggles and software delays, making it difficult to achieve stable output at high frequencies and consuming significant processor resources. While PWM frequency division relies on hardware peripherals, the number of controllable pulses per pulse is often a fixed step size, making it difficult to precisely control the number of pulses to any target quantity. Comparison interrupt-based schemes require dynamic register rewriting in each comparison event interrupt, and as pulse frequency and microstepping requirements increase, interrupt frequency and CPU load rise significantly.
[0003] A prominent problem with existing solutions of this type is that it is difficult to accurately output the actual number of pulses that corresponds one-to-one with the target number of pulses within a "fixed execution cycle" timescale. Parameters such as the timer total value, repetition count, auto-reload value, and comparison value often lack a clear and unified mapping relationship with the target number of pulses, which makes it easy for the output pulse count to deviate within the cycle, and the error is difficult to correct in a timely manner after long-term operation.
[0004] On the other hand, existing implementations of "current pulse state" management for A and B phase signals are generally inadequate. When the number of target pulses changes, the direction switches, or the number of target pulses is zero in certain cycles, the combined level state of phase A and phase B often relies solely on simple counting or flag bit maintenance, making it difficult to guarantee phase continuity across cycles. This can easily lead to state jumps, affecting the reliability of direction judgment and position accumulation.
[0005] Furthermore, although many solutions use timers, they do not form a complete configuration closed loop centered on the target pulse count: there is a lack of systematic collaborative configuration mechanism between the target pulse count and the timer's repetition count register, autoload register, and comparison register. The output behavior after the timer starts also lacks a feedback update strategy that is combined with the "actual output pulse count", resulting in low resource utilization and difficulty in balancing pulse count accuracy, phase relationship correctness, and system real-time performance. Summary of the Invention
[0006] The main objective of this invention is to provide a pulse generation method, apparatus, device, and storage medium based on timer comparison output. This invention aims to solve the technical problems of existing technologies, which struggle to accurately output AB phase quadrature pulses that correspond one-to-one with the target number of pulses within a fixed execution cycle, and lack pulse number control and current pulse state update mechanisms based on timer comparison output, resulting in insufficient output accuracy and phase continuity.
[0007] To achieve the above objectives, the present invention provides a pulse generation method based on timer comparison output, comprising: Initialize a fixed execution cycle, where the fixed execution cycle corresponds to the total value of the timer; Determine the target number of pulses within the fixed execution cycle; At the start of the fixed execution cycle, the current pulse state is obtained, which is a combination of the levels of the first pulse signal and the second pulse signal; Based on the absolute value of the target pulse count, the pulse repetition count, the timer reload value, and the first comparison value and the second comparison value are dynamically set to control the output behavior of the first pulse signal and the second pulse signal. Based on the direction of the target pulse quantity and the current pulse state, set the comparison registers corresponding to the first pulse signal and the second pulse signal; Configure the repeat count register and auto-reload register of the timer; Start the timer to output the first pulse signal and the second pulse signal; The current pulse state is updated based on the actual number of pulses output.
[0008] Furthermore, to achieve the above objectives, the present invention provides a pulse generation device based on timer comparison output, comprising: A fixed-cycle initialization module is used to initialize a fixed execution cycle, wherein the fixed execution cycle corresponds to the total value of the timer; The pulse count analysis module is used to determine the target pulse count within the fixed execution cycle; The pulse state acquisition module is used to acquire the current pulse state at the beginning of the fixed execution cycle, wherein the current pulse state is a combination of the levels of the first pulse signal and the second pulse signal; The parameter dynamic configuration module is used to dynamically set the pulse repetition count, timer repetition load value, first comparison value and second comparison value based on the absolute value of the target pulse count, so as to control the output behavior of the first pulse signal and the second pulse signal; The comparison register setting module is used to set the comparison registers corresponding to the first pulse signal and the second pulse signal according to the direction of the target pulse number and the current pulse state; A register loading module is used to set the repeat count register and the auto-load register of the timer; A timer startup module is used to start the timer to output the first pulse signal and the second pulse signal; The pulse state update module is used to update the current pulse state based on the actual number of pulses output.
[0009] Furthermore, to achieve the above objectives, the present invention also provides a computer device, the computer device including a memory, a processor, and a pulse generation program based on timer comparison output stored in the memory and executable on the processor, wherein when the pulse generation program based on timer comparison output is executed by the processor, it implements the steps of the pulse generation method based on timer comparison output as described above.
[0010] Furthermore, to achieve the above objectives, the present invention also provides a computer-readable storage medium storing a pulse generation program based on timer comparison output, wherein the pulse generation program based on timer comparison output, when executed by a processor, implements the steps of the pulse generation method based on timer comparison output as described above.
[0011] Beneficial Effects: This invention relates to the field of pulse generators and industrial control technology, and discloses a pulse generation method, apparatus, device, and medium based on timer comparison output. The method includes: initializing a fixed execution cycle and determining the target number of pulses; acquiring the current pulse state; controlling the output of the first and second pulse signals based on the target number of pulses, setting the pulse repetition count, timer load value, and comparison value; setting the comparison register according to the direction and current state; setting the timer register and starting the timer to output pulse signals; and updating the current state based on the actual number of output pulses. This invention establishes a correspondence between the target number of pulses and timer parameters, utilizes comparison output control to achieve precise output of AB phase pulses, and maintains signal phase continuity through state updates, achieving high-precision quadrature pulse generation under low-cost conditions. Attached Figure Description
[0012] The present invention will be further described below with reference to the accompanying drawings and embodiments. In the accompanying drawings: Figure 1 This is a schematic diagram of an application environment for a pulse generation method based on timer comparison output according to an embodiment of the present invention; Figure 2 This is a flowchart illustrating an embodiment of the pulse generation method based on timer comparison output according to the present invention; Figure 3 This is a schematic diagram of the functional modules of a preferred embodiment of the pulse generation device based on timer comparison output of the present invention; Figure 4 This is a schematic diagram of the structure of a computer device according to an embodiment of the present invention; Figure 5 This is another structural schematic diagram of a computer device according to one embodiment of the present invention; Figure 6 This is a schematic diagram of the blocking execution flow of a pulse generation method based on timer comparison output in one embodiment of the present invention; Figure 7 This is a schematic diagram of the non-blocking execution flow of a pulse generation method based on timer comparison output in one embodiment of the present invention. Detailed Implementation
[0013] It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the invention.
[0014] The pulse generation method based on timer comparison output provided in this invention can be applied to, for example... Figure 1 In this application environment, the client communicates with the server via a network. The server can initialize a fixed execution cycle and determine the target number of pulses through the client; obtain the current pulse state; control the output of the first and second pulse signals by setting the pulse repetition count, timer load value, and comparison value based on the target number of pulses; set the comparison register according to the direction and current state; set the timer register and start the timer to output pulse signals; and update the current state based on the actual number of output pulses. This invention establishes a correspondence between the target number of pulses and timer parameters, utilizes comparison output control to achieve accurate output of AB phase pulses, and maintains signal phase continuity through state updates, achieving high-precision orthogonal pulse generation under low-cost conditions. The client can be, but is not limited to, various personal computers, laptops, smartphones, tablets, and portable wearable devices. The server can be implemented using a standalone server or a server cluster composed of multiple servers. The invention will be described in detail below through specific embodiments.
[0015] Please see Figure 2 , Figure 2 This is a flowchart illustrating an embodiment of the pulse generation method based on timer comparison output provided by the present invention. It should be noted that although the logical order is shown in the flowchart, in some cases, the steps shown or described may be performed in a different order than that shown here.
[0016] like Figure 2 As shown, the pulse generation method based on timer comparison output proposed in this invention includes the following steps: S10, Initialize a fixed execution cycle, where the fixed execution cycle corresponds to the total value of the timer; In this embodiment, a fixed execution period is used to define the time boundary of the output pulse signal, and its duration corresponds to the total value of the timer. The total value of the timer is determined by the counting clock frequency and the value loaded in the auto-reload register. For example, in an embedded microcontroller environment, the timer counting frequency is determined by the external crystal oscillator frequency and the frequency divider. By initializing the fixed execution period, the timing of the output pulses can be kept constant within each execution period, thereby achieving pulse period stability. The initialization operation includes clearing the timer count register, loading the preset auto-reload value, and enabling the clock source input to ensure that the timer starts counting from a uniform reference state.
[0017] The fixed execution cycle is typically set via register programming, such as writing the total value into the Automatic Reload Register (ARR) or an equivalent load unit on the controller. The total value can be calculated by working backwards from the pulse output frequency requirement. For example, if the target output frequency is Fout and the counting clock frequency is Fclk, the total value can be set to Fclk / Fout, thus generating a matching time interval when the timer overflows. This parameter works in conjunction with the pulse count control module to determine the duration and interval accuracy of each output pulse.
[0018] During the fixed execution cycle initialization process, a synchronization mechanism must also be established to ensure that the timer start time is consistent with the control logic state. For example, in a system with multi-channel pulse output, hardware synchronization input (TRGO signal) or software triggering can be used to achieve synchronous start of multi-channel timers. To avoid phase drift, a pre-load comparison register operation can also be performed during the initialization phase to align the first comparison event with the counting start point, forming a phase reference point.
[0019] After the fixed execution cycle initialization is completed, the timer enters the pre-running state. The counting logic and the output comparison logic operate within the same reference cycle, providing a time reference for subsequent pulse quantity control and phase switching. The accuracy of this cycle determines the timing stability and quadrature accuracy of the pulse signal.
[0020] This embodiment initializes a fixed execution cycle before output and establishes a precise correspondence with the total value of the timer, so that each pulse output cycle has a uniform time scale. This maintains the consistency of pulse timing and phase continuity when switching between different output frequencies and directions, thereby improving the accuracy and stability of quadrature pulse output.
[0021] S20, determine the target number of pulses within the fixed execution cycle; In this embodiment, the target pulse count is used to determine the number of pulses output within a fixed execution cycle, and is a key parameter for controlling the output frequency, direction, and phase changes. Its determination process typically involves obtaining pulse output command data from the host computer control terminal, motion control module, or sensor feedback module. This command includes the desired pulse count, direction sign, and output mode. The target pulse count not only represents the number of pulses but also implicitly contains information such as output frequency and movement distance, corresponding to a discrete count of one position or angle change in the encoder simulation or servo control system.
[0022] The process of determining the target pulse count can be divided into data reception, verification, parsing, and adjustment. The control unit transmits data packets containing pulse commands via serial port, CAN bus, SPI, or Ethernet interface, with a checksum field included in the data packet. After acquiring the data, the receiving module performs a CRC check or checksum calculation to ensure data integrity. The verified command data is read by the parsing module, which extracts the target pulse field. This field is typically a signed integer, with positive values representing forward movement and negative values representing reverse movement.
[0023] After parsing, the system performs a rationality check, including checking whether the number of pulses in the command is zero, whether it exceeds a preset safety threshold, or whether it conflicts with the current system state. For example, when the output device is in a limit state or the previous pulse output is incomplete, the target number of pulses will be limited or delayed. The system can also dynamically adjust the target number of pulses based on the current load state, the upper limit of the output frequency, and the temperature rise control strategy, thereby achieving flexible control.
[0024] In multi-source control scenarios, multiple tasks may simultaneously issue pulse output requests, which the system processes through a priority fusion mechanism. Each instruction source is assigned a priority weight, and when conflicts occur, the system selects the highest-priority task for execution based on priority and timestamp. The final target pulse count is confirmed, written to the buffer, and synchronized to the non-volatile storage module to ensure output consistency after system reset or interrupt recovery.
[0025] This embodiment accurately determines the number of target pulses within a fixed execution cycle, enabling the system to maintain stable output under different frequencies and directions. This achieves precise matching of timer parameters, reduces pulse loss and phase misalignment during direction reversal or frequency switching, and improves the real-time response and control accuracy of signal output.
[0026] S30, at the start of the fixed execution cycle, the current pulse state is obtained, wherein the current pulse state is a combination of the levels of the first pulse signal and the second pulse signal; In this embodiment, at the start of a fixed execution cycle, the current pulse state needs to be obtained from the system's state record structure. The current pulse state is an instantaneous state reflecting the current logic level combination of the pulse output port, used to indicate the phase relationship between the first and second pulse signals. The level combination between the two pulse signals has four possible forms, typically corresponding to the four quadrant states of a quadrature encoder. By obtaining this state at the start of the cycle, it can be ensured that the direction of subsequent pulse outputs is consistent with the current level, thereby avoiding signal misalignment caused by pulse jumps or direction reversals.
[0027] The calculation of the current pulse state is typically based on the accumulated pulse count within the system. The control unit obtains the state index value by taking the remainder of the accumulated pulse count with a fixed modulus (e.g., four). This index value corresponds to a specific entry in a predefined state array, with each entry containing two bits representing the level values of the first and second pulse signals, respectively. For example, an index of zero indicates that both signals are low, an index of one indicates that the first signal is high and the second is low, and so on. In this way, the current level combination can be derived from the counting logic without reading the levels of external pins.
[0028] In some implementations, the two output levels can be read directly from the current status bit of the timer compare output register. This method is suitable for hardware platforms with direct output mapping registers. The read status value must undergo validity checking before entering the output control logic to prevent invalid states from being applied due to interrupt latency or register synchronization lag. The detection method can include comparing the phase difference between the previous cycle state and the current state. If the phase difference is greater than 90 degrees or less than zero degrees, it is determined to be an invalid state, and the previous state output is maintained.
[0029] The level combination is used in the output control logic to determine the phase offset direction. If the current state indicates that the first pulse signal leads the second, the direction is positive; otherwise, it is negative. This information is passed to the subsequent comparison register setting unit to determine the loading order of the first and second comparison values in subsequent output cycles. In this way, the system can smoothly transition from the end state of the previous output cycle at the beginning of each execution cycle, ensuring the phase continuity of the quadrature pulse signals.
[0030] The current pulse state can be obtained through software calculation. The controller periodically reads the accumulated pulse count in a timer update interrupt, updates the current state index based on the modulo operation, and then looks up the level combination in a table. Alternatively, it can be implemented in hardware using state machine logic, using two-bit flip-flops to store the previous state of the two output signals respectively, and triggering state synchronization when the count overflows. For control systems requiring higher real-time performance, the current level combination can also be obtained by directly reading the instantaneous value of the GPIO output register, which is particularly suitable for use in microcontrollers without dedicated state registers.
[0031] For systems requiring multiple output signals, an independent state buffer can be maintained for each output channel. At the start of the cycle, the states of each channel are read in parallel and then uniformly passed to the subsequent register configuration logic. To prevent state contention in a multi-threaded environment, atomic read / write mechanisms or bus locking operations can be used to ensure consistency between state readings and updates.
[0032] This embodiment obtains the current pulse state at the beginning of a fixed execution cycle. The system can use the actual level of the current two pulse signals as the starting point for output control, so that the comparison register setting of the next cycle is completely connected with the output phase, thereby avoiding level reversal and phase jump, and maintaining the continuity and directional accuracy of the output pulse waveform.
[0033] S40, based on the absolute value of the target pulse number, dynamically set the pulse repetition count, timer repetition load value, first comparison value and second comparison value to control the output behavior of the first pulse signal and the second pulse signal; In this embodiment, the absolute value of the target pulse count is used to calculate the number of pulse groups to be generated within the output cycle and the repetitive operation parameters of the timer, serving as the core of the dynamic adjustment of the entire pulse output logic. By extracting the absolute value of the target pulse count, the output pulse rhythm can be uniformly controlled without considering the direction, ensuring that the output frequency matches the total number of pulses.
[0034] The pulse repetition count indicates the number of counting cycles the timer needs to complete within a fixed execution cycle. The number of pulse toggle pairs in each output group is determined by dividing the absolute value of the target pulse count by the integer part of two. For example, when the target pulse count is eight, the system sets the pulse repetition count to four, meaning the timer completes four count toggle operations within the current execution cycle. This value is directly written to the timer's repetition count register to limit the number of times the comparison output is triggered.
[0035] The timer reload value determines the duration of each counting cycle. This value is calculated based on the ratio of the total timer value to the number of pulse repetitions, i.e., reload value = total value / number of pulse repetitions, thus dividing the entire execution cycle into several counting intervals. By adjusting this parameter, the interval width of a single pulse can be changed while keeping the total execution cycle constant, achieving dynamic frequency adjustment.
[0036] The first and second comparison values determine the phase switching times of the two pulse signals. The first comparison value is typically set to one-quarter of the reload value minus the offset, used to control the flipping time of the first pulse signal; the second comparison value is three-quarters of the reload value minus the offset, used to control the flipping time of the second pulse signal. The offset is used to correct for timer hardware delays and synchronization errors, ensuring that the phase difference between the two pulse signals remains around 90 degrees. Through this setting method, the system can maintain phase synchronization and output stability under different pulse counts.
[0037] When the pulse count is one, the system sets the repetition count to one, the timer reload value equal to the total value, the first comparison value to half the period, and the second comparison value to a non-flipping value, indicating that the second signal does not participate in the flipping in the current period, thus outputting a single pulse. When the target pulse count is zero or invalid, all comparison values remain unchanged, and the output module remains stationary.
[0038] The dynamic setting process is completed before the timer starts, and the consistency of the configuration parameters before they take effect is ensured through an interrupt locking mechanism. The system recalculates these parameters at the end of each execution cycle, so that the output frequency, phase, and number of pulse groups can change in real time according to the input command without generating intermediate state interference.
[0039] The dynamic setting process can be implemented through software calculations. In the interrupt callback function, the target pulse count buffer is read, integer division and offset correction are performed, and then the timer parameter register is updated. Alternatively, a hardware coprocessor can be used, triggering DMA transfer via timer events to write pre-calculated reload values and comparison values into the register, achieving low-latency parameter updates.
[0040] Various adjustment strategies can be adopted to meet different output requirements. For example, in high-frequency pulse output scenarios, a double-buffered register mechanism can be used to preload the next set of parameters within one counting cycle to reduce parameter switching latency. In low-speed, high-precision control scenarios, a phase calibration module can be added to correct the phase error between the first and second comparison values through feedback signals. For systems with direction switching requirements, the loading order of the comparison values of the two pulses can be dynamically interchanged according to the sign of the target pulse count to achieve seamless reversal of the output direction.
[0041] This embodiment dynamically sets the pulse repetition count, timer repetition load value, and comparison value based on the absolute value of the target pulse count. It can automatically adjust the timer parameters under different output counts and frequencies, keeping the phase difference and timing stability of the output pulse signal constant. This achieves flexible and adjustable quadrature pulse output, improving the controllability and accuracy of signal generation.
[0042] S50, based on the direction of the target pulse quantity and the current pulse state, set the comparison registers corresponding to the first pulse signal and the second pulse signal; In this embodiment, setting the comparison registers corresponding to the first and second pulse signals based on the direction of the target pulse quantity and the current pulse state is a crucial step in output direction control and phase maintenance. The direction of the target pulse quantity is used to distinguish the forward and reverse logic of the pulse output, while the current pulse state is used to determine the level combination of the two signals. Through the joint judgment of both, the system can dynamically determine which signal should undergo a level flip first in the current execution cycle, thereby achieving controllable and continuous directional output of the AB phase quadrature.
[0043] The direction of the target pulse count is determined by the instruction parsing module during the instruction receiving phase, typically using a sign bit. A positive direction indicates that the first pulse signal leads the second pulse signal by 90 degrees, while a negative direction indicates that the second pulse signal leads the first pulse signal by 90 degrees. The current pulse state is composed of the level combination recorded at the end of the previous cycle and stored in a status register or software buffer, used to determine which quadrant of the quadrant the current output is in.
[0044] The comparator register is the core register unit in the timer used to trigger level switching. Based on the current direction and level combination, the system determines whether to write the first or second comparison value into the comparator register corresponding to the first and second signals, respectively. For example, when the direction is positive and the current level combination is in phase, the first comparison value is written to the first comparator register, and the second comparison value is written to the second comparator register, causing the first pulse signal to flip when the count value reaches the first comparison value, thus maintaining its phase lead. If the direction is negative and the current level combination is out of phase, the writing order is reversed.
[0045] The logical judgment in this process is typically implemented using a branching structure. The system first determines the direction of the target pulse count, and then classifies the current pulse state into two combinations: those with the same or different levels. For the four possible state and direction combinations, four sets of register write rules are defined so that any input state can be mapped to the correct output sequence. The write operation is performed when the timer is not started, and a synchronous trigger signal ensures that the comparison register takes effect simultaneously in the next counting cycle, avoiding false triggering in intermediate states.
[0046] In terms of hardware, different microcontroller platforms may provide different compare register mapping structures. For example, in the STM32 series, the first and second signals can correspond to the TIMx_CCR1 and TIMx_CCR2 registers; in the NXP Kinetis series, they can correspond to the Channel Compare register of the FlexTimer module. Regardless of the specific hardware architecture, the logical essence of this setup process is to determine the register write order and the source of the comparison value based on the direction and level state.
[0047] The comparison register setting logic can be implemented as a function in the firmware. In one implementation, the direction flag and the current pulse status flag register are read and combined into an index number to access a predefined register write table. This table contains the comparison value allocation rules for each direction and state, thus enabling fast configuration via unconditional jumps. Alternatively, it can be implemented as a state machine, where the register update order for the next state is determined by the current state transition logic within the interrupt service routine.
[0048] The comparison register can also be updated within the microcontroller's on-chip peripherals via DMA or event-triggered mechanisms. When the direction flag or current pulse state changes, a timer update event or comparison match event triggers a transfer, moving the first and second comparison values from the pre-prepared parameter buffer to the comparison registers corresponding to the first and second pulse signals, respectively. This reduces CPU involvement and shortens register update latency. Alternatively, the comparison register can be written within an interrupt service routine, triggering a register synchronization signal upon completion. This ensures the new value of the comparison register takes effect in the next counting cycle, preventing erroneous flips caused by mid-cycle rewriting. For higher frequencies or more stringent timing scenarios, a double parameter buffer can be added, and the buffer pointer can be switched at update event boundaries to align register writes with timer counting boundaries.
[0049] This embodiment achieves real-time control of the pulse output direction and phase relationship by dynamically setting the comparison registers corresponding to the first and second pulse signals by combining the direction of the target pulse quantity with the current pulse state. This enables the timer to maintain output continuity and synchronization under different direction switching and level combination changes, eliminating the problems of pulse misalignment, phase jump and dead zone delay when the direction is reversed in the traditional scheme.
[0050] S60, Set the repeat count register and auto-reload register of the timer; In this embodiment, setting the timer's repetition count register and auto-reload register are core operations to ensure a stable period and controllable repetition count for the timing output signal. A timer is a commonly used hardware logic unit in embedded controllers. By using the auto-reload register and the repetition count register in conjunction, continuous periodic pulse output can be achieved. The repetition count register limits the number of repetitions in the counting cycle, thereby controlling the total number of pulse output cycles; the auto-reload register automatically loads a preset initial value after the counter reaches its overflow point, maintaining the timer's periodicity.
[0051] During configuration, the control logic first calculates the number of times a single timing cycle should be executed based on the relationship between the target pulse count and the fixed execution period. This value is written to the repetition count register, enabling the timer to repeatedly count according to the set period. This repetition count directly affects the total number of pulses in the output signal and is crucial for achieving precise pulse output control. The auto-load register stores the count value corresponding to the fixed execution period, representing the number of clock cycles required for the timer to count from zero to overflow. When the counter reaches overflow, the value in the auto-load register is rewritten to the count register, causing the timer to immediately restart counting, thus achieving continuous and stable periodic output without interrupting the main control program.
[0052] In practical implementation, the auto-load register can be calculated based on the system clock frequency and the required output frequency. For example, when the system clock frequency is 100MHz and the target output period is 1kHz, the auto-load value is 100000. By modifying the value of this register, the output period can be flexibly adjusted to adapt to the response characteristics of different devices. The value of the repetition count register can be calculated by dividing the target number of pulses by the number of pulses per cycle, ensuring that the timer automatically stops after the output cycle ends without generating extra pulses.
[0053] The typical order for configuring registers is to configure the autoload register first, followed by the repetition count register, to ensure the timer executes with the latest parameters upon subsequent startup. To prevent abnormal output during register updates, register write operations are usually performed when the timer is off. The control logic can trigger a synchronous update event after configuration, making the new parameters effective in the next cycle and avoiding output interruptions. For hardware timers with buffering mechanisms, register data can be preloaded in the background and updated seamlessly during timer operation.
[0054] This embodiment achieves precise control over the pulse output period and the number of repetitions by setting the repetition count register and auto-reload register of the timer, enabling the system to complete continuous output without main control intervention. This mechanism effectively improves the time stability and phase consistency of the pulse output, avoiding period offset or pulse loss caused by main control delay. The combination of the timer's auto-reload mechanism and repetition counting control gives the output behavior self-synchronization characteristics, improving the real-time performance and reliability of the control system.
[0055] S70, start the timer to output the first pulse signal and the second pulse signal; In this embodiment, starting the timer to output the first and second pulse signals is the execution phase of the entire pulse control process, marking the entry into the hardware output stage after parameter configuration is completed. After configuring the repetition count register and auto-load register, the timer is written with the start control bit and enters the counting state. When the count value matches the preset comparison register value, the timer output port undergoes a level flip, thereby forming a periodic pulse signal. By setting two independent output channels, the first and second pulse signals are output with a fixed phase difference to form orthogonal signal pairs, achieving bidirectional control of direction and displacement.
[0056] In the actual control logic, the startup process includes enabling the timer clock, clearing the counter register, setting the compare interrupt enable bit, and writing the startup control command. The system enables the start bit in the timer control register, and the timer begins counting and outputting according to the preset period and compare value. At this time, the output port automatically flips at the arrival of each compare event through internal capture and compare logic, thus forming a precisely timed pulse waveform. The first and second output channels maintain a fixed time offset relationship through phase logic, with the offset direction determined by the direction parameter of the target pulse count.
[0057] Timers are typically started via either hardware triggering or software commands. In hardware triggering mode, an external event signal can be used as the start condition, such as a synchronization signal from a host computer or a start signal detected by a sensor. In software start mode, the main control unit directly triggers the timer to start running via control commands after all registers are configured. To ensure the continuity and accuracy of the output timing, the system can perform a synchronization update event before startup, so that the latest configurations of the autoload register and the compare register take effect simultaneously.
[0058] The level toggling of the output signal is typically driven by compare-match logic. When the count value equals the first compare value, the first output toggles; when the count value equals the second compare value, the second output toggles. The toggling order of the two signals is controlled by a direction parameter: the first signal toggles first in a positive direction, and the second signal toggles first in a negative direction. After the counter reaches its overflow value, it reads the initial value from the auto-reload register to begin a new round of counting, achieving continuous periodic pulse output.
[0059] This embodiment achieves precise generation of quadrature pulse sequences by starting a timer to output dual-channel pulse signals, enabling synchronized execution of pulse direction and phase control. This process automatically completes the periodic output without CPU intervention, improving system real-time performance and output stability. The timer automatically performs counting, comparison, and toggling logic at the hardware level, effectively reducing the main control load and avoiding phase jitter or time errors caused by software delays, thereby achieving high-precision motion control and synchronized signal output.
[0060] S80, update the current pulse state based on the actual number of pulses output.
[0061] In this embodiment, updating the current pulse state based on the actual number of output pulses is a crucial step in achieving output signal self-calibration and state synchronization during closed-loop control. The current pulse state represents the level combination relationship between the first and second pulse signals, reflecting the actual state of the current output sequence in phase and direction. By comparing the theoretical number of pulses output by the timer with the actual number of outputs fed back by the peripheral, state updates can be achieved, enabling the system to redefine the initial output state based on the actual pulse positions in the next cycle.
[0062] The actual number of output pulses can be obtained through various detection mechanisms, including reading from a hardware counter, counting via GPIO edge detection interrupts, or the cumulative pulse value fed back by the encoder module. During implementation, the system reads the current counter value at the end of each fixed execution cycle and compares it with the target number of pulses. If a deviation exists, the current pulse state is updated based on the direction of the deviation and the phase combination of the pulse signal to ensure the logical continuity of the output signal. The updated pulse state is stored in a status register or software variable for initial condition configuration before the next timer start.
[0063] The level combination update follows orthogonal encoding logic. If the first and second pulse signals are orthogonal phase signals, when the actual number of output pulses is odd, the level state cycles through four combinations; when it is even, the level state returns to its initial value. In this way, the system can maintain the correctness of the pulse phase in real time. To prevent signal jitter under high-frequency conditions, a synchronous latching mechanism can be added to the update logic to ensure that the state update is completed when the timer stops or during the output interval.
[0064] This embodiment updates the current pulse state based on the actual number of output pulses, enabling the system to maintain correct phase logic and output direction even in the presence of output delay, lost pulses, or counting errors. This mechanism allows the output signal of the next cycle to be initiated based on the actual state, thereby improving the continuity and accuracy of the output waveform, reducing pulse accumulation errors, and enhancing the stability and reliability of closed-loop control.
[0065] This invention relates to the field of pulse generators and industrial control technology, and discloses a pulse generation method, apparatus, device, and medium based on timer comparison output. The method includes: initializing a fixed execution cycle and determining the target number of pulses; acquiring the current pulse state; controlling the output of first and second pulse signals by setting the pulse repetition count, timer load value, and comparison value based on the target number of pulses; setting a comparison register according to the direction and current state; setting the timer register and starting the timer to output pulse signals; and updating the current state based on the actual number of output pulses. This invention establishes a correspondence between the target number of pulses and timer parameters, utilizes comparison output control to achieve precise output of AB phase pulses, and maintains signal phase continuity through state updates, thus achieving high-precision quadrature pulse generation at low cost.
[0066] In one embodiment, step S20 above includes: S201, Receive pulse output command data packet from the control terminal, verify the integrity and correctness of the pulse output command data packet, and obtain the verification result; S202, based on the verification result, parse the pulse output command data packet to obtain the target pulse count; S203, determine the direction sign of the target pulse quantity; S204, Check whether the number of target pulses is zero or an abnormal value, and obtain the check result; S205, dynamically adjust the target pulse count based on the current system load and the inspection results to obtain the adjusted target pulse count; S206, Based on the multi-source instruction priority fusion processing, the adjusted target pulse number is obtained to obtain the final target pulse number; S207, store the final target pulse count in a non-volatile memory, update the target pulse count cache, and send an acknowledgment signal based on the storage result.
[0067] In this embodiment, receiving pulse output command data packets from the control terminal is achieved collaboratively with the communication layer and application layer. The communication layer establishes a bounded frame structure and timeout control, while the application layer maintains the order of command arrival and deduplication flags in the buffer. The pulse output command data packet includes a sender identifier, session number, timestamp, payload length, payload content, and an integrity field. The integrity field can use CRC or message verification code. The buffer adopts a circular structure and separates write and read pointers to reduce the number of copies. When an interrupt or DMA arrives, a parsing process is triggered. Data packets that fail the minimum length and frame header matching check are immediately discarded and recorded as a statistical count.
[0068] The integrity and correctness of the pulse output command data packet are verified using a two-layer mechanism. The first layer addresses transmission errors through CRC or polynomial checksum verification. The second layer addresses protocol consistency through field range verification, sequence number monotonic verification, timestamp window verification, and source whitelist verification. Sequence number monotonic verification is used to prevent replay attacks, timestamp window verification is implemented by comparing the local clock with offset tolerance, and the source whitelist is identified through control terminal keys or port binding. The verification result is expressed in memory as an enumeration value and an error bitmask, indicating both success and the specific reason for failure, providing a basis for subsequent alarm and rate limiting strategies.
[0069] The target pulse count is obtained by parsing the pulse output command data packet based on the verification result using a type-safe deserialization process. The target pulse count in the payload is represented using fixed-point or integer representation. During parsing, byte order conversion and range limiting are performed. The range limiting is bound to hardware capabilities; for example, the upper limit cannot exceed the number of pulses that can be mapped from the total value of the timer. To avoid implicit overflow, the parsing result is first placed in a high-precision temporary variable and then saturated and pruned before finally being written into the operation domain variable "target pulse count" along with a data source marker to participate in priority decision-making.
[0070] The direction sign for determining the target pulse count is accomplished through zero-value judgment and numerical sign extraction. Sign extraction is performed with uniform precision, with positive values corresponding to positive directions and negative values corresponding to negative directions, and zero values are identified separately. The direction sign corresponds one-to-one with the subsequent phase relationship and the order of writing to the comparison register, and is stored as an independent field in the data structure and enters the decision pipeline along with the target pulse count.
[0071] The check for the target pulse count being zero or an anomaly is driven by a set of rules. Zero values are directly entered into the short-circuit path to avoid unnecessary output preparation. Anomalies include out-of-range values, unresolvable states, untrusted sources, and incompatibility with the current device mode. The check result is represented by a Boolean value and an anomaly code. When a critical anomaly, such as a large out-of-range value, occurs, degradation processing is immediately performed and an acknowledgment signal carrying an error code is triggered to prevent the output from entering an undefined state.
[0072] The target pulse count is dynamically adjusted based on the current system load and inspection results, implemented through a feedback adjustment model. The current system load includes CPU usage, timer channel usage, bus bandwidth window, and interrupt backlog depth. Load sampling employs a combination of moving average and peak hold. The adjustment strategy performs proportional reduction or segmentation of the target pulse count. Proportional reduction is used for rapid mitigation during instantaneous overload, while segmentation completes the target within multiple fixed execution cycles to balance jitter and timing. The adjustment output is expressed as the adjusted target pulse count, retaining the difference from the original value for log review.
[0073] The target pulse count is adjusted based on multi-source command priority fusion processing to unify conflicts. The multi-source components include the host computer control terminal, online policy engine, field safety interlocks, and local backup logic. The priority table is primarily statically configured, allowing safety interlocks to override at any time. The fusion process first selects a baseline value based on priority, then weights or overrides it based on source credibility and time freshness, preventing outdated commands from altering the latest intent. The fusion result is the final target pulse count, verified for consistency with the direction symbol. When a contradiction is found between the symbols before and after fusion, the source with higher credibility takes precedence, and the conflict entry is recorded.
[0074] The final target pulse count is stored in non-volatile memory using an atomication and wear leveling mechanism. Atomization is achieved through double-page mirroring and valid bit switching. Before writing, CRC generation is performed again in the verification buffer. After writing, the count is read back and compared; if they match, the valid bit is toggled; otherwise, the previous version is rolled back. Wear leveling is maintained through round-robin addresses and a write count table to avoid overwriting a single block. After storage is complete, the target pulse count cache is updated. The cache is located in high-speed RAM and carries a version number. An acknowledgment signal is sent to the control terminal, containing the version number, the final target pulse count, and a brief status code. If the fragmentation mode is entered, a planned fragment count is additionally provided for upper-level scheduling.
[0075] This embodiment employs a closed-loop path from receiving and verifying to parsing and direction determination, then to load adaptive adjustment and multi-source instruction priority fusion. The final target pulse count undergoes consistency verification, capacity pruning, and conflict resolution before entering the execution side, and is atomically written to disk and synchronized with the cache. A confirmation signal provides a verifiable result of the effective output. Compared to unfiltered direct output, this process reduces the risk of timing jitter and pulse loss caused by abnormal commands and overloaded instructions, reduces direction reversal and phase misalignment caused by source conflicts, and improves the predictability and traceability of subsequent comparison register configuration and timer output. This results in more robust pulse count control and direction consistency within a fixed execution cycle.
[0076] In one embodiment, step S30 above includes: S301, at the beginning of the fixed execution cycle, calculate the state array index based on the system's cumulative pulse count; S302, obtain the current pulse state value through the state array index and the predefined state array; S303, Verify whether the current pulse state value is valid; S304 applies a valid current pulse state value to the first and second pulse signals through a timer comparison output function to output the corresponding level combination.
[0077] In this embodiment, the boundary at the start of the fixed execution cycle needs to form a snapshot of the observation at the same moment between the timing reference and the output path. The fixed execution cycle is derived from the cycle of the timer's total value. The initial determination is confirmed by updating the event flag or submitting an event in the shadow register, avoiding instantaneous inconsistencies in the level caused by reading during the counting process. The system's cumulative pulse count is a monotonic counting variable maintained on the execution side, which records both the total number of valid pulse edges that have been output and the pulse progress left over from the previous fixed execution cycle. During reading, short critical sections with interrupts disabled or double-consistent readings are used to ensure the atomicity and consistency of the index calculation.
[0078] The state array index is calculated based on the system's cumulative pulse count using a modulo-cyclic mapping, compressing the linearly growing count into a finite set of phase categories. The index space is tied to the resolution of the orthogonal coding; for quadruple harmonics, it uses a modulo of four; for single or double harmonics, it uses a subset of two or four, with the specific values consistent with the edge strategy for generating subsequent comparison values. Index calculation is performed in a uniform-width unsigned field to avoid differences in right-shift signed extensions between different compilers. When inverse direction mapping is required, a direction symbol is introduced to perform addition / subtraction shifts on the index before taking the modulo. The direction symbol comes from the direction decision of the target pulse count, ensuring the index aligns with the motion intent. Figure 1 To.
[0079] A predefined state array represents the stable level relationship between the first and second pulse signals using a two-dimensional level combination table, maintaining consistency with the physical phase order. The quadruple frequency forward sequence can be configured as a circular sequence of low-low, low-high, high-high, high-low, while the reverse sequence is obtained by reading in reverse order. When there are engineering differences such as peripheral polarity reversal or line reversal, the array content is rewritten during the loading phase using a one-time polarity mapping table, without modifying the upper-level logic. The state array resides in a non-executable read-only area or a protected constant area to prevent accidental overwriting during runtime. In scenarios requiring hot-switching of direction encoding rules, two sets of arrays can be maintained, and the active set can be selected based on the direction sign at the beginning of a fixed execution cycle.
[0080] The current pulse state value is retrieved via the state array index and executed immediately after the index calculation. The retrieved current pulse state value represents the level combination of the first and second pulse signals using two or two Boolean bits, along with a version stamp and a count snapshot of the time of retrieval, ensuring consistency with the boundary at the start of the fixed execution cycle. To facilitate the use of subsequent output comparison paths, the current pulse state value is also projected onto the duty cycle field, forming a mask bit that forces hold or allows toggling, providing a criterion for preloading and disabling toggling in the comparison register.
[0081] Verification of the validity of the current pulse state value is performed in three layers. The first layer is encoding validity verification, checking if the current pulse state value belongs to a valid member of a predefined array. Superset values or uninitialized flags directly trigger a backoff. The second layer is topology continuity verification, comparing the difference between the system's accumulated pulse count and the previous effective state. Allowed transitions are only between adjacent positions in the circular array; crossing two or more positions is considered a dropped edge or jitter intrusion, triggering a backoff path. The third layer is hardware observation consistency verification, reading the current output latch level of the comparison output function or the GPIO input readback level and comparing it with the current pulse state value. If an inconsistency exists and exceeds the tolerance window, the actual hardware level is used to correct the current pulse state value, and a consistency correction event is recorded for subsequent statistical and adaptive filtering reference.
[0082] The process of applying a valid current pulse state value to the first and second pulse signals via the timer comparison output function aims to avoid introducing extra edges within the same fixed execution cycle. If the first and second pulse signals match the current output level, only the allowable toggle mask in the shadow register is updated, without triggering a forced write. If there is a discrepancy, the forced output mode is used first to pull the channel output to the target level, and then the process is restored to the comparison output mode, with the comparison event taking over subsequent toggle operations. A minimum safety interval is inserted between the forced output and the restoration action, with the interval length consistent with the timer clock, dead-time setting, and output filtering. To avoid race conditions when the counter approaches the comparison critical point, the application process is executed within a non-flippable window immediately following the update event. The window length is calculated as a number of timer clock cycles, and new comparison matches are prohibited within the window to ensure atomic level switching. After the application is completed, a synchronization request is written to verify the contents of the shadow register and the output stage as a whole at the boundary of the next counting cycle, ensuring that the first and second pulse signals operate according to the predetermined phase relationship under the drive of subsequent comparison values.
[0083] This embodiment constructs a state array index at the beginning of a fixed execution cycle, using the system's accumulated pulse count as the sole driver. It obtains the current pulse state value through a predefined state array and performs three levels of verification: validity, continuity, and hardware consistency. Then, the comparison output function atomically applies the result to the first and second pulse signals within a safe window, ensuring that the two signal levels reach the desired level at the cycle boundary. Figure 1 The mechanism aligns historical counts, phase topology, and peripheral latches, reducing phase drift and race conditions at the starting boundary. This lowers the probability of miscounting caused by jitter or dropped edges, providing a stable initial value for subsequent pulse flips and direction determination. Consequently, it achieves lower initial transient error and higher direction determination confidence under the same clock and load conditions.
[0084] In one embodiment, step S40 above includes: S401, determine the absolute value of the target pulse count; S402, when the absolute value of the target pulse number is greater than or equal to the first threshold, the pulse repetition number is calculated as the integer part of the absolute value of the target pulse number divided by two, the timer reload value is calculated as the total value of the timer divided by the pulse repetition number, and the first comparison value and the second comparison value are determined, wherein the first comparison value is the timer reload value divided by four minus the offset, and the second comparison value is the timer reload value multiplied by three-quarters minus the offset. S403, when the absolute value of the target pulse count is equal to the second threshold, the pulse repetition count is set to one, the timer reload value is set to the timer total value, the first comparison value is set to the timer reload value divided by two, and the second comparison value is set to the non-flip value; S404, when the absolute value of the target pulse count is equal to the third threshold, the pulse repetition count is set to one, the timer reload value is set to the timer total value, and the first comparison value and the second comparison value are set to the non-flip value; S405, write the first comparison value and the second comparison value into the comparison registers corresponding to the first pulse signal and the second pulse signal respectively, so that when the timer count value reaches the first comparison value and the second comparison value, the level of the corresponding pulse signal is triggered to flip; S406, set the output behavior according to the direction of the target pulse number, wherein when the direction of the target pulse number is positive, the first pulse signal flips relative to the second pulse signal in a leading order, and when the direction of the target pulse number is negative, the second pulse signal flips relative to the first pulse signal in a leading order.
[0085] In this embodiment, the absolute value of the target pulse count is determined based on the target pulse count given in the previous step. First, amplitude reading and validity verification are performed, and then the absolute value is obtained in the unsigned domain to prevent boundary anomalies caused by sign expansion. To avoid extreme inputs causing subsequent register configuration out-of-bounds errors, the absolute value is saturated and pruned within a preset upper limit, which is constrained by the total timer value, the number of comparison channels, and the synchronization delay budget. After the absolute value is generated, it is compared with the first, second, and third thresholds one by one. The three types of branches are mapped to different output clock cycle planning paths. The comparison operation is placed in the short critical section with interrupt disabled to ensure the consistency of the one-time decision.
[0086] When the absolute value of the target pulse count is greater than or equal to the first threshold, the pulse repetition count is obtained by dividing the absolute value by two to obtain an integer result, which is used to plan the two edges in pairs within a fixed execution cycle. After the pulse repetition count is generated, it is divided by the ratio of the total timer value to obtain the timer repetition load value, so that each repetition load forms an equal-length counting interval, ensuring that the time interval between two adjacent flips is consistent. Before writing the timer repetition load value, the lower limit and upper limit of the interval are checked. The lower limit is based on the minimum resolvable count beat to avoid loading zero or too small values, which may cause excessively dense comparison events; the upper limit does not exceed the total timer value to ensure that the cycle division is complete. The first comparison value and the second comparison value are located at the one-quarter and three-quarter positions within this interval, respectively, and offset compensation is introduced for each. The offset is used to offset the channel transmission delay, the synchronous event propagation delay, and the phase offset caused by the peripheral polarity mapping; the offset direction and magnitude are adjustable, and before writing, the comparison point is ensured to still fall within the effective window of the timer repetition load value by pruning. To reduce critical contention, a safety margin is maintained between the comparison point and the interval boundary. The safety margin is determined jointly by the clock frequency, the shadow register commit delay, and the output filter time constant.
[0087] When the absolute value of the target pulse count equals the second threshold, the pulse repetition count is set to once, the timer reload value is equal to the total timer value, the first comparison value falls at the midpoint of the cycle, and the second comparison value is set to a non-flipping value. A non-flipping value means that the comparison channel will not trigger a flipping event in the current cycle. Specifically, this can be achieved by disabling the comparison channel output enable, placing the comparison point in an unreachable region for natural failure, or disabling the flipping at the shadow register level using a flip mask. This branch generates only one pair of edges, while the other channel maintains a constant level, satisfying the requirement for fine-grained single-pulse output.
[0088] When the absolute value of the target pulse count equals the third threshold, the pulse repetition count is set to once, the timer reload value is equal to the total timer value, and both the first and second comparison values are set to non-flipping values to fully represent the zero output case. This setting ensures that no extra edges are introduced in this cycle, while maintaining the phase relationship consistent with the current pulse state.
[0089] When writing the first and second comparison values into the comparison registers corresponding to the first and second pulse signals, respectively, the shadow register is written first, and then submitted to the active register uniformly through an update event to avoid half-cycle contention when the count approaches the comparison critical point. The writing process includes value range verification, polarity consistency check, and mutual exclusion detection. Mutual exclusion detection is used to identify cases where the first and second comparison values are indistinguishably overlapping in the same counting interval. When overlap is detected, the offset is finely adjusted according to a priority strategy to maintain the order. After submission, the comparison output hardware triggers a level flip of the corresponding channel when the count value reaches its respective comparison point. The level flip follows a preset polarity to ensure that the flip direction matches the subsequent phase relationship.
[0090] The output behavior is set according to the direction of the target pulse count by adjusting the mapping between the comparison value and the channel. In a positive direction, the first pulse signal flips before the second pulse signal within the same interval, with the mapping strategy being that the first comparison value is written to the first comparison register and the second comparison value is written to the second comparison register. In a negative direction, the writing order is swapped, causing the second pulse signal to flip first within the same interval. Before submission, this mapping is checked for consistency with the current pulse state to avoid unnecessary flips due to mismatched starting levels. If an inconsistency is detected, the output latch level is corrected within a safety window before submitting the mapping, ensuring that the directional semantics accurately correspond to the physical flip sequence.
[0091] This embodiment dynamically sets the pulse repetition count, timer reload value, first comparison value, and second comparison value. It divides the multi-pulse output into equal-length intervals and plans two-way flipping within each interval using quartile comparison points. Simultaneously, it compensates for hardware and wiring lag with offsets and controls the leading order through direction mapping, enabling paired flipping, high single-pulse output, and zero output scenarios to be implemented collaboratively under the same mechanism. This mechanism reduces the tight coupling of timing maintenance to the CPU, lowers the probability of comparison event contention, and reduces phase jitter and counting errors. While maintaining a fixed execution cycle, it balances the accuracy of pulse count and the controllability of phase relationships, thereby achieving higher output consistency and reliable direction determination.
[0092] In one embodiment, step S50 above includes: S501, determine whether the direction of the target pulse quantity is positive or negative; S502, based on the current pulse state, the current pulse state is divided into a first type of current pulse state and a second type of current pulse state, wherein the first type of current pulse state corresponds to the first pulse signal and the second pulse signal having the same level, and the second type of current pulse state corresponds to the first pulse signal and the second pulse signal having different levels; S503, when the direction of the target pulse quantity is positive and the current pulse state is the first type of current pulse state, the first comparison value is written into the comparison register corresponding to the first pulse signal, and the second comparison value is written into the comparison register corresponding to the second pulse signal; S504, when the direction of the target pulse quantity is positive and the current pulse state is the second type of current pulse state, the second comparison value is written into the comparison register corresponding to the first pulse signal, and the first comparison value is written into the comparison register corresponding to the second pulse signal; S505, when the direction of the target pulse quantity is negative and the current pulse state is the first type of current pulse state, the second comparison value is written into the comparison register corresponding to the first pulse signal, and the first comparison value is written into the comparison register corresponding to the second pulse signal. S506, when the direction of the target pulse quantity is negative and the current pulse state is the second type of current pulse state, the first comparison value is written into the comparison register corresponding to the first pulse signal, and the second comparison value is written into the comparison register corresponding to the second pulse signal.
[0093] In this embodiment, the direction of the target pulse count is used to define the order of the two pulse edges. A positive direction indicates that the first pulse signal flips before the second pulse signal within a counting interval, while a negative direction indicates that the second pulse signal flips before the first pulse signal within a counting interval. The direction is derived from the analysis and sign determination of the target pulse count in the previous stage and is locked in a short, uninterrupted critical section before entering this stage to avoid direction jitter during the comparison register write process. Once the direction is determined, it participates in the mapping selection between the comparison value and the channel and persists throughout the submission cycle of an update event, ensuring a stable and consistent flipping order within the counting interval.
[0094] The current pulse state is a combination of the levels of the first and second pulse signals, used to indicate the starting level pair at the beginning of this counting interval. The current pulse state is jointly given by the state array index and the cached latch level. When the state array and the peripheral latch level are inconsistent, the peripheral latch level takes precedence and is written back to the state array to ensure consistency between the software and hardware views. Upon entering this stage, the current pulse state immediately triggers a classification calculation. Classification is based on whether the levels are the same; if the levels are the same, they are grouped into the first category of current pulse states; if the levels are different, they are grouped into the second category. This division converges into two mutually exclusive sets, facilitating conditional assignment in constant time and avoiding additional assumptions about the absolute high or low levels, thus ensuring compatibility with differences in polarity configurations.
[0095] The first and second comparison values are two reachable comparison points within the counting interval. Both have undergone amplitude boundary verification, shadow register write validity verification, and safety margin assessment through the upstream process and are in the shadow register pending submission state. The comparison register is a set of shadow registers and active registers corresponding to the channel. The shadow register is used to receive new comparison points, and the active register is atomically replaced when an update event arrives. To avoid half-cycle races caused by the count approaching the comparison point during writing, this step checks the count arrival window before writing. If it has entered the danger window, an update event is triggered first to submit the previous round of shadow values before starting the current round of writing.
[0096] Direction and classification jointly determine the mapping strategy. When the direction is positive and it is the current pulse state of type 1, the first comparison value is positioned as the comparison point of the first pulse signal, and the second comparison value is positioned as the comparison point of the second pulse signal. As a result, the first pulse signal flips first, and the second pulse signal flips later, and the two signals with the same starting level are naturally separated in phase within this interval. When the direction is positive and it is the current pulse state of type 2, the mapping is swapped. The second comparison value is written to the comparison register corresponding to the first pulse signal, and the first comparison value is written to the comparison register corresponding to the second pulse signal. As a result, the leading relationship of the positive direction is maintained while avoiding unnecessary flips at the beginning of the interval. When the direction is negative and it is the current pulse state of type 1, a mapping mirrored to the positive direction is used. The second comparison value is assigned to the first pulse signal, and the first comparison value is assigned to the second pulse signal. As a result, the second pulse signal leads within the interval. When the direction is negative and it is the second type of current pulse state, the first comparison value is assigned to the first pulse signal and the second comparison value is assigned to the second pulse signal. The result is that the negative leading relationship is maintained while maintaining phase continuity with the state with different initial levels.
[0097] The four branches described above perform conflict resolution before writing to the compare register. Conflict resolution checks whether two compare points are too close within the interval to be distinguishable due to output filtering or rising edge limitations. If a conflict occurs, the offset of the compare point is finely adjusted, moving it forward or backward by one smallest resolvable count unit within a safety margin, always maintaining the order and channel mapping unchanged. The write order adopts a strategy of low-to-high or concurrent writing of the same value to reduce the total write time under fast counting. After completion, a unified commit flag is immediately set, taking effect atomically in the next update event, avoiding phase tearing caused by one channel taking effect while another does not.
[0098] To ensure that the combination of direction and current pulse state does not introduce unnecessary flips at the beginning of the interval, this step performs a look-ahead simulation for the two upcoming comparison events after the write operation is completed. Based on the current pulse state and polarity preset, the level sequence after the flip is derived. If it is found that the first event has the same level as the start of the interval, resulting in an invalid flip, then within the safety margin, the comparison point is slightly shifted backward by one minimum resolvable counting unit, and the other comparison point is adjusted synchronously to ensure that both flips are valid and maintain the expected phase difference. All shifts are limited to not crossing the interval boundary. If the interval cannot accommodate the required safety margin, the process reverts to the upstream pulse repetition count planning, expands the counting interval upstream, and then performs mapping.
[0099] To coordinate with peripheral polarity and output idle level, a one-time polarity check is performed upon first transition from idle to operating state. If the current pulse state and peripheral output polarity combination would cause an undesirable premature flip before the first comparison value arrives, a polarity latch is written to maintain the initial level before mapping is committed, and then released upon the arrival of the first event to ensure phase start consistency. This check is triggered only during the transition from idle to operating state and is not repeated in consecutive operating states to avoid introducing additional delays.
[0100] This embodiment uses a joint mapping between direction and current pulse state to accurately assign the first and second comparison values to the comparison registers of the first and second pulse signals from four combinations. Atomic activation is achieved using shadow registers and update events. Furthermore, conflict resolution and look-ahead simulation correction ensure minimum safe intervals and effective flips, resulting in a stable lead and lag relationship in each counting interval. This mapping avoids extra edges caused by inconsistent start levels, reduces the probability of phase tearing and invalid flips, and guarantees that direction semantics and phase difference are implemented as expected under a fixed execution period, thereby improving the timing consistency and direction determination reliability of the two pulses.
[0101] In one embodiment, step S60 above includes: S601, The number of pulse repetitions is written into the repetition count register of the timer to limit the number of repetitions of the timer; S602, The timer reload value is written to the autoload register for automatic reloading of the initial count value after each count overflow; S603, after writing is completed, trigger the register synchronization signal so that the repeat count register of the timer and the autoload register take effect in the next counting cycle; S604, when the number of pulse repetitions exceeds a preset threshold, a dynamic register refresh operation is performed, and the timer repetition value in the autoload register is rewritten each time the count overflows; S605, when the number of pulse repetitions is equal to a preset threshold, the timer repetition value in the autoload register remains unchanged to maintain a stable output of the timing cycle.
[0102] In this embodiment, "writing the pulse repetition count to the timer's repetition count register" is used to limit the number of repetitions within a single submission cycle. The pulse repetition count originates from the upstream planning result of the absolute value of the target pulse quantity, and range verification and saturation pruning have been completed before entering this stage. In actual implementation, a write image is first generated in the shadow buffer. The image structure includes the target value, parity bit, and timestamp. Then, during the counting window check phase, it is determined whether the interval between the current count value and the next comparison event is less than the safety margin. If it is in a dangerous window, an update event is triggered first to make the previous round of shadow value atomically effective, and then the current image is written, avoiding half-cycle contention when the count approaches the threshold. The write is always completed through a bus atomic transaction, and a write success flag is carried in the return code. If it fails, it rolls back to the previous stable image and records a soft fault.
[0103] "Writing the timer reload value to the autoload register" is used to automatically reload the initial count value after overflow, thus defining a stable counting range. There is a one-to-one correspondence between the timer reload value and the fixed execution period; the value generation already takes into account clock source division and peripheral timing resolution. The implementation path is to first write to the shadow register of the autoload register, and then commit within the safe window. If dynamic divider switching is enabled, a cross-check is performed before committing to ensure that the reload value matches the current division configuration; if they do not match, the division is switched before committing to prevent actual period drift. To suppress short-term delays caused by bus jitter, a low-to-high word order strategy is used for writing, shortening the key byte lifetime.
[0104] "After the write operation is complete, the register synchronization signal is triggered, causing the timer's repetition count register and auto-reload register to take effect in the next counting cycle," ensuring that parameters switch simultaneously and eliminating phase tearing where one channel's parameters have taken effect while another channel still holds the old value. The register synchronization signal is driven by an update event, and the commit action includes three sub-operations: clearing the pending commit flag, setting the synchronization trigger bit, and read-back verification after writing. These three operations are completed consecutively within the uninterruptible region. If the hardware supports master-slave synchronization, a time base will also be broadcast once before triggering to ensure that multiple timers take effect at the same boundary, suitable for multi-axis output or cross-clock domain collaborative scenarios.
[0105] "When the number of pulse repetitions exceeds a preset threshold, a dynamic register refresh operation is performed, rewriting the timer repetition value in the auto-load register each time the count overflows." This addresses clock accumulation error and temperature drift compensation during long-sequence output. The preset threshold is generated through offline calibration or online self-test to determine whether to enter long-sequence mode. Once entered, a fine-tuning amount is generated based on the difference between the actual output feedback and the reference period in each overflow interrupt or event callback. The fine-tuned repetition value is written back to the shadow register and takes effect with the next update event. To avoid jitter introduced by adjustment, the fine-tuning amount uses a first-order correction with integral limiting. A single correction does not cross the smallest resolvable counting unit and is linked to the comparison value safety interval to ensure that it is not compressed to an area below the edge resolution. If the hardware has DMA capability, the repetition value sequence can be pre-arranged into a circular buffer, and the overflow event triggers DMA to refresh item by item, further reducing CPU usage.
[0106] "When the number of pulse repetitions equals a preset threshold, the timer repetition value in the auto-load register remains unchanged to maintain stable output during the timing period," covering short sequences or boundary conditions. In implementation, the dynamic refresh channel is disabled, only the synchronous submission of update events is retained, ensuring the repetition value remains constant throughout the entire sequence period. Simultaneously, one-time bias cancellation is enabled to eliminate the residual phase error of the first cycle through a slight offset of the comparison value, avoiding over-adjustment in short sequences. If the previous stage was in dynamic refresh mode, switching to hold mode will first write back the baseline repetition value and wait for a complete update event before outputting, preventing overlap of different strategies.
[0107] To ensure determinism in high-frequency output scenarios, the entire process is executed with two levels of debouncing and two levels of fault tolerance. The first level of debouncing addresses input parameter variations, employing a shortest lifespan constraint to prohibit multiple changes to the repetition count and reload value within a single counting interval. The second level of debouncing addresses hardware writes, requiring the interval between two consecutive writes to be greater than the safety window width. The first level of fault tolerance rolls back to the previous shadow image and increments the count when write verification fails. The second level of fault tolerance triggers a soft reset path when the number of consecutive failures exceeds a threshold. The soft reset includes stopping the count, writing back the baseline reload value and repetition count, re-triggering the register synchronization signal, and re-entering the working state to prevent the output from entering an invalid phase. All state changes are recorded in the log channel to support subsequent state recovery and offline analysis.
[0108] This embodiment uses a simultaneous operation of the repetition count register and the autoload register via shadow write and update events to avoid phase tearing caused by parameter interleaving. When triggered by a long sequence of conditions, dynamic register refresh performs minor corrections at the overflow boundary, forming a closed-loop suppression of period errors caused by clock drift and temperature. When triggered by a short sequence of conditions, the repetition load value is kept constant to reduce regulation noise. Thus, a stable counting interval and consistent phase relationship are obtained within a fixed execution cycle framework, while reducing CPU intervention and bus contention, and improving the timing consistency of pulse output and the reliability of direction determination.
[0109] In one embodiment, step S70 above includes: S701, read the counting direction, comparison mode, and output polarity parameters from the configuration register of the timer; S702, reset the timer counter to the initial count value, and set the initial count period according to the timer reload value in the autoload register; S703, write the start instruction bit to the control register of the timer to start the timer's counting logic; S704, based on the first comparison value and the second comparison value, controls the output behavior through the timer comparison output function, so that the first pulse signal and the second pulse signal are flipped sequentially according to the phase relationship; S705, during the output process, maintains synchronization between the counting period and the output period through the timer update event to achieve stable output of the first pulse signal and the second pulse signal.
[0110] In this embodiment, the process of reading the counting direction, comparison mode, and output polarity parameters from the timer's configuration register begins with register consistency verification. First, a snapshot of the configuration register is read in the bus idle window to obtain the current values of the counting direction, comparison mode, and output polarity parameters. Then, the snapshot is compared with the previous round of shadow buffer. If an unexpected difference is found, a read-back kernel is triggered to eliminate transient bus jitter. The counting direction determines the timer counter's increment or decrement path, affecting the order in which comparison events are triggered. The comparison mode defines the mapping from comparison events to pin behavior, determining whether the first and second pulse signals will perform a toggle, set, or clear action when a comparison hits. The output polarity parameter determines the pin's idle level direction, serving as a reference for unifying phase relationships. After verifying all three, the valid values are written to the shadow buffer and timestamped for subsequent compatibility checks with the first and second comparison values. For example, when the comparison mode is toggle, the first and second comparison values must fall within the valid counting range and maintain a safe interval between them.
[0111] The process of resetting the timer counter to its initial count value and setting the initial counting period based on the timer reload value in the autoload register emphasizes boundary safety. First, update requests to the compare output channel are paused to prevent unexpected edges from being triggered at the moment of reset. Then, the timer counter is written to its initial count value, which is matched to the counting direction: zero is selected for the increment direction, and the timer reload value is selected for the decrement direction, ensuring the first compare event is aligned with the expected phase. Next, the existing timer reload value in the autoload register is read, and the counting period is calculated by combining clock division and gating status. The result is written to the running state description block to constrain the relative positions of the first and second compare values. If it is detected that the autoload register has not yet been synchronized to the latest setpoint, an update event is triggered first to complete the loading, and then the counter is reset to avoid initial period offset.
[0112] Write the start command bit to the timer's control register to initiate the timer's counting logic, following the write-after-read principle. Before setting the start command bit in the control register, confirm that the comparison output buffer has loaded valid first and second comparison values, and confirm that the counting direction, comparison mode, and output polarity parameters in the configuration register have passed the aforementioned consistency checks. Then, enter the uninterruptible window, atomically write the start command bit, and immediately read back the control register to verify that the start command bit has actually taken effect. At the same time, pull the current counter value once to confirm that the counting logic has progressed in the counting direction, thus completing the observable closed loop of the start.
[0113] Based on the first and second comparison values, the output behavior is controlled by a timer comparison output function, ensuring that the first and second pulse signals are sequentially flipped according to their phase relationship, relying on a double comparison hit sequence. The first and second comparison values are mapped to the buffer registers of two comparison channels respectively. When the comparison mode is flipped and the output polarity parameter is consistent with the target level definition, a count value hitting the first comparison value triggers the edge of the first pulse signal, and a count value hitting the second comparison value triggers the edge of the second pulse signal. To ensure a stable phase relationship, a shadow mechanism is used for comparison value writing, with updates uniformly transported to the active register to avoid phase tearing caused by one channel parameter taking effect first. If the counting direction is decreasing, the first and second comparison values are normalized before transport to ensure that the physical order of the edges on the time axis is consistent with the phase relationship setting. During operation, the comparison overflow flag and event timestamp are monitored. If event congestion or abnormal sorting is detected, the interval between the two values is increased to above the safe minimum interval in the next counting cycle.
[0114] During the output process, the counting cycle and output cycle are synchronized through timer update events to maintain stable output of the first and second pulse signals, relying on event-driven parameter validity boundaries. Each update event plays three roles simultaneously: pushing the timer reload value in the autoload register to be reloaded at the overflow boundary; pushing the first and second comparison values in the comparison buffer to be consistent at the boundary; and pushing the shadow configuration associated with the counting direction, comparison mode, and output polarity parameters to switch at the same boundary. In this way, in any single counting cycle, the counting cycle and output cycle maintain a one-to-one correspondence, and the phase relationship between the first and second pulse signals will not drift across cycles. If the hardware supports master-slave linkage, a synchronization pulse can be distributed to the slave timer when the master timer update event occurs, thereby establishing a unified boundary between multiple outputs and ensuring that the phase relationship remains consistent across all channels in a multi-axis scenario. To reduce hardware and software race conditions, all shadow writes are performed only within a safe window before the update event. The width of the safe window is calculated by the count value and the distance between the most recent comparison hits, ensuring that the write does not compress into the comparison boundary.
[0115] In addition, starting the timer to output the first and second pulse signals includes performing the following steps via a timer interrupt service routine: When a timer count overflows or a comparison match event triggers an interrupt, the interrupt service routine is entered. In the interrupt service routine, the accumulated pulse count is updated based on the actual number of pulses output; Calculate the current pulse state based on the accumulated pulse count; Branch processing is based on the absolute value of the target pulse count, dynamically setting the pulse repetition count, timer reload value, first comparison value, and second comparison value; Configure the timer's repeat count register and auto-reload register; Before returning from the interrupt, the above parameters and registers are updated, and the timer counting logic is kept enabled so that the updated first comparison value and second comparison value take effect in subsequent counting cycles to continuously drive the output of the first pulse signal and the second pulse signal.
[0116] This embodiment avoids phase misalignment caused by mismatch between the counting direction, comparison mode, and output polarity parameters and the actual comparison value by configuring register read and consistency verification; the combination of counter reset and autoload register sets the initial counting period, eliminating first-cycle drift; the atomic commit and readback confirmation of the start instruction bit establish an observable start loop; the first comparison value and the second comparison value are shadow-transferred and direction-normalized to ensure that the two edges flip sequentially according to the predetermined phase relationship; the unified effective boundary of the update event binds the counting period and the output period, maintaining stable output and phase consistency during operation, while obtaining scalable synchronization capability in multi-channel collaboration.
[0117] In one embodiment, a pulse generation device based on timer comparison output is provided, which corresponds one-to-one with the pulse generation method based on timer comparison output in the above embodiments. (Refer to...) Figure 3 , Figure 3 This is a schematic diagram of the functional modules of a preferred embodiment of the pulse generation device based on timer comparison output of the present invention. The modules include a fixed period initialization module 10, a pulse quantity parsing module 20, a pulse state acquisition module 30, a parameter dynamic configuration module 40, a comparison register setting module 50, a register loading module 60, a timer start module 70, and a pulse state update module 80. Detailed descriptions of each functional module are as follows: Fixed period initialization module 10 is used to initialize a fixed execution period, wherein the fixed execution period corresponds to the total value of the timer; Pulse count analysis module 20 is used to determine the target number of pulses within the fixed execution cycle; The pulse state acquisition module 30 is used to acquire the current pulse state at the beginning of the fixed execution cycle, wherein the current pulse state is a combination of the levels of the first pulse signal and the second pulse signal; The parameter dynamic configuration module 40 is used to dynamically set the pulse repetition count, timer repetition load value, first comparison value and second comparison value based on the absolute value of the target pulse count, so as to control the output behavior of the first pulse signal and the second pulse signal. The comparison register setting module 50 is used to set the comparison registers corresponding to the first pulse signal and the second pulse signal according to the direction of the target pulse number and the current pulse state; Register loading module 60 is used to set the repeat count register and auto-load register of the timer; The timer start module 70 is used to start the timer to output the first pulse signal and the second pulse signal; The pulse state update module 80 is used to update the current pulse state based on the actual number of pulses output.
[0118] In one embodiment, a computer device is provided, which may be a server, and its internal structure diagram may be as follows: Figure 4 As shown, the computer device includes a processor, memory, network interface, and database connected via a system bus. The processor provides computing and control capabilities. The memory includes non-volatile and / or volatile storage media and internal memory. The non-volatile storage media stores the operating system, computer programs, and database. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with external clients via a network connection. When executed by the processor, the computer program implements the functions or steps of a pulse generation method based on timer comparison output on the server side.
[0119] In one embodiment, a computer device is provided, which may be a client, and its internal structure diagram may be as follows: Figure 5 As shown, the computer device includes a processor, memory, network interface, display screen, and input devices connected via a system bus. The processor provides computational and control capabilities. The memory includes non-volatile storage media and internal memory. The non-volatile storage media stores the operating system and computer programs. The internal memory provides an environment for the operation of the operating system and computer programs stored in the non-volatile storage media. The network interface is used to communicate with an external server via a network connection. When executed by the processor, the computer program implements client-side functions or steps of a pulse generation method based on timer comparison output.
Claims
1. A pulse generation method based on timer comparison output, characterized in that, Includes the following steps: Initialize a fixed execution cycle, where the fixed execution cycle corresponds to the total value of the timer; Determine the target number of pulses within the fixed execution cycle; At the start of the fixed execution cycle, the current pulse state is obtained, which is a combination of the levels of the first pulse signal and the second pulse signal; Based on the absolute value of the target pulse count, the pulse repetition count, the timer reload value, and the first comparison value and the second comparison value are dynamically set to control the output behavior of the first pulse signal and the second pulse signal. Based on the direction of the target pulse quantity and the current pulse state, set the comparison registers corresponding to the first pulse signal and the second pulse signal; Configure the repeat count register and auto-reload register of the timer; Start the timer to output the first pulse signal and the second pulse signal; The current pulse state is updated based on the actual number of pulses output.
2. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, Determining the target number of pulses within the fixed execution cycle includes: Receive pulse output command data packets from the control terminal, verify the integrity and correctness of the pulse output command data packets, and obtain the verification result; Based on the verification result, the pulse output command data packet is parsed to obtain the target pulse count; Determine the direction sign of the target pulse quantity; Check whether the number of target pulses is zero or an abnormal value, and obtain the check result; The target pulse count is dynamically adjusted based on the current system load and the inspection results to obtain the adjusted target pulse count. The adjusted target pulse count is obtained by fusing the multi-source instruction priority; Store the final target pulse count in a non-volatile memory, update the target pulse count cache, and send an acknowledgment signal based on the storage result.
3. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, At the start of the fixed execution cycle, the current pulse state is acquired. The current pulse state is a combination of the levels of the first pulse signal and the second pulse signal, including: At the start of the fixed execution cycle, the state array index is calculated based on the system's cumulative pulse count; The current pulse state value is obtained by using the state array index and the predefined state array; Verify whether the current pulse state value is valid; The timer compares the output function and applies a valid current pulse state value to the first and second pulse signals to output the corresponding level combination.
4. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, Based on the absolute value of the target pulse count, the pulse repetition count, the timer repetition load value, and the first and second comparison values are dynamically set to control the output behavior of the first and second pulse signals, including: Determine the absolute value of the target pulse count; When the absolute value of the target pulse count is greater than or equal to the first threshold, the pulse repetition count is calculated as the integer part of the absolute value of the target pulse count divided by two, the timer reload value is calculated as the total value of the timer divided by the pulse repetition count, and the first comparison value and the second comparison value are determined. The first comparison value is the timer reload value divided by four minus the offset, and the second comparison value is the timer reload value multiplied by three-quarters minus the offset. When the absolute value of the target pulse count is equal to the second threshold, the pulse repetition count is set to one, the timer reload value is set to the total timer value, the first comparison value is set to the timer reload value divided by two, and the second comparison value is set to the non-flip value. When the absolute value of the target pulse count is equal to the third threshold, the pulse repetition count is set to one, the timer reload value is set to the timer total value, and the first comparison value and the second comparison value are set to the non-flip value. Write the first comparison value and the second comparison value into the comparison registers corresponding to the first pulse signal and the second pulse signal, respectively, so that when the timer count value reaches the first comparison value and the second comparison value, the level of the corresponding pulse signal is triggered to flip. The output behavior is set according to the direction of the target pulse number. When the direction of the target pulse number is positive, the first pulse signal flips relative to the second pulse signal in a leading order. When the direction of the target pulse number is negative, the second pulse signal flips relative to the first pulse signal in a leading order.
5. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, Based on the direction of the target pulse quantity and the current pulse state, the comparison registers corresponding to the first pulse signal and the second pulse signal are set, including: The direction of the target pulse quantity is determined to be either positive or negative. Based on the current pulse state, the current pulse state is divided into a first type of current pulse state and a second type of current pulse state, wherein the first type of current pulse state corresponds to the first pulse signal and the second pulse signal having the same level, and the second type of current pulse state corresponds to the first pulse signal and the second pulse signal having different levels; When the direction of the target pulse quantity is positive and the current pulse state is the first type of current pulse state, the first comparison value is written into the comparison register corresponding to the first pulse signal, and the second comparison value is written into the comparison register corresponding to the second pulse signal. When the direction of the target pulse quantity is positive and the current pulse state is the second type of current pulse state, the second comparison value is written into the comparison register corresponding to the first pulse signal, and the first comparison value is written into the comparison register corresponding to the second pulse signal. When the direction of the target pulse quantity is negative and the current pulse state is the first type of current pulse state, the second comparison value is written into the comparison register corresponding to the first pulse signal, and the first comparison value is written into the comparison register corresponding to the second pulse signal. When the direction of the target pulse quantity is negative and the current pulse state is the second type of current pulse state, the first comparison value is written into the comparison register corresponding to the first pulse signal, and the second comparison value is written into the comparison register corresponding to the second pulse signal.
6. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, Setting the repeat count register and auto-reload register of the timer includes: The number of pulse repetitions is written into the repetition count register of the timer to limit the number of repetitions counted by the timer; The timer reload value is written to the autoload register to automatically reload the initial count value after each count overflow. After the write operation is completed, a register synchronization signal is triggered, which makes the repeat count register of the timer and the autoload register effective in the next counting cycle; When the number of pulse repetitions exceeds a preset threshold, a dynamic register refresh operation is performed, and the timer repetition value in the autoload register is rewritten each time the count overflows. When the number of pulse repetitions equals a preset threshold, the timer repetition value in the autoload register remains unchanged to maintain a stable output of the timing cycle.
7. The pulse generation method based on timer comparison output as described in claim 1, characterized in that, Starting the timer to output the first pulse signal and the second pulse signal includes: Read the counting direction, comparison mode, and output polarity parameters from the timer's configuration register; Reset the timer counter to its initial count value and set the initial count period according to the timer reload value in the autoload register; Write a start instruction bit into the control register of the timer to start the timer's counting logic; Based on the first comparison value and the second comparison value, the output behavior is controlled by the timer comparison output function, so that the first pulse signal and the second pulse signal are flipped sequentially according to the phase relationship. During the output process, the counting period is kept synchronized with the output period through the timer update event to achieve stable output of the first pulse signal and the second pulse signal.
8. A pulse generation device based on timer comparison output, characterized in that, The pulse generation device based on timer comparison output includes: A fixed-cycle initialization module is used to initialize a fixed execution cycle, wherein the fixed execution cycle corresponds to the total value of the timer; The pulse count analysis module is used to determine the target pulse count within the fixed execution cycle; The pulse state acquisition module is used to acquire the current pulse state at the beginning of the fixed execution cycle, wherein the current pulse state is a combination of the levels of the first pulse signal and the second pulse signal; The parameter dynamic configuration module is used to dynamically set the pulse repetition count, timer repetition load value, first comparison value and second comparison value based on the absolute value of the target pulse count, so as to control the output behavior of the first pulse signal and the second pulse signal; The comparison register setting module is used to set the comparison registers corresponding to the first pulse signal and the second pulse signal according to the direction of the target pulse number and the current pulse state; A register loading module is used to set the repeat count register and the auto-load register of the timer; A timer startup module is used to start the timer to output the first pulse signal and the second pulse signal; The pulse state update module is used to update the current pulse state based on the actual number of pulses output.
9. A computer device, characterized in that, The computer device includes a memory, a processor, and a pulse generation program based on timer comparison output stored in the memory and executable on the processor. When executed by the processor, the pulse generation program based on timer comparison output implements the steps of the pulse generation method based on timer comparison output as described in any one of claims 1-7.
10. A computer-readable storage medium, characterized in that, The storage medium stores a pulse generation program based on timer comparison output, which, when executed by a processor, implements the steps of the pulse generation method based on timer comparison output as described in any one of claims 1-7.