Last active
May 6, 2020 13:24
-
-
Save ronanj/6bfd1d4af7c0e0e9ff3583ecb782d84d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Accumulator | |
{ | |
#define MAXACCVALUES 100 | |
int vals[MAXACCVALUES]; | |
unsigned long startTime; | |
public: | |
int count = 0; | |
Accumulator() | |
{ | |
startTime = millis(); | |
reset(); | |
} | |
bool hasData() | |
{ | |
return count!=0; | |
} | |
bool full() { | |
unsigned long dt = millis()-startTime; | |
return count==MAXACCVALUES || (count>0&&dt>60*1000); | |
} | |
void add(int val) | |
{ | |
if (count==0) { | |
startTime = millis(); | |
} | |
if (count==MAXACCVALUES-1) { | |
for (int i=0;i<MAXACCVALUES-1;i++) { | |
vals[i]=vals[i+1]; | |
} | |
count --; | |
} | |
vals[count++]=val; | |
} | |
void reset() | |
{ | |
count = 0; | |
for (int i=0;i<MAXACCVALUES;i++) { | |
vals[i]=0; | |
} | |
startTime = millis(); | |
} | |
float stddev() | |
{ | |
int u =avg(); | |
if (u<0) return -1; | |
int t = 0; | |
for (int i=0;i<count;i++) { | |
t+=(vals[i]-u)*(vals[i]-u); | |
} | |
return sqrt(t)/count; | |
} | |
int median() | |
{ | |
if (count==0) return -1; | |
for (int i=0;i<count;i++) { | |
for (int j=0;j<i;j++) { | |
if (vals[i]>vals[j]) { | |
float t = vals[j]; | |
vals[j]=vals[i]; | |
vals[i]=t; | |
} | |
} | |
} | |
// std::sort(vals,vals+count); | |
return vals[count/2]; | |
} | |
float avg() | |
{ | |
if (count==0) return -1; | |
float t = 0; | |
// Serial.printf("[avg(%d):",count); | |
for (int i=0;i<count;i++) { | |
t+=vals[i]; | |
// Serial.printf("%d,",vals[i]); | |
} | |
// Serial.printf("=>%d] ",int(t/count)); | |
return t/count; | |
} | |
int min() | |
{ | |
if (count==0) return -1; | |
int t = vals[0]; | |
for (int i=0;i<count;i++) { | |
if (t>vals[i]) { | |
t=vals[i]; | |
} | |
} | |
return t; | |
} | |
int max() | |
{ | |
if (count==0) return -1; | |
int t = vals[0]; | |
for (int i=0;i<count;i++) { | |
if (vals[i]>t) { | |
t=vals[i]; | |
} | |
} | |
return t; | |
} | |
void print() { | |
unsigned long dt = (millis()-startTime)/1000; | |
Serial.printf("#%2d values in %3ld sec - %3d<%3d<%3d - stddev:",count,dt,min(),median(),max()); | |
Serial.println(stddev()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment