from machine import Pin, I2C, time_pulse_us
import ssd1306
import time
# Initialize I2C
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
# Initialize OLED Display
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Initialize HC-SR04
trigger = Pin(23, Pin.OUT)
echo = Pin(19, Pin.IN)
def get_distance():
# Send a 10µs pulse to trigger
trigger.value(0)
time.sleep_us(2)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Measure the duration of the echo pulse
duration = time_pulse_us(echo, 1) # 1 for rising edge
distance = (duration * 0.0343) / 2 # Convert duration to distance in cm
return distance
while True:
distance = get_distance()
# Clear the display
oled.fill(0)
# Display distance
oled.text('Distance:', 0, 0)
oled.text('{:.2f} cm'.format(distance), 0, 10)
# Update display
oled.show()
# Wait for a bit before the next measurement
time.sleep(1)