// Define select pins for the MUX using #define
#define SELECT_PIN_0 0
#define SELECT_PIN_1 1
#define SELECT_PIN_2 2
// Define button pin using #define
#define BUTTON_PIN 4
// State to store the current state (starts from 0 to 4, representing Y0 to Y4)
int currentState = 0;
// State to store the button state
int lastButtonState = LOW;
int buttonState = LOW;
// Debounce time
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 50;
void setup() {
// Set select pins as outputs
pinMode(SELECT_PIN_0, OUTPUT);
pinMode(SELECT_PIN_1, OUTPUT);
pinMode(SELECT_PIN_2, OUTPUT);
// Set button pin as input with pull-up resistor
pinMode(BUTTON_PIN, INPUT_PULLUP);
// Start with the first state Y0
updateState();
}
void loop() {
// Read the button state
int reading = digitalRead(BUTTON_PIN);
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// Reset the debouncing timer
lastDebounceTime = millis();
}
// Wait for the debounce time to pass
if ((millis() - lastDebounceTime) > debounceDelay) {
// If the button state has changed
if (reading != buttonState) {
buttonState = reading;
// Only increment the state if the button is pressed
if (buttonState == LOW) {
// Increment the current state and wrap around after 4 (Y4)
currentState = (currentState + 1) % 5;
updateState();
}
}
}
// Save the reading for the next loop
lastButtonState = reading;
}
void updateState() {
// Set the select pins based on the currentState value
switch (currentState) {
case 0: // Y0: SEL2=L, SEL1=L, SEL0=L
digitalWrite(SELECT_PIN_0, LOW);
digitalWrite(SELECT_PIN_1, LOW);
digitalWrite(SELECT_PIN_2, LOW);
break;
case 1: // Y1: SEL2=L, SEL1=L, SEL0=H
digitalWrite(SELECT_PIN_0, HIGH);
digitalWrite(SELECT_PIN_1, LOW);
digitalWrite(SELECT_PIN_2, LOW);
break;
case 2: // Y2: SEL2=L, SEL1=H, SEL0=L
digitalWrite(SELECT_PIN_0, LOW);
digitalWrite(SELECT_PIN_1, HIGH);
digitalWrite(SELECT_PIN_2, LOW);
break;
case 3: // Y3: SEL2=L, SEL1=H, SEL0=H
digitalWrite(SELECT_PIN_0, HIGH);
digitalWrite(SELECT_PIN_1, HIGH);
digitalWrite(SELECT_PIN_2, LOW);
break;
case 4: // Y0 Y1 Y2 Y3 OFF
digitalWrite(SELECT_PIN_0, HIGH);
digitalWrite(SELECT_PIN_1, HIGH);
digitalWrite(SELECT_PIN_2, HIGH);
break;
}
}