# import all related module
from machine import Pin, SoftI2C, PWM
import hcsr04
import oled
from utime import sleep
# declare pin connection for ultrasonic
# create an object for ultrasonic using oop
# format oop --> library.name.class name()
abu = hcsr04.HCSR04(trigger_pin=27, echo_pin=26, echo_timeout_us=500*2*30)
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64 #based on spec
oled = oled.SSD1306_I2C(oled_width, oled_height, i2c_oled)
buzzer = PWM(Pin(33), Pin.OUT) #buzzer
while True:
# test abu
jarak_in_mm = abu.distance_mm()
jarak_in_cm = abu.distance_cm()
# oled
oled.fill(0)
oled.text('object detected', 0, 0, 1)
oled.text(str(jarak_in_cm), 0, 30, 1)
oled.text('cm', 70, 30, 1)
oled.text(str(jarak_in_mm), 0, 50, 1)
oled.text('mm', 40, 50, 1)
oled.show()
# making decision
if jarak_in_cm <= 200:
for i in range (5):
buzzer.init(freq=800, duty=300)
sleep(1)
buzzer.init(freq=1, duty=0)
sleep(1)
elif 100 <= jarak_in_cm:
for i in range (5):
buzzer.init(freq=400, duty=300)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
else:
buzzer.init(freq=1,duty=0)
# display distance serial monitor
print("the distance from object in mm:",jarak_in_mm)
print("the distance from object in cm:",jarak_in_cm)
print('----------------------------------------')
print('\n')
# making buzzer sound
sleep(5)