Issue
I am trying to setup GPIO ports on a flask server to give it input remotely.
from flask import Flask
from flask import request
import RPi.GPIO as GPIO
app = Flask(__name__)
@app.before_first_request():
def before_first_request():
GPIO.setmode(GPIO.BCM)
pwmOne = GPIO.PWM(12, 100)
pwmOneDutyCycle = 0
pwmOne.start(pwmOneDutyCycle)
@app.route('/', methods = ['GET', 'POST'])
def remoteInput():
if request.method == 'POST':
...
pwmOneDutyCycle += 10
pwmOne.ChangeDutyCycle(pwmOneDutyCycle)
....
Whenever it receives a request it says the pwmOneDutyCycle is not defined (i'm assuming pwmOne is not defined either). Why? Any tips for how I can fix this? I need to initialize this code once and don't want it to reinitialize upon each individual request.
Solution
You need to have
pwmOneDutyCycle
outside of the 2 functions -before_first_request
,remoteInput
Then you need to make it global in each of the 2 functions
In the end, you should have something like this
pwmOneDutyCycle = None def before_first_request(): global pwmOneDutyCycle def remoteInput(): global pwmOneDutyCycle
Explanation
a) When your file loads, it initializes the variable
pwmOneDutyCycle
to a value of Noneb) Then before the first request is sent, it updates that value to 0
c) Finally in remoteInput, it increases the value by 10
Answered By - NoCommandLine Answer Checked By - David Marino (WPSolving Volunteer)