Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code

#define button_inc  10
#define button_dcr  11

int LEDs[4] = {4, 5, 6, 7};

uint8_t counter = 0;

void setup() {
  // Initialiaze LEDs to OUTPUT mode
  for(int i = 0; i < 4; i++)
    pinMode(LEDs[i], OUTPUT);

  // Initialize buttons to INPUT PULLUP mode
  pinMode(button_inc, INPUT_PULLUP);
  pinMode(button_dcr, INPUT_PULLUP);

}

void loop() {
  int button_inc_read = digitalRead(button_inc);
  int button_dcr_read = digitalRead(button_dcr);
  delay(200);
  if(button_inc_read == 0)
  {
    counter++;
    if(counter == 16) 
      counter = 0;
  }

  if(button_dcr_read == 0)
  {
    counter--;
    if(counter == -1) 
      counter = 15;
  }

  uint8_t bit0 = counter & 1;
  uint8_t bit1 = (counter >> 1) & 1;
  uint8_t bit2 = (counter >> 2) & 1;
  uint8_t bit3 = (counter >> 3) & 1;
  
  digitalWrite(LEDs[0], bit0);
  digitalWrite(LEDs[1], bit1);
  digitalWrite(LEDs[2], bit2);
  digitalWrite(LEDs[3], bit3);

}

 

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!