Skip to content

Instantly share code, notes, and snippets.

@dybber
Last active August 1, 2018 13:54
Show Gist options
  • Save dybber/91413483fc6a619d9ccaf723436b1552 to your computer and use it in GitHub Desktop.
Save dybber/91413483fc6a619d9ccaf723436b1552 to your computer and use it in GitHub Desktop.
Simple dustsensor MicroPython library
import machine
import time
# Python version of
# https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/
# returns duration in MICRO seconds
def pulseIn(pin, value):
# Wait till we hit the wanted value
while pin.value() != value:
pass
# Start timing
start = time.ticks_us()
# Wait till we are no longer == value
while pin.value() == value:
pass
now = time.ticks_us()
tdiff = time.ticks_diff(now, start)
return tdiff
def readDustsensor(pin, sampletime_ms):
starttime_ms = time.ticks_ms()
timePassed = 0
lowpulseoccupancy_us = 0
while timePassed < sampletime_ms:
duration_us = pulseIn(pin, 0)
lowpulseoccupancy_us = lowpulseoccupancy_us+duration_us
timePassed = time.ticks_diff(time.ticks_ms(), starttime_ms)
# Integer percentage 0%-100%
ratio = lowpulseoccupancy_us/(timePassed*10.0)
# Using spec sheet curve
concentration = 1.1*pow(ratio, 3)-3.8*pow(ratio, 2)+520*ratio+0.62
return concentration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment