The Problem
In part 1 of this series we have covered the schematics and hardware for a IoT parking sensor. Now we are gonna have a look into the software which is able to transmit the state of the device to an arbitrary MQTT broker.
The Solution
The software is straight forward:
- Set up the display
- Connect to the WiFi
- Connect to the MQTT broker
- Read and transmit the sensor reading continuously
Here is my implementation:
WLAN_SSID = "iot" WLAN_PASS = "iot12345" MQTT_BROKER = "iot.eclipse.org" MQTT_TOPIC = "bytebang/pps/a" -- setup the display gdisplay.attach(gdisplay.SSD1306_128_64, gdisplay.LANDSCAPE, false, 0x3c) gdisplay.clear() gdisplay.setfont(gdisplay.UBUNTU16_FONT) -- Configure wifi in Station Mode with SSID gdisplay.write({gdisplay.CENTER,gdisplay.CENTER},"cnnct: " .. WLAN_SSID) net.wf.setup(net.wf.mode.STA, WLAN_SSID, WLAN_PASS) net.wf.start() tmr.sleepms(10000) -- Get current time from sntp server net.service.sntp.start() net.service.sntp.stop() -- connect to mqtt broker server = MQTT_BROKER print(MQTT_BROKER .. ": "..net.lookup(MQTT_BROKER)) gdisplay.write({gdisplay.CENTER,20},MQTT_BROKER) -- Connect to the MQTT Broker client = mqtt.client("myuniqueclientid",MQTT_BROKER, 1883, false) client:connect("","") -- READ THE SENSOR - GPIO13 (TRIG) and GPIO14 (ECHO) s = sensor.attach("US015", pio.GPIO13, pio.GPIO15) s:set("temperature", 25) -- inifinte loop while true do dist = 999 -- read the distance try(function() dist = s:read("distance") end) -- display it on the screen gdisplay.clear() gdisplay.write({gdisplay.CENTER,gdisplay.CENTER},tostring(dist)) -- transmit the value, and reconnect on error try(function() client:publish(MQTT_TOPIC,1 - (dist/100) ,mqtt.QOS0) end, function() client:connect("","")end) -- wait for a second tmr.sleepms(1000) end
Just save this snippet into a *.lua file and execute it from the shell. If you want to run it as soon as the ESP32 is powered up, then place it into the autorun.lua
OK - it is just a prototype, the following problems are not addressed within this snippet:
- Initial configuration of the MQTT and WIFI settings via shell or a commandline
- Reconnect if the WiFi becomes unavailable
- Consistent logging to the screen
- Usage of the secret reed sensor
- <Insert any other cool feature here>
If you need help, don’t hesitate to contact our professional services.
Happy coding !