import network
import time
from machine import Pin
import machine
from pico_i2c_lcd import I2cLcd
from umqtt_simple import MQTTClient
''' 1.take input from the keypad not the keyboard
2.wait time should be updating in real time
3.display entered cond on lcd
'''
# Wi-Fi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Adafruit IO credentials
ADAFRUIT_AIO_USERNAME = "preethi_kannan"
ADAFRUIT_AIO_KEY = "aio_Rqyc95apVwXs8gn0wzAGxVQiDxXV"
# MQTT settings
BROKER = "io.adafruit.com"
FOOD_AVAILABLE_FEED = f"{ADAFRUIT_AIO_USERNAME}/feeds/food"
WAIT_TIME_FEED = f"{ADAFRUIT_AIO_USERNAME}/feeds/queue"
WAIT_TIME_GRAPH = f"{ADAFRUIT_AIO_USERNAME}/feeds/queue"
# HC-SR04 Trigger and Echo Pins
trigger = machine.Pin(5, machine.Pin.OUT)
echo = machine.Pin(18, machine.Pin.IN)
# I2C Pins for LCD
i2c = machine.I2C(0, sda=Pin(0), scl=Pin(1), freq=400000)
lcd = I2cLcd(i2c, 0x27, 2, 16) # 2x16 LCD display
# Food dictionary
food_dict = {
"1234": "veg fried rice",
"5678": "channa masala",
"1256": "battura"
}
current_food = [] # List of available food items
# Keypad setup (Example: 4x4 keypad matrix)
rows = [Pin(i, Pin.OUT) for i in [13,12,11,10]] # Adjust pins for your setup
cols = [Pin(i, Pin.IN, Pin.PULL_DOWN) for i in [9,8,7,6]]
key_map = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
# Function to scan keypad
#Activating the row by setting it HIGH means that any button connected
#to that row can now allow the signal to flow through it when pressed
#basically the pressed button only gets signal to be resigtered as
#pressed if the row it is in is active at the time.
def read_keypad():
for row in rows:
row.value(1)
for col, col_pin in enumerate(cols):
if col_pin.value():
row.value(0)
return key_map[rows.index(row)][col]
row.value(0)
return None
# Wi-Fi connection function
def connect_to_wifi():
"""Connect to Wi-Fi."""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print("Connecting to Wi-Fi...")
while not wlan.isconnected():
time.sleep(1)
print("Still connecting...")
print("Connected to Wi-Fi!")
print("Network config:", wlan.ifconfig())
# Publish message to MQTT
def mqtt_publish(client, topic, message):
"""Publish a message to an MQTT topic."""
try:
client.publish(topic, message)
print(f"Published to {topic}: {message}")
except Exception as e:
print(f"Failed to publish: {e}")
# Process keypad input
def process_keypad_input(client, input_code):
global current_food
lcd.clear()
lcd.putstr(f"Input: {input_code}")
if input_code.endswith("#"): # Add food
item_code = input_code[:-1]
if item_code in food_dict and food_dict[item_code] not in current_food:
current_food.append(food_dict[item_code])
mqtt_publish(client, FOOD_AVAILABLE_FEED, "\n".join(current_food))
elif input_code.endswith("*"): # Remove food
item_code = input_code[:-1]
if item_code in food_dict and food_dict[item_code] in current_food:
current_food.remove(food_dict[item_code])
mqtt_publish(client, FOOD_AVAILABLE_FEED, "\n".join(current_food))
# Measure distance
#manual function to get the distance of objects near the
#ultrasonic distance sensor.
def measure_distance():
"""Measure the distance using the HC-SR04 sensor."""
# Trigger the sensor
trigger.value(0)
time.sleep_us(2)
trigger.value(1)
time.sleep_us(10)
trigger.value(0)
# Measure the echo pulse duration
pulse_time = machine.time_pulse_us(echo, 1, 30000) # 30ms timeout
if pulse_time < 0: # No pulse received
return -1 # Indicate out of range or sensor error
# Convert pulse duration to distance in cm
distance_cm = (pulse_time * 0.0343) / 2 # Divide by 2 for round trip
return max(0, int(distance_cm)) # Ensure positive distance
# Main Program
connect_to_wifi()
client = MQTTClient("pico", BROKER, user=ADAFRUIT_AIO_USERNAME, password=ADAFRUIT_AIO_KEY)
client.connect()
try:
lcd.putstr("System Ready!")
time.sleep(2)
lcd.clear()
entered_code = ""
while True:
# Measure and publish wait time
wait_time = measure_distance()
mqtt_publish(client, WAIT_TIME_FEED, str(wait_time))
mqtt_publish(client,WAIT_TIME_GRAPH, str(wait_time))
time.sleep(0.2)
key = read_keypad()
if key:
lcd.clear()
if key == "#": # Finalize input
lcd.putstr(f"Processing {entered_code}")
process_keypad_input(client, entered_code + "#")
entered_code = ""
elif key == "*": # Remove food
lcd.putstr(f"Processing {entered_code}")
process_keypad_input(client, entered_code + "*")
entered_code = ""
else: # Append key
entered_code += key
lcd.putstr(f"Code: {entered_code}")
except KeyboardInterrupt:
print("Program stopped.")
finally:
mqtt_publish(client, WAIT_TIME_FEED, str(0))
mqtt_publish(client, FOOD_AVAILABLE_FEED, "")
client.disconnect()