Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2 Point calibration fix #232

Merged
merged 14 commits into from
Mar 19, 2023
26 changes: 18 additions & 8 deletions software/firmware/europi.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,20 +212,30 @@ def __init__(self, pin, min_voltage=MIN_INPUT_VOLTAGE, max_voltage=MAX_INPUT_VOL
def percent(self, samples=None):
"""Current voltage as a relative percentage of the component's range."""
# Determine the percent value from the max calibration value.
reading = self._sample_adc(samples)
max_value = max(reading, INPUT_CALIBRATION_VALUES[-1])
return reading / max_value
reading = self._sample_adc(samples) - INPUT_CALIBRATION_VALUES[0]
max_value = max(
reading,
INPUT_CALIBRATION_VALUES[-1] - INPUT_CALIBRATION_VALUES[0],
)
return max(reading / max_value, 0.0)

def read_voltage(self, samples=None):
reading = self._sample_adc(samples)
max_value = max(reading, INPUT_CALIBRATION_VALUES[-1])
percent = reading / max_value
raw_reading = self._sample_adc(samples)
reading = raw_reading - INPUT_CALIBRATION_VALUES[0]
max_value = max(
reading,
INPUT_CALIBRATION_VALUES[-1] - INPUT_CALIBRATION_VALUES[0],
)
percent = max(reading / max_value, 0.0)
# low precision vs. high precision
if len(self._gradients) == 2:
cv = 10 * (reading / INPUT_CALIBRATION_VALUES[-1])
cv = 10 * max(
reading / (INPUT_CALIBRATION_VALUES[-1] - INPUT_CALIBRATION_VALUES[0]),
0.0,
)
else:
index = int(percent * (len(INPUT_CALIBRATION_VALUES) - 1))
cv = index + (self._gradients[index] * (reading - INPUT_CALIBRATION_VALUES[index]))
cv = index + (self._gradients[index] * (raw_reading - INPUT_CALIBRATION_VALUES[index]))
return clamp(cv, self.MIN_VOLTAGE, self.MAX_VOLTAGE)


Expand Down
14 changes: 12 additions & 2 deletions software/tests/mock_hardware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
from machine import ADC, Pin

from europi import AnalogueReader, DigitalReader, Knob, MAX_UINT16, INPUT_CALIBRATION_VALUES
from europi import (
AnalogueReader,
DigitalReader,
Knob,
MAX_UINT16,
INPUT_CALIBRATION_VALUES,
)


class MockHardware:
Expand Down Expand Up @@ -31,7 +37,11 @@ def set_percent(self, reader: AnalogueReader, value: float):
self.set_ADC_u16_value(reader, value * MAX_UINT16)

def set_analogue_input_percent(self, reader: AnalogueReader, value: float):
self.set_ADC_u16_value(reader, value * INPUT_CALIBRATION_VALUES[-1])
self.set_ADC_u16_value(
reader,
value * (INPUT_CALIBRATION_VALUES[-1] - INPUT_CALIBRATION_VALUES[0])
+ INPUT_CALIBRATION_VALUES[0],
)

def set_knob_percent(self, knob: Knob, value: float):
self.set_ADC_u16_value(knob, (1 - value) * MAX_UINT16)