ULTRASONIC sensor is  popular in many applications where measuring distance or sensing objects are required.

The module has two eyes in the front which forms the Ultrasonic transmitter and Receiver.



1.Vcc  The Vcc pin powers the sensor, typically with +5V,The current consumed by the sensor is less than 15mA


Trigger pin is an Input pin. This pin has to be kept high for 10us to initialize measurement by sending Ultrasonic burst of 40KHz.


Echo pin is an Output pin. This pin goes high for a period of time which will be equal to the time taken for the US wave to return back from object to the sensor.


To start the measurement, the trigger pin has to be made high for 10uS and then turned off.

This action will trigger an ultrasonic wave at frequency of 40Hz from the transmitter and the receiver will wait for the wave to return.

Once the wave is returned after it getting reflected by any object the Echo pin goes high for a particular amount of time which will be equal to the time taken for the wave to return back to the sensor.

The amount of time during which the Echo pin stays high is measured by the esp32 as it gives the information about the time taken for the wave to return back to the Sensor. Using this information the distance is measured

As the ultrasonic sensor requires 5v , we use a separate power source.

This sensor will not operate on 3.3v.

Vcc –> 5v

Gnd to Gnd

Trigger –> GPIO 5

Echo  –>  GPIO 18

Both Gnd of 3.3v & that of 5v to be made common.

As the ECHO PIN of ultrasonic gives 5v level , we need a LEVEL SHIFTER in between ECHO & GPIO18




OLED connections :

Vcc to 3.3v

Gnd – Gnd

SCL –> GPIO 22

SDA –> GPIO 21

We use THONNY PYTHON to test and upload code.

2 library modules are required.

One ssd1306.py for OLED

hcsr04.py module for ultrasonic measurement support.

Download the files from :



From ThonnyPython File –> open and browse to the location to select ssd1306.py

Save it to Micropython device as ssd1306.py

Image 14[5]

Same way import the hcsr04.py

and save it on Micropython device.

Image 12

Sample code is provided as main.py

After saving these file , the ESP32 has 4 files





Image 15

Image 10

In the example code

we import classes Pin,I2C

Then we import modules ssd1306, hcsr04 and time

i2c is initiated with scl pin GPIO22 &  sda pin GPIO21

oled object is initiated by passing arguments width 128, height 64, protocol i2c and address 0x3c.

ultrasonic sensor object is instantiated from HCSR04 Class by passing on trigger pin GPIO5

Echo pin GPIO18

Inside never ending loop

distance_cm() method used to measure distance

oled.text() method to display result on OLED.

Note the conversion to STRING variable while dusplaying on OLED.

Image 11


Click on F5 to execute.

The OLED will display the sensor distance reading.