You'll need to modify the VB application to send more data. Currently it sends the value as a string, apparently. If the VB application sends data as the mouse moves, it might send
'1', '5', '6', 1', '5', '8', '1', '4', 9'...
In that data stream, where does one value begin and end? Is the data supposed to represent 15, 61, 58, 14, 9 or 156, 158, 149?
Change the VB app. to send '<', '1', '5', '6', '>', '<', '1', '5', '8', '>', '<', '1', '4', 9', '>'.... This way, there is no ambiguity.
Then, do something like this on the Arduino:
int servoValue = 0;
char inData[12];
int index = 0;
bool started = false;
bool ended = false;
void loop()
{
if(Serial.available() > 0)
{
while(Serial.available() > 0)
{
char aChar = Serial.read();
if(aChar == '<')
{
index = 0;
inData[index] = '\0'; // Null out the array
started = true;
ended = false;
}
if(aChar != '>' && started && !ended)
{
inData[index] = aChar;
index++;
inData[index] = '\0';
}
if(aChar == '>')
{
ended = true;
started = false;
}
if(ended && !started)
{
servoValue = atoi(inData);
// Move the servo
// Wait for it to get there
ended = false; // Set up for the next packet
}
}
}
}
This code uses two flags, started and ended, to indicate whether we have encountered a start of data marker and and end of data marker.
If the character is a start of data marker, started is set to true, and the array is initialized.
If the character is an end of data marker, started is set to false, and ended is set to true. This means that we can now use the data received, because we know it is complete.
If the character is not an end of data marker, and we have received a start of data marker, the character is added at the end of the string, the pointer is advanced, and the string is (again) properly terminated.
If an end of data marker has been received (ended is true and started is false), we move the servo, and set the flags to false.
Try out various data loss scenarios, and you'll see that a dropped start of data marker is handled properly - the next one starts the process of receiving data again. An end of data marker loss is handled the same way.
The only thing that is not handled is a dropped character between start and end of data markers. That could be handled by making the payload look like:
numberOfcharacters:validCharacters
An example:
<3:156>
Then, the received string should look like '3', ':', '1', '5', '6', NULL. You could then convert the value before the : to an integer, 3, and then make sure that there are 3 characters after the :. This is probably more than you really need to deal with, though, for this simple application.