/**
ESP32 + DHT22 Example for Wokwi
https://wokwi.com/arduino/projects/322410731508073042
*/
/*********
Rui Santos
Complete project details at https://RandomNerdTutorials.com/esp32-hc-sr04-ultrasonic-arduino/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
*********/
#include <ESP32Servo.h>
Servo myservo; // create servo object to control a servo
int pos = 0; // variable to store the servo position
// First HC-SR04 Sensor Pins
const int trigPin = 12;
const int echoPin = 27;
// Second HC-SR04 Sensor Pins
const int trigPin2 = 25;
const int echoPin2 = 33;
// Relay Pin
const int relayPin = 26;
// Define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration, duration2;
float distanceCm, distanceCm2;
float distanceInch, distanceInch2;
void setup() {
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(trigPin2, OUTPUT); // Sets the trigPin2 as an Output
pinMode(echoPin2, INPUT); // Sets the echoPin2 as an Input
pinMode(relayPin, OUTPUT); // Sets the relayPin as an Output
myservo.attach(13); // attaches the servo on pin 13 to the servo object
}
void loop() {
// First HC-SR04 Sensor
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distanceCm = duration * SOUND_SPEED/2;
distanceInch = distanceCm * CM_TO_INCH;
Serial.print("Distance 1 (cm): ");
Serial.println(distanceCm);
// Second HC-SR04 Sensor
digitalWrite(trigPin2, LOW);
delayMicroseconds(2);
digitalWrite(trigPin2, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin2, LOW);
duration2 = pulseIn(echoPin2, HIGH);
distanceCm2 = duration2 * SOUND_SPEED/2;
distanceInch2 = distanceCm2 * CM_TO_INCH;
Serial.print("Distance 2 (cm): ");
Serial.println(distanceCm2);
// Control Servo
if(distanceCm < 50) {
myservo.write(180);
delay(15);
} else {
myservo.write(90);
delay(15);
}
// Control Relay
if(distanceCm2 > 50) {
digitalWrite(relayPin, HIGH); // Turn on relay if distance is more than 50 cm
} else {
digitalWrite(relayPin, LOW); // Turn off relay otherwise
}
delay(1000);
}