const int pingpin = 27;
const int echopin =26;
const int buzz =25;
void setup() {
Serial.begin(115200);
pinMode(pingpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(buzz, OUTPUT);
}
void loop() {
long duration;
float inches, cm;
// Send ultrasonic pulse
digitalWrite(pingpin, LOW);
delayMicroseconds(2);
digitalWrite(pingpin, HIGH);
delayMicroseconds(10);
digitalWrite(pingpin, LOW);
// Measure the duration of the echo pulse
duration = pulseIn(echopin, HIGH);
// Check if the sensor is out of range
if (duration == 0) {
Serial.println("Out of range");
digitalWrite(buzz, LOW);
return;
}
// Convert duration to inches and centimeters
inches = microsecondsToInches(duration);
cm = microsecondsToCentimeters(duration);
// Activate buzzer if an object is closer than 100 cm
if (cm < 100) {
digitalWrite(buzz, HIGH);
} else {
digitalWrite(buzz, LOW);
}
// Print measurements to the Serial Monitor
Serial.print(inches);
Serial.print(" in, ");
Serial.print(cm);
Serial.println(" cm");
delay(100);
}
// Function to convert duration to inches
float microsecondsToInches(long microseconds) {
return microseconds / 74.0 / 2.0;
}
// Function to convert duration to centimeters
float microsecondsToCentimeters(long microseconds) {
return microseconds / 29.0 / 2.0;
}
// Define the servo object
ServoESP32 myServo;
// Define the servo pin
#define SERVO_PIN 18 // Change based on your wiring
void setup() {
Serial.begin(115200);
// Attach the servo to a pin with a frequency of 50Hz
myServo.attach(SERVO_PIN, 500, 2400); // 500-2400 µs pulse width range
Serial.println("Servo Ready!");
}
void loop() {
// Move servo to 0 degrees
myServo.write(0);
Serial.println("Servo at 0°");
delay(1000);
// Move servo to 90 degrees
myServo.write(90);
Serial.println("Servo at 90°");
delay(1000);
// Move servo