#include <Arduino.h>
const int trigPin = 5; // GPIO pin for the Trig of HC-SR04
const int echoPin = 18; // GPIO pin for the Echo of HC-SR04
const int ledPin = 2; // GPIO pin for the LED
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baud rate
pinMode(trigPin, OUTPUT); // Set the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Set the echoPin as an INPUT
pinMode(ledPin, OUTPUT); // Set the ledPin as an OUTPUT
digitalWrite(trigPin, LOW); // Initialize trigPin to LOW
delay(500); // Wait for 500 milliseconds to ensure the sensor is ready
}
void loop() {
long duration, distance;
// Trigger the sensor by sending a 10 microsecond pulse to the trigPin
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Read the pulse from echoPin
duration = pulseIn(echoPin, HIGH);
// Calculate the distance in cm
distance = duration * 0.0344 / 2;
// Print distance to the Serial Monitor
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
// Control the LED based on the distance
if (distance < 10) { // If distance is less than 10 cm
digitalWrite(ledPin, HIGH); // Turn on the LED
} else {
digitalWrite(ledPin, LOW); // Turn off the LED
}
delay(500); // Wait for 500 milliseconds before the next measurement
}Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1