/*
HC-SR04 Ultrasonic Sensor Example.
Turn the LED on when an object is within 100cm range.
Copyright (C) 2021, Uri Shaked
*/
#define ECHO_PIN 2
#define TRIG_PIN 3
#define LEDRED 13
#define LEDGREEN 12
void setup() {
Serial.begin(115200);
pinMode(LEDRED, OUTPUT);
pinMode(LEDGREEN, OUTPUT);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
digitalWrite(LEDRED,LOW);
digitalWrite(LEDGREEN,LOW);
}
float readDistanceCM() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
int duration = pulseIn(ECHO_PIN, HIGH);
return duration * 0.034 / 2;
}
void loop() {
float distance = readDistanceCM();
if(distance <= 100)
{
digitalWrite(LEDRED, HIGH);
digitalWrite(LEDGREEN, LOW);
Serial.println("LED RED ON / LED GREEN OFF");
delay(1000);
}
if(distance > 100)
{
digitalWrite(LEDRED, LOW);
digitalWrite(LEDGREEN, HIGH);
Serial.println("LED RED OFF / LED GREEN ON");
delay(1000);
}
Serial.print("Measured distance: ");
Serial.println(distance);
delay(100);
}