In this tutorial we will learn how to use an HC-SR04 reference ultrasonic distance sensor with the ESP32 board.
The assembly is disconcertingly simple:
For HC-SR04 sensor :
The 3.3V power supply from the ESP32 board goes to the VCC pin of the sensor.
The GND pin of the ESP32 board goes to the GND pin of the sensor.
Pin D5 of the ESP32 board goes to the TRIGGER pin of the sensor.
Pin D18 of the ESP32 board goes to the ECHO pin of the sensor.
For SSD1306 display:
the SCL pin to pin D22 of the ESP32 board
the VCC pin to the 3.3V pin of the ESP32 board
the GND pin to the GND pin of the ESP32 board
the SDA pin the D21 pin of the ESP32 card
Here is the program that displays the distance in cm that separates the ultrasonic sensor from an obstacle.
from hcsr04 import HCSR04
from machine import Pin,I2C
i2c = I2C(scl=Pin(22), sda=Pin(21)) #Init i2c oled=ssd1306.SSD1306_I2C(128,64,i2c,0x3c)
sensor = HCSR04(trigger_pin=5,echo_pin=18,echo_timeout_us=1000000)
distance = sensor.distance_cm() print(distance,' cm')
oled.show() #display the distance between the sensor and a detected obstacle