Hi, I am using an arduino uno..
I want to measure a sinusoidal frequency around 800Hz. I decided i wanted to use a physical interrupt to measure T . Apart from anything else i want to get a better understanding of interrupts which look very useful for interacting with the real world. This is to be part of a larger project.
My simple sketch works OK, BUT:
I am using a sq wave generator, but, my generator has some jitter and i thought to try EMA to get a better average.
When i use the EMA (or even just averaging) code at lines 43 or 44 the serialmonitor gives me 'inf'. Its probably just a simple logic error but I cant find it having looked a long time - maybe I'm missing something. It works ok without that. I'm feeling rather dumb, `` but help would be appreciated?
A second query, interrupts() and nointerrupts() at lines 39 and 60 seem to have no effect, should i use them or not?
Thanks to anyone willing to help.
/*
##### Pin 2 is the interrupt pin
interrupt set to 'rising' on pin 2
*/
//*************************
float alpha = 0.8; //use for EMA function
int counter = 0; //counting the number of times interrupted
int waiting = 0; //counting the number of cycles waited between interrupts
float now = 0;
float then = 0;
float duration = 0; //will be (now - then)
float freq = 1;
float prevfreq = 1;
const byte interruptPin = 2; //pin2 will be the interrupt
bool flag = true; //used in ISR
//**************************
void checktISR() {
flag = false;
}
//======================
void setup() {
Serial.begin(115200);
pinMode(2, INPUT_PULLUP);
//pinMode(2, INPUT);
Serial.println();
Serial.println();
Serial.println("***********test of interrupts use************");
attachInterrupt(digitalPinToInterrupt(2), checktISR, RISING); //rising level on pin 2 triggers the checktisr
delay(3000);//time to read sketch name -and clear serial monitor output
}
//==========
void loop()
{
if (flag == false) { //an interrupt has occurred
//noInterrupts();
waiting = 0;
duration = ((now - then) / 1000000);
freq = (1/duration);
//freq = ((freq * alpha) + (prevfreq * (1 - alpha))); //implement simple EMA to smooth measurement DONT WORK??
//freq = (freq + prevfreq)/2; //simple averaging DONT WORK?? gives 'inf' in serialmonitor.
/*
Serial.println(now);
Serial.println(then);
Serial.println(now - then);
Serial.println ("");
Serial.print (" interrupt operated ");
counter = counter + 1;
Serial.print (counter);
Serial.print(" ********* duration = ");
Serial.println(duration); */
Serial.println(freq);
//Serial.println ("");
flag = true; //reset the flag
then = now;
prevfreq = freq;
//interrupts();
//delay(10);
}
/*
Serial.print (" waiting for interrupt ");
Serial.println(waiting);
waiting = waiting + 1;
delay(50);
Serial.print (" Now = ");
Serial.print(now);
Serial.print (" Then = ");
Serial.print(then);
*/
now = micros();
}