在Arduino和RPi IOT C#之间通过I2C发送JSON字符串



我正试图通过I2C将JSON字符串从Arduino Uno发送到运行Win-IOT Core的RaspPi。

连接工作正常,我在Arduino端注册了一个事件处理程序,当master(rpi)请求数据时,它被称为fine。

void I2CRequest()
{
Serial.println("I2C Request received");
/*Send data to WinIoT */
int bt = Wire.write(lastJSON.c_str());
Serial.println(lastJSON);
Serial.print("Send bytes: ");
Serial.println(bt);
}

串行监视器上的输出看起来也很好。。。

I2C Request received
{"Sensor":"OneWire","data":["28ffc8675216451",23.9375,"28ff9feb521645e",24.0625]}
Send bytes: 81

RPi上的C#方法如下:

public static async Task<byte[]> GetI2CTemperatures()
{
var ReceivedData = new byte[1024];
/* Arduino Nano's I2C SLAVE address */
int SlaveAddress = 64;              // 0x40
try
{
// Initialize I2C
var Settings = new I2cConnectionSettings(SlaveAddress);
Settings.BusSpeed = I2cBusSpeed.StandardMode;
if (AQS == null || DIS == null)
{
AQS = I2cDevice.GetDeviceSelector("I2C1");
DIS = await DeviceInformation.FindAllAsync(AQS);
}

using (I2cDevice Device = await I2cDevice.FromIdAsync(DIS[0].Id, Settings))
{
if (Device==null)
{
Debug.Write("No access to I2C Device");
}

/* Read from Arduino  */
Device.Read(ReceivedData);
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception occurred on reading I2C",ex);
// SUPPRESS ANY ERROR
}
/* Return received data or ZERO on error */
return ReceivedData;
}
}

不幸的是,无论我做什么,在ReceivedData中,我只得到了一个00作为第一个字节,后面跟着FFs。
我也尝试了Device.ReadPartial()而不是Device.Read(),结果相同。

有人能告诉我正确的方向吗?我做错了什么?

Arduino平台上的write()命令只写入一个字节。您正试图在一个命令中写入整个字符串。您需要在数组中循环,并分别发送每个字节。

但是,一旦执行此操作,就会遇到32字节缓冲区限制。可以将缓冲区增加到64字节,但这是Uno(Atmel 328)的限制。

我把一些代码放在一起,展示如何在Uno和Raspberry Pi之间建立关系,该关系可以传输不同大小的JSON字符串。代码在GitHub中https://github.com/porrey/i2c

如果你想了解更多使用I2C在Arduino和运行Windows IoT Core的Raspberry Pi之间进行通信的方法,请访问查看我的Hackster项目https://www.hackster.io/porrey

  • 连接树莓派和阿杜因诺
  • DHT小突破树莓派
  • 在Raspberry Pi上发现i2c设备

也许将这个字节数组转换为字符串会提供更多信息。

String myString = (char*)myByteArray

最新更新