// HC-SR04 Ultrasonic Distance Sensor with 7 Segment Display

#include <SevSeg.h>

#define TRIG_PIN A3
#define ECHO_PIN A4

SevSeg sevseg;

uint16_t duration = 0;
uint32_t interval = 0;

float distance = 0;

void setup()
{
  uint8_t numDigits = 4;
  uint8_t digitPins[] = {2, 3, 4, 5};
  uint8_t segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  uint8_t displayType = COMMON_ANODE; // (Common Anode or Common Cathode)

  bool resistorsOnSegments = false;
  bool updateWithDelays = false;
  bool leadingZeros = false;
  bool disableDecPoint = false;

  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sevseg.begin(displayType, numDigits, digitPins, segmentPins, resistorsOnSegments,
               updateWithDelays, leadingZeros, disableDecPoint);
  sevseg.setBrightness(90);
}

void loop()
{
  if ((millis() - interval) >= 100) {
    interval = millis();

    digitalWrite(TRIG_PIN, LOW);
    delayMicroseconds(5);
    digitalWrite(TRIG_PIN, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIG_PIN, LOW);

    // Read time of the trig and echo pins
    duration = pulseIn(ECHO_PIN, HIGH);

    // Calculates the distance
    distance = (duration / 2) / 29;

    sevseg.setNumber(distance);
  }

  sevseg.refreshDisplay();
}