Go Down

Topic: Moving array variables (Read 1 time) previous topic - next topic

Dogsbody

Apr 27, 2012, 01:38 am Last Edit: Apr 27, 2012, 01:45 am by Dogsbody Reason: 1
I'm reading a string of characters from serial but I'm only interested in one byte of data.  I thought the most efficient way to do this was to use an array of 3 chars (char c[2];) and look for my byte based on the bytes either side...

Code: [Select]
while (Serial.available() > 0) {
  c[0] = Serial.read();
  if (c[2] == 'P' && c[0] == 'V') {
   if (bitRead(c[1],0) == 0) {
     // do some stuff here
     }
   }
 c[2] = c[1];
 c[1] = c[0];
}


My code doesn't work.  The last two lines are breaking it but I can't see what I'm doing wrong.  I'm sure it's something basic.

Please help.

Thank you.

RoyK

you're missing a } at the very end

Dogsbody

Sorry, no, that was just be copy/pasting the bit of code out the bigger program.  I've added it back into the top post, thanks.

There is a whole load of debug lines in my code now as I've been trying to work out what's happening  :~

PaulS

Quote
I thought the most efficient way to do this was to use an array of 3 chars (char c[2];) and look for my byte based on the bytes either side...

An array of 2 characters, one of which will be the NULL, you mean. The value in the brackets is the count, not the upper index. You need to allow room for the trailing NULL, too.

Dogsbody

You absolute star!  Thank you :-)

GoForSmoke

Why should there have to be a NULL, Paul? I see no string or print commands.
I find it harder to express logic in English than in Code.
Sometimes an example says more than many times as many words.

Nick Gammon


... use an array of 3 chars (char c[2];) and look for my byte based on the bytes either side...

Code: [Select]

  if (c[2] == 'P' && c[0] == 'V') {
}



Regardless of whether there is a null or not, an array of 2 characters has indexes 0 and 1. So you can't check index 2 for a P.

Nick Gammon


.. to use an array of 3 chars (char c[2];)


In fact, even that should give you pause. An array of 3 chars you say?

Code: [Select]
char c [3];

mromani

Isn't an initialization step missing ? Something like "if numCharsReceived >=3 <code here> else <do nothing>".

Or maybe the fact that c[] has random contents is enough to cover this case ?

Dogsbody

I've changed this to the following now...
Code: [Select]
char c[3] = {0,0,0};
... is that what you mean?

AWOL

If your array "c" is a global or a static, the compiler will helpfully set all elements to zero, unless you tell it to set them to some other value.
Difficult to tell from snippets though (hint)
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

mromani

Well, I guess explicitly initializing the array is a simpler way to solve the issue.

Go Up