/// \file LED_blinker.ino

// Copyright (c) 2017, Garth Zeglin. All rights reserved. Licensed under the
// terms of the BSD 3-clause license as included in LICENSE.

/// \brief Onboard LED blinker demo module for EventBusyBox illustrating
/// event-loop programming.

// ================================================================================
// Global state variables for the module.

/// Time remaining in microseconds before the next LED update.
long led_blink_timer = 0;

/// The number of microseconds between LED updates.
const long led_blink_interval = 500000; // microseconds duration of both ON and OFF intervals

/// Current LED output state.
int led_blink_state = LOW;

// ================================================================================
/// Configuration function to call from setup().
void setup_LED_blinker(void)
{
  /// Use the on-board LED (generally D13).
  pinMode(LED_BUILTIN, OUTPUT);
}
// ================================================================================

/// Status function to report the current LED state.
bool is_LED_blinker_on(void)
{
  return (led_blink_state != LOW);
}  

// ================================================================================
/// Update function to poll from loop().
void poll_LED_blinker(unsigned long interval)
{
  // Test whether to update the output.
  led_blink_timer -= interval;

  // The interval has elapsed once the timer variable reaches zero or overruns
  // into negative values:
  if (led_blink_timer <= 0) {

    // Reset the timer for the next sampling period.  This approach adds in the
    // interval value to maintain precise timing despite variation in the
    // polling time.  E.g. if this sampling point was a little late, the
    // led_blink_timer value will be negative, the next one will occur a little
    // sooner, maintaining the overall average interval.
    led_blink_timer += led_blink_interval;

    // Toggle the hardware output.
    if (led_blink_state == LOW) led_blink_state = HIGH;
    else led_blink_state = LOW;
    digitalWrite(LED_BUILTIN, led_blink_state);
  }
}
// ================================================================================
