简体   繁体   English

Python代码无法正确读取串行数据

[英]Python Code Isn't Reading Serial Data Properly

So I am writing a program to Read and Write data to and from a Serial Port. 因此,我正在编写一个程序,以从串行端口读取和写入数据。 Said port is setup where I know the specific byte codes it sends for the different states it is in. However, I am having an issue with my Python script that should be reading the Serial data and printing it to the screen. 所说的端口是在我知道它所处的不同状态时发送的特定字节码的地方设置的。但是,我的Python脚本遇到了问题,该脚本应该读取串行数据并将其打印到屏幕上。

Here is the setup for the Port, and my ReadLine method: 这是Port的设置以及我的ReadLine方法:

class SerialCommunicator:

    def __init__(self, *args, **kwargs):    
        self.port = serial.Serial("/dev/ttyUSB0")
        self.portSettings = {
            'baudrate' : 57600,
            'bytesize' : 8,
            'parity' : 'N',
            'stopbits' : 1,
            'timeout' : 0,
            'inter_byte_timeout' : None,
            'write_timeout' : None,
            'xonxoff' : False,
            'rtscts' : False,
            'dsrdtr' : False }
        self.port.apply_settings(self.portSettings)
        while True:
            output = self.ReadLine()
            if (output != ''):
                print(output)

    def ReadLine(self):
        readValue = ""
        isReading = True
        while isReading:
            currentRead = self.port.read()
            currentRead = currentRead.decode()
            readValue += currentRead
            if currentRead == '\r' or currentRead = '':
                isReading = False
                return readValue

So when I run this code, the output I am expecting aa garbled mess. 因此,当我运行此代码时,我期望输出混乱。 I am expecting two output strings from the serial port running on standby: 我期望在待机状态下运行的串行端口有两个输出字符串:

T12F8B0A2200F8

and

T1610FFA20

The second output is always coming out correctly. 第二个输出始终正确输出。 However the first one either has the head of the code cut off, or it's sliced in the middle, or it's tail is missing. 但是,第一个要么被剪切掉了代码的开头,要么被切成中间,或者它的尾部丢失了。 I need the code to be properly intact because I use the code in reading what state the device is in. What could be my problem? 我需要代码完整无缺,因为我使用代码读取设备处于什么状态。这可能是我的问题吗?

EDIT: For those curious, yes I have tried adjusting the baudrate. 编辑:对于那些好奇的人,是的,我尝试过调整波特率。 However with a baudrate higher than 57600 I get no output data at all. 但是,如果波特率高于57600,我将完全没有输出数据。

So it turns out my problem was with my timeout value. 因此,事实证明我的问题在于timeout值。 Setting 'timeout' : 1 fixed my problem :) 设置'timeout' : 1解决了我的问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM