IoT-Based Temperature Monitoring Using ThingSpeak and Arduino Hardware
This example shows how to create a ThingSpeak™ channel and use MATLAB® functions to collect the temperature data from a BMP280 sensor connected to your Arduino® board, and then use MATLAB Analysis in ThingSpeak to analyze the maximum and minimum temperature. This example also shows you how to set up an email alert if the room temperature exceeds a threshold value, by using MATLAB functions in ThingSpeak.
Hardware Setup
This example uses:
Arduino Uno
Arduino Sensor Kit - Base
BMP280 sensor
Hardware Connection
Place the Base Shield that is part of the Arduino Sensor Kit, on top of Arduino Uno board.
Connect the BMP280 sensor to one of the I2C pin grove connectors on the Base Shield.
Connect the Arduino Uno to the MATLAB computer via USB.
Create ThingSpeak Channel and Add Widgets
ThingSpeak is an IoT analytics platform service that allows you to aggregate, visualize, and analyze live data streams in the cloud. For more details, refer to Get Started with ThingSpeak (ThingSpeak). You need to first create a new channel in ThingSpeak by defining multiple fields, which help you to collect the data and then write the analyzed data to the same channel.
Sign In to ThingSpeak™ using your MathWorks® Account credentials, or create a new account.
Click Channels > MyChannels.
On the Channels page, click New Channel.
In Channel Settings, select the check boxes next to Fields 1–3. Enter these values for the field names (the unit of temperature in this example is assumed to be degrees Celsius):
Name:
Temperature
Field 1: Live
Temperature
Field 2:
Min Temperature
Field 3:
Max Temperature
Click Save Channel to save the settings. The Channel Stats area of the new channel displays three charts (which correspond to the three fields that you configured).
Add Widgets
In the window that displays the saved channel (Temperature
), click Add Widgets, select Numeric Display and then click Next.
Configure each widget by specifying the name and its corresponding field. For example, the Max Temperature widget can be configured like this:
The new Numeric Display widgets that you configured appear for each of the fields, along with the charts in the Channel Stats area.
Identify API Keys
Before you write the MATLAB code, it is required that you identify the API Keys of the ThinkSpeak channel because these will be used in the code in the MATLAB Analysis app.
To identify the API Keys, click API Keys among the options available for configuring the channel.
To explore the data from the sensor and find the maximum and minimum temperature using ThingSpeak, in MATLAB Analysis app, we use the Read API Key. After obtaining the result, we send the same to the channel using the Write API Key.
Add Code for MATLAB Analysis in ThingSpeak
The MATLAB Analysis app in ThingSpeak lets you explore the data stored in ThingSpeak channels and do further analysis. In this example, we use a custom MATLAB code that reads temperature data from the channel (the data which is originally obtained from the BMP280 sensor) and calculates the minimum and maximum temperature, and then writes the result back to the channel.
To create the code for MATLAB Analysis in ThingSpeak:
Click Apps > MATLAB Analysis.
Click New to get started with your code.
Under Examples, select Calculate high and low temperatures, and then click Create.
In the MATLAB Code area, customize the code as displayed below. Ensure that you change the values assigned to readChannelID, readAPIKey and writeAPIKey fields to match the actual values corresponding to your channel. After you write the code, click Save and Run.
readChannelID = xxxxxx; TemperatureFieldID = 1; readAPIKey = 'XXXXXXX'; [tempF,timeStamp] = thingSpeakRead(readChannelID,'Fields',TemperatureFieldID, ... 'numDays',1,'ReadKey',readAPIKey); [maxTempF,maxTempIndex] = max(tempF); [minTempF,minTempIndex] = min(tempF); timeMaxTemp = timeStamp(maxTempIndex); timeMinTemp = timeStamp(minTempIndex); display(maxTempF,'Maximum Temperature for the past 24 hours is'); display(minTempF,'Minimum Temperature for the past 24 hours is'); writeAPIKey = 'XXXXXXXX'; thingSpeakWrite(readChannelID,[minTempF,maxTempF],'WriteKey',writeAPIKey,'Fields',[2,3]); pause(1)
Run MATLAB Code to Obtain Temperature Data from BMP280 Sensor
After you configure ThingSpeak channel, you can run the MATLAB code on the Arduino board that has BMP280 sensor connected. The MATLAB code uses channel ID and its Write API Key to publish data over IoT to the ThingSpeak channel.
The bmp280
object in MATLAB Support Package for Arduino Hardware establishes a connection to the connected BMP280 sensor and reads the temperature data.
Run these commands, one after the other, in the MATLAB command window (it is assumed that Arduino board is connected to the COM9 port). Replace channel ID (first argument in thingSpeakWrite
function) and the Write API Key to match the actual values corresponding to your channel.
a=arduino('COM9','Uno','Libraries','I2C') sensorObj=bmp280(a); while 1 temp=readTemperature(sensorObj); thingSpeakWrite(xxxxxx,temp,'WriteKey','XXXXXXXXX','Fields',1); pause(300); %sending data every 5 minutes end
Note: To stop the while
loop and stop executing the code (to stop sending data to the ThingSpeak channel), press Ctrl+C
in the MATLAB Command Window.
The data from BMP280 sensor is sent to the channel every 5 minutes. You can view the Channel Stats in ThingSpeak and observe the live temperature and the maximum and minimum recorded temperature till that time. This figure shows an example of recorded data based on live temperature sent from BMP280 sensor over IoT using ThingSpeak. The figure shows the plot of temperature variation and displays the two Numeric Display widgets that you added.
Set Up Email Alert for Temperature Beyond Threshold Using ThingSpeak
After the data from the BMP280 sensor connected to Arduino board is available in the ThinkSpeak channel, you can set up an email alert that triggers an email. The email will be sent to the email ID registered with your ThinkSpeak account, whenever the temperature exceeds a threshold.
To set up the email alert:
Click Apps > MATLAB Analysis.
Click New to get started with your code.
Under Examples, select Read channel to trigger email, and then click Create.
In the MATLAB Code area, customize the code as shown below. Ensure that you change the values assigned to readChannelID and readAPIKey fields to match the actual values corresponding to your channel. The alertAPIKey is the one associated with your profile in ThingSpeak. After you write the code, click Save and Run.
% Enter your MATLAB Code below readChannelID = xxxxxxx; % Temperature Field ID TemperatureFieldID = 1; % Channel Read API Key % If your channel is private, then enter the read API Key between the '' below: readAPIKey = 'XXXXXXXXXX'; % Read temperature data for the last 24 hours. [tempF,timeStamp] = thingSpeakRead(readChannelID,'Fields',TemperatureFieldID, ... 'numDays',1,'ReadKey',readAPIKey); % Calculate the maximum and minimum temperatures [maxTempF,maxTempIndex] = max(tempF); [minTempF,minTempIndex] = min(tempF); alertApiKey='XXXXXXXXX'; alertURL = "https://api.thingspeak.com/alerts/send"; options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]); alertBody = sprintf("It's hot here and the temperature is %0.2f°F!.", maxTempF); alertSubject = sprintf("Temperature exceeded threshold!"); try webwrite(alertURL, "body", alertBody, "subject", alertSubject, options); catch % Code execution will end up here when an error 429 (error due to frequent request) is caught end
You can set up a React app that triggers the email alert, as configured above, when the temperature exceeds a particular temperature.
To do this, click Apps > Actions > React, and then configure the app as shown in this image (the MATLAB Analysis app that you configured as shown above is saved with the name, Alert
).
Click Save React. Whenever the room temperature, as read by the BMP280 sensor, exceeds 26 degrees Celsius, an email is sent to the ThingSpeak-registered email ID. This figure shows a sample email based on the alertBody
and alertSubject
fields that you configured in the MATLAB Analysis app.