#Name:LUQMAN HAKIM BIN BAHARUM
#ID : 51220222091
#GROUP: L01-B02
#PHASE TEST
# Import necessary modules
from machine import Pin, time_pulse_us
import time
# Set the pin numbers for the ultrasonic sensor and LEDs
PIN_TRIG = Pin(26, Pin.OUT)
PIN_ECHO = Pin(25, Pin.IN)
LOW_LED = Pin(18, Pin.OUT)
MID_LED = Pin(19, Pin.OUT)
HIGH_LED = Pin(21, Pin.OUT)
MOTOR_PUMP = Pin(27, Pin.OUT)
# Set the initial values for LEDs and motor pump
LOW_LED.value(1)
MID_LED.value(1)
HIGH_LED.value(1)
MOTOR_PUMP.value(0)
# Loop to continuously read the distance and control the LEDs and motor pump
while True:
# Trigger the ultrasonic sensor
PIN_TRIG.value(1)
time.sleep_us(10)
PIN_TRIG.value(0)
# Measure the duration of the pulse from the ultrasonic sensor and calculate the distance
duration = time_pulse_us(PIN_ECHO, 1)
distance_cm = duration / 58
distance_inches = duration / 148
# Print the distance
print("Distance in CM:", distance_cm)
print("Distance in inches:", distance_inches)
# Set the water level based on the distance
if distance_cm < 100:
LOW_LED.value(0) # Turn off the low LED
MOTOR_PUMP.value(1) # Turn on the water pump
HIGH_LED.value(1) # Turn on the high LED
MID_LED.value(1) # Turn on the mid LED
elif distance_cm > 200 and distance_cm < 400:
LOW_LED.value(1) # Turn on the low LED
HIGH_LED.value(1) # Turn on the high LED
MID_LED.value(0) # Turn off the mid LED
elif distance_cm >= 400:
HIGH_LED.value(0) # Turn off the high LED
MID_LED.value(1) # Turn on the mid LED
LOW_LED.value(1) # Turn on the low LED
MOTOR_PUMP.value(0) # Turn off the water pump
# Wait for 1 second before measuring again
time.sleep(1)