首页 > 解决方案 > Python 串行通信脚本问题(在 Visual Studio 中)

问题描述

我目前正在尝试在 Windows PC 上使用 Python 通过串行/USB 连接在 Arduino UNO 和 PC 之间建立通信。

目标是在 Arduino 要求时在笔记本电脑上启动视频。

我在网上找到了一个指南,它引导我找到下面的代码,但 Visual Studio 2017 似乎到处都是随机显示错误。其中很多似乎来自导入和 VS 的 IntelliSense 混乱(我相信现在已经修复)。

所以目前当我运行程序时,它卡在ser = serial.Serial(port, 9600, timerout=0)行,错误为“未定义名称‘端口’”知道为什么会这样吗?

我不确定这是否是核心问题,因为每次我进行更改时,都会为portnewlineprintser出现很多“意外令牌”和“缩进”错误(完全随机)

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)

标签: pythonpython-3.xarduinoserial-portpyserial

解决方案


似乎您没有找到任何 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)

推荐阅读