This method may be superior.
[code]
// Example 5 - Receive with start- and end-markers combined with parsing
const byte numChars = 32;
char receivedChars[numChars];
char tempChars[numChars]; // temporary array for use when parsing
// variables to hold the parsed data
int firstIntegerFromPC = 0;
int secondIntegerFromPC = 0;
// int floatFromPC = 0.0;
boolean newData = false;
// my servo addition
#include <Servo.h>
Servo mys[20]; //Now we have 20 servos but only use 2-19 (ie 18 servos)
//
//============
void setup() {
Serial.begin(9600);
Serial.println("This demo expects 2 pieces of data - two integers");
Serial.println("Enter data in this style <1, 180> ");
Serial.println();
// my addition
for(int i=2; i<20; i++)
{
mys[i].attach(i); // was i+2
}
// end my addition
}
//============
void loop() {
recvWithStartEndMarkers();
if (newData == true) {
strcpy(tempChars, receivedChars);
// this temporary copy is necessary to protect the original data
// because strtok() used in parseData() replaces the commas with \0
parseData();
showParsedData();
servoMove();
newData = false;
}
}
//============
void recvWithStartEndMarkers() {
static boolean recvInProgress = false;
static byte ndx = 0;
char startMarker = '<';
char endMarker = '>';
char rc;
while (Serial.available() > 0 && newData == false) {
rc = Serial.read();
if (recvInProgress == true) {
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
recvInProgress = false;
ndx = 0;
newData = true;
}
}
else if (rc == startMarker) {
recvInProgress = true;
}
}
}
//============
void parseData() { // split the data into its parts
char * strtokIndx; // this is used by strtok() as an index
strtokIndx = strtok(tempChars,","); // get the first part - the string
// tim comments out strcpy(firstIntegerFromPC, strtokIndx); // copy it to firstIntegerFromPC
firstIntegerFromPC = atoi(strtokIndx); // my addition convert first part to an integer
strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
secondIntegerFromPC = atoi(strtokIndx); // convert this part to an integer
// Tim comments out strtokIndx = strtok(NULL, ",");
// Tim comments out floatFromPC = atof(strtokIndx); // convert this part to a float
}
//============
void showParsedData() {
Serial.print("Servo Number ");
Serial.println(firstIntegerFromPC);
Serial.print("Degrees movement ");
Serial.println(secondIntegerFromPC);
// Serial.print("Float ");
// Serial.println(floatFromPC);
}
void servoMove() {
// start my addition
mys[firstIntegerFromPC].write(secondIntegerFromPC); //write servo position
// end my addition
}
[/code]