A 12 bit binary counter, my first go with Arduino

I just got my Ardunio inventor kit about two hours ago. I tried out the blink hello world and flipped through the other suggested programs but nothing caught my eye.

So I set about to making a binary counter. I used the “8 LED” example for the hardware. The code was a bit more tricky since I didn’t have a full grasp (still don’t) of binary. I had to fix a bug or two in my original algorithm but once that was done I cleaned up the code and added some simple configuration options.

Video, sorry about the out of focus portions

http://www.youtube.com/watch?v=uA8re61ZBDw

Anyway thank you Sparkfun and arduino.

The code if anyone is interested:

/*
  Binary counter
  Counts up and prints result to LEDs, for practicing binary counting.
 
  This code is in the public domain.
 */

int startPin = 2;
int everyNthPin = 1;
int totalPins = 12;
int delayInms = 500;


void setup() {                
  for (int i = startPin; ( i / everyNthPin ) - startPin < totalPins;  i += everyNthPin) {
    pinMode(i, OUTPUT);    
  } 
}

int expo( int base , int power) {
  int total = base;
  for( int times = power; times > 1; times--) {
    total *= base;
  }
  return total;
}

int i = 0;

void loop() {
  int carry = i;
  int currentbit = 0;
  
  int j = startPin;
  for (; ( j / everyNthPin ) - startPin < totalPins;  j += everyNthPin)  {
    currentbit = carry % 2;
    carry = carry / 2;
   
    if (currentbit > 0)  {
      digitalWrite(j, HIGH);
    } else {
      digitalWrite(j, LOW);
    }
  }

  i++;
  if (i >= expo(2 , totalPins) ) i = 0;
  delay(delayInms); 
}

One big picture suggestion: instead of successive multiplication to computer powers of 2, you can just left-shift. If the exponent is known at design/code time, it’s just a compiler constant. If at run time, you can compute it by shifting:

unsigned int i = 0;

i = (1<<10); // is 2 to the 10th. In this case the compiler will replace (1<<10) with a constant and compute nothing.

i = (1<<n); // is 2 to the nth

or more commonly, you start with 2 to the nth in a variable and iterate a loop, shifting left once per loop, like

i = 1;

for (j = 0; j < 16; j++)

i <<= 1; // successive powers of 2, rather than computing i = 2 to the j

Thank you, I assume you are referring to the overflow check towards the bottom of the code where I use expo()?

I actually have been thinking about optimizing it, right now it only gets up to the 8th or so power before it starts blinking slow enough to discern :smiley:

I did know about shifting but I wanted to avoid it since it is clever technique. Although I can move the computation out of loop, same with the initializations.