Bits4Bots LLC
Published © LGPL

Binary Up/Down Counter

Build a binary counter using an Arduino microcontroller.

IntermediateShowcase (no instructions)Over 1 day6,173
Binary Up/Down Counter

Things used in this project

Story

Read more

Code

Binary Up/Down Counter File

C/C++
Upload code to Arduino Sketch
//Binary Up & Down Counter
//By: Bits4Bots

int buttonup = 2;      // pin to connect the button up
int buttondn = 3;      // pin to connect the button down
int presses = 0;    // variable to store number of presses
long time = 0;      // used for debounce
long debounce = 50;  // how many ms to "debounce" between presses
const byte numPins = 8; // how many leds
int state;        // used for HIGH or LOW
 // pins to connect leds
byte pins[] = {5, 6, 7, 8, 9, 10, 11, 12};
 
void setup()
{
  /* we setup all led pins as OUTPUT */
  for(int i = 0; i < numPins; i++) {
    pinMode(pins[i], OUTPUT);
  }
  pinMode(buttonup, INPUT);
  digitalWrite(buttonup, HIGH); //prevent floating pin
  /* use pin 2 and 3 which have interrupt 0 on Arduino UNO */
  pinMode(buttondn, INPUT);
  digitalWrite(buttondn, HIGH); //prevent floating pins
  attachInterrupt(0, countdn, LOW);
  attachInterrupt(1, countup, LOW);
}
 
void loop()
{
  /* convert presses to binary and store it as a string */
  String binNumber = String(presses, BIN);
  /* get the length of the string */
  int binLength = binNumber.length(); 
  if(presses <= 255) {  // if we have less or equal to 255 presses
                
    for(int i = 0, x = 1; i < binLength; i++, x+=2) { 
      if(binNumber[i] == '0') state = LOW;
      if(binNumber[i] == '1') state = HIGH;
      digitalWrite(pins[i] + binLength - x, state);
      if ((0 <= presses) && (presses <= 255)) { 
// do something here
  } else {
    if (presses > 255) presses = 255;
    if (presses < 0) presses = 0;   // you can flip it to make it roll over instead of stopping
}

    } 
  } else {
    // do something when we reach 255
  }
}
 
/* function to count the presses */
void countup() { 
  // we debounce the button and increase the presses
  if(millis() - time > debounce)  presses++;
  time = millis();
}
void countdn() {  
  // we debounce the button and decrease  the presses
  if (millis() - time > debounce)  presses--;
  time = millis();
}

Credits

Bits4Bots LLC

Bits4Bots LLC

5 projects • 2 followers
Electronics Engineer and technology blogger. PCB rapid prototype designer. DIY kits and blogs at www.bits4bots.com Tinkering since age 7.

Comments