Skip to content

Instantly share code, notes, and snippets.

@syu5-gh
Created June 7, 2015 06:58
Show Gist options
  • Save syu5-gh/f03d242e639809dd67b3 to your computer and use it in GitHub Desktop.
Save syu5-gh/f03d242e639809dd67b3 to your computer and use it in GitHub Desktop.
I2C Read/Write Transaction for NETMF
int writeTransaction(byte[] data)
{
int tryCount = 0;
int writtenSize = 0;
while (writtenSize < data.Length && tryCount < MAX_TRY)
{
var dataForWrite = new byte[data.Length - writtenSize];
Array.Copy(data, writtenSize, dataForWrite, 0, data.Length - writtenSize);
var i2ctx = new I2CDevice.I2CTransaction[] {
I2CDevice.CreateWriteTransaction(dataForWrite),
};
// https://msdn.microsoft.com/en-us/library/hh400235.aspx
var writeResult = Device.Execute(i2ctx, TIMEOUT);
writtenSize += writeResult;
tryCount++;
}
return writtenSize;
}
int readTransaction(int requestSize, out byte[] resultData)
{
int tryCount = 0;
int readSize = 0;
var arrayBuffer = new ArrayList();
while (readSize < requestSize && tryCount < MAX_TRY)
{
var dataForRead = new byte[requestSize - readSize];
var i2ctx = new I2CDevice.I2CTransaction[] {
I2CDevice.CreateReadTransaction(dataForRead),
};
// https://msdn.microsoft.com/en-us/library/hh400235.aspx
var readResult = Device.Execute(i2ctx, TIMEOUT);
for (int idx = 0; idx < readResult; idx++)
{
arrayBuffer.Add(dataForRead[idx]);
}
readSize += readResult;
tryCount++;
}
resultData = (byte[])arrayBuffer.ToArray(typeof(byte));
return readSize;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment