0

我正在尝试使用 C# 从串行端口读取数据。

整数或浮点数和布尔值的普通字节不是问题。但是,有一个 3 个字节的序列被打乱了,我无法正确解析它。

这 3 个字节代表 2 个无符号 12 位整数,一个用于 MainSupplyDC,一个用于 Motor Power。它们以需要在解析之前重新排序的方式进行混洗。

我的最后一次尝试以这样的方式结束,但现在我再次意识到这不可能是正确的。

    // 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 将有正确的答案。

4

2 回答 2

1

我猜这两个 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

这看起来对吗?

于 2019-02-21T16:22:23.573 回答
0

如果我正确阅读了表格,以下方法应该可以解决问题:

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;
于 2019-02-21T16:26:08.320 回答