IoT-Based Automatic Cooling Fan Control Using ThingSpeak and Arduino Hardware
This example shows how to create a ThingSpeak™ channel and use the MATLAB® functions to collect the temperature data from a BMP280 sensor connected to your Arduino® board, and then use MATLAB Analysis in ThingSpeak to trigger the automatic control of a CPU cooling fan kept in the room and then monitor the usage of the fan by calculating the runtime. This example also shows you how to set up an email alert if the fan turns on, by using MATLAB functions in ThingSpeak.
This example uses:
Arduino Sensor Kit - Base
CPU cooling fan (12V DC)
5V General Purpose Relay Module
XL6009 DC-DC Step-Up Converter
Input power source (5V)
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 grove connectors on the Base Shield.
Connect the Arduino Uno to the computer running MATLAB via USB.
Connect the Vcc pin of the relay to 5V pin of Arduino Uno, and connect the GND pin of relay to GND pin of Arduino Uno.
Connect the IN pin of the relay to D2 pin of Arduino Uno.
Connect the output pins of relay to the + and - power inputs of XL6009 DC-DC Step-Up Converter. Make the connections such that the LED on the relay glows till it receives input signal from Arduino board (NC - Normally Closed condition).
Connect the + and - terminals of the fan to the output of the XL6009 DC-DC Step-Up Converter.
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. 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–4. Enter these values for the field names (the unit of temperature in this example is assumed to be degree celsius):
Automatic Fan Control
Click Save Channel to save the settings. The Channel Stats area of the new channel displays four charts (which correspond to the four fields that you configured). However, for this example, we use only Field 1 Chart, and use widgets for the other three fields.
In the window that displays the saved channel (
Automatic Fan Control), click Add Widgets, select Lamp Indicator and then click Next.
Configure the widget by specifying the name as Status and by selecting Field 2.
For Field 3 and Field 4, add Numeric Display widgets with the names
Overall Runtime respectively. The updated widgets look like this in the Channel Stats area.
Identify API Keys in ThingSpeak
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.
To identify the API Keys, click API Keys among the options available for configuring the channel.
Run MATLAB Code to Obtain Temperature Data from BMP280 Sensor
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.
bmp280 object in MATLAB Suport Package for Arduino Hardware establishes a connection to the connected BMP280 sensor and reads the temperature data.
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 triggers a signal when temperature crosses a threshold, and then writes the result back to the channel.
To explore the data from the sensor and find the temperature using ThingSpeak, we use the Read API Key. After comparing the temperature against a threshold (26 degree celsius), we use the Write API Key to send the signal that triggers the fan control on pin D2 of Arduino board that is connected to the relay, and also to send the calculated run time values to the same channel.
Run these commands, one after the other, in the MATLAB command window (it is assumed that Arduino board is connected to COM9 port). Replace the values of ChannelID, ReadAPI and WriteAPI variables to match the actual values corresponding to your channel. In this example, we set the
threshold to 26 degree celsius (you can change it, if required).
a=arduino('COM9','Uno','Libraries','I2C') sensorObj=bmp280(a); %Setting to trigger relay configurePin(a,'D2','DigitalOutput'); writeDigitalPin(a,'D2',1); % Writing 1 to D2 disconnects the relay switch temp=readTemperature(sensorObj); %Setting up ThingSpeak Parameters ChannelID=XXXXXXXX; threshold=26; ReadAPI='XXXXXXXXXXX'; WriteAPI='XXXXXXXXXXX'; flag=0; % start/stop the timer based on this variable Runtime=0; overallRuntime=0; thingSpeakWrite(ChannelID,[temp,0,0,0],'WriteKey',WriteAPI,'Fields',[1,2,3,4]); pause(1); while 1 % Read Data temp=readTemperature(sensorObj); if (temp>threshold) if flag==0 tic; flag=1; % Switching on the relay and turning on the fan writeDigitalPin(a,'D2',0); % Read previous entry y=thingSpeakRead(ChannelID,'ReadKey',ReadAPI,'Fields',[3,4]); %Update all the fields thingSpeakWrite(ChannelID,[temp,1,y(1),y(2)],'WriteKey',WriteAPI,'Fields',[1,2,3,4]); pause(1); end else if flag==1 Runtime=toc; flag=0; %Turn off the fan writeDigitalPin(a,'D2',1); % Read previous entry x=thingSpeakRead(ChannelID,'ReadKey',ReadAPI,'Fields',4); %Calculate overall runtime overallRuntime = Runtime + x; end % Update all the fields thingSpeakWrite(ChannelID,[temp,0,Runtime,overallRuntime],'WriteKey',WriteAPI,'Fields',[1,2,3,4]); end pause(5); 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. You can view the Channel Stats in ThingSpeak and observe the live temperature, the status of the fan, and the runtime values. 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, the status of the fan (ON), and the display in 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:
In ThingSpeak, 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 = XXXXXXXX; % Temperature Field ID TemperatureFieldID = 1; % Channel Read API Key % If your channel is private, then enter the read API Key between the '' below: readAPIKey = 'XXXXXXXXXXXX'; % 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='XXXXXXXXXXXXXXXX'; alertURL = "https://api.thingspeak.com/alerts/send"; options = weboptions("HeaderFields", ["ThingSpeak-Alerts-API-Key", alertApiKey ]); alertBody = sprintf("The temperature is %0.2f°F.Turning on the Fan", maxTempF); alertSubject = sprintf("Temperature exceeded threshold"); try webwrite(alertURL, "body", alertBody, "subject", alertSubject, options); catch % Code execution will end up here when a 429 (error due to frequent request) is caught end
Next, let's set up a React app that triggers the email alert, as configured above, when the temperature exceeds 26 degree celsius.
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,
Click Save React. Whenever the room temperature, as read by the BMP280 sensor, exceeds 26 degree Celsius, an email is sent to the ThingSpeak-registered email ID. This figure shows a sample email based on the
alertSubject fields that you configured in the MATLAB Analysis app.