For loop increments ok, decrements not so much!

How is this possible?

  for (x = 0; x < 8; x = x + 1) {
    Serial.println (x);
    digitalWrite (ssPin, LOW);
    SPI.transfer (pattern7 [x]);
    digitalWrite (ssPin, HIGH);
    delay (hold);
  }
  // invert the pattern
  Serial.println ("down");
  for (x = 7; x >= 0; x = x - 1) {
    Serial.println (x);
    digitalWrite (ssPin, LOW);
    SPI.transfer (pattern7 [x]);
    digitalWrite (ssPin, HIGH);
    delay (hold);
  }
  for (x = 7; x >= 0; x = x - 1) {
    Serial.println (x);
    digitalWrite (ssPin, LOW);
    SPI.transfer (pattern6 [x]);
    digitalWrite (ssPin, HIGH);
    delay (hold);
  }

In the serial monitor I get:

0
1
2
3
4
5
6
7
down
7
6
5
4
3
2
1
0
65535
65534
65533
65532
65531
65530
65529
65528

x is a global unsigned int.[/code]

Never mind, 0 - 1 = 65535 with unsigned int. Which is >=0, so weird stuff happens as out of bounds locations are accessed.
Changed to signed int, now 0 -1 = -32767 or -32768 and it continues correctly.

CrossRoads:
Never mind, 0 - 1 = 65535 with unsigned int. Which is >=0, so weird stuff happens as out of bounds locations are accessed.
Changed to signed int, now 0 -1 = -32767 or -32768 and it continues correctly.

You nailed it

Surprised you lasted this long w/o getting burned by that one @XRoads! :wink:

a7

I don't typically count down so it rarely comes up.

You should also know not to post snippets :wink:

The warnings from the compiler should have been a hint:

sketch_dec26a.ino:11:17: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
   for (x = 7; x >= 0; x = x - 1)
               ~~^~~~
sketch_dec26a.ino:15:17: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
   for (x = 7; x >= 0; x = x - 1)
               ~~^~~~

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.