ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

trying to import RPi.GPIO in module

Tue Jul 23, 2019 9:10 pm

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

hippy
Posts: 6099
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: trying to import RPi.GPIO in module

Tue Jul 23, 2019 9:26 pm

This works for me, Pi 3B, Buster, Python 2.7 and Python 3 ...

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]
Perhaps post your full code as that may reveal where the issue lies.

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 1:33 pm

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

Paul Hutch
Posts: 398
Joined: Fri Aug 25, 2017 2:58 pm
Location: Blackstone River Valley, MA, USA
Contact: Website

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 1:52 pm

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:

Code: Select all

def setPwm(self, gpio):
Should be:

Code: Select all

def setPwm(self):
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.

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 2:10 pm

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?

User avatar
B.Goode
Posts: 8889
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 2:24 pm

ridgerunnersjw wrote:
Sat Jul 27, 2019 2:10 pm
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?

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.

gordon77
Posts: 4237
Joined: Sun Aug 05, 2012 3:12 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 2:35 pm

You'll find it here....

Paste your code between the code boxes
Attachments
IMG_20190727_153441.jpg
IMG_20190727_153441.jpg (57.31 KiB) Viewed 788 times

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 2:43 pm

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:

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")

User avatar
B.Goode
Posts: 8889
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 2:51 pm

if I run the commands from CLI all works
What commands?

In a Linux context, 'CLI' is usually taken to mean a shell prompt. That doesn't seem to be the case here?

ghp
Posts: 1419
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 3:02 pm

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

Code: Select all

print( dd.setPwm())
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.

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 4:52 pm

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

User avatar
B.Goode
Posts: 8889
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 5:07 pm

The return is
'good'

but NO servo changes
Isn't the Servo in the target position as a result of the previous test?

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 5:12 pm

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??

User avatar
B.Goode
Posts: 8889
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 5:41 pm

What is the result of

Code: Select all

import RPi.GPIO as gpio
print (gpio)

(Still unclear what this 'CLI' is that you are using.. )

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 5:52 pm

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"

User avatar
B.Goode
Posts: 8889
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 6:35 pm

Untested, but try:

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.

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 6:54 pm

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?

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sat Jul 27, 2019 7:14 pm

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")

hippy
Posts: 6099
Joined: Fri Sep 09, 2011 10:34 pm
Location: UK

Re: trying to import RPi.GPIO in module

Sun Jul 28, 2019 12:08 pm

ridgerunnersjw wrote:
Sat Jul 27, 2019 6:54 pm
guessing at the CLI I should be typing
import steveClass
which gives me access to the gpio
No, it only gives you access to "steveClass".

You can only interact with "gpio" through interacting with "steveClass".
ridgerunnersjw wrote:
Sat Jul 27, 2019 4:52 pm
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
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 -

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'
>>>
Added: Right; you earlier had "d = servoSL500()", and yes that should work.
Last edited by hippy on Sun Jul 28, 2019 12:28 pm, edited 2 times in total.

mattmiller
Posts: 2114
Joined: Thu Feb 05, 2015 11:25 pm

Re: trying to import RPi.GPIO in module

Sun Jul 28, 2019 12:13 pm

I'd suggest writing a simple program without classes and see if your servo moves as expected

ghp
Posts: 1419
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: trying to import RPi.GPIO in module

Sun Jul 28, 2019 6:01 pm

think "the problem" is the pwm-variable

Code: Select all

    def setPwm(self):
        gpio.setup(self.boardPin, gpio.OUT)
        r = gpio.PWM(self.boardPin, 50)
        r.start(2)
        return ("good")
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):
        print("setPwm", self.boardPin)
        self.r = gpio.PWM(self.boardPin, 50)

        self.r.start(2)
        return ("good")

ridgerunnersjw
Posts: 30
Joined: Sat Jul 20, 2019 5:32 pm

Re: trying to import RPi.GPIO in module

Sun Jul 28, 2019 7:22 pm

Thanks for all the help from everyone....ghp you hit it on the head....sleep(1) after r.start() solves the problem!

Thanks all!!

Return to “Python”