refining the input from a HC SR04 sensor to a servo

i am attempting to move a servo relative to the input from a HC SR04 sensor.

i have adapted some code from the new ping library and added a couple of lines myself (still a newbe)

the servo moves but erratically and not always in relation to the distance (i.e the sensor max range has been set to 100 cms, therefore i want the servo to go from 0 - 180 degrees as i move closer to the sensor) any ideas?

#include <Servo.h>
#include <NewPing.h>

#define TRIGGER_PIN  13  // Arduino pin tied to trigger pin on the Ultrasonic sensor
#define ECHO_PIN     12  // Arduino pin tied to echo pin on the Ultrasonic sensor
#define MAX_DISTANCE 100 // Sets the maximum ping range (in Centimeters)

Servo myservo;
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance

void setup()
{
  Serial.begin(9600);
  myservo.attach(7);
}

void loop(){
  delay(50);
  int uS = sonar.ping();
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");
  int servo = map (uS, 0, 100, 0, 255);
  myservo.write(uS);
}

thanks for looking (and not laughing to hard)

regards

Martin

the servo moves but erratically and not always in relation to the distance

Probably because your code has issues.

  int uS = sonar.ping();
  Serial.print("Ping: ");
  Serial.print(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  Serial.println("cm");

Oh, look. Serial output that you didn't share.

int servo = map (uS, 0, 100, 0, 255);

Map the value from the ping sensor to 0 to 255, assuming it is in the range 0 to 100. What happens if it isn't in the range 0 to 100? The output won't be in the range 0 to 255.

  myservo.write(uS);

Not that it matters, since you are not using the output from the map function. Waste to time doing the mapping, isn't it?

@mgodsell1973, have you tried a "sweep" program to ensure the servo works the way you expect?