def connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
pass # wait till connection
print('network config:', sta_if.ifconfig())
print("Benvinguts a MicroPython per a la placa IoT-02")
connect()
'''
Based on: https://bhave.sh/micropython-mqtt/
https://github.com/jordibinefa/IoT-02/tree/master/micropython/prj_mqtt_00
20220830
'''
from umqttsimple import MQTTClient
from machine import Pin
from time import sleep
from random import choice
import ubinascii,network
def cadenaAleatoria(longitud):
lletres = ['a','b','c','d','e','f','0','1','2','3','4','5','6','7','8','9']
return 'IoT-02_'+''.join(choice(lletres) for i in range(longitud))
def controlLedVerd(topic,msg):
print("tema: %s, msg: %s"%(topic,msg))
if msg.decode() == '1':
ledG.value(1)
else:
ledG.value(0)
btn = Pin(35,Pin.IN)
ledW = Pin(19,Pin.OUT)
ledG = Pin(2,Pin.OUT)
wlan_sta = network.WLAN(network.STA_IF)
# wlan_mac = wlan_sta.config('mac')
# MAC = ubinascii.hexlify(wlan_mac).decode().upper()
MAC = "7C9EBDEA5BA0"
print("MAC: %s"%MAC)
TEMA_BOTO = b'/' + MAC.encode() + b'/btI35'
TEMA_LED_VERD = b'/' + MAC.encode() + b'/ledW'
print("TEMA_LED_VERD: %s"%TEMA_LED_VERD)
CLIENT_NAME = cadenaAleatoria(10)
BROKER_ADDR = 'broker.emqx.io'
BROKER_PORT = 1883
BROKER_USER = ''
BROKER_PWD = ''
mqttc = MQTTClient(CLIENT_NAME, BROKER_ADDR, port=BROKER_PORT, user=BROKER_USER,password=BROKER_PWD,keepalive=60)
mqttc.connect()
mqttc.set_callback(controlLedVerd)
mqttc.subscribe(TEMA_LED_VERD)
currentBtn = btn()
lastBtn = currentBtn
n = 0
while True:
currentBtn = btn()
if currentBtn != lastBtn:
lastBtn = currentBtn
if currentBtn == 1:
print("Button released. ",end='')
missatge = "0"
else:
print("Button pressed. ",end='')
missatge = "1"
# missatge = str(currentBtn).encode()
try:
mqttc.publish( TEMA_BOTO, missatge )
print("Tema: %s, missatge: %s"%(TEMA_BOTO,missatge))
except:
print("It looks like there is not MQTT connection")
mqttc.check_msg()
n += 1
if n > 20:
mqttc.ping() # this ping every two seconds keeps MQTT connection reliable
# print("mqttc.ping()")
n = 0
sleep(0.05)
esp:VIN
esp:GND.2
esp:D13
esp:D12
esp:D14
esp:D27
esp:D26
esp:D25
esp:D33
esp:D32
esp:D35
esp:D34
esp:VN
esp:VP
esp:EN
esp:3V3
esp:GND.1
esp:D15
esp:D2
esp:D4
esp:RX2
esp:TX2
esp:D5
esp:D18
esp:D19
esp:D21
esp:RX0
esp:TX0
esp:D22
esp:D23
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
r1:1
r1:2
led1:A
led1:C
r3:1
r3:2