from machine import Pin, I2C, time_pulse_us
from ssd1306 import SSD1306_I2C
import time
# initialize SSD1306 OLED display
i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# initialize HC-SR04 sensor pins
trig_pin = Pin(4, Pin.OUT)
echo_pin = Pin(5, Pin.IN)
while True:
# trigger the sensor
trig_pin.value(0)
time.sleep_us(2)
trig_pin.value(1)
time.sleep_us(10)
trig_pin.value(0)
# measure the duration of the echo pulse
duration_us = time_pulse_us(echo_pin, 1)
# calculate the distance based on the duration
distance_cm = duration_us / 58.0
# display the distance on the SSD1306 OLED display
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text("{:.2f} cm".format(distance_cm), 0, 16)
oled.show()
time.sleep(1)