I am Making a scale for a project that measues every second, i want to take a rolling average of say 5 data samples and output the average instead of the active data.
import RPi.GPIO as GPIO
import numpy
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.OUT)
import time
import sys
EMULATE_HX711=False
referenceUnit = 1
if not EMULATE_HX711:
import RPi.GPIO as GPIO
from hx711 import HX711
else:
from emulated_hx711 import HX711
def cleanAndExit():
print("Cleaning...")
if not EMULATE_HX711:
GPIO.cleanup()
print("Bye!")
sys.exit()
hx = HX711(5, 6)
hx.set_reading_format("MSB", "MSB")
hx.set_reference_unit(-212.2456) #for calibration hash out devide number by wei>
hx.reset()
hx.tare()
print("Add weight now.")
while True:
try:
val = hx.get_weight(5)
print(val)
time.sleep(0.1)
hx.power_down()
hx.power_up()
time.sleep(0.1)
except (KeyboardInterrupt, SystemExit):
cleanAndExit()
Not too sure if this is of help; it’s a simple illustration of how to output a moving average:
numbers = [number for number in range(1, 100, 3)] # generate some data points
step = 5
for index, _ in enumerate(numbers):
data = numbers[index:index + step] # get step number of data points
if len(data) == step: # only calculate if there are step number of data points
print(f"Average: {sum(data) / step}") # the moving average
print()
else:
break
You’ll need to apply this to your method of data point generation, but I think that in principle it should work. numbers here is a list (just a POC object), but a tuple would work just as well.
tuple would not work with active data and neither will the example, i don’t currently have the data being dumped to a log file and it only exists in the active terminal, is there any way average the data this way?
Look at collections.deque. For every sample, .popleft() then append(). Initialize it with N elements (append only) then enter your popleft()/append() loop, averaging the contents after each append.