print("This program integrate ESP32 with ultrasonic + oled\n")
#import all related module/library
import ultrasonic_lib
import ssd1306
from machine import Pin, SoftI2C, PWM
from utime import sleep
#Pin declaration on OLED
i2c_ssd1306 = SoftI2C(scl=Pin(22), sda=Pin(21))
#define the OLED variables
oled_width = 128 #based on spec
oled_height = 64 #based on spec
#use OOP(object oriented program) to create the object
#remarks: ;library name.class name(width, height, i2c)
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c)
#Declare pin connection for ultrasonic and
#Create an object for ultrasonic usip OOP (object oriented programming)
#Format OOP --> library name.class name()
ciku = ultrasonic_lib.HCSR04(trigger_pin=4, echo_pin=5, echo_timeout_us=500*2*30)
buzzer = PWM(Pin(18) ,Pin.OUT)
while True:
#Test sensor
jarak_in_mm = ciku.distance_mm()
jarak_in_cm = ciku.distance_cm()
#Display the distance value in mm and cm
print('The distance from an object in mm is: ', jarak_in_mm)
print('The distance from an object in cm is: ', jarak_in_cm)
print('-----------------------------------------------------')
print('\n')
#Display the distance value on oled screen
oled.fill(0)
oled.text('Object Detected', 0, 0, 1) # x-axis, y-axis, color font(1-white|0-black)
oled.text('jarak in mm', 0, 10, 1)
oled.text(str(jarak_in_mm), 0, 20, 1)
oled.text('mm', 40, 20, 1)
oled.text('jarak in cm', 0, 40, 1)
oled.text(str(jarak_in_cm), 0, 50, 1)
oled.text('cm', 70, 50, 1)
oled.show()
if jarak_in_cm < 100:
#making sound for buzzer
for i in range (5):
buzzer.init(freq=3510, duty=1204)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
elif 100<= jarak_in_cm <150:
for i in range (3):
buzzer.init(freq=3510, duty=1204)
sleep(1)
buzzer.init(freq=1, duty=0)
sleep(1)
else:
buzzer.init(freq=1, duty=0)
sleep(5)
Loading
ssd1306
ssd1306