Wire (I2C)

lock()

The Wire object does not have built-in thread-safety. If you want to use read or write from multiple threads, including from a software timer, you must lock and unlock it to prevent data from multiple thread from being interleaved or corrupted.

A call to lock lock() must be balanced with a call to unlock() and not be nested. To make sure every lock is released, it's good practice to use WITH_LOCK like this:

// EXAMPLE USAGE
void loop()
{
  WITH_LOCK(Wire) {
    Wire.requestFrom(2, 6);    // request 6 bytes from slave device #2

    while(Wire.available()){   // slave may send less than requested
      char c = Wire.read();    // receive a byte as character
      Serial.print(c);         // print the character
    }
  }
}

Never use lock() or WITH_LOCK() within a SINGLE_THREADED_BLOCK() as deadlock can occur.