I made a Potentiometer testing device that reads the analog values from an MCP3008 ADC.
In order to hide the sporadic analog input fluctuations I am calculating the average of several measurements in a while loop with a function similar to the following:
def analog_average():
analog1 = (mcp_analog)
time.sleep(0.001)
analog2 = (mcp_analog)
time.sleep(0.001)
analog3 = (mcp_analog)
time.sleep(0.001)
analog4 = (mcp_analog)
time.sleep(0.001)
analog5 = (mcp_analog)
analog_average = ((analog1 + analog2 + analog3 + analog4 + analog5) / 5)
print(analog_average)
mcp_analog is the value of the ADC's first analog input.
I am getting the results that I want. Is there, however, a cleaner-more efficient way?
Using a loop and statistics.mean
:
from statistics import mean
def analog_average(N):
measures = []
for _ in range(N):
measures.append(mcp_analog.value)
time.sleep(0.001)
return mean(measures)
print(analog_average(5))
This way you can easily change the amount of samples without having to add more and more lines of sleep
and analog
variables.