Skip to content

Commit

Permalink
Allow re-using ADC readings instead of re-reading all the time (#358)
Browse files Browse the repository at this point in the history
* Add the BufferedKnob experimental class to facilitate re-using prior ADC readings

* Expand docstrings
  • Loading branch information
chrisib authored Apr 9, 2024
1 parent cc9d08f commit 6d4898b
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions software/firmware/experimental/knobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,3 +334,47 @@ def build(self) -> "KnobBank":
@staticmethod
def builder(knob: Knob) -> Builder:
return KnobBank.Builder(knob)


class BufferedKnob(Knob):
"""A wrapper for a Knob instance whose value remains fixed until .update(...) is called
This allows multiple uses of .percent(), .choice(...), etc... without forcing a re-read of
the ADC value
"""

def __init__(self, knob):
"""Create a buffered wrapper for the given analogue input
The parameter @knob can be any Knob instance, including:
- europi.k1
- europi.k2
Until the .update() method is called, this class will return a value of 0.
@param knob The analogue input to wrap e.g.:
```python
from europi import *
from experimental.knobs import *
k1_buffered = BufferedKnob(k1)
```
"""
super().__init__(knob.pin_id)
self.value = 0

def _sample_adc(self, samples=None):
"""Overrides the internal function that samples the ADC
Instead of sampling we simply return the most recent sample value
@param samples Ignored, but needed by the _sample_adc API used by AnalogueReader
"""
return self.value

def update(self, samples=None):
"""Re-read the ADC and update the buffered value
@param samples Specifies the number of samples to average to de-noise the ADC reading
See europi.AnalogueReader for details on ADC sampling
"""
self.value = super()._sample_adc(samples)

0 comments on commit 6d4898b

Please sign in to comment.