Node-RED and MQTT

The video below shows you how to connect Node-RED to the MQTT broker running on the Raspberry Pi:

Task: Try replicating the steps seen in the video.

Okay, once again: what did just happen there?

First we start with an empty flow and add an MQTT subscription node.

Add Subscribe Node

Next we set up the MQTT broker configuration to connect to the broker running on localhost:1883.

Configure broker

Then we configure the node to subscribe to the /led topic.

Subscribe to led topic

Next we set up an MQTT publish node to use the same broker and to publish to the /led topic.

Publish to led topic

Finally we add a debug output node and an injection node.

Add debug nodes

The inject node will, by default, inject a timestamp message, we configure it to instead publish the string on whenever it is triggered.

Inject “on”

The image below shows the flow in action: the injected message is sent to the broker, received by the subscription node and displayed by the debug node.

Run MQTT flow

Now that we know how to use Node-RED with MQTT we can make it actually do something.

Task: Add an injection node that injects the string off.

Task: Connect the microcontrollers that you programmed in the last chapter and controll the LEDs from Node-RED.

Later on we want to make our setup more flexible by routing all the messages through Node-RED.

Right now we will prepare that step by decoupling the functionality of the publishing microcontroller and the subscribing microcontroller.

Task: Edit the program on the publishing microcontroller to publish to the topic /button instead of the topic /led.

The publishing microcontroller should now no longer be able to controll the LED.

Task: In Node-RED: subscribe to the /button topic and, using a debug node, make sure that messages are correctly received there.

Task: In Node-RED: forward messages from the /button topic to the /led topic so that the publishing microcontroller can control the LED again.