sgp30传感器,采用IIC总线与处理器通信。树莓派刚好有IIC引脚。且有现成的python包支持。

但是这个包用起来是有问题的,直接pip install sgp30后使用会报错。

所以截止目前网上都是单片机用C语言来写的sgp30传感器检测实例。下面我将一步步的介绍使用python在树莓派上编写一个sgp30传感器监测co2的实例。


环境:

树莓派3B+

python3

1.连接树莓派和sgp30传感器接口

python光照传感器 python传感器监测系统_树莓派

2.打开树莓派I2C使能

树莓派默认打开I2C功能,连接好树莓派和SGP30硬件接线后,检查树莓派是否开启了I2C功能:

sudo i2cdetect -y -a 1

如果开启了会显示:

python光照传感器 python传感器监测系统_树莓派_02

 表示SGP30传感器I2C地址:0x58

如果I2C没有打开,可以使用命令sudo raspi-config进入树莓派功能配置 。

python光照传感器 python传感器监测系统_python_03

python光照传感器 python传感器监测系统_树莓派_04

enable即可。

3.安装python的SGP30模块

pip install sgp30

 4.修正SGP模块中的一些引用

在包SGP的快速使用示例中看到它从smbus2中import SMBusWrapper。

但是smbus2中其实是没有SMBusWrapper的。在sgp30中它也import了SMBusWrapper。因此这个写法就会报错。

解决:将import SMBusWrapper改为from smbus2 import SMBus(sgp30中也对应的改)

错误示例:

python光照传感器 python传感器监测系统_嵌入式硬件_05

 5.愉快的上代码:

from smbus2 import SMBus
from sgp30 import Sgp30
import time
import os.path
import matplotlib.pyplot as plt
import datetime
import schedule
def run_recordData():
    print(".",end="")
    print()
    print(sgp.read_measurements())
    TimeNow=datetime.datetime.now().strftime('%H:%M')
    co2Data.append(sgp.read_measurements()[0][0])
    recordTime.append(TimeNow)
def run_show8hourPic():
    plt.close()
    plt.plot(recordTime,co2Data,linestyle='-', linewidth=1, marker='.', markersize=10, label='CO2')
    plt.legend()
    plt.xticks(rotation = 45)
    plt.show(block=False)
    plt.pause(3)
def run_resetData():
    co2Data=[]
    recordTime=[]
co2Data=[]
recordTime=[]
with SMBus(1) as bus:
    sgp=Sgp30(bus,baseline_filename="/tmp/mySGP30_baseline")#这句是sgp示例里面写的,我没仔细去看是用来做什么的,可以删掉
    print("resetting all i2c devices")
    sgp.i2c_geral_call()
    print(sgp.read_features())
    print(sgp.read_serial())
    sgp.init_sgp()
    print(sgp.read_measurements())
    print(sgp.read_measurements()[0][0])
    print("the SGP30 takes at least 15 seconds to warm up, 12 hours before the readigs become really stable")
    schedule.every(10).minutes.do(run_recordData)
    schedule.every(1).hours.do(run_show8hourPic)
    schedule.every(24).hours.do(run_resetData)
    while True:
        schedule.run_pending()  # run_pending:运行所有可以运行的任务

实现:每10分钟采集一次CO2的值,每小时更新一次展示图。每24小时重值归零数据后展示新一天的数据。

python光照传感器 python传感器监测系统_树莓派_06


彩蛋:网上找到的空间环境中二氧化碳对人的影响:

python光照传感器 python传感器监测系统_嵌入式硬件_07