1

I want to use a slider button of 3 pins.

Actually I'm using 2 of it, like the schematic below:

schematic

simulate this circuit – Schematic created using CircuitLab

My code is:

import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
green_led = 21
GPIO.setup(green_led, GPIO.IN)

while True:
    green_led_state = GPIO.input(green_led)
    print('#### - ',green_led_state, ' - ####')

In my opinion whith this code, if don't touch my slider always have to print the same value (1 or 0) depending of its position. And if I change the position of the slider, print the other value all the time.

But now, without touching nothing is printing 0 and 1 randomly (I think randomly). Why this? Why some times has current and sometimes not?

Thanks

  • Like your earlier question, you are connecting LEDs without a current limiting resistor. You are lucky not to have blown something up, but excessive current will eventually cause problems. – Milliways May 25 at 23:34
  • Sorry I didn't put in the schematic but it is in my real circuit :) – NEA May 26 at 9:00
1

A GPIO set as an input will float (read randomly low/high) until a voltage is applied.

The simplest thing to do is set the internal resistor pulls to the opposite of the value set by the switch. If I read your circuit correctly use

GPIO.setup(green_led, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

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.