Python 从串口解码数据并存储到列表中

-1 投票
1 回答
41 浏览
提问于 2025-04-14 18:12

我正在使用Python和pyserial与外部硬件进行通信。目前,我可以从硬件发送和接收数据。

我遇到的问题是,当我像下面这样读取数据时,我已经能够从值中读取并分离出通道。

一切都很好,直到我尝试将这些通道添加到一个列表中。

读取的数据:

response_line = self.main.serial_port.readline().decode('utf-8')
                if response_line and "calling" not in response_line :  
                    print(f"\t\t{response_line}")
                    self.add_channel(response_line)
                    if time.time() - start_time > 0.01 and not self.channel_detected:
                        self.channel_detected_number = len(self.channels_detected_list)
                        print(f"{self.channel_detected_number} channels detected")
                        break

添加通道的代码:

data_parts = response.split('=')
 
    if self.channels_detected_list.count(data_parts[0]) > 0:
        print("Channel already present.")
    else: 
        #add channels 
        self.channels_detected_list.append(data_parts[0])
        print(self.channels_detected_list)

当我打印这个列表时 -> 这些奇怪的值会输出

但是当我访问列表中的元素,比如第二个元素时,/x00这些值不会打印出来,只有通道的真实值会显示。

1 个回答

0

空值(\x00)是不会被打印出来的。如果你想看到原始的十六进制值,可以使用打印格式化工具,比如:

>>> a = '\x00'
>>> print(f'{a!r}')
'\x00'

撰写回答