One side of a switch is usually tied to GND, so you have to configure your pin as "resistive pull-up", reading a "1" when the switch is open and a "0" when closed. When the switch is tied to Vcc configure pin to "Resistive Pull-Down" and read the opposite polarities.
Dont forget to debounce the switch, with deglitch component, or in SW (attached)
When a GPIO pin is set as an input it is “floating” and has no defined voltage level. For us to be able to reliably detect whether the input is high or low we need to tie it so that it is always connected and either reads high or low.
To tie the pin we connect either a Pull Up or Pull Down resistor. A Pull down resistor connects the pin to ground through a large resistor, this means that when the switch is open there is a path to ground and so it will read low. When the switch is pressed (with the other side connected to 3.3V) there is a lower resistance path to high and so the pin will read high. The large (10kΩ) resistor ensures that only a little current is drawn when the switch is pressed.
Setting up a circuit like this means that we will be able to take reliable readings from a switch, however we could still damage the pins if they are accidentally set to an output. If we drive it low the output is connected directly to ground. Pushing the button will then create a short circuit between 3.3V and ground! To make this safer we put in a current limiting resistor (1kΩ will do) to make sure the Pi can handle the current drawn.
Debounce6.zip 6.8 MB
Note, in prior post, "Normally" the series R would be omitted if doing a switch to ground
as the higfh side PMOS fet cannot source much current if output driven high and switch
closed.. And R1 would be a pin config uration pull up or pull down.