Python output on Webserver REALTIME

Viewed 244

I have a Raspberry Pi with an I2C temperature sensor.

Python code:

import board
import adafruit_mlx90614
import time

i2c = board.I2C()
mlx = adafruit_mlx90614.MLX90614(i2c)
while True:
    print("Object Temp: ", mlx.object_temperature)

OUTPUT:

Object Temp:  21.89
Object Temp:  22.73
Object Temp:  27.31

It's working fine. But how can I make the output shown on the local webserver? REALTIME, no page refreshing? Just like a text. Nothing fancy.

Thanks

1 Answers

We will first need to set up a python web server, I chose to use Flask here. Second, we need to create an HTML file with a script that will update the data every few seconds (I chose 5 seconds here). So just make a new file called index.html in a new directory called /templates. Then just add the following html in the index.html file.

PS: You can cahnge that 5000 value in the setInterval function in the script, just make sure you count by the thousands, like 3 seconds would be 3000.

Python Code:

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 Code:

<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>
Related