-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
trying to import RPi.GPIO in module
Can someone tell me how to successfully import RPi.GPIO and use it within methods within a class.....
I have s.py :
import RPi.GPIO as GPIO
class xxx:
GPIO.setmode(GPIO.BOARD)
def func(self):
GPIO.setup.......etc...
CLI Error NameError: name 'GPIO' is not defined
thank you
Steve
I have s.py :
import RPi.GPIO as GPIO
class xxx:
GPIO.setmode(GPIO.BOARD)
def func(self):
GPIO.setup.......etc...
CLI Error NameError: name 'GPIO' is not defined
thank you
Steve
Re: trying to import RPi.GPIO in module
This works for me, Pi 3B, Buster, Python 2.7 and Python 3 ...
Perhaps post your full code as that may reveal where the issue lies.
Code: Select all
import RPi.GPIO as GPIO
class xxx:
GPIO.setmode(GPIO.BOARD)
print("[1]")
def configure(self):
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
print("[2]")
x = xxx()
x.configure()
Code: Select all
pi@Pi3B:~/tmp $ python s.py
[1]
[2]
pi@Pi3B:~/tmp $ python3 s.py
[1]
[2]
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
Here's code...I'm new to Python / Pi, so I'm sure I'm doing something semantically wrong:
import RPi.GPIO as gpio
class servoSL500:
"""....mxxDC (Duty Cycle) values are % of Period which is in ms"""
def __init__(self, minDC = 2, maxDC = 11, pwmPeriod = 20, boardPin = 12):
"""constructor for servoSL500"""
self.minDC = minDC
self.maxDC = maxDC
self.pwmPeriod = pwmPeriod
self.boardPin = boardPin
self.currentValue = 2
gpio.cleanup()
gpio.setmode(gpio.BOARD)
def setPwm(self, gpio):
"""move servo to a position bounded by 0 - 180 degrees"""
while(1):
newValue = input ("Enter the pulse width between " + str(self.minDC) + " and " + str(self.maxDC) + " ")
if ((self.minDC > float(newValue)) or (self.maxDC < float(newValue))):
print ("try again, value out of bound")
continue
else:
break
self.currentValue = float(newValue)
gpio.setup(self.boardPin, gpio.OUT)
t = self.gpio.PWM(self.boardPin, float(1000/self.pwmPeriod))
t.start(self.currentValue)
return 0
The error I keep getting is
AttributeError: 'servoSL500' object has no attribute 'gpio' on line gpio.setup(self.boardPin, gpio.OUT)
thanks
import RPi.GPIO as gpio
class servoSL500:
"""....mxxDC (Duty Cycle) values are % of Period which is in ms"""
def __init__(self, minDC = 2, maxDC = 11, pwmPeriod = 20, boardPin = 12):
"""constructor for servoSL500"""
self.minDC = minDC
self.maxDC = maxDC
self.pwmPeriod = pwmPeriod
self.boardPin = boardPin
self.currentValue = 2
gpio.cleanup()
gpio.setmode(gpio.BOARD)
def setPwm(self, gpio):
"""move servo to a position bounded by 0 - 180 degrees"""
while(1):
newValue = input ("Enter the pulse width between " + str(self.minDC) + " and " + str(self.maxDC) + " ")
if ((self.minDC > float(newValue)) or (self.maxDC < float(newValue))):
print ("try again, value out of bound")
continue
else:
break
self.currentValue = float(newValue)
gpio.setup(self.boardPin, gpio.OUT)
t = self.gpio.PWM(self.boardPin, float(1000/self.pwmPeriod))
t.start(self.currentValue)
return 0
The error I keep getting is
AttributeError: 'servoSL500' object has no attribute 'gpio' on line gpio.setup(self.boardPin, gpio.OUT)
thanks
-
- Posts: 663
- Joined: Fri Aug 25, 2017 2:58 pm
- Location: Blackstone River Valley, MA, USA
Re: trying to import RPi.GPIO in module
It's hard to tell without the essential Python formatting, please use the code tags to preserve formatting of code.
However I think the problem is that:
Should be:
Also remove any parameter in the code that calls your setPwm().
With a global import you can reference it anywhere in the module so don't pass it as parameter inside the module.
However I think the problem is that:
Code: Select all
def setPwm(self, gpio):
Code: Select all
def setPwm(self):
With a global import you can reference it anywhere in the module so don't pass it as parameter inside the module.
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
ok....dumb question....How do I set up code tags ? I am using Geany....is it a flag somewhere or do I have to download/link a file?
Re: trying to import RPi.GPIO in module
ridgerunnersjw wrote: ↑Sat Jul 27, 2019 2:10 pmok....dumb question....How do I set up code tags ? I am using Geany....is it a flag somewhere or do I have to download/link a file?
Nothing to do with the editor on your workstation, and nothing to download.
Just use the Code 'button' (5th from the left) at the top of the forum message submission screen.
Re: trying to import RPi.GPIO in module
You'll find it here....
Paste your code between the code boxes
Paste your code between the code boxes
- Attachments
-
- IMG_20190727_153441.jpg (57.31 KiB) Viewed 2352 times
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
Thank you....Ok I hope this helps....Anyway I have a basic servo connected to the Pi 3 and if I run the commands from CLI all works but when I create this class in python, save and then try and run from CLI the code below does not do anything....(I have shortened the code from previous examples as I am trying to track down what is going on....My CLI entry is
from steveClass.py import servoSL500
d = servoSL500()
d.setPwm()
Code is below:
from steveClass.py import servoSL500
d = servoSL500()
d.setPwm()
Code is below:
Code: Select all
import RPi.GPIO as gpio
class servoSL500:
"""....mxxDC (Duty Cycle) values are % of Period which is in ms"""
def __init__(self, minDC = 2, maxDC = 11, pwmPeriod = 20, boardPin = 12):
"""constructor for servoSL500"""
self.minDC = minDC
self.maxDC = maxDC
self.pwmPeriod = pwmPeriod
self.boardPin = boardPin
self.currentValue = 2
gpio.cleanup()
gpio.setmode(gpio.BOARD)
def setPwm(self):
gpio.setup(self.boardPin, gpio.OUT)
r = gpio.PWM(self.boardPin, 50)
r.start(2)
return ("good")
Re: trying to import RPi.GPIO in module
What commands?if I run the commands from CLI all works
In a Linux context, 'CLI' is usually taken to mean a shell prompt. That doesn't seem to be the case here?
Re: trying to import RPi.GPIO in module
Hello, when you say "the code below does not do anything", I assume there are no error messages. Did you try to print the result of the d.setPwm()-method like
just to be sure that this method is called ?
If you use a basic servo, the valid pulse with are 1 to 2 ms in the 20 ms frame==50Hz. (Some servo have slightly different values). The "r.start(2)" sets , according to the docs,
p.start(dc) # where dc is the duty cycle (0.0 <= dc <= 100.0)
1ms is 5%, 2 ms is 10%. So start(2) is possibly too small and the servo does not react. Try values between 5.0 and 10.0.
Also if the servo is already at target position, there will be no visible action.
Code: Select all
print( dd.setPwm())
If you use a basic servo, the valid pulse with are 1 to 2 ms in the 20 ms frame==50Hz. (Some servo have slightly different values). The "r.start(2)" sets , according to the docs,
p.start(dc) # where dc is the duty cycle (0.0 <= dc <= 100.0)
1ms is 5%, 2 ms is 10%. So start(2) is possibly too small and the servo does not react. Try values between 5.0 and 10.0.
Also if the servo is already at target position, there will be no visible action.
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
If I print (d.setPwm()) at terminal I get "good"....
Yes the values between 2 and 11 work for this servo....
When I run from the terminal (CLI) I can issue all the gpio.commands and the servo moves as expected...
from RPi.GPIO as gpio
gpio.cleanup()
gpio.setmode(gpio.BOARD)
gpio.setup(12, gpio.OUT)
r = gpio.PWM(12, 50)
r.start(2)
My class file compiles fine and as I said if I then issue the following at the command line:
from steveClass import servoSL500
d = servoSL500
d.setPwm()
The return is
'good'
but NO servo changes
Yes the values between 2 and 11 work for this servo....
When I run from the terminal (CLI) I can issue all the gpio.commands and the servo moves as expected...
from RPi.GPIO as gpio
gpio.cleanup()
gpio.setmode(gpio.BOARD)
gpio.setup(12, gpio.OUT)
r = gpio.PWM(12, 50)
r.start(2)
My class file compiles fine and as I said if I then issue the following at the command line:
from steveClass import servoSL500
d = servoSL500
d.setPwm()
The return is
'good'
but NO servo changes
Re: trying to import RPi.GPIO in module
Isn't the Servo in the target position as a result of the previous test?The return is
'good'
but NO servo changes
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
Yes I do change the numbers in r.start to ensure it moves but even more than this....
fundamentally import RPi.GPIO as gpio is NOT working within the file steveClass.py
if I run at CLI
import steveClass
print (servoSL500)
I get <class 'steveClass.servoSL500'>
however if I do
print (gpio)
I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'gpio' is not defined
Am I missing something fundamental here??
fundamentally import RPi.GPIO as gpio is NOT working within the file steveClass.py
if I run at CLI
import steveClass
print (servoSL500)
I get <class 'steveClass.servoSL500'>
however if I do
print (gpio)
I get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'gpio' is not defined
Am I missing something fundamental here??
Re: trying to import RPi.GPIO in module
What is the result of
(Still unclear what this 'CLI' is that you are using.. )
Code: Select all
import RPi.GPIO as gpio
print (gpio)
(Still unclear what this 'CLI' is that you are using.. )
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
sorry....CLI : Command Line Interface.....synonymous with the terminal...I open a terminal do sudo python3 in raspbian and after python opens in the terminal I run the commands one at a time
If I run the commands you requested in the terminal the result is:
<module 'RPi.GPIO' from '/usr/lib/python3/dist-packages/RPi/GPIO/__init__.py'>
but if I
import steveClass
print (gpio)
I get the aforementioned error
Is it possible that after you import the file steveClass.py that I have to do something else to get the first line in the file (import RPi.GPIO as gpio) to be "active"
If I run the commands you requested in the terminal the result is:
<module 'RPi.GPIO' from '/usr/lib/python3/dist-packages/RPi/GPIO/__init__.py'>
but if I
import steveClass
print (gpio)
I get the aforementioned error
Is it possible that after you import the file steveClass.py that I have to do something else to get the first line in the file (import RPi.GPIO as gpio) to be "active"
Re: trying to import RPi.GPIO in module
Untested, but try:
For the background see something like https://docs.python.org/3/tutorial/classes.html for details of Modules, Classes and Namespaces.
And I think you are performing your tests using the Python3 interpreter interactively, not the system CLI (shell) prompt.
Code: Select all
import steveClass
print (steveClass.gpio)
For the background see something like https://docs.python.org/3/tutorial/classes.html for details of Modules, Classes and Namespaces.
And I think you are performing your tests using the Python3 interpreter interactively, not the system CLI (shell) prompt.
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
thank you! Yes that works....Now can I lead you back to the original problem....I'm beginning to see the error of my ways....clearly with "import RPi.GPIO....."at the top of the file and NOT within the class creates grief when I
from steveClass import servoSL500
guessing at the CLI I should be typing
import steveClass
which gives me access to the gpio
thoughts?
from steveClass import servoSL500
guessing at the CLI I should be typing
import steveClass
which gives me access to the gpio
thoughts?
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
At the end of the day...I do not know how to correctly instantiate this. I would like to test it at the terminal level and I do not completely understand how to make this happen....If I independently issue the import and calls of gpio one at a time at the command line the servo works as expected...
Code: Select all
import RPi.GPIO as gpio
class servoSL500:
"""....mxxDC (Duty Cycle) values are % of Period which is in ms"""
def __init__(self, minDC = 2, maxDC = 11, pwmPeriod = 20, boardPin = 12):
"""constructor for servoSL500"""
self.minDC = minDC
self.maxDC = maxDC
self.pwmPeriod = pwmPeriod
self.boardPin = boardPin
self.currentValue = 2
gpio.cleanup()
gpio.setmode(gpio.BOARD)
def setPwm(self):
gpio.setup(self.boardPin, gpio.OUT)
r = gpio.PWM(self.boardPin, 50)
r.start(2)
return ("good")
Re: trying to import RPi.GPIO in module
No, it only gives you access to "steveClass".ridgerunnersjw wrote: ↑Sat Jul 27, 2019 6:54 pmguessing at the CLI I should be typing
import steveClass
which gives me access to the gpio
You can only interact with "gpio" through interacting with "steveClass".
Not sure how you are getting that. It doesn't work for me, using Python 2 or Python 3, which is what I would have expected -ridgerunnersjw wrote: ↑Sat Jul 27, 2019 4:52 pmMy class file compiles fine and as I said if I then issue the following at the command line:
from steveClass import servoSL500
d = servoSL500
d.setPwm()
The return is
'good'
but NO servo changes
Code: Select all
Python 2.7.16 (default, Apr 6 2019, 01:42:57)
[GCC 8.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from steveClass import servoSL500
>>> d = servoSL500
>>> d.setPwm()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unbound method setPwm() must be called with servoSL500 instance as first argument (got nothing instead)
>>>
Code: Select all
Python 3.7.3 (default, Apr 3 2019, 05:39:12)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from steveClass import servoSL500
>>> d = servoSL500
>>> d.setPwm()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: setPwm() missing 1 required positional argument: 'self'
>>>
Last edited by hippy on Sun Jul 28, 2019 12:28 pm, edited 2 times in total.
-
- Posts: 2247
- Joined: Thu Feb 05, 2015 11:25 pm
Re: trying to import RPi.GPIO in module
I'd suggest writing a simple program without classes and see if your servo moves as expected
Re: trying to import RPi.GPIO in module
think "the problem" is the pwm-variable
When the method terminates, the r-variable is destroyed and PWM terminates. To vaIidate this, I added a time.sleep(10) after the r.start() and got some pulses on my oscilloscope.
When changing this variable to a class member, then it works. It's lifetime is then as long as the class itself.
Code: Select all
def setPwm(self):
gpio.setup(self.boardPin, gpio.OUT)
r = gpio.PWM(self.boardPin, 50)
r.start(2)
return ("good")
When changing this variable to a class member, then it works. It's lifetime is then as long as the class itself.
Code: Select all
def setPwm(self):
print("setPwm", self.boardPin)
self.r = gpio.PWM(self.boardPin, 50)
self.r.start(2)
return ("good")
-
- Posts: 39
- Joined: Sat Jul 20, 2019 5:32 pm
Re: trying to import RPi.GPIO in module
Thanks for all the help from everyone....ghp you hit it on the head....sleep(1) after r.start() solves the problem!
Thanks all!!
Thanks all!!