Go back to the examples list

Watchdog with interrupt

This example is similar to Basic watchdog usage, but in this case Interrupt Mode is enabled. When the watchdog is triggered, instead of immediately resetting the microcontroller, wdtHandler() is called. This function will turn the green LED on and wait for a button press to clear the watchdog. If the button is not pressed in the time of another watchdog trigger, the microcontroller is reset.

You can think of this as a sort of warning that the watchdog sends you before performing a reset.

wdt_interrupt.cpp [download]
wget https://libtungsten.io/static/code/examples/wdt_interrupt/wdt_interrupt.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);
}

// Handler called when the watchdog time is triggered.
// This function will block until the button is pressed
// then clear the interrupt. If the button is not
// pressed before the watchdog is triggered again, the
// microcontroller will be reset.
void wdtHandler() {
    Carbide::setLedB(false);
    Carbide::setLedG(true);
    while (!Carbide::isButtonPressed());
    WDT::clearInterrupt();
}

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 with the interrupt handler.
    // Because of counter constraints, the actual timeout
    // will be around 4.5s instead of 3s (see module reference)
    WDT::enable(3000, WDT::Unit::MILLISECONDS, wdtHandler);

    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_interrupt/Makefile

NAME=wdt_interrupt

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