如何在网页和LCD上显示python个变量

How to display python variables on a web page and an LCD

我正在尝试在 LCD 显示器和访问网页(仅限本地网络)时显示时间和温度以及其他变量。这是 运行 Raspberry pi 零 2 W,使用 python。我的想法是,flask 应用程序应该在后台 运行,并在调用时提供模板。同时,定时器应该每秒中断一次并导致 LCD 显示更新。

只要 flask 服务器未处于活动状态(注释掉“flask_app.run...”),LCD 显示屏就可以正常工作,每秒刷新一次数据。但是启用flask后,网页可以正常显示,但显示不正常

我对 python 和 Flask 的理解已经到了极限——你能看出这里有什么问题吗?谢谢

# Display data from furnace to raspberry pi zero W
#
import time
from flask import Flask, render_template, request
import RPi.GPIO as GPIO
import sys
import datetime
import SDL_DS3231
import smbus
from gpiozero import Button
import lcddriver

heatLEDPin = 5
heatPin = 27
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(heatLEDPin, GPIO.OUT)
GPIO.output(heatLEDPin,GPIO.LOW)
GPIO.setup(heatPin, GPIO.IN)
thermostatOn = Button(heatPin)


ds3231 = SDL_DS3231.SDL_DS3231(1, 0x68)

flask_app = Flask(__name__)
@flask_app.route('/')

def index():
    print ("here")
    display = ['1258','87','1259','2','61.2','on']
    datetimestr = str(ds3231.read_datetime())
    temperature = (ds3231.getTemp()*9/5+32)
   
    return render_template('index.html',
                           datetimestr = datetimestr,
                           temperature = temperature,
                           m24=display[0],
                           p24=display[1],
                           m30=display[2],
                           p30=display[3],
                           heat=display[5])

# Define functions
def mainLoop():
        # === Main loop ===
       # Get the time
        datetimestr = str(ds3231.read_datetime())
        month = int(datetimestr[5:7])
        day = int(datetimestr[8:10])
        hour = int(datetimestr[11:13])
        second = int(datetimestr[14:16])
        mylcd.lcd_display_string("%s" % datetimestr,1)
        mylcd.lcd_display_string(("Temp:%5.1f  Heat off" % (ds3231.getTemp()*9/5+32)),4)

# Main program

print ("")
print ("Test SDL_DS3231 Version 1.0 - SwitchDoc Labs/n/n")
print ("Program Started at:"+ time.strftime("%Y-%m-%d %H:%M:%S"))
print ("")
print ("DS3231=\t\t%s" % ds3231.read_datetime())
print ("DS3231 Temp=", ds3231.getTemp()*9/5+32)

interval = 1000000000 # system clock seconds
lastTime = 0


mylcd = lcddriver.lcd()
mylcd.lcd_clear()
#mylcd.lcd_backlight("On")  # Backlight is hard wired
mylcd.lcd_display_string("Hello world",1)

if __name__ == '__main__':
#    flask_app.run(debug=True, host='0.0.0.0')

# Loop
    while True:
        thisTime = time.time_ns()
        if (thisTime - lastTime >= interval):
            lastTime = thisTime
            mainLoop()

一旦调用 flask_app.run(),即为阻塞调用...它将永远保留在该函数中。因此,当取消注释 flask_app.run() 时,您的 LCD 计时器循环将永远不会执行。我的建议是使用多线程方法,其中一个线程负责 Flask 应用程序,另一个线程负责您想要执行的其他 board-level I/O。这是一个简单的工作示例,其中 flask 应用程序使用主线程,模拟 LCD 进程更新计数器(控制台模拟您的 LCD):

from flask import Flask
import threading
import time

# Using a global here for simplicity in this demo
# Globals are generally bad practice, so you would maintain
# the status of "lcd_counter" in a more elegant way
# (e.g. through a shared module, through classes, etc.)
# A simple global serves the purpose for this demo
# of a flask server running in parallel to another process
# emulating some I/O, printing to the console, etc.
lcd_counter = 0

flask_app = Flask(__name__)

@flask_app.route("/")
def hello_world():
    # See comment about global above
    global lcd_counter
    return f'<p>LCD counter = {lcd_counter}</p>'

def lcd_update():
    # This prints the value of the counter to the console to simulate sending it to the LCD
    # See comment about global above
    global lcd_counter
    while True:
        print(f'{lcd_counter}')
        time.sleep(1.0)
        lcd_counter += 1

if __name__ == '__main__':
    # Start a background thread to control/update the LCD
    # You'll also want to devise a graceful way to shutdown your whole app
    # by providing a kill signal to your threads, for example (beyond the scope of this answer)
    thread_LCD = threading.Thread(target=lcd_update, name='lcd_counter')
    thread_LCD.start()
    # Now run the flask web server in the main thread
    # debug=False to avoid Flask printing duplicate info to the console
    flask_app.run(debug=False, host='0.0.0.0')