Arduino Nano, serial communication, servo speed control problem

Here is a demo that receives a position and speed from the serial port and sets a servo to the position at the speed. The code uses methods and code from the serial input basics tutorial and the MobaTools servo library. This code does not use the String class and has been tested on real hardware.

// by groundFungus aka c. goulding

#include <MobaTools.h>

const int servoPin   = 3 ;  // The servo is connected to this pin

const byte numChars = 12;
char receivedChars[numChars];   // an array to store the received data

MoToServo servo;

boolean newData = false;

int position;
int speed;

void setup()
{
   Serial.begin(115200);
   Serial.println("<Arduino is ready>  Enter servo position and speed separated by a comma");
   Serial.println("Like 120,20");
   Serial.println("Set serial monitor line endings to Newline or Both");
   servo.attach(servoPin);
}

void loop()
{
   recvWithEndMarker();
   showNewData();
   if (newData)
   {
      parseData();
      servo.setSpeed( speed );
      servo.write(position);
      newData = false;
   }
}

void recvWithEndMarker()
{
   static byte ndx = 0;
   char endMarker = '\n';
   char rc;

   while (Serial.available() > 0 && newData == false)
   {
      rc = Serial.read();
      if (rc == '\r') // ignore carruage return
      {
         return;
      }
      if (rc != endMarker)
      {
         receivedChars[ndx] = rc;
         ndx++;
         if (ndx >= numChars)
         {
            ndx = numChars - 1;
         }
      }
      else
      {
         receivedChars[ndx] = '\0'; // terminate the string
         ndx = 0;
         newData = true;
      }
   }
}

void showNewData()
{
   if (newData == true)
   {
      Serial.print("This just in ... ");
      Serial.println(receivedChars);
      //newData = false;
   }
}

void parseData()
{
   char *strings[2]; // an array of pointers to the pieces of the above array after strtok()
   char *ptr = NULL; byte index = 0;
   ptr = strtok(receivedChars, ",");  // delimiters, comma
   while (ptr != NULL)
   {
      strings[index] = ptr;
      index++;
      ptr = strtok(NULL, ",");
   }
   //Serial.println(index);
   // print all the parts
   Serial.println("The Pieces separated by strtok()");
   for (int n = 0; n < index; n++)
   {
      Serial.print("piece ");
      Serial.print(n);
      Serial.print(" = ");
      Serial.println(strings[n]);
   }
   // convert string data to numbers
   position = atoi(strings[0]);
   speed = atoi(strings[1]);

   Serial.print("position = ");
   Serial.print(position);
   Serial.print("   speed = ");
   Serial.print(speed);

   //newData = false;
}

The MobaTools library is available for installation via the IDE library manager.

See the MobaTools instructions document for explanation of the setSpeed() function.