from machine import Pin, I2C
import ssd1306
from hcsr04 import HCSR04
from time import sleep
# OLED display I2C pins
i2c = I2C(-1, scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
# HC-SR04 sensor
sensor = HCSR04(trigger_pin=13, echo_pin=12)
# Buzzer
buzzer = Pin(2, Pin.OUT)
def measure_distance():
distance = sensor.distance_cm()
print('distance' , distance, "CM")
sleep(0.1)
oled.fill(0)
oled.text('Distance:', 0, 0)
oled.text(str(distance) + ' cm', 0, 10)
oled.show()
if distance < 150: # distance threshold in cm
buzzer.on()
else:
buzzer.off()
sleep(1)
while True:
measure_distance()