import machine
import network
import time
from umqtt.simple import MQTTClient
import ujson
import urandom
# Wifi-Connection
print("Connecting to Wifi...")
sta_if = network.WLAN(network.STA_IF) # WLAN Object
sta_if.active(True) # Activate WLAN
sta_if.connect('Wokwi-GUEST', '') # SSID und PW
# Wait until WLAN is connected
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print("\nWifi connected")
# MQTT Setup
SERVER = "industrial.api.ubidots.com"
port = 1883
client_name = "Display1"
topic = b"/v1.6/devices/tictactoe/coordinate" # Achtung auf Variable Zugreifen!!
ubidots_token = "BBUS-ml6CuHMu7EDmyFMPILbxQBb4EJgZ0D"
# Client Object:
client = MQTTClient(client_name, SERVER, port, user=ubidots_token, password=ubidots_token)
# LED Konfiguration
led_pins = [
{'r': 14, 'b': 26}, # Erste LED
{'r': 25, 'b': 32}, # Zweite LED
{'r': 23, 'b': 18}, # Dritte LED
{'r': 19, 'b': 5}, # Vierte LED
{'r': 17, 'b': 4}, # Fünfte LED
{'r': 22, 'b': 13}, # Sechste LED
{'r': 12, 'b': 27}, # Siebte LED
{'r': 0, 'b': 33}, # Achte LED
{'r': 15, 'b': 16} # Neunte LED
]
leds = []
for pins in led_pins:
leds.append({
'r': machine.Pin(pins['r'], machine.Pin.OUT),
'b': machine.Pin(pins['b'], machine.Pin.OUT),
'state': False, # Zustand der LED (an/aus)
'color': 'none' # Farbe der LED (rot/blau)
})
# Funktion zur Steuerung der LEDs
def set_led(index, color):
if 0 <= index < len(leds):
leds[index]['r'].value(color[0])
leds[index]['b'].value(color[1])
leds[index]['state'] = (color[0] == 1 or color[1] == 1)
leds[index]['color'] = 'red' if color[0] == 1 else 'blue'
def clear_leds():
for led in leds:
led['r'].value(0)
led['b'].value(0)
led['state'] = False
led['color'] = 'none'
# Mapping of coordinates to LED index
coordinate_to_led = {
111: 0, 112: 1, 113: 2, # A1, A2, A3
114: 3, 115: 4, 116: 5, # B1, B2, B3
117: 6, 118: 7, 119: 8, # C1, C2, C3
211: 0, 212: 1, 213: 2, # A1, A2, A3
214: 3, 215: 4, 216: 5, # B1, B2, B3
217: 6, 218: 7, 219: 8 # C1, C2, C3
}
# Callback-Funktion. Liest die Message vom Server aus und übergibt die Temp in eine int Variable
def sub_cb(topic, msg):
global temp
data = ujson.loads(msg)
temp = data["value"]
if temp == -1:
# Alle LEDs lila für 3s (rot und blau an)
for i in range(len(leds)):
set_led(i, (1, 1))
time.sleep(3)
clear_leds()
elif temp == 0:
# Alle LEDs abwechselnd rot und blau für 5 Sekunden blinken
num_red_leds = len(leds) // 2 # Anzahl der roten LEDs
num_blue_leds = len(leds) - num_red_leds # Anzahl der blauen LEDs
for _ in range(5):
for i in range(len(leds)):
if i < num_red_leds:
set_led(i, (1, 0)) # Rot
else:
set_led(i, (0, 1)) # Blau
time.sleep(urandom.randint(1, 10) / 10) # Zufällige Wartezeit zwischen 0.1 und 1 Sekunde
clear_leds()
elif temp == 100:
clear_leds() # Alle LEDs ausschalten
elif 111 <= temp <= 119 or 211 <= temp <= 219:
led_index = coordinate_to_led.get(temp, None)
if led_index is not None:
# Nur die entsprechende LED einschalten, wenn sie nicht schon an ist
if not leds[led_index]['state']:
if 111 <= temp <= 119:
set_led(led_index, (1, 0)) # Rot
elif 211 <= temp <= 219:
set_led(led_index, (0, 1)) # Blau
# Client Funktion im Objekt festlegen
client.set_callback(sub_cb)
# Loop
temp = -999 # Mustertemperatur
last_temp = None # Variable zum Speichern der letzten Temperatur
while True:
# Connect to server and check msg
client.connect()
client.subscribe(topic)
client.check_msg()
client.disconnect()
# Überprüfen, ob sich die Temperatur geändert hat
if temp != last_temp:
# Erst die LED einschalten, wenn die Zahl sich am Server aktualisiert hat
if temp != -999 and temp != -1: # Prüfen, ob die erste Verbindung zum Server hergestellt wurde und temp nicht -1 ist
if temp == 100:
clear_leds() # Alle LEDs ausschalten
else:
led_index = coordinate_to_led.get(temp, None)
if led_index is not None:
if 111 <= temp <= 119:
set_led(led_index, (1, 0)) # Rot
elif 211 <= temp <= 219:
set_led(led_index, (0, 1)) # Blau
print(f'Aktuelle Zahl: {temp}')
last_temp = temp # Update last_temp
time.sleep(2) # Wait