Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Control Remote Peripherals With MQTT

DZone's Guide to

Control Remote Peripherals With MQTT

Building an LED app with a dashboard just takes a bit of code and a few clicks. Let's build something using Ubidots and MQTT for communication.

· IoT Zone
Free Resource

Address your IoT software testing needs – improve quality, security, safety, and compliance across the development lifecycle.

I recently covered the MQTT protocol and how it works, and we already know the IoT MQTT is used to send data from remote sensors. Just to recap briefly, MQTT is a lightweight protocol used in the telemetry. Several IoT platforms support MQTT to exchange data with remote IoT boards and sensors. Usually, IoT boards use MQTT to connect to the IoT platforms that acquire information.

Project Description

In this project, we use MQTT in a different way. We want to control an IoT board (like the MKR1000) using MQTT. The target of this project is controlling an RGB LED Matrix remotely using MQTT. To build this project, we will use:

  • Arduino MKR1000
  • 4×4 RGB LED Matrix

The MKR1000 will connect to the Ubidots cloud platform using MQTT. This project is divided into two steps:

  1. Configure Ubidots to handle the RGB color components using the web interface
  2. Develop an MQTT client to connect to Ubidots and manage the LED Matrix

At the end of this project, we will control the RGB LED Matrix remotely using the Ubidots web interface.

Configure the IoT Board

In this first step, we will configure the Ubidots interface to handle three color components. We will use sliders to control them. Let us begin.

Before continuing, you have to create a free account using this link. Log into the application and click on the Device to create a new device. mqtt tutorial config

We used RGB Controller as the device name. A device acts as a data container where we can group variables that hold the exchanged data. Once the device is ready, we can start adding a new variable:

Image title

We will create three variables called:

  • redColor
  • greenColor
  • blueColor

Now it is time to create the dashboard that we will use to control these variable values. Go to Dashboard and click on "Add". Give a name to your dashboard and start adding controls. In this project, we add sliders, so click on "Add new widget" and then on "Slider":

Image title

Select the device (AKA the data source) previously configured:

Image title

Select the RGB Controller and you will see three variables:

Image title

Select one of them and repeat the process for all three variables. At the end, you will have a dashboard that looks like this:

Image title


Implementing a Client to Handle MQTT

Once the IoT platform is configured, we can focus our attention on the IoT MQTT client. This client receives the data from the platform and manages the RGB LED matrix. To create the client, we use the following libraries:

The first step is initialized the Neomatrix, providing a set of information like the matrix width and height and the pin number. In our case, the RGB LED Matrix is connected using MKR PIN 5.

Adafruit_NeoMatrix matrix = Adafruit_NeoMatrix(4, 4, 5,
                           NEO_MATRIX_TOP     + NEO_MATRIX_RIGHT +
                           NEO_MATRIX_COLUMNS + NEO_MATRIX_PROGRESSIVE,
                           NEO_GRB + NEO_KHZ800);


Notice the first three parameters represent the number of LEDs in a row and in a column. Using the matrix instance, we can color the matrix.

Let us implement the MQTT client. This project uses an MKR1000, so we'll use a Wi-Fi connection:

WiFiClient net;
MQTTClient mqttClient;
 
void setup() {
      Serial.begin(115000);  
      Serial.println("Configuring the net...");
      WiFi.begin("your WiFi SID", "your WiFi password");
 
  while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(1000);
    }
    Serial.println("Begin...");
    mqttClient.begin("mqtt://things.ubidots.com", net);
    matrix.begin();
    connect();
}


In the setup() method, we simply initialize the Wi-Fi connection and the mqttClient. To initialize the MQTT client, we have to set the MQTT server (Ubidots server address) and the net.
The connect() method handles the connection and the MQTT topic subscription. According to the Ubidots docs, each variable defined in the data source (AKA device) has its own topic:

/v1.6/devices/_device_name/_variable_name/lv


Notice that the lv at the end of the topic stands for last value. In other words, we are interested only in the last variable value to control the RGB LED Matrix. In this project, the application has to subscribe to the following topics:

/v1.6/devices/RGBController/redColor/lv
/v1.6/devices/RGBController/greenColor/lv
/v1.6/devices/RGBController/blueColor/lv


So the connect() method is:

void connect() {
    Serial.println("Connecting to MQTT....");
    if (mqttClient.connect("YOUR_UNIQUE_ID", "YOUR_UBIDOTS_TOKEN", "")) {
        Serial.println("MQTT client connected");
        int result = mqttClient.
        subscribe("/v1.6/devices/RGBController/redColor/lv");
        Serial.println(result);
        Serial.println("Subscribed red topic.");
        int result1 = mqttClient.
        subscribe("/v1.6/devices/RGBController/greenColor/lv");
        Serial.println(result1);
        Serial.println("Subscribed green topic.");
        int result2 = mqttClient.
        subscribe("/v1.6/devices/RGBController/blueColor/lv");
        Serial.println(result1);
        Serial.println("Subscribed blue topic.");
    } else {
        Serial.println("######### Client not connected ########");
    }
}


Once the application is connected to the MQTT server and subscribed to the variable topics, we have to implement the method that listens to the values coming from the MQTT server. To this purpose, we have to implement a method named:

messageReceived(String topic, String payload, char * bytes, unsigned int length)

In this method, the application has to do the following tasks:

  • Identify the topic that holds the message.
  • Convert the message to the color component value.
  • Control the RGB LED Matrix, setting the new color.

This is the method implementation:

void messageReceived(String topic, String payload,
    char * bytes, unsigned int length) {

    if (topic.indexOf("redColor") >= 0) {
        red = atoi(bytes);
    } else if (topic.indexOf("greenColor") >= 0) {
        green = atoi(bytes);
    } else if (topic.indexOf("blueColor") >= 0) {
        blue = atoi(bytes);
    }
    matrix.fillScreen(matrix.Color(red, green, blue));
    matrix.show();
}


That’s all. In the last two lines of the method, we use the instance of matrix to fill the RGB LED Matrix with the color identified by the red, green, or blue component, and we show it.

Now you can try to use the three sliders in the Ubidots IoT console to change the RGB LED matrix color. 

Conclusion

At the end of this post, hopefully, you have gained knowledge about the MQTT protocol and how to use it to control remote peripherals.

Accelerate the delivery of high-quality software in the connected IoT era through an integrated analysis, testing, security, and analytics platform

Topics:
iot ,mqtt ,embedded development ,tutorial ,remote development

Published at DZone with permission of Francesco Azzola, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}