In this project, we will learn how to control the position of a Servo Motor using a Potentiometer. By turning the knob of the potentiometer, we can precisely move the servo arm from 0 to 180 degrees.
How it Works
The Potentiometer acts as an analog input. The Arduino reads the voltage (0V to 5V) and converts it into a digital value between 0 and 1023. Since a servo motor moves between 0 and 180 degrees, we use the map() function in our code to convert the input value into a degree value.
Components Required
- Arduino Uno
- Servo Motor (e.g., SG90)
- Potentiometer (10k Ohm)
- Capacitors (100µF)
- Breadboard
- Jumper Wires
- External Power Supply (Recommended for servos to prevent Arduino resets)
Circuit and Connection (Step-by-Step)
Based on the wiring diagram:
- Potentiometer:
- Left Pin: Connect to GND.
- Middle Pin (Wiper): Connect to Arduino Analog Pin A0.
- Right Pin: Connect to 5V.
- Servo Motor:
- Brown/Black Wire: Connect to GND.
- Red Wire: Connect to Positive (+) of the Power Supply.
- Orange/Yellow Wire (Signal): Connect to Arduino Digital Pin 9.
- Power Supply:
- Ensure the GND of the external power supply is connected to the Arduino GND (Common Ground).
The Code
Copy and paste this code into your Arduino IDE:
#include <Servo.h>
Servo myservo; // Create servo object to control a servo
int potpin = 0; // Analog pin used to connect the potentiometer (A0)
int val; // Variable to read the value from the analog pin
void setup() {
myservo.attach(9); // Attaches the servo on pin 9 to the servo object
}
void loop() {
val = analogRead(potpin); // Reads potentiometer (0 to 1023)
val = map(val, 0, 1023, 0, 180); // Scale it for the servo (0 to 180)
myservo.write(val); // Move the servo to the scaled position
delay(15); // Small delay to allow the servo to move
}
Understanding the Code
#include <Servo.h>: This imports the library that allows Arduino to talk to the servo easily.analogRead(potpin): This reads the position of the knob.map(val, 0, 1023, 0, 180): This is the "brain" of the code. It converts the large potentiometer number into a servo angle.myservo.write(val): This sends the final angle command to the motor.
Troubleshooting Tips
- Servo Jittering: Ensure you are using a separate power supply. Small servos can pull more current than the Arduino's USB port can handle.
- No Movement: Double-check the "Common Ground" (connecting external GND to Arduino GND).