int count = 0; // Counter variable shared by both inputs
int SW1 = 8; // Set SW1 to Pin 8 for count up
int SW2 = 9; // Set SW2 to Pin 9 for count down
int prevSW1State = HIGH; // Previous state of SW1
int prevSW2State = HIGH; // Previous state of SW2
void setup() {
DDRD = DDRD | B00011100; // set direction bits for pins 2 to 4, leave 0 and 1 untouched
Serial.begin(9600);
pinMode(SW1, INPUT);
digitalWrite(SW1, HIGH); //enable pullup. Switch connected to ground
pinMode(SW2, INPUT);
digitalWrite(SW2, HIGH); //enable pullup. Switch connected to ground
}
void loop() {
int currentSW1State = digitalRead(SW1);
int currentSW2State = digitalRead(SW2);
// Check if SW1 is pressed (count up)
if (currentSW1State == LOW && prevSW1State == HIGH) {
count++;
if (count > 7) {
count = 0;
}
}
// Check if SW2 is pressed (count down)
if (currentSW2State == LOW && prevSW2State == HIGH) {
count--;
if (count < 0) {
count = 7;
}
}
// 3 bits manipulated 0 to 7
PORTD = PORTD & B11100011; // clear out bits 2 - 4, leave pins 0 and 1 untouched (xx & 11 = xx)
int i = (count << 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1
PORTD = PORTD | i; // combine the port information with the new information for LED pins
Serial.print("Count=");
Serial.println(count);
Serial.print("PORTD in Binary=");
Serial.println(PORTD, BIN); // debug to show masking
prevSW1State = currentSW1State;
prevSW2State = currentSW2State;
delay(100); // Adjust delay as needed to pick up on input interaction
}