Create RESOURCES_DIR early
[EVA-2020-02-2.git] / library / enviroplus / gas.py
CommitLineData
dd7489f8 1"""Read the MICS6814 via an ads1015 ADC"""
4f8716dc 2
82b86ca6 3import atexit
4f8716dc
PH
4import ads1015
5import RPi.GPIO as GPIO
6
dd7489f8 7MICS6814_HEATER_PIN = 24
4f8716dc
PH
8
9
10ads1015.I2C_ADDRESS_DEFAULT = ads1015.I2C_ADDRESS_ALTERNATE
11_is_setup = False
12
13
dd7489f8 14class Mics6814Reading(object):
4f8716dc
PH
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):
a155e335
SM
23 return """Oxidising: {:05.02f} Ohms
24Reducing: {:05.02f} Ohms
25NH3: {:05.02f} Ohms
4f8716dc
PH
26""".format(self.oxidising, self.reducing, self.nh3)
27
28 __str__ = __repr__
29
30
31def 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)
dd7489f8
SM
44 GPIO.setup(MICS6814_HEATER_PIN, GPIO.OUT)
45 GPIO.output(MICS6814_HEATER_PIN, 1)
82b86ca6
PH
46 atexit.register(cleanup)
47
48
49def cleanup():
dd7489f8 50 GPIO.output(MICS6814_HEATER_PIN, 0)
4f8716dc
PH
51
52
53def 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
dd7489f8 64 return Mics6814Reading(ox, red, nh3)
4f8716dc
PH
65
66
67def 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
76def 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
85def read_nh3():
86 """Return gas resistance for nh3/ammonia"""
87 setup()
88 return read_all().nh3