Shiva Teja
Shiva Teja

Reputation: 13

how to change variable value automatically in while loop?

I'm trying to control led lights based on its previous state using python code on my raspberry pi. Any suggestion how can I do it?

I have tried using checking gpio state using gpio.input() function, and changing variable value

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(35,GPIO.OUT)
GPIO.output(35,GPIO.HIGH)

f = '1'

while True:
    time.sleep(3)
    print "before"
    print f
    if f == '1':
        GPIO.output(35,GPIO.HIGH)
        f = '0'

    if f == '0':
        GPIO.output(35,GPIO.LOW)
        f = '1'
    print "after"
    print f
time.sleep(3)

I expect to turn off light if it is in on condition and vice-versa

Upvotes: 0

Views: 125

Answers (1)

BoarGules
BoarGules

Reputation: 16951

Your code is changing f from 1 to 0 and then immediately changing it back again, so your code is working, but it switches the light off so quickly again you don't see it.

Change this line

if f == '0':

to

elif f == '0':

Upvotes: 1

Related Questions