import machine
import rp2
from rp2 import PIO
from machine import Pin, Timer, PWM
from time import sleep, time
import urequests
import ujson
import network
# ThingSpeak settings
THINGSPEAK_API_KEY = 'H0U40QXE9KNY3V5M'
THINGSPEAK_URL = 'https://api.thingspeak.com/update?api_key='
# Wi-Fi settings
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Function to send data to ThingSpeak
def send_data_to_thingspeak(event_message):
data = {'field1': event_message}
print("Sending log to ThingSpeak, please wait...")
response = urequests.post(THINGSPEAK_URL + THINGSPEAK_API_KEY, json = data, headers={'Content-Type': 'application/json'})
response.close()
print("Log sent successfully")
# Initialize the Wi-Fi connection
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
# Wait for the Wi-Fi connection to establish
while not wifi.isconnected():
sleep(1)
print("Connected to Wi-Fi")
# Define 7-segment display segment pins
SEG_PINS = {
'A': Pin(26, Pin.OUT),
'B': Pin(27, Pin.OUT),
'C': Pin(18, Pin.OUT),
'D': Pin(19, Pin.OUT),
'E': Pin(20, Pin.OUT),
'F': Pin(22, Pin.OUT),
'G': Pin(21, Pin.OUT),
}
# Buzzer and RGB LED pins
buzzer = PWM(Pin(28, Pin.OUT))
led_r = Pin(2, Pin.OUT)
led_g = Pin(1, Pin.OUT)
led_b = Pin(0, Pin.OUT)
# 7-segment display encoding
SEGMENTS = {
'0': [0, 0, 0, 0, 0, 0, 1],
'1': [1, 0, 0, 1, 1, 1, 1],
'2': [0, 0, 1, 0, 0, 1, 0],
'3': [0, 0, 0, 0, 1, 1, 0],
'4': [1, 0, 0, 1, 1, 0, 0],
'5': [0, 1, 0, 0, 1, 0, 0],
'6': [0, 1, 0, 0, 0, 0, 0],
'7': [0, 0, 0, 1, 1, 1, 1],
'8': [0, 0, 0, 0, 0, 0, 0],
'9': [0, 0, 0, 0, 1, 0, 0],
'*': [0, 1, 1, 0, 1, 1, 0],
'#': [1, 1, 1, 1, 1, 1, 1],
}
# Display a character on the 7-segment display
def display_digit(char):
pattern = SEGMENTS.get(char, [1, 1, 1, 1, 1, 1, 1])
for seg_name, seg_pin in SEG_PINS.items():
seg_pin.value(pattern['ABCDEFG'.index(seg_name)])
# LED control functions
def led_color(r, g, b):
led_r.value(r)
led_g.value(g)
led_b.value(b)
def blink_led(r, g, b, times, delay):
for _ in range(times):
led_color(r, g, b)
sleep(delay)
led_color(0, 0, 0)
sleep(delay)
# State variables
password_set = False
password = []
entry = []
password_reset = False
reset_step = 0
input_timer = None
# Keypad PIO Assembly
@rp2.asm_pio(set_init=[PIO.IN_HIGH]*4)
def keypad():
wrap_target()
set(y, 0)
label("scan")
mov(isr, null)
set(pindirs, 1)
in_(pins, 4)
set(pindirs, 2)
in_(pins, 4)
set(pindirs, 4)
in_(pins, 4)
set(pindirs, 8)
in_(pins, 4)
mov(x, isr)
jmp(x_not_y, "detect")
jmp("scan")
label("detect")
push(block)
irq(0)
mov(y, x)
jmp("scan")
wrap()
# Initialize keypad input pins
for i in range(10, 14):
Pin(i, Pin.IN, Pin.PULL_DOWN)
key_names = "*7410852#963"
# Keypad event handler
def oninput(machine):
global password_set, password, entry, password_reset, reset_step, input_timer
keys = machine.get()
while machine.rx_fifo():
keys = machine.get()
pressed = [key_names[i] for i in range(len(key_names)) if keys & (1 << i)]
if pressed:
char = pressed[0]
display_digit(char)
if input_timer:
input_timer.deinit()
if not password_reset:
input_timer = Timer().init(period=1000, mode=Timer.ONE_SHOT, callback=clear_display)
if password_reset:
led_color(0, 0, 1)
if reset_step == 1:
entry.append(char)
if len(entry) == 4:
if entry == password:
print("Old password correct. Enter new password.")
blink_led(0, 1, 0, 2, 0.1)
entry = []
reset_step = 2
else:
print("Incorrect old password. Returning to lock state.")
blink_led(1, 0, 0, 3, 0.1)
send_data_to_thingspeak("Password change failed")
password_reset = False
entry = []
elif reset_step == 2:
if char == '#':
if len(entry) == 4:
print("New password set.")
password = entry[:]
password_set = True
send_data_to_thingspeak("Password changed")
password_reset = False
blink_led(0, 1, 0, 2, 0.1)
entry = []
else:
print("Invalid new password.")
blink_led(1, 0, 0, 3, 0.1)
send_data_to_thingspeak("Entry failed")
password_reset = False
entry = []
elif len(entry) < 4:
entry.append(char)
return
if not password_reset:
entry.append(char)
if password_set and len(entry) == 4:
if entry == password:
print("Correct password!")
send_data_to_thingspeak("Entry successful")
led_color(0, 1, 0)
buzzer.freq(500)
buzzer.duty_u16(1000)
sleep(2)
buzzer.duty_u16(0)
sleep(3)
else:
print("Incorrect password!")
blink_led(1, 0, 0, 3, 0.2)
send_data_to_thingspeak("Entry failed")
entry = []
elif not password_set and len(entry) == 5:
if entry[-1] == '#':
password = entry[:-1] # Exclude '#' from password
if len(password) == 4:
password_set = True
print("Password set.")
blink_led(0, 0, 1, 3, 0.2)
else:
print("Invalid password length.")
send_data_to_thingspeak("Entry failed")
password = []
else:
print("Invalid input sequence. Use '#' to confirm.")
blink_led(1, 0, 0, 3, 0.2)
send_data_to_thingspeak("Entry failed")
entry = []
if entry == ['*']:
password_reset = True
entry = []
reset_step = 1
print("Enter old password to reset.")
led_color(0, 0, 1)
# Timer callback to clear display after inactivity
def clear_display(t):
display_digit(' ')
# Initialize PIO StateMachine for keypad
sm = rp2.StateMachine(0, keypad, freq=2000, in_base=Pin(10, Pin.IN, Pin.PULL_DOWN), set_base=Pin(6))
sm.active(1)
sm.irq(oninput)
# Main loop
display_digit(' ')
print("Ready.")
while True:
if password_set and not password_reset:
blink_led(1, 0, 0, 1, 1)
sleep(0.1)