Arduino Binary Counter

January 25, 2018 ยท 2 minute read

I am volunteering for a little science group once a week for my daughter's 1st grade class. I thought it would be fun to learn to count binary so I programed an LED binary counter using an arduino. I am using an Arduino Mini Pro 3.3V.

For reference, the following table shows the binary representation of the base 10 digits 0 to 15. Endianness has to do with the order the bits are stored. In this case I have chosen the smallest digit to be the first bit. So the digit 110 would be 1000 using 4 bits.

Digit (base 10)binary (little endian)binary (big endian)
000000000
110000001
201000010
311000011
400100100
510100101
601100110
711100111
800011000
910011001
1001011010
1111011011
1200111100
1310111101
1401111110
1511111111

And here is the source. The trick is the bit masking part. Since the integer is already in binary form we just have to extract out the 0 or 1 from the right location with (mask >> i) & 1.

const int N_PINS = 4;
int pins[] = {2,3,4,5};
int mask = 0;

void setup() {                
  for(int i=0; i < N_PINS; i++) {
    pinMode(pins[i], OUTPUT);
  } 
}

void loop() {
  for(int i = 0; i < N_PINS; i++) {
    digitalWrite(pins[i], (mask >> i) & 1);
  }
  delay(1000);
  mask++;
  if (mask > 15) mask = 0;
}

[download file]

Binary Counter Schematic

I then wanted to add a button to increment the count.

const int N_PINS = 4;
const int buttonPin = 9;

int pins[] = {2,3,4,5};
int mask = 0;
int buttonState = 0;
int lastButtonState = 0;

void setup() {                
  for(int i=0; i < N_PINS; i++) {
    pinMode(pins[i], OUTPUT);
  } 
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if(buttonState != lastButtonState && buttonState == HIGH) {
    mask++;
    if (mask > 15) mask = 0;
    delay(50); // to avoid bouncing
  }
  lastButtonState = buttonState;
  for(int i = 0; i < N_PINS; i++) {
    digitalWrite(pins[i], (mask >> i) & 1);
  }
}

[download file]

Binary Counter with Button Schematic