Implement a 4-bit binary counter

AliToufaily
AliToufaily

Solving Approach

How do you plan to solve it?

 Atach an interrupt to each of the buttons, debounce the buttons (GPIO 2 & 3).

Attach the four LEDs of the counter to pins 4,5,6,7 

simulated on tinkercad.com


 

 

 

 

Code

// C++ code
//

#define INCINTRPIN  2
#define DECINTRPIN  3

#define BIT0PIN 4  
#define BIT1PIN 5  
#define BIT2PIN 6  
#define BIT3PIN 7  


int incButtonStateChanged = 0;
int decButtonStateChanged = 0;
long incLastChange = 0;
long decLastChange = 0;
#define  DebounceTime 50

void myIncISR() {
  incButtonStateChanged = 1;
}

void myDecISR() {
  decButtonStateChanged = 1;
}


bool debouncedPress(int buttonStateChanged, long lastChange) {
  if (buttonStateChanged == 1) {
    if ((millis() - lastChange) >= DebounceTime) {
      return true;
    }
    else {
      return false;
    }
  }
  else {
    return false;
  }
}


void setup() {
  pinMode(BIT0PIN, OUTPUT);
  pinMode(BIT1PIN, OUTPUT);
  pinMode(BIT2PIN, OUTPUT);
  pinMode(BIT3PIN, OUTPUT);
  digitalWrite(INCINTRPIN, HIGH);
  digitalWrite(DECINTRPIN, HIGH);
  
  pinMode(INCINTRPIN, INPUT_PULLUP);
  pinMode(DECINTRPIN, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(INCINTRPIN), myIncISR, FALLING);
  attachInterrupt(digitalPinToInterrupt(DECINTRPIN), myDecISR, FALLING);
  Serial.begin(9600);
}


int theCounter= 0;
void loop()
{
  if (incButtonStateChanged && debouncedPress(incButtonStateChanged, incLastChange)) {
    incLastChange = millis();
    incButtonStateChanged=0;
    theCounter++;
    theCounter = theCounter & 0xF;
    Serial.print("increment to: ");
	  Serial.println(theCounter);
  }

  if (decButtonStateChanged && debouncedPress(decButtonStateChanged, decLastChange)) {
    decLastChange = millis();
    decButtonStateChanged=0;
    theCounter--;
    theCounter = theCounter & 0xF;
    Serial.print("decrement to: ");
	  Serial.println(theCounter);
  }
  digitalWrite(BIT0PIN, ((theCounter & 0x1) == 0)? LOW : HIGH);
  digitalWrite(BIT1PIN, ((theCounter & 0x2) == 0)? LOW : HIGH);
  digitalWrite(BIT2PIN, ((theCounter & 0x4) == 0)? LOW : HIGH);
  digitalWrite(BIT3PIN, ((theCounter & 0x8) == 0)? LOW : HIGH);
  
}

 

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!