In this lesson we show you how to precisely control the position of two servos using a joystick. We derive the math equations which will allow you to get smooth and precise control of the servo. We also add a buzzer to the project to create an audible alarm when the button the joystick is pressed.
If you want to follow along at home, you can order the Arduino Kit we are using HERE.
Typically, the servos in electronics kits are not the best ones, but are suitable to learn with. If you want a more stable and better quality servo, this is the one I user in more of my projects: HiTEC
Below is the code we developed in this project.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | #include <Servo.h> Servo Xservo; Servo Yservo; int Xpin=A0; int Ypin=A1; int Spin=2; int XSpin=9; int YSpin=10; int buzzPin=7; int WVx; int WVy; int Xval; int Yval; int Sval; int dt=200; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(Xpin,INPUT); pinMode(Ypin,INPUT); pinMode(Spin,INPUT); pinMode(XSpin,OUTPUT); pinMode(YSpin,OUTPUT); pinMode(buzzPin,OUTPUT); Xservo.attach(XSpin); Yservo.attach(YSpin); digitalWrite(Spin,HIGH); } void loop() { Xval=analogRead(Xpin); WVx=(180./1023.)*Xval; Yval=analogRead(Ypin); WVy=(180./1023.)*Yval; Sval=digitalRead(Spin); Xservo.write(WVx); Yservo.write(WVy); if (Sval==0){ digitalWrite(buzzPin, HIGH); } else { digitalWrite(buzzPin, LOW); } delay(dt); Serial.print("X Value = "); Serial.print(Xval); Serial.print(" Y Value = "); Serial.print(Yval); Serial.print(" Switch State is "); Serial.println(Sval); } |