Skip to content

Commit

Permalink
Avoid division by zero, make voltage readable on VoltageOut
Browse files Browse the repository at this point in the history
  • Loading branch information
theacodes committed Oct 28, 2019
1 parent aa82fac commit 41c4cf1
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
3 changes: 3 additions & 0 deletions tests/test_winterbloom_voltageio.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ def __init__(self):
(0.5, 32768),
(0.75, 49151),
(1.0, 65535),
(2.0, 65535),
]
)
def test_out_linear_calibration_normalized(voltage, value):
Expand All @@ -87,6 +88,7 @@ def test_out_linear_calibration_normalized(voltage, value):
(2.475, 49151),
# 100%
(3.3, 65535),
(4.0, 65535),
]
)
def test_out_linear_calibration_real_range(voltage, value):
Expand All @@ -107,6 +109,7 @@ def test_out_linear_calibration_real_range(voltage, value):
(1.0, 32768),
(5.5, 49152),
(10, 65535),
(11, 65535),
]
)
def test_out_direct_calibration(voltage, value):
Expand Down
17 changes: 14 additions & 3 deletions winterbloom_voltageio.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ class VoltageOut:
def __init__(self, analog_out):
self._analog_out = analog_out
self._calibration = {}
self._voltage = 0

@classmethod
def from_pin(cls, pin):
Expand Down Expand Up @@ -150,7 +151,10 @@ def _calibrated_value_for_voltage(self, voltage):

low, high = _take_nearest_pair(self._calibration_keys, voltage)

normalized_offset = (voltage - low) / (high - low)
if high == low:
normalized_offset = 0
else:
normalized_offset = (voltage - low) / (high - low)

low_val = self._calibration[low]
high_val = self._calibration[high]
Expand All @@ -159,11 +163,15 @@ def _calibrated_value_for_voltage(self, voltage):

return min(lerped, 65535)

def _get_voltage(self):
return self._voltage

def _set_voltage(self, voltage):
self._voltage = voltage
value = self._calibrated_value_for_voltage(voltage)
self._analog_out.value = value

voltage = property(None, _set_voltage)
voltage = property(_get_voltage, _set_voltage)


class VoltageIn:
Expand Down Expand Up @@ -234,7 +242,10 @@ def _calibrated_voltage_for_value(self, value):

low, high = _take_nearest_pair(self._calibration_keys, value)

normalized_offset = (value - low) / (high - low)
if high == low:
normalized_offset = 0
else:
normalized_offset = (value - low) / (high - low)

low_volt = self._calibration[low]
high_volt = self._calibration[high]
Expand Down

0 comments on commit 41c4cf1

Please sign in to comment.