from machine import Pin, Timer
from time import ticks_ms, ticks_diff
import network
import time
from umqtt.simple import MQTTClient
SSID = 'Wokwi-GUEST'
PASS = ''
BROKER = 'broker.hivemq.com'
CLIENT_ID = 'Men94' # Change to a unique name to avoid collision
# Connect to WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID,PASS)
print('WiFi ', end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
print(' connected to', wlan.ifconfig()[0])
# Connect to MQTT broker
client = MQTTClient(CLIENT_ID, BROKER)
try:
client.connect()
print('MQTT Connected')
except:
print('MQTT Error')
sw = Pin(2, Pin.IN, Pin.PULL_UP) # button -> GND
last = sw.value() # 1 = OFF, 0 = ON
debounce_ms = 40
tmr = Timer(0)
def sw_read(t):
global last
sw_read = sw.value()
if sw_read != last:
last = sw_read
if sw_read == 0:
print('ON')
client.publish('ae_iot/Men/sw', 'On')
else:
print('OFF')
client.publish('ae_iot/Men/sw', 'Off')
def _irq(pin):
tmr.init(mode=Timer.ONE_SHOT, period=debounce_ms, callback=sw_read)
sw.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=_irq)
while True:
pass