Implement a 4-bit binary counter

Solving Approach

How do you plan to solve it?

 
 

 

 

 

Code






#define BUTTON_INCREMENT 3
#define BUTTON_DECREMENT 2

#define LED1_PIN 4
#define LED2_PIN 5
#define LED3_PIN 6
#define LED4_PIN 7

typedef union {
    uint8_t raw;
    struct {
        uint8_t led1  : 1;
        uint8_t led2  : 1;
        uint8_t led3  : 1;
        uint8_t led4  : 1;
        uint8_t block : 4;
    } bits;
} Led_Series_t;

/* ---------------- LED Output ---------------- */

void apply_leds(const Led_Series_t *leds)
{
    digitalWrite(LED1_PIN, leds->bits.led1);
    digitalWrite(LED2_PIN, leds->bits.led2);
    digitalWrite(LED3_PIN, leds->bits.led3);
    digitalWrite(LED4_PIN, leds->bits.led4);
}

/* ---------------- Buttons ------------------- */

void button_increment(Led_Series_t* leds, uint8_t* last_state)
{
    uint8_t button = digitalRead(BUTTON_INCREMENT);

    if (button == HIGH && *last_state == LOW) {
        leds->raw++;
        leds->raw &= 0x0F;   // keep only 4 bits
    }

    *last_state = button;
}

void button_decrement(Led_Series_t* leds, uint8_t* last_state)
{
    uint8_t button = digitalRead(BUTTON_DECREMENT);

    if (button == HIGH && *last_state == LOW) {
        leds->raw--;
        leds->raw &= 0x0F;   // keep only 4 bits
    }

    *last_state = button;
}

/* ---------------- Setup --------------------- */

void setup()
{
    pinMode(BUTTON_INCREMENT, INPUT);   // external pull-downs
    pinMode(BUTTON_DECREMENT, INPUT);

    pinMode(LED1_PIN, OUTPUT);
    pinMode(LED2_PIN, OUTPUT);
    pinMode(LED3_PIN, OUTPUT);
    pinMode(LED4_PIN, OUTPUT);
}

/* ---------------- Loop ---------------------- */

void loop()
{
    static Led_Series_t leds = { .raw = 0 };
    static uint8_t inc_state = LOW;
    static uint8_t dec_state = LOW;

    button_increment(&leds, &inc_state);
    button_decrement(&leds, &dec_state);

    apply_leds(&leds);
    delay(50);
}






 

Output

Video

Add a video of the output (know more)

https://wokwi.com/projects/450781914931974145

 

 

 

 

 

 

 

 

 

Upvote
Downvote

Submit Your Solution

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