1

Im working on something similar these link: Connecting a Push Switch

But with few changes: LED attached and wish the LED to be high only when the switch is pressed.

I tried something like this, but the program does not run.

GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
try:
        while True:
                input_state = GPIO.input(18)
                if input_state == True:
                        GPIO.setup(18,GPIO.OUT)
                        GPIO.output(18, True)

Should it not work if we just make high/up to low/down and make the switch to change it to high/up?

  • While False:, means run while the constant "False" is equal to "True" hence it will never run, try while True: – rob Feb 2 '15 at 10:17
3

You can't just change from pull-up to pull-down without changing the wiring.

If one end of the switch is wired to ground and the other to a gpio you need a pull-up on the gpio. Then the gpio will read high normally and will read low when the switch is closed.

If one end of the switch is wired to 3V3 and the other to a gpio you need a pull-down on the gpio. Then the gpio will read low normally and will read high when the switch is closed.

However, for instance, suppose one end of the switch is wired to ground and the other to a gpio with a pull-down. Then the gpio will read low normally and will still read low when the switch is closed.

  • one end of switch to 3v3 the while: goes to an infinite loop. and the LED is unaffected. – moz ado Feb 3 '15 at 12:08
  • 1
    Not quite sure what you are trying to do. You really ought to connect the switch and LED to different gpios. – joan Feb 3 '15 at 12:16
  • I'm trying to make the LED high whenever the switch is pressed, so thought it would be a good idea to connect to the same GPIO, I'm still very new at these so any suggestion is very much appreciated – moz ado Feb 3 '15 at 12:22
  • 1
    You seem to be trying to use the gpio as an input (switch) and output (LED) at the same time. That won't work. I'd use one gpio as an input and connect that to the switch. Use another gpio as an output and connect that to the LED + resistor (you need a resistor to limit the LED current). Check the input (switch) gpio and set the output (LED) gpio accordingly. – joan Feb 3 '15 at 12:51
  • I was hoping that we could use the same GPIO for both. Understood what you meant, thanks for the help – moz ado Feb 5 '15 at 7:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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