OK, I finally got this working. Now I can feed in a serial string of 5 digits, say 03180, and it moves the servo at pin 3 to 180 degrees. Works on my mega for pins 2-19.
// zoomkat 12-13-11 serial servo (2) test
// for writeMicroseconds, use a value like 1500
// for IDE 1.0
// Powering a servo from the arduino usually DOES NOT WORK.
// two servo setup with two servo commands
// send five character string like 02180 to move servo pin 2 to 180 degrees or 19000 to move servo at pin 19 to 0 degrees
// use serial monitor to test
#include <Servo.h>
String readString, servoname, servo2;
Servo mys[20]; //Now we have 20 servos but only use 2-19 (ie 18 servos)
void setup() {
Serial.begin(115200);
for(int i=2; i<20; i++)
{
mys[i].attach(i); // was i+2
}
Serial.println("two-servo-test-1.0"); // so I can keep track of what is loaded
}
void loop() {
while (Serial.available()) {
delay(3); //delay to allow buffer to fill
if (Serial.available() >0) {
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
}
}
if (readString.length() >0) {
Serial.println(readString); //see what was received
// expect a string like 07180 containing the servo position and degrees
servoname = readString.substring(0, 2); //get the first two characters name
servo2 = readString.substring(2, 5); //get the next three characters
Serial.println(servoname); //print to serial monitor to see parsed results
Serial.println(servo2);
int n1 = servoname.toInt();
int n2 = servo2.toInt();
Serial.println("the numbers are :");
Serial.println(n1); //print to serial monitor to see number results
Serial.println(n2);
mys[n1].write(n2); //set servo position
readString="";
}
}