Last active
December 14, 2025 21:02
-
-
Save sarvagnakadiya/8591b20b52d9f9e0b3faae78e6011f34 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #define TRIG_PIN 9 | |
| #define ECHO_PIN 10 | |
| #define ALERT_PIN 13 | |
| int distance; | |
| int blinkDelay; | |
| void setup() { | |
| pinMode(TRIG_PIN, OUTPUT); | |
| pinMode(ECHO_PIN, INPUT); | |
| pinMode(ALERT_PIN, OUTPUT); | |
| Serial.begin(9600); | |
| } | |
| void loop() { | |
| // Measure distance | |
| digitalWrite(TRIG_PIN, LOW); | |
| delayMicroseconds(2); | |
| digitalWrite(TRIG_PIN, HIGH); | |
| delayMicroseconds(10); | |
| digitalWrite(TRIG_PIN, LOW); | |
| long duration = pulseIn(ECHO_PIN, HIGH); | |
| distance = duration * 0.034 / 2; | |
| Serial.print("Distance: "); | |
| Serial.println(distance); | |
| // Decide blink speed based on distance | |
| if (distance > 30) { | |
| blinkDelay = 0; // No blink - OFF | |
| } | |
| else if (distance > 20) { | |
| blinkDelay = 400; // Slow | |
| } | |
| else if (distance > 10) { | |
| blinkDelay = 200; // Medium | |
| } | |
| else if (distance > 5) { | |
| blinkDelay = 100; // Fast | |
| } | |
| else { | |
| blinkDelay = -1; // Constant ON (under 5cm) | |
| } | |
| // Blink LED or keep constant | |
| if (blinkDelay == -1) { | |
| // Constant ON for very close objects | |
| digitalWrite(ALERT_PIN, HIGH); | |
| delay(50); | |
| } | |
| else if (blinkDelay > 0) { | |
| // Blink | |
| digitalWrite(ALERT_PIN, HIGH); | |
| delay(blinkDelay); | |
| digitalWrite(ALERT_PIN, LOW); | |
| delay(blinkDelay); | |
| } | |
| else { | |
| // OFF | |
| digitalWrite(ALERT_PIN, LOW); | |
| delay(50); | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#define TRIG_PIN 9
#define ECHO_PIN 10
#define ALERT_PIN 6
long duration;
int distance;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(ALERT_PIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
// Ultrasonic trigger
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH, 30000);
if (duration == 0) return;
distance = duration * 0.034 / 2;
// -------- ALERT LOGIC --------
if (distance > 50) {
digitalWrite(ALERT_PIN, LOW); // OFF
}
else if (distance > 30) {
// Slow beep
digitalWrite(ALERT_PIN, HIGH);
delay(500);
digitalWrite(ALERT_PIN, LOW);
delay(500);
}
else if (distance > 15) {
// Fast beep
digitalWrite(ALERT_PIN, HIGH);
delay(200);
digitalWrite(ALERT_PIN, LOW);
delay(200);
}
else {
// Very close → continuous
digitalWrite(ALERT_PIN, HIGH);
}
}