#include <Adafruit_NeoPixel.h>

#define LED_PIN 20            // IR LED pin (2 before 30.5.25) 31.5: 20 did not work
#define SENSOR_PIN 4         // Analog input (D2, GPIO4 before 30.5.25) 31.5: GPIO6 D4 did not work
#define NEOPIXEL_PIN D6      // NeoPixel data pin 
#define NUM_PIXELS 20        // Number of NeoPixels
#define LED_COUNT_START 1    // Starting NeoPixel
#define PULSE_PIN 7         // D5 GPIO7 output pulse to another main board

Adafruit_NeoPixel strip(NUM_PIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);

unsigned long lastTriggerTime = 0;
const unsigned long cooldown = 3000; // 3 seconds cooldown

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
  pinMode(PULSE_PIN, OUTPUT);
  digitalWrite(PULSE_PIN, LOW);

  strip.begin();
  strip.clear();
  strip.show();
}

void loop() {
  // Turn LED off and read ambient
  digitalWrite(LED_PIN, LOW);
  delayMicroseconds(200);
  int off = analogRead(SENSOR_PIN);

  // Turn LED on and read reflected light
  digitalWrite(LED_PIN, HIGH);
  delayMicroseconds(200);
  int on = analogRead(SENSOR_PIN);

  int reflected = on - off;

  Serial.print("ON: ");
  Serial.print(on);
  Serial.print("  OFF: ");
  Serial.print(off);
  Serial.print("  REFLECTED: ");
  Serial.println(reflected);

  unsigned long now = millis();

  if ((reflected <= 0 && reflected >= -200) && (now - lastTriggerTime > cooldown)) {
    // Pulse to notify other ESP32-C3
    digitalWrite(PULSE_PIN, HIGH);
    delay(10);  // 10 ms pulse
    digitalWrite(PULSE_PIN, LOW);

    // NeoPixel effect
    colorWipe(strip.Color(255, 255, 255), 0);
    delay(5);
    colorWipe(strip.Color(255, 255, 0), 0);
    delay(10);
    colorWipe(strip.Color(0, 255, 0), 0);
    delay(10);
    colorWipe(strip.Color(100, 100, 0), 0);
    delay(20);
    colorWipe(strip.Color(50, 50, 0), 0);
    delay(40);
    strip.clear();
    strip.show();

    // Update cooldown
    lastTriggerTime = now;
  } else {
    strip.clear();
    strip.show();
  }

  delay(10);
}

void colorWipe(uint32_t color, int wait) {
  for (int i = LED_COUNT_START; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
    strip.show();
    delay(wait);
  }
}