from machine import I2C, Pin
import time
import json
safty_led = Pin(2, Pin.OUT)
# DS1307 I2C address
DS1307_ADDR = 0x68
# PIR sensor pin
pir = Pin(15, Pin.IN)
# Initialize I2C (I2C0: SDA=GP0, SCL=GP1)
i2c = I2C(
0,
scl=Pin(1),
sda=Pin(0),
freq=100000
)
# Convert BCD to Decimal
def bcd_to_dec(bcd):
return (bcd >> 4) * 10 + (bcd & 0x0F)
# Read time from DS1307
def read_ds1307():
data = i2c.readfrom_mem(DS1307_ADDR, 0x00, 7)
seconds = bcd_to_dec(data[0] & 0x7F)
minutes = bcd_to_dec(data[1])
hours = bcd_to_dec(data[2] & 0x3F)
day = bcd_to_dec(data[4])
month = bcd_to_dec(data[5])
year = bcd_to_dec(data[6]) + 2000
return {
"year": year,
"month": month,
"day": day,
"hour": hours,
"minute": minutes,
"second": seconds
}
print("PIR + DS1307 Motion-Based JSON Logger Started...\n")
motion_last_state = 0
while True:
motion = pir.value()
# Trigger only on new motion detection
if motion == 1 and motion_last_state == 0:
rtc_data = read_ds1307()
safty_led.toggle()
payload = {
"event": "motion_detected",
"timestamp": rtc_data
}
print(json.dumps(payload))
# PIR needs a short delay to avoid repeat triggers
time.sleep(2)
motion_last_state = motion
time.sleep(0.1)