Binary counter using for loop with LEDs in Arduino

2.6k views Asked by At

I am a beginner at using Arduino and I am trying to count up in binary using LEDs.

My code is:

int ledPins[] = {2,3,4,5,6,7,8,9};
{
  int delaytime = 500;
  int x;
  int mod;
  int index;
  int remain;
  for (x=0; x<512; x++)
  {
   if(x%2 == 1)
   {
    digitalWrite(2,HIGH);
   }
   else
   {
    digitalWrite(2,LOW);
   }
   for (index=1, mod=4, remain=1; index<8; index++, mod*=2, remain+=4)
    {
      if(x%mod>remain)
      { 
        digitalWrite(ledPins[index],HIGH);

      }
      else {
        digitalWrite(ledPins[index], LOW);
      }
    }
  delay(delaytime);
  }
}

I want the LED to turn on when x%mod>remain. (e.g. 7%4>1, so LED 3 will turn on)

Someone help me out please. Thank you very much.

2

There are 2 answers

0
Carl On

Rather than using the modulo operator '%', you can use bit-wise operations. For instance, the following writes the current value of x to your LEDs:

for(i=0; i<8; i++)
{
    digitalWrite(ledPins[i], (x >> i) & 0x01);
}

There are two operations involved here, a bitwise shift to the right (">>") and a bit-wise AND ("&").

For instance, let's imagine we want to get bit 3 of the number 170. The following shows how the number is manipulated in binary:

(original value of x)   10101010
(after bitwise shift 3) 00010101
(after bitwise and 1)   00000001

For more information search for "bitwise operators" or "bit masks".

To figure out why your approach didn't work, the best way is to dry run it by choosing a value for x and working through what would happen on paper like I did above. At a glance, it looks wrong to me that you're always adding 4 to the remainder each loop.

When the pins are contiguous on a port, you can simply assign the value of x directly to the port; this is what Bappi was getting at. This works because under-the-hood micro-controllers store multiple pin values in a single register.

0
AudioBubble On

I assume that pint 9 is LSD and pin 2 is MSD, try following code.

LEDControlLoop(){

    int x = 0;
    int delaytime = 500;
    DDRD = B11111111; // sets port d as output

    while(1){ // infinte while loop,
        PORTD = x;
        delay(delaytime);
        x++;
        if(x>255){
            x = 0;
            //break; //optional
        }   
    }
}