// (C) 2020 Philip Endecott.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENCE.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#ifndef lipstick_wdt_hh
#define lipstick_wdt_hh

#include "registers.hh"
#include "clocks.hh"
#include "arm.hh"


inline void wdt_poke()
{
  // The two writes must not be interrupted, so disable interrupts if 
  // they are enabled around this call (see atomic_poke below).
  *WDFEED = 0xaa;
  *WDFEED = 0x55;
}


inline void wdt_atomic_poke()
{
  disable_irq();
  wdt_poke();
  enable_irq();
}


template <int timeout_s>
inline void setup_wdt()   // Interrupts must be disabled when this is called, due to the poke.
{
  constexpr auto f_tick = f_pclk / 4;
  constexpr auto ticks = timeout_s * f_tick;
  *WDTC = ticks;
  *WDMOD = 0b00000011;  // Set WDEN and WDRESET bits
  wdt_poke();
}


inline bool wdt_timedout()
{
  return *WDMOD & 0b00000100;
}


#endif

