ThingSpeak MATLAB Analysis and Visualization

NodeMCU ESP8266 Weather Station Hardware Setup

Climate change has led to unpredictable weather conditions. There are many weather stations around the world that are used by researchers and government agencies to observe, record, and analyze weather patterns to study climate changes and provide weather forecasts. These Weather stations are highly advanced and can, not only tell the current weather condition but also tell the predictions about the upcoming weather. Basically there are three major parameters to measure in any weather station- Humidity, Temperature, and Pressure. We previously built few IoT weather stations using Arduino, Raspberry Pi and ESP32 and published the weather data on various cloud platforms like IBM Watson, ThingSpeak, Local webserver etc.

 

Here in this project, we will build a NodeMCU based Weather Station, and analyze and visualize weather streaming data like temperature, humidity using the ThingSpeak MATLAB analysis and visualization tool.  Here a DHT11 sensor will be used to collect the real-time temperature and humidity data.

 

MATLAB Analysis and Visualization

ThingSpeak has integrated support from the MATLAB. It allows ThingSpeak users to analyze and visualize live data using MATLAB without any MATLAB license from Mathworks. You can access the MATLAB tools from your ThingSpeak channel.

MATLAB Analysis and Visualization tools can show relationships, patterns, and trends in data, and can visualize it in plots, charts, and gauges.

Using the MATLAB analysis, you can:

  • Convert the data units, combine different data, and calculate new data.
  • Schedule calculations to run at a specific time.
  • Visually understand relationships in data using built-in plotting functions.
  • Combine data from multiple channels to build a more sophisticated analysis.

 

Components Required

  • NodeMCU ESP8266
  • DHT11 Sensor

 

Circuit Diagram

ESP8266 Weather Station Circuit Diagram

ESP8266 Weather Station Setup

 

ThingSpeak Setup for MATLAB

ThingSpeak is an open data platform that allows you to aggregate, visualize, and analyze live data in the cloud. You can control your devices using ThingSpeak, you can send data to ThingSpeak from your devices, and even you can create instant visualizations of live data, and send alerts using web services like Twitter and Twilio. ThingSpeak has integrated support from the numerical computing software MATLAB. MATLAB allows ThingSpeak users to write and execute MATLAB code to perform preprocessing, visualizations, and analyses. ThingSpeak takes minimum of 15 seconds to update your readings. We have also done other interesting projects with ThingSpeak like

 

Step 1: ThingSpeak Account Setup

To create channel on ThingSpeak first you need to Sign up on ThingSpeak. In case if you already have an account on ThingSpeak, sign in using your id and password.

For creating your account go to www.thinspeak.com

 

Click on Sing up if you don’t have an account and if you already have an account click on sign in. After clicking on signup fill your details.

 

After this verify your E-mail id and click on continue.

 

Step 2: Create a Channel for Your Data

Now, after login, create a new channel by clicking the “New Channel” button.

ThingSpeak MATLAB Analysis and Visualization

After clicking on “New Channel,” enter the Name and Description of the data you want to upload on this channel. For example, I named it as “Weather station”

Enter the name of your data in Field1 and Field2. If you want to use more than two Fields, then check the box next to the Field option and enter the name and description of new data.

After this, click on the save channel button to save the details.

 

Step 3: API Key

To send data to ThingSpeak, we need a unique API key, which we will use later in our code to upload our sensor data to Thingspeak Website.

Click on the “API Keys” button to get your unique API key for uploading your sensor data.

ThingSpeak MATLAB Analysis and Visualization

 

Code Explanation

Complete code for MATLAB ThingSpeak visualization is given at the end of this document. Here we are explaining the code for better understanding.

In this code, we are using the DHT11 sensor library and ThingSpeak library. So first download and install the ThingSpeak library from here.

The code starts by including the libraries for DHT11, ThingSpeak, and ESP8266 Wi-Fi. ThingSpeak library is used to send data to the ThingSpeak platform. Few variables are defined to store ThingSpeak API key, Wi-Fi name, password and ThingSpeak channel no.

#include <DHT.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>;
#include <ThingSpeak.h>;
// replace with your channel’s thingspeak API key,
const char * myWriteAPIKey = "Write API key";
unsigned long myChannelNumber = 762208; //Replace it with your channel ID
const char* ssid = "WiFi Name";
const char* password = "WiFi Password";

 

Inside the void loop function dht.readHumidity(), dht.readTemperature() functions are used to read the temperature and humidity data from DHT11 sensor. Then temperature and humidity data are published to the ThingSpeak channel using the ThingSpeak.writeField function.

void loop() {
float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius Humidity: ");
Serial.print(h);
Serial.println("% send to Thingspeak");
ThingSpeak.writeField(myChannelNumber, 1,t, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber, 2,h, myWriteAPIKey);
}

 

After uploading the code into NodeMCU, you can check the real-time temperature and humidity data on your ThingSpeak channel.

ThingSpeak MATLAB Analysis and Visualization

 

Now, as the sensor data is streaming over the ThingSpeak channel, we will use the MATLAB Analysis tool to calculate the Dew point using the temperature and humidity data. It reads the temperature and humidity data from the Weather Station channel. After calculating the Dew point, write this data to a new channel along with temperature and humidity data.

For MATLAB analysis, go to the Apps tab, and click MATLAB Analysis.

ThingSpeak MATLAB Analysis and Visualization

 

Now click on ‘New.’  Then select the Custom template, and click on ‘Create.’ In the Name field, enter your project name.

 

ThingSpeak MATLAB Analysis

MATLAB code for analysis is given below.

readChannelID = 762208; % Channel ID from which you are reading the data
readAPIKey = 'GXBL8OUK85WI36UR'; % Channel read API key from which you are reading the data
TemperatureFieldID = 1; % Temperature Field ID
HumidityFieldID = 2; % Humidity Field ID
[temp,time] = thingSpeakRead(readChannelID,'Fields',TemperatureFieldID, ...
                                                'NumPoints',1,'ReadKey',readAPIKey); % Read the temperature data
humidity = thingSpeakRead(readChannelID,'Fields',HumidityFieldID, ...
                                                'NumPoints',1,'ReadKey',readAPIKey); % Read the humidity data
tempC = (5/9)*(temp-32);
b = 17.62; % constant for water vapor (b)
c = 243.5; % constant for barometric pressure (c).
gamma = log(humidity/100)+b*tempC./(c+tempC);
dewPoint = c*gamma./(b-gamma)
dewPointF = (dewPoint*1.8) + 32; 
display(dewPointF,'Dew Point is');
writeChannelID = 899642; % Write channel ID
writeAPIKey = '5VI7OCQWBB86DK77'; % Write channel API Key
thingSpeakWrite(writeChannelID,[temp,humidity,dewPointF],'Fields',[1,2,3],'timestamp',time,'WriteKey',writeAPIKey);

 

A brief explanation about the code is given below. First Enter the read channel ID and API Key so that it can read the channel data.

readChannelID = 762208;
readAPIKey = 'GXBL8OUK85WI36UR'

 

Now enter the temperature and humidity data field no. In my case, I saved the temp. Data in field 1 and humidity data in field 2.

TemperatureFieldID = 1;
HumidityFieldID = 2;

 

Read the temperature and humidity data from the field 1 & 2 with a timestamp.

[temp,time] = thingSpeakRead(readChannelID,'Fields',TemperatureFieldID, ...
                                                'NumPoints',1,'ReadKey',readAPIKey);
humidity = thingSpeakRead(readChannelID,'Fields',HumidityFieldID, ...
                                                'NumPoints',1,'ReadKey',readAPIKey);
Change the temperature reading from Fahrenheit to Celsius.
tempC = (5/9)*(temp-32); 
Enter the constants water vapor (b) and barometric pressure (c) constants.
b = 17.62;
c = 243.5;

 

Calculate the dew point using temperature and humidity readings.

gamma = log(humidity/100)+b*tempC./(c+tempC);
dewPoint = c*gamma./(b-gamma)
dewPointF = (dewPoint*1.8) + 32;

 

Enter the write channel ID and API key.

writeChannelID = 899642;
writeAPIKey = '5VI7OCQWBB86DK77';

 

Write the data to another channel. It will write the dew point data along with temperature and humidity.

thingSpeakWrite(writeChannelID,[temp,humidity,dewPointF],'Fields',[1,2,3],'timestamp',time,'WriteKey',writeAPIKey);

 

Now click on ‘Save and Run’ and check the output field. Now check the Dew point Measurement channel.

ThingSpeak MATLAB Analysis and Visualization

This analysis runs only when we click on ‘Save and Run.’ To schedule the analysis, you can use the ‘Time Control App.’ You can find the ‘Time Control’ option at the bottom of the page.

 

ThingSpeak MATLAB Visualization

After calculating the Dew point using MATLAB Analysis, now we will use the MATLAB Visualizations tool to visualize the measured data, i.e. dew point, temperature, and humidity.

For Visualization Go to Apps and then click on MATLAB Visualizations. After that, click on ‘New’ to create a visualization. 

MATLAB code for Visualization is given below.

readChId = 899642
readKey = 'FGONJCQYKNSZ5PSQ';
[dewPointData,timeStamps] = thingSpeakRead(readChId,'fields',[1,2,3],...
    'NumPoints',100,'ReadKey',readKey);
plot(timeStamps,dewPointData);
xlabel('TimeStamps');
ylabel('Measured Values');
title('Dew Point Measurement');
legend({'Temperature','Humidity','Dew Point'});
grid on;

 

Here we are explaining the above code in detail. First enter the read channel ID and API Key.

readChId = 899642
readKey = 'FGONJCQYKNSZ5PSQ';

 

Read data from your Read channel fields, and get the last 100 points of temperature, humidity, and dew point data.

 [dewPointData,timeStamps] = thingSpeakRead(readChId,'fields',[1,2,3],...
    'NumPoints',100,'ReadKey',readKey);

 

Plot the graph with TimeStamps data on x label and Measured Values on y label, a title, and a legend. Legend used to create a legend with descriptive labels for each plotted data line.

plot(timeStamps,dewPointData);
xlabel('TimeStamps');
ylabel('Measured Values');
title('Dew Point Measurement');
legend({'Temperature','Humidity','Dew Point'});
grid on;

 

Now click on ‘Save and Run’ and check the output field. Output plot looks like this:

ThingSpeak MATLAB Analysis and Visualization

This is how you can use MATLAB Analysis and Visualization tools in ThingSpeak. Apart from calculating the Dew Point, you can calculate average humidity and temperature, high and low-temperature levels, and can analyze how temperature behaved on a particular day/month.

Code

#include <DHT.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>;
#include <ThingSpeak.h>;
// replace with your channel’s thingspeak API key,
const char * myWriteAPIKey = "Write API key";
unsigned long myChannelNumber = 762208; //Replace it with your channel ID
const char* ssid = "WiFi Name";
const char* password = "WiFi Password";

const char* server = "api.thingspeak.com";
#define DHTPIN D4 // CONNECT THE DHT11 SENSOR TO PIN D4 OF THE NODEMCU

DHT dht(DHTPIN, DHT11,15); //CHANGE DHT11 TO DHT22 IF YOU ARE USING DHT22
WiFiClient client;

void setup() {
Serial.begin(9600);
delay(10);
dht.begin();
ThingSpeak.begin(client);
WiFi.begin(ssid, password);

Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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

}

void loop() {

float h = dht.readHumidity();
float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
}
Serial.print("Temperature: ");
Serial.print(t);
Serial.print(" degrees Celcius Humidity: ");
Serial.print(h);
Serial.println("% send to Thingspeak");
ThingSpeak.writeField(myChannelNumber, 1,t, myWriteAPIKey);
ThingSpeak.writeField(myChannelNumber, 2,h, myWriteAPIKey);
}
 

Video

25 Comments

I simply wanted to say thanks yet again. I am not sure the things that I could possibly have gone through in the absence of those basics shown by you regarding my industry. It was a very horrifying setting in my view, nevertheless looking at a new well-written style you dealt with the issue forced me to jump with delight. I will be thankful for this help and then hope that you are aware of a great job you are always providing educating the mediocre ones by way of your blog. More than likely you haven't come across any of us.

Thanks so much for providing individuals with such a splendid opportunity to discover important secrets from this web site. It's usually so sweet plus full of fun for me personally and my office peers to search your website particularly three times in 7 days to see the newest guidance you will have. And lastly, we're usually happy with the breathtaking opinions you give. Selected 2 tips on this page are truly the most beneficial I've ever had.

A lot of thanks for all of the labor on this web page. My mum really loves engaging in internet research and it's really obvious why. Many of us learn all of the powerful tactic you deliver very important information on this blog and therefore increase contribution from other people on this article plus my child is starting to learn so much. Take pleasure in the rest of the year. You're the one carrying out a very good job.

I want to express thanks to the writer for rescuing me from this dilemma. Right after looking out throughout the world wide web and obtaining principles that were not pleasant, I figured my entire life was done. Living without the presence of answers to the problems you have resolved through your entire short post is a crucial case, and the ones which may have in a negative way damaged my entire career if I had not noticed your website. Your own knowledge and kindness in controlling almost everything was excellent. I'm not sure what I would've done if I hadn't discovered such a subject like this. I can at this point relish my future. Thank you so much for this skilled and results-oriented help. I will not think twice to propose the website to any individual who should get recommendations on this subject.

I and my guys ended up reading through the excellent procedures on your web site then all of the sudden I had an awful suspicion I never expressed respect to the site owner for those secrets. The women were definitely for that reason excited to read through all of them and have in effect extremely been making the most of those things. Thanks for simply being very kind as well as for using this sort of very good ideas most people are really wanting to understand about. Our honest apologies for not expressing appreciation to you earlier.

My wife and i got very joyful when Peter managed to finish off his survey with the ideas he gained out of your web pages. It's not at all simplistic just to find yourself giving for free facts the others might have been selling. And now we recognize we have the website owner to thank for this. These explanations you've made, the straightforward web site navigation, the relationships you give support to create - it's got all sensational, and it is aiding our son and us consider that that issue is awesome, and that's seriously important. Thank you for the whole lot!

I precisely wanted to thank you very much yet again. I do not know the things I might have followed in the absence of the actual strategies discussed by you over that situation. Certainly was a alarming condition for me, however , observing a new professional approach you dealt with it made me to cry with fulfillment. Extremely thankful for your service and then expect you are aware of a powerful job you're carrying out educating most people all through your webblog. I'm certain you've never come across any of us.

I definitely wanted to post a word to be able to express gratitude to you for those unique points you are giving out at this website. My considerable internet search has at the end been rewarded with extremely good information to exchange with my companions. I would mention that most of us visitors are definitely endowed to exist in a perfect community with so many wonderful people with very beneficial opinions. I feel very privileged to have discovered your website and look forward to plenty of more exciting times reading here. Thanks a lot once more for a lot of things.

I simply wanted to say thanks all over again. I am not sure the things I would have done without the entire thoughts contributed by you about such area of interest. It previously was a real intimidating issue in my position, but taking a look at the specialized avenue you dealt with it took me to jump over fulfillment. I will be happier for your assistance and pray you really know what an amazing job you have been accomplishing teaching people today with the aid of your web page. More than likely you have never encountered any of us.

I would like to express appreciation to the writer for rescuing me from this dilemma. Right after exploring throughout the the net and seeing principles which were not helpful, I thought my entire life was gone. Being alive minus the strategies to the difficulties you have resolved through your website is a critical case, as well as the kind that would have in a negative way affected my entire career if I hadn't noticed your site. Your own personal capability and kindness in touching all areas was vital. I don't know what I would've done if I hadn't come across such a solution like this. It's possible to now look ahead to my future. Thank you so much for the expert and amazing guide. I won't think twice to suggest your blog to any person who desires support on this issue.

My wife and i were really glad when Albert could do his investigations through the ideas he discovered out of your weblog. It is now and again perplexing just to be giving away instructions which often many people may have been making money from. And we figure out we have got the blog owner to give thanks to for this. The most important explanations you made, the easy site navigation, the friendships you can help foster - it's everything fantastic, and it is helping our son in addition to us feel that that subject is satisfying, and that's very vital. Many thanks for all the pieces!

Needed to compose you that little observation in order to thank you the moment again on your pleasing information you have shown on this site. It was particularly open-handed of you to make openly just what most people would've offered for sale as an e book to end up making some money for themselves, notably considering that you could possibly have tried it if you decided. These advice as well worked like a great way to understand that someone else have similar interest just as my very own to learn significantly more in terms of this issue. I'm certain there are some more pleasurable opportunities in the future for many who scan through your blog.

I truly wanted to type a simple word to be able to say thanks to you for all the fabulous advice you are posting at this website. My prolonged internet lookup has at the end been rewarded with excellent strategies to talk about with my family. I 'd tell you that many of us website visitors actually are rather blessed to be in a useful community with very many special professionals with insightful ideas. I feel truly fortunate to have seen your entire website and look forward to plenty of more pleasurable times reading here. Thank you again for a lot of things.

Needed to draft you that tiny observation in order to give thanks yet again for the superb methods you have documented in this case. It was quite surprisingly open-handed with you to give unreservedly what exactly many people would've offered for sale for an e book to earn some dough for their own end, most notably considering that you could possibly have tried it in case you considered necessary. Those inspiring ideas in addition acted like a fantastic way to recognize that the rest have similar zeal like my very own to know the truth more regarding this matter. I'm certain there are some more enjoyable opportunities up front for folks who find out your blog post.

My spouse and i were very glad Edward managed to carry out his survey from the precious recommendations he discovered in your weblog. It's not at all simplistic to simply continually be giving for free tips and hints other people have been making money from. And we also consider we've got the blog owner to give thanks to because of that. All of the explanations you have made, the easy site navigation, the relationships your site give support to create - it's everything powerful, and it's really helping our son and the family do think the subject is cool, which is certainly exceptionally pressing. Many thanks for the whole thing!

I wish to show my appreciation to this writer just for bailing me out of this setting. Just after researching throughout the world-wide-web and meeting advice which were not productive, I was thinking my entire life was gone. Living without the presence of strategies to the issues you have fixed all through your entire short post is a crucial case, and the kind that could have in a negative way damaged my entire career if I hadn't come across your blog post. That training and kindness in taking care of all areas was invaluable. I don't know what I would have done if I hadn't come upon such a thing like this. I can also at this moment look ahead to my future. Thanks a lot very much for the specialized and effective guide. I will not hesitate to recommend your web site to any person who should have direction on this issue.

I intended to send you the bit of observation so as to thank you so much the moment again considering the pretty guidelines you've contributed at this time. This has been quite shockingly generous of you to convey extensively all that many individuals would have distributed as an e-book to make some bucks for their own end, principally considering that you might well have done it in the event you decided. These inspiring ideas likewise served as the easy way to know that someone else have the identical desire similar to my personal own to learn lots more with regard to this matter. I know there are a lot more fun sessions ahead for many who looked at your website.

I truly wanted to post a quick message to say thanks to you for the splendid information you are showing on this website. My time intensive internet search has at the end been rewarded with high-quality tips to write about with my two friends. I would suppose that most of us readers actually are really fortunate to exist in a wonderful website with so many awesome people with helpful advice. I feel really happy to have seen your entire webpage and look forward to some more amazing times reading here. Thanks a lot once again for all the details.

That is the precise blog for anyone who needs to search out out about this topic. You notice a lot its almost hard to argue with you (not that I actually would want匟aHa). You positively put a brand new spin on a topic thats been written about for years. Nice stuff, just nice!

I needed to write you a tiny remark to say thanks a lot again for all the spectacular ideas you have discussed in this article. This is simply unbelievably open-handed of you in giving easily exactly what many people would have offered for sale as an e-book in making some cash for themselves, most importantly given that you could possibly have tried it if you ever desired. Those tricks in addition worked like the easy way to recognize that the rest have similar desire much like my own to understand significantly more with regards to this problem. I'm sure there are thousands of more fun times in the future for individuals that view your blog.

Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.