Skip to content

Instantly share code, notes, and snippets.

@stonehippo
Last active November 25, 2025 23:07
Show Gist options
  • Select an option

  • Save stonehippo/e1c26358a9024fd224640a2b35146e86 to your computer and use it in GitHub Desktop.

Select an option

Save stonehippo/e1c26358a9024fd224640a2b35146e86 to your computer and use it in GitHub Desktop.
Playing with filtering and smooting in CircuitPython
from random import randint
from time import sleep
DELAY = 0.05
# simulate data coming from a noisy analog sensor, where the ADC range is 0-65536
def source():
return randint(0, 2 ** 16)
# exponential smoothing (AKA exponential moving average)
# ALPHA should be between 0 and 1, and may be changed to adjust the smoothing
# the lower the ALPHA, the greater the smoothing
ALPHA = 0.15
def exp_smooth(alpha, new_sample, filtered):
return alpha * new_sample + (1 - alpha) * filtered
smoothed = 0
while True:
sample = source()
smoothed = exp_smooth(ALPHA, sample, smoothed)
# print out the actual and smoothed/filtered results, good for use with a plotter
print((sample, smoothed))
sleep(DELAY)
from random import randint
from ulab import numpy as np
# simple moving average
# see also:
# https://www.geeksforgeeks.org/python/how-to-calculate-moving-averages-in-python/
# simulate data coming from a noisy analog sensor, where the ADC range is 0-65536
def source():
return randint(0, 2 ** 16)
def print_buffer(buff):
for v in buff:
print((v,))
# store a bunch of "readings"
ma_buffer = [source() for x in range(0,100)]
window_size = 10
i = 0
moving_averages = []
while i < len(ma_buffer) - window_size + 1:
# Calculate the average of current window
window_average = round(np.sum(ma_buffer[
i:i+window_size]) / window_size, 2)
# Store the average of current
# window in moving average list
moving_averages.append(window_average)
# Shift window to right by one position
i += 1
while len(moving_averages) < len(ma_buffer):
moving_averages.insert(0,0)
for v in range(0, 100):
print((ma_buffer[v], moving_averages[v]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment