Cirkit Designer LogoCirkit DesignerYour all-in-one circuit design IDE Launch Cirkit Designer App

ESP32-Controlled Ultrasonic Distance Measurement with Relay-Activated Pilot Lamps

View and Edit Project In Cirkit DesignerImage of ESP32-Controlled Ultrasonic Distance Measurement with Relay-Activated Pilot Lamps

Circuit Documentation

Summary

The circuit in question is designed to interface an ESP32 microcontroller with various components including HC-SR04 Ultrasonic Sensors, Pilot Lamps (Green, Red, and Blue), and multiple 2 Channel 12V Relays. The ESP32 is responsible for controlling the relays based on the input from the ultrasonic sensors and indicating the system status through the pilot lamps. The circuit is powered by a 12V battery, which also supplies power to the relays.

Component List

ESP32 (30 pin)

Pilot Lamp Green

Pilot Lamp Red

HC-SR04 Ultrasonic Sensor

2 Channel 12V Relay

Pilot Lamp Blue

12V Battery

Wiring Details

ESP32 (30 pin)

Pilot Lamp Green

Pilot Lamp Red

HC-SR04 Ultrasonic Sensor

2 Channel 12V Relay

Pilot Lamp Blue

12V Battery

Documented Code

Code for ESP32 (30 pin)

const int trigPin = 12;
const int echoPin = 13;
const int relayGreen1 = 14;

// Define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701

long duration;
int distanceCm;
int distanceInch;

void setup() {
  Serial.begin(115200);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);  // Sets the echoPin as an Input

  pinMode(relayGreen1, OUTPUT);
}

void loop() {
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance
  distanceCm = duration * SOUND_SPEED / 2;
  
  // Convert to inches
  distanceInch = distanceCm * CM_TO_INCH;
  
  // Prints the distance in the Serial Monitor
  Serial.print("Distance (cm): ");
  Serial.println(distanceCm);
  Serial.print("Distance (inch): ");
  Serial.println(distanceInch);
  
  // Normally Open configuration, send LOW signal to let current flow
  digitalWrite(relayGreen1, LOW);
  Serial.println("Current Flowing");
  delay(5000);
  
  // Normally Open configuration, send HIGH signal to stop current flow
  digitalWrite(relayGreen1, HIGH);
  Serial.println("Current not Flowing");
  delay(5000);
}

(Note: The code provided is associated with the ESP32 microcontroller and is intended to control a relay based on the distance measured by the ultrasonic sensor. The code includes setup and loop functions that initialize the pins and perform the distance measurement and relay control in a continuous loop. The relay is activated for 5 seconds and then deactivated for 5 seconds in a repeating cycle.)