Serial nested if statements (Not working)

I have been trying to get this to work for a few days.

What i have at the moment is TouchOSC installed on my Iphone sending commands to a processing program, which in turn simplify's them and sends them off to my arduino through serial.

This is where my problem is the commands get there and I can print them out easy enough. They arrive correctly. Format is t11 or t10 (t for toggle control, then # for id of control changed, the last # is on or off (1 or 0)

Now when I try and break this down with if statements it never seams to work. I know the data is correct when it gets to the arduino.

I need to test if the first char is a 't' simple if statement

if(Serial.read() == 't')


before this i test if

Serial.available()


is true then through similar if statements i test if next is the number '1' or '2' for the control id, then if number is on or off, '1' or '2'

When i test this in Serial monitor or with real data off my phone never seam to get into the loops or will get it to one and not the other. Some times i can tweak it to get into all of them to switch the LED on, but then won't turn it off or vica-versa

Can anyone please give me an example of the logic that i need to use, i have also tried using switch statements for the ID doesn't seam to make much difference

Thanks

• Can you post the code for your parser? – Toby Jaffey Jul 15 '10 at 8:55

Without seeing your code I'm taking a guess, but I suspect that you are entering into the code to parse before you have a full serial command available. So sometimes there's only 1 byte available and sometimes all 3 are there, hence the unpredictable behavior.

I would change the first test to the following:

if (Serial.available() >= 3)


Which will wait until you have an entire command present before doing all the tests.

/y

• That works perfectly. Thanks for the explaintion as well. I now know it was acting before the whole serial message arrived. So much headache for something so simple – Ashley Hughes Jul 15 '10 at 20:37

Although I'm not familiar with Arduino programming, if you have a series of if statements like if(Serial.read() == 't') then I believe the first one probably is gobbling up the character from the serial port, and in then the next test if(Serial.read() == '1') the port will be empty and the character gone.

Instead, you want to save the character in a variable, and then test the variable:

ch = Serial.read(); if (ch == 't') ... else if (ch == '1') ...

etc.

• Agreed, it is never a good idea to read in the if statement. Best to wait for a command to be available and read it into blocks so you can reuse them in further tests. Especially if you end up doing if (Serial.read() == 't') ... if (Serial.read() == 'x') .... where the second read would contain a number from the command and no longer the command character. – Wouter Simons Jul 16 '10 at 13:48