计算高温和低温
此示例演示如何读取数据、识别某些元素并显示结果。在示例中,您修改了 MATLAB Analysis 和 MATLAB Visualization App 提供的代码模板之一。该示例使用来自 ThingSpeak 通道 12397 的数据,该数据从位于马萨诸塞州纳蒂克的 Arduino® 气象站收集天气数据。
从模板代码创建 MATLAB Analysis 脚本
要计算纳蒂克气象站的每日最高和最低气温,请使用提供的代码模板编写 MATLAB® 脚本。
转至 ThingSpeak 中的 Apps 选项卡,然后选择 MATLAB Analysis。点击 New,选择 Calculate high and low temperatures,然后点击 Create。
分析您的数据
MATLAB Code 字段预先填充了代码,用于计算过去 24 小时内的最高和最低温度。
1) 设置与 ThingSpeak 通信的变量。readChannelID
是从气象站收集数据的公共通道的通道 ID。temperatureFieldID
是通道中包含温度值的字段。仅当您从私有通道读取数据时才为 readAPIkey 分配一个值。气象站是公共的,因此对于此示例,不要设置 readAPIkey。
readChannelID = 12397;
temperatureFieldID = 4;
readAPIKey = '';
2) 使用 thingSpeakRead
函数读取过去 24 小时的温度值。
[tempF,timeStamp] = thingSpeakRead(readChannelID,'Fields',temperatureFieldID,'numDays',1,'ReadKey',readAPIKey);
3) 使用 max
和 min
计算华氏最高和最低温度。然后,识别相应的时间戳并显示结果。
[maxTempF,maxTempIndex] = max(tempF);
[minTempF,minTempIndex] = min(tempF);
timeMaxTemp = timeStamp(maxTempIndex);
timeMinTemp = timeStamp(minTempIndex);
display(maxTempF,'Maximum temperature for the past 24 hours is');
78.9000
display(minTempF,'Minimum temperature for the past 24 hours is');
50.8000
4) 点击 Save and Run 来执行您的代码。Output 字段显示您的结果。
将数据写入通道
1) 通过将最大或最小温度计算结果写入私有通道来存储它。要创建 ThingSpeak 通道,转至 Channels 选项卡并选择 My Channels。点击 New Channel。选中相应的复选框,并输入这些通道设置值:
Name -
Temperature Measurement
Field 1 -
Temperature (F)
点击 Save Channel。
2) 在 MATLAB Code 字段中,设置用于写入私有通道的变量。将 writeChannelID
和 writeAPIKey
的给定值替换为您的值。您可以在页面右侧的 Channel Info 面板中找到通道 ID 并写入 API 密钥。
% Replace with the ID of the channel to write data to. writeChannelID = 17504; % Enter the write API key between the ''. writeAPIKey = '23ZLGOBBU9TWHG2H';
3) 取消注释以下行,将最高温度读数写入您的通道。要保存最低温度值,请将 maxTempF
更改为 minTempF
。
% thingSpeakWrite(writeChannelID,maxTempF,'timestamp',timeMaxTemp,'Writekey',writeAPIKey);
4) 点击 Save and Run 来执行您的代码。ThingSpeak 通道中的图中有一个点,代表记录时的最高温度读数。您可以通过点击页面右侧 Channel Info 面板中的通道链接来访问您的通道。
另请参阅
函数
thingSpeakRead
|thingSpeakWrite
|max
(MATLAB) |min
(MATLAB)