from machine import Pin, PWM, I2C, time_pulse_us
from ssd1306 import SSD1306_I2C
import time
#Pin Declaration
TRIG = Pin(5, Pin.OUT)
ECHO = Pin(18, Pin.IN)
GREEN_LED = Pin(19, Pin.OUT)
RED_LED = Pin(25, Pin.OUT)
BUTTON_SCAN = Pin(15, Pin.IN, Pin.PULL_UP) #Single button for scanning
BUZZER = PWM(Pin(23), freq=2000, duty=0)
#OLED Setup
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
#Simulated Queue of QR Codes
scan_queue = ["12345", "67890", "12345", "00000", "54321", "67890"]
#Registered Users
registered_users = {
"12345": "Ali",
"67890": "Siti",
"54321": "Raju",
"11111": "Aminah"
}
#Track who already claimed
claimed_today = set()
#Buzzer Functions
def buzzer_on():
BUZZER.freq(2000)
BUZZER.duty(512)
def buzzer_off():
BUZZER.duty(0)
#OLED Display Functions
def display_message(title, line2):
oled.fill(0)
oled.text(title, 0, 0)
oled.text(line2, 0, 20)
oled.show()
#Measure food level (Ultrasonic)
def measure_distance():
TRIG.value(0)
time.sleep_us(2)
TRIG.value(1)
time.sleep_us(10)
TRIG.value(0)
duration = time_pulse_us(ECHO, 1)
distance_cm = (duration * 0.0343) / 2
return distance_cm
#Food Level Checking
def check_food_level():
distance = measure_distance()
print("Current Food Level: {:.2f} cm".format(distance))
if distance > 100:
display_message("FOOD LOW", "")
RED_LED.on()
GREEN_LED.off()
buzzer_on()
time.sleep(2)
buzzer_off()
RED_LED.off()
else:
display_message("FOOD OK", "")
GREEN_LED.on()
RED_LED.off()
return distance
#Feedback when scan QR
def give_feedback(success):
if success:
GREEN_LED.on()
RED_LED.off()
buzzer_off()
else:
GREEN_LED.off()
RED_LED.on()
buzzer_on()
time.sleep(2)
GREEN_LED.off()
RED_LED.off()
buzzer_off()
#Main Program
print("System Initialized. Ready for QR Scan Simulation...\n")
while True:
# Always check food level
food_level = check_food_level()
if BUTTON_SCAN.value() == 0 and scan_queue:
scanned_qr = scan_queue.pop(0)
print("QR Scanned:", scanned_qr)
time.sleep(0.5) # Debounce
if scanned_qr in registered_users:
name = registered_users[scanned_qr]
if scanned_qr in claimed_today:
display_message("ALREADY CLAIMED", name)
print(f"{name} already claimed today!")
give_feedback(False)
else:
if food_level <= 100:
claimed_today.add(scanned_qr)
display_message("CLAIM APPROVED", name)
print(f"{name} successfully claimed.")
give_feedback(True)
else:
display_message("NO STOCK", name)
print(f"Cannot claim. Food stock low!")
give_feedback(False)
else:
display_message("NOT REGISTERED", "Unknown")
print("QR not recognized.")
give_feedback(False)
time.sleep(1.5)
time.sleep(0.1)