我正在使用最新公开版本的 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?您可以通过以十六进制打印所有响应数据来解决此问题。
在“响应代码和处理延迟”页面中,示例显示了从设备请求数据的工作流程。请注意。
If there is no processing delay or the processing delay is too short, the response code will always be 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);
}
}
关于c# - 在 Windows 10 IOT 上使用 I2C 从传感器读取时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54487863/