1.所需材料:
树莓派、面包板、温湿度传感器DHT11、直流电机、风扇、L298N电机驱动模块。
2.树莓派从DHT11温湿度传感器读取数据
(1)DHT11 介绍
DHT11是一款有已校准数字信号输出的温湿度传感器。 其精度湿度+-5%RH, 温度+-2℃,量程湿度20-90%RH, 温度0~50℃。
(2)硬件连接图
(3)具体流程
DHT11的读取需要遵循特定的信号协议完成,为了方便使用Adafruit DHT库。
a.软件安装
sudo apt-get install build-essential python-dev
b.从GitHub获取Adafruit库
sudo git clone https://github.com/adafruit/Adafruit_Python_DHT.git
cd Adafruit_Python_DHT
c.给python2和python3安装该库
sudo python setup.py install
sudo python3 setup.py install
d.书写dht.py程序引入Adafruit库来读取DHT11的数据
import Adafruit_DHT
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
# Set GPIO sensor is connected to
gpio=17
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# Reading the DHT11 is very sensitive to timings and occasionally
# the Pi might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
e.运行结果图
3.树莓派从DHT11温湿度传感器读取数据写入到数据库中
(1)在树莓派上安装MySQL数据库
a.安装MySQL
使用管理员权限运行获取最新的MySQL及Python编程接口。
$ sudo apt-get install mysql-server python-mysqldb
安装过程中需要输入root管理员的密码,该密码用于之后访问数据库。
b.登录MySQL
mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 53
Server version: 5.5.60-0+deb8u1 (Raspbian)
Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
c.查看当前的数据库
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
+--------------------+
3 rows in set (0.00 sec)
d.创建一个新的数据库
mysql> CREATE DATABASE jiankong;
Query OK, 1 row affected (0.00 sec)
e.在jiankong数据库下创建dht2的表
mysql> use jiankong;
Database changed
mysql> create table dht2(id int auto_increment primary key not null, time char(255),temperature int,humidity int);
Query OK, 0 rows affected (0.03 sec)
f.查看表是否创建成功。
mysql> describe dht2;
+-------------+-----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| time | char(255) | YES | | NULL | |
| temperature | int(11) | YES | | NULL | |
| humidity | int(11) | YES | | NULL | |
+-------------+-----------+------+-----+---------+----------------+
4 rows in set (0.00 sec)
(2)在树莓派上通过python来对mysql数据库进行存储操作
书写测试文件mysql_test.py来测试是否成功
import MySQLdb
sql='show databases';
conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='jiankong',port=3306)
cur=conn.cursor(
cur.execute(sql)
print cur.fetchone()
测试成功结果图
(3)将树莓派读取到的温湿度信息写入到我们mysql数据库,对dht.py文件进行修改
#coding: utf8
import Adafruit_DHT
import MySQLdb
import datetime
#引入gpio的模块
import RPi.GPIO as GPIO
import time
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
# Set GPIO sensor is connected to
gpio=4
dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# Reading the DHT11 is very sensitive to timings and occasionally
# the Pi might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
print "temperature:",temperature
print "humidity:",humidity
conn=MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='jiankong',
)
sql="insert into dht2(time,temperature,humidity) values('%s','%d','%d')"%(dt,temperature,humidity)
cur=conn.cursor()
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
else:
print('Failed to get reading. Try again!')
查看一下数据表dht2中的数据
4.树莓派结合L298N模块驱动直流电机
(1)L298N模块的介绍
接口说明:INT1、INT2、INT3、INT4分别接了树莓派的GPIO13、GPIO15、GPIO16、GPIO18。+5V接树莓派5V,GND接地。
(2)Python代码:
#!/usr/bin/python
#coding: utf8
#引入gpio的模块
import RPi.GPIO as GPIO
import time
#设置GPIO模式
GPIO.setmode(GPIO.BOARD)
#设置in1到in4接口
IN1 = 13
IN2 = 15
IN3 = 16
IN4 = 18
#初始化接口
def init():
GPIO.setup(IN1,GPIO.OUT)
GPIO.setup(IN2,GPIO.OUT)
GPIO.setup(IN3,GPIO.OUT)
GPIO.setup(IN4,GPIO.OUT)
#前进的代码
def qianjin(sleep_time):
GPIO.output(IN1,GPIO.HIGH)
GPIO.output(IN2,GPIO.LOW)
GPIO.output(IN3,GPIO.HIGH)
GPIO.output(IN4,GPIO.LOW)
time.sleep(sleep_time)
GPIO.cleanup()
#后退
def cabk(sleep_time):
GPIO.output(IN1,GPIO.LOW)
GPIO.output(IN2,GPIO.HIGH)
GPIO.output(IN3,GPIO.LOW)
GPIO.output(IN4,GPIO.HIGH)
time.sleep(sleep_time)
GPIO.cleanup()
#左转
def left(sleep_time):
GPIO.output(IN1,False)
GPIO.output(IN2,False)
GPIO.output(IN3,GPIO.HIGH)
GPIO.output(IN4,GPIO.LOW)
time.sleep(sleep_time)
GPIO.cleanup()
#右转
def right(sleep_time):
GPIO.output(IN1,GPIO.HIGH)
GPIO.output(IN2,GPIO.LOW)
GPIO.output(IN3,False)
GPIO.output(IN4,False)
time.sleep(sleep_time)
GPIO.cleanup()
init()#调用初始化方法初始化接口
cabk(10)#调用后退方法,并且10秒后停止
运行该程序,直流电机可运行10s。
5.树莓派智能调温综合
对dhp.py程序进行修改,使其测温度、湿度的时候,如果温度超过25℃,会自启动风扇降温。
#coding: utf8
import Adafruit_DHT
import MySQLdb
import datetime
#引入gpio的模块
import RPi.GPIO as GPIO
import time
# Set sensor type : Options are DHT11,DHT22 or AM2302
sensor=Adafruit_DHT.DHT11
# Set GPIO sensor is connected to
gpio=4
dt=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
#设置GPIO模式
GPIO.setmode(GPIO.BOARD)
#设置in1到in4接口
IN1 = 13
IN2 = 15
IN3 = 16
IN4 = 18
#初始化接口
def init():
GPIO.setup(IN1,GPIO.OUT)
GPIO.setup(IN2,GPIO.OUT)
GPIO.setup(IN3,GPIO.OUT)
GPIO.setup(IN4,GPIO.OUT)
#后退
def cabk(sleep_time):
GPIO.output(IN1,GPIO.LOW)
GPIO.output(IN2,GPIO.HIGH)
GPIO.output(IN3,GPIO.LOW)
GPIO.output(IN4,GPIO.HIGH)
time.sleep(sleep_time)
GPIO.cleanup()
# Use read_retry method. This will retry up to 15 times to
# get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
# Reading the DHT11 is very sensitive to timings and occasionally
# the Pi might fail to get a valid reading. So check if readings are valid.
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
print "temperature:",temperature
print "humidity:",humidity
conn=MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='root',
db='jiankong',
)
sql="insert into dht2(time,temperature,humidity) values('%s','%d','%d')"%(dt,temperature,humidity)
cur=conn.cursor()
cur.execute(sql)
cur.close()
conn.commit()
conn.close()
if temperature > 25:
init()
cabk(30)
else:
print('Failed to get reading. Try again!')