Commit | Line | Data |
---|---|---|
4f8716dc PH |
1 | """Read the MICS6812 via an ads1015 ADC""" |
2 | ||
82b86ca6 | 3 | import atexit |
4f8716dc PH |
4 | import ads1015 |
5 | import RPi.GPIO as GPIO | |
6 | ||
82b86ca6 | 7 | MICS6812_HEATER_PIN = 24 |
4f8716dc PH |
8 | |
9 | ||
10 | ads1015.I2C_ADDRESS_DEFAULT = ads1015.I2C_ADDRESS_ALTERNATE | |
11 | _is_setup = False | |
12 | ||
13 | ||
14 | class Mics6812Reading(object): | |
15 | __slots__ = 'oxidising', 'reducing', 'nh3' | |
16 | ||
17 | def __init__(self, ox, red, nh3): | |
18 | self.oxidising = ox | |
19 | self.reducing = red | |
20 | self.nh3 = nh3 | |
21 | ||
22 | def __repr__(self): | |
23 | return """Oxidising: {:05.02f} | |
24 | Reducing: {:05.02f} | |
25 | NH3: {:05.02f} | |
26 | """.format(self.oxidising, self.reducing, self.nh3) | |
27 | ||
28 | __str__ = __repr__ | |
29 | ||
30 | ||
31 | def setup(): | |
32 | global adc, _is_setup | |
33 | if _is_setup: | |
34 | return | |
35 | _is_setup = True | |
36 | ||
37 | adc = ads1015.ADS1015(i2c_addr=0x49) | |
38 | adc.set_mode('single') | |
39 | adc.set_programmable_gain(6.148) | |
40 | adc.set_sample_rate(1600) | |
41 | ||
42 | GPIO.setwarnings(False) | |
43 | GPIO.setmode(GPIO.BCM) | |
82b86ca6 PH |
44 | GPIO.setup(MICS6812_HEATER_PIN, GPIO.OUT) |
45 | GPIO.output(MICS6812_HEATER_PIN, 1) | |
46 | atexit.register(cleanup) | |
47 | ||
48 | ||
49 | def cleanup(): | |
50 | GPIO.output(MICS6812_HEATER_PIN, 0) | |
4f8716dc PH |
51 | |
52 | ||
53 | def read_all(): | |
82b86ca6 PH |
54 | """Return gas resistence for oxidising, reducing and NH3""" |
55 | setup() | |
4f8716dc PH |
56 | ox = adc.get_voltage('in0/gnd') |
57 | red = adc.get_voltage('in1/gnd') | |
58 | nh3 = adc.get_voltage('in2/gnd') | |
59 | ||
60 | ox = (ox * 56000) / (3.3 - ox) | |
61 | red = (red * 56000) / (3.3 - red) | |
62 | nh3 = (nh3 * 56000) / (3.3 - nh3) | |
63 | ||
64 | return Mics6812Reading(ox, red, nh3) | |
65 | ||
66 | ||
67 | def read_oxidising(): | |
68 | """Return gas resistance for oxidising gases. | |
69 | ||
70 | Eg chlorine, nitrous oxide | |
71 | """ | |
72 | setup() | |
73 | return read_all().oxidising | |
74 | ||
75 | ||
76 | def read_reducing(): | |
77 | """Return gas resistance for reducing gases. | |
78 | ||
79 | Eg hydrogen, carbon monoxide | |
80 | """ | |
81 | setup() | |
82 | return read_all().reducing | |
83 | ||
84 | ||
85 | def read_nh3(): | |
86 | """Return gas resistance for nh3/ammonia""" | |
87 | setup() | |
88 | return read_all().nh3 |