from machine import Pin, I2C
import time
import ssd1306
import network
from umqtt.robust import MQTTClient
import ujson
# --- OLED Setup ---
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# --- LED Setup ---
led_gas = Pin(4, Pin.OUT)
led_motion = Pin(5, Pin.OUT)
# --- WLAN Setup ---
WIFI_SSID = 'Wokwi-GUEST'
WIFI_PASS = ''
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(WIFI_SSID, WIFI_PASS)
print("Connecting to WiFi...", end="")
oled.fill(0)
oled.text('WiFi: Connecting', 0, 0)
oled.show()
while not sta_if.isconnected():
print(".", end="")
oled.text('.', 0, 20)
oled.show()
time.sleep(0.2)
print("\nWiFi connected!")
oled.fill(0)
oled.text('WiFi: Connected', 0, 0)
oled.show()
time.sleep(2)
# --- MQTT Setup ---
MQTT_SERVER = "industrial.api.ubidots.com"
CLIENT_ID = "Sensoren_IOT"
PORT = 1883
UBIDOTS_TOKEN = "BBUS-plXlv65a0MYUnh0dzi5HRUHNc5HCUf"
# Topics für einzelne Variablen
topic_temp = b"/v1.6/devices/sensoren-iot/temperature"
topic_motion = b"/v1.6/devices/sensoren-iot/motion"
topic_gas = b"/v1.6/devices/sensoren-iot/gas_detected"
# Globale Variablen
temp = 0
motion = 0
gas = 0
# --- Callback Funktion ---
def sub_cb(topic, msg):
global temp, motion, gas
try:
data = ujson.loads(msg)
value = data.get("value", 0)
if topic == topic_temp:
temp = int(value)
print("Temp:", temp)
elif topic == topic_motion:
motion = int(value)
print("Motion:", motion)
elif topic == topic_gas:
gas = int(value)
print("Gas:", gas)
except Exception as e:
print("Error parsing message:", e)
# --- MQTT Client erstellen ---
client = MQTTClient(CLIENT_ID, MQTT_SERVER, PORT, user=UBIDOTS_TOKEN, password=UBIDOTS_TOKEN)
client.set_callback(sub_cb)
# --- Hauptloop ---
while True:
try:
client.connect()
client.subscribe(topic_temp)
client.subscribe(topic_motion)
client.subscribe(topic_gas)
# Auf eingehende Nachrichten prüfen
for _ in range(5): # mehrere Male abfragen, um alle Nachrichten zu empfangen
client.check_msg()
time.sleep(0.5)
client.disconnect()
# LEDs steuern
led_gas.value(gas)
led_motion.value(motion)
# OLED anzeigen
oled.fill(0)
oled.text("Temp: {} C".format(temp), 0, 0)
oled.text("Bewegung: {}".format("Ja" if motion else "Nein"), 0, 20)
oled.text("Gas: {}".format("Ja" if gas else "Nein"), 0, 40)
oled.show()
time.sleep(5) # alle 5 Sekunden aktualisieren
except Exception as e:
print("Fehler im Hauptloop:", e)
oled.fill(0)
oled.text("Fehler!", 0, 0)
oled.show()
time.sleep(5)