Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

/*Paste your code here*/
const int buttonPin = 7;
const int ledPins[4] = {3,4,5,6};

int counter = 0;
bool lastState = HIGH;
unsigned long lastDebounceTime = 0;
const unsigned long debounceDelay = 50;

void setup() {
    Serial.begin(9600); 
  pinMode(buttonPin, INPUT_PULLUP);
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop() {
  bool reading = digitalRead(buttonPin);

  if (reading != lastState) {
    lastDebounceTime = millis();
  }

  if ((lastDebounceTime) > debounceDelay) {
    if (reading == LOW && lastState == HIGH) {
      counter = (counter + 1) & 0x0F;  // keep 4 bits (0–15)
      updateLEDs();
    }
  }

  lastState = reading;
}

void updateLEDs() {
  for (int i = 0; i < 4; i++) {
    digitalWrite(ledPins[i], (counter >> i) & 1);
    Serial.println(counter);
  }
}

 

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!