Advertisement
Guest User

Untitled

a guest
Aug 27th, 2015
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.08 KB | None | 0 0
  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.
  28. const int numReadings = 10;
  29.  
  30. int readings[numReadings]; // the readings from the analog input
  31. int index = 0; // the index of the current reading
  32. int total = 0; // the running total
  33. int average = 0; // the average
  34.  
  35. int inputPin = A0;
  36.  
  37. void setup()
  38. {
  39. // initialize serial communication with computer:
  40. Serial.begin(9600);
  41. // initialize all the readings to 0:
  42. for (int thisReading = 0; thisReading < numReadings; thisReading++)
  43. readings[thisReading] = 0;
  44. }
  45.  
  46. void loop() {
  47. // subtract the last reading:
  48. total= total - readings[index];
  49. // read from the sensor:
  50. readings[index] = analogRead(inputPin);
  51. // add the reading to the total:
  52. total= total + readings[index];
  53. // advance to the next position in the array:
  54. index = index + 1;
  55.  
  56. // if we're at the end of the array...
  57. if (index >= numReadings)
  58. // ...wrap around to the beginning:
  59. index = 0;
  60.  
  61. // calculate the average:
  62. average = total / numReadings;
  63. // send it to the computer as ASCII digits
  64. Serial.println(average);
  65. delay(1); // delay in between reads for stability
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement