A few months ago my daughter received a 'spy gear' at a fast-food restaurant. It's an ir-detector that has a little piezo buzzer that beeps when someone enters the 'beam'.
I have tapped into the piezo and connected it to digitail pin 2 (interrupt 0) and have this code to detect that the piezo beeps.
int pin = 13;
volatile int state = LOW;
int lastmillis = 0;
void setup()
{
pinMode(pin, OUTPUT);
attachInterrupt(0, blink, CHANGE);
Serial.begin(9600);
}
void loop()
{
}
void blink()
{
if ((lastmillis + 10000) <= millis())
{
state = !state;
digitalWrite(pin, state);
Serial.print("--lastmillis: ");
Serial.println(lastmillis);
Serial.print("--millis(): ");
Serial.println(millis());
lastmillis = millis();
}
}
For some reason that I can't find I only get into the if-construction for 2 times. After that I still get in the blink function, but not in the if-construction.
While millis() will still return a value inside an ISR, it will not be updated because it is updated with another ISR. So if you spend long in your own ISR, millis() will be slow. There is nothing to use instead just don't use it, or at least be aware of the limitations.
Best is if you make a note of it in a global variable and pick that up in the main loop.