Last night, a colleague of ours organized a small meeting where we discussed the microcontroller code for a project using the Nuvoton microcontroller. During the meeting, several issues were discussed, and I would like to summarize them in hopes of helping those who write microcontroller code.
The code written by my colleague is excellent, but I can’t show the specific code.
Some memory spaces of the microcontroller:
data —> Addressable on-chip RAM
bdata —> Bit-addressable on-chip RAM
idata —> Addressable on-chip RAM, allows access to all internal RAM
pdata —> Page-addressable off-chip RAM (MOVX @R0) (256 BYTE/page)
xdata —> Addressable off-chip RAM (64k address range FFFFH)
code —> Program storage area (64k address range), corresponding to MOVC @DPTR
Program Size: data=12.0 xdata=120 code=3349
— —Using const
We generally define a global variable that occupies RAM space. If we define this variable as const, we can allocate its space from RAM to code space, thus saving memory space.
After testing, we found that const variables not only occupy RAM space but also increase the size of the code. Everyone can try this out during usage.
The reason it doesn’t move to code space is probably that the ROM lacks the capability to run programs.
It is often heard that program code can run on NOR Flash but not on NAND Flash, which can be misleading. The CPU executes code in three steps: fetch, decode, and execute. Therefore, the one truly running the code is still the CPU. The statement that code can run directly on NOR Flash means that the CPU can fetch instructions directly from NOR Flash via the address bus.
— —Try to use global variables
Local variables in functions occupy stack space. If there are many local variables, it can be difficult to troubleshoot issues later on. Using global variables can utilize code space, ensuring there is enough stack space for the program to run, ensuring that there is enough stack space during execution.
——Try to enable the watchdog
For mobile phones, the watchdog is not very important, but for microcontrollers, it is crucial. The watchdog can ensure that the microcontroller can recover and resume operation after a crash.
——Declared as char type, but may actually be unsigned char
This is an issue with the compiler. If you find the program does not run as expected, you may want to pay attention to this.
