-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMATLAB_Anomaly_Filter.m.txt
More file actions
53 lines (42 loc) · 2 KB
/
Copy pathMATLAB_Anomaly_Filter.m.txt
File metadata and controls
53 lines (42 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
% MATLAB Code for Anomaly Detection (ThingSpeak Analysis App)
%
% This script runs on ThingSpeak's cloud platform.
% It reads the raw data from Field 1, applies a Moving Average Filter
% for noise reduction (DSP), and writes the anomaly status to a new field (e.g., Field 2).
% 1. Read the last 60 data points (approx 10 minutes) from Field 1
% Note: Replace YOUR_CHANNEL_ID and YOUR_READ_API_KEY with your credentials
readChannelID = YOUR_CHANNEL_ID;
fieldID = 1;
readAPIKey = 'YOUR_READ_API_KEY';
tempData = thingSpeakRead(readChannelID, 'Field', fieldID, 'NumPoints', 60, 'ReadKey', readAPIKey);
% 2. Digital Signal Processing (DSP): Apply a Moving Average Filter
% We use a window size of 5 data points (50 seconds) to smooth the noise.
windowSize = 5;
b = (1/windowSize)*ones(1,windowSize);
a = 1;
tempFiltered = filter(b, a, tempData);
% Get the latest filtered value
latestFilteredTemp = tempFiltered(end);
latestRawTemp = tempData(end);
% 3. Anomaly Detection and Threshold Logic
% Critical Threshold set at 60.0 C
CRITICAL_THRESHOLD = 60.0;
% Default status: 0 (Normal)
anomalyStatus = 0;
statusMessage = 'Normal';
% Check if the latest RAW data is above the threshold (confirming the anomaly)
if latestRawTemp > CRITICAL_THRESHOLD
anomalyStatus = 1; % Status 1 means Anomaly Detected
statusMessage = '!!! ANOMALY DETECTED (70C Spike) !!!';
end
% 4. Write the results back to ThingSpeak
% We write the Filtered Temperature to Field 2 and the Anomaly Status to Field 3.
outputField2 = latestFilteredTemp; % Filtered Value
outputField3 = anomalyStatus; % Anomaly Flag (1 or 0)
writeChannelID = YOUR_CHANNEL_ID;
writeAPIKey = 'YOUR_WRITE_API_KEY'; % Use the WRITE_API_KEY for the output channel
thingSpeakWrite(writeChannelID, [outputField2, outputField3], 'WriteKey', writeAPIKey);
% 5. Output for Debugging
disp(['Latest Filtered Temp (Field 2): ', num2str(latestFilteredTemp)]);
disp(['Anomaly Status (Field 3): ', num2str(anomalyStatus)]);
disp(statusMessage);