I have a Python script which should read if a switch is pressed (a normal light switch).

This switch I've connected to GPIO pin 40 and GND

I read the state of GPIO:

GPIO.setFunction(GPIO_startprog1, GPIO.IN)
if (GPIO.digitalRead(GPIO_startprog1) == GPIO.HIGH):
    print ("Prog 1 Start by press button") 

def Prog1():

The moment I connect a wire to pin 38 (GPIO20) my readings are randomly flipping between high and low. Touching the wire with your fingers causes more GPIO.HIGHs (I can monitor the state of the GPIO pins with a tool named WebIOPi).

What is the proper method to detect if a physical switch is on/off? I just need a clear and simple GPIO.HIGH or GPIO.LOW.

3 Answers 3


Until you apply a voltage to the GPIO it will be floating and return random results.

The normal method of applying a default voltage is by attaching a resistor between the GPIO and ground (pull-down) or between the GPIO and 3V3 (pull-up).

If the other end of the switch is connected to ground use a pull-up. If the other end of the switch is connected to 3V3 use a pull-down.

There are internal pull-ups and pull-downs you can enable via software (your GPIO library will provide a method). This ensures the GPIO stays in a stable state until overridden by the switch.

Switches may bounce. However they only bounce when you are operating the switch.


With the help of the answers in this post i've found this solution which works the best for me. Simply ad the following parameter:


will do the job perfectly. In my program it looks now like this:

GPIO.setFunction(GPIO_startprog1, GPIO.IN,pull_up_down=GPIO.PUD_DOWN)

You don't say if you have one but you definitely need a pullup resistor. There are internal pullups but these are high resistance and more subject to interference. See http://elinux.org/RPi_GPIO_Interface_Circuits#Buttons_and_switches

If when you say "a normal light switch" you mean one normally used for mains power. These are actually lousy switches for the purpose, as they are designed to switch high voltage high currents and are particularly prone to bounce.

You need to de-bounce, even if you are using a more suitable switch. Python does have de-bounce options although these tend to be either rising or falling. I normally detect a switch change, delay (50-250 mSec depending on switch and application) and verify the switch is still in the same state.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.