#include <TM1637.h>
#define trigPin 2
#define echoPin 4
#define clockPin 5
#define dataPin 18
const int digits[] = {0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F};
long duration;
int distance;
TM1637 display(clockPin, dataPin);
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(115200);
display.init();
display.setBrightness(10);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
// Print the distance to the serial monitor
Serial.print("Distance: ");
Serial.println(distance);
// Display the distance on the seven-segment display
int digit1 = distance / 10; // Extract the tens digit
int digit2 = distance % 10; // Extract the units digit
// Determine which digit to blink based on the distance range
int blinkDigit = -1;
if (distance >= 0 && distance <= 40) {
blinkDigit = 0;
} else if (distance >= 41 && distance <= 80) {
blinkDigit = 1;
} else if (distance >= 81 && distance <= 120) {
blinkDigit = 2;
} else if (distance >= 121 && distance <= 160) {
blinkDigit = 3;
} else if (distance >= 161 && distance <= 200) {
blinkDigit = 4;
} else if (distance >= 201 && distance <= 240) {
blinkDigit = 5;
} else if (distance >= 241 && distance <= 280) {
blinkDigit = 6;
} else if (distance >= 281 && distance <= 320) {
blinkDigit = 7;
} else if (distance >= 321 && distance <= 360) {
blinkDigit = 8;
} else if (distance >= 361 && distance <= 400) {
blinkDigit = 9;
}
if (blinkDigit != -1) {
// Blink the selected digit
for (int i = 0; i < 5; i++) {
display.display(digits[blinkDigit]);
delay(250);
display.display(0x00); // Turn off the digit
delay(250);
}
} else {
// Display the distance normally if it doesn't fall into any range
display.display(digits[digit1] << 8 | digits[digit2]);
}
delay(100);
}