I've got a small embedded device (Beaglebone Black) with a I2C device hooked up on /dev/i2c-2
.
Now i'm trying to communicate with that device from C#/Mono, how is this possible? I've looked at some C++ code, but im not very strong in that language, but it looks like its possible just to open it as a file and write to it? Though im not sure how this code would translate to C#.
//C++ sample of i2c communication...
int BMA180Accelerometer::writeI2CDeviceByte(char address, char value){
cout << "Starting BMA180 I2C sensor state write" << endl;
char namebuf[MAX_BUS];
snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", I2CBus);
int file;
if ((file = open(namebuf, O_RDWR)) < 0){
cout << "Failed to open BMA180 Sensor on " << namebuf << " I2C Bus" << endl;
return(1);
}
if (ioctl(file, I2C_SLAVE, I2CAddress) < 0){
cout << "I2C_SLAVE address " << I2CAddress << " failed..." << endl;
return(2);
}
char buffer[2];
buffer[0] = address;
buffer[1] = value;
if ( write(file, buffer, 2) != 2) {
cout << "Failure to write values to I2C Device address." << endl;
return(3);
}
close(file);
cout << "Finished BMA180 I2C sensor state write" << endl;
return 0;
}
I'm not sure if this is too late, but I have done this on a BBB using mono. You need to look at DLLImport attributes. Basically, you need to write a small C++ file and compile it that contains a custom method that just invokes ioctl() called invoke_ioctl(...) then place the compiled DLL into the /bin directory on your BBB and add this to your C# project code.
[DllImport("pinvoke.dll")]
[SuppressUnmanagedCodeSecurityAttribute()] //Optional, for speed
private static extern int invoke_ioctl(int file_handle, int address);
public static FileStream getI2CStream(byte address)
{
FileStream result = File.Open("/dev/i2c-2", FileMode.Open);
invoke_ioctl(result.SafeFileHandle.DangerousGetHandle().ToInt32(), address);
return result;
}
This will setup ioctl() for the I2C line when writing to that specific I2C address. Just open files for each device on the I2C line. There is probably a C# way to do this too more safely/effectively.