Skip to main content

IoT Lab Day 1 (1st mini project)

ESP32 with Ultrasonic Sensor

The ultrasonic sensor uses sonar to determine the distance to an object. This sensor reads from 2cm to 400cm (0.8inch to 157inch) with an accuracy of 0.3cm (0.1inches), which is good for most hobbyist projects. In addition, this particular module comes with ultrasonic transmitter and receiver modules.

image.png

How Does the Ultrasonic Sensor Work?

1. The ultrasound transmitter (trig pin) emits a high-frequency sound (40 kHz).
2. The sound travels through the air. If it finds an object, it bounces back to the module.
3. The ultrasound receiver (echo pin) receives the reflected sound (echo).

image.png

Schematic – ESP32 with Ultrasonic Sensor

image.png

Wire the Ultrasonic sensor to the ESP32 as shown in the following schematic diagram. We’re connecting the Trig pin to GPIO 18 and the Echo pin to GPIO 5, but you can use any other suitable pins.

Code

const int trig = 18; // trigger pin
const int echo = 5; // echo pin
long duration, distance; 

const float soundSpeed = 0.034;

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  pinMode(echo, INPUT); // Set the echo pin to be an input
  pinMode(trig, OUTPUT); // Set the trig pin to be an output
}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(trig, LOW); // Clear the trig pin
  delayMicroseconds(5); 

  digitalWrite(trig, HIGH);  // Sets the trig pin on HIGH state for 10 micro seconds
  delayMicroseconds(10); 
  digitalWrite(trig, LOW);
  
  duration = pulseIn(echo, HIGH); // Read the value from echo pin

  distance = (duration * soundSpeed/2); // Calculate to centimeters.

  Serial.print(distance); 
  Serial.print(" cm\n");
}