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; 

// The `soundSpeed` variable saves the velocity of sound in the air at 20ºC. We’re using the value in cm/uS
const float soundSpeed = 0.034;

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

  //  This tells the ESP32 to get ready to exchange messages with the Serial Monitor at a data rate of 9600 bits per second.  That’s 9600 binary ones or zeros per second, and is commonly called a baud rate.  
  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");
}

After that, save your code and upload your code to the microcontroller.

When your code uploads completely, you can see the Serial Monitor which is a console of your microcontroller by clicking the Magnifier icon at the top right of the screen.

In the Serial monitor you can change the speed of exchange messages with the Serial Monitor and microcontroller by clicking the dropdown at the bottom right of the screen. (The speed should be the same with your speed in the code Serial.begin(115200))

After that, The sensor measurements will be displayed in the Serial Monitor.

------ End of the 1st simple mini project ------