Keypress Input

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
25 messages Options
12
Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie

 Hello.

 Very new to Python and looking for some basic help.

 Would like a set-up where something happens when a key is pressed. Not
propose a question, have the user type something, then hit return, then
something happens, but just the R key is pressed, something happens, then
something else happens if the B key is pressed, then a third thing
happens if the G key is pressed.

 My research only served to confuse me. Firstly, I do not understand how
it is possible for this to be a difficult thing not built into the system
for any scripting language made within the last few decades. More to the
point I am unclear on specific suggestions. Most of them seem to be for
Windows only and I want this working on a Raspberry Pi. Saw getch but I
am still confused if it is platform specific or not, or requires a module
to be installed or not. Just get errors if I try to install getch using
PIP.

 Other suggestions seemed to be overkill and confused me to due to my
beginner level knowledge and the fact these suggestions have other, more
complicated elements to them.

 I just want a button press on a device connected to a Raspberry Pi to
trigger an action. If anyone can give me some guidance on this I would
appreciate it.

 Thank you.


Reply | Threaded
Open this post in threaded view
|

Keypress Input

Gary Herron-2
On 06/03/2015 11:22 AM, John McKenzie wrote:

>   Hello.
>
>   Very new to Python and looking for some basic help.
>
>   Would like a set-up where something happens when a key is pressed. Not
> propose a question, have the user type something, then hit return, then
> something happens, but just the R key is pressed, something happens, then
> something else happens if the B key is pressed, then a third thing
> happens if the G key is pressed.
>
>   My research only served to confuse me. Firstly, I do not understand how
> it is possible for this to be a difficult thing not built into the system
> for any scripting language made within the last few decades. More to the
> point I am unclear on specific suggestions. Most of them seem to be for
> Windows only and I want this working on a Raspberry Pi. Saw getch but I
> am still confused if it is platform specific or not, or requires a module
> to be installed or not. Just get errors if I try to install getch using
> PIP.

If you are using Python through a CLI (command line interface i.e., a
shell), then in fact your request doesn't really make sense.  CLIs by
their nature don't support that kind of interaction.

BUT don't despair.  Nearly every GIU framework on the planet has a
Python interface, and they all allow for a window to be opened with
event processing of your choice.

This are some good places to start:
     https://wiki.python.org/moin/GuiProgramming
     https://wiki.python.org/moin/GUI%20Programming%20in%20Python

Several of these (Tkinter and the curses module) are distributed with
Python, so you should already have them installed.

Gary Herron



>
>   Other suggestions seemed to be overkill and confused me to due to my
> beginner level knowledge and the fact these suggestions have other, more
> complicated elements to them.
>
>   I just want a button press on a device connected to a Raspberry Pi to
> trigger an action. If anyone can give me some guidance on this I would
> appreciate it.
>
>   Thank you.
>


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


Reply | Threaded
Open this post in threaded view
|

Keypress Input

Laura Creighton-2
In reply to this post by John McKenzie
Tkinter runs on raspberry pi.

Get it installed, and then run this program.

from Tkinter import *
root = Tk()
prompt = 'Press any key. Remember to keep your mouse in the cyan box. '
lab = Label(root, text=prompt, width=len(prompt), bg='cyan')
lab.pack()

def key(event):
    msg = 'event.char is %r and event.keysym is %r' % (event.char, event.keysym)
        lab.config(text=msg)

root.bind_all('<Key>', key)
root.mainloop()

Now you will have to bind the various keys to do what it is you want.
You need to read online dociumentation for tkinter to learn how to do
this, as well as how to use tkinter in general.

Laura

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Gary Herron-2
In reply to this post by John McKenzie
On 06/03/2015 11:22 AM, John McKenzie wrote:

>   Hello.
>
>   Very new to Python and looking for some basic help.
>
>   Would like a set-up where something happens when a key is pressed. Not
> propose a question, have the user type something, then hit return, then
> something happens, but just the R key is pressed, something happens, then
> something else happens if the B key is pressed, then a third thing
> happens if the G key is pressed.
>
>   My research only served to confuse me. Firstly, I do not understand how
> it is possible for this to be a difficult thing not built into the system
> for any scripting language made within the last few decades. More to the
> point I am unclear on specific suggestions. Most of them seem to be for
> Windows only and I want this working on a Raspberry Pi. Saw getch but I
> am still confused if it is platform specific or not, or requires a module
> to be installed or not. Just get errors if I try to install getch using
> PIP.

If you are using Python through a CLI (command line interface i.e., a
shell), then in fact your request doesn't really make sense.  CLIs by
their nature don't support that kind of interaction.

BUT don't despair.  Nearly every GIU framework on the planet has a
Python interface, and they all allow for a window to be opened with
event processing of your choice.

This are some good places to start:
     https://wiki.python.org/moin/GuiProgramming
     https://wiki.python.org/moin/GUI%20Programming%20in%20Python

Several of these (Tkinter and the curses module) are distributed with
Python, so you should already have them installed.

Gary Herron



>
>   Other suggestions seemed to be overkill and confused me to due to my
> beginner level knowledge and the fact these suggestions have other, more
> complicated elements to them.
>
>   I just want a button press on a device connected to a Raspberry Pi to
> trigger an action. If anyone can give me some guidance on this I would
> appreciate it.
>
>   Thank you.
>


--
Dr. Gary Herron
Department of Computer Science
DigiPen Institute of Technology
(425) 895-4418


Reply | Threaded
Open this post in threaded view
|

Keypress Input

Laura Creighton-2
In reply to this post by Laura Creighton-2
In a message of Wed, 03 Jun 2015 20:59:04 +0200, Laura Creighton writes:

>Tkinter runs on raspberry pi.
>
>Get it installed, and then run this program.
>
>from Tkinter import *
>root = Tk()
>prompt = 'Press any key. Remember to keep your mouse in the cyan box. '
>lab = Label(root, text=prompt, width=len(prompt), bg='cyan')
>lab.pack()
>
>def key(event):
>    msg = 'event.char is %r and event.keysym is %r' % (event.char, event.keysym)
>        lab.config(text=msg)
>
>root.bind_all('<Key>', key)
>root.mainloop()
>
>Now you will have to bind the various keys to do what it is you want.
>You need to read online dociumentation for tkinter to learn how to do
>this, as well as how to use tkinter in general.
>
>Laura


I was in a hurry last night.  What I mean is -- Python out of the box
is not in the business of detecting key input.  You normally use a
Gui kit for that.  There are lots of them, and they all do things
sort of the same but slightly differently.  So what you need is
a gui kit that runs on Raspberry Pi.  If you are already using a
gui, then it probably will do it for you; check its documentation.
However, if you aren't using one ...

I don't have a Raspberry Pi, but I have read that tkinter runs there.
We can check.  First make sure that tkinter is installed and run that
short program I posted (also included above). If it works -- every time
you press a key char, it is supposed to tell you what you typed -- then
you are in business.  I just bound pressing every key with telling you that
it got pressed.  You will need to bind particular keys to do particular
things, which you can read about in tkinter documentation about keybinding.

Tkinter is python wrapped around tk, so this page
http://www.tcl.tk/man/tcl8.6/TkCmd/keysyms.htm

lists all the keys you can bind.  Not every OS provides the ability to
bind every key.  You are advised to try the keys you want to bind with
Raspberry Pi -- not having one I cannot check this for you.

Laura

Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie
In reply to this post by John McKenzie

 Laura and Gary, thank you for your replies. I have three physical
buttons connected to a Kade device emulating a keyboard. These buttons
control an LED light strip. So there is no screen, so a GUI did not cross
my mind. I thought it made sense as it is easily done by other scripting
languages. Thank you both for pointing my in the right direction.

 It turns out Tkinter is installed on Raspian and my Pi has it. Typing
import tkinter into the Python interpreter gave me an error, then I
corrected my spelling. The T should be upper case. No errors with "import
Tkinter".

 Laura, thank you for typing up example code. I had to remove one indent
on line 9, but after that it worked on my desktop. The Pi gave an error
about Tkinter when I tried to run your code but I will work on that. In
the meantime I will work my basic code out on the desktop and then move
it over to the Pi, adapting it for and fixing Pi issues then.

 In my mind the Tkinter information I read on the web contradicts the
examples given with the text, so obviously I am not getting it at all.
Tkinter seems very confusing to me right now, but I think I just need to
review the conceptual stuff again and keep trying. Also, I have your
example, which I can experiment with.
 

 Thanks.












Reply | Threaded
Open this post in threaded view
|

Keypress Input

Laura Creighton-2
In a message of Sat, 06 Jun 2015 18:28:29 +0000, John McKenzie writes:

>
>
> Laura and Gary, thank you for your replies. I have three physical
>buttons connected to a Kade device emulating a keyboard. These buttons
>control an LED light strip. So there is no screen, so a GUI did not cross
>my mind. I thought it made sense as it is easily done by other scripting
>languages. Thank you both for pointing my in the right direction.
>
> It turns out Tkinter is installed on Raspian and my Pi has it. Typing
>import tkinter into the Python interpreter gave me an error, then I
>corrected my spelling. The T should be upper case. No errors with "import
>Tkinter".
>
> Laura, thank you for typing up example code. I had to remove one indent
>on line 9, but after that it worked on my desktop. The Pi gave an error
>about Tkinter when I tried to run your code but I will work on that. In
>the meantime I will work my basic code out on the desktop and then move
>it over to the Pi, adapting it for and fixing Pi issues then.
>
> In my mind the Tkinter information I read on the web contradicts the
>examples given with the text, so obviously I am not getting it at all.
>Tkinter seems very confusing to me right now, but I think I just need to
>review the conceptual stuff again and keep trying. Also, I have your
>example, which I can experiment with.
>
>
> Thanks.

You are most welcome.  Sorry if I mangled the indent when pasting it
into my mail.

http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html
is useful.
Especially http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/key-names.html

So is http://effbot.org/tkinterbook/

Write back if you run into trouble.  The simple code I sent is just about
binding every key press to something that announces what you pressed.
You will have to bind particular keys, or sequence of keys to what
you want to do.  Write a small example to make sure that tkinter can
talk to your Kade device ok, because if it cannot we will have to
look harder at the problem.

Laura

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Chris Angelico
In reply to this post by John McKenzie
On Sun, Jun 7, 2015 at 4:28 AM, John McKenzie <davros at bellaliant.net> wrote:
>  It turns out Tkinter is installed on Raspian and my Pi has it. Typing
> import tkinter into the Python interpreter gave me an error, then I
> corrected my spelling. The T should be upper case. No errors with "import
> Tkinter".

Ah, that means your Python interpreter is the older (version 2) type,
rather than the newer (version 3). As of Python 3.0, the module is
named "tkinter". Use whichever one you have; there are a few other
changes inside the module, but the functionality's mostly the same.

ChrisA

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Michael Torrie
In reply to this post by John McKenzie
On 06/06/2015 12:28 PM, John McKenzie wrote:
>
>  Laura and Gary, thank you for your replies. I have three physical
> buttons connected to a Kade device emulating a keyboard. These buttons
> control an LED light strip. So there is no screen, so a GUI did not cross
> my mind. I thought it made sense as it is easily done by other scripting
> languages. Thank you both for pointing my in the right direction.

I assume this is on a Linux box of some kind, perhaps an embedded computer?

Actually you can indeed do what you want from a command-line program.
The curses module supports a function called "getch" which grabs keys
interactively  from whatever tty or ptty you are running the program on.
 You'll have to consult the docs on curses and how to use it in this
fashion.

The problem is you can't just ssh into your device and run the program
as it will fetch input from the terminal (and your remote keyboard)
which isn't what you want.  But if you can get it to run on the linux
console, it would work.  I have not idea how to do this in a
non-interactive startup fashion.

If your buttons are USB you might be able to read their status via
libusb but that gets complicated as Linux tries to grab it as a HID
keyboard.




Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie
In reply to this post by John McKenzie

from Tkinter import *
from blinkstick import blinkstick

led = blinkstick.find_first()

timered = 0
timeyellow = 0
timeblue = 0

colour = None

root = Tk()
root.title('eFlag 1')



def red1(event):
    colour = 1

def yellow1(event):
    colour = 2

def blue1(event):
    colour = 3

root.bind_all('r', red1)
root.bind_all('b', blue1)
root.bind_all('y', yellow1)
root.mainloop()

while colour == None:
    led.pulse(red=0, green=255, blue=0, repeats=1, duration=5000,
steps=50)

while colour == 1:
    led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000,
steps=50)
    timered += 1

while colour == 2:
    led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000,
steps=50)
    timeyellow += 1

while colour == 3:
    led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000,
steps=50)
    timeblue += 1


def exit_handler():
    print '\033[0;41;37mRed Team:\033[0m ', timered
    print '\033[0;43;30mYellow Time:\033[0m ', timeyellow
    print '\033[0;44;37mBlue Time:\033[0m ', timeblue
    flog = open('flag1log.text', 'a')
    flog.write(timestamp + '\n' + 'Red Team: ' + str(timered) + '\n' +
'Yellow Team: ' + str(timeyellow) + '\n' + 'Blue Team: ' + str(timeblue)
+ '\n')
    flog.close()
    atexit.register(exit_handler)



Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie
In reply to this post by John McKenzie

 Thank to the others who joined in and posted replies.

 Michael, your assumption is correct. To quote my original post, "and I
want this working on a Raspberry Pi." Doing a superficial look at curses
and getch it looks excessively complicated. I was under the impression it
was not multi-platform and Linux was excluded. Searching for getch and
raspberry pi on the web I see it is not and is available for Raspian.

 Worried about implementing it but I will consider it again. May spend
time reading about during my treatment tomorrow as the hospital has wifi
and Internet access and I am allowed to have my laptop there.

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Oscar Benjamin-2
On 15 June 2015 at 06:23, John McKenzie <davros at bellaliant.net> wrote:
>
>  Thank to the others who joined in and posted replies.
>
>  Michael, your assumption is correct. To quote my original post, "and I
> want this working on a Raspberry Pi." Doing a superficial look at curses
> and getch it looks excessively complicated. I was under the impression it
> was not multi-platform and Linux was excluded. Searching for getch and
> raspberry pi on the web I see it is not and is available for Raspian.

I'm not sure what you mean but you can write a getch function for
Unixy systems using the tty module (I can't remember where I
originally borrowed this code from):

import sys, tty, termios

def getch():
    fd = sys.stdin.fileno()
    oldsettings = termios.tcgetattr(fd)
    try:
        tty.setraw(sys.stdin.fileno())
        c = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
    return c

while True:
    key = getch()
    print("key: '%c'  code: '%d'" % (key, ord(key)))
    if key == 'q':
        break

This puts the terminal in "raw mode" and waits for a key-press. Once a
key is pressed the terminal is restored to it's previous mode (most
likely not raw mode) and the character is returned. This is important
because once your program finishes you don't want the terminal to be
in raw mode. If the terminal goes weird you can usually fix it by
typing "reset" and pressing enter.

Note that going into raw mode has other implications such as not being
able to exit your program with ctrl-c or suspend with ctrl-z etc. You
can explicitly process those kinds of contrl keys with something like:

while True:
    key = getch()
    if 1 <= ord(key) <= 26:
        ctrl_key = chr(ord(key) + 64)
        print("ctrl-%c" % ctrl_key)
        if ctrl_key == 'C':
            break
    else:
        print("key: '%c'" % key)


--
Oscar

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Grant Edwards-7
In reply to this post by John McKenzie
On 2015-06-15, Oscar Benjamin <oscar.j.benjamin at gmail.com> wrote:

> Note that going into raw mode has other implications such as not
> being able to exit your program with ctrl-c or suspend with ctrl-z
> etc. You can explicitly process those kinds of contrl keys with
> something like:
>
> while True:
>     key = getch()
>     if 1 <= ord(key) <= 26:
>         ctrl_key = chr(ord(key) + 64)
>         print("ctrl-%c" % ctrl_key)
>         if ctrl_key == 'C':
>             break
>     else:
>         print("key: '%c'" % key)

It's probably better (at least on Linux) to just enable handling of
those characters in by setting the ISIG lflag:

    def getch():
        fd = sys.stdin.fileno()
        oldsettings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
   
            # enable handling of ctrl-C, ctrl-Z, etc.            
            attr = termios.tcgetattr(fd)
            attr[3] |= termios.ISIG
            termios.tcsetattr(fd,termios.TCSANOW,attr)
   
            c = sys.stdin.read(1)
   
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
        return c

It would be a bit cleaner if the termios module supported the the
cfmakeraw(3) function, then you could do it this way and save a couple
of system calls:

    def getch():
        fd = sys.stdin.fileno()
        oldsettings = termios.tcgetattr(fd)
        try:
            newsettings = termios.makeraw(oldsettings)
            newsettings[3] |= termios.ISIG
            termios.tcsetattr(fd,termios.TCSANOW,newsettings)
            c = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, oldsettings)
        return c

[I'm a bit surprised that after all these years using literal integers
to index into the attribute list is the "right" way.]
       
--
Grant Edwards               grant.b.edwards        Yow! Well, O.K.
                                  at               I'll compromise with my
                              gmail.com            principles because of
                                                   EXISTENTIAL DESPAIR!

Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie
In reply to this post by John McKenzie

 It appears that one of my posts was cut off. It contains my script but
none of the lengthy text in front of it.

 To summarize, my set-up consists of three "massive arcade buttons" from
Adafruit. one red, one blue, one yellow. They are connected to a Kade
Device that is connected to a Raspberry Pi via USB cable and emulates a
USB keyboard. The goal is to get the LED light strip attached to the Pi
via a Blinkstick Pro and LED adapter to glow the colour of the button
pushed. Also, I want the Pi to record how long it spent as each colour.

 For development purposes I am using an actual keyboard.

 The script brings up a blank tkinker window (expected) and the window
seems to have focus when it is created. Pressing the keys does nothing.

 Would appreciate any insight into why it does not respond. Just look a
few posts above (Date: Mon, 15 Jun 2015 05:15:31 GMT) and you will see my
script.

 Tried a bunch of different approaches and in some of them, an error
message appeared when I pressed a key. It may not have worked, but it was
registering the key press.

 Thanks.


Reply | Threaded
Open this post in threaded view
|

Keypress Input

Michael Torrie
In reply to this post by John McKenzie
On 06/14/2015 11:23 PM, John McKenzie wrote:

>  Thank to the others who joined in and posted replies.
>
>  Michael, your assumption is correct. To quote my original post, "and I
> want this working on a Raspberry Pi." Doing a superficial look at curses
> and getch it looks excessively complicated. I was under the impression it
> was not multi-platform and Linux was excluded. Searching for getch and
> raspberry pi on the web I see it is not and is available for Raspian.
>
>  Worried about implementing it but I will consider it again. May spend
> time reading about during my treatment tomorrow as the hospital has wifi
> and Internet access and I am allowed to have my laptop there.

I'm not sure exactly what you mean by not available on Linux.  Curses
provides the same API on all platforms it runs on and I know it can read
keystrokes.  Curses getch is certainly available on Linux.  In fact,
here's an example:

http://stackoverflow.com/questions/10693256/how-to-accept-keypress-in-command-line-python

Again, however, you probably can't just fire up your program from a
startup script and have it run automatically, since stdin for a script
is not going to be the tty.  One idea would be to run your program from
init as a getty on tty1 (the default tty).  That would run as soon as it
boots up.

Though question for you. Why are you hooking the arcade buttons up to a
kade USB device?  Would not it be far simpler to hook the buttons
directly to a GPIO pin and read them from python?  You're already using
GPIO pins to run the LEDs.  Seems like the usb keyboard hack is
unnecessary and it's making your task more difficult.


Reply | Threaded
Open this post in threaded view
|

Keypress Input

John McKenzie
In reply to this post by John McKenzie

 That was the impression I got reading some comments people made online
and doing research, so I focused on tkinter. As I mentioned in the 4th
sentence of the post you quoted I discovered that was not the case, but
by then I had already done some work on the tkinter script so I kept with
it.

 Before I actually tried any of this and was just thinking of it
conceptually I bought the Kade device. It was my hope that it would save
on soldering, something I hate so very, very much, and I had not started
learning Python at that point. It never occurred to me something so
simple as keystrokes would not be present in Python, a language rated as
being terrific by everyone I know who knows it.

 Out of great ignorance I thought I could hook up the Kade device and do
something like if keypress == r then do this. Also out of ignorance I
thought that using the GPIO would require days of soldering and
incredibly complicated coding to talk to the pins.

 Only since I got much more deep into actually doing this did I start to
find out otherwise. Spent the last few days looking at breakout boards to
see if they would make the wiring easier to test out. When I saw one that
had built in electrical protection (RaspIO Pro) I thought about getting
it and going the route you suggest. However, I cannot find any option
that does not require a breadboard. The lack of compactness and all the
exposed wires does bother me a bit. More than it should, but I need a
compact setup I can place outdoors. Breadboards and loose wires worry me
in this case.

 Still, I must admit I spent the last 3 or 4 days thinking about exactly
what you said and I may do it that way after all just to get it to work
software wise.

 And BTW, I am not using any GPIO for the lights, the LED light strip is
hooked up to a Blinkstick Pro through a USB port.


Reply | Threaded
Open this post in threaded view
|

Keypress Input

Grant Edwards-7
On 2015-06-16, John McKenzie <davros at bellaliant.net> wrote:

> It never occurred to me something so simple as keystrokes would not
> be present in Python, a language rated as being terrific by everyone
> I know who knows it.

Ah, but in reality "keystrokes" is not simple at all.  Keyboards and
input handling is a very messy, complicated area.

--
Grant Edwards               grant.b.edwards        Yow! FOOLED you!  Absorb
                                  at               EGO SHATTERING impulse
                              gmail.com            rays, polyester poltroon!!

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Paul Rubin-7
In reply to this post by John McKenzie
John McKenzie <davros at bellaliant.net> writes:
>  Would like a set-up where something happens when a key is pressed. Not
> propose a question, have the user type something, then hit return, then
> something happens, but just the R key is pressed, something happens,

The quick answer is that you want raw mode tty input.  Type "stty raw"
to the shell, and sys.stdin.read(1) will give you the bytes of the typed
characters immediately.  Use "stty -raw" to put it back in cooked mode,
or maybe better, "stty sane" to restore normal settings in general.

Yes there are messy details like function keys actually sending several
characters.  In practice you'll also want to control the tty modes from
your program instead of the shell, but that should get you started.  You
may also want to turn off echo, i.e. "stty raw -echo".

Reply | Threaded
Open this post in threaded view
|

Keypress Input

Michael Torrie
In reply to this post by Grant Edwards-7
On 06/16/2015 02:49 PM, Grant Edwards wrote:
> On 2015-06-16, John McKenzie <davros at bellaliant.net> wrote:
>
>> It never occurred to me something so simple as keystrokes would not
>> be present in Python, a language rated as being terrific by everyone
>> I know who knows it.
>
> Ah, but in reality "keystrokes" is not simple at all.  Keyboards and
> input handling is a very messy, complicated area.

If you do choose to go with the GPIO route, unless your code for
accessing the GPIO lines does debouncing, you will have to debounce the
key.  There are lots of examples out there (most in C on the arduino,
but still applicable). Most of them check for a button press, then do a
timer count-down to let things settle out before recording a button
press.  So it's still complicated even if you talk directly to the
buttons!  No way around some complexity though.



Reply | Threaded
Open this post in threaded view
|

Keypress Input

Oscar Benjamin-2
On Wed, 17 Jun 2015 at 02:23 Michael Torrie <torriem at gmail.com> wrote:

> On 06/16/2015 02:49 PM, Grant Edwards wrote:
> > On 2015-06-16, John McKenzie <davros at bellaliant.net> wrote:
> >
> >> It never occurred to me something so simple as keystrokes would not
> >> be present in Python, a language rated as being terrific by everyone
> >> I know who knows it.
> >
> > Ah, but in reality "keystrokes" is not simple at all.  Keyboards and
> > input handling is a very messy, complicated area.
>
> If you do choose to go with the GPIO route, unless your code for
> accessing the GPIO lines does debouncing, you will have to debounce the
> key.  There are lots of examples out there (most in C on the arduino,
> but still applicable). Most of them check for a button press, then do a
> timer count-down to let things settle out before recording a button
> press.  So it's still complicated even if you talk directly to the
> buttons!  No way around some complexity though.
>

I use the following. I found in testing that when you push the button it
prints 'Button pressed' 10 times a second (in actual use it calls poweroff
so I guess bounce isn't an issue there). Is there some reason it needs to
be cleverer in this case?

 #!/usr/bin/env python

import RPi.GPIO as GPIO
import subprocess
import time

PIN_NUM = 21

GPIO.setmode(GPIO.BCM)

GPIO.setup(PIN_NUM, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    time.sleep(0.1)
    if not GPIO.input(PIN_NUM):
        print('Button pressed')

--
Oscar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150618/70f36c0e/attachment.html>

12