Reacting to Events in Your Data With MATLAB

Chris Hayhurst uses a solar water heater at his house to lower energy costs and use hot water in his house heated up by the sun. Chris is a consulting manager for The MathWorks and partnered with the IoT team to use ThingSpeak to collect data about his system and use ThingSpeak’s built-in MATLAB app to analyze it. In this project, Adarsh and I are going to show you how to send alerts when events are detected in the data by using the MATLAB Analysis app.

Solar water heating system

Chris’ home solar water heating system is an example of an IoT application that uses multiple sensors to collect data about a physical system.  Chris’s water heater measures ambient temperature, stored water temperature, collector temperature, and pump speed. All of this data gets collect by ThingSpeak and stored in Channel 29633.

Solar water heater

On days when the stored water temperature exceeds 50°C (122°F), there’s no need to use other methods to heat the store of water to a useful working temperature.  The pump should turn on only when the collector temperature is greater than the temperature of the stored water tank. If the pump turns itself on when the collector is cooler than the stored water temperature, valuable heat is lost from the stored water tank. Chris wants to be alerted of this condition, so that he can adjust the controller settings and increase the efficiency of the system.

IoT systems like Chris’ solar water heating system, typically gather large amounts of data but often the real interest is in events that occur infrequently. The ability to take action when these infrequent events occur is important and requires a mechanism to detect such an event and launch an action. We are going to use the data collected by the solar water heating system stored in the ThingSpeak Channel 29633 and use the MATLAB Analysis app to detect a condition and alert him using Twitter.


MATLAB Event Detection

To detect an erroneous pump behavior event, create a new MATLAB Analysis on ThingSpeak with the following code:

% Read data from fields 1, 2, and 3 from channel 26633.
% Field 1 represents the stored water temperature
% Field 2 represents the collector temperature
% Field 3 represents the state of the pump - on or off
[data, time] = thingSpeakRead(29633, 'Fields', [1, 2, 3]);

% Assign measurements to individual variables
storeTemp = data(1);
collectorTemp = data(2);
pumpState = data(3);

% Check if collectorTemp is less than storeTemp
isCollectorCooler = collectorTemp < storeTemp;

% Identify if pump is on while the collector is cooler.
% We apply a logical AND operation to detect an event only when collector
% is cooler than store temperature and the pump is on.
eventDetected = isCollectorCooler & pumpState

Press the ‘Run & Save’ button to save the MATLAB Analysis App. The code above sets eventDetected to 1 every time the collector temperature is cooler than stored temperature and if the pump is on. Now that we can detect the event, we need to set the MATLAB App to be run on a schedule. To do this, we will setup a TimeControl to run our MATLAB code every 5 minutes.

TimeControl options

Sending Alerts using MATLAB Analysis

So far, we’ve created a MATLAB Analysis to detect events in the data being collected in the solar water heater data channel. We associated our MATLAB Analysis code with a TimeControl to have it run every 5 mins to check for our event of interest. To receive a notification via Twitter when the pump is on incorrectly, we can use MATLAB Analysis to send a Tweet.

First, you need to link your Twitter account to your ThingSpeak account. Then, add the following lines of code at the end of your MATLAB Analysis code to send a Tweet when an event is detected:

If eventDetected
'api_key', '<ThingTweet_APIKey>', 'status', 'Alert! Solar pump error!')

Be sure to replace <ThingTweet_APIKey> with your ThingTweet API Key.

If the solar water heater pump turns on at the wrong times, you will get a Tweet to let you know!

Next Steps

This example shows you the power of some of the ThingSpeak apps that we make available to you to experiment with. The MATLAB Analysis app is really powerful and can be used to detect events in your data and send alerts. MATLAB Analysis can be used for all sorts of calculations and orchestrations of different web services. We could have also used MATLAB to control the pump.

Feel free to try this example and take it further…

  • Reading data from fields in different channels
  • Combining data from fields in a channel and data read from a website such as a weather station or weather forecast.

What will you MATLAB?

Schedule MATLAB Code with TimeControl

Here at our headquarters we have a weather station collecting lots of weather data and sending it to ThingSpeak. We have made that data public for use in your own projects.

MathWorks Weather Station

We write the temperature and humidity values from the weather station to a ThingSpeak channel. At some point in the project, we started to wonder about dew point calculations. We wrote some MATLAB code that combined the temperature and humidity to calculate dew point. I did this using the ThingSpeak app, “MATLAB Analysis”. You can try this out with ThingSpeak now by signing in, selecting Apps, MATLAB Analysis, New, selecting “Calculate Dew point”, and clicking “Create”. This happens to be one of our built-in examples using our weather station’s public data.

It is great that it was easy to calculate dew point with MATLAB, but I want to see this analyzed data over time just like any other sensor data. The solution is a powerful combination of MATLAB Analysis and TimeControl. We use MATLAB Analysis to do the analysis and write the data to a ThingSpeak channel. Then, we use the TimeControl app to repeat the analysis every 5 minutes.

To setup MATLAB Analysis on a schedule, sign into ThingSpeak, select Apps, TimeControl, and New TimeControl.

Dew Point TimeControl in ThingSpeak

My MATLAB code now runs every 5 minutes doing analysis and writing data to my ThingSpeak channel. The TimeControl settings can be tailored to your needs such as executing MATLAB code once a day or only on weekends. This combination of MATLAB Analysis + TimeControl allows you to create continuous analysis of your project data.

To try this out for yourself, we have a public channel of weather station data that we have collected in Natick, MA at our headquarters. You can use that data and do your own MATLAB Analysis and writing the results back to your own channel. Also, Check out the ThingSpeak Documentation where we have a complete tutorial for you to help get started with ThingSpeak and MATLAB.

Sending Tweets Automatically Every Morning With TimeControl

TimeControl can be used to send Tweets automatically at predetermined times.  In this tutorial, we’ll be sending a Tweet every weekday with the current time and the current CheerLights color.

The first step is to link a Twitter account to ThingSpeak.

Next, we’ll create a new TimeControl with the following values:

  • Name: “CheerLights to Twitter”
  • Frequency: “Recurring”
  • Days: “Mon”, “Tue”, “Wed”, “Thu”, “Fri”
  • Time: “9:40 am”
  • Fuzzy Time: “+/- 10 minutes”
  • Action: “ThingTweet”
  • Tweet: “It is currently %%datetime%% and CheerLights is %%channel_1417_field_1%%.”
  • Twitter Account: (select your linked Twitter account)

Save this TimeControl and you’re finished.  Every weekday within 10 minutes of 9:40 am in your timezone, TimeControl will send a Tweet with the current datetime and the current CheerLights color.

The CheerLights Channel ID is 1417, and colors are saved in field 1, so %%channel_1417_field_1%% will be replaced with the current CheerLights color.  You can change these values to access the most recent data from your own Channels.

Here’s an example Tweet from this tutorial.

ThingSpeak Introduces New Internet of Things App – TimeControl

A ThingSpeak App is a service offered by ThingSpeak that runs in the cloud to help you build connected projects and release connected products for the Internet of Things. We are happy to announce today that we are releasing a new app and we are excited to see what you do with it!

Introducing TimeControl…

TimeControl is a web service hosted by ThingSpeak that executes any type of HTTP service call or sends Tweets at predetermined times or schedules. We now offer one-time commands and weekly recurring schedules for commands. TimeControl executes a ThingHTTP or ThingTweet command, and ThingHTTP can interface with any external Web Service API by doing SSL, Basic Auth, custom HTTP headers, GETs, POSTs, PUTs, and DELETEs. ThingHTTP simplifies connecting low-power, low-resource microcontrollers to complex web service APIs such as Twilio, Xively, and Amazon. When you combine TimeControl + ThingHTTP, you get scheduled triggers to any web service you can imagine and scheduled control of an embedded IoT device.

TimeControl Examples Apps

Example TimeControl Projects

  • Turn on your lights every day at 4pm
  • Set a feeder schedule on your aquarium
  • Schedule full control of ioBridge and devices
  • Send a Tweet of your Channel’s last value every morning

ThingSpeak IoT Apps

  • ThingTweet – Link your Twitter account to ThingSpeak and send Twitter messages using our simple API
  • ThingHTTP – Create custom POSTs or GETs to other web services and retrieve the data
  • TweetControl – Listen to commands from Twitter and then perform an action
  • React – Perform actions when conditions are met by your data in your channels
  • TalkBack – Allow devices to execute queued commands
  • TimeControl – Automatically execute ThingHTTP requests at predetermined times and schedules 

TimeControl Resources