MQTT Publish

Next we will program a microcontroller to publish information for the previous application to consume.

To do so we will connect a second microcontroller board to the Raspberry Pi. In order to reduce confusion later on on which board you are connect to you should open a new terminal emulator now, dedicated to working on the second microcontroller board.

Now connect the microcontroller board to your Raspberry Pi (disconnect and reconnect if it is already connected) and run dmesg like in the first chapter to find the name to use with picocom and nodemcu-uploader.

[user@computer ~]$ dmesg
…
[100000.000000] cp210x 1-9:1.0: cp210x converter detected
[100000.010000] usb 1-9: cp210x converter now attached to ttyUSB1

Now create a project folder for the publishing side of our application, based on the code written earlier:

cd projects
cp -rv chapter_3_sub/ chapter_3_pub
cd chapter_3_pub

As every client connect to the MQTT broker needs its own ID you have to edit the credentials.lua file in the chapter_3_pub folder and replace "ESP1" with "ESP2".

You are now ready to edit the application.lua in the chapter_3_pub folder. You can remove the mqtt_on_message function as it will not be used and replace the mqtt_on_connect function with the following code snippet:

function mqtt_on_connect(mc)
   print("MQTT connection successful")

   local status = gpio.HIGH

   function gpio_check(timer)
      local level = gpio.read(1)

      if level ~= status then
         status= level

         if level == gpio.HIGH then
            mc:publish("/led", "on", 1, 0)
         else
            mc:publish("/led", "off", 1, 0)
         end
      end
   end

   gpio.mode(1, gpio.INPUT, gpio.PULLUP)

   print("Install D1 watcher")

   local t = tmr.create()
   t:register(100, tmr.ALARM_AUTO, gpio_check)
   t:start()
end

Upload all .lua files in the chapter_3_pub folder to the second microcontroller board, connect picocom to the second board and press the reset button on the second board.

If everything went well the output should look something like this:

[user@computer ~]$ picocom -b 115200 /dev/ttyUSB1
…
init: connected to AP: nota_1
init: got IP address 192.168.94.159 via DHCP
init: startup will continue in 3s
init: handing over to application
MQTT connection successful
Install D1 watcher

Task: find out what the code does and use a piece of wire connected to GND to make the microcontroller publish messages. If everything went well you should be able to controll the LED on the first board by connecting a wire on the second board.