Skip to content

Instantly share code, notes, and snippets.

@dupontgu
Created May 12, 2023 18:42
Show Gist options
  • Save dupontgu/ca149161da0c18ee9d05e1f8fc694219 to your computer and use it in GitHub Desktop.
Save dupontgu/ca149161da0c18ee9d05e1f8fc694219 to your computer and use it in GitHub Desktop.
CircuitPython demo showing how to reduce ADC "flickering" when reading potentiometer
import board
import time
from analogio import AnalogIn
analog_in = AnalogIn(board.A0)
pot_v_9bit = analog_in.value >> 7
pot_v_7bit = pot_v_9bit >> 2
while True:
# take a few readings and average them for a tiny bit of filtering
# analog_in.value is an unsigned, 16 bit value
pot_readings = []
pot_sample_count = 15
for _ in range(pot_sample_count):
pot_readings.append(analog_in.value >> 7)
time.sleep(0.001)
current_pot_v_9bit = round(sum(pot_readings) / pot_sample_count)
# it tends to flicker between adjacent values,
# so safe to move forward once the value changes by a magnitude >= 3
if (abs(current_pot_v_9bit - pot_v_9bit) >= 3):
pot_v_9bit = current_pot_v_9bit
current_pot_v_7bit = current_pot_v_9bit >> 2
# avoid sending the same value twice
if (current_pot_v_7bit != pot_v_7bit):
pot_v_7bit = current_pot_v_7bit
print("POT adjusted:", pot_v_7bit)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment