/*
* This ESP32 code is created by esp32io.com
*
* This ESP32 code is released in the public domain
*
* For more detail (instruction and wiring diagram), visit https://esp32io.com/tutorials/esp32-ultrasonic-sensor-servo-motor
*/
#include <ESP32Servo.h>
#define TRIG_PIN 23 // ESP32 pin GPIO23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN 22 // ESP32 pin GPIO22 connected to Ultrasonic Sensor's ECHO pin
#define TRIG_PIN1 17 // ESP32 pin GPIO23 connected to Ultrasonic Sensor's TRIG pin
#define ECHO_PIN1 16 // ESP32 pin GPIO22 connected to Ultrasonic Sensor's ECHO pin
#define SERVO_PIN 26 // ESP32 pin GPIO26 connected to Servo Motor's pin
//#define BUTTON_PIN 27
#define LED_PIN 14
#define DISTANCE_THRESHOLD 60 // centimeters
Servo servo; // create servo object to control a servo
// variables will change:
float duration_us, distance_cm, duration_us1, distance_cm1;
//int led_state = LOW; // the current state of LED
//int button_state; // the current state of button
//int last_button_state; // the previous state of button
void setup() {
Serial.begin (9600); // initialize serial port
pinMode(LED_PIN, OUTPUT);
//pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(TRIG_PIN, OUTPUT); // set ESP32 pin to output mode
pinMode(ECHO_PIN, INPUT); // set ESP32 pin to input mode
pinMode(TRIG_PIN1, OUTPUT); // set ESP32 pin to output mode
pinMode(ECHO_PIN1, INPUT); // set ESP32 pin to input mode
servo.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object
servo.write(0);
}
void loop() {
// generate 10-microsecond pulse to TRIG pin
digitalWrite(TRIG_PIN, HIGH);
digitalWrite(TRIG_PIN1, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
digitalWrite(TRIG_PIN1, LOW);
// digitalWrite(TRIG_PIN1, HIGH);
// delayMicroseconds(10);
// digitalWrite(TRIG_PIN1, LOW);
//last_button_state = button_state; // save the last state
//button_state = digitalRead(BUTTON_PIN); // read new state
// measure duration of pulse from ECHO pin
duration_us = pulseIn(ECHO_PIN, HIGH);
duration_us1 = pulseIn(ECHO_PIN1, HIGH);
// calculate the distance
distance_cm = 0.017 * duration_us;
distance_cm1 = 0.017 * duration_us1;
if ((distance_cm < DISTANCE_THRESHOLD) && (distance_cm1 < DISTANCE_THRESHOLD)){
servo.write(90); // rotate servo motor to 90 degree
digitalWrite(LED_PIN, HIGH);
}
else{
servo.write(0); // rotate servo motor to 0 degree
digitalWrite(LED_PIN, LOW);
}
// print the value to Serial Monitor
// Serial.print("distance: ");
// Serial.print(distance_cm);
// Serial.println(" cm");
delay(500);
}