树莓派加温湿度传感器,并上传至mysql

目录

硬件部分

编程部分

1、下载安装Adafruit提供的python驱动

3、把以上代码保存为dht22.py,然后执行

4、安装pymysql

4.1输入python3或者pyhton确认版本

4.2输入pip,检查pip是否安装

4.3安装PyMySQL

4.4测试连接

5、添加开机启动脚本

6、整合代码,实现间隔[m]分钟自动采集传感器数据,并传给mysql


硬件部分

使用的传感器是DHT22,有3个引脚,分别是电源正、数据、和电源负。正负不可接反,否则烧传感器

树莓派加温湿度传感器,并上传至mysql_第1张图片

接线方式,借用一下https://www.cnblogs.com/junjun001/p/9335246.html的图

树莓派加温湿度传感器,并上传至mysql_第2张图片

编程部分

1、下载安装Adafruit提供的python驱动

#sudo apt-get update

#sudo apt-get install build-essential python-dev

#git clone https://github.com/adafruit/Adafruit_Python_DHT.git

#cd Adafruit_Python_DHT

#sudo python setup.py install

如果不出错的话就能安装好了。

2、dht22的代码如下,(如果是dht11,把sensor = Adafruit_DHT.DHT22改为sensor = Adafruit_DHT.DHT11)

在Adafruit_Python_DHT目录外新建一个.py文件

#!/usr/bin/python

import Adafruit_DHT

sensor = Adafruit_DHT.DHT22

pin = 4  #GPIO4

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

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!')

3、把以上代码保存为dht22.py,然后执行

#sudo python dht22.py

4、安装pymysql

4.1输入python3或者pyhton确认版本

#python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.

4.2输入pip,检查pip是否安装

#pip

Usage:   
  pip  [options]

Commands:
  install                     Install packages.

4.3安装PyMySQL

pi@raspberrypi:~/ $ sudo pip install pymysql
Collecting pymysql
  Downloading https://files.pythonhosted.org/packages/ed/39/15045ae46f2a123019aa968dfcba0396c161c20f855f11dea6796bcaae95/PyMySQL-0.9.3-py2.py3-none-any.whl (47kB)
    100% |████████████████████████████████| 51kB 330kB/s 
Installing collected packages: pymysql
Successfully installed pymysql-0.9.3

4.4测试连接

import pymysql

con = pymysql.connect(
    host = '192.168.0.2',
    port = 3306,
    user = 'root',
    password = 'yourpassword',
    db = 'yourdatabase',
    charset = 'utf8'
)
cur = con.cursor()
cur.execute("show tables")
data=con.fetchall
print(data)

5、添加开机启动脚本

编辑/etc/rc.local 在exit 0 前添加对应的脚本 

pi@raspberrypi:~ $ cat /etc/rc.local
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

python /home/pi/ht.py
exit 0

6、整合代码,实现间隔[m]分钟自动采集传感器数据,并传给mysql

mysql中添加数据库

create database yourdb COLLATE utf8_general_ci;

添加表格 

create table ht(
ID int  primary key not null auto_increment,
Time datetime,
Position varchar(20),
Temperature float(3,1),
Humidity float(3,1)
);

整合后的ht.py 

#!/usr/bin/python
import Adafruit_DHT
import pymysql
import time
import datetime
pos = "weizhi1" #传感器安装位置
def caiji(pos):
    sensor = Adafruit_DHT.DHT22
    pin = 4 #GPIO4
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    #mysql
    con = pymysql.connect(
        host = '192.168.0.2',
        port = 3306,
        user = 'root',
        password = 'youerpassword',
        db = 'yourdb',
        charset = 'utf8'
    )
    cur = con.cursor()

    if humidity is not None and temperature is not None:

        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))
        cur.execute("insert into ht(Time,Position,Temperature,Humidity) value(now(),'%s','%s','%s')" %(pos,temperature,humidity))
        con.commit()
    else:

        print('Failed to get reading. Try again!')
        
    cur.close()
    con.close()

def main(m=0):
    print("Start collection data,interval [%s] minutes" %(m));
    while True:
        while True:
            now=datetime.datetime.now()
            if now.minute % m == 0:
                break
			#过20秒再检测一次
            time.sleep(20)
        print(datetime.datetime.now())
        caiji(pos)
        #采集一次后等待一段时间再判断
        if m>1:
            time.sleep((m-1)*60)
        
        else:
            time.sleep(60)
              
main(10) #10分钟采集一次
            

 

你可能感兴趣的:(mysql,RaspberryPI)