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.

#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

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


One thought on “Code to Control Servo via Potentiometer

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s