6

Almost all the simple 8051 programs I have seen so far ends with the code LOOP: SJMP LOOP.

From my understanding I think the above instruction creates an infinite loop by calling the same instruction again and again. But what is the purpose of having infinite loop at the end of a program and if it keeps running again and again then when does the program gets terminated.

Sparkzz
  • 367
  • 5
  • 14
  • 1
    So that the program doesn't continue executing random/semi-random data after the last instruction. The CPU sees it all as data and will gladly try to execute whatever is in memory thus causing undefined behavior. Putting processor in a loop like that prevents the CPU wandering aimlessly through whatever remains in memory. – Michael Petch Apr 17 '17 at 21:00

1 Answers1

9

How else do you "terminate" or end a bare metal program? There generally is no halt or other command, the processor doesnt stop. The safest/cleanest is to have it infinite loop (as opposed to just wandering through memory trying to execute what it finds).

so for simple educational processor/microcontroller programs, programs that "end", you would want to end them in an infinite loop if the processor doesnt have a halt. Most mcus never halt they run whatever forever (they might go to sleep in a low power state, but then wake up when you press a button on the remote or whatever).

old_timer
  • 69,149
  • 8
  • 89
  • 168