使用Python

时间:2016-06-06 13:56:23

标签: python pyserial

我想使用PySerial将数据发送到外设。但是, sometime 中的错误会出现在收到的数据中。

import serial

dongle = serial.Serial("/dev/ttyUSB0", 9600)

dongle.write("Some data\n")

然后,Some data\n被传输到外围设备。

有时它效果很好,但有时会在收到的数据中出现错误:Somata\nSom a\n等......

如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我怀疑你需要在串行写入中添加一个字符串间延迟。不幸的是,PySerial中没有这样的东西。有inter_byte_timeout,但这是读取。

类似的东西:

import serial
import time

def write_with_delay(command):
    while len(command)>0: # Loop till all of string has been sent
        char_to_tx = command[0] # Get a
        dongle.write(char_to_tx)
        command = command[1:] # Remove sent character                                
        time.sleep(0.01)

dongle = serial.Serial("/dev/ttyUSB0", 9600)
write_with_delay('Some data\n')

将在每个字符之间发送一个10ms(0.01s)延迟的字符串。通常,在代码中添加任意延迟是件坏事,但对于串行通信,它有时是必要的。