使用Powershell维护Python中打开的串行端口

2024-10-04 01:30:14 发布

您现在位置: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()

Tags: ioosportopenexesystemsubprocessimu
1条回答
网友
1楼 · 发布于 2024-10-04 01:30:14

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

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

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

您还可以更改超时,也可以更改停止位的数量

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

相关问题 更多 >