c# - 在 Windows 10 IOT 上使用 I2C 从传感器读取问题
问题描述
我正在使用 Windows 10 IoT 17763.253 的最新公开版本,但从 i2c Co2 传感器读取时出现问题。
奇怪的是,对于其他传感器来说,这似乎不是问题。
每隔一段时间,它就会破坏最后两个 utf8 字符,例如 1126 显示为 11\u0011/2,其中最后 1/2 是单个 UTF8 字符。很多时候,钻石问号替换字符也出现在那里。
关于如何解决它的任何想法?我正在使用最新版本的 vs2019、Raspberry Pi 3 和 Windows 17763.253
代码:
using System;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Devices.I2c;
public string GetReading()
{
try
{
byte[] i2CReadBuffer = new byte[20];
_device.Read(i2CReadBuffer);
Task.Delay(300).Wait(); //MXu
string answer_string = "";
bool got_error = false;
int bufsize = i2CReadBuffer.Length;
for(int i =0;i<bufsize;i++)
{
Debug.WriteLine(i2CReadBuffer[i].ToString("X"));
}
Debug.WriteLine("");
switch (i2CReadBuffer[0]) //first character denotes I2C reception status
{
case 1:
i2CReadBuffer[0] = 0;
answer_string = Encoding.UTF8.GetString(i2CReadBuffer).Replace("\0", string.Empty);
// does it match ?L,1 .... if so , makegot_error to true, even though it isn't an error.
Regex regex = new Regex(@"\\?L,[0-9]*,?T?");
Match match = regex.Match(answer_string);
if (match.Success)
{
got_error = true;
}
break;
case 2:
case 254:
case 255:
default:
got_error = true;
break;
}
我们的传感器: https ://www.atlas-scientific.com/_files/_datasheets/_probe/EZO_CO2_Datasheet.pdf
解决方案
从数据表中,编码是 ASCII,但不是您的代码中使用的 UTF8。另外,你是不是在发送命令后延迟了300ms?您可以通过以十六进制打印所有响应数据来解决此问题。
在“响应代码和处理延迟”页面中,示例显示了从设备请求数据的工作流程。请注意。
如果没有处理延迟或处理延迟太短,则响应代码将始终为 254。
我认为您可以尝试在 Read 方法之前移动延迟。
public string GetReading()
{
try
{
Task.Delay(300).Wait(); //MXu
byte[] i2CReadBuffer = new byte[20];
_device.Read(i2CReadBuffer);
string answer_string = "";
bool got_error = false;
int bufsize = i2CReadBuffer.Length;
for(int i =0;i<bufsize;i++)
{
Debug.WriteLine(i2CReadBuffer[i].ToString("X"));
}
Debug.WriteLine("");
switch (i2CReadBuffer[0]) //first character denotes I2C reception status
{
case 1:
i2CReadBuffer[0] = 0;
answer_string = Encoding.UTF8.GetString(i2CReadBuffer).Replace("\0", string.Empty);
// does it match ?L,1 .... if so , makegot_error to true, even though it isn't an error.
Regex regex = new Regex(@"\\?L,[0-9]*,?T?");
Match match = regex.Match(answer_string);
if (match.Success)
{
got_error = true;
}
break;
case 2:
case 254:
case 255:
default:
got_error = true;
break;
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}