python - Python 串行通信脚本问题(在 Visual Studio 中)
问题描述
我目前正在尝试在 Windows PC 上使用 Python 通过串行/USB 连接在 Arduino UNO 和 PC 之间建立通信。
目标是在 Arduino 要求时在笔记本电脑上启动视频。
我在网上找到了一个指南,它引导我找到下面的代码,但 Visual Studio 2017 似乎到处都是随机显示错误。其中很多似乎来自导入和 VS 的 IntelliSense 混乱(我相信现在已经修复)。
所以目前当我运行程序时,它卡在ser = serial.Serial(port, 9600, timerout=0)行,错误为“未定义名称‘端口’”知道为什么会这样吗?
我不确定这是否是核心问题,因为每次我进行更改时,都会为port、newline、print和ser出现很多“意外令牌”和“缩进”错误(完全随机)
import serial, os, time, serial.tools.list_ports
cmd = '"C:\\Users\\Josef\\Desktop\\PYTHON_PlayVideo\\PYTHON_PlayVideo\\Video1.mp4" -f --fullscreen --play-and-exit'
for p in serial.tools.list_ports.comports():
sp = str(p)
#if (sp.find('COM5') != -1):
if (sp.find('Arduino') != -1):
flds = sp.split()
port = flds[0]
print(port)
ser = serial.Serial(port, 9600, timeout=0)
while 1:
try:
line = ser.readline()
if (line):
print (cmd)
os.system(cmd)
except:
pass
time.sleep(1)
解决方案
似乎您没有找到任何 COM 端口,因此port
从未定义。我修改了你的代码,这个版本对我有用(USB
用你的关键字替换)。
import serial, os, time, serial.tools.list_ports
# Get the COM port
Ports = serial.tools.list_ports.comports()
if(len(Ports) == 0):
print("[ERROR] No COM ports found!")
exit()
TargetPort = None
for Port in Ports:
StringPort = str(Port)
print("[INFO] Port: {}".format(StringPort))
if("USB" in StringPort):
TargetPort = StringPort.split(" ")[0]
print("[INFO] Use {}...".format(TargetPort))
if(TargetPort is None):
print("[ERROR] No target COM port found!")
exit()
# Open the COM port
ser = serial.Serial(TargetPort, 9600, timeout = 0)
if(ser.isOpen() == False):
ser.open()
while(True):
try:
line = ser.readline()
if (line):
print (cmd)
#os.system(cmd)
except:
pass
time.sleep(1)
推荐阅读
- vb.net - vb.net 能否支持 Chromium 引擎?
- imgur - Imgur 访问令牌过期时间这么长(315360000 秒还是毫秒?)
- nginx - nginx:服务器没有处理程序
- vuejs2 - 如何使用代理处理 vue cli 开发服务器中的重定向?
- c# - C#、WinForms 和应用程序图标
- javascript - 错误的 x 轴最小值最大值 Highcharts
- python - 如何使用 matplotlib 中的 mpatches.Patch 将自定义标签添加到条形图中
- google-apps-script - 如何在谷歌应用程序脚本上更改日志消息的语言
- ios - Apple Enterprise 计划,用于为我的客户分发组织的员工应用程序
- json - 使用 curl 时出现 Github API 错误“解析 JSON 的问题”,但与 Postman 一起工作正常