Practical Microcontroller Programming Experience Summary

Practical Microcontroller Programming Experience Summary

Experience 1: Use “Software Trap + Program ID” to Deal with PC Pointer Fluctuations

When the CPU is disturbed by external factors, sometimes the PC pointer may jump to another segment of the program or to a blank segment. In fact, if the PC pointer jumps to a blank segment, it can be handled easily. Just set up a software trap (intercept instruction) in the blank segment to redirect the program to the initialization segment or error handling segment. However, what if the PC pointer jumps to another segment of the program? Here, I recommend a method—program ID, with the following ideas:

1. First, the program must be modular. Each module (subroutine) performs a single function. Each module has only one exit (RET).

2. Set up a module (subroutine) ID register.

3. Assign a unique ID number to each subroutine.

4. Before returning (RET) from a subroutine, send the ID number of the current subroutine to the ID register.

5. After returning to the upper-level program, first check the ID number in the ID register.

If it is correct, continue execution; if incorrect, it indicates that the PC pointer may have jumped incorrectly, and the subroutine did not return as expected. At this point, intercept the program to the initialization segment or error handling segment.

This method is like setting up several sentinels in the program; every time a subroutine returns, it must verify the ID number before being released. When combined with software traps, it can detect most occurrences of PC pointer fluctuations. When reaching the error handling segment, whether to cold start or warm start is up to you.

To reveal the essence of program runaway with a line of code! 750102H; MOV 01H, #02H, if the current PC is not pointing to 75H, but to 01H or 02H, then the instruction decoder in the 51 will faithfully translate them into AJMP X01H or LJMP XXXXH, and what are XX01H and XXXXH? God knows! If this runaway continues, you are doomed! Reform it:

CLR A; 0C4H

INC A; 04H

MOV R1, A; 0F9H

INC A; 04H

MOV @R1, A; 86H

Each byte of code must not generate jumps and loops, and all are single-byte instructions! Where to run? If it runs out, it must come back! “Home” is good for a thousand days! “Jumping out” is always difficult! As long as you are accustomed to using accumulators and registers to flip the numbers and eliminate those dangerous codes, although it adds two bytes of “package” to the “foot” of the PC, it is not easy to “run”! “Foot package” === run! Some friends may ask: What if the PC grabs 02H–LJMP and then grabs a far XXH, and then grabs the neighboring YYH? Only someone like ZENYIN would ask such a question! Who is the most active at PC? PC0! If there is a “twist”, it obviously happens to her, while PC15 is sleeping like a dead pig, even a strong disturbance cannot wake her up? Moreover, if the disturbance is so strong that even the high-level PC is affected! Shut down! Shut down! We are done! “It’s not that we can’t, but the enemy is too strong”! Conversely, if the enemy occasionally comes out to make trouble under your dictatorship, but when they do, they rush to the high level of PC, you need to ask if there is a problem with the foundation of your kingdom (hardware), rather than in the ideology (software)! Hardware is fundamental! Software is secondary! Treating both the symptoms and the root causes creates a strong body that can resist all poisons!

Experience 2: Do Not Trust Software Dogs

There is much discussion about software dogs in forums. I have also read many articles about software dogs. Some experts have indeed proposed some skillful methods. However, my advice is: do not trust software dogs! In fact, software dogs are a form of self-discipline for software. The general idea is to set up a counter, incrementing it during a timing interrupt, and resetting it at appropriate places in the main program. If the program goes out of control, the reset command may not be executed, but the interrupt occurs regularly, leading to counter overflow (the dog barks). However, there is a problem: if interference causes the interrupt to be masked, the software dog will never bark! — To address this possibility, some people propose to refresh the interrupt enable flag repeatedly in the main program to ensure that the interrupt is not masked. — But if the program jumps into a dead loop and no longer executes the “refresh interrupt enable flag” function, the dog may starve to death.

Therefore, my view is: the watchdog must have an independent counter (i.e., hardware watchdog). Fortunately, many chips now provide internal WDTs. These dogs come with their own counters. Even if interference causes the program to go out of control, WDT will still count until it overflows. Of course, I do not mean to completely dismiss software dogs. After all, whether soft dogs or hard dogs, catching mice is good dog behavior (Is the dog catching mice—meddling?). If any dog training expert has indeed raised a good software dog, please bring it out for everyone to see.

Experience 3: Discussing RAM Redundancy Technology

RAM redundancy refers to:

1. Backing up important data in 2 (or more) copies and storing them in different areas of RAM (i.e., non-contiguous addresses).

2. When modifying these data regularly, also update the backups.

3. When interference occurs and is intercepted into the “program error handling segment”, compare the data with the backups and use a voting method (the minority obeys the majority) to select the correct (or possibly correct?) one.

4. The more backups, the better the effect. (Of course, you need enough storage space).

5. Only back up the most original data. Intermediate variables (i.e., those that can be derived from the original data) do not need to be backed up.

Note: 1. The theoretical basis for this idea is said to come from a “probability theory”; that is, the probability of a person being beaten by his wife is very high, but if he covers his face to go to work and finds that every married man’s face in the company is bruised, this probability is very low. Similarly, the probability of a RAM register’s data being corrupted is very high, but the probability of multiple non-contiguous RAMs being corrupted simultaneously is very low.

2. A couple of years ago, when I was an apprentice, I used this method once, but the effect was not ideal. At that time, I felt that perhaps the probability theory had failed me? Now looking back, it may have been that the timing of the backup was poorly chosen. As a result, I backed up already corrupted data. Thus, the recovered data was naturally incorrect.

Experience 4: Discussing Instruction Redundancy Technology

A friend asked about instruction redundancy. According to my understanding, instruction redundancy means action redundancy. For example, if you want to output a high level to a certain output port to drive an external device, if you only send “1” once, then when interference arrives, this “1” may turn into “0”. The correct way to handle this is to periodically refresh this “1”. Thus, even if it is accidentally disturbed, it can recover. In addition to I/O action redundancy, I strongly recommend that everyone adopt this method in the following areas:

1. LCD display. Sometimes, you may use some dedicated driver chips for LCDs (like HT1621). The advantage of such chips is that once you send the display data to them, they will continuously scan the LCD automatically. However, do not think that this means you have nothing to do. The correct way to handle it is to remember to periodically refresh the display data (even if the displayed content has not changed). For CPUs with built-in LCD DRIVER, also periodically refresh the LCD RAM.

2. Setting the interrupt enable flag. Do not think that you are done once you set the interrupt in the program initialization segment. You should periodically refresh it at appropriate places in the main program to avoid having your interrupt suspended.

3. Other flags and parameter registers (including your own defined ones) should also be refreshed regularly.

4. Other areas you deem necessary to refresh frequently.

Experience 5: 10 Software Filtering Methods

Here are 10 software filtering methods compiled from the depths of my heart:

1. Clipping Filtering Method (also known as Program Judgment Filtering Method)

A. Method: Based on experience, determine the maximum allowable deviation between two samples (set as A). Each time a new value is detected, judge: if the difference between the current value and the previous value <= A, then the current value is valid. If the difference > A, then the current value is invalid, discard it, and use the previous value instead.

B. Advantages: Effectively overcomes pulse interference caused by random factors.

C. Disadvantages: Cannot suppress periodic interference, poor smoothness.

2. Median Filtering Method

A. Method: Continuously sample N times (N is an odd number), arrange the N sampled values in order, and take the middle value as the effective value.

B. Advantages: Effectively overcomes fluctuations caused by random factors, has good filtering effects on slowly changing parameters like temperature and liquid levels.

C. Disadvantages: Not suitable for rapidly changing parameters like flow and speed.

3. Arithmetic Mean Filtering Method

A. Method: Continuously take N sampled values for arithmetic mean calculation. When N is large: the signal smoothness is high, but sensitivity is low; when N is small: the signal smoothness is low, but sensitivity is high. Selection of N: generally for flow, N=12; for pressure, N=4.

B. Advantages: Suitable for filtering signals with random interference, which typically have an average value and fluctuate around a certain range.

C. Disadvantages: Not suitable for real-time control requiring fast data computation, relatively wasteful of RAM.

4. Recursive Average Filtering Method (also known as Sliding Average Filtering Method)

A. Method: Treat the continuous N sampled values as a queue with a fixed length of N. Each time a new data point is sampled, it is added to the tail of the queue, and the data at the head of the queue is discarded (FIFO principle). The arithmetic mean of the N data points in the queue can yield a new filtering result. Selection of N: for flow, N=12; for pressure, N=4; for liquid level, N=4~12; for temperature, N=1~4.

B. Advantages: Good suppression of periodic interference, high smoothness, suitable for systems with high-frequency oscillations.

C. Disadvantages: Low sensitivity, poor suppression of occasional pulse interference, not suitable for scenarios with severe pulse interference, relatively wasteful of RAM.

5. Median Average Filtering Method (also known as Anti-Pulse Interference Average Filtering Method)

A. Method: Equivalent to “Median Filtering Method” + “Arithmetic Mean Filtering Method”. Continuously sample N data points, discard one maximum and one minimum, and then calculate the arithmetic mean of the remaining N-2 data points. Selection of N: 3~14.

B. Advantages: Combines the advantages of both filtering methods, can eliminate sampling value deviations caused by occasional pulse interference.

C. Disadvantages: Slow measurement speed, like the arithmetic mean filtering method, relatively wasteful of RAM.

6. Clipping Average Filtering Method

A. Method: Equivalent to “Clipping Filtering Method” + “Recursive Average Filtering Method”. Each time a new sample is taken, it is first clipped, then sent to the queue for recursive average filtering.

B. Advantages: Combines the advantages of both filtering methods, can eliminate sampling value deviations caused by occasional pulse interference.

C. Disadvantages: Relatively wasteful of RAM.

7. First-Order Lag Filtering Method

A. Method: Set a=0~1, this filtering result = (1-a)*current sample value + a*previous filtering result.

B. Advantages: Good suppression of periodic interference, suitable for scenarios with high fluctuation frequencies.

C. Disadvantages: Phase lag, low sensitivity, lag degree depends on the value of a, cannot eliminate interference signals with frequencies higher than half the sampling frequency.

8. Weighted Recursive Average Filtering Method

A. Method: An improvement of the recursive average filtering method, where data from different times are given different weights. Generally, data closer to the current time has a larger weight. The closer the weight coefficient given to the new sample value is to 1, the higher the sensitivity, but the lower the signal smoothness.

B. Advantages: Suitable for objects with large pure time lag constants and systems with short sampling periods.

C. Disadvantages: For objects with small pure time lag constants and long sampling periods, the signal cannot quickly reflect the severity of the current interference, resulting in poor filtering effects.

9. Debouncing Filtering Method

A. Method: Set a filtering counter to compare each sampled value with the current effective value: if the sampled value = current effective value, reset the counter; if the sampled value != current effective value, increment the counter by 1, and check if the counter >= upper limit N (overflow). If the counter overflows, replace the current effective value with the current sample value and reset the counter.

B. Advantages: Good filtering effects for slowly changing parameters, can avoid repeated on/off flickering of the controller near critical values or jittering of the displayed values.

C. Disadvantages: Not suitable for rapidly changing parameters; if the value sampled during the counter overflow happens to be the interference value, it will be treated as an effective value.

10. Clipping Debouncing Filtering Method

A. Method: Equivalent to “Clipping Filtering Method” + “Debouncing Filtering Method”. First clip, then debounce.

B. Advantages: Inherits the advantages of both clipping and debouncing, improves certain deficiencies in the “Debouncing Filtering Method”, avoiding the introduction of interference values into the system.

C. Disadvantages: Not suitable for rapidly changing parameters.

IIR Digital Filter

A. Method: Determine the signal bandwidth, filter it. Y(n) = a1*Y(n-1) + a2*Y(n-2) + … + ak*Y(n-k) + b0*X(n) + b1*X(n-1) + b2*X(n-2) + … + bk*X(n-k).

B. Advantages: High-pass, low-pass, band-pass, band-stop are all possible. Simple design (using MATLAB).

C. Disadvantages: High computational load.

Scan the QR code below to follow us!

Practical Microcontroller Programming Experience SummaryLet’s walk together on the electronic road!

Leave a Comment