source: arduino-1-6-7/trunk/fuentes/arduino-ide-amd64/examples/03.Analog/Smoothing/Smoothing.ino @ 46

Last change on this file since 46 was 46, checked in by jrpelegrina, 4 years ago

First release to Xenial

File size: 1.9 KB
Line 
1/*
2
3  Smoothing
4
5  Reads repeatedly from an analog input, calculating a running average
6  and printing it to the computer.  Keeps ten readings in an array and
7  continually averages them.
8
9  The circuit:
10    * Analog sensor (potentiometer will do) attached to analog input 0
11
12  Created 22 April 2007
13  By David A. Mellis  <dam@mellis.org>
14  modified 9 Apr 2012
15  by Tom Igoe
16  http://www.arduino.cc/en/Tutorial/Smoothing
17
18  This example code is in the public domain.
19
20
21*/
22
23
24// Define the number of samples to keep track of.  The higher the number,
25// the more the readings will be smoothed, but the slower the output will
26// respond to the input.  Using a constant rather than a normal variable lets
27// use this value to determine the size of the readings array.
28const int numReadings = 10;
29
30int readings[numReadings];      // the readings from the analog input
31int readIndex = 0;              // the index of the current reading
32int total = 0;                  // the running total
33int average = 0;                // the average
34
35int inputPin = A0;
36
37void setup() {
38  // initialize serial communication with computer:
39  Serial.begin(9600);
40  // initialize all the readings to 0:
41  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
42    readings[thisReading] = 0;
43  }
44}
45
46void loop() {
47  // subtract the last reading:
48  total = total - readings[readIndex];
49  // read from the sensor:
50  readings[readIndex] = analogRead(inputPin);
51  // add the reading to the total:
52  total = total + readings[readIndex];
53  // advance to the next position in the array:
54  readIndex = readIndex + 1;
55
56  // if we're at the end of the array...
57  if (readIndex >= numReadings) {
58    // ...wrap around to the beginning:
59    readIndex = 0;
60  }
61
62  // calculate the average:
63  average = total / numReadings;
64  // send it to the computer as ASCII digits
65  Serial.println(average);
66  delay(1);        // delay in between reads for stability
67}
68
69
Note: See TracBrowser for help on using the repository browser.