Variable definition error Pyboard V1.1

The official pyboard running MicroPython.
This is the reference design and main target board for MicroPython.
You can buy one at the store.
Target audience: Users with a pyboard.
Post Reply
James Canova
Posts: 3
Joined: Wed Aug 18, 2021 11:04 pm

Variable definition error Pyboard V1.1

Post by James Canova » Sun Aug 29, 2021 6:20 pm

Hello,

I am receiving the following error from the code below.

I have marked this in the code, see: if global_bPbPushed == True: #line 44, error occurs here***

Any help would be appreciated.


James

========================= RESTART =========================
>>> %Run switches.py
Traceback (most recent call last):
File "/home/james/Public/mpProjects/Project_4/switches.py", line 66, in <module>
File "/home/james/Public/mpProjects/Project_4/switches.py", line 44, in mainloop
NameError: local variable referenced before assignment

Code: Select all

#switches.py, Project_4
#Micropython and Pyboard V1.1
#Date August 29, 2021

import micropython
import machine
import pyb
from pyb import Pin

micropython.alloc_emergency_exception_buf(100)

#for identifying pyboard LEDs
red = 1
green = 2
yellow = 3
blue = 4

#setup push buttons
pb1 = Pin('X1', Pin. IN, Pin.PULL_UP)
pb2 = Pin('X2', Pin.IN, Pin.PULL_UP)

#setup variables
global global_nNumPbPushed
global global_bPbPushed

global_bPbPushed = False
global_nNumPbPushed = None


#ISR for push buttons
#note that pin is type int
def pbChanged(pin):

       print('Pin changed = ', pin) 
       global global_bPbPushed
       global_bPbPushed = True
       

#main loop 
def mainloop():

    while True:

        if global_bPbPushed == True:    #line 44, error occurs here***

            state = machine.disable_irq() #disable all interrupts

            if global_nNumPbPushed == 0: 
                pyb.LED(green).on()                
                    
            elif global_nNumPbPushed == 1: 
                pyb.LED(blue).on()

            else:   #neither switch pressed so do nothing
                pass

            machine.enable_irq(state) #re-enable all interrupts to previous state

        else:  
            pass
      
    global_bPbPushed = False  
    global_nNumPbPushed = None
    
#run main loop  
mainloop()

User avatar
Roberthh
Posts: 2841
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Variable definition error Pyboard V1.1

Post by Roberthh » Mon Aug 30, 2021 6:21 am

You have to put the statements:

global global_nNumPbPushed
global global_bPbPushed

into the respective function, which assigns to the variables. In this case the function mainloop().

User avatar
pythoncoder
Posts: 5373
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Variable definition error Pyboard V1.1

Post by pythoncoder » Mon Aug 30, 2021 5:59 pm

This is a common misunderstanding. I remember having difficulties with global when I was learning Python.
Peter Hinch

Post Reply