Skip to content

Instantly share code, notes, and snippets.

@jon1012
Forked from geoffwatts/sds011.py
Last active October 23, 2017 09:23
Show Gist options
  • Save jon1012/9409e50287343a5ab5d3a451b5e4a515 to your computer and use it in GitHub Desktop.
Save jon1012/9409e50287343a5ab5d3a451b5e4a515 to your computer and use it in GitHub Desktop.
Read an SDS011 Laser PM2.5 Sensor (Nova PM Sensor) with Python
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import serial, time, struct
import httplib, urllib
ser = serial.Serial("/dev/ttyUSB0", baudrate=9600, stopbits=1, parity="N", timeout=2)
ser.flushInput()
KEY = 'your_thingspeak_write_key_here'
byte, lastbyte = "\x00", "\x00"
while True:
lastbyte = byte
byte = ser.read(size=1)
# We got a valid packet header
if lastbyte == "\xAA" and byte == "\xC0":
sentence = ser.read(size=8) # Read 8 more bytes
readings = struct.unpack('<hhxxcc',sentence) # Decode the packet - big endian, 2 shorts for pm2.5 and pm10, 2 reserved bytes, checksum, message tail
pm_25 = readings[0]/10.0
pm_10 = readings[1]/10.0
# ignoring the checksum and message tail
#pm_25 = (ord(sentence[0]) | ord(sentence[1])<<8) / 10.0
#pm_10 = (ord(sentence[2]) | ord(sentence[3])<<8) / 10.0
params = urllib.urlencode({'field1': pm_25,
'field2': pm_10,
'key':KEY})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
data = response.read()
conn.close()
except Exception, e:
print "error sending data to thingspeak"
print "PM 2.5:",pm_25,"μg/m^3 PM 10:",pm_10,"μg/m^3"
@jon1012
Copy link
Author

jon1012 commented Jul 20, 2016

I changed the byte order, as the first byte is the low byte, and the second the high byte.
I've also set the parameters as args for the serial.Serial instanciation.

@jon1012
Copy link
Author

jon1012 commented Jul 22, 2016

Now added upload to thingspeak.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment