All submissions

Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

/*Paste your code here*/
uint8_t ledPins[4] = {2, 3, 4, 5};
uint8_t switchPins[2] = {8, 9};
uint8_t counter = 0;
uint8_t debounceDelay = 50;
unsigned long lastDebounceTime[2] = {0, 0};
uint8_t lastButtonState[2] = {HIGH, HIGH};
uint8_t ButtonState[2] = {HIGH, HIGH};

void setup() {
  for (int i = 0; i < 4; i++) {
    pinMode(ledPins[i], OUTPUT);
  }
  for (int i = 0; i < 2; i++) {
    pinMode(switchPins[i], INPUT_PULLUP);
  }
}

void loop() {
  if (isButtonPressed(0) && counter < 15) {
    counter++;
    updateLEDs();
  }

  if (isButtonPressed(1) && counter > 0) {
    counter--;
    updateLEDs();
  }
}

bool isButtonPressed(uint8_t switchIndex) {
  int reading = digitalRead(switchPins[switchIndex]);

  if (reading != lastButtonState[switchIndex]) {
    lastDebounceTime[switchIndex] = millis();
  }
  lastButtonState[switchIndex] = reading;

  if ((millis() - lastDebounceTime[switchIndex]) > debounceDelay) {
    if (reading != ButtonState[switchIndex]) {
      ButtonState[switchIndex] = reading;
      if (ButtonState[switchIndex] == LOW) {
        return true;
      }
    }
  }
  return false;
}

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

 

Output

Video

Add a video of the output (know more)

 

 

 

 

 

 

 

 

 

 

Submit Your Solution

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