I know there has been some existing forum activity in this area, and in fact, I even see the question I have has been asked before - but I have not seen or understood a clear answer.
I have a passive IR motion detector module. It takes an ATMEGA328's digital input high when it detects motion. My code tests this input and - if high - sends a single character via Serial.write() out through a bluetooth module to a listening mobile phone. However, my main loop code does a lot of things, and the time interval between polling this digital input has grown too long.
The obvious answer seems to be to connect the motion detector to an interrupt pin and have an ISR send the character to the BT module, except that Serial doesn't work in an ISR.
All the literature says use the ISR to set a flag and test that flag in the main loop. Now the question I've seen asked before but not answered:
If I have to test the ISR-set flag in the main loop,
then why don't I just do a digital read in the main loop and delete the ISR?
One reason is to ensure that short high transitions on the pin are captured which the main loop might otherwise miss. However, my motion detector holds the pin high for seconds - so this isn't an issue in this appplication.
Another possible reason is that doing repeated digital reads might be far slower than doing repeated boolean tests - can anyone say whether it is or not?
As it is, I'm thinking I'll just litter the main loop with far more digitalread-and-test IF statemnts.
It's ugly and offensive, and it gets worse because I'd need to sprinkle these inside some hefty functions, too.
However, the equivalent ISR-and-test-the-flag would look just as bad. It would just replace all my occurences of:
if (digitalread(mypin)=HIGH) Serial.write("M");
if (ISRflag) Serial.write("M")l
- no better.
Am I missing a better way? Any help would be appreciated.