A simple program controlling Raspberry Pi GPIO


21 posts
by hzhwang » Mon Nov 05, 2012 11:16 pm
Hi everyone,

I wrote a simple program that control GPIO in LXDE. Currently you can control GPIO 4,17,18,21,22,23,24,25 high/low just simply press the button.
Image
Video:
http://www.youtube.com/watch?v=15m4-KmMlJM

I am new to Raspberry Pi hardware and Python/Tkinter. I wrote it under Raspbian, it should works for other distributions. But remember this program must run as root.

It still under development, and need your kindly comment and suggestions.

Thank you in advance.


Code: Select all
from Tkinter import *
import RPi.GPIO as GPIO
import time

GPIO.setmode( GPIO.BCM )
GPIO.setup( 4, GPIO.OUT)
GPIO.setup(17, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(21, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)
GPIO.setup(25, GPIO.OUT)

class App:
    io4=0
    io17=0
    io18=0
    io21=0
    io22=0
    io23=0
    io24=0
    io25=0

def __init__(self, master):

        frame = Frame(master)
        frame.pack()

       
        self.p1 = Button(frame, text="3V3 Power", fg="yellow", command=self.reserved)
        self.p1.pack(side=LEFT)
        self.p1.grid(row=0,column=0)

        self.p2 = Button(frame, text="5V Power", fg="red", command=self.reserved)
        self.p2.pack(side=LEFT)
        self.p2.grid(row=0,column=1)

        self.p3 = Button(frame, text="GPIO 0", fg="blue", command=self.reserved)
        self.p3.pack(side=LEFT)
        self.p3.grid(row=1,column=0)

        self.p4 = Button(frame, text="5V Power", fg="red",command=self.reserved)
        self.p4.pack(side=LEFT)
        self.p4.grid(row=1,column=1)

        self.p5 = Button(frame, text="GPIO 1", fg="blue",command=self.reserved)
        self.p5.pack(side=LEFT)
        self.p5.grid(row=2,column=0)

        self.p6 = Button(frame, text="Ground", command=self.reserved)
        self.p6.pack(side=LEFT)
        self.p6.grid(row=2,column=1)

        self.p7 = Button(frame, text="GPIO 4",fg="green", command=self.gpio4)
        self.p7.pack(side=LEFT)
        self.p7.grid(row=3,column=0)

        self.p8 = Button(frame, text="GPIO 14",fg="yellow", command=self.reserved)
        self.p8.pack(side=LEFT)
        self.p8.grid(row=3,column=1)

        self.p9 = Button(frame, text="Ground", command=self.reserved)
        self.p9.pack(side=LEFT)
        self.p9.grid(row=4,column=0)

        self.p10 = Button(frame, text="GPIO 15",fg="yellow", command=self.reserved)
        self.p10.pack(side=LEFT)
        self.p10.grid(row=4,column=1)

        self.p11 = Button(frame, text="GPIO 17",fg="green", command=self.reserved)
        self.p11.pack(side=LEFT)
        self.p11.grid(row=5,column=0)
        self.p12 = Button(frame, text="GPIO 18",fg="green", command=self.reserved)
        self.p12.pack(side=LEFT)
        self.p12.grid(row=5,column=1)

        self.p13 = Button(frame, text="GPIO 21",fg="green", command=self.reserved)
        self.p13.pack(side=LEFT)
        self.p13.grid(row=6,column=0)

        self.p14 = Button(frame, text="Ground", command=self.reserved)
        self.p14.pack(side=LEFT)
        self.p14.grid(row=6,column=1)

        self.p15 = Button(frame, text="GPIO 22",fg="green", command=self.gpio22)
        self.p15.pack(side=LEFT)
        self.p15.grid(row=7,column=0)

        self.p16 = Button(frame, text="GPIO 23",fg="green", command=self.gpio23)
        self.p16.pack(side=LEFT)
        self.p16.grid(row=7,column=1)

        self.p17 = Button(frame, text="3V3 Power",fg="yellow", command=self.reserved)
        self.p17.pack(side=LEFT)
        self.p17.grid(row=8,column=0)

        self.p18 = Button(frame, text="GPIO 24",fg="green", command=self.gpio24)
        self.p18.pack(side=LEFT)
        self.p18.grid(row=8,column=1)
        self.p19 = Button(frame, text="GPIO 10", fg="purple",command=self.reserved)
        self.p19.pack(side=LEFT)
        self.p19.grid(row=9,column=0)

        self.p20 = Button(frame, text="Ground", command=self.reserved)
        self.p20.pack(side=LEFT)
        self.p20.grid(row=9,column=1)

        self.p21 = Button(frame, text="GPIO 9", fg="purple",command=self.reserved)
        self.p21.pack(side=LEFT)
        self.p21.grid(row=10,column=0)

        self.p22 = Button(frame, text="GPIO 25", fg="green",command=self.gpio25)
        self.p22.pack(side=LEFT)
        self.p22.grid(row=10,column=1)

        self.p23 = Button(frame, text="GPIO 11", fg="purple",command=self.reserved)
        self.p23.pack(side=LEFT)
        self.p23.grid(row=11,column=0)

        self.p24 = Button(frame, text="GPIO 8", fg="purple",command=self.reserved)
        self.p24.pack(side=LEFT)
        self.p24.grid(row=11,column=1)

        self.p25 = Button(frame, text="Ground", command=self.reserved)
        self.p25.pack(side=LEFT)
        self.p25.grid(row=12,column=0)

        self.p26 = Button(frame, text="GPIO 7", fg="purple",command=self.reserved)
        self.p26.pack(side=LEFT)
        self.p26.grid(row=12,column=1)


    def gpio4(self):
        if self.io4==0:
          GPIO.output(4, GPIO.HIGH)
          self.io4=1
        else:
          GPIO.output(4, GPIO.LOW)
          self.io4=0
        return

    def gpio17(self):
        if self.io17==0:
          GPIO.output(17, GPIO.HIGH)
          self.io17=1
        else:
          GPIO.output(17, GPIO.LOW)
          self.io17=0
        return

    def gpio18(self):
        if self.io18==0:
          GPIO.output(18, GPIO.HIGH)
          self.io18=1
        else:
          GPIO.output(18, GPIO.LOW)
          self.io18=0
        return


    def gpio21(self):
        if self.io21==0:
          GPIO.output(21, GPIO.HIGH)
          self.io21=1
        else:
          GPIO.output(21, GPIO.LOW)
          self.io21=0
        return

    def gpio22(self):
        if self.io22==0:
          GPIO.output(22, GPIO.HIGH)
          self.io22=1
        else:
          GPIO.output(22, GPIO.LOW)
          self.io22=0
        return

    def gpio23(self):
        if self.io23==0:
          GPIO.output(23, GPIO.HIGH)
          self.io23=1
        else:
          GPIO.output(23, GPIO.LOW)
          self.io23=0
        return

    def gpio24(self):
        if self.io24==0:
          GPIO.output(24, GPIO.HIGH)
          self.io24=1
        else:
          GPIO.output(24, GPIO.LOW)
          self.io24=0
        return

    def gpio25(self):
        if self.io25==0:
          GPIO.output(25, GPIO.HIGH)
          self.io25=1
        else:
          GPIO.output(25, GPIO.LOW)
          self.io25=0
        return



    def reserved(self):
        return

root = Tk()

app = App(root)

root.mainloop()

==
My RaspberryPi playground http://ezzep.blogspot.com
Posts: 19
Joined: Mon Oct 22, 2012 4:44 pm
by sompor9 » Tue Nov 06, 2012 8:05 am
Thank you so much
Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by vallesasecas » Tue Nov 06, 2012 8:09 am
Thanks for your code lines!

Ill try to use a little to understand a little better the uses of GPIO in raspberry...step by step.
Posts: 6
Joined: Mon Oct 29, 2012 6:39 am
by BlackJack » Tue Nov 06, 2012 8:42 am
@hzhwang: Way too much code repitition. When you copy and pasting a piece of code over and over again think a moment about the differences and make a function of it that gets the differences as arguments.

Numbering names is very often a sign you actually want a list or some other data structure instead of all the names. All the `p*` attributes are not even used.

You are `pack()`\ing *and* `grid()`\ing all buttons – the `pack()` has no effect then. There can always be just one layout manager for placing a widget.

Asterisk imports pollute the namespace of the module. `Tkinter` contains ≈190 names. It makes finding out where a name comes from harder if more than one *-import is used. And there is the risk of name collisions — several modules containing the same name for different things. With `Tkinter` it is common to import it as `tk`.

The `time` import is not used anywhere.

The `io*` names should not be defined at class level. They are instance attributes. And a dictionary mapping pin number to state would be more flexible.

Untested:
Code: Select all
import Tkinter as tk
from functools import partial
import RPi.GPIO as GPIO


class App(object):

    def __init__(self, master):

        frame = tk.Frame(master)
        frame.pack()
       
        pins = [4, 17, 18, 21, 22, 23, 24, 25]
        GPIO.setmode(GPIO.BCM)
        for pin in pins:
            GPIO.setup(pin, GPIO.OUT)
       
        self.pin_states = dict((p, False) for p in pins)
        #
        # Green is a special color only to be used for the pins that can be
        # toggled.
        #
        columns_data = [
            [
                ('3V3 Power', 'yellow'),
                (0, 'blue'),
                (1, 'blue'),
                (4, 'green'),
                ('Ground', 'black'),
                (17, 'green'),
                (21, 'green'),
                (22, 'green'),
                ('3V3 Power', 'yellow'),
                (10, 'purple'),
                (9, 'purple'),
                (11, 'purple'),
                ('Ground', 'black'),
            ],
            [
                ('5V Power', 'red'),
                ('5V Power', 'red'),
                ('Ground', 'black'),
                (14, 'yellow'),
                (15, 'yellow'),
                (18, 'green'),
                ('Ground', 'black'),
                (23, 'green'),
                (24, 'green'),
                ('Ground', 'black'),
                (25, 'green'),
                (8, 'purple'),
                (7, 'purple'),
            ],
        ]

        for column_no, column_data in enumerate(columns_data):
            for row_no, (value, colour) in enumerate(column_data):
                text = 'GPIO %d' % value if isinstance(value, int) else value
                command = (
                    partial(self.toggle_pin, value)
                    if colour == 'green'
                    else None
                )
                assert (
                    colour == 'green' and value in self.pin_states
                    or colour != 'green' and value not in self.pin_states
                )
                button = tk.Button(frame, text, fg=colour, command=command)
                button.grid(row=row_no, column=column_no, sticky='WE')
   
    def toggle_pin(self, pin):
        self.pin_states[pin] = state = not self.pin_states[pin]
        GPIO.output(pin, state)


def main():
    root = tk.Tk()
    app = App(root)
    root.mainloop()


if __name__ == '__main__':
    main()
Code: Select all
while not self.asleep():
    sheep += 1
Posts: 288
Joined: Sat Aug 04, 2012 8:28 am
by hzhwang » Tue Nov 06, 2012 8:56 am
Sorry everyone

I found a problem in my code, I didn't notice it when I paste the code

Code: Select all
class App:
    io4=0
    io17=0
    io18=0
    io21=0
    io22=0
    io23=0
    io24=0
    io25=0

def __init__(self, master):


should be:

Code: Select all
class App:
    io4=0
    io17=0
    io18=0
    io21=0
    io22=0
    io23=0
    io24=0
    io25=0

    def __init__(self, master):


Source code can be download here:
https://s3.amazonaws.com/HZ-Studio/rpi_gpio_gui.py.zip

Sorry for any inconvenience
==
My RaspberryPi playground http://ezzep.blogspot.com
Posts: 19
Joined: Mon Oct 22, 2012 4:44 pm
by hzhwang » Tue Nov 06, 2012 9:00 am
BlackJack wrote:@hzhwang: Way too much code repitition. When you copy and pasting a piece of code over and over again think a moment about the differences and make a function of it that gets the differences as arguments.

...


Thank for your comment and suggestions ,it helps.

I will refine my code again.

Thank you
==
My RaspberryPi playground http://ezzep.blogspot.com
Posts: 19
Joined: Mon Oct 22, 2012 4:44 pm
by rlust » Thu Nov 08, 2012 11:46 pm
Trying out this code.

When I press the button on one of the GPIO buttons let's say 17 should the output go low.

I was hooking it to a led with a current limiting resistor. I thought the led would turn off, but it stays on when I press the button. Am I missing something here?


thanks for the code!!
Well done!

Randy
Posts: 2
Joined: Thu Aug 30, 2012 4:22 pm
by techpaul » Fri Nov 09, 2012 10:00 am
rlust wrote:Trying out this code.

When I press the button on one of the GPIO buttons let's say 17 should the output go low.

I was hooking it to a led with a current limiting resistor. I thought the led would turn off, but it stays on when I press the button. Am I missing something here?


thanks for the code!!
Well done!

Randy

If the code has been done to use GPIO pin connector numbering - pin 17 is 3V3 power and cannot be turned low, except by powering down the whole Pi. If done as chip numbering then yes pin 11 on connector should go low.

The code shows that only those with green writing can be changed.

A quick scan of peoples code suggest they have a mix up between connector and chip numbering their code. Whilst the graphic interface is done as connector pin numbering, probably would be more understandable code to match the graphic so connector pin numbering was used throughout
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/
Posts: 1482
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
by sompor9 » Sat Nov 10, 2012 11:32 am
Hi All

Please recommend me to fix error when run program
Attachments
ScreenHunter_12 Nov. 10 18.30.jpg
ScreenHunter_12 Nov. 10 18.30.jpg (23.36 KiB) Viewed 6622 times
Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by techpaul » Sat Nov 10, 2012 12:16 pm
sompor9 wrote:Hi All

Please recommend me to fix error when run program

As it says you need to run as root.

Looks like you are in Windows interface and running IDLE by the icon

When trying to do IDLE and access GPIO do it this way

Start menu button

Click RUN

Enter in box

sudo IDLE

Then try your test
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/
Posts: 1482
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
by sompor9 » Sun Nov 11, 2012 5:00 am
Please help me agian

i found this error but i check lib normaly

and lib installed alrealy
Attachments
ScreenHunter_15 Nov. 11 11.56.jpg
ScreenHunter_15 Nov. 11 11.56.jpg (27.88 KiB) Viewed 6538 times
Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by sompor9 » Sun Nov 11, 2012 5:02 am
Installed library alreadly.
Attachments
ScreenHunter_16 Nov. 11 11.58.jpg
ScreenHunter_16 Nov. 11 11.58.jpg (33.56 KiB) Viewed 6538 times
Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by croston » Sun Nov 11, 2012 8:35 am
Do you have any files or directories named RPi, RPi.py, GPIO, or GPIO.py in the same area as your script?
User avatar
Posts: 421
Joined: Sat Nov 26, 2011 12:33 pm
Location: Blackpool
by sompor9 » Sun Nov 11, 2012 10:49 am
Thanks for you answer
please more explaint issue about any GPIO file on the same directory..

and I have more detial for analyze this.

sudo python blink.py --> work

sudo ./blink.py --> not work
Attachments
ScreenHunter_17 Nov. 11 17.45.jpg
ScreenHunter_17 Nov. 11 17.45.jpg (44.39 KiB) Viewed 6494 times
Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by sompor9 » Sun Nov 11, 2012 11:01 am
This is blink.py for test my GPIO Function on top issue

Code: Select all
#' /usr/bin/python

import RPi.GPIO as GPIO
import time

count = 1

GPIO.setmode(GPIO.BOARD)
GPIO.setup(26,GPIO.OUT)

while (count <= 10):
        print '------ tick : ',count
        GPIO.output(26,GPIO.HIGH)
        print 'LED ON'
        time.sleep(.5)
        GPIO.output(26,GPIO.LOW)
        print 'LED OFF'
        time.sleep(.5)
        count = count + 1

GPIO.cleanup()

Posts: 13
Joined: Mon Oct 29, 2012 8:12 am
by techpaul » Sun Nov 11, 2012 1:02 pm
Change from this
Code: Select all
#' /usr/bin/python

To this
Code: Select all
#! /usr/bin/python

You had a typo
Just another techie on the net - For GPIO boards see http:///www.facebook.com/pcservicesreading
or http://www.pcserviceselectronics.co.uk/pi/
Posts: 1482
Joined: Sat Jul 14, 2012 6:40 pm
Location: Reading, UK
by hzhwang » Sun Dec 09, 2012 11:19 pm
Thanks for everyone comments and suggestions and sorry for late reply

This program requires RPi.GPIO Library and must run as root. It works under Rev.B v1.0, v2.0 may need some modification. GPIO numbering and color is referred to RPi Low-level peripherals - eLinux.org

http://elinux.org/Rpi_Low-level_periphe ... troduction

I made few change about graphic interface and hope it become more understandable. I rewrote the code and now is much simpler than before (I think)

Currently this program can control GPIO 4, 7, 8, 9, 10, 11, 14, 15, 17, 18, 21/27, 22, 23, 24, 25 output status high/low just simply press the button.

It still under development, and need your kindly comment and suggestions.
Thank you in advance.
==
My RaspberryPi playground http://ezzep.blogspot.com
Posts: 19
Joined: Mon Oct 22, 2012 4:44 pm
by charleslinquist » Mon Dec 10, 2012 4:32 pm
I'm trying to use the example, but I can't figure out how to load the RPi.GPIO library.

I went to the source,
http://code.google.com/p/raspberry-gpio ... loads/list

and tried

"wget http://code.google.com/p/raspberry-gpio ... b&can=2&q="

But that didn't work. So how do I get the library?

And when I invoke Python, and put the source there, and save the file with the extension .py, how do I make the file executable? Do I have to create a shell script such as -

#! bin/bash
example.py

and make it executable with chmod +x (name of my new shell script) ?
Posts: 19
Joined: Wed Sep 05, 2012 12:43 pm
by hzhwang » Mon Dec 10, 2012 5:04 pm
Hi,

charleslinquist wrote:I'm trying to use the example, but I can't figure out how to load the RPi.GPIO library.

I went to the source,
http://code.google.com/p/raspberry-gpio ... loads/list

and tried

"wget http://code.google.com/p/raspberry-gpio ... b&can=2&q="

But that didn't work. So how do I get the library?


I remember I download it by using midori (Browser in Raspbian's LXDE)



And when I invoke Python, and put the source there, and save the file with the extension .py, how do I make the file executable? Do I have to create a shell script such as -

#! bin/bash
example.py

and make it executable with chmod +x (name of my new shell script) ?


This program must run under LXDE, use the root Terminal and execute following command:
python rpi_gpio_gui.py
==
My RaspberryPi playground http://ezzep.blogspot.com
Posts: 19
Joined: Mon Oct 22, 2012 4:44 pm
by charleslinquist » Mon Dec 10, 2012 6:49 pm
Isn't there a command-line way to do these things? I don't use LXDE at all.
Posts: 19
Joined: Wed Sep 05, 2012 12:43 pm
by texy » Tue Dec 11, 2012 9:48 pm
You don't need to install RPi.GPIO for raspbian - it comes pre installed with the image.
At least for the latest and perhaps the last few versions.
Texy
"2.8inch TFT LCD + Touch screen" add-on boards for sale here :
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=93&t=65566
50p goes to the Foundation ;-)
Moderator
Moderator
Posts: 2207
Joined: Sat Mar 03, 2012 10:59 am
Location: Berkshire, England