-
Notifications
You must be signed in to change notification settings - Fork 0
/
dust.py
64 lines (55 loc) · 1.46 KB
/
dust.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import machine
from time import sleep
# pin setup
LED_PIN = machine.Pin(16, machine.Pin.OUT) # D0
VO_PIN = machine.ADC(0) # A0
# constants
SAMPLING_TIME = 0.00028
DELTA_TIME = 0.00004
SLEEP_TIME = 0.00968
VOC = 0.6
MAX = 0
def calc_volt(val):
return val * 3.3 / 1024
def calc_density(vo, k=0.5):
global VOC
global MAX
dv = vo - VOC
if dv < 0:
dv = 0
VOC = vo
density = dv / k * 100
MAX = max(MAX, density)
return density
def monitor(sample_size=100, callback=None):
vals = []
while True:
try:
LED_PIN.value(0)
sleep(SAMPLING_TIME)
vals.append(VO_PIN.read())
sleep(DELTA_TIME)
LED_PIN.value(1)
sleep(SLEEP_TIME)
if len(vals) == sample_size:
avg = sum(vals) / len(vals)
volt = calc_volt(avg)
density = calc_density(volt)
mv = volt * 1000
print(
"{mv} mV / {density} ug/m3 (Voc={voc}) | Max: {max_} ug/m3".format( # noqa
mv=mv,
density=density,
voc=VOC,
max_=MAX,
)
)
vals = []
if callback:
callback(density)
except KeyboardInterrupt:
break
except Exception:
raise
finally:
LED_PIN.value(0)