top of page

HTML Sensor Dashboard Lab with Python



This lab simulates receiving sensor values and then dynamically creating an HTML Dashboard. We use Python to create the sensor value and then write an HTML document based off of the value. We set the Python script to continuously loop using while True: and we have the HTML page automatically refresh using <meta http-equiv="refresh" content="2">


For the script we import randint and sleep functions. We use randint to get a random int between 1-100 and we use sleep to pause the script for 1 second between each loop.


We then use a while True loop to create a continuous loop.


We then set the temp variable to a random int between 1-100. With that number we create an if/elif/else statement to set the variable value for color.


After that we create a variable for the text for the HTML page we will create. We use an f string to dynamically set the temperature value, and the CSS color for that text. We add the meta tag at the beginning so that the HTML page will auto refresh itself every 2 seconds.


We then use with open() to write the page value to sensor.html web page. This page will be written to whereever your current working directory is set.


We then print the temp and color values to the console screen for troubleshooting purposes, and pause the code for 1 second.


from random import randint
from time import sleep

while True:

    temp = randint(0,100)

    if temp >= 90:
        color = 'red'
    elif temp < 90 and temp >= 70:
        color = 'yellow'
    elif temp < 70 and temp >= 50:
        color = 'green'
    else:
        color = 'blue'

    page = f'''<meta http-equiv="refresh" content="2">
            <h1>Temp Sensor</h1>
            <p style="color:{color};font-size:100;">{temp}</p>

    		'''

    with open('sensor.html', 'w') as file:
        file.write(page)
    
    print(temp)
    print(color)
    sleep(1)

Comments


bottom of page