使用網頁控制 GPIO

安裝 Python Flask 套件:

sudo apt-get update
sudo apt-get install python-pip python-flask
sudo pip install flask

接線說明

LED

  1. GND(接地)
  2. GPIO18

1602 LCD

  1. 5V
  2. GND
  3. SDA
  4. SCL

程式碼

檔案:app.py

import RPi.GPIO as GPIO
import subprocess
from flask import Flask, render_template, request

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, GPIO.LOW)

@app.route("/")
def main():
   return render_template('main.html')

@app.route("/led/on")
def led_on():
   GPIO.output(18, GPIO.HIGH)
   return render_template('main.html')

@app.route("/led/off")
def led_off():
   GPIO.output(18, GPIO.LOW)
   return render_template('main.html')

@app.route("/lcd")
def lcd():
   line1 = request.args.get('line1')
   line2 = request.args.get('line2')
   subprocess.call(["python", "lcd1602.py", line1, line2])
   return render_template('main.html')

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

檔案:templates/main.html

<!DOCTYPE html>
<head>
   <title>RPi GPIO Demo</title>
</head>
<body>
   <h3>LED燈控制</h3>
   <ul>
      <li><a href="/led/on">On</a></li>
      <li><a href="/led/off">Off</a></li>
   </ul>
   <h3>LCD-1602顯示器控制</h3>
   <form action="/lcd">
      第一行:<input name="line1" maxlength="16" /><br/>
      第二行:<input name="line2" maxlength="16" /><br/>
      <button type="submit">Send</button>
   </form>
</body>
</html>

執行方法

sudo python app.py

加入溫濕度監控

app.js 加入:

import Adafruit_DHT
import sys
from flask import jsonify

以及:

history = [['Time', 'Temp', 'Humidity']]
c = 1

@app.route("/dht11")
def dht11():
   global history, c
   h, t = Adafruit_DHT.read_retry(11, 4)
   history.append([str(c), t, h])
   c = c + 1
   return jsonify(history)

main.html 加入:

   <h3>溫濕度監控</h3>
   <div id="curve_chart" style="width: 900px; height: 500px"></div>

   <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
   <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
   <script type="text/javascript">
   $(function() {

      $.getJSON( "/dht11", function( json ) {
         google.charts.load('current', {'packages':['corechart']});
         google.charts.setOnLoadCallback(drawChart);

         function drawChart() {
            console.log(json);
           var data = google.visualization.arrayToDataTable(json);

           var options = {
             title: 'DHT-11 Sensor',
             curveType: 'function',
             legend: { position: 'bottom' }
           };

           var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

           chart.draw(data, options);
         }
      });
   });
   </script>

results matching ""

    No results matching ""