So Easy MicroPython — MQTT, IoT

from MyMQTT import myMQTT
my = myMQTT(YOUR_MQTT_SERVER)
my.connect()
my.publish(YOUR_MQTT_TOPIC, "your message here")

Step 1: Upload library to your MCU

  • MyMQTT: A basic library for using MQTT, a publish-subscribe protocol
  • MyWifi: A basic library for WiFi connection (No need, if your MCU can connect to WiFi already by your own script)

Step 2: Lets’ learn some examples

Example 0: Let MCU connect to your WiFi AP first

from MyWifi import myWifi
my = myWifi(YOUR_WIFI_SSID, YOUR_WIFI_PWD)
my.connect()

Example 1:(Publish) Upload/Write data to MQTT Broker

from MyMQTT import myMQTT
mq = myMQTT(MQTT_SERVER)
mq.connect()
mq.publish(YOUR_MQTT_TOPIC, "your message here")

Example 2:(Subscribe) Download/Read data from MQTT Broker

from MyMQTT import myMQTT
mq = myMQTT(server=MQTT_SERVER, client=MQTT_CLIENT)
mq.connect()
mq.subscribe(YOUR_MQTT_TOPIC)
while True:
message = mq.subCheck()
if message is not None:
print('\n *** Subscribe (Download) data from the MQTT Broker:', message)
time.sleep_ms(300) # check new message every 0.3 second

Example 3:(Callback) Download/Read data and do the action

def mqttCallback(topic, msg):
print("*** Callback ===> Received topic: {}, message: {}".format(topic, msg))
from MyMQTT import myMQTT
mq = myMQTT(server=MQTT_SERVER, client=MQTT_CLIENT)
mq.connect()
mq.setCallback(mqttCallback)
mq.subscribe(MQTT_TOPIC)
while True:
mq.subCheck() # check if new subscribed message published
time.sleep_ms(300) # check new message every 0.3 second

DEMO:

That’s all, so easy right ? Hope this helps !

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store