NodeMCU and RGB LED Strip with Adafruit IO – Arduino IDE

by Dec 4, 2022MQTT, NodeMCU, nodemcu projects

In this tutorial, we will connect an RGB LED strip of 5 meters to a NodeMCU and control them via adafruit IO. A combination of 3 LEDs—RED, GREEN, and BLUE—makes up an RGB LED. Red, green, and blue can be combined to create any color. RGB LEDs may produce a variety of colors by having their supplied voltage varied. Different voltages are delivered to the Node MCU using the analog output feature.

The interfaces for RGB LEDs are 4 pins. Red, Blue, and Green each have three pins. The common pins for the three LEDs are present.

Adafruit IO

Adafruit IO is a platform designed to control and display the data from your devices in a secure way. As a communication channel, you can use messaging protocols such as MQTT or HTTP. There are two different packages such as free and premium, we will use a free subscription to the adafruit IO in this tutorial. For more details on this platform, check out their official link.

Hardware Required

  • NodeMCU (ESP8266)
  • RGB LED (5 meters)
  • Jumper wires for connection

Software Required

  • Arduino IDE
  • Libraries – Neopixels Adafruit and Adafruit MQTT (screenshots below)

Neopixels

To get started, download the NeoPixel library from Adafruit. Simply download the library’s.zip file, unzip it on your computer, and then drag the contents into the folder for your Arduino libraries. (Typically, you create the “library” folder in the same “Arduino” folder where you save your sketches. Create one now if you don’t already have one.) Additionally, if the Arduino IDE was already open, restart it.

For starters, you can try some example sketches in your library folder.

File > Examples > Adafruit NeoPixel > simple

This file simple will just light up your LED strips with a moderately bright green color.

1. Getting started with the connection

Connect the three pins from RGB LED to the ESP8266,

RGBESP8266
VCC3.3 V
GNDGND
D in D2
Connections

2. Adafruit IO Setup

Step 1: Navigate to io.adafruit.com to create your new IoT dashboard. Here you are controlling your colors on your RGB LED strip.

First of all, create an account for yourself at io.adafruit.com. While creating your account, you would also be setting up your username, and your IO Key will be generated, which is very important to connect your Arduino code with your dashboard.

Step 2: Then navigate to Dashboard on the menu, and create your dashboard.

Step 3: Select Create New Block

Step 4: Since we are going to control the color in the LED strip, we will choose the widget – color picker from the widget options.

Step 5: After selecting the widget, connect the widget to a feed. In the next step, you will create a new feed with a unique name that will be used in the code later.

Step 6: Press Create Block.

Step 7: Finally, you have created a new feed on your new dashboard.

3. Arduino IDE – Code

It is time to write a piece of code that communicates your dashboard from the ESP8266.

  1. We will import the Neopixel library from the adafruit
  2. Using MQTT as the protocol
  3. Subscribe from the Dashboard for the color picker value in hex form

The adafruit IO dashboard contains the color value in the hex format, whereas in the Neopixel, the pixels are in the form of RGB. So in order to change the hex format to RGB format, we would also include a piece of logic that does this conversion.

In the below code, you will be changing your wifi SSID and the password, and also provide the IO Key.

In addition to the Neopixel library, we would also need the MQTT Adafruit Library.

#include <Adafruit_NeoPixel.h>
#define PIN  2
#define NUMPIXELS      250
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

int delayval = 50;
#define BRIGHTNESS 100
#include <ESP8266WiFi.h>

#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
 
#define WLAN_SSID       "your ssid"
#define WLAN_PASS       "your wifi password"
#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883                  
#define AIO_USERNAME    "monisha1104"
#define AIO_KEY         "your IO Key"
 

 
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;
 
// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
 
/****************************** Feeds ***************************************/
 
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>

Adafruit_MQTT_Subscribe LED = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/color_picker");
 
/*************************** Sketch Code ************************************/
void setup() 
{
  Serial.begin(115200);
   
   pixels.begin();
   pixels.setBrightness(BRIGHTNESS);
 
  // Connect to WiFi access point.
  Serial.print("\n\n\nConnecting to ");
  Serial.println(WLAN_SSID);
  WiFi.begin(WLAN_SSID, WLAN_PASS);
  
   
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print(">>");
    delay(5000);
  }
  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());
 mqtt.subscribe(&LED);
}
 
void loop()
{
   MQTT_connect();

Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &LED) {
      Serial.print(F("Got: "));
      Serial.println((char *)LED.lastread);
      String hexstring = (char *)LED.lastread;

    // String hexstring = "B787B7";
    long number = (long) strtol( &hexstring[1], NULL, 16);
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

    Serial.print("red is ");
    Serial.println(r);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);     
    for(int i=0;i<NUMPIXELS;i++){
    pixels.setPixelColor(i, pixels.Color(r,g,b)); // Moderately bright green color.
    pixels.show(); // This sends the updated pixel color to the hardware.
    delay(delayval); // Delay for a period of time (in milliseconds).
  } 
    }
  }
}

void MQTT_connect()
 
{
  int8_t ret;
 
  // Stop if already connected.
  if (mqtt.connected())
  {
    return;
  }
 
  Serial.print("Connecting to MQTT... ");
 
  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(3000);  // wait 3 seconds
       retries--;
       if (retries == 0) {
         // basically die and wait for WDT to reset me
         while (1);
       }
  }
  Serial.println("MQTT Connected!");
}

Code Explanation

The ESP8266 will connect to the MQTT initially, using the function MQTT_connect, and then the subscription to the feeds from your dashboard will take place.

Adafruit_MQTT_Subscribe LED = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/color_picker");

More on MQTT Tutorials Click Here.

The above line indicates that a variable LED is subscribed to the feed name color_picker, which was created in your dashboard.


    // String hexstring = "B787B7";
    long number = (long) strtol( &hexstring[1], NULL, 16);
    int r = number >> 16;
    int g = number >> 8 & 0xFF;
    int b = number & 0xFF;

    Serial.print("red is ");
    Serial.println(r);
    Serial.print("green is ");
    Serial.println(g);
    Serial.print("blue is ");
    Serial.println(b);

The hex values are finally converted to the pixel values RGB using the above logic.

4. Connecting Everything

Compile and upload the code to your ESP8266, then open your dashboard. Choose your desired color to change from the widget color picker.

The color will change on the LED stripes based on the delays.

Video

Creating a multiplication Skill in Alexa using python

Written By Monisha Macharla

Hi, I'm Monisha. I am a tech blogger and a hobbyist. I am eager to learn and explore tech related stuff! also, I wanted to deliver you the same as much as the simpler way with more informative content. I generally appreciate learning by doing, rather than only learning. Thank you for reading my blog! Happy learning!

RELATED POSTS

How to use MQTTBox to debug MQTT messages?

How to use MQTTBox to debug MQTT messages?

MQTTBox is a versatile MQTT (Message Queuing Telemetry Transport) client tool that facilitates testing and debugging of MQTT-based applications. MQTT is a lightweight messaging protocol commonly used in IoT (Internet of Things) and other scenarios where low-bandwidth,...

How to enable Mosquitto MQTT over WebSocket on Windows

How to enable Mosquitto MQTT over WebSocket on Windows

WebSocket is one of the communication protocols which provides full duplex communication over a single TCP/IP connection. It uses HTTP as a intial connection establishment. The WebSocket enables the communication from the web browser (client) to the server, in which...

MQTT Mosquitto Broker on Windows via Windows PowerShell

MQTT Mosquitto Broker on Windows via Windows PowerShell

Eclipse Mosquitto is an open-source message broker (EPL/EDL licensed) that supports MQTT versions 5.0, 3.1.1, and 3.1. The MQTT protocol uses a publish/subscribe method to deliver a lightweight messaging method. This makes it outstanding for Internet of Things (IoT)...

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

How to Install the Mosquitto MQTT Broker on Linux (Ubuntu)?

With IoT becoming a leading name in the market, businesses are keen to import it in their strategy. Due to the increasing demand, many people seek to learn the use of Mosquitto MQTT broker Linux to pump up their IoT productivity. Eclipse Mosquitto is an open-source...

How to build an MQTT Server using Raspberry Pi

installing-and-testing-MQTT-on-Raspberry_Pi What is MQTT ? MQTT stands for Message Queuing Telemetry Transport and is a network messaging protocol commonly used for messaging between IoT devices. MQTT is a publish/subscribe protocol that allows edge-of-network devices...

CoAP and MQTT: Analyzing the Best IoT Protocol

CoAP and MQTT: Analyzing the Best IoT Protocol

INTRODUCTION TO CoAP and MQTT CoAP and MQTT are two of the most important and most used IoT protocols nowadays. Both are equally important in machine communication. CoAP is a considerable competitor for MQTT because of the similarities in their use. Yet both have...

Mosquitto MQTT Broker introduction

Mosquitto MQTT Broker introduction

In this tutorial, we will discuss about the intro of Mosquittto MQTT broker. MQTT Broker is responsible for receiving network connections from the client and handling the client’s requests of Subscribe/Unsubscribe and Publish, as well as forwarding the messages...

How to Install the Mosquitto MQTT Broker on Windows?

How to Install the Mosquitto MQTT Broker on Windows?

The Mosquitto or MQTT broker is an OASIS standard messaging protocol for IoT. The inculcation of IoT in modern-day lives has pulled MQTT in the picture. Being a lightweight messaging transport that can remotely connect devices, MQTT tutorials were in much demand. So,...

VIDEOS – FOLLOW US ON YOUTUBE

EXPLORE OUR IOT PROJECTS

IoT Smart Gardening System – ESP8266, MQTT, Adafruit IO

Gardening is always a very calming pastime. However, our gardens' plants may not always receive the care they require due to our active lifestyles. What if we could remotely keep an eye on their health and provide them with the attention they require? In this article,...

How to Simulate IoT projects using Cisco Packet Tracer

In this tutorial, let's learn how to simulate the IoT project using the Cisco packet tracer. As an example, we shall build a simple Home Automation project to control and monitor devices. Introduction Firstly, let's quickly look at the overview of the software. Packet...

All you need to know about integrating NodeMCU with Ubidots over MQTT

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

All you need to know about integrating NodeMCU with Ubidots over Https

In this tutorial, let's discuss Integrating NodeMCU and Ubidots IoT platform. As an illustration, we shall interface the DHT11 sensor to monitor temperature and Humidity. Additionally, an led bulb is controlled using the dashboard. Besides, the implementation will be...

How to design a Wireless Blind Stick using nRF24L01 Module?

Introduction Let's learn to design a low-cost wireless blind stick using the nRF24L01 transceiver module. So the complete project is divided into the transmitter part and receiver part. Thus, the Transmitter part consists of an Arduino Nano microcontroller, ultrasonic...

Sending Temperature data to ThingSpeak Cloud and Visualize

In this article, we are going to learn “How to send temperature data to ThingSpeak Cloud?”. We can then visualize the temperature data uploaded to ThingSpeak Cloud anywhere in the world. But "What is ThingSpeak?” ThingSpeak is an open-source IoT platform that allows...

Amaze your friend with latest tricks of Raspberry Pi and Firebase

Introduction to our Raspberry Pi and Firebase trick Let me introduce you to the latest trick of Raspberry Pi and Firebase we'll be using to fool them. It begins with a small circuit to connect a temperature sensor and an Infrared sensor with Raspberry Pi. The circuit...

How to implement Machine Learning on IoT based Data?

Introduction The industrial scope for the convergence of the Internet of Things(IoT) and Machine learning(ML) is wide and informative. IoT renders an enormous amount of data from various sensors. On the other hand, ML opens up insight hidden in the acquired data....

Smart Display Board based on IoT and Google Firebase

Introduction In this tutorial, we are going to build a Smart Display Board based on IoT and Google Firebase by using NodeMCU8266 (or you can even use NodeMCU32) and LCD. Generally, in shops, hotels, offices, railway stations, notice/ display boards are used. They are...

Smart Gardening System – GO GREEN Project

Automation of farm activities can transform agricultural domain from being manual into a dynamic field to yield higher production with less human intervention. The project Green is developed to manage farms using modern information and communication technologies....