#MUHAMMAD HAZIQ BIN ROZMAN 52224121174
from machine import Pin, SoftI2C, time_pulse_us
import ssd1306
import time
# Set up the I2C interface and OLED display
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Set up the HC-SR04 sensor pins
trigger_pin = Pin(13, Pin.OUT)
echo_pin = Pin(12, Pin.IN)
def distance():
# Send a trigger signal to the sensor
trigger_pin.on()
time.sleep_us(100)
trigger_pin.off()
# Wait for the echo signal and calculate the distance
pulse_time = time_pulse_us(echo_pin, 1, 10000)
distance = pulse_time / 58.0
return distance
while True:
# Read the distance from the sensor
dist = distance()
# Display the distance on the OLED display
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text("{:.2f} cm".format(dist), 0, 20)
oled.show()
# Wait for a short time before measuring again
time.sleep(0.1)