#ADRIANA SARAH // INDIVIDUAL PROJECT
import network
import time
import ujson
import ubinascii
import machine
from machine import Pin, I2C
from umqtt.simple import MQTTClient
from ssd1306 import SSD1306_I2C # OLED library
# MQTT Server Parameters
MQTT_CLIENT_ID = ubinascii.hexlify(machine.unique_id()).decode()
MQTT_BROKER = "broker.mqtt.cool"
MQTT_TOPIC_SEAT = "teddy/bus/seats"
# WiFi Setup
SSID = "Wokwi-GUEST"
PASSWORD = ""
# Connect to WiFi
print("Connecting to WiFi...", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(SSID, PASSWORD)
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# Add delay for stability
time.sleep(2)
# Connect to MQTT Broker with error handling
print("Connecting to MQTT server...", end="")
try:
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER) # Removed authentication
client.connect()
print(" Connected!")
except Exception as e:
print("MQTT Connection Failed:", str(e))
# GPIO Setup
btn_board = Pin(18, Pin.IN, Pin.PULL_UP) # Boarding button
btn_exit = Pin(19, Pin.IN, Pin.PULL_UP) # Exiting button
led_reserved = Pin(5, Pin.OUT) # Red LED (Reserved seat)
led_available = Pin(4, Pin.OUT) # Green LED (Available seat)
buzzer = Pin(13, Pin.OUT) # Buzzer
# I2C & OLED Display Setup
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
seats_available = 10 # Number of available seats
# Function to Update OLED Display
def update_oled():
oled.fill(0) # Clear screen
oled.text("Seats Available:", 0, 10)
oled.text(f"{seats_available}", 40, 30)
oled.show()
update_oled() # Initial screen display
# Function: Reserve a Seat
def reserve_seat(pin):
global seats_available
if seats_available > 0:
seats_available -= 1
led_reserved.on()
led_available.off()
buzzer.on()
time.sleep(0.5)
buzzer.off()
print("Seat Reserved!")
message = ujson.dumps({"status": "Reserved", "available_seats": seats_available})
client.publish(MQTT_TOPIC_SEAT, message)
update_oled()
# Function: Free a Seat
def free_seat(pin):
global seats_available
if seats_available < 10:
seats_available += 1
led_reserved.off()
led_available.on()
buzzer.on()
time.sleep(0.5)
buzzer.off()
print("Seat Freed!")
message = ujson.dumps({"status": "Available", "available_seats": seats_available})
client.publish(MQTT_TOPIC_SEAT, message)
update_oled()
# Attach Interrupts to Buttons
btn_board.irq(trigger=Pin.IRQ_FALLING, handler=reserve_seat)
btn_exit.irq(trigger=Pin.IRQ_FALLING, handler=free_seat)
# Keep Script Running
while True:
time.sleep(1)