#This is a program for a car reverse sensor system.
print("By Afif for IOT BEB 34303:")
# STEP 1: import library for ultrasonic sensor, OLED
import hcsr04 #import ultrasonic sensor library
import ssd1306
from machine import SoftI2C, PWM, Pin
from time import sleep
#STEP 2: DECLARE CONNECTION
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=5, echo_pin=18, echo_timeout_us=500*2*30)
oled_display = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, oled_display)
#STEP 2: Declare the connection of the buzzer
buzzer = PWM(Pin(23), Pin.OUT)
#STEP 3: The process
while True:
#for ultrasonic sensor on the terminal
distance_in_cm = ultrasonic_sensor.distance_cm()
distance_in_mm = ultrasonic_sensor.distance_mm()
print('An object is detected in:', distance_in_cm, 'cm')
print('An object is detected in:', distance_in_mm, 'mm')
#to display the distance on OLED
oled.fill(1) # 1 means line number 1
oled.text('Object detected: ',3,0,0)
oled.text(str(distance_in_cm),5,20,0)
oled.text('cm',75,20,0)
oled.text(str(distance_in_mm),5,40,0)
oled.text('mm',75,40,0)
oled.show()
#check the range <50
if distance_in_cm<50:
for i in range (100):
buzzer.init(freq = 1400, duty = 400)
sleep(0.5)
buzzer.init(freq = 1, duty = 0)
sleep(0.5)
elif 50<distance_in_cm<150:
for i in range (100):
buzzer.init(freq = 1400, duty = 400)
sleep(1)
buzzer.init(freq = 1, duty = 0)
sleep(1)
else:
buzzer.init(freq = 1, duty = 0)
sleep(5)