# using exit(EXIT_SUCCESS) or exit(EXIT_FAILURE) in AVR or any other microcontroller

How does one use exit(EXIT_SUCCESS) or exit(EXIT_FAILURE) in microcontroller C programming. I know it works on application level C programs when you include #include<stdlib.h>.

The idea is to exit the main loop altogether when some unexpected value is returned, for example. What exactly would be the common approach in such a case? I could do a Reset but i want to see if somethings gone wrong in main. Is it a good practice to use goto: exit_main or something similar?

exit() is not the proper way to handle unexpected results in embedded platforms. You could use it, but it will cause a system reset. Either by design, or by timeout of the watchdog. Or just simply enter an infinite loop.

For example, ARM will do this, after a few library exit jumps.
(see for yourself in the simulator)

_sys_exit:
0x08000258 4901      LDR      r1,[pc,#4]  ; @0x08000260
0x0800025A 2018      MOVS     r0,#0x18
0x0800025C BEAB      BKPT     0xAB
0x0800025E E7FE      B        0x0800025E
0x08000260 0026      DCW      0x0026
0x08000262 0002      DCW      0x0002


BKPT is a hardcoded breakpoint. Else, the B instruction here will form an infinite loop.

On cricital errors that cannot be recovered you can instead do NVIC_SystemReset() on arm, or let the watchdog timeout. I believe AVR, as mention in an answer, does not have a dedicated system reset bit.

• it does, however, have a watchdog. – Jasen Jun 7 '17 at 21:19

C11 5.1.2.1(2)

The effect of program termination in a freestanding environment is implementation-defined.

exit() may or,may not, do what you want.

looks like it will halt sort-of.

if you want a restart do this instead:

http://www.atmel.com/webdoc/avrlibcreferencemanual/FAQ_1faq_softreset.html

code:

#include <avr/wdt.h>

...

#define soft_reset()        \
do                          \
{                           \
wdt_enable(WDTO_15MS);  \
for(;;)                 \
{                       \
}                       \
} while(0)


Other microcontrollers will have other means of performing a software-triggered reset.

• I learnt a while ago thats what Arduino does on exit(0), does a cli();//disabling interrupts and while(1)//Infinite loop, did not know it was valid for avr as well. In assembly, i would just write a goto and jump in an implemented routine, to leave the main loop. I am just not sure if its a good practice in C. – Abel Tom Jun 7 '17 at 5:29
• the stub that runs before main() assumes that the processor has just come out of reset so all the I/O registers are in known states, so you can't just branch to that and always get a good result, atmel reccomends triggering the watchdog, (edit to aswer). – Jasen Jun 26 '17 at 5:01