/// \file PinballGame/PinballSensor.cpp
/// \copyright No copyright, 2016, Garth Zeglin.  This file is explicitly placed in the public domain.

/****************************************************************/

#include "Arduino.h"
#include "PinballSensor.h"

/****************************************************************/
// Constructor for an instance of the class.
PinballSensor::PinballSensor(int pin)
{
  // initialize the state variables
  input_pin   	    = pin;
  sample_timer      = 0;
  raw_input         = 0;
  sampling_interval = 5000;  // 5000 usec == 5 msec == 200 Hz
  lower_threshold   = 700;
  upper_threshold   = 750;
  active            = false;
  triggered         = false;
  event_count       = 0;
  sample_count      = 0;
}

/****************************************************************/

// Update polling function for an instance of the class.
void PinballSensor::update(unsigned long interval)
{
  // always reset any event indication
  triggered = false;

  // test whether to sample the input
  sample_timer -= interval;
  
  if (sample_timer <= 0) {

    // Reset the timer for the next sampling period.  Adding in the value helps
    // maintain precise timing in the presence of variation in the polling time,
    // e.g. if this sampling point was a little late, the next one will occur a
    // little sooner, maintaining the overall average.
    sample_timer += sampling_interval;

    // read the raw input
    raw_input = analogRead(input_pin);
    sample_count++;
    
    if (!active) {
      // if waiting for another input, use the lower threshold to detect an event
      if (raw_input < lower_threshold) {
	active = true;
	triggered = true;
	event_count++;
      }
    }
    else {
      // if waiting for an input to end, use the upper threshold to detect a reset
      if (raw_input > upper_threshold) {
	active = false;
      }
    }
  }
}
/****************************************************************/
void PinballSensor::send_debug(void)
{
  Serial.print("sensor pin:");
  Serial.print(input_pin);

  Serial.print("  raw: ");
  Serial.print(raw_input);

  Serial.print("  active: ");
  Serial.print(active);

  Serial.print("  samples: ");
  Serial.print(sample_count);

  Serial.print("  events: ");
  Serial.print(event_count);

  Serial.print("  thresholds: ");
  Serial.print(lower_threshold);
  Serial.print(" ");
  Serial.print(upper_threshold);
  
  Serial.println();
}
/****************************************************************/
