exactly correct but unable to write button code
Why not? You are not detecting a transition of the switch state, which you need to do.
To do this, you need to keep track of the previous state.
int prevState1 = HIGH; // Keep track of previous state of pin 1
void loop()
{
int currState1 = digitalRead(switchPin1);
if(currState1 != prevState1)
{
// A transition occurred
if(currState1 == LOW)
{
// The transition is to pressed
}
else
{
// The transition is to released
}
}
prevState1 = currState1;
}
Now that you know when a transition occurs, you can take action only once when the switch is pressed, only once when the switch is released, or whenever the switch is pressed or released.
You can add the code to set the pin HIGH, twiddle your thumbs and do nothing for a second, then set the pin LOW.
Or, you can get smart and skip the delays and simply set the pin HIGH, record when it was set HIGH, and use millis() to determine if it is time to turn the pin back off. This would allow multiple output pins to be HIGH at once.
Using delay will allow only one at a time to be HIGH.