python - 从串口发送数据

标签 python serial-port raspberry-pi2 zigbee

我想通过串行端口发送一个字符串:

我有两个树莓派2。每个都有一个xbee模块。我想将数据从一个发送到另一个。它们已正确连接。

为了测试发送数据,我有这个小 python 脚本:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=.5)
cpt = 0

while True:
    ser.write('{}'.format(cpt))
    ser.write(' Hello world ! \r\n')
    cpt = cpt + 1

我的另一个与 minicom 连接的树莓派收到这些数据

 world !
8  Hello world !
9  Hello world !
10  Hello world !
11  Hello world !
12  Hello world !
13  Hello world !
14  Hello world !
15  Hello world !
...

输出很奇怪,有时从 10 开始,有时从 5 开始。在这个输出中,我有一个单词“world”,它是单独的......

但我只想使用此代码发送一个字符串:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=.5)

ser.write('Hello world ! \r\n')

现在我什么也没收到......我不知道为什么。

大家都知道我的问题吗?

最佳答案

打开串行端口后,在开始向其发送数据之前添加延迟。 XBee 模块可能在打开串行端口之前没有启动,并且需要一些时间来启动并重新建立与其他模块的链接。

在 9600 波特(大约 960 cps)下,如果丢失 190 个字符(10 个序列 0 到 9,每 19 个字符包括空格和 CRLF),您需要大约 190/960 = 0.2 秒的延迟。如果您不着急,请将其提高到 0.5 秒,看看是否可以解决问题。

关于python - 从串口发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35428517/

相关文章:

python - 控制台窗口失去焦点时如何检测按键

python - Networkx 旅行商问题 (TSP)

windows - 监控 rs232 流量

c# - 将许多变量从 Unity 发送到 Arduino

python - 按钮 GPIO.FALLING 事件被触发两次

python - 将 Pandas 列中的字符串转换为 int

linux - 如何在嵌入式linux中查找哪个串口设备用于终端输出

linux - 在树莓派2中,如何配置PWM1 channel ?

Raspberry Pi 上使用 JOGL 的 LibGDX - 运行时出错

python - 将 Python 模块安装为模块和脚本