Skip to main content

9.5 Node Red Tutorial

Node Red Setup

  1. In this tutorial, I am using a Linux terminal in Windows (WSL) for simplicity, if you're using other environment, that is fine too but some steps might be a little bit different, so be ready to adapt.

  2. Install Node and NPM

sudo apt update
sudo apt install nodejs npm
  1. Install Node Red
sudo npm install -g --unsafe-perm node-red
  1. Run Node Red
node-red

  1. Access the Node Red server http://127.0.0.1:1880/ in the web browser

Node Red Debug

  1. Drag Inject Node in to the editor

  1. Double click the node and set the payload type to String

  1. Set the Payload and Topic to whatever you want, then click the "Done" button

  1. Drag the Debug Node in to the editor

  1. Connect both nodes

  1. Click the "Deploy" button in the top right corner

  1. Click the button in the inject node

Node, ehem I mean Note: you can see the debug messages in the right section.

Node Red Dashboard

  1. Click the 3 stripes button in the top-right corner, then click "Manage Palette"

  1. Go to the "Install" section, search for dashboard in the search bar, then install the dashboard palette from @flowfuse. Click the "Done" button once it is finished.

  1. You should now see the "Dashboard 2" node section if you scroll down enough. If you don't, then try to refresh the web or try to restart Node Red. Once you found it, drag the "button" node to the editor

  1. Double click the button node, then set the name to "LED", group to default (look at the screenshot below for reference), Label to "Toggle LED" and click the "Done" button once it is all finished

  1. Now scroll above in the node section till you found the Function node section. Drag the "function" node to the editor and connect it with the "button" node that you've setup previously.

  1. Double click the "function" node and insert this code below, then click the "Done" button.
// Store LED state
context.ledState = context.ledState || false;

// Toggle LED state when button pressed
context.ledState = !context.ledState;

// Create message
msg.payload = {
    led_state: context.ledState,
    timestamp: new Date().toISOString(),
    message: context.ledState ? "LED ON" : "LED OFF"
};

return msg;

Note: The code here is to simulate an LED, since we haven't integrate to Wokwi yet in this Tutorial.

  1. Go back to the Dashboard 2 section and drag the "Text Output" node in to the editor and connect it with the "function" node

  1. Double click the "Text Output" node then apply these configurations. Set name to "LED Status", set the group to default (see the screenshot below for reference), set the label to "LED Status:", make sure the value type is msg and its value is "payload.message", and set the Layout the same as seen in the screenshot below. Click the "Done" button once eveything is finished.

9, Drag the "debug" node to the editor and connect it to the "function" node

  1. Click the dropdown icon in the top-right corner, then click on "Dashboard 2.0"

  1. Click on the setting of your default group

  1. Set the size to 3 x 1. You can change the value later on to experiment on the dashboard layout, but for now we keep it on 3 x 1 for simplicity. Click the "Update" button, once it is finished.

  1. Click the "Deploy" button so that the changes are reflected

  1. To check on the dashboard, click the "open dashboard" button

  1. You should be directed to a page similar to this. Try clicking on the "Toggle LED" button and see what happens.

  1. You can also see the log history in the debug section since you use the "debug" node

Node Red x Wokwi

  1. Drag the "Button Group" Node to the editor

  1. Double click the "Button Group" Node and apply this configuration

  1. Drag the "MQTT Out" Node to the editor

  1. Double click the "MQTT Out" node and add a MQTT server

  1. Apply this configuration and save the server

  1. Copy the remaining configuration for the "MQTT Out" node

Note: After this I added a "Debug" node that connects with the "Button Group" Node, but this is fully optional for you

  1. Drag the "MQTT In" node to the editor

  1. Double click the "MQTT IN" node and apply this configuration

  1. Drag the "Text Output" Node from the "Dashboard 2" Section and apply this configuration

  1. Create a new WOKWI ESP32 project and copy paste this code
#include <WiFi.h>
#include <PubSubClient.h>

// Wokwi WiFi - works in simulation
const char* ssid = "Wokwi-GUEST";
const char* password = "";

const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);

const int ledPin = 2;
bool ledState = false;

void setup_wifi() {
  delay(10);
  Serial.println("Connecting to WiFi...");
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* message, unsigned int length) {
  Serial.print("Message arrived on topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  
  String messageTemp;
  for (int i = 0; i < length; i++) {
    messageTemp += (char)message[i];
  }
  Serial.println(messageTemp);

  // Check if message is for LED control
  if (String(topic) == "wokwi/led/control") {
    Serial.print("Changing LED to ");
    if(messageTemp == "ON"){
      digitalWrite(ledPin, HIGH);
      ledState = true;
      Serial.println("ON");
      client.publish("wokwi/led/status", "ON");
    }
    else if(messageTemp == "OFF"){
      digitalWrite(ledPin, LOW);
      ledState = false;
      Serial.println("OFF");
      client.publish("wokwi/led/status", "OFF");
    }
  }
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "WokwiClient-";
    clientId += String(random(0xffff), HEX);
    
    // Attempt to connect
    if (client.connect(clientId.c_str())) {
      Serial.println("connected");
      // Subscribe to control topic
      client.subscribe("wokwi/led/control");
      // Publish connected message
      client.publish("wokwi/led/status", "connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  
  Serial.begin(115200);
  setup_wifi();
  
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // Add a small delay
  delay(100);
}
  1. Create the sketch where an LED is connected to PIN. The result should be similar to the following screenshot

  1. Add the PubSubClient library in the library manager

  1. Run the Wokwi simulation

Note: if you're having difficulties, you can follow this as a reference

  1. Deploy the Node Red project and go to the dashboard. You should be able to control the LED using the button there.