Introduction
In this experiment, you’ll learn how to control the position of a servo motor using a potentiometer. The potentiometer acts as an input, allowing you to vary the servo's position by adjusting the potentiometer's knob.
Components Needed
Circuit Setup
- Connect the middle pin of the potentiometer to the Arduino's analog input pin A0.
- Connect one of the side pins of the potentiometer to the 5V pin on the Arduino and the other side pin to GND.
- Connect the servo motor's Signal pin to digital pin 9 on the Arduino.
- Connect the servo motor's VCC pin to the breadboard power supply.
- Connect the servo motor's GND pin to the breadboard power supply's GND.
- Ensure the Arduino GND and the breadboard power supply GND are connected together.
Note: Always power the servo motor using an external power supply, as driving it directly from the Arduino's 5V pin may cause instability or damage to the Arduino.
Code for Potentiometer-Controlled Servo
Upload the following code to your Arduino to control the servo position with the potentiometer:
// Include the Servo library
#include
Servo myServo; // Create a Servo object
const int potPin = A0; // Analog pin for the potentiometer
void setup() {
myServo.attach(9); // Attach the servo to digital pin 9
}
void loop() {
// Read the potentiometer value (0 - 1023)
int potValue = analogRead(potPin);
// Map the potentiometer value to a range for the servo (0 - 180 degrees)
int angle = map(potValue, 0, 1023, 0, 180);
// Set the servo to the calculated angle
myServo.write(angle);
delay(15); // Small delay to allow the servo to reach the position
}
Explanation
The potentiometer acts as an input device that provides a variable resistance based on its position. By reading the analog value from the potentiometer, we can control the servo position as follows:
- The potentiometer reading (0–1023) is mapped to the servo's range of 0–180 degrees.
- The
map()
function adjusts the potentiometer's value to match the servo’s range. - The servo motor is then positioned to the mapped angle, which corresponds to the potentiometer’s position.
Troubleshooting
- If the servo doesn't move, check the wiring and ensure the servo is connected to the correct pins.
- Ensure the servo is powered by the breadboard power supply and not directly by the Arduino.
- If the potentiometer seems unresponsive, ensure it's connected to the correct analog input pin.
- Double-check that the Arduino GND and the external power supply GND are connected.