python - 使用 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()
解决方案
尝试在命令末尾添加换行符:
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)
推荐阅读
- python - 如何使用 tkinter .after() 方法来创建延迟
- c# - 如何在一个子句中写“group by”+“sum”?
- c# - 按字符串动态排序
- javascript - 如何从嵌套在对象中的数组中选择随机项
- python - 将长列表/数组放入以索引为键的字典中
- python - 在 vizdoom 中找不到 basic.cfg 文件,而 doom 实现
- c - 在替换文本之前使用 # 时不正确地终止宏调用
- javascript - 在打字稿中编写此开关/案例的更好方法?
- javascript - (React js)如何在分组条形图中获取点击的条形名称
- linux - 无法拉取 .vim/ 目录