from hcsr04 import HCSR04
import ssd1306
from utime import sleep
from machine import I2C, Pin, PWM
import time
i2c = I2C(0, scl=Pin(22), sda=Pin(23))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
buzzer = PWM(Pin(2), Pin.OUT)
uss = HCSR04(trigger_pin=14, echo_pin=27, echo_timeout_us=1000000)
def sound_buzzer(frequency, duration_ms):
buzzer.freq(frequency)
buzzer.duty(512)
time.sleep(durtion_ms / 1000)
buzzer.duty(0)
while True:
distance = uss.distance_cm()
print(distance)
oled.fill(0)
oled.text("distance =",5 ,10)
oled.text('(:.2f)'.format(distance),5 ,30)
oled.show()
if distance <= 30:
sound_buzzer(700, 80)
else:
buzzer.duty(0)
time.sleep(0.1)