FRIENDz

FAILURE IS THE SIGN OF SUCCESS!!

Controlling Servos from the Serial Port

 Each servo line wire gets connected to a digital pin. All servo grounds are connected to Arduino ground. The servo power lines are connected together, and you may need an external 5V or 6V power source if your servos require more current than the Arduino power supply can provide. An array named myservo is used to hold references for the four servos. A for loop in setup attaches each servo in the array to consecutive pins defined in the servoPins array. If the character received from serial is a digit (the character will be greater than or equal to zero and less than or equal to 9), its value is accumulated in the variable pos. If the character is the letter a, the position is written to the first servo in the array (the servo connected to pin 7). The letters b, c, and d control the subsequent servos. 

You can use software to control the servos. This has the advantage that any number of servos can be supported. However, your sketch needs to constantly attend to refreshing the servo position, so the logic can get complicated as the number of servos increases if your project needs to perform a lot of other tasks.
This recipe drives four servos according to commands received on the serial port. The commands are of the following form:
• 180a writes 180 to servo a
• 90b writes 90 to servo b
• 0c writes 0 to servo c
• 17d writes 17 to servo d
Here is the sketch that drives four servos connected on pins 7 through 10:

#include <Servo.h> // the servo library
#define SERVOS 4 // the number of servos
int servoPins[SERVOS] = {7,8,9,10}; // servos on pins 7 through 10
Servo myservo[SERVOS];
void setup()
{
Serial.begin(9600);
for(int i=0; i < SERVOS; i++)
myservo[i].attach(servoPins[i]);
}

void loop()
{
serviceSerial();
}
// serviceSerial checks the serial port and updates position with received data
// it expects servo data in the form:
// "180a" writes 180 to servo a
// "90b writes 90 to servo b
void serviceSerial()
{
static int pos = 0;
if ( Serial.available()) {
char ch = Serial.read();
if(ch >= '0' && ch <= '9') // is ch a number?
pos = pos * 10 + ch - '0'; // yes, accumulate the value
else if(ch >= 'a' && ch <= 'a'+ SERVOS) // is ch a letter for our servos?
myservo[ch - 'a'].write(pos); // yes, save position in position array
}
}

No comments:

Post a Comment