Help with smoothing

I’ve got a system setup that reads a temp sensor, and depending on temp sensor readings it will move a servo. The problem I’m having is that the servo gets very jittery. How can I work the smoothing example into my code? I see the example just writes to serial output. Here is my code for my control:

// Controlling a servo position using a temperature sensor 
// by Michal Rinott <http://people.interaction-ivrea.it/m.rinott> 
// edited 5-12-2010 by Will Lyon to include base setting for servo if voltage not detected on pin 7

#include <Servo.h> 
#define CONTROL 7

Servo myservo;  // create servo object to control a servo 
 
int temps = 0;  // analog pin used to connect the temp sensor
int val;        // variable to read the value from the analog pin
 
void setup() 
{ 
  pinMode (CONTROL, INPUT);       // sets the control pin to input
  myservo.attach(9);              // attaches the servo on pin 9 to the servo object
  digitalWrite(CONTROL, LOW);     // ensure internal pullup resistor is disabled.

} 
 
void loop()   
{
  val = digitalRead(CONTROL);         //read input of pin 7 and store it
  if (val == HIGH){                   // reads whether or not 5v is present on pin 7, if 5v present, continue:
  val = analogRead(temps);            // reads the value of the temp sensor (value between 0 and 1023) 
  val = map(val, 350, 700, 75, 105);  // scale it to use it with the servo (value between 0 and 180) 
  myservo.write(val);                 // sets the servo position according to the scaled value 
  delay(25);                          // waits for the servo to get there 
} else {
  if (val == LOW);                    // if no voltage present on pin 7, continue
  myservo.write(50);                  //sets servo position to 50 if no voltage is detected on pin 7
}
delay(25);        // waits for the servo to get there

}

Here is a link to my projects:
Fritzing setup: http://fritzing.org/projects/arduino-temperature-based-servo-control/
Worklog @ TheBestCaseScenario.com: TBCS Community Forums

Thanks in advance for the help!

Just a simple rolling average - take off, say one eighth of the sum, and add in one eighth of the new reading.

Hint:

  if (val == HIGH){} else {
...
...
  if (val == LOW);

if val isn't HIGH, there's no need to test to see if it's low.

take, say one eighth of the sum, and add in one eighth of the new reading.

Could you give an example of the code?

I mean, for a moving average don't you, somehow, have to subtract the oldest value from the sum and add the newest value?

That is: for a filter of length eight don't you need to keep the most recent eight samples in an array or some such thing?

Regards,

Dave

sum = (sum - (sum / 8)) + (analogRead (pin) / 8);

Or yes, you could maintain a history in an array.

Thank you.

Regards,

Dave