0% found this document useful (0 votes)
3 views2 pages

Coding

This code controls a servo motor using an ESP32 and an ultrasonic distance sensor. It sends an ultrasonic pulse to measure distance and opens the servo if an object is detected within 20 cm, otherwise, it keeps the servo closed. The distance is printed to the serial monitor every 500 milliseconds.

Uploaded by

mannnybabe3307
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Coding

This code controls a servo motor using an ESP32 and an ultrasonic distance sensor. It sends an ultrasonic pulse to measure distance and opens the servo if an object is detected within 20 cm, otherwise, it keeps the servo closed. The distance is printed to the serial monitor every 500 milliseconds.

Uploaded by

mannnybabe3307
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

CODING :

#include <ESP32Servo.h>
#define TRIG_PIN 5
#define ECHO_PIN 18
#define SERVO_PIN 13
Servo myServo;
long duration;
float distance;
void setup() {
[Link](115200);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
[Link](SERVO_PIN);
// Initially closed
[Link](0);
}
void loop() {
// Send ultrasonic pulse
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
// Read echo time
duration = pulseIn(ECHO_PIN, HIGH);
// Calculate distance
distance = duration * 0.034 / 2;
[Link]("Distance: ");
[Link](distance);
[Link](" cm");
// If object within 20 cm
if (distance <= 20) {
[Link]("OPEN");
[Link](90); // Open position
}
else {
[Link]("CLOSE");
[Link](0); // Close position
}
delay(500);
}

You might also like