Using I2C on the Raspberry Pi with C#

There are three breakouts that make up the sensors for Mr. Gibbs, the GPS, the Accelerator/Gyro, and the Compass. While the GPS connects using UART (serial port), the other two connect using i2c to the raspberry pi.

For my first pass at getting i2c working with Mr. Gibbs I found an existing implementation, but of course, after a while I decided to fork it and make some implementation changes to suit my style. The biggest changes are that the bus and device have been broken out into separate objects, the devices remember their own addresses for calls to read/write etc, and Dispose was added to ensure that the file descriptor gets cleaned up.

//open i2c bus 1, aka /dev/i2c-1
using (var i2cBus = new I2CBus(0x01))
  //create a device at address 0x3c
  var i2cDevice = new I2CDevice(i2cBus, 0x3c);
  var bytes = new byte[2];
  //read 2 bytes starting at register 0x00
  i2cDevice.ReadBytes(0x00, 2, bytes);
  //do someting useful with the bytes
}//note that disposing the bus closes the file

I should mention, there is another implementation of i2c in c# in raspberry sharp. It has many features which are raspberry pi specific (such as detecting which bus to use automatically based on the pi model) whereas my implementation is more generic for linux and will happily try to open a bus that doesn't even exist.

I will write some followup posts detailing the specifics of using i2c to interact with the MPU-6050 accelerometer and HMC5883L magnetometer.