| 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 analog input 0 |
| 10 |
|
| 11 |
created 22 Apr 2007 |
| 12 |
by David A. Mellis <[email protected]> |
| 13 |
modified 9 Apr 2012 |
| 14 |
by Tom Igoe |
| 15 |
|
| 16 |
This example code is in the public domain. |
| 17 |
|
| 18 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Smoothing |
| 19 |
*/ |
| 20 |
|
| 21 |
// Define the number of samples to keep track of. The higher the number, the |
| 22 |
// more the readings will be smoothed, but the slower the output will respond to |
| 23 |
// the input. Using a constant rather than a normal variable lets us use this |
| 24 |
// value to determine the size of the readings array. |
| 25 |
const int numReadings = 10; |
| 26 |
|
| 27 |
int readings[numReadings]; // the readings from the analog input |
| 28 |
int readIndex = 0; // the index of the current reading |
| 29 |
int total = 0; // the running total |
| 30 |
int average = 0; // the average |
| 31 |
|
| 32 |
int inputPin = A0; |
| 33 |
|
| 34 |
void setup() { |
| 35 |
// initialize serial communication with computer: |
| 36 |
Serial.begin(9600); |
| 37 |
// initialize all the readings to 0: |
| 38 |
for (int thisReading = 0; thisReading < numReadings; thisReading++) { |
| 39 |
readings[thisReading] = 0; |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
void loop() { |
| 44 |
// subtract the last reading: |
| 45 |
total = total - readings[readIndex]; |
| 46 |
// read from the sensor: |
| 47 |
readings[readIndex] = analogRead(inputPin); |
| 48 |
// add the reading to the total: |
| 49 |
total = total + readings[readIndex]; |
| 50 |
// advance to the next position in the array: |
| 51 |
readIndex = readIndex + 1; |
| 52 |
|
| 53 |
// if we're at the end of the array... |
| 54 |
if (readIndex >= numReadings) { |
| 55 |
// ...wrap around to the beginning: |
| 56 |
readIndex = 0; |
| 57 |
} |
| 58 |
|
| 59 |
// calculate the average: |
| 60 |
average = total / numReadings; |
| 61 |
// send it to the computer as ASCII digits |
| 62 |
Serial.println(average); |
| 63 |
delay(1); // delay in between reads for stability |
| 64 |
} |