蟒蛇和串行.如何发送消息和接收答复 [英] python and serial. how to send a message and receive an answer

查看:67
本文介绍了蟒蛇和串行.如何发送消息和接收答复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须通过与 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\nvia 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆