Skip to content

Commit 336cb5a

Browse files
committed
factoring out the read
1 parent 3b68fc7 commit 336cb5a

File tree

1 file changed

+13
-19
lines changed

1 file changed

+13
-19
lines changed

adafruit_pcf8591/pcf8591.py

Lines changed: 13 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@
4444

4545
OUT = const(0)
4646

47+
4748
class PCF8591:
4849
"""Driver for the PCF8591 DAC & ADC Combo breakout.
4950
@@ -72,38 +73,31 @@ def reference_voltage(self):
7273
An ADC value of 65535 will equal `reference_voltage`"""
7374
return self._reference_voltage
7475

75-
def read(self, channel):
76-
"""Read an analog value from one of the four ADC inputs
77-
78-
param: :adcnum The single-ended ADC to read from, 0 thru 3
79-
"""
76+
def _half_read(self, channel):
8077
if self._dac_enabled:
8178
self._buffer[0] = _PCF8591_ENABLE_DAC
8279
self._buffer[1] = self._dacval
8380
else:
8481
self._buffer[0] = 0
8582
self._buffer[1] = 0
8683

87-
if channel < 0 or channel > 3:
88-
raise ValueError("channel must be from 0-3")
89-
9084
self._buffer[0] |= channel & 0x3
9185

9286
with self.i2c_device as i2c:
9387
i2c.write_then_readinto(self._buffer, self._buffer)
9488

95-
if self._dac_enabled:
96-
self._buffer[0] = _PCF8591_ENABLE_DAC
97-
self._buffer[1] = self._dacval
98-
else:
99-
self._buffer[0] = 0
100-
self._buffer[1] = 0
101-
self._buffer[0] |= channel & 0x3
102-
103-
# final read before render
89+
def read(self, channel):
90+
"""Read an analog value from one of the four ADC inputs
10491
105-
with self.i2c_device as i2c:
106-
i2c.write_then_readinto(self._buffer, self._buffer)
92+
param: :channel The single-ended ADC channel to read from, 0 thru 3
93+
"""
94+
if channel < 0 or channel > 3:
95+
raise ValueError("channel must be from 0-3")
96+
# reads are started on the ACK of the WRITE to the 'register' and
97+
# not returned until the read after the _next_ WRITE so we have to
98+
# do it twice to get the actual value
99+
self._half_read(channel)
100+
self._half_read(channel)
107101

108102
return unpack_from(">B", self._buffer[1:])[0]
109103

0 commit comments

Comments
 (0)