不能使用pyserial串行写入arduino



我试图使用pyserial包发送1或0到arduino。我将arduino物理地插入USB端口(COM6),并使其运行以下代码块,以根据输入打开或关闭灯。

#define LED_PIN 12
void setup()
{
// Set up serial communication at 9600 baud
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
}
void loop()
{
if (Serial.available() > 0) {
char cmd = Serial.read();
if (cmd == '1') {
digitalWrite(LED_PIN, HIGH);
Serial.println("LED turned on!");
}
else if (cmd == '0') {
digitalWrite(LED_PIN, LOW);
Serial.println("LED turned off!");
}
}
}

然而,我的python代码ser = serial.Serial("COM6", 9600)中的行正在产生错误消息:serial.serialutil.SerialException: could not open port 'COM6': PermissionError(13, 'Access is denied.', None, 5)。我试过确保所有可以访问串行端口的程序都关闭(包括arduino IDE),并更新和重新启动我的PC。奇怪的是,这两段代码在朋友的计算机上运行良好,并且arduino能够接受串行命令。有没有人有进一步的问题解决建议?

下面是所有的python代码,如果它是有用的,我们正在尝试使用flask建立一个UI。提前感谢任何有耐心帮助这个初学者的人:)

import numpy
from flask import Flask, render_template, session, redirect
from functools import wraps
import pymongo
import serial

app = Flask(__name__)
#set up secret.key
app.secret_key = ...
#Database
client = pymongo.MongoClient(...)
db = client.user_login_system
# Decorators, decide whether or not to allow user go to specific pages
def login_required(f):
@wraps(f)
def wrap(*arg, **kwargs):
#checks if user is logged in
if 'logged_in' in session:
#if yes, it renders the dashboard templates
return f(*arg, **kwargs)
else:
#if not, it redirects to the home pahe
return redirect('/')

return wrap
#We need to import our routes as well in this file
from user import routes
#create route
@app.route('/')
def home():
return render_template('home.html')
#best rout to assure that assure lands on that page
@app.route('/dashboard/')
#checks if user is logged in before even allowing access to dashboard
@login_required
def dashbaord():
# Render the dashboard template with the current LED status
return render_template("dashboard.html", status='OFF')
#create file to automatically execute flask
#set up two templates one for Home page and another for dashboard page
#arduino stuff (V1)
ser = serial.Serial("COM6", 9600)
# Define route for turning LED on
@app.route('/turn_on/')
def turn_on():
ser.write(b'1')  # Send "1" to Arduino to turn on LED
#return 'LED turned on!'
return render_template("dashboard.html", status="LED is oN")
# Define route for turning LED off
@app.route('/turn_off/')
def turn_off():
ser.write(b'0')  # Send "0" to Arduino to turn off LED
#return 'LED turned off!'
return render_template("dashboard.html", status="LED is off")

你有没有尝试给它正确的权限?尝试以管理员身份运行此代码。

检查端口名称是否正确

from serial import Serial
import serial.tools.list_ports as ports
def test():
print('List Of Available Serial Ports')
for p in (ports.comports(False)):
print (p)
print('_'*40)
s = Serial('COM6')
print(s.name, s.baudrate, end='')
if s.is_open :
print(' open')
else :
print(' closed')