from machine import I2C, Pin, UART
from i2c_lcd import I2cLcd
import time
import network
import urequests
# ==== LCD SETUP ====
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=400000) # Change pins as needed
lcd_addr = i2c.scan()[0]
lcd = I2cLcd(i2c, lcd_addr, 2, 16)
# ==== BUTTONS ====
btn_next = Pin(32, Pin.IN, Pin.PULL_UP)
btn_prev = Pin(33, Pin.IN, Pin.PULL_UP)
btn_vote = Pin(25, Pin.IN, Pin.PULL_UP)
# ==== CANDIDATES ====
candidates = ["Alice", "Bob", "Charlie"]
index = 0
# ==== QR SCANNER ====
uart = UART(2, baudrate=9600, tx=17, rx=16) # Change pins if needed
# ==== Wi-Fi ====
def connect_wifi(ssid, password):
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
return wlan
connect_wifi("Your_SSID", "Your_PASSWORD")
# ==== DISPLAY ====
def show_candidate(idx):
lcd.clear()
lcd.putstr("Vote:\n> " + candidates[idx])
show_candidate(index)
# ==== READ QR ====
def read_qr():
if uart.any():
qr_data = uart.readline()
return qr_data.decode().strip()
return None
# ==== MAIN LOOP ====
voted = False
voter_id = None
while True:
qr = read_qr()
if qr and not voted:
voter_id = qr
lcd.clear()
lcd.putstr("Welcome!\nID: " + qr)
time.sleep(2)
show_candidate(index)
if btn_next.value() == 0:
index = (index + 1) % len(candidates)
show_candidate(index)
time.sleep(0.3)
if btn_prev.value() == 0:
index = (index - 1) % len(candidates)
show_candidate(index)
time.sleep(0.3)
if btn_vote.value() == 0 and voter_id and not voted:
lcd.clear()
lcd.putstr("Voting...\nPlease wait")
# === Send vote to your backend ===
try:
response = urequests.post("http://YOUR_SERVER/vote", json={
"voter_id": voter_id,
"candidate": candidates[index]
})
if response.status_code == 200:
lcd.clear()
lcd.putstr("Vote casted!\nThank you.")
voted = True
else:
lcd.clear()
lcd.putstr("Vote failed.\nTry again.")
response.close()
except:
lcd.clear()
lcd.putstr("Error: WiFi/Net")
time.sleep(3)
lcd.clear()