// (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_timer_hh
#define lipstick_timer_hh

#include "registers.hh"

constexpr int f_timer = 10000;                   // 10 kHz; 100 us per tick.
constexpr int t_tick_us = 1000000 / f_timer;


inline void setup_timer()
{
  constexpr int timer_prescale = f_pclk / f_timer;
  *T0PR = timer_prescale;
  *T0TCR = 2;    // Reset.
  *T0MCR = 0;    // Disable interrupts (should be defualt)
  *T0TCR = 1;    // Enable.
}


inline void set_timer(int delay_us)
{
  int ticks = delay_us / t_tick_us;
  *T0MR0 = *T0TC + ticks;
  *T0MCR = 0b1;  // MR0I = 1; interrupt on match register 1.
}


inline void cancel_timer()
{
  *T0MCR = 0;
}


#endif

