蟒蛇和串行.如何发送消息和接收答复 [英] python and serial. how to send a message and receive an answer
问题描述
我必须通过与 python 的串行通信发送 ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n
.
这是我的代码:
导入串口ser = serial.Serial('/dev/cu.usbserial-A901HOQC')ser.baudrate = 57600msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
如果我写:
<预><代码>>>>ser.write(msg)答案将是 33
,这是我发送的消息的字节长度.
我怎样才能得到答案?连接的设备会在收到消息后立即应答,但如果我输入
<预><代码>>>>ser.write(msg);ser.readline()结果将是 readline
根本没有收到任何消息...
有什么想法吗?
我相信之前的答案没有理解您使用相同的端口进行读写.
我遇到了同样的问题并使用睡眠功能解决了它.基本上:
导入串口从时间导入睡眠ser = serial.Serial('/dev/cu.usbserial-A901HOQC', timeout=1)ser.baudrate = 57600msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'ser.write(msg)睡眠(0.5)ser.readline()
因此,通过睡眠,您可以给接收者(一台机器?)发送回复的时间.另请注意,如果要使用 readline,则必须添加超时.
I have to send ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n
via serial communication with python.
here is my code:
import serial
ser = serial.Serial('/dev/cu.usbserial-A901HOQC')
ser.baudrate = 57600
msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
If I write:
>>> ser.write(msg)
the answer will be 33
, which is the length in byte of the message I'm sending.
How can I receive the answer? The connected device will answer just after he gets the message, but if I type
>>> ser.write(msg); ser.readline()
the result will be that readline
never gets any message at all...
any ideas?
I believe the earlier answers didn't understand that you are using the same port for writing and reading.
I'm having the same problem and solved it using a sleep function. Basically:
import serial
from time import sleep
ser = serial.Serial('/dev/cu.usbserial-A901HOQC', timeout=1)
ser.baudrate = 57600
msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
ser.write(msg)
sleep(0.5)
ser.readline()
So with that sleep you are giving time to the receiver (a machine?) to send the reply. Also note that you have to add a timeout if you want to use readline.
这篇关于蟒蛇和串行.如何发送消息和接收答复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!