trivial newb question: counting down

There are no stupid questions you say? HA! how about:

I'm trying to count down from 15 to 0 in a loop.

        for (byte counter=15; counter>=0; counter--)

does not turn around at 0, wraps around to 255 and continues to decrement ("...4, 3, 2, 0, 255, 254...")

Modifying to:

        for (byte counter=15; counter>0; counter--)

turns around, but does not output 0: "...4, 3, 2, 1, 1, 15..." (no delay after the second 1))

Any help appreciated.

Use char instead of byte.

try this:

for (signed char counter=15; counter>=0; counter--)
[\code]

sorry, here's the whole code snippet:

      {     
        for (byte counter=seqLength; counter>=0; counter--)  //--DAMMIT.  if counter>=0, does not turn around at 0, wraps around to 255 and continues to decrement
                                                            //if counter>0, turns around but does not output 0: "4, 3, 2, 1, 1, 15..." (no delay after the second 1))
        {
          displayBinary(counter);
          Serial.println(counter);
          delay(seqSpeed); 
        }
      }

seqLength and seqSpeed are variables; displayBinary is a routine to convert output to binary on 4 digital pins.

Right? So change byte into a signed char like I suggested and try it.

Also start using the code tags to post your code.

Two options, do as the two above say.

Or, when you are 100% convinced the initial value is lower as 255 make it

for (byte counter=15; counter != 255; counter--)

signed char seems to work, thanks!

i'm still getting an extra value output at the turnaround, and something similar in countUp function

  • countdown: 4, 3, 2, 1, 0, 1, 15, 14 (second 1 does not trigger delay)

  • countup: 13, 14, 15, 0, 0, 1, 2, 3 (second 0 no delay)

not a problem, i think, but makes me curious

Post your whole code using the tags, and we might be able to spot it.

found it (errant debugging println i forgot to comment out). thanks again, all, this is a foreign land to me...

Id like to write an explanation of binary arithmetic using car odometers as a metaphor

Could someone please explain or point to an explanation of the reason why "signed char" must be used instead of "byte" ?

A byte is an unsigned type so it can't become negative. So 0 - 1 will roll around to the greatest value 255. A signed char can be negative but the greatest value is 127.

So instead for checking:

for(byte i = 10; i < 0; i--) //will never stop because i can not become negative

You can use the fact it will just roll around and check for

for(byte i = 10; i != 255; i--) //will happen because i will become 255 after subtracting 1 from 0

Ok, got it, any data type that handles negative values will work. Signed char was chosen in this case because the value "counter" is not exceeding 127. Or, use this: i != 255; with byte, so i will never be 255. Thank you very much for the explanation septillion. +1 karma