Node-RED guide series

Node-RED, the "switch" node

The "switch" node allows your flow to execute one of several possible paths depending on the rules you have specified.

The "switch" node is like the "if" statement in a text programming language.

Like the "if" statement, you can use the "switch" node to define one or more logical rules. According to the truthfulness (or falseness") of those rules, the "switch" node can be configured to trigger one or more paths of execution.

You can find the "switch" node in the "function" group of the left tool bar.

The "switch" node.

Setup the "switch" node

To explain how to use the "switch" node, I have create this simple flow:

This flow contains a "switch" node.

The flow begins with an "inject" node which will emit a numerical "6" when you click on the button.

The payload will go into the switch node, which will evaluate it. If the payload is larger than 5, then the top output will be triggered. If the payload is equal or less than 5, then the bottom output will be triggered.

Take a look inside the "switch" node:

The properties of the "switch" node.

I have marked the important fields of the edit pane with a box.

First, you must set the property to evaluate. In this case, I have configure the node to get the value from the message payload.

Next, you must define at least one rule to be evaluated. The rule is defined by a boolean comparator, a value, and the output that will be triggered if the rule is evaluated to be true.

The available comparators are comprehensive:

The comparators available in the "switch" node.

The last field in the edit menu allows you to set the evaluation mode. You can set the node to stop when it finds a true rule, or to evaluate all rules.

Go ahead and try out this example. Deploy the flow, and then click on the "inject" node's button. The output will be "6" from node ">5", as expected:

The output shows that the first rule of the "switch" node was true.

The "switch" node will evaluate numerical "6" and continue flow execution from the top output.

Learn Node-RED and how to use it with the ESP32

This course will guide you through the construction of an automated control system. The deliverable is a Terrarium controller.

Along the way, you will learn a great deal about useful technologies such as the Node Red programming environment and MQTT.

Browse this article
[publication_date]

We publish fresh content each week. Read how-to's on Arduino, ESP32, KiCad, Node-RED, drones and more. Listen to interviews. Learn about new tech with our comprehensive reviews. Get discount offers for our courses and books. Interact with our community. One email per week, no spam; unsubscribe at any time

{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}