Skip to content

Commit 98e17d7

Browse files
authored
Create Smoothing.py
1 parent 99e4738 commit 98e17d7

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

03.Analog/Smoothing.py

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Smoothing
3+
4+
Reads repeatedly from an analog input, calculating a running average and
5+
printing it to the computer. Keeps ten readings in an array and continually
6+
averages them.
7+
8+
The circuit:
9+
- analog sensor (potentiometer will do) attached to GPIO34
10+
"""
11+
from machine import Pin, ADC
12+
from time import sleep
13+
14+
# Define the number of samples to keep track of. The higher the number, the
15+
# more the readings will be smoothed, but the slower the output will respond to
16+
# the input. Using a constant rather than a normal variable lets us use this
17+
# value to determine the size of the readings array.
18+
numReadings = 10
19+
20+
21+
readings = [0] * numReadings # the readings from the analog input
22+
readIndex = 0 # the index of the current reading
23+
total = 0 # the running total
24+
average = 0 # the average
25+
26+
pot = ADC(Pin(34))
27+
pot.atten(ADC.ATTN_11DB)
28+
29+
print(readings)
30+
31+
while True:
32+
#subtract the last reading:
33+
total = total - readings[readIndex]
34+
#read from the sensor:
35+
readings[readIndex] = pot.read()
36+
#add the reading to the total:
37+
total = total + readings[readIndex]
38+
#advance to the next position in the array:
39+
readIndex = readIndex + 1
40+
41+
#if we're at the end of the array...
42+
if (readIndex >= numReadings):
43+
#wrap around to the beginning:
44+
readIndex = 0
45+
46+
#calculate the average:
47+
average = total / numReadings
48+
#send it to the computer as ASCII digits
49+
print(average)
50+
sleep(0.1) # delay in between reads for stability

0 commit comments

Comments
 (0)