树莓派(十五)——用flask实现在网页上读取树莓派PGIO状态和系统时间

文章目录

      • 1、文件结构
      • 2、创建hello-gpio.py文件
      • 3、创建read_pin.html
      • 4、验证

在前面两节的基础上,我们已经学会使用flask搭建一个WEB服务应用程序,实现传感器数据和流媒体数据的简单处理。
在这一节,我们将学习如何通过编写Python脚本来读取树莓派PGIO口的状态和系统时间,并且展示在网页上面。通过这一节的教程,希望同学们能够对树莓派的PGIO口有更加深入的理解。

1、文件结构

这次的应用比较简单,所以要创建的文件也比较少,只有两个,这是最终的文件结构:

read_gpio/
├── hello-gpio.py
└── templates
    └── read_pin.html

2、创建hello-gpio.py文件

from flask import Flask, render_template
import datetime    #导入系统时间
import RPi.GPIO as GPIO   #导入GPIO
app = Flask(__name__)

GPIO.setmode(GPIO.BCM) #设置GPIO模式为BCM

@app.route("/")
def readPin():
      now = datetime.datetime.now()   #抓取时间
      timeString = now.strftime("%Y-%m-%d %H:%M:%S")   #抓取系统时间函数到timeString
try:
      GPIO.setup(20, GPIO.IN)    #读取BCM_gpio_20
      if GPIO.input(20) == True:
         response = "BCM_gpio_20 is high!"
      else:
         response = "BCM_gpio_20 is low!"
   except:
      response = "There was an error reading pin"

   templateData = {
      'time': timeString
      'title' : 'Status of Pin' + pin,
      'response' : response
      }

   return render_template('read_pin.html', **templateData)   #把templates送到read_pin.html


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

3、创建read_pin.html


   <head>
      <title>{{ title }}title>
   head>

   <body>
      <h1>Pin Statush1>
      <h2>{{ response }}h2>
      <h2>{{ time }}h2>
   body>
html>

4、验证

开启服务之后,可以在浏览器上看到如下结果:
树莓派(十五)——用flask实现在网页上读取树莓派PGIO状态和系统时间_第1张图片
说明实验成功!
更多关于树莓派GPIO的控制应用,大家可以参考《爱上Raspberry Pi》P183-188.

参考文档:https://www.cnblogs.com/smartkeke/p/6852100.html?tdsourcetag=s_pctim_aiomsg

你可能感兴趣的:(树莓派)