/*
  Robotika – Course 44, Lesson 2 · BONUS
  Auto-brightness: the display dims itself in a dark room.

  Two senses working together — the light sensor decides how bright the
  distance display should be. map() again, this time: light -> brightness.

  Wiring: the Level 3 wiring (HC-SR04 + TM1637) PLUS the light sensor:
    Light module:  VCC -> 5V   GND -> GND   AO -> A0
*/

#include <TM1637Display.h>

const int LIGHT_PIN = A0;
const int TRIG_PIN  = 9;
const int ECHO_PIN  = 10;
const int CLK_PIN   = 4;
const int DIO_PIN   = 5;

TM1637Display display(CLK_PIN, DIO_PIN);

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

void loop() {
  int light = analogRead(LIGHT_PIN);           // 0..1023

  // turn the light reading into a display brightness level 0..7
  int brightness = map(light, 0, 1023, 0, 7);
  display.setBrightness(brightness);

  int distance = getDistanceCm();
  display.showNumberDec(distance);             // re-draw so the new brightness shows

  delay(150);
}

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;
}
