[英]background monitoring of GPIO pin in dash
恐怕這是一個非常基本的問題,我找不到正確的搜索詞,因此我們將不勝感激。
我想不斷監控覆盆子的 GPIO (24) 引腳。 在最小的示例中,我將它連接到一個按鈕,並希望在儀表板站點上顯示按下的次數。 我設法使用此處顯示的dash_core_components.Interval做到了這一點。 但是,這也會在每個時間間隔刷新頁面。 我想持續監控 GPIO 引腳,並且只在站點刷新時顯示當前計數值。
import RPi.GPIO as GPIO
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
globalCounter = 0
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN) #connected to 3.3V Pin of the pi, separated by a button.
app = dash.Dash()
app.layout = html.Div(
html.Div([
html.H1(id="live-update-text"),
dcc.Interval(
id='interval-component',
interval=1*1000, # in milliseconds
n_intervals=0
)
])
)
@app.callback(Output('live-update-text', 'children'),
Input('interval-component', 'n_intervals'))
def update_metrics(n):
global globalCounter
if GPIO.input(24) == 1:
globalCounter += 1
return "Number of presses: "+str(globalCounter)
if __name__ == '__main__':
app.run_server(debug=True, host='0.0.0.0', port=8080)
我想為此我需要將app.layout鏈接到 function (如文檔中的 2. 示例中所示),但是我如何仍然持續監控按鈕是否被按下?
找到了帶線程的解決方案。 GPIO 在線程中的 while 循環中進行監控,並且破折號布局鏈接到 function,如文檔中所述。
import dash
import dash_core_components as dcc
import dash_html_components as html
import RPi.GPIO as GPIO
import threading
gC = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(24, GPIO.IN)
def thread_function():
isButtonPressed = False #bool to avoid multi registration per press
while True:
global gC
if GPIO.input(24) == 1 and not isButtonPressed:
isButtonPressed = True
gC += 1
elif GPIO.input(24) == 0 and isButtonPressed:
isButtonPressed = False
x = threading.Thread(target=thread_function)
x.start()
app = dash.Dash()
colors = {
'background': '#ff0000',
'text': '#7FDBFF'
}
def sever_layout():
return html.Div(style={'backgroundColor': colors['background']}, children=[
html.H1(children='Counter '+str(gC))
])
app.layout = sever_layout
if __name__ == '__main__':
app.run_server(debug=True, host='0.0.0.0', port=8080)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.