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.
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:
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:
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.