from machine import Pin, ADC
import time
# ===== 1. LCD Subsystem (Direct Driver for HD44780) =====
RS = Pin(23, Pin.OUT)
E = Pin(22, Pin.OUT)
# DATA Pins: D4 -> 17, D5 -> 16, D6 -> 4, D7 -> 2
DATA_PINS = [Pin(17, Pin.OUT), Pin(16, Pin.OUT), Pin(4, Pin.OUT), Pin(2, Pin.OUT)]
def _pulse():
E.value(1)
time.sleep_us(1)
E.value(0)
time.sleep_us(50)
def _write4(nibble):
for i in range(4):
DATA_PINS[i].value((nibble >> i) & 1)
_pulse()
def _send(value, is_data):
RS.value(1 if is_data else 0)
_write4(value >> 4)
_write4(value & 0x0F)
def command(cmd):
_send(cmd, False)
if cmd in (0x01, 0x02):
time.sleep_ms(2)
def write_char(ch):
_send(ord(ch), True)
def write_str(text):
for ch in text:
write_char(ch)
def set_cursor(col, row):
row_offsets = [0x00, 0x40]
command(0x80 | (row_offsets[row] + col))
def lcd_init():
time.sleep_ms(40)
RS.value(0)
_write4(0x03); time.sleep_ms(5)
_write4(0x03); time.sleep_us(150)
_write4(0x03)
_write4(0x02)
command(0x28) # 4-bit mode, 2 lines
command(0x0C) # Display ON
command(0x01) # Clear
command(0x06)
def update_line1(text):
set_cursor(0, 0)
write_str((text + " " * 16)[:16])
def update_line2(text):
set_cursor(0, 1)
write_str((text + " " * 16)[:16])
# ===== 2. Component Setup =====
RED = Pin(27, Pin.OUT)
GREEN = Pin(26, Pin.OUT)
BLUE = Pin(25, Pin.OUT)
BUTTON = Pin(14, Pin.IN, Pin.PULL_UP)
BUZZER = Pin(13, Pin.OUT)
PIR = Pin(33, Pin.IN)
SOUND = ADC(Pin(34))
SOUND.atten(ADC.ATTN_11DB)
def rgb(r, g, b):
RED.value(r)
GREEN.value(g)
BLUE.value(b)
# ===== 3. Start Program =====
lcd_init()
update_line1("WELCOME FARES")
update_line2("System Ready")
last_state = ""
# ===== 4. Main Loop =====
while True:
sound_val = SOUND.read()
current_state = ""
if BUTTON.value() == 0:
current_state = "BUTTON"
rgb(0, 1, 0)
BUZZER.value(0)
if last_state != current_state:
update_line1("WELCOME FARES")
update_line2("Button Pressed")
elif PIR.value() == 1:
current_state = "PIR"
rgb(1, 0, 0)
BUZZER.value(1)
if last_state != current_state:
update_line1("WELCOME FARES")
update_line2("Motion Detected")
elif sound_val > 2000:
current_state = "SOUND"
rgb(0, 0, 1)
BUZZER.value(1)
if last_state != current_state:
update_line1("WELCOME FARES")
update_line2("Sound Detected")
else:
current_state = "READY"
rgb(0, 0, 0)
BUZZER.value(0)
if last_state != current_state:
update_line1("WELCOME FARES")
update_line2("System Ready")
last_state = current_state
time.sleep(0.1)