Skip to content

Instantly share code, notes, and snippets.

@GettyOrawo
Created October 6, 2023 10:14
Show Gist options
  • Save GettyOrawo/a315ac99de50cbc5e3b2af0a251b014b to your computer and use it in GitHub Desktop.
Save GettyOrawo/a315ac99de50cbc5e3b2af0a251b014b to your computer and use it in GitHub Desktop.
const int TRIG_PIN = 4;
const int ECHO_PIN = 5;
const int BUZZER_PIN = 3;
const int DISTANCE_THRESHOLD = 30;
// variables will change:
float duration_us, distance_cm;
void setup() {
Serial.begin (9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;
if(distance_cm < DISTANCE_THRESHOLD)
digitalWrite(BUZZER_PIN, HIGH); // turn on Piezo Buzzer
else
digitalWrite(BUZZER_PIN, LOW); // turn off Piezo Buzzer
// print the value to Serial Monitor
Serial.print("distance: ");
Serial.print(distance_cm);
Serial.println(" cm");
delay(500);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment