Last active
March 18, 2017 18:57
-
-
Save erspark2002/724b9a9364de80f596a7af2bc18665e1 to your computer and use it in GitHub Desktop.
Arduino - Joystick controlling 2 Servos using the X-Axis and Y-Axis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Servo.h> | |
/* | |
Wiring Guides | |
Servos | |
http://www.instructables.com/id/Arduino-Servo-Motors/?ALLSTEPS | |
Check the Rotation of each servo in degrees. Search for your model number on servodatabase.com | |
eg. http://www.servodatabase.com/servo/futaba/s3003 | |
0-60 degrees | |
Joystick | |
https://brainy-bits.com/blogs/tutorials/arduino-joystick-tutorial | |
*/ | |
// Arduino pin numbers | |
const int SW_pin = 2; // digital pin connected to switch output | |
const int X_pin = 0; // analog pin connected to X output | |
const int Y_pin = 1; // analog pin connected to Y output | |
// define 2 servos. | |
Servo servo; | |
Servo servoB; | |
const int PIN_BUTTON = 6; | |
const int PIN_SERVO = 9; | |
const int PIN_SERVO_B = 10; | |
// default servo position for each. | |
int position = 1500; | |
int prevButtonState = HIGH; | |
int currentButtonState = HIGH; | |
int getXaxis() { | |
Serial.print(digitalRead(SW_pin)); | |
Serial.print("\n"); | |
Serial.print("X-axis: "); | |
Serial.print(analogRead(X_pin)); | |
return analogRead(X_pin); | |
} | |
int getYaxis() { | |
Serial.print(digitalRead(SW_pin)); | |
Serial.print("\n"); | |
Serial.print("Y-axis: "); | |
Serial.print(analogRead(Y_pin)); | |
return analogRead(Y_pin); | |
} | |
void setup() { | |
//button - not used ATM | |
pinMode(PIN_BUTTON, INPUT_PULLUP); | |
//joystick setup | |
pinMode(SW_pin, INPUT); //2 | |
digitalWrite(SW_pin, HIGH); // sets value to 1 | |
Serial.begin(9600); | |
//servo setup | |
servo.attach(PIN_SERVO); | |
servo.writeMicroseconds(position); | |
servoB.attach(PIN_SERVO_B); | |
servoB.writeMicroseconds(position); | |
} | |
int xPos = -1; | |
int yPos = -1; | |
void loop() { | |
xPos = getXaxis (); | |
yPos = getYaxis (); | |
//0 - 60 degrees | |
int servoPosition = xPos / 17; // divide joystick reading (0-1023) by 17 to convert max of 1023 to max of 60 degrees for servo. | |
int servoPositionB = yPos / 17; | |
servo.write(servoPosition); | |
servoB.write(servoPositionB); | |
// Testing the servo by hardcoding values | |
//servo.write(0); //0 degrees | |
// delay(1000); | |
//servo.write(30); //30 degrees | |
// delay(1000); | |
//servo.write(60); //60 degrees | |
// delay(1000); | |
// servo.writeMicroseconds(xPos); | |
delay(100); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment