Arduino RGB LEDs and MQTT

Yesterday I took my RGB LED strip project and upgraded it to use MQTT instead of the simple terminal server I was using before. I couldn’t get it working using my WiFly shield, the system would work fine for five minutes or so and then crash. I did a little digging around, thinking it may be a memory issue, put came up blank.  So ditch the WiFly shield and dig out an Ethernet shield…

Arduino Ethernet RGB Lights

Arduino Ethernet RGB Lights

Then installed the Nick O’Leary’s Arduino MQTT library, and got coding:

 * Ethernet RGB LEDS with MQTT 
 * (c) Mark McKillen

#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

#define MQTT_SERVER "<Mosquitto Server IP>"

byte MAC_ADDRESS[] = { 0x91, 0xA3, 0xAA, 0x00, 0x01, 0x03 };
char message_buff[30];

int redPin   = 3;   // Red LED,   connected to digital pin 9
int greenPin = 5;   // Green LED, connected to digital pin 10
int bluePin  = 6;   // Blue LED,  connected to digital pin 11

EthernetClient ethClient;  // Ethernet object
PubSubClient client( MQTT_SERVER, 1883, callback, ethClient); // MQTT object

void setup() {
  Serial.println("Net begin");

  if (Ethernet.begin(MAC_ADDRESS) == 0)       // Get connected!
      Serial.println("Failed to configure Ethernet using DHCP");

  Serial.print("IP: ");                       // A little debug.. show IP address

  if (client.connect("arduinoClient")) {      // connect to MQTT server
    client.subscribe("rgblight");             // subscribe to topic "rgblight"
    Serial.println("Connected to MQTT");      // let us know this has happened

void loop()
  client.loop();                              // loop for ever waiting for MQTT event

// handles message arrived on subscribed topic
void callback(char* topic, byte* payload, unsigned int length) {
  int i = 0;

  // create character buffer with ending null terminator (string)
  for(i=0; i<length; i++) {
    message_buff[i] = payload[i];
  message_buff[i] = '\0';

  long colorVal = strtol( message_buff, NULL, 16);

  analogWrite(redPin, (colorVal&0xff0000)>>16 );
  analogWrite(greenPin, (colorVal&0x00ff00)>>8 );
  analogWrite(bluePin, (colorVal&0x0000ff)>>0 );

Really simple, that is the cool thing about MQTT, it’s so easy and powerful.

To light the lights all I need to do is:

mosquitto_pub -h <mqtt server> -t rgblight -m "ff0000"  # All red
mosquitto_pub -h <mqtt server> -t rgblight -m "00ff00"  # All green
mosquitto_pub -h <mqtt server> -t rgblight -m "0000ff"  # All blue

The lights respond quickly, much faster than my last version. Success!