Flask,Arduino和PySerial出现问题

时间:2019-05-03 01:52:07

标签: python flask arduino pyserial

我在 Windows 上,并且试图将 Arduino Flask 连接。

我可以使用 PySerial Arduino 建立连接,但是当我在 Flask 中使用连接时,它将无法正常工作。相反,我得到以下错误:

raise SerialException("could not open port {!r}: {!r}".format(self.portstr,
ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM5': PermissionError(1
3, 'Denied Access.', None, 5)

我已经尝试过:

  • 更改端口
  • 以管理员身份运行控制台

这是我的代码:

from flask import Flask, render_template, request
import time
import serial

app = Flask(__name__)

@app.route("/show/all", methods=["GET", "POST"])
def showAll():
    if request.method == "POST":
        sess = serial.Serial("COM5", 9600)
        dt = sess.readline().decode("utf-8")
        return dt

    else:
        return render_template("show.html") 

app.run()

我正在执行AJAX请求以触发与Arduino的连接:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="{{ url_for('static', filename = 'css/styles.css') }}">
    <script src="{{url_for("static", filename="js/script.js")}}"></script>
    <title>Document</title>
</head>
<body>
    <h1 class="titulo">Datos:</h1>

    <script>
    function make_request(){
        var ajax_request = new XMLHttpRequest();

        ajax_request.addEventListener("readystatechange", function(){
            if(ajax_request.status == 200 && ajax_request.readyState == 4){
                var nw_obj = document.createElement("p");
                nw_obj.classList.add("info");
                nw_obj.innerHTML = ajax_request.responseText;
                document.body.appendChild(nw_obj);
            }
        });

        ajax_request.open("POST", "/show/all", true);
        ajax_request.send();
    }

    window.addEventListener("load", {
        setInterval(make_request, 1000);
    });
    </script>

</body>
</html>

Arduino代码:

int contador = 0;

void setup() {
    Serial.begin(9600);
}

void loop() {
    contador++;
    Serial.println(contador);
    delay(1000);
}

0 个答案:

没有答案