Making Things Interactive

February 5, 2008

Binary Counter

Filed under: 4: Counting Sensor Input,Lea — tovelet @ 12:32 am

I made a binary counter, that displays the number of button presses with four green LEDs, because I wanted to see if I could figure out a simple way of coding it. My answer uses the modulus function.

 * Binary Blink
 * Four LEDs as a counting display

int onesPlace = 12;                // 
int twosPlace = 11;                // 
int foursPlace = 10;               // 
int eightsPlace = 9;               // Pins for ones through eights places
int switchPin = 2;                 // Pin for switch
int n = 0;                         // Number of clicks
int buttonPress = 1;               // Will change when button is pressed

void setup()                       // run once, when the sketch starts
  pinMode(onesPlace, OUTPUT);
  pinMode(twosPlace, OUTPUT); 
  pinMode(foursPlace, OUTPUT);
  pinMode(eightsPlace, OUTPUT);     // sets the LED pins as output
  pinMode(switchPin, INPUT);
  Serial.begin(9600);               // for feedback that "n" is correct

void loop()                         // run over and over again
if (digitalRead(switchPin) == HIGH) {buttonPress = 0;}
if (digitalRead(switchPin) == LOW && buttonPress == 0) // only if the button has been pushed and released
      n++;                          // increment "n"
      digitalWrite(onesPlace, n % 2);
      digitalWrite(twosPlace, (n / 2) % 2);
      digitalWrite(foursPlace, (n / 4) % 2);
      digitalWrite(eightsPlace, (n / 8 ) % 2);
      Serial.println(n);            // tell me what "n" is
      buttonPress = 1;              // don't do anything until another button press

I did all of the coding without testing, unfortunately, because I’d left my Arduino elsewhere. I also drew a quick wiring diagram, so I’d be able to put my breadboard together relatively quickly once I had the components.

Once I figured out the right direction for the DPST switch, the counter worked, surprisingly smoothly. The only glitch is that the counter occasionally skips forward quickly during a button press, and I think that is the switch malfunctioning, or a loose contact.


Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Create a free website or blog at

%d bloggers like this: