print("\n================================================")
print("Automated River Debris & Flood Control Gate")
print("================================================\n")
#Import Libraries
import machine
import utime
from machine import Pin, ADC, PWM
import neopixel
# Import External Libraries
from ultrasonic_library import HCSR04
from servo_library import Servo
#Pin Declaration
#ldr and potentialmeter
ldr = ADC(Pin(34)) # Day/Night detection
pot = ADC(Pin(35)) # River current speed simulation
#configure the attenuation of the ADC pins (Nak selaraskan bacaan)
ldr.atten(ADC.ATTN_11DB)
pot.atten(ADC.ATTN_11DB)
#buzzer and neo
buzzer = PWM(Pin(12))
pixels = neopixel.NeoPixel(Pin(14), 16) # 16-LED NeoPixel Ring on Pin 14
sensor = HCSR04(trigger_pin=26, echo_pin=25)
#for the cleaning gate/arm
gate_servo = Servo(pin=13)
def set_floodlight(color):
"""Sets the color of the entire NeoPixel ring.
(tnda tiga" utk comment bnyak baris)"""
for i in range(16):
pixels[i] = color
pixels.write()
print("System Initialized: Automated River Debris & Flood Control")
#MAIN LOOP
while True:
try:
# Read sensor values
debris_distance = sensor.distance_cm()
flow_speed = pot.read() # Range: 0 - 4095
light_level = ldr.read() # Lower values = Darker
# Define logic thresholds
debris_detected = debris_distance < 25 # Object detected closer than 25cm
high_flow = flow_speed > 2500
max_flow = flow_speed > 3800
is_night = light_level < 1500
"""Servo act as to open the gate and pot tu to make sure sampah mengalir
The gate opens only if the grate is blocked AND the flow is high"""
if debris_detected and high_flow:
gate_servo.move(90) # Open gate to clear debris
cleaning_active = True
current_status = "CLEANING"
else:
gate_servo.move(0) # Close gate/Standby
cleaning_active = False
current_status = "MONITORING"
# Maintenance Floodlight (NeoPixel)
# Lights turn on ONLY if cleaning is active AND it is nighttime
if cleaning_active and is_night:
set_floodlight((255, 255, 255)) # Bright White max for(red, green, blue)
else:
set_floodlight((0, 0, 0)) # Off
# Emergency Flood Warning (Buzzer)
# Sounds if river speed is at max AND the grate remains blocked (danger)
if max_flow and debris_detected:
buzzer.freq(1000)
buzzer.duty(512)
current_status = "DANGER: FLOOD"
else:
buzzer.duty(0)
# Monitor output in the Serial Console (f is f string lateral)
print(f"[{current_status}] Distance: {debris_distance:.1f}cm | Flow: {flow_speed} | Light: {light_level}")
except OSError as e:
# Prevents crashing if the ultrasonic sensor is 'Out of range'
print("Sensor Error:", e)
gate_servo.move(0)
set_floodlight((255, 0, 0)) # Red light indicates system error
utime.sleep(0.5)