Control 2 Servos With A Joystick - Code, Please Used On
Control 2 Servos With A Joystick - Code, Please Used On
#include <Servo.h> // Set this code included the “Servo library”, this library allows you to control
servo by using the command such as attach(); and write();. The library is the code other people
already wrote it and well tested, and #include <> is just call and using these code.
int Xpin = A0; // Assign the analog pin A0 for the integer value of joystick X-axis
int Ypin = A1; // Assign the analog pin A1 for the integer value of joystick Y-axis
int Spin = 13; // Assign the digital pin 13 for the integer value of joystick switch
int Xval; // Declare a integer value Xval, will define later
int Yval; // Declare a integer value Yval, will define later
int Sval; // Declare a integer value Sval, will define later
int DLay = 25; // Create a common integer delay time of 25ms
const int servoXPin = 3; // Constantly assign the pin 3 for the integer value of servo motor
const int servoYPin = 5; // Constantly assign the integer value for digital pin 5 for the second
servo motor
Servo servoX; // Create a Servo object to control the servo motor
Servo servoY; // Create another Servo object to control the second servo motor
const int buzzerPin = 7; // Constantly assign the digital pin 7 for the buzzer
void setup() {
Serial.begin(9600); // Let the baud rate in serial monitor use the port 9600(select 9600 baud
when running)
void loop() {
Xval = analogRead(Xpin); // Let the value from X-axis joystick equals to analog input from A0
Yval = analogRead(Ypin); // Let the value from Y-axis joystick equals to analog input from A1
Sval = digitalRead(Spin); // Read the value from joystick switch
delay(DLay);
int angleX = map(Xval, 0, 1023, 0, 180); // Convert the sensor value(0-1023) to servo angle
range(0-180)
int angleY = map(Yval, 0, 1023, 0, 180); // Convert the sensor value(0-1023) to servo angle
range(0-180)
servoX.write(angleX); // Move the servo motor to the position(0-180), position is base on
angleX
servoY.write(angleY); // Move the second servo motor to the position(0-180)
if (Sval == LOW) {
tone(buzzerPin, 3000); // Piezo play a 3000Hz tone
delay(1000); //Wait for 1000ms until the tone over
noTone(buzzerPin); //Stop the piezo keep play the tone
}