SparkFun Forums 

Where electronics enthusiasts find answers.

For the discussion of Arduino related topics.
By Danieru
#112117
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:
Code: Select all
/*
  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); 
}
By stevech
#112197
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
By Danieru
#112201
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 :D

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.