How to plot real-time data in MATLAB over MQTT

MQTT in MATLAB – plot real time data

Welcome to another tutorial of the MQTT protocol.

In this tutorial, we will move forward with our MQTT series.

And we will learn how we can use MQTT protocol in MATLAB.

We will follow the following topics,

  1. How to install the MQTT toolbox in MATLAB.
  2. Make communication with the MQTT broker.
  3. Publish a message from MATLAB.
  4.  How to subscribe to a topic in MATLAB.
  5. Make a callback function to receive MQTT messages.
  6. Plot real-time sensor data coming from ESP8266 over MQTT.

I have made other videos on Realtime Plotting using Arduino in the past.

Arduino Real-Time Plotting with MATLAB and Arduino Real-Time Plotting with Python.

If you have been following my MQTT series or you tube channel. You will be familiar with What is MQTT protocol ?

If not, here is a short introduction of MQTT protocol.

MQTT protocol is an IoT ( Internet of things) protocol that is lightweight that uses publish/subscribe to communicate between devices.

MQTT works well at unreliable networks.

There are few MQTT terminologies that you should know, which are as follows.

  • Publish / Subscribe
  • Messages
  • Topics
  • Broker

We already discussed a lot about brokers in the “Mosquitto MQTT Broker Raspberry Pi” blog.

In which we made our own cheap MQTT broker, also check how to make android app for same project.

So lets start, how we can use MQTT in MATLAB.

But before that let’s start by knowing the motivation behind using MQTT protocol in MATLAB.

Buying guide

Development boardAmazon (US)Ali express
ESP32MQTT in MATLAB - plot real time dataMQTT in MATLAB - plot real time data
Raspberry pi zeroMQTT in MATLAB - plot real time dataMQTT in MATLAB - plot real time data

Raspberry pi 4
MQTT in MATLAB - plot real time dataMQTT in MATLAB - plot real time data
ESP8266MQTT in MATLAB - plot real time dataMQTT in MATLAB - plot real time data
DHT11MQTT in MATLAB - plot real time dataMQTT in MATLAB - plot real time data
Buying guide for How to MQTT series

Why MQTT in MATLAB?

This is of course a basic example.

But if you know MATLAB.

This basic example can help you do more complex tasks using the other functionalities of MATLAB.

Here is the motivation behind using MATLAB.

  1. MATLAB is for Engineers and scientists.
    It is often taught in the many engineering courses for simulating different mathematics and physical things.
    So, this blog will be helpful for all those students who want to use the MQTT protocol in their projects and do other complex tasks using MATLAB.
  2. MATLAB has professionally developed toolboxes that can be used for basic to advanced specialized projects.
  3. You can visualize data easily in MATLAB.
    One aim of the Internet of Things is to collect data, visualize it, find patterns and apply advanced machine learning algorithms. MATLAB can help in this case.

MQTT in MATLAB

Like I mentioned, MATLAB has so many professionally developed toolboxes.

There is a toolbox for using MQTT in MATLAB.

So, we will start by installing that tool box.

Installing MQTT toolbox in MATLAB

  1. The first thing you have to do is to open MATLAB.

2. On the home screen click on add-on and get addons.

how to install add on in MATLAB
how to install add on in MATLAB

3. Add on explorer will be opened and search for “MQTT in MATLAB”.

Find MQTT in MATLAB toolbox
Find MQTT in MATLAB toolbox

4. Open it and click on Add.

MQTT in MATLAB - plot real time data
install MQTT in MATLAB toolbox

5. After installation, it will ask you to open documentation. If you want to read you can read, otherwise we are going to cover most of the things.

MQTT in MATLAB documentation
MQTT in MATLAB documentation

Make connections between MATLAB and MQTT broker

The next thing is to make connections between MATLAB and MQTT broker.

So we will open a new script and write,

clc; 
clear all; 
close all;

To clear the command window, clear all variables, and close all windows.

Then we can make a variable and call MQTT function like this,

myMQTT= mqtt('tcp://brokerurl');

That is the minimal way of making a connection.

But if you need other parameters like username, password, client id and port.

Add more parameters like this,

myMQTT=mqtt('tcp://brokerurl','Username','yourUsername','Password','yourPassword','ClientID','clientId','Port',1883);

Run the program to make sure there are no errors and connection has been established.

Publish using MQTT in MATLAB toolbox

Then we can publish something using MQTT protocol.

Let’s turn on and off the LED.

So we can make a variable for topic and message like this,

Topic = 'Led1/status';
Message = '1';

And then we can use publish function to publish message.

Publish(myMQTT, Topic, message);

I am using the same circuit and code for ESP8266 that I used in the previous blog.

How to use ESP8266 with MQTT Cloud.

MQTT in MATLAB - plot real time data
circuit diagram

I have just changed the topics. You can use the same code for local and cloud MQTT brokers.

The final code will be available in the end of this blog.

If you want to change Quality of service.

You can do that by adding extra parameter in publish function like this,

publish(myMQTT, Topic, message, ‘Qos’, n);

N can be the 0,1 or 2 depending on your quality of service.

Subscribe a topic using MQTT in MATLAB toolbox

Now lets learn how we can subscribe to a topic to receive sensor data on our topic.

In order to subscribe, you can make a variable and write.

Topic2 = “ESP8266/data”
Data = subscribe(myMQTT, Topic);

Similarly if you don’t want to use default Quality of service, you can add additional parameters.

Data = subscribe(myMQTT, Topic,’Qos’,n);

You will be subscribed to the topic.

Now let’s make a callback function that will be called whenever our subscribed topic receives a message.

So we will add another parameter in Data variable,

Data = subscribe(myMQTT, Topic,’Qos’,n,'Callback',@myMQTT_Callback);
@myMQTT_Callback is the name of the function which will be called. Let's make one.

So we will write,

function myMQTT_Callback(topic, msg)
fprintf('MQTT callback topic "%s": "%s"\n', topic, msg)
end

So let’s run and see what values we are getting.

data received from MQTT in JSON
data received from MQTT in JSON

You can see that I have encoded the temperature, and humidity values in JSON.

Real-time plotting ESP8266 data on MATLAB using MQTT protocol

Ok now lets, plot the data that is coming from ESP8266 over MQTT protocol.

In this case, we will not be using the callback function.

so we will remove callback function.

and it should look like this,

Topic = "ESP8266/data"
Data = subscribe(myMQTT, Topic);

Then we will put a delay so we can start receiving messages.

pause(6);

We will then create some variables that we will use later.

x=0;
y=0;
z=0;

Finally, we will write a while loop to plot data continuously.

and count the messages coming in MQTT topic.

If messages are coming, we will plot the data.

The loop will look like this,

while true
   values=Data.MessageCount;
   if(values>0)
      op = jsondecode(read(Data));
      temp = op.parameters.temp;
      hum = op.parameters.humidity;
      ran = op.parameters.Random;
      
      x = [x,temp];
      y = [y,hum];
      z = [z,ran];
      
      subplot(3,1,1);
      plot(x);
      ylim([0,100]);
      grid ON;
      title("Temperature");
      
      subplot(3,1,2);
      plot(y);
      ylim([0,100]);
      grid ON;
      title("Humidity");
      
      subplot(3,1,3);
      plot(z);
      ylim([0,100]);
      grid ON;
      title("Random Number");
      
      drawnow
      pause(3) 
   end        
end

Now run the code and you will see a beautiful graph like this,

MATLAB real-time plotting over MQTT
MATLAB real-time plotting over MQTT

Video Tutorial

MQTT in MATLAB video tutorial

ESP8266 Code

#include <Adafruit_Sensor.h> //Library for Adafruit sensors , we are using for DHT
#include <DHT_U.h> //DHT library which uses some func from Adafruit Sensor library
#include <ESP8266WiFi.h> //library for using ESP8266 WiFi 
#include <PubSubClient.h> //library for MQTT
#include <ArduinoJson.h> //library for Parsing JSON

//defining Pins
#define DHTPIN 5
#define LED D2

//DHT parameters
#define DHTTYPE    DHT11     // DHT 11
DHT_Unified dht(DHTPIN, DHTTYPE);
uint32_t delayMS;

//MQTT Credentials
const char* ssid = "SSID";//setting your ap ssid
const char* password = "Password";//setting your ap psk
const char* mqttServer = "iot.reyax.com"; //MQTT URL
const char* mqttUserName = "MQTT username";  // MQTT username
const char* mqttPwd = "Password";  // MQTT password
const char* clientID = "username0001"; // client id username+0001
const char* topic = "ESP8266/data"; //publish topic

//parameters for using non-blocking delay
unsigned long previousMillis = 0;
const long interval = 5000;

String msgStr = "";      // MQTT message buffer

float temp, hum;


//setting up wifi and mqtt client
WiFiClient espClient;
PubSubClient client(espClient);

void setup_wifi() {
  delay(10);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void reconnect() {
  while (!client.connected()) {
    if (client.connect(clientID, mqttUserName, mqttPwd)) {
      Serial.println("MQTT connected");
      client.subscribe("Led1/status");
      Serial.println("Topic Subscribed");
    }
    else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);  // wait 5sec and retry
    }

  }

}

//subscribe call back
void callback(char*topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
  Serial.print("Message:");
  String data = "";
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    data += (char)payload[i];
  }



  if (data == "1") {
    Serial.println("LED");
    digitalWrite(LED, HIGH);
  }
  else {
    digitalWrite(LED, LOW);
  }
}


void setup() {
  Serial.begin(115200);
  // Initialize device.
  dht.begin();
  // get temperature sensor details.
  sensor_t sensor;
  dht.temperature().getSensor(&sensor);
  dht.humidity().getSensor(&sensor);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);

  setup_wifi();

  client.setServer(mqttServer, 1883); //setting MQTT server
  client.setCallback(callback); //defining function which will be called when message is recieved.
  randomSeed(analogRead(0));


}

void loop() {
  if (!client.connected()) { //if client is not connected
    reconnect(); //try to reconnect
  }
  client.loop();

  unsigned long currentMillis = millis(); //read current time

  if (currentMillis - previousMillis >= interval) { //if current time - last time > 5 sec
    previousMillis = currentMillis;

    //read temp and humidity
    sensors_event_t event;
    dht.temperature().getEvent(&event);


    if (isnan(event.temperature)) {
      Serial.println(F("Error reading temperature!"));
    }
    else {
      Serial.print(F("Temperature: "));
      temp = event.temperature;
      Serial.print(temp);
      Serial.println(F("°C"));
    }
    // Get humidity event and print its value.
    dht.humidity().getEvent(&event);
    if (isnan(event.relative_humidity)) {
      Serial.println(F("Error reading humidity!"));
    }
    else {
      Serial.print(F("Humidity: "));
      hum = event.relative_humidity;
      Serial.print(hum);
      Serial.println(F("%"));
    }
    int rand_num = random(90);

    msgStr = "{\"parameters\" : { \"temp\" : " + String(temp) + ",\"humidity\": " + String(hum) + ",\"Random\": " + String(rand_num) + "}}";
    byte arrSize = msgStr.length() + 1;
    char msg[arrSize];

    Serial.print("PUBLISH DATA:");
    Serial.println(msgStr);
    msgStr.toCharArray(msg, arrSize);
    client.publish(topic, msg);
    msgStr = "";
    delay(50);

  }

}

MATLAB CODE

clc;
clear all;
close all;

myMQTT=mqtt('tcp://brokerurl','Username','yourUsername','Password','yourPassword','ClientID','clientId','Port',1883);

%Publish data

Topic = 'Led1/status';
Message = '0';

publish(myMQTT,Topic,Message,'Qos',0);
%n can be 0,1,2

%susbcribe

Topic2 = "ESP8266/data";
Data = subscribe(myMQTT,Topic2,'Qos',0);

pause(6);

x=0;
y=0;
z=0;

while true
   values=Data.MessageCount;
   if(values>0)
      op = jsondecode(read(Data));
      temp = op.parameters.temp;
      hum = op.parameters.humidity;
      ran = op.parameters.Random;
      
      x = [x,temp];
      y = [y,hum];
      z = [z,ran];
      
      subplot(3,1,1);
      plot(x);
      ylim([0,100]);
      grid ON;
      title("Temperature");
      
      subplot(3,1,2);
      plot(y);
      ylim([0,100]);
      grid ON;
      title("Humidity");
      
      subplot(3,1,3);
      plot(z);
      ylim([0,100]);
      grid ON;
      title("Random Number");
      
      drawnow
      pause(3)      
   end   
end

github: https://github.com/HighVoltages/MQTT-in-MATLAB

Conclusion

In this blog we learned to use MQTT protocol in MATLAB.

We published ESP8266 data on topic ESP8266/data.

MATLAB subscribed to that topic.

Receives data and plotted the data in real time.

If you find it helpful, Make sure to like .

Also, check the sponsor of this tutorial . Elegoo .

MQTT in MATLAB - plot real time data
Elegoo

Cheers!

4 thoughts on “MQTT in MATLAB – plot real time data”

  1. Pingback: How to plot real-time data in MATLAB over MQTT | iotosphere - Internet of Things

  2. Pingback: How to make MQTT dashboard in Python - High Voltages

  3. Pingback: How to make MQTT android application using MIT app inventor - High Voltages

  4. Pingback: How to make MQTT web app using HTML and Javascript - High Voltages

Leave a Comment

Your email address will not be published. Required fields are marked *