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
  • 5,292
  • 7
  • 30
  • 51
Luke Wood
  • 21
  • 2

0 Answers0