How shall I end my program?
Submitted By: Jan Waclawek FAQ Last Modified: 09/05/07
- It is a common pitfall for newbies to believe, that putting the END statement at the end of a linear piece of assembly code will stop the program execution.
This is not the case.
END is only an assembler directive, which tells the assembler, that there are no more lines of code to read and translate in this file. So, it does not result in any opcode for the microcontroller.
Consequently, as there is no opcode defined for the code space addresses after the last statement, they will be filled by the default value the program memory (FLASH) has after being erased (FF). After having executed the last statement, the '51 will happily continue to execute the FFs as MOV R7,A , until the end of the internal FLASH; and then, the behaviour is in most of the cases undefined.
It is therefore necessary, if you want to "stop" the program's execution, to place an old fashioned "infinite" loop after the last statement, e.g. "STOP: SJMP STOP".
Similarly for 'C'
Submitted By: Andy Neil FAQ Last Modified: 09/05/07
- A similar situation also applies for 'C' programs:
The 'C' programming language "assumes" that main() will be called by the host system and, on completion, will return.
But, in an embedded system, there is usually nothing to return to - so the programmer must ensure that main() does not return!
A simple solution, equivalent to the "STOP: SJMP STOP" in assembler is to add
for( ;; );at the end of main()
For example:
void main( void ) { printf( "Hello, world!" ); for( ;; ); }
Add Information to this FAQ: If you have additional information or alternative solutions to this question, you may add to this FAQ by clicking here.