Best practice for locking the I2C bus on Write and WriteRead operations?

Feb 14, 2015 at 8:30 PM
Edited Feb 15, 2015 at 12:15 PM
I have read the source code for several Gadgeteer drivers for I2C-based modules from various authors, and I notice that some drivers perform a C# lock on the bus object on all Write and WriteRead operations. Other I2C drivers don't ever lock.

I wondered why some drivers do this and others don't, so I read the Gadgeteer source files I2CBus.cs and NativeI2CBus.cs. It appears that Write and WriteRead operations ultimately become calls to Execute in NativeI2CBus, and that method performs a C# lock on the bus object.

Based on this information, it seems like locking the bus in the module driver is not necessary. Is this a correct conclusion, or am I missing something?

Feb 14, 2015 at 9:10 PM
Edited Feb 14, 2015 at 9:11 PM
The reason NativeI2CBus performs locking is to ensure that the native Execute method takes place with the correct configuration set, as you can have multiple devices with different configurations and you do not want the control to be handed over to a thread that will change the configuration you have just set before given chance to speak to the device.

Your conclusion is correct, drivers do not need to lock the I2C bus for hardware reasons. (It still might be desirable to atomize several transactions or other things you don't want to be interrupted.)

Marked as answer by kengr on 2/14/2015 at 2:51 PM
Feb 14, 2015 at 9:51 PM
Edited Feb 15, 2015 at 12:16 PM
Thanks for your informative confirmation.