Hi, I'm building a simple project where a servo is supposed to move based on the distance of an Ultrasonic sensor. The Ultrasonic values I get are quite 'jumpy' moving around between the real value and very high ones in a sort of a glitch.
If I simply allow the servo to move based on the Ultrasonic value I get, the servo keeps jumping back and forth in an uncontrollable way.
I've written the sketch below to try and overcome this problem. In essence I'm limiting the input to be up to 25 cm and checking that the distance between the reads is not greater than 5 cm. It works ok, but still not very smooth. the servo is a bit jittery.
Any ideas on how to improve this, preferably without going into complicated maths (e.g. take 10 sample reads and calculate the average etc.).
This is a code that I'm creating to teach kids ages 10-14, so I want to keep it as simple as possible.
#include "Ultrasonic.h"
#include <Servo.h>
Servo myservo;
Ultrasonic ultrasonic( 12, 13 ); //Using HC-SR04 Ultrasonic sensor. Trig connected to pin 12 and Echo to pin 13
int dis = 0;
int servoPin = 8;
int pos = 0;
int prevDis = 0;
void setup()
{
Serial.begin( 9600 );
myservo.attach(servoPin); //Start servo
}
void loop()
{
dis = ultrasonic.distanceRead(); //Get a read from the Ultrasonic sensor
if (dis <= 25 && (prevDis >= dis + 5 || prevDis >= dis - 5)) {
pos = map (dis, 3, 25, 0, 360); //Normalise distance values to suit the degrees of the servo engine
}
Serial.print( dis ); //Print values to serial monitor
Serial.print( " CM " );
Serial.print( prevDis );
Serial.print( " PREV " );
Serial.print( pos );
Serial.println( " POS" );
myservo.write(pos); //Change the servo to the location based on the distance
delay(50); //Provide a short delay to allow servo to get to the right position
prevDis = dis; //Set prev distance variable to equal the current distance for the next read
}
Thanks in advance!