Wire.begin(MY_ADDRESS);and then for sending data, they use:
Wire.onReceive(receiveI2C);
Wire.beginTransmission(DEST_ADDRESS);So what's happening here?
Wire.write(0x30);
Wire.endTransmission();
- Basically, if you use Wire.begin(MY_ADDRESS) you are initializing the I2C bus in slave mode, and by registering the "onReceive" interrupt service handler, you define what needs to happen when the slave receives data.
- Next up, these examples all start sending data as a MASTER (despite being configured as a slave) by initializing the transmission, writing the data and then putting the data on the bus with the endTransmission() call.
This works on 8-bit AVR Arduino's (and a bunch of other devices) because of how the Wire library is implemented on these devices. Just have a look at the following files (from your Arduino IDE installation folder):
- hardware\arduino\avr\libraries\Wire\src\Wire.cpp
- hardware\arduino\avr\libraries\Wire\src\utility\twi.c
You can see endTransmission() calls the twi_WriteTo() function from twi.c (yes, Wire is merely a wrapper around some C implementation of I2C). What does twi_WriteTo() do? It attempts to become the master on the I2C bus and then sends data. That's actually a very good way of combining master & slave functionality on a single device on the I2C bus, and most definitely the way to go.
Now cue the Wire implementation on the 32-bit Atmel processors. These use the hardware SERCOM's of the SAMD21 processors, and directly use the corresponding I2C (well.. SERCOM) hardware registers to put the MCU in I2C master or slave mode... Unfortunately, there is no corresponding temporary promotion to a master going on in this implementation. Let's have a look at the SAMD21 implementation of Wire, which you can find in your %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\1.6.8\libraries\Wire folder:
- The endTransmission() implementation directly calls SERCOM->startTransmissionWIRE(), which is from the the %LOCALAPPDATA%\Arduino15\packages\arduino\hardware\samd\1.6.8\cores\arduino\SERCOM.cpp file.
- That startTransmissionWIRE() function first checks if the I2C bus is idle (multimaster collision protection) or whether it already owns the I2C bus using:
while ( !isBusIdleWIRE() && !isBusOwnerWIRE() );
This is one of the many differences between AVR & SAMD based Arduino's that you'll encounter when diving into the details. The solution is to do extend your code and do your own proper promotion towards I2C master when you need to send data, and depromote yourself to slave in case you don't need to send anything... basically mimicing the behaviour of the original twi.c that all started it.