Welcome to bytebang » The blog about all and nothing » IoT parking sensor - MQTT version

IoT parking sensor - MQTT version

May 14 2019

This blog post is not published yet.

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:

  1. Set up the display
  2. Connect to the WiFi
  3. Connect to the MQTT broker
  4. 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)

-- 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)

-- Get current time from sntp server

-- connect to mqtt broker
server = MQTT_BROKER
print(MQTT_BROKER .. ": "..net.lookup(MQTT_BROKER))

-- Connect to the MQTT Broker
client = mqtt.client("myuniqueclientid",MQTT_BROKER, 1883, false)

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

 -- 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

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 !

Get Social

(c) 2019, by bytebang e.U. - Impressum - Datenschutz / Nutzungsbedingungen