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?

  • 2
    Let's not imagine stuff. Let's post an example piece of code. – Nick Gammon Feb 22 '18 at 6:57
  • Interrupts happen (almost) immediately if that answers your question. – Nick Gammon Feb 22 '18 at 6:59
  • if i have loop of 10 lines, and when loop is on line 4, at that time there is i2c request, will arduino switch to i2c request process it and then countiniue to line 5 of loop or it will finish loop first then go to i2c request? – Nicky Feb 22 '18 at 15:21
  • You are basically asking how interrupts work so see my question and answer about interrupts. – Nick Gammon Feb 22 '18 at 20:05
  • Thanks Nick, now when i know that receiveEvent is just a classic ISR now its all clear. – Nicky Feb 23 '18 at 18:38

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.

| improve this answer | |
  • 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

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