Code to Control Servo via Potentiometer

This example shows the code to control a servo on digital pin 2 via a potentiometer on analog pin 0.

You can change the pins around via the variables in the beginning of the sketch.

[php]
#include <softwareservo.h>

SoftwareServo myservo; // create servo object to control a servo

int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin
int servopin = 2; //digital pin used to connect the servo

void setup()
{
myservo.attach(servopin); // attaches the servo on pin 2 to the servo object
Serial.begin(9600);
}

void loop()
{
val = analogRead(potpin); // reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 179); // scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15); // waits for the servo to get there

SoftwareServo::refresh();
Serial.println(val);
}[/php]

Author: Helicopter Jeff

I'm a vinyl decal cutting and designing, Astrophotography and general photography capturing, RC helicopter/quad copter pilot, Arduino and Raspberry Pi hardware/software developer, network, scripting and troubleshooting ninja living in the metro NY area. I am passionate about my hobbies so much I do them for a living. There's nothing better than getting paid to do what you love.

1 thought on “Code to Control Servo via Potentiometer”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s