// Pin definitions for ultrasonic sensor
const int trigPin = 9;
const int echoPin = 10;

// 7-segment display pin definitions
const int segmentPins[7] = {2, 3, 4, 5, 6, 7, 8}; // Assuming segments a to g
const int digitPins[3] = {11, 12, 13}; // Assuming digits for hundreds, tens, and ones

// Digit patterns for 7-segment display (common cathode)
const byte digitPatterns[10] = {
  0b00111111, // 0
  0b00000110, // 1
  0b01011011, // 2
  0b01001111, // 3
  0b01100110, // 4
  0b01101101, // 5
  0b01111101, // 6
  0b00000111, // 7
  0b01111111, // 8
  0b01101111  // 9
};

void setup() {
  // Initialize ultrasonic sensor pins
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);

  // Initialize 7-segment display pins
  for (int i = 0; i < 7; i++) {
    pinMode(segmentPins[i], OUTPUT);
    digitalWrite(segmentPins[i], LOW);
  }
  for (int i = 0; i < 3; i++) {
    pinMode(digitPins[i], OUTPUT);
    digitalWrite(digitPins[i], LOW);
  }

  // Initialize serial communication for debugging
  Serial.begin(9600);
}

void loop() {
  // Measure distance
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;

  // Limit distance to 999
  if (distance > 999) {
    distance = 999;
  }

  // Extract digits
  int hundreds = distance / 100;
  int tens = (distance % 100) / 10;
  int ones = distance % 10;

  // Display digits using multiplexing
  displayDigit(0, hundreds);
  delay(5);
  displayDigit(1, tens);
  delay(5);
  displayDigit(2, ones);
  delay(5);
}

void displayDigit(int digitIndex, int number) {
  // Turn off all digits
  for (int i = 0; i < 3; i++) {
    digitalWrite(digitPins[i], LOW);
  }

  // Set the segments to display the number
  byte pattern = digitPatterns[number];
  for (int i = 0; i < 7; i++) {
    digitalWrite(segmentPins[i], bitRead(pattern, i));
  }

  // Turn on the current digit
  digitalWrite(digitPins[digitIndex], HIGH);

  // Wait a bit to make sure the digit is visible
  delay(1);

  // Turn off the digit again
  digitalWrite(digitPins[digitIndex], LOW);
}