Toegang tot de LED en knop geven

from flask import Flask, render_template
from gpiozero import Button, LED

led = LED(22)
button = Button(26)

button_count = 0

def increment_counter():
    global button_count
    button_count = button_count + 1

button.when_pressed = increment_counter

app = Flask(__name__)

@app.route("/")
def main():
    page_data = {
        "led": led.value,
        "button": button.value,
        "button_count": button_count
    }
    return render_template('webpi.html', **page_data)

@app.route("/led/")
def led_action(action):
    if action == "on":
        led.on()
    elif action == "off":
        led.off()

    return main()

@app.route("/button/value")
def button_value():
    return dict(value=button.value, count=button_count)

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000)

Eenvoudige HTML-pagina listing, LET OP: Onze website werkt helaas niet mee, dus om deze code te kopieren en te plakken, klik rechtermuisknop en paginabron weergeven, dan vind je op regel 392 t/m 421 de juiste code. Excuses van team Linux!




  
    
    
    
    

WebPi

 

LED

{% if led == 1 %}
Turn off
{% else %}
Turn on
{% endif %}

Button

 

{% if button == 1 %}

{% else %}

{% endif %}
{{ button_count }}

 



JavaScript bestand

function updateButton() {
    $.getJSON("/button/value", function(data){
        if(data.value == 1) {
            $("i#button").removeClass("bi-toggle-off").addClass("bi-toggle-on");
        } else {
            $("i#button").removeClass("bi-toggle-on").addClass("bi-toggle-off");
        }
        $("span#count").text(data.count);
    })
}
  
setInterval(updateButton, 50);

Webpi.service inhoud

[Unit]
Description=WebPi
After=network-online.target
[Service]
Restart=on-failure
Type=simple
User=pi
ExecStart=/usr/bin/python3 /home/pi/webpi/webpi.py

[Install]
WantedBy=multi-user.target