树莓派开机自动运行定时访问DHT22并将温湿度保存到mysql数据库

import datetime
import os
import Adafruit_DHT
import time
import pymysql
from apscheduler.schedulers.blocking import BlockingScheduler
def timedTask():
    sensor=Adafruit_DHT.DHT22
    pin=21
    humidity,temperature=Adafruit_DHT.read_retry(sensor,pin)
    print("temperature:",temperature)
    print("humidity:",humidity)

    db = pymysql.connect("192.168.31.12","wang","123456","wendu" )
# 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()
    s_time=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    s_didan="卧室"
    wendu=temperature
    shidu=humidity
# SQL 插入语句
    sql = "INSERT INTO wendubiao VALUES ('{时间}', '{地点}', {温度}, \
          {湿度})".format(时间=s_time,地点=s_didan,温度=wendu,湿度=shidu)
    try:
   # 执行sql语句
       cursor.execute(sql)
   # 提交到数据库执行
       db.commit()
       print(s_time)
    except:
   # 如果发生错误则回滚
       db.rollback()

# 关闭数据库连接
    db.close()

if __name__ == '__main__':
    scheduler=BlockingScheduler()
    scheduler.add_job(timedTask,'interval',seconds=5)
    #scheduler.start()
    print('Press Ctrl+{0} to exit'.format('Break' if os.name == 'nt' else 'C    '))
    try:
        scheduler.start()
    except (KeyboardInterrupt, SystemExit):
        pass
 

 

开机自动运行设置:

sudo nano /home/pi/.config/autostart/run.desktop
如果没有autostart和run.desktop就创建

run.desktop内容如下:

[Desktop Entry]
Type=Application
Exec=python3 /home/pi/wendusql.py

 

远程访问,画图。

import pymysql
import matplotlib.pyplot as plt
import pandas as pd

db = pymysql.connect("192.168.31.13","wang","123456","wendu" )
# 使用 cursor() 方法创建一个游标对象 cursor
print("连接成功")
data=pd.read_sql("SELECT * FROM wendubiao ",con=db)
x=list(data.time)
y=list(data.wd)
z=list(data.sd)
pjwd=data.wd.mean()
# 样本平均值
zdwd=data.wd.max()
# 样本最大值
zxwd=data.wd.min()
# 样本最小值
pj=[pjwd for i in x]
zd=[zdwd for i in x]
zx=[zxwd for i in x]
plt.plot(x,y,"g-")
plt.plot(x,pj,"r-")
plt.plot(x,zd,"b-")
plt.plot(x,zx,"k-")
print(y)
print(data.wd.mean())
print(len(y))
#plt.plot(x,z,"r--")
plt.show()
#plt.plot(x,z,"r--")
#print(z)
#plt.show()
db.close()

你可能感兴趣的:(温度传感器,mysql,树莓派)