Since a couple of months we’re developing an IoT (Internet of Things) application. We built our prototype with an Arduino Uno accompanied by a GSM/GPRS shield.
It took me a while to make the whole GPRS (re)connect flow stable, except for one annoying bug. If we would lose connection while sending data to the server, we went into Gibberish land. The only solution I came up with, would be a manual reset of the device. Pretty hard if you know that our device is bolted to a car that’s racing around a race track.
Solution: Arduino Watchdog Timer
A watchdog timer checks if your program is still running, in case it gets stuck, resets your Arduino. AVR supplies the Arduino's with such an hardware implemented watchdog timer that you can configure with different threshold intervals.
Include the watchdog timer in your sketch.
#include <avr/wdt.h>
Enable and configure it.
wdt_enable(WDTO_8S);
WDTO_8S is defined in the header file as a constant. This will set the interval threshold at 8 seconds before the Arduino would reset. Other options are:
Constant | Interval threshold |
---|---|
WDTO_15MS | 15 ms |
WDTO_30MS | 30 ms |
WDTO_60MS | 60 ms |
WDTO_120MS | 120 ms |
WDTO_250MS | 250 ms |
WDTO_500MS | 500 ms |
WDTO_1S | 1 s |
WDTO_2S | 2 s |
WDTO_4S | 4 s |
WDTO_8S | 8 s |
The next function would reset the timer before it reaches the end of the interval.
wdt_reset();
As long as you keep on calling this function within 8 secondsn your program keeps on running.
What to do about long running library functions that run longer than your threshold interval? My connect to GPRS network functions would always run longer then 8 seconds. I needed a way to disable the watchdog temporarily. I took a peek in the wdt.h file and found this:
wdt_disable();
And it does work. Don't forget to enable your watchdog again after you disabled it.
Sidenote:
Be careful if you use small threshold intervals. Since enabling a watchdog means you set it in the register, which state is remembered after a reset. It would start the watchdog timer immediately on reset, which could cause your Arduino to infinitely reset while starting up the bootloader.