/*  Klingel-Sensor auf Arduino Nano ATmega168
 * 
 *  https://www.arduino.cc/en/Tutorial/BuiltInExamples/Button
 * 
 *  D2  -------------
 *          |       |
 *        Button    |
 *          |       |
 *  +5V -----       |
 *               10kOhm
 *                  |
 *  GND -------------
 */

const int ledPin = LED_BUILTIN;
const int buttonPin = 2; // Button connected to D2
const int flare_threshold = 200;
const int ring_delay = 250;

bool active = false;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
  Serial.println("Doorbell sensor");
}

void loop() {
  int val = digitalRead(buttonPin);

  if (val == HIGH) {
    delay(flare_threshold); // catch flares
    val = digitalRead(buttonPin);
    
    if (val == HIGH && active == false) {
      Serial.println("RING");
      digitalWrite(ledPin, HIGH);
      active = true;
      delay(ring_delay);
    }
    else if (val == LOW) {
      Serial.print("flare (<");
      Serial.print(flare_threshold);
      Serial.println(")");
    }
  } else {
    digitalWrite(ledPin, LOW);
    active = false;
  }
}
