Search code examples
pythonflaskraspberry-pi

Flask Setup Code. UnboundLocalError: local variable 'pwmOneDutyCycle' referenced before assignment


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

    1. You need to have pwmOneDutyCycle outside of the 2 functions - before_first_request, remoteInput

    2. 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
      
      
    3. Explanation

      a) When your file loads, it initializes the variable pwmOneDutyCycle to a value of None

      b) Then before the first request is sent, it updates that value to 0

      c) Finally in remoteInput, it increases the value by 10