Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

const int incBtn = 2;
const int decBtn = 3;

const int ledPins[4] = {8, 9, 10, 11};

int count = 0;

bool lastIncState = HIGH;
bool lastDecState = HIGH;

void setup() {
  pinMode(incBtn, INPUT_PULLUP);
  pinMode(decBtn, INPUT_PULLUP);

  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  bool incState = digitalRead(incBtn);
  bool decState = digitalRead(decBtn);

  // Increment button
  if (lastIncState == HIGH && incState == LOW) {
    count++;
    if (count > 15) count = 0;
    updateLEDs();
  }

  // Decrement button
  if (lastDecState == HIGH && decState == LOW) {
    count--;
    if (count < 0) count = 15;
    updateLEDs();
  }

  lastIncState = incState;
  lastDecState = decState;
}

void updateLEDs() {
  for (int i = 0; i < 4; i++) {
    digitalWrite(ledPins[i], (count >> i) & 0x01);
  }
}

 

Output

Video

Add a video of the output (know more)

 

 

 

 

 

 

 

Upvote
Downvote

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!