Proximity Sensor Converting to Servo (Jerky Pings)

Hi all,

I am trying to use a ultrasonic sensor to rotate a servo motor (as you get closer the motor rotates one way and as you get farther it rotates the other way)

So far this definition i made works, however it picks up some random pings that are either really far or close which makes the servo jerky

any help please??

// ---------- included libraries ------------
#include <Servo.h>
#include <NewPing.h>

// ---------- hardware pin defines -----------
int triggerPin = 12; // select the pin for ultrasonic trigger
int echoPin = 11; // select the pin for echo

// ---------- variable initialization -----------
int delayTime = 0; //variable that holds the delay time in milliseconds
int scaling = 1;
unsigned int uS = 0; // holds the time it took for the pulse to be recived
unsigned int distance = 0; // holds the distance in centimeters
int maxValue = 100; // in centimeter
int minValue = 0; // in centimeter
int maxDistance = 250; // in centimeters
int angle;

// ---------- library initialization -----------
Servo myservo; // create servo object to control a servo a maximum of eight servo objects can be created
NewPing sonar(triggerPin, echoPin, maxDistance);

void setup() {
Serial.begin(9600);
// declare hardware connections
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}

void loop() {
// Input
delay(29); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
distance = uS / US_ROUNDTRIP_CM; // convert time to distance
// Debugging
Serial.print("uS value: "); Serial.println(uS);
Serial.print("Distance (cm): "); Serial.println(distance);

// Processing
//Scaling
angle = map (distance, minValue, maxValue, 0, 80);
Serial.print(", angle: "); //print outs the servo angle
Serial.println(angle); //writes the word “angle”
myservo.write(angle); // sets the servo position according to the scaled value
delay(105);
}

Please don't cross-post; it wastes time.

Please do use code tags.

delay(29);  // Wait 50ms between pings

Comments that don't agree with the code are also a waste of time.

however it picks up some random pings that are either really far or close which makes the servo jerky

Median filter?

sorry I'm totally new to this, what is cross posting? and median filter would be great but how would I write one?

I tried and if statement but that was not working.

thanks again I appreciate it

Cross-posting is posting the same question in different parts of the forum

It wastes time. Don't do it.

but that was not working

That's probably the most hated phrase around here. What does it mean?

It means i was not writing the code correctly and I did not save it to show you, could you please tell me how I would go about writing a median code for the pings?

Take an odd number of readings. Sort them. Take the (n / 2) + 1 reading

thanks!