print('This program integrates ESP32 and Ultrasonic')
#1. Import Related library/module
import ultrasonic_library
from machine import Pin, SoftI2C, PWM #Pulse width modulation
import Oled_Library
from utime import sleep
#2. Declare Pinconnection of ultrasonic and create an object
#called pikachu using OOP (object Oriented Program)
#OOP format ----> library name.class name (.....)
#pikachu = ultrasonic_library.HCSR04(trigger_pin=27, echo_pin=26, echo_timeout_us=500*2*30)
pikachu = ultrasonic_library.HCSR04(27, 26, 30000)
#Declare Oled connection and create an object for oled --> screen
i2c_oled = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128 #based on spec
oled_height = 64 #based on spec
screen = Oled_Library.SSD1306_I2C(oled_width, oled_height, i2c_oled)
#declare buzzer connection
buzzer = PWM(Pin(5), Pin.OUT)
while True:
#let's test pikachu!!!
jarak_in_mm = pikachu.distance_mm()
jarak_in_cm = pikachu.distance_cm()
#Display the distance from the object
print ('Distance from an object is :', jarak_in_mm,'mm') #Choose mm if u want wholeh number
print ('Distance from an object is :', jarak_in_cm,'cm') #choose cm if u want fraction number
print ('--------------------------------------------')
print ('\n')
#let's test oled
#display on oled screen
screen.fill(0) #To make screen becoming white
screen.text('Object Detected:', 0, 0, ) #X-axis, Y-axis,
screen.text(str(jarak_in_mm,), 0, 10, )
screen.text('mm',50, 10, )
screen.text(str(jarak_in_cm), 0, 20, )
screen.text('cm',50, 20, )
screen.show()
#Making Decision on how 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(1)
buzzer.init(freq=1, duty=0)
sleep(0.3)
elif 500 <= jarak_in_mm <=1000:
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)
else:
buzzer.init(freq=1, duty=0)
sleep (1)