Problem with if construction

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.

Anyone that can tell me why?

Thanks in advance!

JD

Right after posting I explained my father what it was doing and I realized that the 'int lastmillis' should be a (unsigned) long.

Don't use millis() inside an interrupt service routine (ISR) and defiantly don't print in it, it will take too long and clog up the processor.

ISRs should be executed as quickly as possible and then exited. But for this you don't even need to go to ISRs do it all from polling.

Thank you Mike,

In my case it isn't a problem since this is the only code I need for this project.

For future reference, what should I use instead of millis()?

what should I use instead of millis()?

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.

I was thinking about the same solution when I was in the shower this morning.

Thanks again!