/*
  Robotika – Course 44, Lesson 2
  Level 4: A car parking sensor — everything from today, together

    SENSE  -> the distance (the function from Level 3)
    THINK  -> IF we are far: all clear, LED off.
              ELSE we are in the warning zone: blink FASTER the closer we get.
    ACT    -> the display shows the number; a warning LED blinks.

  New helper: map() rescales one range onto another. Here it turns a
  distance of 0..WARN_CM into a blink delay of 40..500 ms — closer = faster.

  Wiring (add a warning LED to the Level 3 setup):
    LED long leg (+)  -> 220 ohm resistor -> D6
    LED short leg (-) -> GND
*/

#include <TM1637Display.h>

const int TRIG_PIN = 9;
const int ECHO_PIN = 10;
const int CLK_PIN  = 4;
const int DIO_PIN  = 5;
const int LED_PIN  = 6;

const int WARN_CM = 30;        // the warning zone begins at this distance (cm)

TM1637Display display(CLK_PIN, DIO_PIN);

void setup() {
  Serial.begin(9600);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);
  display.setBrightness(5);
}

void loop() {
  int distance = getDistanceCm();
  display.showNumberDec(distance);

  // ---- the decision ----
  if (distance > WARN_CM) {
    digitalWrite(LED_PIN, LOW);                      // far away -> all clear
    delay(100);
  } else {
    // inside the zone: blink, and the closer we are the faster it blinks
    int blinkDelay = map(distance, 0, WARN_CM, 40, 500);
    digitalWrite(LED_PIN, HIGH);
    delay(blinkDelay);
    digitalWrite(LED_PIN, LOW);
    delay(blinkDelay);
  }
}

int getDistanceCm() {
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH, 25000);
  if (duration == 0) return 999;
  return duration * 0.0343 / 2;
}
