1

I was using these codes for passing variables from f1.py to f2.py, and it works perfectly:

f1.py:

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23, GPIO.IN)

state = GPIO.input(23)

f2.py:

from f1 import state
print state

My problem now is that when I place f2.py inside an infinite loop, the variable state doesn't update. I even tried printing something inside f1.py to check if the "from f1 import state" part of the f2.py gets executed, but it is only executed once.

new f2.py:

while True:
    from f1 import state
    print state

How do I keep reading new values of "state" variable in f1 from f2?

2 Answers 2

1

Reloading the module each time you want the state is crazy. Put the state code inside a function in f1.py:

import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23, GPIO.IN)

def get_state():
    state = GPIO.input(23)
    return state

Then in f2.py:

import f1
while True:
    state = f1.get_state()

You could always change the function so you could inspect the state of different GPIO channels:

def get_state(channel=23):
    state = GPIO.input(channel)
    return state

And then call it like this:

state = f1.get_state(23)
Sign up to request clarification or add additional context in comments.

Comments

0

After module import, it will not be executed for the second time, just use the reference in the memory, so you had to reload the module to get the new value from gpio.

Something like follows, you can adjust base on next, FYI:

while True:
    from f1 import state
    import sys
    reload(sys.modules['f1'])
    print state

1 Comment

Wow! That made it work! I am actually reading sensor values from f1 and passing them to f2 for automation. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.