3131"""
3232from time import sleep
3333from struct import unpack_from
34- import adafruit_bus_device . i2c_device as i2c_device
34+ from adafruit_bus_device import i2c_device
3535
3636__version__ = "0.0.0-auto.0"
3737__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_SGP40.git"
@@ -111,6 +111,7 @@ def __init__(self, i2c, address=0x59):
111111 self .i2c_device = i2c_device .I2CDevice (i2c , address )
112112 self ._command_buffer = bytearray (2 )
113113 self ._measure_command = _READ_CMD
114+ self ._voc_algorithm = None
114115
115116 self .initialize ()
116117
@@ -133,8 +134,6 @@ def initialize(self):
133134
134135 raise RuntimeError ("Feature set does not match: %s" % hex (featureset [0 ]))
135136
136- # VocAlgorithm_init(&voc_algorithm_params)
137-
138137 # Self Test
139138 self ._command_buffer [0 ] = 0x28
140139 self ._command_buffer [1 ] = 0x0E
@@ -226,6 +225,34 @@ def measure_raw(self, temperature=25, relative_humidity=50):
226225 self ._measure_command = bytearray (_cmd )
227226 return self .raw
228227
228+ def measure_index (self , temperature = 25 , relative_humidity = 50 ):
229+ """Measure VOC index after humidity compensation
230+ :param float temperature: The temperature in degrees Celsius, defaults to :const:`25`
231+ :param float relative_humidity: The relative humidity in percentage, defaults to :const:`50`
232+ :note VOC index can indicate the quality of the air directly.
233+ The larger the value, the worse the air quality.
234+ :note 0-100, no need to ventilate, purify
235+ :note 100-200, no need to ventilate, purify
236+ :note 200-400, ventilate, purify
237+ :note 00-500, ventilate, purify intensely
238+ :return int The VOC index measured, ranged from 0 to 500
239+ """
240+ # import/setup algorithm only on use of index
241+ # pylint: disable=import-outside-toplevel
242+ from adafruit_sgp40 .voc_algorithm import (
243+ VOCAlgorithm ,
244+ )
245+
246+ if self ._voc_algorithm is None :
247+ self ._voc_algorithm = VOCAlgorithm ()
248+ self ._voc_algorithm .vocalgorithm_init ()
249+
250+ raw = self .measure_raw (temperature , relative_humidity )
251+ if raw < 0 :
252+ return - 1
253+ voc_index = self ._voc_algorithm .vocalgorithm_process (raw )
254+ return voc_index
255+
229256 def _read_word_from_command (
230257 self ,
231258 delay_ms = 10 ,
@@ -288,7 +315,7 @@ def _generate_crc(crc_buffer):
288315 if crc & 0x80 :
289316 crc = (
290317 crc << 1
291- ) ^ 0x31 # 0x31 is the Seed for SGP40's CRC polynomial
318+ ) ^ 0x31 # 0x31 is the Seed for SGP40's CRC polynomial
292319 else :
293320 crc = crc << 1
294321 return crc & 0xFF # Returns only bottom 8 bits
0 commit comments