Module ADS1x15
[hide private]
[frames] | no frames]

Source Code for Module ADS1x15

  1  # Copyright (c) 2016 Adafruit Industries 
  2  # Author: Tony DiCola 
  3  # 
  4  # Permission is hereby granted, free of charge, to any person obtaining a copy 
  5  # of this software and associated documentation files (the "Software"), to deal 
  6  # in the Software without restriction, including without limitation the rights 
  7  # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
  8  # copies of the Software, and to permit persons to whom the Software is 
  9  # furnished to do so, subject to the following conditions: 
 10  # 
 11  # The above copyright notice and this permission notice shall be included in 
 12  # all copies or substantial portions of the Software. 
 13  # 
 14  # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 15  # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 16  # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 17  # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 18  # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 19  # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 20  # THE SOFTWARE. 
 21   
 22  # Slightly modified by Aegidius Pluess (www.aplu.ch), to remove references to other modules 
 23   
 24  import time 
 25  import smbus 
 26   
 27  # Register and other configuration values: 
 28  ADS1x15_DEFAULT_ADDRESS        = 0x48 
 29  ADS1x15_POINTER_CONVERSION     = 0x00 
 30  ADS1x15_POINTER_CONFIG         = 0x01 
 31  ADS1x15_POINTER_LOW_THRESHOLD  = 0x02 
 32  ADS1x15_POINTER_HIGH_THRESHOLD = 0x03 
 33  ADS1x15_CONFIG_OS_SINGLE       = 0x8000 
 34  ADS1x15_CONFIG_MUX_OFFSET      = 12 
 35  # Maping of gain values to config register values. 
 36  ADS1x15_CONFIG_GAIN = { 
 37      2/3: 0x0000, 
 38      1:   0x0200, 
 39      2:   0x0400, 
 40      4:   0x0600, 
 41      8:   0x0800, 
 42      16:  0x0A00 
 43  } 
 44  ADS1x15_CONFIG_MODE_CONTINUOUS  = 0x0000 
 45  ADS1x15_CONFIG_MODE_SINGLE      = 0x0100 
 46  # Mapping of data/sample rate to config register values for ADS1015 (faster). 
 47  ADS1015_CONFIG_DR = { 
 48      128:   0x0000, 
 49      250:   0x0020, 
 50      490:   0x0040, 
 51      920:   0x0060, 
 52      1600:  0x0080, 
 53      2400:  0x00A0, 
 54      3300:  0x00C0 
 55  } 
 56  # Mapping of data/sample rate to config register values for ADS1115 (slower). 
 57  ADS1115_CONFIG_DR = { 
 58      8:    0x0000, 
 59      16:   0x0020, 
 60      32:   0x0040, 
 61      64:   0x0060, 
 62      128:  0x0080, 
 63      250:  0x00A0, 
 64      475:  0x00C0, 
 65      860:  0x00E0 
 66  } 
 67  ADS1x15_CONFIG_COMP_WINDOW      = 0x0010 
 68  ADS1x15_CONFIG_COMP_ACTIVE_HIGH = 0x0008 
 69  ADS1x15_CONFIG_COMP_LATCHING    = 0x0004 
 70  ADS1x15_CONFIG_COMP_QUE = { 
 71      1: 0x0000, 
 72      2: 0x0001, 
 73      4: 0x0002 
 74  } 
 75  ADS1x15_CONFIG_COMP_QUE_DISABLE = 0x0003 
 76   
 77   
78 -class ADS1x15(object):
79 """Base functionality for ADS1x15 analog to digital converters.""" 80
81 - def __init__(self, address = ADS1x15_DEFAULT_ADDRESS, busnum = 1):
82 self._address = address 83 self._bus = smbus.SMBus(busnum)
84
85 - def _data_rate_default(self):
86 """Retrieve the default data rate for this ADC (in samples per second). 87 Should be implemented by subclasses. 88 """ 89 raise NotImplementedError('Subclasses must implement _data_rate_default!')
90
91 - def _data_rate_config(self, data_rate):
92 """Subclasses should override this function and return a 16-bit value 93 that can be OR'ed with the config register to set the specified 94 data rate. If a value of None is specified then a default data_rate 95 setting should be returned. If an invalid or unsupported data_rate is 96 provided then an exception should be thrown. 97 """ 98 raise NotImplementedError('Subclass must implement _data_rate_config function!')
99
100 - def _conversion_value(self, low, high):
101 """Subclasses should override this function that takes the low and high 102 byte of a conversion result and returns a signed integer value. 103 """ 104 raise NotImplementedError('Subclass must implement _conversion_value function!')
105
106 - def _read(self, mux, gain, data_rate, mode):
107 """Perform an ADC read with the provided mux, gain, data_rate, and mode 108 values. Returns the signed integer result of the read. 109 """ 110 config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion. 111 # Specify mux value. 112 config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET 113 # Validate the passed in gain and then set it in the config. 114 if gain not in ADS1x15_CONFIG_GAIN: 115 raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16') 116 config |= ADS1x15_CONFIG_GAIN[gain] 117 # Set the mode (continuous or single shot). 118 config |= mode 119 # Get the default data rate if none is specified (default differs between 120 # ADS1015 and ADS1115). 121 if data_rate is None: 122 data_rate = self._data_rate_default() 123 # Set the data rate (this is controlled by the subclass as it differs 124 # between ADS1015 and ADS1115). 125 config |= self._data_rate_config(data_rate) 126 config |= ADS1x15_CONFIG_COMP_QUE_DISABLE # Disble comparator mode. 127 # Send the config value to start the ADC conversion. 128 # Explicitly break the 16-bit value down to a big endian pair of bytes. 129 self.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF]) 130 # Wait for the ADC sample to finish based on the sample rate plus a 131 # small offset to be sure (0.1 millisecond). 132 time.sleep(1.0/data_rate+0.0001) 133 # Retrieve the result. 134 result = self.readList(ADS1x15_POINTER_CONVERSION, 2) 135 return self._conversion_value(result[1], result[0])
136
137 - def _read_comparator(self, mux, gain, data_rate, mode, high_threshold, 138 low_threshold, active_low, traditional, latching, 139 num_readings):
140 """Perform an ADC read with the provided mux, gain, data_rate, and mode 141 values and with the comparator enabled as specified. Returns the signed 142 integer result of the read. 143 """ 144 assert num_readings == 1 or num_readings == 2 or num_readings == 4, 'Num readings must be 1, 2, or 4!' 145 # Set high and low threshold register values. 146 self.writeList(ADS1x15_POINTER_HIGH_THRESHOLD, [(high_threshold >> 8) & 0xFF, high_threshold & 0xFF]) 147 self.writeList(ADS1x15_POINTER_LOW_THRESHOLD, [(low_threshold >> 8) & 0xFF, low_threshold & 0xFF]) 148 # Now build up the appropriate config register value. 149 config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion. 150 # Specify mux value. 151 config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET 152 # Validate the passed in gain and then set it in the config. 153 if gain not in ADS1x15_CONFIG_GAIN: 154 raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16') 155 config |= ADS1x15_CONFIG_GAIN[gain] 156 # Set the mode (continuous or single shot). 157 config |= mode 158 # Get the default data rate if none is specified (default differs between 159 # ADS1015 and ADS1115). 160 if data_rate is None: 161 data_rate = self._data_rate_default() 162 # Set the data rate (this is controlled by the subclass as it differs 163 # between ADS1015 and ADS1115). 164 config |= self._data_rate_config(data_rate) 165 # Enable window mode if required. 166 if not traditional: 167 config |= ADS1x15_CONFIG_COMP_WINDOW 168 # Enable active high mode if required. 169 if not active_low: 170 config |= ADS1x15_CONFIG_COMP_ACTIVE_HIGH 171 # Enable latching mode if required. 172 if latching: 173 config |= ADS1x15_CONFIG_COMP_LATCHING 174 # Set number of comparator hits before alerting. 175 config |= ADS1x15_CONFIG_COMP_QUE[num_readings] 176 # Send the config value to start the ADC conversion. 177 # Explicitly break the 16-bit value down to a big endian pair of bytes. 178 self.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF]) 179 # Wait for the ADC sample to finish based on the sample rate plus a 180 # small offset to be sure (0.1 millisecond). 181 time.sleep(1.0/data_rate+0.0001) 182 # Retrieve the result. 183 result = self.readList(ADS1x15_POINTER_CONVERSION, 2) 184 return self._conversion_value(result[1], result[0])
185
186 - def read_adc(self, channel, gain=1, data_rate=None):
187 """Read a single ADC channel and return the ADC value as a signed integer 188 result. Channel must be a value within 0-3. 189 You can also pass in an optional data_rate parameter that controls 190 the ADC conversion time (in samples/second). Each chip has a different 191 set of allowed data rate values, see datasheet Table 9 config register 192 DR bit values. 193 ADS1015: 128, 250, 490, 920, 1600(default), 2400, 3300 194 ADS1115: 8, 16, 32, 64, 128 (default), 250, 475, 860 195 Each returned value will be a 12 or 16 bit signed integer value depending on the 196 ADC (ADS1015 = 12-bit, ADS1115 = 16-bit). 197 Gain of 1 for reading voltages from 0 to 4.09V. 198 Or pick a different gain to change the range of voltages that are read: 199 - 2/3 = +/-6.144V 200 - 1 = +/-4.096V 201 - 2 = +/-2.048V 202 - 4 = +/-1.024V 203 - 8 = +/-0.512V 204 - 16 = +/-0.256V 205 See table 3 in the ADS1015/ADS1115 datasheet for more info on gain. 206 """ 207 assert 0 <= channel <= 3, 'Channel must be a value within 0-3!' 208 # Perform a single shot read and set the mux value to the channel plus 209 # the highest bit (bit 3) set. 210 return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)
211
212 - def read_adc_difference(self, differential, gain=1, data_rate=None):
213 """Read the difference between two ADC channels and return the ADC value 214 as a signed integer result. Differential must be one of: 215 - 0 = Channel 0 minus channel 1 216 - 1 = Channel 0 minus channel 3 217 - 2 = Channel 1 minus channel 3 218 - 3 = Channel 2 minus channel 3 219 """ 220 assert 0 <= differential <= 3, 'Differential must be a value within 0-3!' 221 # Perform a single shot read using the provided differential value 222 # as the mux value (which will enable differential mode). 223 return self._read(differential, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)
224
225 - def start_adc(self, channel, gain=1, data_rate=None):
226 """Start continuous ADC conversions on the specified channel (0-3). Will 227 return an initial conversion result, then call the get_last_result() 228 function to read the most recent conversion result. Call stop_adc() to 229 stop conversions. 230 You can also pass in an optional data_rate parameter that controls 231 the ADC conversion time (in samples/second). Each chip has a different 232 set of allowed data rate values, see datasheet Table 9 config register 233 DR bit values. 234 ADS1015: 128, 250, 490, 920, 1600(default), 2400, 3300 235 ADS1115: 8, 16, 32, 64, 128 (default), 250, 475, 860 236 Each returned value will be a 12 or 16 bit signed integer value depending on the 237 ADC (ADS1015 = 12-bit, ADS1115 = 16-bit). 238 Gain of 1 for reading voltages from 0 to 4.09V. 239 Or pick a different gain to change the range of voltages that are read: 240 - 2/3 = +/-6.144V 241 - 1 = +/-4.096V 242 - 2 = +/-2.048V 243 - 4 = +/-1.024V 244 - 8 = +/-0.512V 245 - 16 = +/-0.256V 246 See table 3 in the ADS1015/ADS1115 datasheet for more info on gain. 247 """ 248 assert 0 <= channel <= 3, 'Channel must be a value within 0-3!' 249 # Start continuous reads and set the mux value to the channel plus 250 # the highest bit (bit 3) set. 251 return self._read(channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_CONTINUOUS)
252
253 - def start_adc_difference(self, differential, gain=1, data_rate=None):
254 """Start continuous ADC conversions between two ADC channels. Differential 255 must be one of: 256 - 0 = Channel 0 minus channel 1 257 - 1 = Channel 0 minus channel 3 258 - 2 = Channel 1 minus channel 3 259 - 3 = Channel 2 minus channel 3 260 Will return an initial conversion result, then call the get_last_result() 261 function continuously to read the most recent conversion result. Call 262 stop_adc() to stop conversions. 263 """ 264 assert 0 <= differential <= 3, 'Differential must be a value within 0-3!' 265 # Perform a single shot read using the provided differential value 266 # as the mux value (which will enable differential mode). 267 return self._read(differential, gain, data_rate, ADS1x15_CONFIG_MODE_CONTINUOUS)
268
269 - def start_adc_comparator(self, channel, high_threshold, low_threshold, 270 gain=1, data_rate=None, active_low=True, 271 traditional=True, latching=False, num_readings=1):
272 """Start continuous ADC conversions on the specified channel (0-3) with 273 the comparator enabled. When enabled, the comparator checks if 274 the ADC value is within the high_threshold & low_threshold value (both 275 should be signed 16-bit integers) and trigger the ALERT pin. The 276 behavior can be controlled by the following parameters: 277 - active_low: Boolean that indicates if ALERT is pulled low or high 278 when active/triggered. Default is true, active low. 279 - traditional: Boolean that indicates if the comparator is in traditional 280 mode where it fires when the value is within the threshold, 281 or in window mode where it fires when the value is _outside_ 282 the threshold range. Default is true, traditional mode. 283 - latching: Boolean that indicates if the alert should be held until 284 get_last_result() is called to read the value and clear 285 the alert. Default is false, non-latching. 286 - num_readings: The number of readings that match the comparator before 287 triggering the alert. Can be 1, 2, or 4. Default is 1. 288 Will return an initial conversion result, then call the get_last_result() 289 function continuously to read the most recent conversion result. Call 290 stop_adc() to stop conversions. 291 """ 292 assert 0 <= channel <= 3, 'Channel must be a value within 0-3!' 293 # Start continuous reads with comparator and set the mux value to the 294 # channel plus the highest bit (bit 3) set. 295 return self._read_comparator(channel + 0x04, gain, data_rate, 296 ADS1x15_CONFIG_MODE_CONTINUOUS, 297 high_threshold, low_threshold, active_low, 298 traditional, latching, num_readings)
299
300 - def start_adc_difference_comparator(self, differential, high_threshold, low_threshold, 301 gain=1, data_rate=None, active_low=True, 302 traditional=True, latching=False, num_readings=1):
303 """Start continuous ADC conversions between two channels with 304 the comparator enabled. See start_adc_difference for valid differential 305 parameter values and their meaning. When enabled the comparator to will 306 check if the ADC value is within the high_threshold & low_threshold value 307 (both should be signed 16-bit integers) and trigger the ALERT pin. The 308 behavior can be controlled by the following parameters: 309 - active_low: Boolean that indicates if ALERT is pulled low or high 310 when active/triggered. Default is true, active low. 311 - traditional: Boolean that indicates if the comparator is in traditional 312 mode where it fires when the value is within the threshold, 313 or in window mode where it fires when the value is _outside_ 314 the threshold range. Default is true, traditional mode. 315 - latching: Boolean that indicates if the alert should be held until 316 get_last_result() is called to read the value and clear 317 the alert. Default is false, non-latching. 318 - num_readings: The number of readings that match the comparator before 319 triggering the alert. Can be 1, 2, or 4. Default is 1. 320 Will return an initial conversion result, then call the get_last_result() 321 function continuously to read the most recent conversion result. Call 322 stop_adc() to stop conversions. 323 """ 324 assert 0 <= differential <= 3, 'Differential must be a value within 0-3!' 325 # Start continuous reads with comparator and set the mux value to the 326 # channel plus the highest bit (bit 3) set. 327 return self._read_comparator(differential, gain, data_rate, 328 ADS1x15_CONFIG_MODE_CONTINUOUS, 329 high_threshold, low_threshold, active_low, 330 traditional, latching, num_readings)
331
332 - def stop_adc(self):
333 """Stop all continuous ADC conversions (either normal or difference mode). 334 """ 335 # Set the config register to its default value of 0x8583 to stop 336 # continuous conversions. 337 config = 0x8583 338 self.writeList(ADS1x15_POINTER_CONFIG, [(config >> 8) & 0xFF, config & 0xFF])
339
340 - def get_last_result(self):
341 """Read the last conversion result when in continuous conversion mode. 342 Will return a signed integer value. 343 """ 344 # Retrieve the conversion register value, convert to a signed int, and 345 # return it. 346 result = self.readList(ADS1x15_POINTER_CONVERSION, 2) 347 return self._conversion_value(result[1], result[0])
348
349 - def readList(self, register, length):
350 """Read a length number of bytes from the specified register. Results 351 will be returned as a bytearray.""" 352 results = self._bus.read_i2c_block_data(self._address, register, length) 353 return results
354 355
356 - def writeList(self, register, data):
357 """Write bytes to the specified register.""" 358 self._bus.write_i2c_block_data(self._address, register, data)
359 360
361 -class ADS1115(ADS1x15):
362 """ADS1115 16-bit analog to digital converter instance.""" 363
364 - def __init__(self, *args, **kwargs):
365 super(ADS1115, self).__init__(*args, **kwargs)
366
367 - def _data_rate_default(self):
368 # Default from datasheet page 16, config register DR bit default. 369 return 128
370
371 - def _data_rate_config(self, data_rate):
372 if data_rate not in ADS1115_CONFIG_DR: 373 raise ValueError('Data rate must be one of: 8, 16, 32, 64, 128, 250, 475, 860') 374 return ADS1115_CONFIG_DR[data_rate]
375
376 - def _conversion_value(self, low, high):
377 # Convert to 16-bit signed value. 378 value = ((high & 0xFF) << 8) | (low & 0xFF) 379 # Check for sign bit and turn into a negative value if set. 380 if value & 0x8000 != 0: 381 value -= 1 << 16 382 return value
383
384 -class ADS1015(ADS1x15):
385 """ADS1015 12-bit analog to digital converter instance.""" 386
387 - def __init__(self, *args, **kwargs):
388 super(ADS1015, self).__init__(*args, **kwargs)
389
390 - def _data_rate_default(self):
391 # Default from datasheet page 19, config register DR bit default. 392 return 1600
393
394 - def _data_rate_config(self, data_rate):
395 if data_rate not in ADS1015_CONFIG_DR: 396 raise ValueError('Data rate must be one of: 128, 250, 490, 920, 1600, 2400, 3300') 397 return ADS1015_CONFIG_DR[data_rate]
398
399 - def _conversion_value(self, low, high):
400 # Convert to 12-bit signed value. 401 value = ((high & 0xFF) << 4) | ((low & 0xFF) >> 4) 402 # Check for sign bit and turn into a negative value if set. 403 if value & 0x800 != 0: 404 value -= 1 << 12 405 return value
406