Interrupt missing events

Hi,

I am trying to use interrupts to log High->Low and Low->High changes on Pin 2 of my Uno. I need to send information about the events over the serial connection.

However, it seems that some data is missing in my output. In my expectation, the output on serial should always be 010101010101... since interrupts are generated by level change. But sometimes I see output like 0101000011010...

I'm wondering if the writing on the serial port messes up the interrupt handling or vice versa. If that is the case, what would be a good way to collect the data without missing any events and (maybe periodically) sending that data over the serial line?

My sample code looks like this:

const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
volatile byte lastState = !state;

void setup() {
  Serial.begin(115200);            
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), blink, CHANGE);
}

void loop() {

  if (!lastState == state){
    Serial.println(state);   // send the data
    lastState = state;  
  }
  
}

void blink() {
  state = digitalRead(interruptPin);
  
}

Thanks in advance for your helpful input,

Erik

The interrupt handler probably isn't missing any events. What happens, though, is that it may be triggered two or three times while loop() is determining that a change happened, and buffering the data, so you don't catch all the changes. You could speed loop() up by using print() instead of println(), and send 1/3 the amount of data.

What is triggering the external interrupt? How are you dealing with bouncing? What are you sending the data to?

Hi Paul,

The input is a digital signal originating from a sensor which will trigger every time a light beam is broken. There should be no bouncing issues. If there is anyway, I will need to filter out very short pulses.

The data is sent to a Raspberry Pi which will then do some additional data processing and connect to a cloud service.

The frequency of the input signal should be no more than 10Hz so I am not too worried that I will have issues because of speed (I may be wrong). I am more concerned if I am taking a completely wrong approach by using interrupts and the serial communication the way I am.

Erik

The frequency of the input signal should be no more than 10Hz

Then interrupts are not necessary, unless the Arduino is doing more than the code you posted here. Polling the pin, as in that state change detection example should be sufficient (and certainly a lot easier to debug).

OK, thanks for your help and prompt reply.

Best regards,

Erik