3

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 simplifies 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 easily 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 seems 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 seems to get into the loops or will get it to one and not the other. Sometimes I can tweak it to get into all of them to switch the LED on, but then won't turn it off or vice-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.

Transistor
  • 168,990
  • 12
  • 186
  • 385
Ashley Hughes
  • 1,225
  • 4
  • 19
  • 25

2 Answers2

3

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
2

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.

tcrosley
  • 47,708
  • 5
  • 97
  • 161
  • 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