{"id":128776,"date":"2023-03-17T11:30:33","date_gmt":"2023-03-17T11:30:33","guid":{"rendered":"https:\/\/randomnerdtutorials.com\/?p=128776"},"modified":"2023-03-17T11:34:22","modified_gmt":"2023-03-17T11:34:22","slug":"esp8266-nodemcu-big-timer-node-red","status":"publish","type":"post","link":"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-big-timer-node-red\/","title":{"rendered":"ESP8266 Time-Based Events using Node-RED and Big Timer"},"content":{"rendered":"\n<p>In this tutorial, you&#8217;ll learn how to control the ESP8266 NodeMCU outputs using time-based events. For that, we&#8217;ll set up an automation system on Node-RED with the Big Timer node. This is a powerful and easy-to-use timing node that provides a huge range of timing facilities to create automated flows based on different time conditions: hours, minutes, days of the week, months, include\/exclude specific days or months, based on sunset and sunrise time, and much more.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" fetchpriority=\"high\" decoding=\"async\" width=\"1200\" height=\"675\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?resize=1200%2C675&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 NodeMCU Time-Based Events using Node-RED and Big Timer\" class=\"wp-image-128777\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?w=1280&amp;quality=100&amp;strip=all&amp;ssl=1 1280w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?resize=300%2C169&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?resize=1024%2C576&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?resize=768%2C432&amp;quality=100&amp;strip=all&amp;ssl=1 768w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Project Overview<\/h2>\n\n\n\n<p class=\"rntbox rntclgray\">The Big Timer Node was created by Peter Scargill. We recommend taking a look at the Big Timer page on Peter Scargill\u2019s blog: <a href=\"https:\/\/tech.scargill.net\/big-timer\/\" target=\"_blank\" rel=\"noopener\" title=\"\">Big Timer page.<\/a> Consider donating to the author if you think this node will be useful for your projects.<\/p>\n\n\n\n<p>To show you how you can use the Big Timer node in Node-RED to control the ESP8266 based on schedules, we&#8217;ll set up a system that automatically turns the ESP8266 GPIOs on and off at certain times. The Big Timer node allows you to set up complex schedule rules to determine when the GPIOs will be on and off.<\/p>\n\n\n\n<p>To communicate between Node-RED and the ESP8266, we&#8217;ll use MQTT communication protocol. Learn more about MQTT: <a href=\"https:\/\/randomnerdtutorials.com\/what-is-mqtt-and-how-it-works\/\">What is MQTT and How It Works<\/a>.<\/p>\n\n\n\n<p>The following diagram shows a high-level overview of the example we&#8217;ll build.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"1200\" height=\"1033\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=1200%2C1033&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Big Timer Node-RED Control ESP32 Outputs via MQTT\" class=\"wp-image-128780\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?w=3126&amp;quality=100&amp;strip=all&amp;ssl=1 3126w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=300%2C258&amp;quality=100&amp;strip=all&amp;ssl=1 300w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=1024%2C882&amp;quality=100&amp;strip=all&amp;ssl=1 1024w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=768%2C661&amp;quality=100&amp;strip=all&amp;ssl=1 768w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=1536%2C1323&amp;quality=100&amp;strip=all&amp;ssl=1 1536w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?resize=2048%2C1764&amp;quality=100&amp;strip=all&amp;ssl=1 2048w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-MQTT-ESP8266-Overview-02.png?w=2400&amp;quality=100&amp;strip=all&amp;ssl=1 2400w\" sizes=\"(max-width: 1200px) 100vw, 1200px\" \/><\/figure><\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>We&#8217;ll create a Node-RED flow with the Big Timer node. We&#8217;ll set up the timer to send ON and OFF messages at specific times. You can create any schedule conditions easily with the Big Timer node. We&#8217;ll send a <strong>0<\/strong> at the OFF time and a <strong>1<\/strong> at the ON time.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The output of the Big Timer node will be published on a topic that contains the GPIO number we want to control. In our example, we&#8217;ll use the following topic: <span class=\"rnthl rntliteral\">esp8266\/digital\/&lt;<strong>gpio<\/strong>&gt;<\/span>, in which <strong>&lt;gpio&gt;<\/strong> represents the GPIO number you want to control. For example, if you want to control GPIO 2, you would publish on the following topic <span class=\"rnthl rntliteral\">esp8266\/digital\/2<\/span>.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The ESP8266 is subscribed to the multi-level topic <span class=\"rnthl rntliteral\">esp8266\/digital\/#<\/span>, so it receives all messages of any topic that begins with <span class=\"rnthl rntliteral\">esp8266\/digital<\/span>. This means it receives all messages, regardless of the GPIO you want to control.<\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The ESP8266 will receive a different message at the ON and OFF times (1 and 0) on a topic that contains the GPIO to be controlled. This way, we can easily control the ESP8266 GPIOs automatically accordingly to the schedule set up on the Big Timer node.<\/li>\n<\/ul>\n\n\n\n<p>This project is divided into two parts:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><a href=\"#program-esp32-subscribe-mqtt\" title=\"\">Program the <\/a><a href=\"#program-esp8266-subscribe-mqtt\" title=\"\">ESP8266<\/a> <a href=\"#program-esp32-subscribe-mqtt\" title=\"\">(subscribe to MQTT topic)<\/a><\/li>\n\n\n\n<li><a href=\"#node-red-flow-big-timer\" title=\"\">Setup the Node-RED Flow<\/a><\/li>\n<\/ol>\n\n\n\n<h2 class=\"wp-block-heading\">Prerequisites<\/h2>\n\n\n\n<p>Before continuing, make sure you follow all the next pre-requisites:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/node-red-big-timer-automation\/\">Install Node-RED and the Big Timer node;<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/how-to-install-mosquitto-broker-on-raspberry-pi\/\" title=\"\">Set up Mosquitto broker on your Raspberry Pi or set up any other MQTT broker;<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"program-esp8266-subscribe-mqtt\">1) Program the ESP8266 &#8211; Subscribe to MQTT Topic (Receive Big Timer messages)<\/h2>\n\n\n\n<p>In this section, we&#8217;ll program the ESP8266 to subscribe to the same topic that the Big Timer node is publishing. Then, we&#8217;ll automatically set the corresponding ESP8266 output states to on or off depending on the message received via MQTT.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Installing the AsyncMQTT Library<\/h3>\n\n\n\n<p>There are several MQTT libraries that you can use to set the ESP8266 as an MQTT client. We\u2019ll use the AsyncMQTT library. Click on the following link to download the library ZIP file:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>AsyncMQTT: <a href=\"https:\/\/github.com\/marvinroger\/async-mqtt-client\/archive\/refs\/heads\/develop.zip\" target=\"_blank\" rel=\"noopener\" title=\"\">https:\/\/github.com\/marvinroger\/async-mqtt-client\/archive\/refs\/heads\/develop.zip<\/a> <\/li>\n<\/ul>\n\n\n\n<p>You also need to install the ESPAsyncTCP library. Click on the following link to download the library:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>ESPAsyncTCP: <a href=\"https:\/\/github.com\/me-no-dev\/ESPAsyncTCP\/archive\/refs\/heads\/master.zip\" target=\"_blank\" rel=\"noopener\" title=\"\">https:\/\/github.com\/me-no-dev\/ESPAsyncTCP\/archive\/refs\/heads\/master.zip<\/a><\/li>\n<\/ul>\n\n\n\n<p>Now that you\u2019ve downloaded all the required library files, let\u2019s install them.<\/p>\n\n\n\n<p>Open your Arduino IDE, go to <strong>Sketch<\/strong> &gt; <strong>Include Library<\/strong> &gt; <strong>Add .ZIP library, <\/strong>and select the ZIP file for the AsyncMQTT library. Repeat the same process for the AsyncTCP library. After installing the libraries, restart your Arduino IDE and proceed to the next unit.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" decoding=\"async\" width=\"573\" height=\"262\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/install-library-arduino-ide-via-zip.png?resize=573%2C262&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Arduino IDE Install Libraries via ZIP folder\" class=\"wp-image-128717\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/install-library-arduino-ide-via-zip.png?w=573&amp;quality=100&amp;strip=all&amp;ssl=1 573w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/install-library-arduino-ide-via-zip.png?resize=300%2C137&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 573px) 100vw, 573px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Programming the ESP8266 &#8211; Subscribe to MQTT Topic<\/h3>\n\n\n\n<p>After installing the required libraries, you can finally program the ESP8266 to subscribe to an MQTT topic and turn the GPIOs on and off automatically.<\/p>\n\n\n\n<p>Upload the following code to your board\u2014before uploading you need to insert your network credentials (SSID and password), MQTT broker IP address or URL, MQTT username and password, if applicable.<\/p>\n\n\n<pre style=\"max-height: 40em; margin-bottom: 20px;\"><code class=\"language-c\">\/*********\n  Rui Santos\n  Complete project details: https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-big-timer-node-red\/\n  \n  Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files.\n  The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n*********\/\n\n#include &lt;Arduino.h&gt;\n\n#include &lt;ESP8266WiFi.h&gt;\n#include &lt;Ticker.h&gt;\n#include &lt;AsyncMqttClient.h&gt;\n\n#define WIFI_SSID &quot;REPLACE_WITH_YOUR_SSID&quot;\n#define WIFI_PASSWORD &quot;REPLACE_WITH_YOUR_PASSWORD&quot;\n\n\/\/ BROKER\n#define MQTT_HOST IPAddress(192, 168, 1, XXX) \/\/MQTT BROKER IP ADDRESS\n\/*for example:\n#define MQTT_HOST IPAddress(192, 168, 1, 106)*\/\n#define MQTT_PORT 1883\n#define BROKER_USER &quot;REPLACE_WITH_BROKER_USERNAME&quot;\n#define BROKER_PASS &quot;REPLACE_WITH_BROKER_PASSWORD&quot;\n\n\/\/MQTT Subscribe Topics\n#define MQTT_SUB_DIGITAL &quot;esp8266\/digital\/#&quot;\n\nAsyncMqttClient mqttClient;\n\nTicker mqttReconnectTimer;\nWiFiEventHandler wifiConnectHandler;\nWiFiEventHandler wifiDisconnectHandler;\nTicker wifiReconnectTimer;\n\n\nvoid connectToWifi() {\n  Serial.println(&quot;Connecting to Wi-Fi...&quot;);\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\n}\n\nvoid connectToMqtt() {\n  Serial.println(&quot;Connecting to MQTT...&quot;);\n  mqttClient.connect();\n}\n\nvoid onWifiConnect(const WiFiEventStationModeGotIP&amp; event) {\n  Serial.println(&quot;Connected to Wi-Fi.&quot;);\n  connectToMqtt();\n}\n\nvoid onWifiDisconnect(const WiFiEventStationModeDisconnected&amp; event) {\n  Serial.println(&quot;Disconnected from Wi-Fi.&quot;);\n  mqttReconnectTimer.detach(); \/\/ ensure we don't reconnect to MQTT while reconnecting to Wi-Fi\n  wifiReconnectTimer.once(2, connectToWifi);\n}\n\nvoid onMqttConnect(bool sessionPresent) {\n  Serial.println(&quot;Connected to MQTT.&quot;);\n  Serial.print(&quot;Session present: &quot;);\n  Serial.println(sessionPresent);\n  \/\/Subscribe to topics\n  \/\/ Subscribe to topic MQTT_SUB_DIGITAL when it connects to the broker\n  uint16_t packetIdSub1 = mqttClient.subscribe(MQTT_SUB_DIGITAL, 2);\n  Serial.print(&quot;Subscribing at QoS 2, packetId: &quot;);\n  Serial.println(packetIdSub1);\n}\n\nvoid onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {\n  Serial.println(&quot;Disconnected from MQTT.&quot;);\n\n  if (WiFi.isConnected()) {\n    mqttReconnectTimer.once(2, connectToMqtt);\n  }\n}\n\nvoid onMqttSubscribe(uint16_t packetId, uint8_t qos) {\n  Serial.println(&quot;Subscribe acknowledged.&quot;);\n  Serial.print(&quot;  packetId: &quot;);\n  Serial.println(packetId);\n  Serial.print(&quot;  qos: &quot;);\n  Serial.println(qos);\n}\n\nvoid onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {\n  \/\/ Do whatever you want when you receive a message\n  \n  \/\/ Save the message in a variable\n  String receivedMessage;\n  for (int i = 0; i &lt; len; i++) {\n    Serial.println((char)payload[i]);\n    receivedMessage += (char)payload[i];\n  }\n  \/\/ Save topic in a String variable\n  String receivedTopic = String(topic);  \n  Serial.print(&quot;Received Topic: &quot;);\n  Serial.println(receivedTopic);\n\n  \/\/ Check which GPIO we want to control\n  int stringLen = receivedTopic.length();\n  \/\/ Get the index of the last slash\n  int lastSlash = receivedTopic.lastIndexOf(&quot;\/&quot;);\n  \/\/ Get the GPIO number (it's after the last slash &quot;\/&quot;)\n  \/\/ esp\/digital\/GPIO\n  String gpio = receivedTopic.substring(lastSlash+1, stringLen);\n  Serial.print(&quot;DIGITAL GPIO: &quot;);\n  Serial.println(gpio);\n  Serial.print(&quot;STATE: &quot;);\n  Serial.println(receivedMessage);\n\n  \/\/ Check if it is DIGITAL\n  if (receivedTopic.indexOf(&quot;digital&quot;) &gt; 0) {\n    \/\/Set the specified GPIO as output\n    pinMode(gpio.toInt(), OUTPUT);\n    \/\/Control the GPIO\n    if (receivedMessage == &quot;1&quot;){\n      digitalWrite(gpio.toInt(), HIGH);\n    }\n    else{\n      digitalWrite(gpio.toInt(), LOW);\n    }\n  }\n  Serial.println(&quot;Publish received.&quot;);\n  Serial.print(&quot;  topic: &quot;);\n  Serial.println(topic);\n  Serial.print(&quot;  qos: &quot;);\n  Serial.println(properties.qos);\n  Serial.print(&quot;  dup: &quot;);\n  Serial.println(properties.dup);\n  Serial.print(&quot;  retain: &quot;);\n  Serial.println(properties.retain);\n  Serial.print(&quot;  len: &quot;);\n  Serial.println(len);\n  Serial.print(&quot;  index: &quot;);\n  Serial.println(index);\n  Serial.print(&quot;  total: &quot;);\n  Serial.println(total);\n}\n\nvoid onMqttPublish(uint16_t packetId) {\n  Serial.println(&quot;Publish acknowledged.&quot;);\n  Serial.print(&quot;  packetId: &quot;);\n  Serial.println(packetId);\n}\n\nvoid setup() {\n  Serial.begin(115200);\n  Serial.println();\n  Serial.println();\n\n  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);\n  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);\n\n  mqttClient.onConnect(onMqttConnect);\n  mqttClient.onDisconnect(onMqttDisconnect);\n  mqttClient.onSubscribe(onMqttSubscribe);\n  mqttClient.onMessage(onMqttMessage);\n  mqttClient.onPublish(onMqttPublish);\n  \n  mqttClient.setServer(MQTT_HOST, MQTT_PORT);\n  mqttClient.setCredentials(BROKER_USER, BROKER_PASS);\n\n  connectToWifi();\n}\n\nvoid loop() {\n\n}\n<\/code><\/pre>\n\t<p style=\"text-align:center\"><a class=\"rntwhite\" href=\"https:\/\/github.com\/RuiSantosdotme\/Random-Nerd-Tutorials\/raw\/master\/Projects\/ESP8266\/ESP8266_MQTT_Subscribe_Control_Outputs.ino\" target=\"_blank\">View raw code<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How the Code Works<\/h3>\n\n\n\n<p>Continue reading to learn how the code works or skip to the <a href=\"#demonstration\" title=\"\">Demonstration section<\/a>.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Include Libraries<\/h4>\n\n\n\n<p>First, we need to include the required libraries. To set the board as an MQTT client, we\u2019re using the <span class=\"rnthl rntliteral\">AsyncMQTTClient<\/span> library as we&#8217;ve mentioned previously.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#include &lt;ESP8266WiFi.h&gt;\n#include &lt;Ticker.h&gt;\n#include &lt;AsyncMqttClient.h&gt;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Wi-Fi Credentials and Broker Details<\/h4>\n\n\n\n<p>You need to include your network credentials on the following lines (SSID and password) so that your board can establish a Wi-Fi connection with your router.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define WIFI_SSID \"REPLACE_WITH_YOUR_SSID\"\n#define WIFI_PASSWORD \"REPLACE_WITH_YOUR_PASSWORD\"<\/code><\/pre>\n\n\n\n<p>You need to insert your MQTT broker IP address. It corresponds to the Raspberry Pi IP address:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_HOST IPAddress(192, 168, 1, XXX)  \/\/MQTT BROKER IP ADDRESS\n\/*for example:\n#define MQTT_HOST IPAddress(192, 168, 1, 106)*\/<\/code><\/pre>\n\n\n\n<p>The MQTT broker port is 1883.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define MQTT_PORT 1883<\/code><\/pre>\n\n\n\n<p>Insert your MQTT broker username and password on the following lines.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>#define BROKER_USER \"REPLACE_WITH_BROKER_USERNAME\"\n#define BROKER_PASS \"REPLACE_WITH_BROKER_PASSWORD\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Subscribe to MQTT Topic<\/h4>\n\n\n\n<p>Define the MQTT topic you want your board to subscribe to. We\u2019ll subscribe to multiple topics at once by using the multi-level wildcard (<span class=\"rnthl rntliteral\">#<\/span>).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/MQTT Subscribe Topics\n#define MQTT_SUB_DIGITAL \"esp8266\/digital\/#\"<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">AsyncMQTTClient<\/h4>\n\n\n\n<p>The following line creates an <span class=\"rnthl rntliteral\">AsyncMQTTClient<\/span> object called <span class=\"rnthl rntliteral\">mqttClient<\/span>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>AsyncMqttClient mqttClient;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Timers for Wi-Fi Events<\/h4>\n\n\n\n<p>Then, we create timers for the Wi-Fi events. This section is needed so that we can detect Wi\u2011Fi and MQTT events like connecting and disconnecting and automatically call functions (asynchronously) when those events happen. The following lines are creating the timers and handlers.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Ticker mqttReconnectTimer;\nWiFiEventHandler wifiConnectHandler;\nWiFiEventHandler wifiDisconnectHandler;\nTicker wifiReconnectTimer;<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Connect to Wi-Fi<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">connectToWiFi()<\/span> function will be called later to connect your ESP board to Wi\u2011Fi.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void connectToWifi() {\n  Serial.println(\"Connecting to Wi-Fi...\");\n  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Connect to MQTT<\/h4>\n\n\n\n<p>As the name suggests, the <span class=\"rnthl rntliteral\">connectToMqtt()<\/span> function connects the MQTT client (your board) to the broker.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void connectToMqtt() {\n  Serial.println(\"Connecting to MQTT...\");\n  mqttClient.connect();\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Wi-Fi Events<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onWiFiConnect()<\/span> and <span class=\"rnthl rntliteral\">onWiFiDisconnect()<\/span> will run whenever the ESP8266 connects or disconnects to Wi-Fi.<\/p>\n\n\n\n<p>When it connects to Wi-Fi, the board will connect to the MQTT broker by calling the <span class=\"rnthl rntliteral\">connectToMqtt()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onWifiConnect(const WiFiEventStationModeGotIP&amp; event) {\n  Serial.println(\"Connected to Wi-Fi.\");\n  connectToMqtt();\n}<\/code><\/pre>\n\n\n\n<p>When it disconnects to Wi-Fi, it will try to connect again by calling the <span class=\"rnthl rntliteral\">connectToWifi()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onWifiDisconnect(const WiFiEventStationModeDisconnected&amp; event) {\n  Serial.println(\"Disconnected from Wi-Fi.\");\n  mqttReconnectTimer.detach(); \/\/ ensure we don't reconnect to MQTT while reconnecting to Wi-Fi\n  wifiReconnectTimer.once(2, connectToWifi);\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">onMQTTConnect()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onMQTTConnect()<\/span> function will be called when the board is connected successfully to the MQTT broker. In this example, we print a debugging message about the current MQTT session.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttConnect(bool sessionPresent) {\n  Serial.println(\"Connected to MQTT.\");\n  Serial.print(\"Session present: \");\n  Serial.println(sessionPresent);\n  \/\/Subscribe to topics\n  \/\/ Subscribe to topic MQTT_SUB_DIGITAL when it connects to the broker\n  uint16_t packetIdSub1 = mqttClient.subscribe(MQTT_SUB_DIGITAL, 2);\n  Serial.print(\"Subscribing at QoS 2, packetId: \");\n  Serial.println(packetIdSub1);\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Subscribe to Topics<\/h4>\n\n\n\n<p>To subscribe to an MQTT topic, it\u2019s a good idea to do that right after the ESP connects to the broker, so we do that inside the <span class=\"rnthl rntliteral\">onMQTTConnect()<\/span> function.<\/p>\n\n\n\n<p>To subscribe to topics, simply call the <span class=\"rnthl rntliteral\">subscribe()<\/span> method on the mqttClient object. It accepts as arguments the topic you want to subscribe to and the QoS (quality of service\u2014it can be 0, 1 or 2). This function outputs the <em>packet Id<\/em> (which is simply a number to identify the packet).<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>uint16_t packetIdSub1 = mqttClient.subscribe(MQTT_SUB_DIGITAL, 2);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">onMQTTDisconnect()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onMQTTDisconnect()<\/span> function will be called when the broker suddenly disconnects. When that happens, we try to reconnect.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {\n  Serial.println(\"Disconnected from MQTT.\");\n\n  if (WiFi.isConnected()) {\n    mqttReconnectTimer.once(2, connectToMqtt);\n  }\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">onMqttSubscribe()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onMQTTSubscribe()<\/span> function will run when you subscribe to a topic. In this example, it just prints messages about the packet ID and QoS, but you can add other tasks.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttSubscribe(uint16_t packetId, uint8_t qos) {\n  Serial.println(\"Subscribe acknowledged.\");\n  Serial.print(\"  packetId: \");\n  Serial.println(packetId);\n  Serial.print(\"  qos: \");\n  Serial.println(qos);\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Receive Messages and Control Outputs<\/h4>\n\n\n\n<p>Whenever a message is received on a subscribed topic, the <span class=\"rnthl rntliteral\">onMqttMessage()<\/span> runs.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {\n\n  \/\/ Do whatever you want when you receive a message<\/code><\/pre>\n\n\n\n<p>So, we must add what we want the ESP to do when it receives a message. We need to get the GPIO we want to control (it\u2019s the last topic level), and the state (it\u2019s the payload message).<\/p>\n\n\n\n<p>First, we save the message on the <span class=\"rnthl rntliteral\">receivedMessage<\/span> variable.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Save the message in a variable\nString receivedMessage;\nfor (int i = 0; i &lt; len; i++) {\n  Serial.println((char)payload&#091;i]);\n  receivedMessage += (char)payload&#091;i];\n}<\/code><\/pre>\n\n\n\n<p>Then, we convert the topic to a String variable (<span class=\"rnthl rntliteral\">receivedTopic<\/span>) so it\u2019s easier to manipulate later.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Save topic in a String variable\nString receivedTopic = String(topic);  \nSerial.print(\"Received Topic: \");\nSerial.println(receivedTopic);<\/code><\/pre>\n\n\n\n<p>The GPIO we want to control comes in the topic, and it is the last level of the topic. For example: <strong>esp8266\/digital\/2<\/strong>. We can split the string in the last slash <span class=\"rnthl rntliteral\">\/<\/span>, and we\u2019ll have the GPIO number.<\/p>\n\n\n\n<p>First, we get the length of the topic.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Check which GPIO we want to control\nint stringLen = receivedTopic.length();<\/code><\/pre>\n\n\n\n<p>Then, we can use the <span class=\"rnthl rntliteral\">lastIndexOf()<\/span> function to discover the position of the last slash. The <span class=\"rnthl rntliteral\">lastIndexOf()<\/span> method locates a string within another String. It starts searching from the end of the String.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Get the index of the last slash\nint lastSlash = receivedTopic.lastIndexOf(\"\/\");<\/code><\/pre>\n\n\n\n<p>Once we know the position of the last slash, we can split the string using the <span class=\"rnthl rntliteral\">substring()<\/span> method. The <span class=\"rnthl rntliteral\">substring()<\/span> method gets a substring of a string starting and ending at determined positions. Learn more about the <a href=\"https:\/\/www.arduino.cc\/reference\/en\/language\/variables\/data-types\/string\/functions\/substring\/\" target=\"_blank\" rel=\"noopener\" title=\"\">substring() method<\/a>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Get the GPIO number (it's after the last slash \"\/\")\n\/\/ esp\/digital\/GPIO\nString gpio = receivedTopic.substring(lastSlash+1, stringLen);\nSerial.print(\"DIGITAL GPIO: \");\nSerial.println(gpio);\nSerial.print(\"STATE: \");\nSerial.println(receivedMessage);<\/code><\/pre>\n\n\n\n<p>Then, we control the LED on or off accordingly to the message content using the <span class=\"rnthl rntliteral\">digitalWrite()<\/span> function:<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>\/\/ Check if it is DIGITAL\nif (receivedTopic.indexOf(\"digital\") &gt; 0) {\n  \/\/Set the specified GPIO as output\n  pinMode(gpio.toInt(), OUTPUT);\n  \/\/Control the GPIO\n  if (receivedMessage == \"1\"){\n    digitalWrite(gpio.toInt(), HIGH);\n  }\n  else{\n    digitalWrite(gpio.toInt(), LOW);\n  }<\/code><\/pre>\n\n\n\n<p>As you can see, we don\u2019t need to hardcode any GPIO numbers, because we declare them and control them accordingly to the topics received.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">onMqttPublish()<\/h4>\n\n\n\n<p>The <span class=\"rnthl rntliteral\">onMqttPublish()<\/span> message runs when we publish a message on a topic. In this case, it simply prints the packet id in the Serial Monitor. You can add other tasks that may make sense for your project.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void onMqttPublish(uint16_t packetId) {\n  Serial.println(\"Publish acknowledged.\");\n  Serial.print(\"  packetId: \");\n  Serial.println(packetId);\n}<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">setup()<\/h4>\n\n\n\n<p>In the <span class=\"rnthl rntliteral\">setup()<\/span>, we initialize the Serial Monitor at a baud rate of 115200.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>Serial.begin(115200);\nSerial.println();\nSerial.println();<\/code><\/pre>\n\n\n\n<p>The following lines create the event handlers for when the WiFi connects or disconnects.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);\nwifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);<\/code><\/pre>\n\n\n\n<p>Basically, this means that when the ESP8266 connects successfully to Wi-Fi and gets an IP address (<span class=\"rnthl rntliteral\">onStationModeGotIP<\/span>), it will run the <span class=\"rnthl rntliteral\">onWiFiConnect<\/span> function. When it disconnects from Wi-Fi (<span class=\"rnthl rntliteral\">onStationModeDisconnected<\/span>), it will run the <span class=\"rnthl rntliteral\">onWiFiDisconnect<\/span> function.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Assigning callback functions<\/h4>\n\n\n\n<p>The AsyncMQTT is an asynchronous library. This means that it works with events and callback functions. You create the callback functions and then, assign them to a certain event. When that event happens, the board will automatically run the corresponding callback function. This means that you can be running other tasks on the <span class=\"rnthl rntliteral\">loop()<\/span> and whenever one of the events happens, the corresponding callback functions will run.<\/p>\n\n\n\n<p><strong>Important:<\/strong> one thing you need to keep in mind when creating the callback functions (all those functions we have taken a look at previously) is to never use blocking functions inside them like <span class=\"rnthl rntliteral\">delay()<\/span> or <span class=\"rnthl rntliteral\">yield()<\/span> or methods that use <span class=\"rnthl rntliteral\">delay()<\/span> or <span class=\"rnthl rntliteral\">yield()<\/span>.<\/p>\n\n\n\n<p>On the following lines, we assign the callback functions to their corresponding events.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mqttClient.onConnect(onMqttConnect);\nmqttClient.onDisconnect(onMqttDisconnect);\nmqttClient.onSubscribe(onMqttSubscribe);\nmqttClient.onMessage(onMqttMessage);\nmqttClient.onPublish(onMqttPublish);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Set the MQTT Server and Credentials<\/h4>\n\n\n\n<p>The next two lines set the MQTT host and port, and set the credentials.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>mqttClient.setServer(MQTT_HOST, MQTT_PORT);\nmqttClient.setCredentials(BROKER_USER, BROKER_PASS);<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Connect to Wi-Fi<\/h4>\n\n\n\n<p>Finally, we connect to Wi-Fi by calling the <span class=\"rnthl rntliteral\">connectToWiFi()<\/span> function.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>connectToWifi();<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">loop()<\/h2>\n\n\n\n<p>In this example, the <span class=\"rnthl rntliteral\">loop()<\/span> is empty, but you can add any tasks that you need your ESP8266 to do. For example, publishing messages on MQTT topics.<\/p>\n\n\n\n<pre class=\"wp-block-code language-c\"><code>void loop() {\n\n}<\/code><\/pre>\n\n\n\n<p>That\u2019s pretty much how the code works.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Uploading the Code<\/h1>\n\n\n\n<p>After inserting your network credentials and MQTT broker details, you can upload the code to your board.<\/p>\n\n\n\n<p>First, go to <strong>Tools<\/strong> &gt; <strong>Board<\/strong> and select the board you\u2019re using. Then, select the COM port in <strong>Tools<\/strong> &gt; <strong>Port<\/strong>. Finally, press the <strong>Upload<\/strong> button.<\/p>\n\n\n\n<p>After successfully uploading the code to the board, open the Serial Monitor at a baud rate of 115200.<\/p>\n\n\n\n<p>Press the board RST button to restart it and start running the code.<\/p>\n\n\n\n<p>You should see the ESP8266 board successfully subscribing to the topic we defined in the code.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"601\" height=\"349\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-subscribe-to-topic-mqtt-serial-monitor.png?resize=601%2C349&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 subscribe to MQTT topic Serial Monitor\" class=\"wp-image-128783\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-subscribe-to-topic-mqtt-serial-monitor.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-subscribe-to-topic-mqtt-serial-monitor.png?resize=300%2C174&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<p>Let the Serial Monitor open and let&#8217;s build the Node-RED flow.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity is-style-wide\"\/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"node-red-flow-big-timer\">2) Set up the Node-RED Flow with Big Timer<\/h2>\n\n\n\n<p>In this section, we&#8217;ll build a Node-RED flow with the Big Timer node to create a schedule to send ON and OFF commands via MQTT to control the ESP8266 GPIOs.<\/p>\n\n\n\n<p class=\"rntbox rntclgray\">You should have already installed the Big Timer node on Node-RED. If not, <strong><a href=\"https:\/\/randomnerdtutorials.com\/node-red-big-timer-automation\/\" title=\"\">check this tutorial<\/a><\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Creating the Node-RED Flow<\/h3>\n\n\n\n<p class=\"has-text-align-left\">Drag a <strong>Big Timer<\/strong> node to the flow. Add an <strong>MQTT out<\/strong> node, and a <strong>debug <\/strong>node. Wire the nodes as shown in the picture below.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"439\" height=\"130\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-with-mqtt-example-flow-node-red.png?resize=439%2C130&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Set up the Node-RED Flow with Big Timer\" class=\"wp-image-128731\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-with-mqtt-example-flow-node-red.png?w=439&amp;quality=100&amp;strip=all&amp;ssl=1 439w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-with-mqtt-example-flow-node-red.png?resize=300%2C89&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 439px) 100vw, 439px\" \/><\/figure><\/div>\n\n\n<p>The first output of the Big Timer node sends a payload message of the current state at the specified times. The second output sends a status message of 1 or 0 every minute, so it is ideal to wire to an output debug node.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">MQTT Node<\/h4>\n\n\n\n<p>Double-click on the MQTT node.<\/p>\n\n\n\n<p>Click on the pencil icon next to the <strong>Server<\/strong> field if you haven&#8217;t set the MQTT broker yet.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"657\" height=\"517\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/set-up-mqtt-broker-node.png?resize=657%2C517&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"edit MQTT node broker credentials\" class=\"wp-image-128732\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/set-up-mqtt-broker-node.png?w=657&amp;quality=100&amp;strip=all&amp;ssl=1 657w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/set-up-mqtt-broker-node.png?resize=300%2C236&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 657px) 100vw, 657px\" \/><\/figure><\/div>\n\n\n<p>If you&#8217;re running Mosquitto MQTT broker and Node-RED on the Raspberry Pi or on the same machine, set the server to <strong>localhost <\/strong>and port <strong>1883<\/strong>. If you&#8217;re using another MQTT broker, insert the broker URL on the server field.<\/p>\n\n\n\n<p>Don&#8217;t forget to go to the <strong>Security tab and insert your broker username and password. <\/strong>After filling in<strong> <\/strong>all the details, click <strong>Update<\/strong>.<\/p>\n\n\n\n<p>Now, you can set to which topic we want to publish the message. We&#8217;ve seen previously that the ESP8266 will be subscribed to all messages on the topic <strong>esp8266\/digital\/#<\/strong>. So, we can publish on topics like <strong>esp8266\/digital\/4<\/strong>, or <strong>esp8266\/digital\/2<\/strong> to control the GPIOs 4 and 2 respectively. For testing purposes, we&#8217;ll publish on the <strong>esp8266\/digital\/2<\/strong> topic to control the ESP8266 GPIO 2, the buill-in LED.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"527\" height=\"392\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-node-publish-message-ESP8266.png?resize=527%2C392&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Node-RED MQTT Publish messages to ESP8266\" class=\"wp-image-128781\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-node-publish-message-ESP8266.png?w=527&amp;quality=100&amp;strip=all&amp;ssl=1 527w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/MQTT-node-publish-message-ESP8266.png?resize=300%2C223&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 527px) 100vw, 527px\" \/><\/figure><\/div>\n\n\n<p>You can also set the QoS value and if you want to retain the messages or not. <\/p>\n\n\n\n<div class=\"wp-block-group rntbox rntclgray\"><div class=\"wp-block-group__inner-container is-layout-constrained wp-block-group-is-layout-constrained\">\n<p><strong>What are retained messages in MQTT?<\/strong> <strong>retain (true or false) what does it mean?<\/strong><\/p>\n\n\n\n<p>A retained message is a normal MQTT message with the retained flag set to true. The broker stores the last retained message and the corresponding QoS for that topic.&nbsp;Each client that subscribes to a topic pattern that matches the topic of the retained message receives the retained message immediately after they subscribe. The broker stores only one retained message per topic.<\/p>\n\n\n\n<p><strong>Why is it useful?<\/strong> Retained messages help newly-subscribed clients get a status update immediately after they subscribe to a topic. This is particularly useful to get the status of a device. For example, GPIO 2 is currently HIGH, and the ESP8266 suddenly resets. It doesn\u2019t know what the last state of GPIO 2 was. However, if the state is a retained message, it will receive it right after subscribing to the topic and can update the state of GPIO 2 immediately.<\/p>\n<\/div><\/div>\n\n\n\n<h4 class=\"wp-block-heading\">Big Timer Node<\/h4>\n\n\n\n<p>Double-click on the <strong>Big Timer<\/strong> node to edit its properties. <\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"606\" height=\"891\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-set-on-time-off-time-messages.png?resize=606%2C891&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Setting Big Timer Node properties\" class=\"wp-image-128741\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-set-on-time-off-time-messages.png?w=606&amp;quality=100&amp;strip=all&amp;ssl=1 606w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-set-on-time-off-time-messages.png?resize=204%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 204w\" sizes=\"(max-width: 606px) 100vw, 606px\" \/><\/figure><\/div>\n\n\n<p>Fill the <strong>On Time<\/strong> and <strong>Off Time<\/strong> fields with the time you want to turn an ESP8266 GPIO on and off. For demonstration purposes, we recommend selecting something close to the current time so that you can easily see if it is working as expected. Use the offset times if needed. You can then, try the other options to create more complex schedules.<\/p>\n\n\n\n<p>The on message payload and off message payload should be filled on the <strong>On Msg<\/strong> and <strong>OFF Msg<\/strong> fields. We&#8217;re setting the <strong>On Msg<\/strong> to <span class=\"rnthl rntliteral\">1<\/span> and the <strong>Off Msg<\/strong> to <span class=\"rnthl rntliteral\">0<\/span>. This means that it will output a <span class=\"rnthl rntliteral\">1<\/span> when it reaches the On Time and a <span class=\"rnthl rntliteral\">0<\/span> at Off time.<\/p>\n\n\n\n<p>If you scroll down on the Big Timer node properties, you&#8217;ll find some more options. I would like to call your attention to the <strong>Repeat output<\/strong> and<strong> Output at startup<\/strong> options.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"429\" height=\"180\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-node-red-repeat-output.png?resize=429%2C180&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"set up node-red big timer node configurations\" class=\"wp-image-128748\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-node-red-repeat-output.png?w=429&amp;quality=100&amp;strip=all&amp;ssl=1 429w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-node-red-repeat-output.png?resize=300%2C126&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 429px) 100vw, 429px\" \/><\/figure><\/div>\n\n\n<p>If you have enabled the <strong>Repeat Output<\/strong> option, it means that it will output a message with the current On or Off message every minute. This means, in our example, that it will publish an MQTT message every minute\u2014this might be an interesting feature depending on your project application.<\/p>\n\n\n\n<p>The <strong>Output at startup<\/strong> option means that it will output the current On or Off message right after we deploy the Node-RED flow.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">Debug Node<\/h4>\n\n\n\n<p>Optionally, you can also edit the debug node properties so that it shows the complete output message.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"518\" height=\"356\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/debug-node-complete-msg-object.png?resize=518%2C356&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"set up debug node Node-RED\" class=\"wp-image-128696\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/debug-node-complete-msg-object.png?w=518&amp;quality=100&amp;strip=all&amp;ssl=1 518w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/debug-node-complete-msg-object.png?resize=300%2C206&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 518px) 100vw, 518px\" \/><\/figure><\/div>\n\n\n<h3 class=\"wp-block-heading\">Deploying the Node-RED Flow<\/h3>\n\n\n\n<p>When you\u2019re done deploy your application.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"136\" height=\"35\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2022\/06\/Node-RED-deploy-button.png?resize=136%2C35&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Node-RED deploy button\" class=\"wp-image-111792\"\/><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\">Demonstration<\/h2>\n\n\n\n<p>After deploying you\u2019ll see a timer below the <strong>Big Timer<\/strong> node showing how long it will be on or off.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"468\" height=\"160\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-big-timer-node-red-flow-how-long-off.png?resize=468%2C160&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Big Timer Node-RED Flow how long it will be off\" class=\"wp-image-128784\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-big-timer-node-red-flow-how-long-off.png?w=468&amp;quality=100&amp;strip=all&amp;ssl=1 468w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/esp8266-big-timer-node-red-flow-how-long-off.png?resize=300%2C103&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 468px) 100vw, 468px\" \/><\/figure><\/div>\n\n\n<p>You can open the Node-RED debugging window to see the output of the Big Timer node every minute.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"324\" height=\"568\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-output-node-red-debug.png?resize=324%2C568&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"Node-RED Big Timer demonstration debug node\" class=\"wp-image-128738\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-output-node-red-debug.png?w=324&amp;quality=100&amp;strip=all&amp;ssl=1 324w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/big-timer-output-node-red-debug.png?resize=171%2C300&amp;quality=100&amp;strip=all&amp;ssl=1 171w\" sizes=\"(max-width: 324px) 100vw, 324px\" \/><\/figure><\/div>\n\n\n<p>Right after deploying the node, the ESP8266 should have received an MQTT message with the current state (this happens because we have enabled the option <strong>Output at startup<\/strong>). Additionally, because we&#8217;ve set the <strong>Repeat Output message<\/strong> to true, the ESP8266 will receive MQTT messages with the GPIO state every minute.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"601\" height=\"551\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/ESP8266-receives-gpio-states-MQTT.png?resize=601%2C551&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 NodeMCU Receiving GPIO states via MQTT - Serial Monitor\" class=\"wp-image-128785\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/ESP8266-receives-gpio-states-MQTT.png?w=601&amp;quality=100&amp;strip=all&amp;ssl=1 601w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/ESP8266-receives-gpio-states-MQTT.png?resize=300%2C275&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 601px) 100vw, 601px\" \/><\/figure><\/div>\n\n\n<p>If everything is working as expected GPIO 2 should turn on and off automatically at the times you designated.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img data-recalc-dims=\"1\" loading=\"lazy\" decoding=\"async\" width=\"750\" height=\"421\" src=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/08\/ESP8266-blinking-LED.jpg?resize=750%2C421&#038;quality=100&#038;strip=all&#038;ssl=1\" alt=\"ESP8266 built-in LED ON\" class=\"wp-image-88063\" srcset=\"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/08\/ESP8266-blinking-LED.jpg?w=750&amp;quality=100&amp;strip=all&amp;ssl=1 750w, https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2019\/08\/ESP8266-blinking-LED.jpg?resize=300%2C168&amp;quality=100&amp;strip=all&amp;ssl=1 300w\" sizes=\"(max-width: 750px) 100vw, 750px\" \/><\/figure><\/div>\n\n\n<p class=\"rntbox rntclgray\"><strong>Note:<\/strong> if you&#8217;re controlling the ESP8266 built-in LED, please note that it works with inverted logic. This means it will be off when you send a HIGH signal and it will be on when you send a LOW signal.<\/p>\n\n\n\n<p>Because we&#8217;ve set the retain flag of the MQTT message to true, even if the ESP8266 resets, it will get the last GPIO state and update it accordingly right after connecting to the broker.<\/p>\n\n\n\n<p>You can easily control any other GPIOs on the ESP8266 by simply changing the MQTT topic that the <strong>Big Timer<\/strong> node is publishing in. This is only possible because the ESP8266 is subscribed to a multi-level MQTT topic.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Wrapping Up<\/h2>\n\n\n\n<p>In this tutorial, you learned how to create schedules to automatically control the ESP8266 GPIOs using Node-RED and the Big Timer node. As an example, we&#8217;ve controlled the ESP8266 GPIOs, but you can also use this method to trigger any other task on the ESP8266, like for example activating or deactivating a motion sensor, triggering notifications, and much more.<\/p>\n\n\n\n<p>The advantage of using Node-RED is that once you have set up a generic code on the ESP8266, you just need to make changes to the Node-RED flow to automate tasks.<\/p>\n\n\n\n<p>We hope you found this tutorial useful. If you like home automation and would like to learn more about Node-RED, definitely check out our eBook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/smart-home-ebook\/\" title=\"\"><strong>SMART HOME with Raspberry Pi, ESP32, and ESP8266<\/strong><\/a>: Learn Node-RED and InfluxDB on a Raspberry Pi to build a Home Automation System with the ESP32 and ESP8266.<\/li>\n<\/ul>\n\n\n\n<p>Learn more about the ESP8266 with our resources:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/randomnerdtutorials.com\/home-automation-using-esp8266\/\" title=\"\">Home Automation Using ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/build-web-servers-esp32-esp8266-ebook\/\">Build Web Servers with ESP32 and ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/firebase-esp32-esp8266-ebook\/\">Firebase Web App with ESP32 and ESP8266<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/randomnerdtutorials.com\/projects-esp8266\/\" title=\"\">Free ESP8266 Projects and Tutorials<\/a><\/li>\n<\/ul>\n\n\n\n<p>Thanks for reading.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this tutorial, you&#8217;ll learn how to control the ESP8266 NodeMCU outputs using time-based events. For that, we&#8217;ll set up an automation system on Node-RED with the Big Timer node. &#8230; <\/p>\n<p class=\"read-more-container\"><a title=\"ESP8266 Time-Based Events using Node-RED and Big Timer\" class=\"read-more button\" href=\"https:\/\/randomnerdtutorials.com\/esp8266-nodemcu-big-timer-node-red\/#more-128776\" aria-label=\"Read more about ESP8266 Time-Based Events using Node-RED and Big Timer\">CONTINUE READING \u00bb<\/a><\/p>\n","protected":false},"author":5,"featured_media":128777,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[304,305,225],"tags":[],"class_list":["post-128776","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-0-home-automation","category-0-other","category-home-automation"],"aioseo_notices":[],"jetpack_featured_media_url":"https:\/\/i0.wp.com\/randomnerdtutorials.com\/wp-content\/uploads\/2023\/03\/Big-Timer-Node-RED-ESP8266.jpg?fit=1280%2C720&quality=100&strip=all&ssl=1","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/128776","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/comments?post=128776"}],"version-history":[{"count":6,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/128776\/revisions"}],"predecessor-version":[{"id":129183,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/posts\/128776\/revisions\/129183"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media\/128777"}],"wp:attachment":[{"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/media?parent=128776"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/categories?post=128776"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/randomnerdtutorials.com\/wp-json\/wp\/v2\/tags?post=128776"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}