print("This program integrates ESP32 with ultrasonic sensor ")
#Import all necessary module/librarian
import hcsar04 #the sensor library
from machine import Pin, SoftI2C, PWM #PWM = Pulse with modulation
import ssd1306
from utime import sleep
#declare the ultrasonic pin connection
#create object called ultrasonic using OOP(Object oriented Programming)
#OOP format is --> library name.class name()
ultrasonic_sensor = hcsar04.HCSR04( trigger_pin=12, echo_pin=14, echo_timeout_us=500*2*30)
#Pin declaration on OLED
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
#3. Define the OLED variables
oled_width = 128 #based on spec
oled_height = 64 #based on spec
#4. use OOP (object Oriented Programming) to create the object
#Remarks : object format --> library name.class name
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oled)
#declare buzzer Pin
buzzer = PWM(Pin(15), Pin.OUT)
while True:
#Let's test the ultrasonic sensor
object_detect_cm = ultrasonic_sensor.distance_cm()#Use this if u want decimal point
object_detect_mm = ultrasonic_sensor.distance_mm()#use this if u want whole number
#display the distance on serial monitor
print("Distance from an object in cm :",object_detect_cm)
print("Distance from an object in mm :",object_detect_mm)
print("-------------------------------------------------")
print("]\n")\
#display use object distance on LED
oled.fill(2)
oled.text('Object Detected:', 3, 0, 0)
oled.text(str(object_detect_cm), 0, 20, 0)
oled.text('cm',70,20,0)
oled.text(str(object_detect_mm), 0, 40, 0)
oled.text('mm',70,40,0)
#(x axis, y axis, 1 = white, 0 = black)
oled.show()
if object_detect_cm > 150:
buzzer.init(freq = 1, duty = 0)
else:
for i in range (5):
buzzer.init(freq = 534, duty = 614)
sleep(0.5)
buzzer.init(freq = 1, duty = 0)
sleep(1)
buzzer.init(freq = 534, duty = 614)
sleep(0.5)
buzzer.init(freq = 1, duty = 0)
sleep(1)
sleep(2)