Python serial库出现Access denied错误,请求技术协助
串口Access Denied错误排查(Python+MicroPython项目)
我是单片机编程新手,遇到了Access denied错误,已经检查过端口、波特率、驱动,但问题仍未解决,毫无头绪。
Python代码
import speech_recognition as sr import pyttsx3 import pyaudio import webbrowser import os import subprocess import serial silnik = pyttsx3.init() silnik.setProperty("glosnosc", 0.70) silnik.setProperty("szybkosc", 120) voices = silnik.getProperty('voices') silnik.setProperty('voice', voices[0].id) przegladarka_path = "C:/Users/x/AppData/Local/Programs/Opera GX/launcher.exe %s" num = 5 ser = serial.Serial("COM3", 115200) ser.open() def recognise(msg="Powiedz coś!"): r = sr.Recognizer() with sr.Microphone() as source: print(msg) audio = r.listen(source) try: recognised_text = r.recognize_google(audio, language="pl-PL") print("Powiedziałeś: " + recognised_text) return recognised_text.lower() except sr.UnknownValueError: print("Nie rozumiem co mowisz") except sr.RequestError as e: print("ERROR", e) text = recognise() word_list = text.split(" ") if ("otwórz" in text and word_list[0] == "otwórz") or ("uruchom" in text and word_list[0] == "uruchom"): if "przeglądarkę" in text: silnik.say("Otwieram przeglądarke!") silnik.runAndWait() webbrowser.get(przegladarka_path).open_new_tab("http://www.google.com") if "youtube" in text: silnik.say("Otwieram YouTube!") silnik.runAndWait() webbrowser.get(przegladarka_path).open_new_tab("https://www.youtube.com") if "diskord" or "discord" in text: silnik.say("Otwieram discorda!") silnik.runAndWait() os.startfile("C:/Users/x/AppData/Local/Discord/app-1.0.9013/Discord.exe") if "wyłącz" in text and word_list[0] == "wyłącz": if "komputer" in text: silnik.say(f"Wyłączam komputer za {num} sekund") os.system(f"shutdown /s /t {num}") if "led" in text: ser.write(encode("OFF")) if "włącz" in text and word_list[0] == "włącz": if "led" in text: ser.write(encode("ON"))
MicroPython代码
import machine import time led_pin = machine.Pin(16, machine.Pin.OUT) uart = machine.UART(0, 115200) while True: if uart.any(): command = uart.read().decode().strip() print("Otrzymane polecenie: " + command) if command == "ON": led_pin.on() elif command == "OFF": led_pin.off() time.sleep(0.1)
可能的解决方法
- 以管理员身份运行脚本:Windows系统下,COM端口访问需要系统权限,右键点击Python脚本或终端,选择「以管理员身份运行」。
- 检查端口占用:打开设备管理器→端口(COM和LPT),确认COM3未被其他程序(比如串口调试工具、Arduino IDE)占用,关闭占用程序后重试。
- 修正serial库用法:
serial.Serial()实例化时已经自动打开串口,无需再调用ser.open(),删除这一行避免重复打开引发错误。 - 修复编码函数错误:代码中
encode("ON")是未定义的函数,应改为"ON".encode('utf-8'),否则会抛出NameError,影响串口操作。 - 确保串口正确释放:添加
try...finally块保证脚本结束后关闭串口,避免端口被锁定:ser = serial.Serial("COM3", 115200) try: text = recognise() # 后续所有逻辑代码放在这里 finally: ser.close() - 检查硬件连接:确认USB线是带数据传输功能的(不是纯充电线),尝试更换USB端口或重新插拔单片机。
内容的提问来源于stack exchange,提问作者ROM3K
相关产品推荐
相关产品推荐

