print("This Program will intergrate ESP32 with ultrasonic sensor!")
#Import necessary modules/libraries
import hcsr04
import ssd1306
from utime import sleep
from machine import SoftI2C, Pin, PWM
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin = 13, echo_pin = 27, 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 = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)
buzzer = PWM(Pin(23), Pin.OUT)
while True:
jarak_in_cm = ultrasonic_sensor.distance_cm()
jarak_in_mm = ultrasonic_sensor.distance_mm()
print("Object Detected in = ", jarak_in_cm, "cm")
print("Object Detected in = ", jarak_in_mm, "mm")
print("------------------------------------------")
print("\n")
oled.fill(0)
oled.text('DISTANCE DETECT', 0, 0, 1)
oled.text(str(jarak_in_cm), 0, 10, 1)
oled.text("cm", 70, 10, 1)
oled.text(str(jarak_in_mm), 0, 30, 1)
oled.text("mm", 40, 30, 1)
oled.show()
if jarak_in_cm < 50:
for i in range (10):
buzzer.init(freq = 1703, duty = 400)
sleep(0.5)
buzzer.init(freq = 1, duty = 0)
sleep(0.5)
elif 50 <= jarak_in_cm < 150:
for i in range (10):
buzzer.init(freq = 6936, duty = 400)
sleep(0.5)
buzzer.init(freq = 1, duty = 0)
sleep(0.5)
else:
buzzer.init(freq = 1, duty = 0)
sleep(0.5)
sleep(5)