Hi , I'm using arduino uno to measure an input frequency on pin2 (interrupt 0). The idea is to fill an array of 20 values of the micros() function. When there are 20 values written in an array, the interrupt is disabled untill data is analysed in the loop().
I want the data to be analysed for consistancy (in future) before a frequency is calculated ( eg. elapsed time for 20 samples' divided by the 'number of samples')
With code below I have nice and stable readings, exept the first index of the array gives inacurate data. I could ignore the first index of the array, and work with the other measurements. But it's driving me crazy!!
const int PwmIn=2;
volatile int edgeCounter=0;
volatile unsigned long timeStamps[25];
void setup(){
Serial.begin(9600);
pinMode(PwmIn,INPUT);
attachInterrupt(0, PwmRegist, FALLING);
timeStamps[0]=0; //I've seen this initialisation on a tutorial, doesn't help me...
}
void loop(){
if (edgeCounter>=20){ //measure at least 20 falling edges/interrupts before processing
detachInterrupt(0); //stop measurements and process first
for (int i=0;i<edgeCounter-1;i++){ //normaal i van 0 tem 19
Serial.println(timeStamps[i+1]-timeStamps[i]); /print intervals
}
Serial.println(); /for clarity
edgeCounter=0; //reset for new measurement cycle
attachInterrupt(0, PwmRegist, FALLING); //start measuring again
}
}
void PwmRegist(){ //interrupt service routine
if (edgeCounter<20){ //make 20 measurements
timeStamps[edgeCounter]=micros();
edgeCounter++; // increment edgecounter
} else {
//detachInterrupt(0); //doesn't work because re-enabled on ISR exit
//noInterrupts(); //works but not nescessary
}
}
this code gives me following measurements(intervals) on ~8kHz, notice how first measurements (timeStamps[0]) deviates:
12
108
108
112
112
108
112
112
112
108
112
112
108
112
112
108
112
112
108
104
108
112
112
108
112
112
108
112
112
108
112
112
108
112
112
108
112
112
40
112
112
112
108
112
108
112
112
108
112
112
108
112
112
112
108
112
112
Your advice is highly appreciated, thank you