Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

Initially, create an array of GPIO pins (arrled) of output LED. Assign increment and decrement button as input pullup. Assign initial value of 'value' as 0.

Create a function placeValue() to assign output of ith pin based on ith bit of value.

Initialize all pins. In loop function, check condition of button pressed. If increment button is pressed, increase the value by 1 and if decrement button is pressed, decrement the value by 1. If value is at max (15) or min (0), assign it to 0 or 15 respectively.

Call function placeValue to assign GPIOs based on updated value.


 

 

 

 

Code

int bit_len = 4;
int arrled[4] = {8,9,10,11};
int inc = 2;
int dec = 3;
int value = 0;

void placeValue(int value){
  for(int i=0; i<bit_len; i++){
    digitalWrite(arrled[i],((value>>i)&1));
  }
  Serial.begin(9600);
}

void setup() {
  // put your setup code here, to run once:
  for(int i=0; i<4; i++){
    pinMode(arrled[i], OUTPUT);
  }
  pinMode(inc, INPUT_PULLUP);
  pinMode(dec, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  
  if(digitalRead(inc) == 0){
    value++;
    if(value==16)
      value = 0;
  }
  if(digitalRead(dec) == 0){
    value--;
    if(value == -1)
      value = 15;
  }
  placeValue(value);
  Serial.println(value);
  delay(150);

}

 

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!