Go back to the examples list

Basic watchdog usage

This simple example shows how to enable the watchdog. The red LED will flash anytime the board is started or reset, then the blue LED will blink to show activity. Pressing the button will clear the watchdog and flash the green LED. If the button is not pressed for about 4 seconds, the watchdog will reset the board, shown by the red LED flashing.

wdt_basics.cpp [download]
wget https://libtungsten.io/static/code/examples/wdt_basics/wdt_basics.cpp

#include <carbide.h>
#include <core.h>
#include <wdt.h>

// Handler called when the button is pressed which
// clears the Watchdog and flash the green LED
void onButtonPressedHandler() {
    WDT::clear();
    Carbide::setLedG(true);
    Core::waitMicroseconds(100000);
    Carbide::setLedG(false);
}

int main() {
    // Init the board
    Carbide::init(true);

    // Flash the red LED to indicate a reset
    Carbide::setLedR(true);
    Core::sleep(500);
    Carbide::setLedR(false);

    // Register the button handler
    Carbide::onButtonPressed(onButtonPressedHandler);

    // Enable the watchdog. Because of counter constraints,
    // the actual timeout will be around 4.5s instead of 3s
    // (see module reference)
    WDT::enable(3000, WDT::Unit::MILLISECONDS);

    while (1) {
        // Blink the blue LED to simulate activity
        Carbide::setLedB(true);
        Core::sleep(200);
        Carbide::setLedB(false);
        Core::sleep(200);
    }
}

Makefile [download]
wget https://libtungsten.io/static/code/examples/wdt_basics/Makefile

NAME=wdt_basics

BOOTLOADER=true

# Available modules : adc dac eic gloc i2c spi tc trng usart
# Some modules such as gpio and flash are already compiled by default
# and must not be added here.
MODULES=

# The toolchain's bin/ path, don't forget to customize it
# If this directory is already in your PATH, comment this line.
TOOLCHAIN_PATH=/opt/arm-none-eabi/bin/

# Include the main lib makefile
include libtungsten/Makefile