Skip to content

Instantly share code, notes, and snippets.

@geoffwatts
Created January 25, 2016 22:57
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save geoffwatts/b0b488b5a5257223ed53 to your computer and use it in GitHub Desktop.
Save geoffwatts/b0b488b5a5257223ed53 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
ser = serial.Serial()
ser.port = "/dev/cu.wchusbserial1410" # Set this to your serial port
ser.baudrate = 9600
ser.open()
ser.flushInput()
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
print "PM 2.5:",pm_25,"μg/m^3 PM 10:",pm_10,"μg/m^3"
@zefanja
Copy link

zefanja commented Feb 22, 2016

Are you sure it is a big endian? Shouldn't that be an little endian? (http://inovafitness.com/upload/file/20150311/14261262164716.pdf → Page 5). I don't know much about big and little endian, but your output for PM2.5 and PM10 are to high (negative or over 1000).

@aapris
Copy link

aapris commented Aug 12, 2016

Yes, '<HHxxBBB' seems to return much more reasonable values (got it from here: https://www.snip2code.com/Snippet/1048974/SDS011-dust-sensor-reading ).

@irukard
Copy link

irukard commented Feb 10, 2017

It is definitely big endian.
'<hhxxcc' works fine.

@dhaeb
Copy link

dhaeb commented Oct 16, 2017

it is little endian!!!

http://ecksteinimg.de/Datasheet/SDS011%20laser%20PM2.5%20sensor%20specification-V1.3.pdf

Look at page 7! It starts with the low byte and finishes with the high byte !

So please correct line 22 from ">hhxxcc" to "<hhxxcc"

@senqtus
Copy link

senqtus commented Jul 15, 2018

the sensor doesn't start (the fan doesn't start),can anyone help me?

@smartynov
Copy link

smartynov commented Jun 4, 2019

It is little endian indeed! Thanks for everyone who pointed this out. @geoffwatts could you please fix this in your code? This page is top result in Google so it may confuse a lot of people.

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