Main Content

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.

Hardware Setup

This example uses:

  • Arduino Uno

  • Arduino Sensor Kit - Base

  • BMP280 sensor

  • CPU cooling fan (12V DC)

  • 5V General Purpose Relay Module

  • XL6009 DC-DC Step-Up Converter

  • Input power source (5V)

Hardware Connection

  1. Place the Base Shield that is part of the Arduino Sensor Kit, on top of Arduino Uno board.

  2. Connect the BMP280 sensor to one of the I2C grove connectors on the Base Shield.

  3. Connect the Arduino Uno to the computer running MATLAB via USB.

  4. 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.

  5. Connect the IN pin of the relay to D2 pin of Arduino Uno.

  6. 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).

  7. 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.

  1. Sign In to ThingSpeak™ using your MathWorks® Account credentials, or create a new account.

  2. Click Channels > MyChannels.

  3. On the Channels page, click New Channel.

  4. 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):

  • Name: Automatic Fan Control

  • Field 1: Temperature

  • Field 2: Status

  • Field 3: Runtime

  • Field 4: Overall Runtime


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.

Add Widgets

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 Runtime and 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.

The 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).



%Setting to trigger relay

writeDigitalPin(a,'D2',1); % Writing 1 to D2 disconnects the relay switch


%Setting up ThingSpeak Parameters
flag=0; % start/stop the timer based on this variable

while 1
    % Read Data 
    if (temp>threshold)
        if flag==0

            % Switching on the relay and turning on the fan

            % Read previous entry

            %Update all the fields
        if flag==1

            %Turn off the fan

            % Read previous entry

            %Calculate overall runtime
            overallRuntime = Runtime + x;
        % Update all the fields

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:

  1. In ThingSpeak, click Apps > MATLAB Analysis.

  2. Click New to get started with your code.

  3. Under Examples, select Read channel to trigger email, and then click Create.

  4. 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:  

% Read temperature data for the last 24 hours 

[tempF,timeStamp] = thingSpeakRead(readChannelID,'Fields',TemperatureFieldID, ... 


% Calculate the maximum and minimum temperatures  
[maxTempF,maxTempIndex] = max(tempF);  
[minTempF,minTempIndex] = min(tempF); 
alertURL = ""; 
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"); 
    webwrite(alertURL, "body", alertBody, "subject", alertSubject, options); 
    % Code execution will end up here when a 429 (error due to frequent request) is caught 

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, Alert).


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 alertBody and alertSubject fields that you configured in the MATLAB Analysis app.