Before getting to the RPM I would be glad to get the period right. So I wrote:
unsigned long PreviousMark = 0;
void setup(){
Serial.begin(115200);
attachInterrupt(5, Period, FALLING);//interrupt 5 is pin 18 on mega
}
void loop(){
}
void Period ()
{
unsigned long Period (millis()-PreviousMark);
Serial.println (Period);
PreviousMark = millis();
}
Initially it worked fine, but then I see that I get this erroneus readings at random times. My signal is super clean from a pulse generator. Here is what I get:
I'ts not really a good idea to do serial prints from an ISR.
To speed up things a bit make the variable Period as a volitie global. That way Period can be printed from loop() and the variable Peorid is not created and destroyed with each ISR itteration.
OK, Volatile seems to help. I am getting nice numbers,
Still , dont know how to print from the loop and not miss one reading...
Also I dont know how not to destroy the period with each pulse. It is suppose to vary , right?
Sorry, please help...
volatile long PeriodMs;
unsigned long PreviousMark = 0;
void setup(){
Serial.begin(115200);
attachInterrupt(5, Period, FALLING);//interrupt 5 is pin 18 on mega
}
void loop(){
}
void Period ()
{
PeriodMs =(millis()-PreviousMark);
Serial.println (PeriodMs);
PreviousMark = millis();
}
Keep in mind that latest is a multi-byte variable. There is a possibility that while you are accessing this variable in loop() it could get interrupted and you could end up with a corrupted value! You need to disable interrupts while reading latest. Here is one way to accomplish that:
thanks for the suggestion. I implemented it.
I also have other buttons using the debouncer library.
This way they wont interfere.
If the debouncer "Bounces" during the noInterrupts(), would I miss it?