0

I want to create a simple program that has two loops and I can change between them by pressing a physical button, like a mode selector.

MODE 1: Heating
MODE 2: Cooling

import RPi.GPIO as GPIO
import time

GPIO.setup(21, GPIO.IN, pull_up_down=GPIO.PUD_UP)

mode = 'heating'

def my_callback(channel):
    if mode == 'heating'
        mode = 'cooling'
        print 'turned on cooling'
    elif mode == 'cooling'
        mode = 'heating'
        print 'turned on heating'

GPIO.add_event_detect(21, GPIO.RISING, callback=my_callback)


while mode == 'heating'
    print 'I am heating'
    time.sleep(1.0)

while mode == 'cooling'
    print 'I am cooling'
    time.sleep(1.0)

When I run this code it starts with the heating mode, when I push the button the callback runs but the variable does not change and the heating loop is still running.

frogatto
  • 28,539
  • 11
  • 83
  • 129

2 Answers2

0

you can't have the loops sequential in your code otherwise even if everything worked well you would only be able to press the button twice before the program terminates. you should probably do something more like this:

while True:
    if mode == 'heating':
        print 'I am heating'
        time.sleep(1.0)
    if mode == 'cooling':
        print 'I am cooling'
        time.sleep(1.0)
AntiMatterDynamite
  • 1,495
  • 7
  • 17
0

@Ted Klein Bergman wrote the working answer in his reply:

mode variable has to defined in the function as a global variable. This modification solved the problem:

def my_callback(channel):
    if mode == 'heating'
        global mode
        mode = 'cooling'
        print 'turned on cooling'
    elif mode == 'cooling'
        global mode
        mode = 'heating'
        print 'turned on heating'

Thanks for the feedback!