All submissions

Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

uint8_t ledPins[4] = {2, 3, 4, 5};            // LED pins connected to pins 2, 3, 4, 5
uint8_t switchPins[2] = {8, 9};               // Switch pins connected to pins 8, 9 

uint8_t counter = 0;                          // Initial counter value 


uint8_t debounceDelay = 50;                    // Debounce delay time (in milliseconds)
unsigned long lastDebounceTime[2] = {0, 0};   // Stores last debounce time for each switch
uint8_t lastButtonState[2] = {HIGH, HIGH};    // Stores the last state of each button
uint8_t ButtonState[2] = {HIGH, HIGH};        // Store the current state of each button

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

}

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

  // check decrement switch
  if (isButtonPressed(1) && counter > 0) {
    counter--; 
    updateLEDs();
  }
}

// Check if a button has been pressed with debouncing
bool isButtonPressed(uint8_t switchIndex) {
  
  int reading = digitalRead(switchPins[switchIndex]);       
  
  // If the button state has changed
  if (reading != lastButtonState[switchIndex]) {
    lastDebounceTime[switchIndex] = millis();                 // Reset debounce timer
  }
  lastButtonState[switchIndex] = reading; 
  // If the state has remained stable for the debounce period(50 ms), consider it a valid press
  if ((millis() - lastDebounceTime[switchIndex]) > debounceDelay) {
    
    if (reading !=ButtonState[switchIndex] ) {
     ButtonState[switchIndex] = reading; 
     // Checking if the button is pressed(LOW)
      if (ButtonState[switchIndex] == LOW) {  
        return true;                             // Return true indicating a valid press
      }
    }
  }
 
  return false;                            // No valid press detected
}

// Update LEDs based on the current counter value
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)

https://wokwi.com/projects/442617143372806145

 

 

 

 

 

 

 

 

 

Submit Your Solution

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