print("This program will intergrate esp32 w ultrasonic sensor")
from machine import SoftI2C, Pin, PWM #PWM =pulse width
import hcsr04
from utime import sleep
import ssd1306
buzzer = PWM(Pin(23), Pin.OUT)
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)
#create an object called ultrasonic_sensor using OOP(Obcject Orientd Programming)
#OOP format is --> library name.class name(....)
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=13, echo_pin=27, echo_timeout_us=500*2*30)
while True:
#lets test our ultrasonic sensor
deeztance_in_cm = ultrasonic_sensor.distance_cm() #use when u need decimal num
deeztance_in_mm = ultrasonic_sensor.distance_mm() #use when whole num
#display on serial monitor
print("An object is detected in:", deeztance_in_cm, "cm")
print("An object is detected in:", deeztance_in_mm, "mm")
print("----------------------------------------------------")
print("\n")
oled.fill(0)
oled.text("Object detected:", 0, 10, 1)
oled.text(str(deeztance_in_cm), 0, 30, 1)
oled.text('cm', 100, 30, 1)
oled.text(str(deeztance_in_mm), 0, 50, 1)
oled.text('mm', 100, 50, 1)
oled.show()
if deeztance_in_cm < 50:
for i in range (5):
buzzer.init(freq=420, duty=420)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
elif 50 <= deeztance_in_cm < 150:
for i in range (5):
buzzer.init(freq=696, duty=696)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
else:
buzzer.init(freq=1, duty=0)
sleep(5)