MJRoBot (Marcelo Rovai)
Published © GPL3+

Sensing the Air Quality

A low-cost IoT air quality monitor based on a Raspberry Pi 4.

BeginnerFull instructions provided3 hours5,618
Sensing the Air Quality

Things used in this project

Hardware components

Raspberry Pi 3 Model B
Raspberry Pi 3 Model B
×1
SDS011 - High precision laser pm2.5 air quality detection sensor
×1

Software apps and online services

ThingSpeak API
ThingSpeak API
Jupyter Notebook
Jupyter Notebook

Story

Read more

Code

Code snippet #5

Plain text
def get_data(n=3):
    sensor.sleep(sleep=False)
    pmt_2_5 = 0
    pmt_10 = 0
    time.sleep(10)
    for i in range (n):
        x = sensor.query()
        pmt_2_5 = pmt_2_5 + x[0]
        pmt_10 = pmt_10 + x[1]
        time.sleep(2)
    pmt_2_5 = round(pmt_2_5/n, 1)
    pmt_10 = round(pmt_10/n, 1)
    sensor.sleep(sleep=True)
    time.sleep(2)
    return pmt_2_5, pmt_10

Code snippet #7

Plain text
def save_log(): 
    with open("YOUR PATH HERE/air_quality.csv", "a") as log:
    dt = datetime.now()
    log.write("{},{},{},{},{}\n".format(dt, pmt_2_5, aqi_2_5,       pmt_10,aqi_10))
    log.close()

Code snippet #8

Plain text
while(True): 
    pmt_2_5, pmt_10 = get_data()
    aqi_2_5, aqi_10 = conv_aqi(pmt_2_5, pmt_10)
    try:
        save_log()
    except:
        print ("[INFO] Failure in logging data") 
    time.sleep(60)

Code snippet #13

Plain text
# Sending all data to ThingSpeak every 1 minute
while(True): 
    pmt_2_5, pmt_10 = get_data()
    aqi_2_5, aqi_10 = conv_aqi(pmt_2_5, pmt_10)
    tPayload = "field1=" + str(pmt_2_5)+ "&field2=" + str(aqi_2_5)+ "&field3=" + str(pmt_10)+ "&field4=" + str(aqi_10)
    try:
        publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, tls=tTLS, transport=tTransport)
        save_log()
    except:
        print ("[INFO] Failure in sending data") 
    time.sleep(60)

Gitlab

https://gitlab.com/frankrich/sds011_particle_sensor/blob/master/Code/sds011.py

Github

https://github.com/ikalchev/py-sds011

Credits

MJRoBot (Marcelo Rovai)

MJRoBot (Marcelo Rovai)

66 projects • 956 followers
Professor, Engineer, MBA, Master in Data Science. Writes about Electronics with a focus on Physical Computing, IoT, ML, TinyML and Robotics.

Comments