我正在编写一个python脚本,通过868 MHz无线电模块向电子扭矩扳手写入和读取数据。无线电模块通过USB端口连接,通信通过COM端口运行。操作系统是Windows10
原则上,通信非常简单,通过COM端口发送字符串,然后以相同的方式返回字符串。模块上有一个LED灯,在发送数据时会闪烁。 我在Linux下用putty和Windows下的powershell测试了通过COM端口的通信,输入参数非常低(port=COM3,bitrate=115200),可以正常工作。我可以发送一个小字符串,并从扭矩扳手获得预期的答案。LED也会闪烁
Powershell:
$port= new-Object System.IO.Ports.SerialPort COM3,115200,None,8,one
$port.open()
$port.WriteLine("819090520BAT")
$answer=$port.ReadLine()
$port.Close()
echo $answer
一个小型python脚本可以使用serial.tools.list_ports模块在COM3端口上找到硬件
import serial.tools.list_ports
import serial
vid=8263
pid=1007
serial_timeout = 0.01
serial_baudrate = 115200
ports = list(serial.tools.list_ports.comports())
for p in ports:
if(vid == p.vid and pid == p.pid):
com_port = Serial(port=p.device, baudrate=serial_baudrate)
print("com_port:",com_port)
sended = s.write(b"819090520BAT")
print("sended:",sended)
res = s.readline()
print(res.decode("ASCII"))
当我建立到找到的COM3端口的连接时,返回的连接信息看起来是可信的。写入函数的返回值为12,因此信息被发送到无线电模块。 但是LED不闪烁,模块没有应答(变量res为空)
我尝试了字符串的不同编码(ASCII,UTF-8),但没有区别
sended = s.write("819090520BAT".encode("ASCII"))
sended = s.write("819090520BAT".encode("UTF-8"))
此外,重置缓冲区不会显示其他结果
com_port.reset_input_buffer()
com_port.reset_output_buffer()
com_port.flushInput()
com_port.flushOutput()
最后我尝试了改变通讯参数,但也没有其他模块的反应
xonxoff=True
rtscts=真
dsrdtr=True
这并不奇怪,因为这些参数在putty和powershell下都被禁用了
我的错在哪里?为什么putty和powershell可以连接而不是pyserial
谢谢你的帮助!这是有效的代码:
相关问题 更多 >
编程相关推荐