from machine import Pin
import time
# ===== Display subsystem: HD44780 LCD =======================
RS = Pin(19, Pin.OUT) # Register Select
E = Pin(18, Pin.OUT) # Enable
# Fix 1: Corrected LCD Data Pins order to match diagram.json (D4->5, D5->17, D6->16, D7->4)
DATA = [Pin(5, Pin.OUT), # D4
Pin(17, Pin.OUT), # D5
Pin(16, Pin.OUT), # D6
Pin(4, Pin.OUT)] # D7
# ----- HD44780 command constants ------------------------------------------
LCD_CLEAR = 0x01
LCD_HOME = 0x02
LCD_ENTRY = 0x04
ENTRY_LEFT = 0x02
LCD_DISPLAY = 0x08
DISPLAY_ON = 0x04
LCD_FUNCTION = 0x20
FUNC_4BIT_2LINE = 0x08
LCD_SET_DDRAM = 0x80
ROW_ADDR = (0x00, 0x40)
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[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 (LCD_CLEAR, LCD_HOME):
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):
command(0x80 | (ROW_ADDR[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(LCD_FUNCTION | FUNC_4BIT_2LINE)
command(LCD_DISPLAY | DISPLAY_ON)
command(LCD_CLEAR)
command(LCD_ENTRY | ENTRY_LEFT)
# ===== Sensing subsystem: PIR Motion Sensor ===============================
# Fix 2: Changed PIR pin from 27 to 14 to match diagram.json
pir = Pin(14, Pin.IN)
# ===== Main program =======================================================
lcd_init()
set_cursor(0, 0)
write_str("Motion Alarm")
count = 0
last_motion = 0
last_lcd = time.ticks_ms()
print("Motion Alarm running. Waiting for the PIR...")
while True:
motion = pir.value()
# Fix 3: Fixed comparison operator from '=' to '=='
if motion == 1 and last_motion == 0:
count += 1
print("Motion detected, count =", count)
last_motion = motion
now = time.ticks_ms()
if time.ticks_diff(now, last_lcd) >= 200:
last_lcd = now
if motion == 1:
line2 = "Motion: YES " + str(count)
else:
line2 = "Motion: no " + str(count)
set_cursor(0, 1)
write_str((line2 + " " * 16)[:16])
time.sleep_ms(10)