// Ultrasonic sensor pin definitions
#define TRIG_PIN 27
#define ECHO_PIN 26
// Timing variables to control the reading interval
unsigned long lastReadTime = 0;
const unsigned long readInterval = 1000; // Interval set to 1 seconds
void setup() {
Serial.begin(115200);
// Set TRIG as output (to send the pulse)
// and ECHO as input (to receive the reflected signal)
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
unsigned long currentTime = millis();
// Check if enough time has passed before taking a new reading
if (currentTime - lastReadTime >= readInterval) {
lastReadTime = currentTime;
// Send a 10 µs HIGH pulse to TRIG to start measurement
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Measure the duration of the HIGH pulse received at ECHO
long duration = pulseIn(ECHO_PIN, HIGH);
// Convert duration to distance (in cm)
// 0.0343 cm/µs is the speed of sound divided by 2 (go and return)
float distanceCm = duration * 0.0343 / 2;
// Print the measured distance to the Serial Monitor
Serial.println("=== Ultrasonic Sensor ===");
Serial.print("Distance: ");
Serial.print(distanceCm);
Serial.println(" cm");
Serial.println("=========================\n");
}
}