from machine import Pin, time_pulse_us, ADC, I2C, RTC
from utime import sleep_us, sleep_ms
from i2c_lcd import I2cLcd
TRIG = Pin(3, Pin.OUT)
ECHO = Pin(2, Pin.IN)
RED = Pin(8, Pin.OUT)
GREEN = Pin(9, Pin.OUT)
BLUE = Pin(10, Pin.OUT)
RED.value(1)
BLUE.value(1)
GREEN.value(1)
CLOCK = RTC()
CLOCK.datetime((2024, 4, 22, 0, 18, 56, 0, 0))
AddressOfLcd = 0x27
i2c = I2C(0, scl=Pin(21), sda=Pin(20), freq=400000)
lcd = I2cLcd(i2c, AddressOfLcd, 2, 16)
LDR = ADC(Pin(28, Pin.IN))
PIR = Pin(4, Pin.IN)
SEGMENTS = [
Pin(5, Pin.OUT), # A
Pin(6, Pin.OUT), # B
Pin(7, Pin.OUT), # C
Pin(11, Pin.OUT), # D
Pin(12, Pin.OUT), # E
Pin(13, Pin.OUT), # F
Pin(14, Pin.OUT) # G
]
numbers = [
[1, 1, 1, 1, 1, 1, 0], # 0
[0, 1, 1, 0, 0, 0, 0], # 1
[1, 1, 0, 1, 1, 0, 1], # 2
[1, 1, 1, 1, 0, 0, 1], # 3
[0, 1, 1, 0, 0, 1, 1], # 4
[1, 0, 1, 1, 0, 1, 1], # 5
[1, 0, 1, 1, 1, 1, 1], # 6
[1, 1, 1, 0, 0, 0, 0], # 7
[1, 1, 1, 1, 1, 1, 1], # 8
[1, 1, 1, 1, 0, 1, 1] # 9
]
for i in range(len(numbers)):
curr = numbers[i]
for j in range(len(curr)):
curr[j] = 1 - curr[j]
def show_number(number):
values = numbers[number]
for i in range(len(SEGMENTS)):
SEGMENTS[i].value(values[i])
def read_ultrasonic_sensor():
TRIG.low()
sleep_us(2)
TRIG.high()
sleep_us(10)
TRIG.low()
pulse_duration = time_pulse_us(ECHO, Pin.high)
distance = pulse_duration * 0.0343 / 2 # in centimetres
return int(distance)
def motion_detected():
return True if PIR.value() == 1 else False
def read_photoresistor():
val = LDR.read_u16()
return val
def reset_LED():
RED.value(1)
BLUE.value(1)
GREEN.value(1)
def reset_number():
for i in range(len(SEGMENTS)):
SEGMENTS[i].value(1)
def display(text, x, y):
lcd.move_to(y, x)
lcd.putstr(text)
def get_time():
t = CLOCK.datetime()
return "{:02d}/{:02d} {:02d}:{:02d}:{:02d}".format(t[2], t[1], t[4], t[5], t[6])
mail_count = 0
last_mail_time = ""
# Booleans
exceeded = False
human_nearby = False
mailbox_opened = False
while True:
reset_LED()
if read_photoresistor() >= 54301: # Mail put into mailbox
mail_count += 1
last_mail_time = get_time()
if motion_detected() and read_ultrasonic_sensor() < 50:
human_nearby = True
else:
human_nearby = False
if mail_count > 9:
exceeded = True
lcd.clear()
display("Exceeded capacity.", 0, 0)
else:
exceeded = False
if human_nearby:
if not exceeded:
if mail_count == 0:
reset_LED()
RED.value(0)
else:
reset_LED()
GREEN.value(0)
if last_mail_time != "":
display("Last received at", 0, 0)
display(last_mail_time, 1, 0)
show_number(mail_count)
else: # Turn everything off
reset_number()
reset_LED()
lcd.clear()
sleep_ms(1000)