从串行端口的二进制数据构造一个十六进制数组

时间:2019-05-16 17:26:08

标签: python-3.x numpy pyserial

我有一个串行连接到PC的外部设备。 数据是二进制而不是字符,这意味着我不应该将数据解释为ASCII字符。

在PC中,我有Python 3.7,该软件使用pyserial读取串行设备。 我想用传入的数据填充一个int8数组。

我正在使用线程,到目前为止,这里是我在哪里,但这不是我的第一段代码,我尝试了几件事,但没有一事起作用。

def get_data(sent, m_serport)
    constr_resp = np.int8([0])
    resp = np.int8([0])
    resp_index = 0

        while (1):
            if (m_serport.in_waiting > 0):
                resp = master_ser.read(1)
                constr_resp = np.concatenate(constr_resp, resp)
                resp_index = resp_index + 1
                parse(constr_resp, resp_index)

这会产生以下错误: TypeError:“字节”对象不能解释为整数

我有一定的C语言背景,而Python在数据类型方面令我非常困惑。

我希望我的问题很容易理解。

谢谢。

2 个答案:

答案 0 :(得分:0)

Kostbil,使用python访问外部数据可能有些棘手,但请相信我,这没什么大不了的。在这种情况下,如果您知道错误所在的行,则调试可能会更容易... 您还可以使用print()进行调试。

我认为,您可以在执行任何整数运算之前,对要从外部获取的数据调用解码方法,即.decode()。例如,externalData.decode()

希望这行得通。

答案 1 :(得分:0)

我认为获取数据应该从构建字节列表开始:

def get_data(sent, m_serport)
    alist = []
    resp_index = 0
        while (1):
            if (m_serport.in_waiting > 0):
                resp = master_ser.read(1)
                alist.append(resp)
                resp_index += resp_index
                # parse(alist, resp_index)
    return alist

您可能不需要resp_index,因为它应该只是len(alist)。另外,我认为您不希望在此循环中使用parse,但是我不知道它应该在做什么。