我试图使用C#从串口读取数据。
正常字节到整数或浮点数和布尔值不是问题。但是,有一个3字节的序列被洗牌,我无法正确解析它。
这3个字节代表2个无符号12位整数,一个用于MainSupplyDC,一个用于电机功率。它们在解析之前需要重新排序。
我的最后一次尝试以类似的方式结束,但现在我再次意识到这不可能是正确的。
// Main Supply DC
int MainSupplyDCval = (byte2 >> 4 | byte1);
// MotorPower
int MotorPowerVal = (byte3 << 4 | byte2);
我不知道如何以正确的方式改变它。
这是字节序列布局:
文字相同:
Byte1 | Byte2 | Byte3
------------------------------------------------------
Lowbyte | 4 Lowbit | 4 Highbit | Highbyte
MainSupplyDC | MotorPower| MainSupplyDC | MotorPower
字节序列的示例:
E5-00-00
MainSupplyDC expected around 230
MotorPower expected 0
E4-A0-06
MainSupplyDC expected around 230
MotorPower expected about 97
E5-90-0F
MainSupplyDC expected around 230
MotorPower expected about 190
从现在开始的2天以来我一直在喋喋不休,只是无法让它发挥作用......
编辑
似乎有两种方法可以解释给定的表。在我的情况下@ canton7有正确的答案,但我认为如果供应商/制造商将编码另一种方式,@ dumetrulo将有正确的答案。
我猜这两个12位值有这个结构吗?
MainSupplyDC (low byte) | MainSupplyDC (4 Highbit)
MotorPower (4 lowbit) | MotorPower (Highbyte)
在这种情况下:
var bytes = new byte[] { 0xE4, 0xA0, 0x06 };
int mainSupplyDc = bytes[0] | ((bytes[1] & 0x0F) << 8);
int motorPower = (bytes[1] >> 4) | (bytes[2] << 4);
Console.WriteLine("MainSupplyDC: {0}, MotorPower: {1}", mainSupplyDc, motorPower);
打印:
MainSupplyDC: 228, MotorPower: 106
那看起来对吗?
如果我正确读取表格,以下方法应该可以解决问题:
public static (int, int)
Get12BitValues(byte d1, byte d2, byte d3) =>
((int)d1 | ((int)d2 >> 4),
((int)d3 << 4) | ((int)d2 & 0x0f));
那么你的两个值将获得如下:
var (v1, v2) = Get12BitValues(byte1, byte2, byte3);
float MainSupplyDCval = (float)v1 / 10.0f;
float MotorPowerVal = (float)v2 / 10.0f;