I'm basically wondering if it's OK to Serial.write() or print in the function I register to be called when I2C data is received. I can't seem to find the execution context or any warnings.


1 Answer 1


Looking at twi.c in the Arduino libraries, it seems the callback function is called from within the I2C interrupt service routine (ISR). Any code in the call back will lengthen the ISR so it will have to be short. I don't think Serial.write will be too much of a problem; the TX interrupt will be delayed to the end of the I2C ISR which finishes straight after the callback and the Serial.write function is fairly short.

If you need to have a longer function run, you could instead have the callback store bytes in a ring buffer, then check for any available bytes in the main loop().. but this is what the Wire class helps with already.

  • Serial.write blocks if the serial buffer is full and waits for the buffer to have room before continuing. Conveniently, Serial.write checks to see if interrupts are disabled when it runs; If they are disabled, it runs the interrupt routines itself when a new character needs written to make space in the buffer, preventing lockup. In any case, if the buffer is full, printing on serial can take as long as it physically takes to output that many characters.
    – BrettAM
    Oct 6, 2014 at 2:28
  • @BrettM thanks, I'll edit question with that (or edit it yourself and I will accept) Oct 6, 2014 at 5:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.