05/29/2023
Writing about Distance Sensor HC-SR04 With Arduino for educational and informational purposes only. however, do not hesitate to use this information on your own risk as we make no warranty of any kind.
Connect distance sensor HC-SR04 with Arduino
const int trigPin = 7; // Trigger Pin
const int echoPin = 6; // Echo Pin
const long dist = 5; // This is the distance to turn on the LED
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distinches;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distinches = duration / 74 / 2;
if (distinches < dist) {
digitalWrite(LED_BUILTIN, HIGH); // turn the LED
delay(100);
} else {
digitalWrite(LED_BUILTIN, LOW); // turn the LED off
delay(100);
}
}
const int trigPin = 7; // Trigger Pin
const int echoPin = 6; // Echo Pin
const long dist = 5; // This is the distance to turn on the LED
int timer = 0;
void setup() {
pinMode(13, OUTPUT);
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
long duration, distinches;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distinches = duration / 74 / 2;
if (distinches < dist) {
digitalWrite(13, HIGH); //Turn On Blue
digitalWrite(12, LOW); //Turn Off Green
if (timer > 5 && timer < 10) {
digitalWrite(11, HIGH); //Turn On Yellow
}
if (timer > 9) {
digitalWrite(10, HIGH); //Turn On Red
}
} else {
digitalWrite(13, LOW); //Turn Off Blue
digitalWrite(12, HIGH); //Turn On Green
digitalWrite(11, LOW); //Turn Off Yellow
digitalWrite(10, LOW); //Turn Off Red
timer = 0; // Timer Reset
}
delay(1000);
timer = timer + 1; //Timer +1
}