hi i want to serial print when button is pressed but it should only print when there is change in state of button i wrote a code for that but its not working can anyone help me out.
This is what the code would look like using arrays and loops. I also added switch debounce. You can easily change the number of switch pins and their order by changing the array of pin numbers. (If you want the switches to be known by a name rather than a number you could make an array of pin names.)
I use the internal pull-up resistors so you don't need external pull-up or pull-down resistors. Connect the switches between the pin and Ground. The pin will read HIGH (due to the pull-up) when the switch is OPEN and read LOW when the switch is closed.
const byte SwitchPins[] = {5, 4, 2, 3};
const byte SwitchCount = sizeof SwitchPins / sizeof SwitchPins[0];
const unsigned long DebounceInterval = 15;
boolean LastState[SwitchCount]; // Defaults to 'false'
void setup ()
{
Serial.begin(115200);
for (byte i = 0; i < SwitchCount; i++)
pinMode(SwitchPins[i], INPUT_PULLUP); // Active LOW: Switch between pin and Ground
}
void loop ()
{
// For each switch...
for (byte i = 0; i < SwitchCount; i++)
{
bool state = digitalRead(SwitchPins[i]) == LOW; // Active LOW: Switch between pin and Ground
static unsigned long lastStateChange = 0;
unsigned long currentMillis = millis();
// Looks for state change (with debounce)
if (state != LastState[i] && currentMillis - lastStateChange > DebounceInterval)
{
lastStateChange = currentMillis;
LastState[i] = state;
Serial.print("Switch ");
Serial.print(i + 1);
if (state)
{
// Switch just closed
Serial.println(" Closed");
}
else
{
// Switch just opened
Serial.println(" Open");
}
} // End: if (state != LastState
} // End: for (byte i=0;
}