Parsing Serial commands

Hi all,

I am wondering how best to get information out of my serial strings that come through.

I have an xBee connected to my computer which will send commands to an Arduino connected to another xBee on the same network. The commands will have 3 values in them R0G0B0 to R1023G1023B1023. I would also like to be able to send only one command as well such as R512

How is the cleanest way to write code to process such variable input (Not always the same length)? I have done it in the past but the code has been unstable at best no error catching and did not always do what i wanted it to do. I have since lost the code in my computer some where.

Looking for some ideas on how to write the code so it is more stable

[quote author=Nick Gammon link=topic=128260.msg964600#msg964600 date=1350776006]


Thanks I will read through it later, the state machine seams to be what I am after

Unless you really want to write a parser, this is a good candidate application for Bitlash ( Put Bitlash on the remote Arduino and you can define and then send commands like:


Bitlash can handle all the parsing and call functions you write in Bitlash or in C to handle the commands. In this case, it looks like you might be controlling a tricolor LED, so the rgb() function might be a simple Bitlash function:

function rgb {a4=arg(1); a5=arg(2); a6=arg(3);}

(presuming you have the R, G, and B connected to PWM pins 4, 5, and 6).

Good luck with your project,


The problem with that is that I will be running a python program which sends the serial out over my xBee and it needs to be platform independent as I will be moving the code from my mac to a windows laptop

Puzzled by your comment, replying for clarification. People drive Bitlash programs from python all the time, from several platforms.

As an arduino sketch, Bitlash doesn't care / can't tell whether you send commands from python, from another language, from a keyboard with a terminal emulator, or from any of the above over a wireless link.

How could it tell, after all? It just sees the characters coming over the xbee serial interface and does what you say, whether you're at your mac or pc. Just like your hand-made parser will, if you go that route, but without the fun of coding the parser.



Sorry didnt read into it that well. I will read more about it tonight thnx