Hello everybody,
Although getting data from the Serial port seems to be quite straightforward, I'm still having issues with that. This post is a split of another post (http://forum.arduino.cc/index.php?topic=176890.0)
I want to receive commands on the serial port, coming from a Windows application. Before parsing the command, I must be able to receive many commands. In order to do that, all commands are ended with "^" -> When I find the terminator, I process the incoming command and afterwards I get the new command from the serial port.
The sample below is the part of code retrieving data from the serial port.
Using the Serial Monitor, my test case is:
a=1^b=2^c=3^d=4^e=5^f=6^g=7^h=8^i=9^j=10^k=11^l=12^m=13^n=14^o=15^p=16^q=17^r=18^s=19^t=20^u=21^v=22^w=23^x=24^y=25^z=26^
Here is the code:
#define COMMAND_SUFFIX '^'
const int SERIAL_BUFFER_SIZE = 512; // make it big enough to hold your longest command
char serialBuffer[SERIAL_BUFFER_SIZE + 1]; // +1 allows space for the null terminator
int serialBufferOffset = 0; // number of characters currently in the buffer
void setup()
{
Serial.begin(9600);
}
void loop()
{
if(serialRead())
{
Serial.print("- Incoming command: ");
Serial.println(serialBuffer);
}
}
boolean serialRead()
{
boolean rc = false;
char c;
while(Serial.available())
{
c = Serial.read();
switch(c)
{
case '\r':
case '\n':
// Discard special characters
break;
case COMMAND_SUFFIX:
// End-of-command received
serialBufferOffset = 0;
rc = true;
break;
default:
if(serialBufferOffset < SERIAL_BUFFER_SIZE)
serialBuffer[serialBufferOffset++] = c;
serialBuffer[serialBufferOffset] = '\0';
break;
}
}
return rc;
}
And here is the result:
- Incoming command: a=1
- Incoming command: b=2
- Incoming command: c=3
- Incoming command: d=4
- Incoming command: j=1
- Incoming command: o=1
- Incoming command: t=2
- Incoming command: y=2
- Incoming command: z=26
What am I doing wrong??? I'm completely lost...
Thanks for your help
Serge