https://blog.csdn.net/qq_34803821/article/details/86240096
如果你想在网页上点击按钮,并且让树莓派接收到响应,并做响应的处理,实现网页上与树莓派进行数据交互以及一些数据渲染,那么希望这篇文章对你有所帮助:
源码放在git:https://github.com/StarFishing/ardunio/tree/master
树莓派与Arduino进行通信可以参考另一篇文章:https://blog.csdn.net/qq_34803821/article/details/86238387
首先先看效果图,总体效果我会放在文章末尾
这是已经写好的HTML页面,我截取了其中一部分,当我们点击蓝色按钮,树莓派打开Arduino板上的风扇,点击红色按钮关闭风扇
百度网盘工程:
链接:https://pan.baidu.com/s/1JIh-XsiJI5PbGt9G7pOjWQ
提取码:zu5x
复制这段内容后打开百度网盘手机App,操作更方便哦
环境配置
准备材料:
树莓派上安装flask:sudo pip install flask
python 串口读取:sudo pip insall pyserial
我们针对树莓派进行讲解,我们如何实现点击的相应,让树莓派接收到事件呢?
树莓派服务器
# codinf:utf-8
from flask import Flask, render_template, Response, request
import serial
port = "/dev/ttyACM0"
app = Flask(__name__)
single = serial.Serial(port, 9600)
single.flushInput()
@app.route('/')
def index():
single.flushOutput()
single.flushInput()
single.write('8')
response = str(single.readline().decode())
if response.startswith('hum:'):
# cut int num
hum = response[5:7]
tem = response[-6:-3]
templateData = {
'tem': tem,
'hum': hum
}
print(response.strip('\n'))
return render_template('index.html', **templateData)
@app.route('/fopen', methods=['POST', 'GET'])
def fopen():
if request.method == 'GET':
return render_template('index.html')
else:
single.flushOutput()
single.write('1')
return "Open OK"
@app.route('/fclose', methods=['POST'])
def fclose():
single.flushOutput()
single.write('2')
return "Close OK"
@app.route('/lclose', methods=['POST'])
def lclose():
# single.flushOutput()
# single.write('3')
return "LED Close OK"
@app.route('/lopen', methods=['POST'])
def lopen():
# single.flushOutput()
# single.write('4')
return "LED Open OK"
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True, threaded=True)
© 2019 GitHub, Inc.
在HTML里面,我们做这样一件事情:
将我们的点击事件异步提交到相应的路由下
高温警告:
已自动为您打开风扇
关/开风扇:
$('.open i').click(function() {
if (this.id == 'close') {
$.post('/fclose', this.id, function(data, status) {})
}
if (this.id == 'open') {
$.post('/fopen', this.id, function(data, status) {})
}
})