-
Notifications
You must be signed in to change notification settings - Fork 3
/
pp_i2cdevices.py
240 lines (201 loc) · 8.62 KB
/
pp_i2cdevices.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/env python
# Copyright (c) 2016 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time
# Register and other configuration values:
ADS1x15_DEFAULT_ADDRESS = 0x48
ADS1x15_POINTER_CONVERSION = 0x00
ADS1x15_POINTER_CONFIG = 0x01
ADS1x15_POINTER_LOW_THRESHOLD = 0x02
ADS1x15_POINTER_HIGH_THRESHOLD = 0x03
ADS1x15_CONFIG_OS_SINGLE = 0x8000
ADS1x15_CONFIG_MUX_OFFSET = 12
# Mapping of gain values to config register values.
ADS1x15_CONFIG_GAIN = {
2/3: 0x0000,
1: 0x0200,
2: 0x0400,
4: 0x0600,
8: 0x0800,
16: 0x0A00
}
ADS1x15_CONFIG_MODE_CONTINUOUS = 0x0000
ADS1x15_CONFIG_MODE_SINGLE = 0x0100
# Mapping of data/sample rate to config register values for ADS1015 (faster).
ADS1015_CONFIG_DR = {
128: 0x0000,
250: 0x0020,
490: 0x0040,
920: 0x0060,
1600: 0x0080,
2400: 0x00A0,
3300: 0x00C0
}
# Mapping of data/sample rate to config register values for ADS1115 (slower).
ADS1115_CONFIG_DR = {
8: 0x0000,
16: 0x0020,
32: 0x0040,
64: 0x0060,
128: 0x0080,
250: 0x00A0,
475: 0x00C0,
860: 0x00E0
}
ADS1x15_CONFIG_COMP_WINDOW = 0x0010
ADS1x15_CONFIG_COMP_ACTIVE_HIGH = 0x0008
ADS1x15_CONFIG_COMP_LATCHING = 0x0004
ADS1x15_CONFIG_COMP_QUE = {
1: 0x0000,
2: 0x0001,
4: 0x0002
}
ADS1x15_CONFIG_COMP_QUE_DISABLE = 0x0003
class ADS1x15(object):
"""Base functionality for ADS1x15 analog to digital converters."""
def __init__(self, bus=None,address=ADS1x15_DEFAULT_ADDRESS, **kwargs):
self.bus=bus
pass
def _data_rate_default(self):
"""Retrieve the default data rate for this ADC (in samples per second).
Should be implemented by subclasses.
"""
raise NotImplementedError('Subclasses must implement _data_rate_default!')
def _data_rate_config(self, data_rate):
"""Subclasses should override this function and return a 16-bit value
that can be OR'ed with the config register to set the specified
data rate. If a value of None is specified then a default data_rate
setting should be returned. If an invalid or unsupported data_rate is
provided then an exception should be thrown.
"""
raise NotImplementedError('Subclass must implement _data_rate_config function!')
def _conversion_value(self, low, high):
"""Subclasses should override this function that takes the low and high
byte of a conversion result and returns a signed integer value.
"""
raise NotImplementedError('Subclass must implement _conversion_value function!')
def _read(self, bus, mux, gain, data_rate, mode):
"""Perform an ADC read with the provided mux, gain, data_rate, and mode
values. Returns the signed integer result of the read.
"""
# print bus,mux,gain,data_rate,mode
config = ADS1x15_CONFIG_OS_SINGLE # Go out of power-down mode for conversion.
# Specify mux value.
config |= (mux & 0x07) << ADS1x15_CONFIG_MUX_OFFSET
# Validate the passed in gain and then set it in the config.
if gain not in ADS1x15_CONFIG_GAIN:
raise ValueError('Gain must be one of: 2/3, 1, 2, 4, 8, 16')
config |= ADS1x15_CONFIG_GAIN[gain]
# print hex(ADS1x15_CONFIG_GAIN[gain]), hex(config)
# Set the mode (continuous or single shot).
config |= mode
# Get the default data rate if none is specified (default differs between
# ADS1015 and ADS1115).
if data_rate is None:
data_rate = self._data_rate_default()
# Set the data rate (this is controlled by the subclass as it differs
# between ADS1015 and ADS1115).
config |= self._data_rate_config(data_rate)
config |= ADS1x15_CONFIG_COMP_QUE_DISABLE # Disble comparator mode.
# Send the config value to start the ADC conversion.
# print hex(config)
# Explicitly break the 16-bit value down to a big endian pair of bytes.
bus.write_i2c_block_data(ADS1x15_DEFAULT_ADDRESS,ADS1x15_POINTER_CONFIG,[(config >> 8) & 0xFF, config & 0xFF])
# Wait for the ADC sample to finish based on the sample rate plus a
# small offset to be sure (0.1 millisecond).
time.sleep(1.0/data_rate+0.0001)
# Retrieve the result.
result = bus.read_i2c_block_data(ADS1x15_DEFAULT_ADDRESS, ADS1x15_POINTER_CONVERSION, 2)
raw_adc = self._conversion_value(result[1], result[0])
# convert from 25.83 FS range
# 25.85*4.096/(2048.0*3.3) = 0.0156666666667
volts=raw_adc*0.0156666666667
percent=int(volts*100/3.3)
# print raw_adc, volts,percent
return percent,volts
def read_adc(self, bus, channel, gain=1, data_rate=None):
"""Read a single ADC channel and return the ADC value as a signed integer
result. Channel must be a value within 0-3.
"""
assert 0 <= channel <= 3, 'Channel must be a value within 0-3!'
# Perform a single shot read and set the mux value to the channel plus
# the highest bit (bit 3) set.
return self._read(bus,channel + 0x04, gain, data_rate, ADS1x15_CONFIG_MODE_SINGLE)
class ADS1115(ADS1x15):
"""ADS1115 16-bit analog to digital converter instance."""
def __init__(self, *args, **kwargs):
super(ADS1115, self).__init__(*args, **kwargs)
def _data_rate_default(self):
# Default from datasheet page 16, config register DR bit default.
return 128
def _data_rate_config(self, data_rate):
if data_rate not in ADS1115_CONFIG_DR:
raise ValueError('Data rate must be one of: 8, 16, 32, 64, 128, 250, 475, 860')
return ADS1115_CONFIG_DR[data_rate]
def _conversion_value(self, low, high):
# Convert to 16-bit signed value.
value = ((high & 0xFF) << 8) | (low & 0xFF)
# Check for sign bit and turn into a negative value if set.
if value & 0x8000 != 0:
value -= 1 << 16
return value
class ADS1015(ADS1x15):
"""ADS1015 12-bit analog to digital converter instance."""
def __init__(self, *args, **kwargs):
super(ADS1015, self).__init__(*args, **kwargs)
def _data_rate_default(self):
# Default from datasheet page 19, config register DR bit default.
return 1600
def _data_rate_config(self, data_rate):
if data_rate not in ADS1015_CONFIG_DR:
raise ValueError('Data rate must be one of: 128, 250, 490, 920, 1600, 2400, 3300')
return ADS1015_CONFIG_DR[data_rate]
def _conversion_value(self, low, high):
# Convert to 12-bit signed value.
value = ((high & 0xFF) << 4) | ((low & 0xFF) >> 4)
# Check for sign bit and turn into a negative value if set.
if value & 0x800 != 0:
value -= 1 << 12
# krt - make 0 volts be 0
# value -=1
# print high,low,value
return value
class MCP4725DAC(object):
# https://github.com/samgratte/BeagleboneBlack/blob/master/BBB_MCP4725/i2c_mcp4725.py
def __init__(self):
pass
def write_dac_fast(self,bus,address,value):
if value < 0: value=0
if value>4095: value=4095
bus.write_byte_data(address,(value>>8)&0x0F,value&0xFF)
def write_dac(self,bus,address,value,store=False):
buf=[0,0]
if store is False:
command = 0x40
else:
command = 0x60
if value < 0: value=0
if value>4095: value=4095
buf[0]=(value>>4) & 0xFF
buf[1]=(value<<4) & 0xFF
# print address,buf[0],buf[1]
bus.write_i2c_block_data(address,command,buf)
return