print("This program integrates ESP32 + Ultrasonic Seonsor")
#import related library/modules
import ultrasonic_library
from machine import Pin, SoftI2C, PWM #Pulse With Modulation
import oled_lib
from utime import sleep
#Declare pin connection of ultrasonic and create an object
#called ultraman using OOP (object Oriented Programming)
#OOP format --> library name.class name(.....)
ultraman = ultrasonic_library.HCSR04(trigger_pin=13, echo_pin=14, echo_timeout_us=500*2*30)
#Declare oled connection and create object for lec screen -->
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64 #based on spec
screen = oled_lib.SSD1306_I2C(oled_width, oled_height, i2c_oled)
#Declare buzzer connection
buzzer = PWM(Pin(23), Pin.OUT)
while True:
#Let's test ultraman!
jarak_in_mm = ultraman.distance_mm()
jarak_in_cm = ultraman.distance_cm()
#Display the distance from the object
print('Distance from an object is :', jarak_in_mm, 'mm') #choose mm if u want whole number
print('Distance from an object is :', jarak_in_cm, 'cm') #choose cm if u want fraction number
print('..........................................')
print('\n')
#5. Let's test the OLED
#Remark: The font color is default set to 1 (white)
#Create text to be displayed on OLED screen
screen.fill(0)
screen.text('Object detected',0,0,1) # x-axis, y-axis
screen.text(str(jarak_in_mm), 5, 20,1)
screen.text('mm',40,20,1)
screen.text(str(jarak_in_cm), 5, 40,1)
screen.text('cm',70,40,1)
screen.show()
#making decision on how close the car with an object
if jarak_in_mm < 500:
for i in range (10):
#Turn on the buzzer
buzzer.init(freq=1500, duty=300)
sleep(0.3)
buzzer.init(freq=1, duty=0)
sleep(0.3)
elif 500 <= jarak_in_mm <=1000:
for i in range (5):
#Turn on the buzzer
buzzer.init(freq=1500, duty=300)
sleep(0.8)
buzzer.init(freq=1, duty=0)
sleep(0.8)
else:
buzzer.init(freq=1, duty=0)
sleep(5)