2

I would just like to start off by saying that I am new to Arduino so my code and approach to the wanted outcome are probably not the best. Anyway, I had the idea of using an ultrasonic sensor and my hand to act as a potentiometer to control the position of a servo. So, I wired everything up and wrote the code but the Servo just jitters around and doesn't move the way I wanted it to. The serial readings are fine, it is just that the servo isn't responding the way I hoped. Here is the code

#include <Servo\Servo.h>
#define echoPin 7
#define trigPin 8

int maximumRange = 400;
int minimumRange = 0;
int angle;
long duration, distance;
Servo myServo;

void setup()
{
    Serial.begin(9600);
    pinMode(echoPin, INPUT);
    pinMode(trigPin, OUTPUT);
    myServo.attach(9);
}

void loop()
{
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);

    distance = duration / 58.2;

    angle = map(distance, minimumRange, maximumRange, 0, 179);
    Serial.print("Distance = ");
    Serial.print(distance);
    Serial.print(" Angle = ");
    Serial.println(angle);
    myServo.write(angle);
    delay(50);
}

If anyone can help, it would be appreciated if you could post what is wrong with my code and how to fix it.

Note: I'm using Visual Studio instead of the Arduino IDE, so that is why it says #include <Servo\Servo.h> at the top.

The Guy with The Hat
  • 4,962
  • 7
  • 28
  • 51
Luke Wood
  • 21
  • 2
  • WHat does the serial monitor display? Do you have frequent small variations of angles? If yes, that would explain the servo jittering. The solution is then to somehow smoothen the angle to avoid small angle variations. The fact is that the ultrasonic sensor will not give the exact same value everytime, event if the distance does not change. – jfpoilpret Nov 09 '14 at 14:56
  • This question http://arduino.stackexchange.com/questions/4135/arduino-starter-kit-servo-is-shaking may be related to your problem, check its answers. – jfpoilpret Nov 09 '14 at 14:59
  • what servo are you using? – Treesrule14 Nov 10 '14 at 18:37

0 Answers0