print("Making ultrasonic working!")
print("By: Ikhwanfahmi")
print("Date: 22/4/2024")
# Import libraries/modules
import ultrasonic_library
from machine import Pin, PWM
from utime import sleep
# Pin declaration
TRIG = Pin(12, Pin.OUT)
ECHO = Pin(14, Pin.IN)
Red_led = Pin(4, Pin.OUT)
Buzzer = PWM(Pin(18))
# Create an object for the sensor with the library
sensor_parking = ultrasonic_library.HCSR04(trigger_pin=TRIG, echo_pin=ECHO, echo_timeout_us=500*2*30)
# Main program
while True:
distance_cm = sensor_parking.distance_cm()
print("--------------------------------------------------")
print("Baki jarak dari dinding adalah", distance_cm, "cm")
print('\n')
if distance_cm <= 100: # If the distance is 1 meter or less
Red_led.on()
Buzzer.freq(1000)
Buzzer.duty(512)
sleep(0.4)
Red_led.off()
Buzzer.duty(0)
sleep(0.4)
elif distance_cm <= 50: # If the distance is 0.5 meter or less
Red_led.on()
Buzzer.freq(1500)
Buzzer.duty(512)
sleep(0.2)
Red_led.off()
Buzzer.duty(0)
sleep(0.2)
elif distance_cm <= 10: # If the distance is 0.1 meter or less
Red_led.on()
Buzzer.freq(2000)
Buzzer.duty(512)
sleep(0.1)
Red_led.off()
Buzzer.duty(0)
sleep(0.1)
else:
Red_led.off()
Buzzer.duty(0) # Ensure buzzer is off when no motion is detected