Least significant bit not displayed by binary counter

Hello. I've written a simple program that increments a number and displays it in binary via 14 LEDs connected to pins 0-13 on the Arduino Leonardo. All but one LED displays the correct pattern. The least significant LED, connected to pin 0, remains off. Here's my code:

int number = 0;
int delayTime = 1000;

void setup() {
  for (int thisPin = 0; thisPin < 13; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  int temp = number;
  for (int thisPin = 13; thisPin > 0; thisPin--) {
    if (temp - pow(2, thisPin) >= 0) {
      temp -= pow(2, thisPin);
      digitalWrite(thisPin, HIGH);
    }
    else {
      digitalWrite(thisPin, LOW);
    }
  }
  number++;
  delay(delayTime);
}

Any help is appreciated :slight_smile:

  for (int thisPin = 0; thisPin < 13; thisPin++) {

Set the mode of pins 0 to 12. Good.

  for (int thisPin = 13; thisPin > 0; thisPin--) {
    if (temp - pow(2, thisPin) >= 0) {
      temp -= pow(2, thisPin);
      digitalWrite(thisPin, HIGH);

Write to pins 13 to 1. Bad.

for (int thisPin = 13; thisPin > 0;

Miss out last pin.
Also bad.

Thanks. I fixed the code by changing a line from this:

  for (int thisPin = 13; thisPin > 0; thisPin--) {

to this:

  for (int thisPin = 13; thisPin >= 0; thisPin--) {

I'm confused as to why that worked. I thought the original line would continue to decrement to the 0th pin because it would keep going while it's at a number greater than 0. (thisPin > 0)

I thought the original line would continue to decrement to the 0th pin because it would keep going while it's at a number greater than 0. (thisPin > 0)

It does keep going, decrementing until thisPin is 0. Since 0 is not greater than 0, the body of the for loop is then skipped.

You are still setting the mode of pins 0 to 12, and writing to pins 0 to 13. That can't be right.

Oh, I think I understand now. The middle part of the for loop (in between the two semicolons) only captures the values it explicitly states, not also the next iteration. Here's the full corrected code for anyone with the same problems:

int number = 0;
int delayTime = 1000;

void setup() {
  for (int thisPin = 0; thisPin <= 13; thisPin++) {
    pinMode(thisPin, OUTPUT);
  }
}

void loop() {
  int temp = number;
  for (int thisPin = 13; thisPin >= 0; thisPin--) {
    if (temp - pow(2, thisPin) >= 0) {
      temp -= pow(2, thisPin);
      digitalWrite(thisPin, HIGH);
    }
    else {
      digitalWrite(thisPin, LOW);
    }
  }
  number++;
  delay(delayTime);
}

Here's the full corrected code for anyone with the same problems:

That's not how I'd do it. Using a float function, pow(), to do bit shifting is silly.