I am building a live humidity graph with the possibility to light ON/OFF a LED from the flask application. I am having trouble in creating the serial variable in the app.py file, which looks like below:
import serial
import json
from time import time
from flask import render_template, make_response, Flask
# ser = serial.Serial("COM6", 9600)
app = Flask(__name__)
app.config["SECRET_KEY"] = "mysecretkey"
@app.route('/', methods=['GET', 'POST'])
def index():
# ser = serial.Serial("COM6", 9600)
#
# if request.method == 'POST':
# if request.form.get('action1') == 'ON':
# print('light ON')
# ser.write(b'H')
# print('turning led ON')
# pass # do something
# elif request.form.get('action2') == 'OFF':
# print('light OFF')
# # time.sleep(4)
# ser.write(b'L')
# print('turning led OFF')
# pass # do something else
# else:
# pass # unknown
return render_template('Main.html')
@app.route('/humidity', methods=['GET'])
def humidity():
# Create a PHP array and echo it as JSON
ser = serial.Serial("COM6", 9600)
while True:
temp = ser.read(5).decode('utf-8')
print('temperature ', float(temp))
print('random temperature type ', type(temp))
data = [time() * 1000, float(temp)]
print('temperature ', data)
response = make_response(json.dumps(data))
response.content_type = 'application/json'
return response
if __name__ == '__main__':
app.run(debug=True)
I would like to create the ser variable before the app creation of variable, but this triggers the error: ```serial.serialutil.SerialException: could not open port 'COM6': PermissionError(13, 'Access is denied.', None, 5). How could I solve this issue and be able to see the humidity data, as well as control the LED?