0

Imagine i have a code, that loops, and at one point there is i2c request.

Is loop() paused right away when there is Wire.onReceive() or loop is finished then Wire.onReceive() is called?

Nicky
  • 11
  • 2

1 Answers1

2

The onReceive callback is called from an interrupt service routine (ISR). As the name says, interrupts are "interrupting" the currently executing code almost immediately. And "almost immediately" means that it only will take a few clock cycles. (This is the reason why changing data in an ISR can corrupt data, since the ISR may change a variable, when the main code tries to read it)

So the Arduino will not wait for the loop() function to end. It will interrupt in the line, where it was when the interrupt occured, and return to it after the ISR returns.

chrisl
  • 16,257
  • 2
  • 17
  • 27
  • So basically I2C receiveEvent is just normal ISR?? I didnt know that. – Nicky Feb 23 '18 at 18:31
  • @Nicky - It is not strictly speaking a normal ISR. For one thing, it takes an argument. However it is called from code in the library function which is called by the TWI_vect (I2C interrupt vector). Therefore the time that the onReceive is called is "any time" (that interrupts are enabled). – Nick Gammon Feb 23 '18 at 19:47