我正在尝试使用 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)并更新并重新启动我的电脑。奇怪的是,这两段代码在朋友的电脑上都能正常工作,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")
您是否尝试授予它正确的权限? 尝试以管理员身份运行此代码。