Microcontroller Programming Experience Summary

Microcontroller Programming Experience Summary

Using “Software Traps + Program Command” to Deal with PC Pointer Jumps

When the CPU is interfered with from the outside, sometimes the PC pointer can 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 (to intercept instructions) in the blank segment, redirecting the program to the initialization segment or the error handling segment. However, if the PC pointer jumps to another segment of the program, what should the system do? Here, I recommend a method — program command, 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) after a subroutine is executed,

first 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 it is incorrect, it indicates that the PC pointer may have jumped incorrectly, and the subroutine did not return as expected, at which point the program will be redirected to the initialization segment or the error handling segment.

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

Let me reveal the essence of program runaway with a line of code! 750102H ;MOV 01H, #02H, if the current PC does not point to 75H but points 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? Heaven knows! If this malignant runaway continues, it will be doomed! Let’s reform it:

CLR A ;0C4H

INC A ;04H

MOV R1, A ;0F9H

INC A ;04H

MOV @R1, A ;86H

Every byte of code cannot generate jumps and loops, and they are all single-byte instructions! Where will it run to? If it runs away, it has to come back on its own! “Staying at home” is good for a thousand days! “Jumping out” is difficult in everything! So as long as you are used to using accumulators and registers to pass numbers around, and eliminate those dangerous codes, although this adds two bytes of “package” to the PC’s “foot”, it won’t run away! “Foot package” === run! Some friends may ask: what if the PC grabs 02H –LJMP and then grabs a far XXH, and then grabs the neighbor YYH, isn’t that useless? Only those who are nitpicking like ZENYIN would ask such questions! Which position of the PC is the most active? PC0! If there is a “twist”, it obviously happens there, as for that PC15 comrade, he sleeps like a dead pig, even a strong disturbance can’t wake him up? Furthermore, if the interference is so strong that even the high bits of the PC are erroneous! Turn off the power! Turn off the power! I’m done! “It’s not that we can’t do it, 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 PC high level, you have to ask whether there is a problem with the foundation of your kingdom (hardware) rather than in the ideology (software)! Hardware is fundamental! Software is the standard! Treating both the standard and the fundamental will forge a strong body, making it invulnerable!

Don’t Trust Software Dogs

There has been much discussion about software dogs on forums. I have also checked many articles about software dogs. Some experts have indeed proposed some more technical methods. However, my advice is: don’t trust software dogs! In fact, software dogs are a kind of self-discipline behavior of the software. The general idea is to set up a counter, incrementing it in the timing interrupt, and clearing it in the appropriate place in the main program. If the program goes out of control and the clear command is not executed, but interrupts occur frequently, the counter will overflow (the dog barks). However, there is a problem: what if interference causes the interrupt to be masked? Then the software dog will never bark! — To address this possibility, some people have proposed to repeatedly refresh the interrupt enable flag in the main program to ensure that the interrupt is not masked. — But what if the program jumps into a dead loop and no longer executes the “refresh interrupt enable flag” function? It is still possible to starve the dog to death.

Therefore, my view is: the watchdog must have an independent counter (i.e., a hardware watchdog). Fortunately, many chips now provide an internal WDT. Such dogs come with their own counters. Even if interference causes the program to go out of control, the WDT will still continue counting until it overflows. Of course, I don’t mean to dismiss software dogs entirely. After all, whether it’s a soft dog or a hard dog, it’s a good dog if it catches a mouse (dogs catching mice — meddling in others’ business?). If any dog training expert has indeed raised a good software dog that can guard the door, please bring it out for everyone to see.

RAM Redundancy Technology

RAM redundancy refers to:

1. Backing up important data information in 2 (or more) copies and storing it in different areas of RAM (referring to non-contiguous addresses).

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

3. When interference occurs and is intercepted to the “program error handling segment”,

compare the data with the backup 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 (those that can be derived from the original data) do not need to be backed up.

Note:

1. The theoretical basis for this idea reportedly comes from a kind of “probability theory”, namely, 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 destroyed is very high, but the probability of multiple non-contiguous RAMs being destroyed at the same time is very low.

2. A couple of years ago, when I was an apprentice, I used this method once, but the effect was not very good. At that time, I felt that probability theory had failed me? Looking back now, it may have been due to poor timing for backups. As a result, I backed up already destroyed data. Thus, the restored data was naturally incorrect.

Instruction Redundancy Technology

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

1. LCD display. Sometimes, you may use some dedicated driver chips for LCD (such as HT1621). The advantage of such chips is that as long as you send the display data to them, they will automatically scan the LCD continuously. 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 display content has not changed). For CPUs with built-in LCD DRIVER, you should also periodically refresh the LCD RAM.

2. Setting the interrupt enable flag. Don’t think that just setting the interrupt correctly in the program initialization segment is enough. You should periodically refresh it in appropriate places in the main program to avoid your interrupt being suspended.

3. Other flag words and parameter registers (including those you define yourself) should also be refreshed frequently.

4. Other places you think need to be refreshed frequently.

10 Software Filtering Methods

Below are 10 software filtering methods compiled by me after much thought and effort:

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 this value and the last value is <= A, then this value is valid. If the difference is > A, then this value is invalid, discard this value, and use the last value instead.

B. Advantages: Can effectively overcome pulse interference caused by incidental factors.

C. Disadvantages: Cannot suppress periodic interference, and has 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 valid value.

B. Advantages: Can effectively overcome fluctuations caused by incidental factors, and has a good filtering effect on parameters that change slowly, such as temperature and liquid level.

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

3. Arithmetic mean filtering method

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

B. Advantages: Suitable for filtering signals with random interference, characterized by an average value, and the signal fluctuates around a certain value.

C. Disadvantages: Not suitable for real-time control where measurement speed is slow or data computation speed is required to be fast, and it wastes RAM.

4. Recursive average filtering method (also known as moving average filtering method)

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

B. Advantages: Has a good suppression effect on periodic interference, high smoothness, and is suitable for systems with high-frequency oscillations.

C. Disadvantages: Low sensitivity, poor suppression of incidental pulse interference, and is not easy to eliminate sampling value deviations caused by pulse interference. It also wastes 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, discard one maximum value and one minimum value, and then calculate the arithmetic mean of the remaining N-2 data. Selection of N values: 3~14.

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

C. Disadvantages: Measurement speed is slow, and like the arithmetic mean filtering method, it wastes RAM.

6. Clipping average filtering method

A. Method: Equivalent to “clipping filtering method” + “recursive average filtering method”, each new sampling data is first clipped, and then sent to the queue for recursive average filtering processing.

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

C. Disadvantages: Wastes RAM.

7. First-order lag filtering method

A. Method: Take a=0~1, the filtering result = (1-a)*current sampling value + a*previous filtering result.

B. Advantages: Has a good suppression effect on periodic interference, suitable for cases with high fluctuation frequencies.

C. Disadvantages: Phase lag, low sensitivity, the degree of lag 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 on the recursive average filtering method, assigning different weights to data at different times. Generally, the closer the data is to the current moment, the larger the weight. The greater the weight coefficient assigned to the new sampling value, 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 longer sampling periods, the signal cannot quickly reflect the severity of interference currently affecting the system, leading to poor filtering effects.

9. Debounce filtering method

A. Method: Set a filtering counter to compare each sampling value with the current valid value: if the sampling value = current valid value, clear the counter; if the sampling value <> current valid value, increment the counter by 1, and check if the counter >= upper limit N (overflow); if the counter overflows, replace the current valid value with this value and reset the counter.

B. Advantages: Has good filtering effects for slowly changing measured parameters, can avoid repeated on/off fluctuations of the controller or jittering of values displayed on the screen near critical values.

C. Disadvantages: Not suitable for rapidly changing parameters; if the value sampled at the time of counter overflow happens to be an interference value, it will treat the interference value as a valid value and introduce it into the system.

10. Clipping debounce filtering method

A. Method: Equivalent to “clipping filtering method” + “debounce filtering method”, first clip, then debounce.

B. Advantages: Inherits the advantages of “clipping” and “debounce”, improves on certain defects in the “debounce filtering method”, and avoids introducing interference values into the system.

C. Disadvantages: Not suitable for rapidly changing parameters.

IIR Digital Filter

A. Method: Determine the signal bandwidth and 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 arbitrary. Simple design (using MATLAB).

C. Disadvantages: Large amount of computation.

Microcontroller Programming Experience Summary

Microcontroller Programming Experience Summary

Leave a Comment