
Based on the experiences of many microcontroller programming experts online, today I will summarize 10 tips for programming the 51 microcontroller.

1. Do not define too many variables. The lower 128 bytes are the storage area for user-defined variables (by default), and while variables can also be placed in the upper 128 bytes, it is prone to errors, so it is best to avoid it. You can check the memory variable storage through M51, and it is best not to exceed 110 bytes; otherwise, the program may not run or may produce errors.
2. If a variable is used in multiple places, it can be defined as a global variable. For example, loop variables i and j should minimize parameter passing.

3. Static variables are best placed in the program storage area, defined with code.
4. Variables should be defined as unsigned numbers; variables that only occupy one bit, such as flags, should be defined as bits.
5. Subroutines that appear after the main program in main() should be declared in advance; those that appear before do not need to be declared.6. If variables or subroutines are defined but not used, the system will issue a warning.
7. Although local variables and global variables have different names, they may be changed by global variables at runtime.8. After compilation, the program may produce very large files. For example, a 5k file may become 10k after compilation, which is caused by too arbitrary space allocation during C assembly. You can first mask part of the program for compilation, then mask and recompile, or copy parts to another file for compilation.
9. If a pulse signal is generated using a timer, to remove the pulse signal, the timer should be turned off first, and then the level should be set to high or low as required.
10. You can implement a “watchdog” function in software. For example, if a program runs a loop that requires 50ms, the timer can be set to 100ms; if it exceeds 100ms, the program will reset. At the bottom of the program loop, the timer should be reloaded or the timer parameters reset.



Some screenshots from electronic books

【Complete Set of Hardware Learning Materials Collection】
