Embedded Microcontroller Software Algorithms

Category 1: Basic Data Processing and Algorithms

This type of algorithm is fundamental to programming, but in microcontrollers, special attention must be paid to efficiency and resource usage.

  1. Lookup Method

  • Trigonometric Functions: For example, calculating sin/cos values when displaying waveforms.

  • Non-linear Calibration: Such as temperature compensation for thermocouples and non-linear correction for sensors.

  • Encoding and Decoding: For example, converting between Gray code and binary code.

  • Description: Pre-calculate function results or mapping relationships and store them in program memory (Flash) to form an array (table). When needed, directly look up using an index, trading space for time.

  • Advantages: Extremely fast execution speed and high determinism.

  • Disadvantages: Occupies storage space; for tables with high precision and large ranges, space consumption is significant.

  • Applications:

  • Circular Queue/Circular Buffer

    • Serial Communication: Stores received data streams for the main program to parse.

    • Data Acquisition: Temporarily stores data blocks obtained from ADC sampling.

    • Description: A first-in-first-out (FIFO) data structure managed by head and tail pointers, which automatically wraps back to the beginning when the pointer reaches the end of the buffer.

    • Advantages: Efficiently processes data streams, avoids frequent memory movements, and balances the speed differences between producers and consumers.

    • Applications:

  • Digital Filtering Algorithms

    • Purpose: To extract valid signals from raw data containing noise.

    • Clipping Filter: Set a maximum allowable deviation based on experience; if the difference between the current sample value and the last valid value exceeds this deviation, it is considered interference and discarded.

    • Median Filter: Continuously sample N times (N is odd), sort these N values, and take the middle value as the current valid value. It is very effective against pulse interference.

    • Arithmetic Mean Filter: Continuously take N sample values for arithmetic averaging. Suitable for smoothing general random interference signals.

    • Moving Average Filter: Maintain a queue of length N, place the new sampled value into the queue, discard the oldest value, and then calculate the average of all values in the queue. Saves memory and has good real-time performance.

    • First-order Lag Filter (Low-pass Filter): <span>Y(n) = α * X(n) + (1-α) * Y(n-1)</span>, where α is the filter coefficient. The algorithm is simple and can effectively suppress periodic interference with phase lag.

  • Sorting and Searching

    • Description: Microcontrollers typically handle small-scale data, so simplicity and stability are prioritized.

    • Sorting: Bubble Sort and Selection Sort are commonly used due to their simplicity. For larger data sets, Quick Sort may be used.

    • Searching: Sequential Search (simple) and Binary Search (efficient, but requires sorted data).

    Category 2: Control System Algorithms

    This is the core of microcontrollers in automation.

    1. PID Control Algorithm

    • Description: A combination of Proportional (P), Integral (I), and Derivative (D) control, it is the most widely used and practical control algorithm.

    • Position PID: Directly calculates the absolute size of the control quantity.<span>u(k) = Kp * e(k) + Ki * Σe(j) + Kd * [e(k) - e(k-1)]</span>

    • Incremental PID: Calculates the increment of the control quantity (the difference between this and the last value).<span>Δu(k) = Kp * [e(k) - e(k-1)] + Ki * e(k) + Kd * [e(k) - 2e(k-1) + e(k-2)]</span>. Incremental PID is more commonly used because it requires less computation and does not suffer from integral windup, making the system safer.

    • Applications: DC motor speed control, temperature control, balancing vehicles, drone attitude control, etc.

  • Finite State Machine

    • Button Detection: Recognizes single clicks, double clicks, and long presses.

    • Communication Protocol Parsing: For example, parsing Modbus and custom serial protocol packets.

    • System Mode Management: For example, switching between standby, operation, calibration, error, and other modes.

    • Description: Decomposes complex workflows into a finite number of “states” and defines the “conditions” and “actions” for transitions between states.

    • Advantages: Clear logic, easy to design and maintain, especially suitable for handling non-sequential processes.

    • Implementation Methods: <span>switch-case</span> statements or function pointer arrays.

    • Applications:

    Category 3: Signal Processing and Advanced Algorithms

    When the performance of the microcontroller is strong (e.g., Cortex-M4/M7 cores), more complex algorithms can be run.

    1. Fast Fourier Transform

    • Description: Converts time-domain signals to frequency-domain, analyzing the frequency components of the signal.

    • Note: Requires significant computation, typically using official DSP libraries or optimized FFT functions.

    • Applications: Audio spectrum analysis, vibration monitoring, power harmonic analysis.

  • RMS Value Calculation

    • Description: Used to calculate the effective value of AC signals.<span>RMS = sqrt( (1/N) * Σ(x(i)^2) )</span>.

    • Applications: Measuring the true effective value of AC voltage and current.

    Category 4: System Management and Software Engineering Algorithms

    This type of algorithm ensures that the software itself is stable, reliable, and efficient.

    1. Watchdog

    • Description: A hardware timer that software must “feed” (reset the timer) before it overflows. If the program runs away and cannot feed the watchdog in time, the watchdog will forcibly reset the entire system.

    • Applications: In all products requiring high reliability, to prevent program crashes.

  • Software Timer

    • Description: Implements multiple independent, non-blocking “soft” timers based on hardware timer interrupts. The main loop checks timer flags to execute timed tasks.

    • Advantages: Avoids CPU idling caused by using the <span>delay()</span> function, improving system response efficiency.

    • Applications: Implementing LED blinking, button scanning, data timed uploads, and other tasks that require timing but cannot block the main loop.

  • CRC Check

    • Description: An algorithm that calculates a small checksum based on the data packet. The receiver uses the same algorithm to calculate; if the results differ, it indicates that an error occurred during transmission.

    • Advantages: Extremely strong error detection capability.

    • Applications: Flash read/write integrity checks, communication data packet checks (e.g., Modbus CRC-16).

  • Memory Management

    • Simple Memory Pool: Pre-allocate a block of contiguous memory for fixed-size data structures (e.g., communication data packets). Allocation and deallocation only move pointers, making it efficient and free of fragmentation.

    • Applications: In scenarios requiring dynamic creation/destruction of fixed-size objects.

    Summary and Selection Recommendations

    Algorithm Category

    Core Idea

    Key Considerations

    Basic Data Processing

    Efficiently and stably process data

    Trade-off between time and space, real-time performance

    Control Systems

    Make precise decisions based on feedback

    Stability, response speed, anti-interference

    Signal Processing

    Analyze and extract signal features

    Computational power, precision requirements

    System Management

    Ensure long-term stable operation of the system

    Reliability, resource management, maintainability

    When selecting algorithms for microcontrollers, it is essential to remember theirlimited resources characteristics:

    • ROM (Flash) Space: How large is the algorithm code?

    • RAM Space: How much memory does the algorithm require to run? Will it fragment?

    • CPU Clock Frequency: Does the algorithm execution time meet real-time requirements?

    • Interrupt Response: Will the algorithm disable interrupts for a long time?

    A general principle is: choose the simplest, most resource-efficient, and most deterministic algorithm that meets functionality and requirements. For example, use the lookup method instead of complex formula calculations, and use integer operations instead of floating-point operations when possible.

    Leave a Comment