Skip to content

Instantly share code, notes, and snippets.

@danasf
Created November 21, 2018 15:58
Show Gist options
  • Save danasf/1a5af79b490f374992458e886c45fd04 to your computer and use it in GitHub Desktop.
Save danasf/1a5af79b490f374992458e886c45fd04 to your computer and use it in GitHub Desktop.
laser dust sensor - pm 2.5 plotter
import serial
import time
import struct
import datetime
import matplotlib.pyplot as plt
# for use with sds021 sensor or similar
# https://www.aliexpress.com/item/NOVA-PM2-5-Air-particle-dust-sensor-SDS021-laser-inside-digital-output-SDS021-Laser-PM2-5/32638192686.html
# replace with your serial port
ser = serial.Serial('/dev/tty.wchusbserial1410',9600)
pm_25 = 0
pm_10 = 0
pm_25_old = 0
pm_10_old = 0
x = []
y = []
raw = []
count = 0
def checksum(data):
checksum = 0
for x in range(2,8):
# print(x,data[x],ord(data[x]))
checksum =checksum+ord(data[x])
#print(checksum%256,ord(data[8]))
if(ord(data[8] ) == (checksum%256)):
return True
else:
return False
def calculate(high,low):
return ((ord(high)*256)+ord(low))/10.0
# do some smoothing
def smooth(old,new,alpha=0.25):
if old is None:
old = new
return (old + alpha * (new - old))
# to do - calculate AQI
plt.ion()
while True:
message = ser.read(10)
print("read data",message)
if checksum(message):
pm_10_old = pm_10
pm_25_old = pm_25
pm_25 = smooth(pm_25_old,calculate(message[3],message[2]))
pm_10 = smooth(pm_10_old,calculate(message[5],message[4]))
raw.append(calculate(message[3],message[2]))
x.append(count)
y.append(pm_25)
print("pm2.5",pm_25)
print("pm10",pm_10)
plt.plot(x,y,'g')
#plt.plot(x,raw,'r')
plt.pause(0.0001) #Note this correction
count = count + 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment