How to reset arduino Mega 2560 code automatically?
avr-libc already has the appropriate functions created for you. Just include &lt;avr/wdt.h&gt;.

Sample usage

#include &lt;avr/wdt.h&gt;

void setup()
{
   wdt_enable(WDTO_8S);
   ...
}

void loop()
{
   wdt_reset();// make sure this gets called at least once every 8 seconds!
   ...
}