Note
Hello, welcome to the SunFounder Raspberry Pi & Arduino & ESP32 Enthusiasts Community on Facebook! Dive deeper into Raspberry Pi, Arduino, and ESP32 with fellow enthusiasts.
Why Join?
Expert Support: Solve post-sale issues and technical challenges with help from our community and team.
Learn & Share: Exchange tips and tutorials to enhance your skills.
Exclusive Previews: Get early access to new product announcements and sneak peeks.
Special Discounts: Enjoy exclusive discounts on our newest products.
Festive Promotions and Giveaways: Take part in giveaways and holiday promotions.
👉 Ready to explore and create with us? Click [here] and join today!
CheerLights
CheerLights is a global network of synchronized lights that can be controlled by anyone. Join the @CheerLights - Twitter LED color-changing community, which allows LEDs around the world to change colors simultaneously. Place your LEDs in a corner of your office to remind yourself that you are not alone.
In this case, we also utilize MQTT, but instead of publishing our own messages, we subscribe to the “cheerlights” topic. This allows us to receive messages sent by others to the “cheerlights” topic and use that information to change the color of our LED strip accordingly.
Required Components
In this project, we need the following components.
It’s definitely convenient to buy a whole kit, here’s the link:
Name |
ITEMS IN THIS KIT |
LINK |
|---|---|---|
Elite Explorer Kit |
300+ |
You can also buy them separately from the links below.
COMPONENT INTRODUCTION |
PURCHASE LINK |
|---|---|
- |
|
Wiring
Schematic
Install the Library
To install the library, use the Arduino Library Manager and search for “ArduinoMqttClient” and “FastLED” and install them.
ArduinoMqttClient.h: Used for MQTT communication.
FastLED.h: Used to drive the RGB LED Strip.
Important
With the release of FastLED 3.7.0, the FastLED library now officially supports the Arduino UNO R4. Therefore, you no longer need to manually install the development version. Simply update or install the FastLED library using the Arduino Library Manager.
Warning
[Outdated] Since the FastLED library has not officially released a version supporting Arduino R4 yet, you’ll need to download the latest development code of the FastLED library and overwrite the existing FastLED library files. For detailed instructions on how to do this, please refer to the Manual Installation section. (This note will be retracted when the FastLED library officially releases an update that supports the Arduino UNO R4.)
Run the Code
Note
You can open the file
05_cheerlight.inounder the path ofelite-explorer-kit-main\iot_project\05_cheerlightdirectly.Or copy this code into Arduino IDE.
Note
In the code, SSID and password are stored in arduino_secrets.h. Before uploading this example, you need to modify them with your own WiFi credentials.
#define SECRET_SSID "your_ssid" // your network SSID (name)
#define SECRET_PASS "your_password" // your network password (use for WPA, or use as key for WEP)
1/*
2 The code is designed for an Arduino Uno R4 WiFi to connect to a Wi-Fi network,
3 subscribe to an MQTT topic, and control a chain of NeoPixel LEDs based on messages
4 received from the MQTT broker. It listens for color commands from the cheerlights
5 topic and updates the LED colors accordingly.
6
7 Board: Arduino Uno R4 WiFi
8 Component: WS2812
9 Library: https://github.com/arduino-libraries/ArduinoMqttClient (ArduinoMqttClient by Arduino)
10 https://github.com/FastLED/FastLED (FastLED by Daniel Garcia)
11
12*/
13
14#include <WiFiS3.h>
15#include <ArduinoMqttClient.h>
16#include <FastLED.h>
17
18#define NUM_LEDS 8 // Number of LEDs in the chain
19#define DATA_PIN 6 // Data pin for LED control
20
21#include "arduino_secrets.h"
22///////please enter your sensitive data in the Secret tab/arduino_secrets.h
23char ssid[] = SECRET_SSID; // your network SSID (name)
24char pass[] = SECRET_PASS; // your network password (use for WPA, or use as key for WEP)
25int status = WL_IDLE_STATUS; // the WiFi radio's status
26
27WiFiClient wifiClient;
28MqttClient mqttClient(wifiClient);
29
30const char broker[] = "mqtt.cheerlights.com";
31int port = 1883;
32const char topic[] = "cheerlights";
33
34
35
36CRGB leds[NUM_LEDS]; // Array to hold LED color data
37
38// Define the supported CheerLights colors and their RGB values
39String colorName[] = { "red", "pink", "green", "blue", "cyan", "white", "warmwhite", "oldlace", "purple", "magenta", "yellow", "orange" };
40
41int colorRGB[][3] = { 255, 0, 0, // "red"
42 255, 192, 203, // "pink"
43 0, 255, 0, // "green"
44 0, 0, 255, // "blue"
45 0, 255, 255, // "cyan"
46 255, 255, 255, // "white"
47 255, 223, 223, // "warmwhite"
48 255, 223, 223, // "oldlace"
49 128, 0, 128, // "purple"
50 255, 0, 255, // "magenta"
51 255, 255, 0, // "yellow"
52 255, 165, 0 }; // "orange"
53
54
55void setup() {
56 //Initialize serial and wait for port to open:
57 Serial.begin(9600);
58
59 while (!Serial) {
60 ; // wait for serial port to connect. Needed for native USB port only
61 }
62
63 // check for the WiFi module:
64 if (WiFi.status() == WL_NO_MODULE) {
65 Serial.println("Communication with WiFi module failed!");
66 // don't continue
67 while (true)
68 ;
69 }
70
71 String fv = WiFi.firmwareVersion();
72 if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
73 Serial.println("Please upgrade the firmware");
74 }
75
76 // attempt to connect to WiFi network:
77 while (status != WL_CONNECTED) {
78 Serial.print("Attempting to connect to WPA SSID: ");
79 Serial.println(ssid);
80 // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
81 status = WiFi.begin(ssid, pass);
82
83 // wait 10 seconds for connection:
84 delay(10000);
85 }
86
87 // you're connected now, so print out the data:
88 Serial.print("You're connected to the network");
89 printCurrentNet();
90 printWifiData();
91
92 // You can provide a unique client ID, if not set the library uses Arduino-millis()
93 // Each client must have a unique client ID
94 // mqttClient.setId("clientId");
95
96 // You can provide a username and password for authentication
97 // mqttClient.setUsernamePassword("username", "password");
98
99 Serial.print("Attempting to connect to the MQTT broker: ");
100 Serial.println(broker);
101
102 if (!mqttClient.connect(broker, port)) {
103 Serial.print("MQTT connection failed! Error code = ");
104 Serial.println(mqttClient.connectError());
105
106 while (1)
107 ;
108 }
109
110 Serial.println("You're connected to the MQTT broker!");
111 Serial.println();
112
113 // set the message receive callback
114 mqttClient.onMessage(onMqttMessage);
115
116 Serial.print("Subscribing to topic: ");
117 Serial.println(topic);
118 Serial.println();
119
120 // subscribe to a topic
121 mqttClient.subscribe(topic);
122
123 // topics can be unsubscribed using:
124 // mqttClient.unsubscribe(topic);
125
126 Serial.print("Waiting for messages on topic: ");
127 Serial.println(topic);
128 Serial.println();
129
130 FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS); // Initialize LEDs
131}
132
133void loop() {
134
135 // call poll() regularly to allow the library to receive MQTT messages and
136 // send MQTT keep alives which avoids being disconnected by the broker
137 mqttClient.poll();
138
139 // Add a delay to avoid constant pinging
140 delay(5000);
141}
142
143void printWifiData() {
144 // print your board's IP address:
145 IPAddress ip = WiFi.localIP();
146 Serial.print("IP Address: ");
147
148 Serial.println(ip);
149
150 // print your MAC address:
151 byte mac[6];
152 WiFi.macAddress(mac);
153 Serial.print("MAC address: ");
154 printMacAddress(mac);
155}
156
157void printCurrentNet() {
158 // print the SSID of the network you're attached to:
159 Serial.print("SSID: ");
160 Serial.println(WiFi.SSID());
161
162 // print the MAC address of the router you're attached to:
163 byte bssid[6];
164 WiFi.BSSID(bssid);
165 Serial.print("BSSID: ");
166 printMacAddress(bssid);
167
168 // print the received signal strength:
169 long rssi = WiFi.RSSI();
170 Serial.print("signal strength (RSSI):");
171 Serial.println(rssi);
172
173 // print the encryption type:
174 byte encryption = WiFi.encryptionType();
175 Serial.print("Encryption Type:");
176 Serial.println(encryption, HEX);
177 Serial.println();
178}
179
180void printMacAddress(byte mac[]) {
181 for (int i = 5; i >= 0; i--) {
182 if (mac[i] < 16) {
183 Serial.print("0");
184 }
185 Serial.print(mac[i], HEX);
186 if (i > 0) {
187 Serial.print(":");
188 }
189 }
190 Serial.println();
191}
192
193
194void onMqttMessage(int messageSize) {
195 // we received a message, print out the topic and contents
196 Serial.print("Received a message with topic '");
197 Serial.print(mqttClient.messageTopic());
198 Serial.println("'");
199 Serial.print("Message length: ");
200 Serial.print(messageSize);
201 Serial.println(" bytes:");
202
203 // Read the message contents into a String
204 String message = mqttClient.readString();
205
206 // Convert the received message and comparison strings to lowercase
207 message.toLowerCase();
208
209 // If a message is received on the topic, you will check this message.
210 // Changes the output state according to the message
211 if (String(topic) == "cheerlights") {
212 Serial.print("Changing color to ");
213 Serial.println(message);
214 setColor(message);
215 }
216}
217
218void setColor(String color) {
219 // Loop through the list of colors to find the matching color
220 for (int colorIndex = 0; colorIndex < 12; colorIndex++) {
221 if (color == colorName[colorIndex]) {
222 // Set the color of each NeoPixel on the strip
223 for (int pixel = 0; pixel < NUM_LEDS; pixel++) {
224 leds[pixel] = CRGB(colorRGB[colorIndex][0], colorRGB[colorIndex][1], colorRGB[colorIndex][2]);
225 }
226 FastLED.show();
227 }
228 }
229}
Control global @CheerLights devices
Join the Discord Server and utilize the CheerLights bot to set the color. Simply type
/cheerlightsin any of the channels on the CheerLights Discord Server to activate the bot.
Follow the instructions provided by the bot to set the color. This will allow you to control CheerLights devices globally.
How it works?
Here are the main parts of the code and explanations of their functions:
Include the required libraries:
WiFiS3.h: Used for handling Wi-Fi connections.ArduinoMqttClient.h: Used for handling MQTT connections.FastLED.h: Used for controlling NeoPixel LED strips.
Define some constants:
NUM_LEDS: The number of LEDs on the LED strip.DATA_PIN: The data pin connected to Arduino for controlling the LED strip.arduino_secrets.h: Header file containing Wi-Fi network name and password to protect sensitive information.broker: Address of the MQTT server.port: Port of the MQTT server.topic: The MQTT topic to subscribe to.
Define some global variables:
CRGB leds[NUM_LEDS]: An array to store LED color data.colorName: An array of color names supported by the CheerLights project.colorRGB: An array of RGB color codes corresponding to color names.
setup()function:Initialize serial communication.
Check if the Wi-Fi module is present and output its firmware version.
Attempt to connect to the Wi-Fi network; if it fails, wait 10 seconds and retry.
Upon successful connection, connect to the MQTT broker (server) and subscribe to the specified topic.
Initialize the NeoPixel LED strip.
loop()function:Periodically call the
mqttClient.poll()function to receive MQTT messages and send MQTT keep-alive signals.Add a 5-second delay to avoid continuous connection.
printWifiData()andprintCurrentNet()functions are used to output Wi-Fi network and connection information.printMacAddress()function is used to print the MAC address in hexadecimal format.onMqttMessage()function is a callback function triggered when an MQTT message is received. It outputs the received topic and message content, converting the message content to lowercase. If the topic is “cheerlights,” it calls thesetColor()function to set the LED strip color.setColor()function takes a color name as a parameter, then looks for a matching color in thecolorNamearray. If a matching color is found, it sets the LED strip’s color to the corresponding RGB value and updates the LED strip’s color using theFastLED.show()function.