Leonarduino98
Posts: 5
Joined: Thu Oct 22, 2015 10:38 am

Led keeps on blinking

Tue May 03, 2016 10:03 pm

I tried a very simple project connecting a button to the gpio 22 and a led to the gpio 18 to my RPi 2.
My code is this below:

Code: Select all

import RPi.GPIO as gpio

gpio.setwarnings(False)
gpio.setmode(gpio.BCM)
gpio.setup(18, gpio.OUT)
gpio.setup(22, gpio.IN)

while True:
    if gpio.input(22) == 0:
        gpio.output(18, gpio.LOW)
        print('low')
    else:
        gpio.output(18, gpio.HIGH)
        print('high')
If i press the button, the led will turn on and the value 'high' appears to the terminal.
The problem is when I release the button: the light doesn't turn off but only decreases the brightness and the values oscillate between 'low' and 'high' continuously.
Did I write something wrong?

User avatar
rpdom
Posts: 17275
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Led keeps on blinking

Wed May 04, 2016 5:05 am

You don't have a pull-down resistor in your circuit, so when the button isn't pressed the pin level will "float" and will pick up any random EM radiation in the air which will cause it to flicker between high and low randomly.

You can either add an external resistor, or change your code to use the internal one.

Code: Select all

gpio.setup(22, gpio.IN, pull_up_down=gpio.PUD_DOWN)

Return to “Interfacing (DSI, CSI, I2C, etc.)”