Software setup
Follow Micropython's instructions for installation and the setup. Make sure that you are able to use the WebREPL to upload files to your board. Use a boot.py file to enable the connection to your local WiFi network.
The file main.py will contain all code to consume MQTT messages and show a value. As shown before you will need <Region>, <AppID>, <AppKey> and <DeviceID>. Also, set NAME to the key for the sensor data which is stored in payload_fields. The communication with the display is done over I2C. For further details see the documentation about umqtt and I2C.
import json
import machine
import ssd1306
import time
from umqtt.simple import MQTTClient
DEVICE_NAME = '<DeviceID>'
TTN_BROKER = '<Region>.thethings.network'
TTN_USERNAME = '<AppID>'
TTN_PASSWORD = '<AppKey>'
TTN_TOPIC = '+/devices/{}/up'.format(DEVICE_NAME)
NAME = 'Temperature'
i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4))
oled = ssd1306.SSD1306_I2C(128, 32, i2c)
def sub_callback(topic, msg):
oled.fill(0)
oled.text(NAME, 25, 5)
oled.text(str(json.loads(msg)['payload_fields'][NAME.lower()]), 25, 20)
oled.show()
def main():
c = MQTTClient(
'ttn_client', TTN_BROKER, user=TTN_USERNAME, password=TTN_PASSWORD)
c.set_callback(sub_callback)
c.connect()
c.subscribe(TTN_TOPIC)
while True:
if True:
c.wait_msg()
else:
c.check_msg()
time.sleep(10)
c.disconnect()
if __name__ == "__main__":
main()
Save this and upload the file. After a reboot of the ESP8266 it could take some time till you get the first MQTT message. But as soon you get one, it will be shown on the display.