#include <Wire.h>
#include <Adafruit_GFX.h>
#include "Adafruit_LEDBackpack.h"

// CONFIG
const int sensorPin = 2;               // Digital pin for sensor
const unsigned long lockoutMs = 4000;  // Ignore further triggers for 4s
const unsigned long dotBlinkMs = 500;  // decimal blink during lockout

Adafruit_7segment matrix = Adafruit_7segment();

bool timerRunning = false;
unsigned long startTime = 0;
unsigned long elapsedTime = 0;
unsigned long lastTriggerTime = 0;

void setup() {
  pinMode(sensorPin, INPUT);  // use INPUT_PULLUP if sensor is open-collector
  matrix.begin(0x70);         // I2C addr
  matrix.setBrightness(15);
  showTime(0, true);  // start with 00.00
}

void loop() {
  static int lastState = LOW;
  static bool dotState = true;
  static unsigned long lastDotToggle = 0;

  int sensorState = digitalRead(sensorPin);
  unsigned long now = millis();

  // Rising edge detection
  if (sensorState == HIGH && lastState == LOW) {
    if (now - lastTriggerTime >= lockoutMs) {
      lastTriggerTime = now;
      if (!timerRunning) {
        timerRunning = true;
        startTime = millis();
      } else {
        timerRunning = false;
        elapsedTime = millis() - startTime;  // freeze
      }
    }
  }
  lastState = sensorState;

  // Update elapsed time if running
  if (timerRunning) {
    elapsedTime = millis() - startTime;
  }

  // Blink decimal point if in lockout
  bool dotOn = true;
  if (now - lastTriggerTime < lockoutMs) {
    if (now - lastDotToggle >= dotBlinkMs) {
      dotState = !dotState;
      lastDotToggle = now;
    }
    dotOn = dotState;
  }

  showTime(elapsedTime, dotOn);
}

// --- Show SS.hh on 4-digit display ---
void showTime(unsigned long ms, bool dotOn) {
  int hundredths = (ms / 10) % 100;  // 0-99
  int seconds = (ms / 1000) % 100;   // 0-99

  int tensSec = seconds / 10;
  int onesSec = seconds % 10;
  int tenths = hundredths / 10;
  int hundths = hundredths % 10;

  matrix.clear();
  matrix.writeDigitRaw(2, 0x02); // add colon RJ
  matrix.writeDigitNum(0, tensSec);
  matrix.writeDigitNum(1, onesSec, dotOn);  // decimal point after seconds
  matrix.writeDigitNum(3, tenths);
  matrix.writeDigitNum(4, hundths);
  matrix.writeDisplay();

}
