owned this note
owned this note
Published
Linked with GitHub
# **DHT11 to raspberry pi to webserver**
:::success
**需要的硬體設備**
:::
**一台樹莓派 Raspberry Pi**
**一張SD卡(16G以上可能會比較好)**
**一條網路線(也可以透過設定檔做好wifi的連接就不需要網路線)**
**一顆DHT11感測模組**
:::info
**第一步: 下載 Adafruit_Python_DHT 套件**
:::
pi@raspberrypi:~ $ git clone https://github.com/adafruit/Adafruit_Python_DHT.git
![](https://i.imgur.com/PBJBgjE.png)
:::info
**第二步: 進入剛剛所載的資料夾裡**
:::
pi@raspberrypi:~ $ cd Adafruit_Python_DHT/
![](https://i.imgur.com/LHossum.png)
:::info
**第三步: 安裝 Adafruit_Python_DHT 套件**
:::
pi@raspberrypi:~/Adafruit_Python_DHT $ sudo python setup.py install
![](https://i.imgur.com/dBBknSW.png)
:::info
**第四步: 檢查DHT11模組是否安裝好了**
:::
pi@raspberrypi:~/Adafruit_Python_DHT $ pip list
![](https://i.imgur.com/HQcXhm4.png)
:::info
**第五步:將DHT11模組跟Raspberry Pi對接**
:::
| DHT11 | Raspberry Pi |
| -------- | -------- |
| +(VCC電壓電源) | 3.3V(pin 01) |
| output | GPIO4(pin 07) |
| GND | GND(pin 09) |
### **樹莓派3B針腳的腳位**
:::spoiler
![](https://i.imgur.com/grJuMiC.png)
:::
<br />
:::info
**第六步: 撰寫DHT11 .py**
:::
<pre>
import time
import Adafruit_DHT
GPIO_PIN = 4
try:
print('按下 Ctrl-C 可停止程式')
while True:
h, t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, GPIO_PIN)
if h is not None and t is not None:
print('溫度={0:0.1f}度C 濕度={1:0.1f}%'.format(t, h))
else:
print('讀取失敗,重新讀取。')
time.sleep(10)
except KeyboardInterrupt:
print('關閉程式')
</pre>
---
:::info
**第七步:執行該python**
:::
pi@raspberrypi:~ $ sudo python3 dht11.py
![](https://i.imgur.com/eyVI4bM.png)
:::info
**第八步:安裝mariadb資料庫跟PHP有支援MySQL-PDO**
:::
pi@raspberrypi:~ $ sudo apt-get install default-mysql-server php php-mysql
:::info
**第九步: 進入mysql**
:::
pi@raspberrypi:~ $ sudo mysql -u root -p
![](https://i.imgur.com/036crCl.png)
:::info
**第十步:創建一個使用者讓他使用資料庫**
:::
MariaDB [(none)]> create user 'pi'@'localhost' identified by 'raspberrypi';
![](https://i.imgur.com/NbWVyhD.png)
:::info
**第十一步:設定該使用者對資料庫的權限**
:::
MariaDB [(none)]> grant all privileges on *.* to 'pi'@'localhost' with grant option;
![](https://i.imgur.com/z2gdJAO.png)
:::info
**第十二步:建立資料庫並進入該資料庫**
:::
MariaDB [(none)]> create database dht11;
MariaDB [(none)]> use dht11;
![](https://i.imgur.com/qseTfJp.png)
:::info
**第十三步:建立資料表**
:::
<pre>
create table dht(
id int auto_increment primary key,
temp char(10),
hum char(5)
);
</pre>
![](https://i.imgur.com/tKLuOJG.png)
:::info
**第十四步:輸入一筆資料進去剛剛的資料表**
:::
MariaDB [dht11]> insert into dht values (1,24,70);
![](https://i.imgur.com/8OUoGkR.png)
### **\q;資料庫登出**
:::success
**更改mysql的設定檔**
:::
pi@raspberrypi:~ $ sudo vim /etc/mysql/my.cnf
**加入底下兩行**
[mysqld]
skip-grant-tables
![](https://i.imgur.com/DlAvfuJ.png)
**這麼一來就不必輸入密碼就能進資料庫**
:::success
**安裝mysql.connector**
:::
pi@raspberrypi:~ $ sudo pip install mysql-connector-python
:::info
**第十五步:撰寫可以將數據上傳到資料庫的python**
:::
**程式碼在底下**
:::spoiler
<pre>
import os
import time
import mysql.connector
import Adafruit_DHT
mydb = mysql.connector.connect(
host="localhost",
user="pi",
password="你帳號的密碼",
database="你的資料庫"
)
mycursor = mydb.cursor()
GPIO_PIN = 4
try:
while True:
h, t = Adafruit_DHT.read_retry(Adafruit_DHT.DHT11, GPIO_PIN)
if h is not None and t is not None:
print('{0:.0f}°C {1:.0f}%'.format(t,h))
sql = "INSERT INTO dht (temp,hum) VALUES (%s,%s)"
val = (t,h)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
else:
print('讀取失敗,重新讀取。')
time.sleep(5)
except KeyboardInterrupt:
print('關閉程式')
</pre>
:::
<br />
:::info
**第十六步:查看mysql是否有資料進入**
:::
MariaDB [dht11]> select * from dht;
![](https://i.imgur.com/l8nJ67M.png)
:::info
**第十七步:撰寫可以將資料表的數據傳送到php網頁**
:::
**程式碼在底下**
:::spoiler
<pre>
<?php
$servername = "localhost"; //伺服器連線名
$username = "root"; //資料庫使用者名稱
$password = ""; //資料庫密碼
$dbname = "dht11"; //資料庫名
$conn = new mysqli($servername, $username, $password, $dbname); //連線資料庫
echo "<table width='350' border='1' bordercolor='gold' style='text-align:center;'>";
if (!$conn) {
die("連線失敗:" . mysqli_connect_error());
echo "database error";
//連線資料庫失敗則殺死程序
}
$sql = "select * from dht order by id desc limit 1"; //查詢語句--查詢資料庫表
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>溫度:" . $row["temp"] . "度</td><td>濕度:" . $row["hum"] . "%</td>";
echo "</tr>";
}
}
else {
echo "0 結果";
}
echo "</table>";
mysqli_close($conn); //關閉資料庫
?>
</pre>
:::
<br />
:::info
**第十八步:查看該網頁**
:::
![](https://i.imgur.com/Y7pRW6C.png)
:::info
**第十九步:將數據網頁跟監控網頁寫在一起**
:::
**請將程式碼放置在/var/www/html/底下檔案名稱叫index.php**
<br />
**/var/www/html/index.php程式碼**
:::spoiler
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>遠端監控</title>
<meta charset="utf-8">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.rotate.js"></script>
<!--[if IE 6]>
<link rel="stylesheet" href="fix.css" type="text/css" />
<![endif]-->
<script type="text/javascript">
var phi = 0, flipped = 0, mirrored = 0;
function setXformClass () {
$('.xform').each(function(idx,el) {
el.className = "xform x" +(flipped ? "-flipped":"") + (mirrored ? "-mirrored" : "") + "-rotated-" + phi;
});
}
$(document).ready(function() {
// set rotation angle phi and toggle rotate class
$('#rotate').click(function() {
phi = (phi + 90) % 360;
setXformClass();
if (phi % 180) {
$('.xform-p').addClass('rotated');
} else {
$('.xform-p').removeClass('rotated');
}
});
// toggle mirror class component
$('#mirror').click(function() {
mirrored = ! mirrored;
setXformClass();
});
// toggle flip class component
$('#flip').click(function() {
flipped = ! flipped;
setXformClass();
});
});
</script>
</head>
<body>
<div style="margin:0px auto;text-align:center;">
<h1>遠端監控</h1>
<p class="xform-p"></p>
<p id="streamwrap" class="xform-p">
//img的id自己換成自己的IP
<img id="streamimage" class="xform" src="http://192.168.43.2:8080/?action=stream" />
</p>
</div>
<?php
$servername = "localhost"; //伺服器連線名
$username = "root"; //資料庫使用者名稱
$password = ""; //資料庫密碼
$dbname = "dht11"; //資料庫名
$conn = new mysqli($servername, $username, $password, $dbname); //連線資料庫
echo "<table width='350' border='1' bordercolor='gold' style='text-align:center; margin:0px auto;text-align:center;'>";
if (!$conn) {
die("連線失敗:" . mysqli_connect_error());
echo "database error";
//連線資料庫失敗則殺死程序
}
$sql = "select * from dht order by id desc limit 1"; //查詢語句--查詢資料庫表
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>目前溫度:" . $row["temp"] . "度</td><td>目前濕度:" . $row["hum"] . "%</td>";
echo "</tr>";
}
}
else {
echo "0 結果";
}
echo "</table>";
mysqli_close($conn); //關閉資料庫
?>
</body>
</html>
:::
<br >
:::success
**完成**
:::
![](https://i.imgur.com/MSFnlRc.png)
:::danger
**參考網址**
:::
**1. [『PHP學習筆記』系列七:讀取MySQL資料庫中的資料表](https://www.itread01.com/content/1542396143.html)**