not able to blink led on esp8266 with MQTT App & Raspberry Pi
Posted: Sun May 19, 2019 1:13 pm
Hi,
After googling i build below code to blink in-built led on ESP8266 with MQTT App (Android) and mosquitto broker installed on Raspberry Pi. But i am not able to make the led blink by publishing from MQTT App. can someone suggest me where i do mistake. Also,i have umqttsimple.py file on ESP8266.
boot.py code:-
Main.py code:-
After googling i build below code to blink in-built led on ESP8266 with MQTT App (Android) and mosquitto broker installed on Raspberry Pi. But i am not able to make the led blink by publishing from MQTT App. can someone suggest me where i do mistake. Also,i have umqttsimple.py file on ESP8266.
boot.py code:-
Code: Select all
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'REPLACE_WITH_YOUR_SSID'
password = 'REPLACE_WITH_YOUR_PASSWORD'
mqtt_server = 'REPLACE_WITH_YOUR_MQTT_BROKER_IP'
#EXAMPLE IP ADDRESS
#mqtt_server = '192.168.1.144'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'led'
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
Main.py code:-
Code: Select all
from machine import Pin
pin=Pin(2,Pin.OUT)
def sub_cb(topic, msg):
print((topic, msg))
if topic == b'led' and msg == b'off':
print('ESP received '+msg+' message')
pin.on()
elif topic==b'led' and msg==b'on':
print('ESP received '+msg+' message')
pin.off()
def connect_and_subscribe():
try:
global client_id, mqtt_server, topic_sub
client = MQTTClient(client_id, mqtt_server)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
except OSError as e:
print('Failed to connect to MQTT broker. debug why MQTT not connected')
connect_and_subscribe()