Last active
November 27, 2016 01:37
-
-
Save guyc/1c7187454bb223f94d58945f727114b7 to your computer and use it in GitHub Desktop.
Filter out short spikes from tacho sensor
This file contains hidden or 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
unsigned long hTime = 0; // integer for storing high time | |
unsigned long lTime = 0; // integer for storing low time | |
const int window = 4; // sliding window size | |
const int shift = 3; // reject pulses if width < sum * (window / 2^shift) or 1/2 of mean pulse | |
unsigned long highFilter[window]; | |
int highIndex = 0; | |
unsigned long lowFilter[window]; | |
int lowIndex = 0; | |
// filter returns true if <total> is not less than (1 / 2 ^ shift) x the sum | |
// of the last <window> samples. For window=4 and shift=3, that equates to | |
// 1/2 of the mean of the last 4 samples. It always moves <value> into the sliding window | |
// even if it fails the filter test. | |
// REVISIT: we could eliminate a few cycles by keeping a running sum. | |
int filter(unsigned long *filter, int *index, unsigned long value, unsigned long total) { | |
unsigned long sum = 0; // todo, keep running total. | |
for (int i = 0; i < window; i++) { | |
sum += filter[i]; | |
} | |
unsigned long min = sum >> shift; | |
filter[*index] = value; | |
*index = (*index + 1) % window; | |
return total >= min; | |
} | |
void setup() | |
{ | |
pinMode(8,INPUT); | |
Serial.begin(57600); | |
} | |
void report(unsigned long hTime, unsigned long lTime) { | |
float frequency=1000000/(hTime+lTime); // frequency from total timein Micro seconds | |
Serial.print(frequency); | |
Serial.print("Hz "); | |
Serial.print(frequency*15); | |
Serial.print("RPM "); | |
Serial.print(lTime); | |
Serial.print("lTime "); | |
Serial.print(hTime); | |
Serial.println("hTime "); | |
} | |
void loop() | |
{ | |
unsigned long hPulse=pulseIn(8,HIGH); //read high time | |
unsigned long lPulse=pulseIn(8,LOW); //read low time | |
hTime += hPulse; | |
lTime += lPulse; | |
if (filter(highFilter, &highIndex, hPulse, hTime) && | |
filter(lowFilter, &lowIndex, lPulse, lTime)) { | |
report(hTime, lTime); | |
hTime=0; | |
lTime=0; | |
} | |
delay(5000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment