Reputation: 43
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?
Upvotes: 1
Views: 923
Reputation: 1435
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)
Upvotes: 1
Reputation: 31604
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
Upvotes: 0