 #include "Cosa/Watchdog.hh"
 #include "Cosa/Periodic.hh"
 
-// Use the watchdog job scheduler
+// Use the Watchdog job scheduler
 Watchdog::Scheduler scheduler;
 
 /**

 */
class VCC : public Periodic {
public:
  VCC(uint16_t mv, uint16_t sec = 2) :
    Periodic(&scheduler, sec * 1024),
    m_threshold(mv),
    m_vcc(0)
  {
  }
  virtual void run()
  {
    m_vcc = AnalogPin::bandgap();

	  << PSTR(":warning:low voltage(VCC = ")
	  << m_vcc << PSTR(" mV)\n");
  }
  uint16_t vcc()
  {
    return (m_vcc);
  }
private:
  uint16_t m_threshold;
  uint16_t m_vcc;
};

// Monitor low voltage at 4.4 V
VCC lowPower(4400);

/**
 * Periodical sampling of analog pin.
 */
class Sampler : public AnalogPin, public Periodic {
public:
  Sampler(Board::AnalogPin pin, uint16_t ms) :
    AnalogPin(pin),
    Periodic(&scheduler, ms),
    m_count(0)
  {}
  virtual void run()
  {
    m_count++;
    sample_request();
  }
  uint16_t count()
  {
    return (m_count);
  }
private:
  uint16_t m_count;
};

Sampler sampler(Board::A0, 250);

/**
 * Periodical display the values
 */
class Display : public Periodic {
public:
  Display(uint16_t sec = 1) : Periodic(&scheduler, sec * 1000UL)
  {
    expire_at(1000);
  }
  virtual void run()
  {
    trace << Watchdog::millis()
	  << PSTR(":A0:") << sampler.count()
	  << PSTR(" = ") << sampler.get_value()
	  << PSTR(":Vcc  = ") << lowPower.vcc()
	  << endl;
  }
};

// Print the latest sample value and voltage
Display display(1);

void setup()
{
  uart.begin(9600);
  trace.begin(&uart, PSTR("CosaVCC: started"));
  AnalogPin::powerup();
  lowPower.start();
  sampler.start();
  display.start();
  Watchdog::begin();
}

void loop()
{
  Event::service();
}

