# Import necessary libraries
import library_ultrasonic
from machine import Pin
from utime import sleep
# Declare pin for ultrasonic sensor
TRIG = Pin(5, Pin.IN)
ECHO = Pin(18, Pin.OUT)
# Declare pin for LED
led_yellow = Pin(12, Pin.OUT)
# Declare pin for buzzer
buzzer_pin = Pin(13, Pin.OUT)
# Create an object for the ultrasonic sensor
sensor_malibu = library_ultrasonic.HCSR04(trigger_pin=TRIG, echo_pin=ECHO)
# Main program
while True:
print("##### MARI CHECK INCOMING DISTANCE !! ###### \n")
# Measure distance in mm and cm
distance_mm = sensor_malibu.distance_mm()
distance_cm = sensor_malibu.distance_cm()
# Print the distance
print("UNTUK MENGKAJI HUBUNGAN ANTARA : ", distance_mm, 'mm')
print("UNTUK MENGKAJI HUBUNGAN ANTARA : ", distance_cm, 'cm')
# Control the LED based on distance
if distance_cm < 400: # You can adjust this threshold as needed
led_yellow.on()
# Generate a sound on the buzzer
buzzer_pin.on()
sleep(0.2) # Adjust the duration of the sound
buzzer_pin.off()
else:
led_yellow.off()
sleep(2) # In every 2 seconds, the ultrasonic sensor will sense new incoming distance