
Arduino Controlling the Servo!
Housekeeping Blurb

Draganfly DF-06 Servo
Black -> Ground (0V)
Red -> Power (5V)
At the top of the Arduino there are several Digital Output pins. Let's plug the data cable (control) of Servo #1 into pin #7, and Servo #2 into pin #6. Let's define this in the code that will be loaded onto the Arduino:
int servo1 = 7;
int servo2 = 6;
While you're at it, we also have to define a few other things, myAngle and pulseWidth. There is one for each servo. The explanation of each will follow.
int myAngle1;
int myAngle2;
int pulseWidth1;
int pulseWidth2;
pulseWidth converts the angle to microseconds. You will definitely have to play around with this if you will be using different servos. I used trial and error to get the values to work for the Draganfly servos. I did try this with a Kondo servo, and it worked well! It all depends. Sometimes you may have to tinker with it, sometimes not.
Now, we have to have two methods that we can call in the loop. So, we will call them servoPulse1 and servoPulse2.
Here is the code for each:
*Note: This does not go into the void loop just yet!
void servoPulse1 (int servo1, int myAngle1) {
pulseWidth1 = (myAngle1 * 11) + 500; // Converts angle to microseconds
digitalWrite(servo1, HIGH); // Set servo high (turns it on)
delayMicroseconds(pulseWidth1); // Wait a very very small amount
digitalWrite(servo1, LOW); // Set servo low (turns it off)
delay(20); // Typical Refresh cycle of servo (20 ms)
}
void servoPulse2 (int servo2, int myAngle2) {
pulseWidth2 = (myAngle2 * 11) + 500; // Converts angle to microseconds
digitalWrite(servo2, HIGH); // Set servo high (turns it on)
delayMicroseconds(pulseWidth2); // Wait a very very small amount
digitalWrite(servo2, LOW); // Set servo low (turns it off)
delay(20); // Typical Refresh cycle of servo (20 ms)
}
What happens in this code? We change an angle into a pulse width, turn on the servo for the calculated time pulseWidth, then we turn the servo off!
Next is the void setup(). We just have to put our servo outputs here.
void setup() {
pinMode(servo1, OUTPUT);
pinMode(servo2, OUTPUT);
}
Now for the fun part - the loop! This is the main course of the meal, when it comes to the Arduino program. Here is the code, the explanation will follow!
void loop() {
for (myAngle1=0; myAngle1<=180; myAngle1++) {
myAngle1 = 100;
myAngle2 = 90;
servoPulse1(servo1, myAngle1);
servoPulse2(servo2, myAngle2);
}
}
Pretty neat stuff! It is now very simple for you to move your servo with Arduino. Basically, you just change myAngle1, call the servoPulse method, and your servo will move! I hope that this will help you more!
Please feel free to contact me if you have any further questions!
erin ~at~ robotgrrl.com OR you can message me on learnhub :)

Post Comments