樹莓派 基於Web的溫度計

前言:家裏的樹莓派吃灰好久,因而拿出來作個室內溫度展現也不錯。javascript

 

板子是model b型。html

使用Python開發,web框架是flask,溫度傳感器是ds18b20前端

 

1 硬件鏈接java

 

ds18b20的vcc鏈接樹莓派的vcc , gnd鏈接gnd,DS鏈接GPIO4node

2 ssh登陸樹莓派查看ds18b20的鏈接python

sudo modprobe w1-gpio
sudo modprobe w1-therm
cd /sys/bus/w1/devices
ls

 

若是ls看不到東西,使用下面的命令jquery

打開/boot/config.txt 在最後一行手動添加這個:dtoverlay=w1-gpio-pullup,gpiopin=4

而後 sudo rebootweb

 

3 目錄結構ajax

/static

  /js

    jquery.min.js
/templates

  hello.html

ds18b20.py

hello_flask.py

 

4 代碼展現express

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <h2>當前溫度:<span id="temp"></span></h2>


    <script src="/static/js/jquery.min.js" charset="utf-8"></script>
    <script type="text/javascript">
        // 前端每10s向後臺發起ajax請求,獲取當前溫溼度數據
        setInterval(function() {
            $.get('/update',function(data){
                $("#temp").html(data)
            })
        },2000)
    </script>

</body>
</html>

 

 

ds18b20.py

import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c

# while True:
#     print(read_temp())
#     time.sleep(1)

 

hello_flask.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from flask import Flask,render_template
import ds18b20
tmp = 0.0
app= Flask(__name__)
@app.route('/')
def hello():
    return render_template("hello.html")

#獲取最新溫度
@app.route('/update')
def update():
    tmp = ds18b20.read_temp()
    return str(tmp)

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

 

5 運行

sudo python hello_flask.py

打開 對應樹莓派的ip:8080 查看溫度

 

6 後語

本來打算使用nodejs開發的,但是在樹莓派上調校gpio各類坑,還有express框架的安裝也是不少問題,因而轉而使用python開發了。

相關文章
相關標籤/搜索