我有一个带有I2C温度传感器的树莓派。
Python代码:
import board
import adafruit_mlx90614
import time
i2c = board.I2C()
mlx = adafruit_mlx90614.MLX90614(i2c)
while True:
print("Object Temp: ", mlx.object_temperature)输出:
Object Temp: 21.89
Object Temp: 22.73
Object Temp: 27.31它运行良好。但是,如何在本地can服务器上显示输出呢?实时,无页面刷新?就像一条短信。没什么花哨的。
谢谢
发布于 2021-04-26 10:52:55
我们首先需要设置一个python web服务器,我在这里选择使用Flask。其次,我们需要使用一个脚本创建一个HTML文件,该脚本每隔几秒钟更新一次数据(我在这里选择了5秒)。因此,只需在名为/templates的新目录中创建一个名为index.html的新文件。然后只需在index.html文件中添加以下html即可。
PS:你可以在脚本中的setInterval函数中篡改5000的值,只要确保你是以千为单位计数,比如3秒就是3000。
Python代码:
import board
import adafruit_mlx90614
import time
i2c = board.I2C()
mlx = adafruit_mlx90614.MLX90614(i2c)
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/temp')
def getTemp():
return str(mlx.object_temperature)
@app.route('/')
def hello_world():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug=True)HTML代码:
<html>
<head>
</head>
<body>
<p id="temp">Object Temp: 0</p>
<script>
const Http = new XMLHttpRequest();
const url='http://localhost:5000/temp';
function checkTemp(){
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
document.querySelector("#temp").innerHTML = "Object Temp: " + Http.responseText;
}
}
setInterval(checkTemp, 5000);
</script>
</body>
</html>https://stackoverflow.com/questions/67260071
复制相似问题