Advertisement
MrLunk

Avarage readings smoothing Arduino

Mar 24th, 2021 (edited)
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.31 KB | None | 0 0
  1. const int numReadings = 10; // Total number of readings to use for avaraging / smoothing
  2.  
  3. int readings; // the readings from the analog input
  4. int readIndex = 0; // the index of the current reading
  5. int total = 0; // the running total
  6. int average = 0; // the average
  7.  
  8. int inputPin = A0;
  9.  
  10. void setup() {
  11. Serial.begin(9600); // initialize serial communication with computer:
  12. for (int thisReading = 0; thisReading < numReadings; thisReading++) {
  13. readings = 0; // initialize all the readings to 0:
  14. }
  15. }
  16.  
  17. void loop() {
  18. total = total - readings; // subtract the last reading:
  19.  
  20. readings = analogRead(inputPin); // read the desired data from your sensor here...
  21.  
  22. total = total + readings; // add the reading to the total:
  23. readIndex = readIndex + 1; // advance to the next position in the array:
  24.  
  25. if (readIndex >= numReadings) { // if we're at the end of the array...
  26. readIndex = 0; // ...wrap around to the beginning:
  27. }
  28.  
  29. average = total / numReadings; // calculate the average:
  30.  
  31. Serial.println(average); // Print to serial monitor
  32. delay(1); // delay in between reads for stability
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement