#include <cmath>
#define LENGTH 10
#define PHOTOR 34
int values[LENGTH];
int diffs[LENGTH-1]; // diffs is one element shorter than values
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(PHOTOR, INPUT);
Serial.println(analogRead(PHOTOR));
}
void loop() {
// put your main code here, to run repeatedly:
for(int i=0; i<LENGTH; i++) {
values[i] = values[i+1];
}
values[LENGTH-1]=1023-analogRead(PHOTOR);
// Calculate the differences
for (int i = 1; i < LENGTH; i++) {
//int prev = (i > 0) ? (i - 1) : LENGTH - 1;
diffs[i-1] = values[i] - values[i-1];
}
double y = diffs[LENGTH-2];
double mn = mean(diffs, LENGTH-1);
double std = stdev(diffs, LENGTH - 1);
// Calculate Z-Score for the current reading
double zscore = (y - mn) / std;
Serial.print(zscore > 1.5);
analogRead((PHOTOR));
delay(1000); // this speeds up the simulation
}
double mean(int* arr, int length) {
double sum = 0;
for (int i = 0; i < length; i++) {
sum += arr[i];
}
return sum / length;
}
double variance(int* arr, int length) {
double m = mean(arr, length);
double sum = 0;
for (int i = 0; i < length; i++) {
sum += pow(arr[i] - m, 2);
}
return sum / (length - 1);
}
double stdev(int* arr, int length) {
return sqrt(variance(arr, length));
}