Summary of MCU Programming Experience

Publisher:石头12345Latest update time:2011-10-26 Keywords:MCU Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

Experience 1: Use "software trap + program password" to deal with the flying of PC pointer

When the CPU is disturbed by external factors, sometimes the PC pointer will fly to another program segment, or jump to a blank segment. In fact, if the PC pointer flies to a blank segment, it is easy to handle. Just set up a software trap (intercept instruction) in the blank segment to intercept the program to the initialization segment or program error handling segment. However, if the PC pointer flies to another program segment, what should the system do? Xiaojiang recommends a method here-program password, the idea is as follows:

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

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

3. Configure a unique ID number for each subroutine.

4. Whenever a subroutine is executed, before returning (RET),

First, send the ID number of this subroutine to the ID register.

5. After returning to the parent program, first determine the ID number in the ID register.

If it is correct, continue to execute; if it is incorrect, it means that the PC pointer may have jumped to the wrong position, and the subroutine did not return as expected. At this time, the program is intercepted to the initialization segment or the program error handling segment.

This method is like setting up several sentries in the program. After each call to the subroutine returns, the password (ID number) must be verified before it is released. Combined with software traps, most PC pointer flying phenomena can basically be detected. When it reaches the program error handling segment, it is up to you to kill or cut (cold start or hot start).

Only one piece of code reveals the essence of program running! 750102H; MOV 01H, #02H, if the current PC is not pointing to 75H, but to 01H or 02H, then the instruction decoder in 51 will faithfully translate them into AJMP X01H or LJMP XXXXH. What is XX01H XXXXH? God knows! If you continue to run like this, you will die! Reform it:

CLR A; 0C4H
INC A; 04H
MOV R1, A; 0F9H
INC A; 04H
MOV @R1, A; 86H.

Each byte of code can no longer generate jumps and loops, and all are single-byte instructions! Where are you running to? If you run away, you must come back by yourself! Staying at home is a thousand days! Jumping out is difficult! In this way, as long as you are used to using the accumulator and register to count upside down, and dump all the dangerous codes, although two bytes of "package" are added to the "foot" of PC, it is not easy to "run"! "Foot package" ==== run! Some friends may ask: If PC is caught as 02H--LJMP, and it is caught as XXH, which is far away, and then caught as YYH next door, isn't it useless? Only ZENYIN, who is a bit stubborn, would ask such a question! Which PC is the most active? PC0! The "pull" obviously happened to her. As for comrade PC15, she is sleeping like a dead pig, and can't be awakened even by thunder (strong interference)? In addition, if the interference is so strong that the high position of PC is wrong! Turn off the power! Turn off the power! I won't do it! "It's not that we can't do it, but the enemy is too strong"! On the other hand, if the enemy only occasionally comes out to make trouble under your dictatorship, but once it comes out, it rushes to the top of the PC, you should ask if there is a problem with the foundation of your kingdom (hardware)? Rather than the ideology (software)! Hardware is the foundation! Software is the symptom! Treating both the symptom and the root will build a strong body, so that it can be immune to all poisons!

Experience 2: Don't trust software dogs easily

There are many discussions about software dogs on the forum. The craftsman has also read many articles about software dogs. Some masters have indeed proposed some more skillful methods. However, the craftsman's advice is: Don't trust software dogs easily! In fact, software dogs are equivalent to a self-discipline behavior of software. The general idea is to set up a counter, add 1 to it in the timer interrupt, and clear it to zero in the appropriate place of the main program. If the program is out of control, the clear instruction is not executed, but the interrupt occurs frequently, then the counter overflows (the dog barks). But there is a problem here: if the interrupt is blocked due to interference, then the software dog will never bark! ——In response to this possibility, some people have suggested repeatedly refreshing the interrupt enable flag in the main program to ensure that the interrupt is not blocked. ——But if the program flies into an infinite loop and no longer executes the function of "refreshing the interrupt enable flag", it is still possible that the dog will starve to death.

Therefore, the craftsman’s point of view is: the watchdog must have an independent counter. (That is, a hardware watchdog) Fortunately, many chips now provide internal WDT. This kind of dog has its own counter. Even if interference causes the program to go out of control, the WDT will still create a constant count until it overflows. Of course, the craftsman does not mean to kill all software dogs with one stick. After all, whether it is a soft dog or a hard dog, it is a good dog if it catches a mouse (a dog catching a mouse - meddling in other people's business?). If any dog ​​training expert has indeed raised a good software dog that can watch the door, please bring it out for everyone to see.

Experience 3, talking about RAM redundancy technology

The so-called RAM redundancy is:

1. Back up 2 (or more) copies of important data information and store them in different areas of RAM (referring to non-connected addresses).

2. When these data are modified normally, the backup is also updated.

3. When interference occurs and is intercepted in the "program error handling segment",

Compare the data with the backup, and use voting (the minority obeys the majority) to select the correct (or possibly correct?) one.

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

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

Note:

1. The theoretical basis of this idea is said to be derived from a kind of "probability theory", that is, the probability of a man being beaten by his wife is very high, but if he goes to work with his face covered and finds that every married man in the company has a blue face, this probability is very small. Similarly, the probability of a RAM register data being destroyed is very high, but the probability of multiple RAMs with unconnected addresses being destroyed at the same time is very small.

2. Two years ago, when Xiaojiang was an apprentice, I used this method once, but the effect was not ideal. At that time, I felt that the probability theory might have failed in my case? Now thinking back, it might be that the timing of the backup was not chosen well. As a result, the destroyed data was backed up again. In this way, the restored data is naturally wrong.

Experience 4: Instruction Redundancy Technology

A friend asked about instruction redundancy earlier. According to my understanding, instruction redundancy is action redundancy. For example, if you want to output a high level on a certain output port to drive an external device, if you only send "1" once, then when interference comes, this "1" may become "0". The correct way to deal with it is to refresh this "1" regularly. Then, even if it is accidentally interfered with, it can recover. In addition to the redundancy of I/O port actions, I strongly recommend that you also use this method in the following aspects:

1. LCD display. Sometimes, you may use some dedicated LCD driver chips (such as HT1621). This chip has an advantage, that is, as long as you send the display data to it, it will automatically scan the LCD continuously. However, don't think that you have nothing to do. The correct way to deal with it is to remember to refresh the display data regularly (even if the display content has not changed). For CPUs with built-in LCD DRIVER, LCD RAM should also be refreshed regularly.

2. Setting the interrupt enable flag. Don't think that you are OK after setting the interrupt in the program initialization section. You should refresh it regularly in the appropriate place in the main program to prevent your interrupt from being hung.

3. Remember to refresh other flag words and parameter registers (including those you define yourself) frequently.

4. Other places that you think need to be refreshed repeatedly.

Experience 5: 10 software filtering methods

Here are 10 software filtering methods that the craftsman has worked hard to think about:
1. Limit filter method (also known as program judgment filter method)

A. Method: According to experience, determine the maximum deviation value allowed for two samples (set to A), and judge each time a new value is detected: If the difference between the current value and the previous value is <= A, then the current value is valid. If the difference between the current value and the previous value is > A, then the current value is invalid, abandon the current value, and use the previous value instead of the current value

B. Advantages: It can effectively overcome pulse interference caused by accidental factors.

C. Disadvantages: It cannot suppress periodic interference and has poor smoothness.

2. Median filter method

A. Method: Continuously sample N times (N is an odd number), arrange the N sampling values ​​in order of size, and take the middle value as the effective value of this time.

B. Advantages: It can effectively overcome the fluctuation interference caused by accidental factors, and has no effect on temperature, liquid
It has a good filtering effect for the measured parameters with slow bit changes.

C. Disadvantages: It is not suitable for fast-changing parameters such as flow and speed.

3. Arithmetic average filtering method

A. Method: Take N sampling values ​​continuously for arithmetic averaging. When the N value is large: the signal smoothness is higher, but the sensitivity is lower; when the N value is small: the signal smoothness is lower, but the sensitivity is higher. Selection of N value: general flow, N=12; pressure: N=4

B. Advantages: It is suitable for filtering signals with general random interference. The characteristic of such signals is that there is an average value, and the signal fluctuates around a certain value range.

C. Disadvantages: It is not applicable to real-time control with slow measurement speed or fast data calculation speed, and it wastes RAM.

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

A. Method: Take N consecutive sampling values ​​as a queue, the length of the queue is fixed to N, and each time a new data is sampled, it is put at the end of the queue, and the original data at the head of the queue is discarded. (First-in-first-out principle), perform arithmetic averaging on the N data in the queue to obtain a new filtering result. Selection of N value: flow, N=12; pressure: N=4; liquid level, N=4~12; temperature, N=1~4

B. Advantages: good suppression of periodic interference, high smoothness, suitable for high-frequency oscillation systems.

C. Disadvantages: low sensitivity, poor suppression of occasional pulse interference, difficult to eliminate sampling value deviation caused by pulse interference, not suitable for occasions 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 average filtering method". Continuously sample N data, remove a maximum value and a minimum value, and then calculate the arithmetic mean of N-2 data. Selection of N value: 3~14

B. Advantages: It combines the advantages of the two filtering methods. For occasional pulse interference, it can eliminate the sampling value deviation caused by pulse interference.

C. Disadvantages: The measurement speed is slow, and like the arithmetic average filtering method, it is relatively wasteful of RAM.

6. Limiting average filtering method

A. Method: Equivalent to "limiting filtering method" + "recursive average filtering method". Each time the new data is sampled, it is first limited and then sent to the queue for recursive average filtering.

B. Advantages: It combines the advantages of the two filtering methods. For occasional pulse interference, it can eliminate the sampling value deviation caused by pulse interference.

C. Disadvantages: It wastes RAM.

7. First-order lag filtering method

A. Method: Take a=0~1, and the result of this filtering is

Result = (1-a) * this sampling value + a * last filtering result.

B. Advantages: It has a good inhibitory effect on periodic interference and is suitable for occasions with high fluctuation frequency.

C. Disadvantages: Phase lag, low sensitivity, the degree of lag depends on the value of a, and cannot eliminate interference signals whose filtering frequency is higher than 1/2 of the sampling frequency.

8. Weighted recursive average filtering method

A. Method: It is an improvement on the recursive average filtering method, that is, different weights are given to data at different times. Usually, the closer the data is to the current moment, the greater the weight. The larger the weight coefficient given to the new sampling value, the higher the sensitivity, but the lower the signal smoothness.

B. Advantages: It is suitable for objects with large pure lag time constants and systems with short sampling cycles.

C. Disadvantages: For signals with small pure lag time constants, long sampling cycles, and slow changes, it cannot quickly reflect the severity of the current interference to the system, and the filtering effect is poor.

9. Anti-jitter filtering method

A. Method: Set a filter counter to compare each sampling value with the current effective value: If the sampling value = the current effective value, the counter is cleared. If the sampling value <> the current effective value, the counter is +1, and it is determined whether the counter is >= the upper limit N (overflow). If the counter overflows, the current value replaces the current effective value and the counter is cleared.

B. Advantages: It has a good filtering effect for the slowly changing measured parameters, which can avoid the repeated on/off jump of the controller near the critical value or the numerical jitter on the display.

C. Disadvantages: It is not suitable for rapidly changing parameters. If the value sampled at the time when the counter overflows happens to be an interference value, the interference value will be imported into the system as an effective value.

10. Limiting anti-jitter filtering method

A. Method: It is equivalent to "limiting filtering method" + "anti-jitter filtering method". Limiting first, then eliminating jitter.

B. Advantages: It inherits the advantages of "limiting" and "anti-jittering" and improves some defects in the "anti-jitter filtering method" to avoid importing interference values ​​into the system.

C. Disadvantages: It is 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(nk) + b0*X(n) + b1*X(n-1) + b2*X(n-2) + . + bk*X(nk).

B. Advantages: high pass, low pass, band pass, band stop are arbitrary. Simple design (using matlab)

C. Disadvantages: large amount of calculation.

Keywords:MCU Reference address:Summary of MCU Programming Experience

Previous article:8-channel 12-bit AD converter ADuC812 for embedded MCU and its application
Next article:Research on Anti-interference Method of Single-Chip Microcomputer System Software

Recommended ReadingLatest update time:2024-11-16 20:58

Design of electronic billboard circuit based on 51 single chip microcomputer
0 Introduction Nowadays, neon lights are still the bright colors used to decorate various buildings in cities. However, neon lights have the disadvantages of high heat generation, low brightness, dark colors, high prices and high power consumption, and are no longer the main choice for decoration. Dot matrix scr
[Microcontroller]
Design of electronic billboard circuit based on 51 single chip microcomputer
51 MCU RAM area division
When introducing the microcontroller resources, we mentioned that STC89C52 has a total of 512 bytes of RAM, which is used to store data. For example, the variables we define are directly stored in the RAM. However, the 512 bytes of RAM in the microcontroller are not equal in status, but divided into blocks. There are
[Microcontroller]
ATmega128 microcontroller communicates with the servo control board
The ATmega128 microcontroller controls the actions of multiple servos through the servo control board. The data communication between the servo control board and the microcontroller adopts the common serial communication (USART). The servo control board has the function of automatically identifying the baud rate (9600
[Microcontroller]
Bus stop voice announcement system based on SLH89F5162 single chip microcomputer
1. Project design background and overview With the progress of urbanization and the rapid development of the economy, the situation of "difficulty in taking buses" and "difficulty in driving" in cities is getting worse. Many cities recommend people to take the bus when going out. However, in bad weather or poor visibi
[Power Management]
Bus stop voice announcement system based on SLH89F5162 single chip microcomputer
Summary of MSP430 MCU Development
1.#i nclude<> means to go to the editor setting directory, #i nclude "" means to go to the current project directory. 2. To call a function in another file, put the function file in the current project directory and add it to the project. 3. There cannot be a - in the name, for example: byq-ee will be considered wron
[Microcontroller]
Tetris based on 51 single chip microcomputer
1. Hardware Solution This design uses STC89C52RC microcontroller as the system chip to realize human-computer interaction, entertainment and other functions. LCD12864 is selected to realize the Tetris game interface and graphic display; independent buttons are selected to realize game control. The basic functions real
[Microcontroller]
Tetris based on 51 single chip microcomputer
51 MCU C programming (seven, 5 IO ports scan 10 buttons)
Program name: 5 IO ports scan 10 buttons Author       : jumpmysoul Date       : May 22, 2009 Program function: Use P00~P04 of P1 port to scan 10 keys and display the key values ​​with a digital tube The proteus simulation circuit is as follows:   #include reg51.h #define uchar unsigned char #define uint
[Microcontroller]
How to use the SST MCU P4 port
       The 44-pin package chip of SST89e516 has an additional P4 port like MCS51. The P4 port uses the same IO as P0~P3, but the address of the P4 port is A5H. In the header file, add sfr P4 = 0xa5;        You will find that you cannot use sbit during use. That is to say, because the address of P4 port is A5H, which c
[Microcontroller]
Latest Microcontroller Articles
  • Download from the Internet--ARM Getting Started Notes
    A brief introduction: From today on, the ARM notebook of the rookie is open, and it can be regarded as a place to store these notes. Why publish it? Maybe you are interested in it. In fact, the reason for these notes is ...
  • Learn ARM development(22)
    Turning off and on interrupts Interrupts are an efficient dialogue mechanism, but sometimes you don't want to interrupt the program while it is running. For example, when you are printing something, the program suddenly interrupts and another ...
  • Learn ARM development(21)
    First, declare the task pointer, because it will be used later. Task pointer volatile TASK_TCB* volatile g_pCurrentTask = NULL;volatile TASK_TCB* vol ...
  • Learn ARM development(20)
    With the previous Tick interrupt, the basic task switching conditions are ready. However, this "easterly" is also difficult to understand. Only through continuous practice can we understand it. ...
  • Learn ARM development(19)
    After many days of hard work, I finally got the interrupt working. But in order to allow RTOS to use timer interrupts, what kind of interrupts can be implemented in S3C44B0? There are two methods in S3C44B0. ...
  • Learn ARM development(14)
  • Learn ARM development(15)
  • Learn ARM development(16)
  • Learn ARM development(17)
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号