Introduction
This experiment demonstrates how to control a servo motor using a joystick. The joystick's movement will determine the servo's angle, allowing precise position control.
Components Needed
- Arduino (e.g., Uno, Nano)
- Analog joystick module
- Servo motor
- Breadboard and jumper wires
- External 5V power supply (if required for the servo)
Circuit Setup
Connect the joystick and servo motor to the Arduino as follows:
- Joystick Connections:
- VCC to Arduino 5V
- GND to Arduino GND
- VRx to Arduino A0
- Servo Motor Connections:
- Signal wire to Arduino pin 9
- Power (red) to Arduino 5V (or external 5V supply if required)
- Ground (black) to Arduino GND
Code for Joystick-Controlled Servo
Upload the following code to your Arduino to control the servo using the joystick:
// Include the Servo library
#include
// Create a Servo object
Servo myServo;
// Define the joystick's X-axis pin
#define JOYSTICK_X A0
void setup() {
myServo.attach(9); // Attach the servo to pin 9
Serial.begin(9600); // Initialize serial communication
}
void loop() {
int joystickValue = analogRead(JOYSTICK_X); // Read the joystick X-axis
int servoAngle = map(joystickValue, 0, 1023, 0, 180); // Map joystick value to servo angle
myServo.write(servoAngle); // Set the servo to the mapped angle
// Print joystick value and servo angle for debugging
Serial.print("Joystick: ");
Serial.print(joystickValue);
Serial.print(" | Servo Angle: ");
Serial.println(servoAngle);
delay(20); // Small delay for stability
}
Explanation
analogRead()
: Reads the joystick's X-axis position as an analog value (0-1023).map()
: Converts the joystick value into a corresponding servo angle (0° to 180°).myServo.write()
: Commands the servo to move to the specified angle.- The joystick's central position maps to 90°, with extremes mapping to 0° or 180°.
Troubleshooting
- If the servo doesn’t move, verify the power supply and signal connections.
- Ensure the joystick is properly connected and functioning by checking the Serial Monitor.
- If the servo vibrates or makes noise, use an external power supply to ensure sufficient current.
Applications
Joystick-controlled servos can be used in:
- Robotic arms
- Camera gimbals
- Remote-controlled vehicles