I'm using a hall effect sensor to measure RPM and when using interrupts i see in some sample code, detachInterrupt is called before any calculations followed by attachInterrupt.
These sample programs are very simple and don't show what to do in other functions, so do i need to call detachInterrupt / attachInterrupt in other functions as well?
For example within my loop() of my program I have
GetRPM()
detachInterrupt
rpm = bla bla bla
attachInterrupt
DisplayandWriteRPM()
// detachInterrupt // is this needed?????????
LCD.print bla bla bla
SD.print bla bla bla
//attachInterrupt // is this needed?????????
My program works intermittently sometimes for a few seconds, sometimes a minute before the program "locks" up meaning the display freezes. My suspission is i'm missing the detachInterrupt / attachInterrupt in all my other functions.
I have millis() calls but not in my ISR and I have no delay() anywhere in my code.
Thought I'd ask before i start a nasty debug session.
Thanks in advance.
The only way to avoid race conditions (nasty bugs) is to call attachInterrupt in setup when your sketch is ready to process interrupts then never call either function again.
I do have the attachInterrupt() method in my setup() but sample code indicated to turn it off, then back on during calculation routines.
I guess I'll just give it a shot.
The correct method is to disable interrupts while accessing data shared with the interrupt service routine. When finished accessing shared data enable interrupts. The code between disabling and enabling is called a "critical section".
And what happened if you don't "detachInterrupt"?
An attachInterrupt() allows to change the interrupt condition (rising/falling edge...). Most probably your examples change that condition, that's why attachInterrupt() has to be called more than once.
If an interrupt occurs in the middle of attachInterrupt(), the new address may have been set incompletely, what can be prevented by a detachInterrupt(). But I'd guess that interrupts are already disabled in attachInterrupt(), so that a preceding detachInterrupt() is not really required.