首页 > 解决方案 > 使用 Powershell 维护在 Python 中打开的串口

问题描述

我正在尝试通过 RS 232 将 Novatel Propak6 接收器连接到地面站。(对于 GPS 拒绝环境)

我能够连接接收器以通过 powershell 接收命令,但我想使用 python 将其与其他独立运行的传感器集成。

我使用 pyserial 编写了以下 python 代码,但与 powershell 不同,它不接受命令:

import serial

s = serial.Serial(port="COM1", baudrate=115200)

if (s.isOpen()):
    s.write(b'CONNECTIMU COM3 IMU_ADIS16488')
    s.close()

命令 CONNECTIMU 应该激活 IMU 和接收器之间的连接,但与 powershell 不同,这没有响应。

因此,我尝试使用 subprocess 和 os.system 通过 python 执行 powershell,但它们都返回此错误:

You cannot call a method on a null-valued expression.
At line:1 char:1
+ $port.open()
+ ~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

这些是我用来通过 python 运行 powershell 的代码:

os.system('powershell.exe [System.IO.Ports.SerialPort]::getportnames()')
time.sleep(1)
os.system('powershell.exe "$port= new-Object System.IO.Ports.SerialPort COM1, 115200, None, 8, one"')
time.sleep(1)
os.system('powershell.exe $port.open()')
os.system('powershell.exe $port.WriteLine("CONNECTIMU COM3 IMU_ADIS16488")')
time.sleep(1)
init_port=subprocess.Popen(["powershell.exe", "$port= new-Object System.IO.Ports.SerialPort COM1, 115200, None, 8, one"])
port_open = subprocess.Popen(["powershell.exe", "$port.open()"])
imu_connect = subprocess.Popen(["powershell.exe", "$port.WriteLine('CONNECTIMU COM3 IMU_ADIS16488)"])
init_port.communicate()
port_open.communicate()
imu_connect.communicate()

标签: pythonpowershell

解决方案


尝试在命令末尾添加换行符:

s.write(b'CONNECTIMU COM3 IMU_ADIS16488\n')

或者

cmd = 'CONNECTIMU COM3 IMU_ADIS16488\n'
s.write(cmd.encode("ascii"))

You can also change the timeout and maybe the number of stop bits.

s = serial.Serial(port="COM1", 
                  baudrate=115200, 
                  timeout=1,
                  stopbits=serial.STOPBITS_ONE)

推荐阅读