Here is couple of my code: (main class)
import RPi.GPIO as GPIO
import os
import pigpio
import subprocess
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
pigpio.exceptions = False
pi = pigpio.pi()
class FORWARD(object):
def __init__(self):
self.GPIO = GPIO
self.GPIO_TRIGGER = GPIO_TRIGGER
self.GPIO_ECHO = GPIO_ECHO
def setup():
ENGA = 4
ENGB = 17
ENABLEA = 23
ENABLEB = 24
GPIO.setup(ENGA, GPIO.OUT)
GPIO.setup(ENGB, GPIO.OUT)
GPIO.setup(ENABLEA, GPIO.OUT)
GPIO.setup(ENABLEB, GPIO.OUT)
GPIO_TRIGGER = 14
GPIO_ECHO = 11
def frwd(self):
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.OUT)
GPIO.output(ENABLEB, True)
GPIO.output(ENABLEA, True)
GPIO.output(ENGA, False)
GPIO.output(ENGB, False)
and the sec. file:
from ctrl import FORWARD
run = FORWARD()
run.setup()
run.frwd()
And here is my question: Why it's not working? I am receiving error with the global names:
Traceback (most recent call last):
File "go.py", line 2, in <module>
run = FORWARD()
File "/root/ctrl.py", line 22, in __init__
self.GPIO_TRIGGER = GPIO_TRIGGER
NameError: global name 'GPIO_TRIGGER' is not defined
My point is - i just want to make a 'setup' function in which i will define PINS and GPIO outputs, then i want to define more methods (e.g - backward, stop, etc.). So what's about these selfs or how should it write?
Regards, Maciej
You should read the Python tutorial on classes. https://docs.python.org/2/tutorial/classes.html
The first argument to every method on a class is an instance of that class. It's convention to refer to this variable as self
. So your setup
method should really have self
as an argument.
The specific error you are receiving is with the line:
self.GPIO_TRIGGER = GPIO_TRIGGER
You're attempting to set the GPIO_TRIGGER
property of the instance to the variable GPIO_TRIGGER
. However, the GPIO_TRIGGER
hasn't been defined within the scope that the class is defined. i.e. you haven't defined it anywhere, and haven't imported it from somewhere else. You'll have similar issues with GPIO_ECHO.
Presumably you need to define these variables yourself, e.g.
GPIO_TRIGGER = 7
GPIO_ECHO = 8
Adjust accordingly to the pins you're using.