树莓派安装mysql数据库并且通过python来进行存储操作

本文介绍如何在树莓派上使用Python进行温湿度监测,并将数据存储到MySQL数据库中。文章提供了完整的代码示例,包括GPIO接口设置、温湿度读取及数据入库等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

具体的安装数据库的操作详见:http://blog.youkuaiyun.com/huayucong/article/details/49736427

安装python-Mysqldb


安装完成后,加上我之前有一片的温湿度监测的代码:

(mysql数据库在树莓派上;

用户名密码:root,123456;

端口:3306;

地址:localhost或者127.0.0.1;

数据库:testdb;

表:temp;

列名:time,temperature,humidity)

创建数据库和表的代码没写进去,可以在外面创建或者写在里面。个人建议是写在外面。


import RPi.GPIO as GPIO
import time
import MySQLdb
import os


#print time.time()
aa=time.strftime('%m%d%H%I%M',time.localtime(time.time()))
print aa
bb=int(aa)
#print (type(bb))
channel = 16
data = []
j = 0

GPIO.setmode(GPIO.BCM)

time.sleep(1)

GPIO.setup(channel, GPIO.OUT)

GPIO.output(channel, GPIO.LOW)
time.sleep(0.02)
GPIO.output(channel, GPIO.HIGH)

GPIO.setup(channel, GPIO.IN)

while GPIO.input(channel) == GPIO.LOW:
        continue

while GPIO.input(channel) == GPIO.HIGH:
        continue

while j < 40:
        k = 0
        while GPIO.input(channel) == GPIO.LOW:
                continue

        while GPIO.input(channel) == GPIO.HIGH:
                k += 1
                if k > 100:
                        break

        if k < 8:
                data.append(0)
        else:
                data.append(1)

        j += 1

print "sensor is working."
print data
humidity_bit = data[0:8]
humidity_point_bit = data[8:16]
temperature_bit = data[16:24]
temperature_point_bit = data[24:32]
check_bit = data[32:40]

humidity = 0
humidity_point = 0
temperature = 0
temperature_point = 0
check = 0

for i in range(8):
        humidity += humidity_bit[i] * 2 ** (7 - i)
        humidity_point += humidity_point_bit[i] * 2 ** (7 - i)
        temperature += temperature_bit[i] * 2 ** (7 - i)
        temperature_point += temperature_point_bit[i] * 2 ** (7 - i)
        check += check_bit[i] * 2 ** (7 - i)

tmp = humidity + humidity_point + temperature + temperature_point

if check == tmp:
        print "temperature : ", temperature, ", humidity : " , humidity
        conn= MySQLdb.connect(
                host='127.0.0.1',
                port = 3306,
                user='root',
                passwd='123456',
                db ='testdb',
                )
        cur = conn.cursor()
        # cur.execute("creat table if not exists temp(time int,temperature int,humidity int)")
        cur.execute("insert into temp values('%d','%d','%d')"%(bb,temperature,humidity))
        cur.close()
        conn.commit()
        conn.close()
else:
        print "wrong"
        print "temperature : ", temperature, ", humidity : " , humidity, " check : ", check, " tmp : ", tmp
GPIO.cleanup()


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值