Re: Keypress Input
Thanks again to everyone who tried to help. Michael, I especially appreciate your encouragement and chiming in to point out that telling newbies to learn everything there is before posting question was not helpful in getting more people using Python. Have the Pi wired up directly to the buttons, read up on the GPIO library and I just posted for help regarding the error messages I am getting from my Python buttons script. Thanks. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Wednesday, July 15, 2015 at 11:30:40 PM UTC-5, Michael Torrie wrote: On 07/15/2015 07:03 PM, Rick Johnson wrote: too much to quote I think you've missed the whole point of the OP's project. Obviously my reply was not only too much to quote, but apparently, and sadly, too much to read! I don't know about anyone else here, but i would be cautious about replying to any post before i took the time to read the entire content. I mean, i'd wouldn't want to embarrass myself. But, I suppose this more evidence of the damage social media is doing to our collective attention spans. There are some studies that report an average attention span of only 8 seconds -- which is less than the attention span of a goldfish. AN EFFING GOLDFISH! CLOWN-FISH: Hello Dori! DORI: Who's Dori? I had read an article the other day about how smart phones are making people dumb. However, by focusing on the phone, which is nothing more than a tool, the author ignored the real cause of this ubiquitous intelligence drain that is rotting our culture from the inside out. It's not the *PHONES* that making people dumb, it's the *CONTENT* people *CHOOSE* that is turning us into a society of drooling, superficial, and mindless gossip zombies. TWITTER BEING THE MOST DESTRUCTIVE AND EVIL OF THEM ALL! With Twitter, we have a communication medium that encourages teeny tiny thoughtless reactions to whatever emotional drivel happens to be churning around in the daily cesspools of what, for whatever sociological reason, we still refer to as News. Is the size of some morally corrupt celeb's butt really news? Or the love interest of various talent-less glitterati anything we should concern ourselves with? Heck, just a few days ago, another lip singer made front page world news simply by licking a donut! BY LICKING AN EFFING DONUT! Are our lives that pathetic? In the past there were at least a few educational programs on the tele, now even so called educational channels have devolved into train-wrecks of thought UNprovoking emotion, with episode after episode of totally scripted reality TV far more concerned with shock value than entertainment -- much less education. I once believed that Facebook was the bottom of the barrel for social media -- BOY WAS I WRONG! It's seems there is no level that we, as a society will stoop, in the effort to destroy our capacity of intellectual evolution. So fire up those twitter engines and speed headlong into that wall of ignorant bliss! And don't bother trotting out the old cliche of grab a fiddle folks, because the unwashed masses are not refined enough to appreciate the higher intellectual emotions and the thoughtful introspection that such an instrument can produce, instead, grab a shiny rattle and shake it in front of their pasty little ignorant faces. For they can only understand simple concepts and the selfish emotions. :-O = = = ___^ __ ^_ ___'Modern-Society'___ -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 7/15/2015 9:03 PM, Rick Johnson wrote: You may have solved your input capturing problem, and i don't think a GUI is the preferred solution for a graphically deficient device anyhow, but you may well need a GUI in the future, and this would be a fine example from which to learn. This really is a nice example. Your rationale for defining an app class is the best I remember seeing. To run in 3.x, change the first two lines to import tkinter as tk from tkinter.messagebox import showinfo, showerror import Tkinter as tk from tkMessageBox import showinfo, showerror MSG1 = \ To begin retinal stimulation, press r or g or b on your keyboard Hold key down for extended stimulation! class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.bind(KeyPress, self.evtKeyDown) self.bind(KeyRelease, self.evtKeyUp) self.protocol(WM_DELETE_WINDOW, self.evtDeleteWindow) w = tk.Label(self, text=MSG1) w.pack() self.config(bg='white') self.geometry('500x500') self.focus_set() def evtDeleteWindow(self): showinfo(The window is Dying, Goodbye cruel world!, parent=self) self.destroy() def evtKeyDown(self, event): key = event.keysym.lower() alert = False if key == 'r': self.config(bg='red') elif key == 'g': self.config(bg='green') elif key == 'b': self.config(bg='blue') else: Can condense block above to this easily extended code: (Replacing if if/elif/elif/... chains, when possible, is part of mastering Python.) try: self['bg'] = {'r':'red', 'g':'green', 'b':'blue'}[key] except KeyError: msg = 'I *TOLD* you to press r or g or b, not {0!r}!'.format(key) showerror('', msg, parent=self) def evtKeyUp(self, event): self.config(bg='white') if __name__ == '__main__': app = App() app.title('Retina Stimultor') app.mainloop() print This code only executes *AFTER* the mainloop call returns! Adding parens to print, when there is a single object being printed, has no effect in 2.x and makes the statement work in 3.x. The following works the same in both. print(Mainloop has returned) -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 7/16/2015 12:30 AM, Michael Torrie wrote: On 07/15/2015 07:03 PM, Rick Johnson wrote: too much to quote I think you've missed the whole point of the OP's project. He doesn't want to make a GUI. He simply wants to have his program do something like blink an LED when someone presses a big red button. He just wanted a quick way to test things out since his big red button can emulate a USB keyboard. So all he needed was a simple console app that can fetch keystrokes. In the end, though GPIO is very simple both electrically and in terms of Python, so that is the ultimate route he will go. If you read his last post you'll find he says this. Rick pretty much acknowledged what you said in this paragraph. You may have solved your input capturing problem, and i don't think a GUI is the preferred solution for a graphically deficient device anyhow, but you may well need a GUI in the future, and this would be a fine example from which to learn. It is a fine example. -- Terry Jan Reedy -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 07/16/2015 11:22 AM, Rick Johnson wrote: On Wednesday, July 15, 2015 at 11:30:40 PM UTC-5, Michael Torrie wrote: On 07/15/2015 07:03 PM, Rick Johnson wrote: too much to quote I think you've missed the whole point of the OP's project. Obviously my reply was not only too much to quote, but apparently, and sadly, too much to read! I don't know about anyone else here, but i would be cautious about replying to any post before i took the time to read the entire content. I mean, i'd wouldn't want to embarrass myself. I read a good deal of what you wrote, which is more than most do with such long, rambling posts. Good to know there were some good nuggets in there. This is as much as I read of your current post though. As soon as you started going off about gold fish, I'm out. It's true that attention spans are shorter these days. But it's also true there are ways of being concise. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Thursday, July 16, 2015 at 1:09:32 AM UTC-5, Terry Reedy wrote: This really is a nice example. Your rationale for defining an app class is the best I remember seeing. Well thank you Terry. Your many years of selfless altruistic offerings to this fine group are both inspiring and educational. And i can happily admit that you are no doubt much more of an asset to this group than i. def evtKeyDown(self, event): key = event.keysym.lower() alert = False Oops. I just noticed that i forgot to remove the alert = False line. It was an artifact from one of my earlier versions. It's obviously superfluous to we pyhtonistas, but it could become a source of confusion to the shadow lurkers. if key == 'r': self.config(bg='red') elif key == 'g': self.config(bg='green') elif key == 'b': self.config(bg='blue') else: Can condense block above to this easily extended code: (Replacing if if/elif/elif/... chains, when possible, is part of mastering Python.) try: self['bg'] = {'r':'red', 'g':'green', 'b':'blue'}[key] except KeyError: Yes you make a good point. And i'm glad you injected this alternative, as it offers yet another fine teaching moment for the OP and this group. [Warning: Caveat ahead!] However, i must take exception with your claim that replacing classical conditional chains with Python's unofficial pseudo case/switch is key to: mastering Python. I feel there are instances when a classical condition chain are more appropriate, and then other times, when the pseudo switch/case is superior. For me, I believe the key to mastering Python is not to choose one method over the other (as some sort of religious rule carved into stone), rather, to know when one method is more appropriate than the other. That's my person opinion anyway. Adding parens to print, when there is a single object being printed, has no effect in 2.x and makes the statement work in 3.x. The following works the same in both. print(Mainloop has returned) Yes, another fine teaching moment! But just to be clear of my intentions: I only write code in full 2.x compliance, or full 3.x compliance. And i do this because i don't want to inject any implicit version confusion into my source code. In fact, the only time i will mix the incompatible syntaxes is when i can wrap them explicitly in an exception handler. But since there is no exception to catch in this case, even that option would be unavailable to me. But again. The act of you pointing out this easily overlooked difference between print 2.x and print(3.x) is yet another opportunity at exploiting fundamental teaching moments as they pop up. Hey, who would ever have thunk that teaching could be as exciting and egotistically fulfilling as a game of wack-a-mole! O:-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 07/16/2015 01:10 AM, Terry Reedy wrote: On 7/16/2015 12:30 AM, Michael Torrie wrote: On 07/15/2015 07:03 PM, Rick Johnson wrote: too much to quote I think you've missed the whole point of the OP's project. He doesn't want to make a GUI. He simply wants to have his program do something like blink an LED when someone presses a big red button. He just wanted a quick way to test things out since his big red button can emulate a USB keyboard. So all he needed was a simple console app that can fetch keystrokes. In the end, though GPIO is very simple both electrically and in terms of Python, so that is the ultimate route he will go. If you read his last post you'll find he says this. Rick pretty much acknowledged what you said in this paragraph. You may have solved your input capturing problem, and i don't think a GUI is the preferred solution for a graphically deficient device anyhow, but you may well need a GUI in the future, and this would be a fine example from which to learn. It is a fine example. Good to know. With some posters it's hard to glean the good bits from the ramblings. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 07/15/2015 07:03 PM, Rick Johnson wrote: too much to quote I think you've missed the whole point of the OP's project. He doesn't want to make a GUI. He simply wants to have his program do something like blink an LED when someone presses a big red button. He just wanted a quick way to test things out since his big red button can emulate a USB keyboard. So all he needed was a simple console app that can fetch keystrokes. In the end, though GPIO is very simple both electrically and in terms of Python, so that is the ultimate route he will go. If you read his last post you'll find he says this. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Friday, June 19, 2015 at 12:20:14 AM UTC-5, Christian Gollwitzer wrote: The nonsense starts here: [...snip code...] it seems you don't understand event based programming. Duh. No need to abuse the lad. It waits for the user input and does the dispatching, i.e. when a key is pressed, then according to your bindings, the functions red1, yellow1, blue1 are called, which set a variable but do not do nything else. Now your job is to also do the functionality there, i.e. you have to reformulate your task (waiting for red, then blue...) as a state machine. Alternatively you can circumvent to redo the logic in a state machine by using a coroutine. State machines? Co-routines? Dispatching? Bindings? Are you purposefully attempting to scare the OP away from GUI programming forever, or merely practicing for your next tenure exam? Heck you're scaring me away and i have years of GUI programming experience under my belt! You should read a text about GUI programming, or more specifically event based programming, to understand your mistake. Christian, peppering a student with a barrage of technical verbiage and then smacking them in the face with that tried and true knee-jerk-reactionary condescension of RTFM, is hardly the reaction that the OP deserves when he *DID* attempt to formulate working code from the sample that Laura provided. And even *IF* his attempt was an abysmal failure, we should strive to provide more information than simply: go study the history of GUI design and get back to us in a year or two. Of course, we don't want to write the code for him, but his attempt does warrant a few extra clues. @ John You may have solved your input capturing problem, and i don't think a GUI is the preferred solution for a graphically deficient device anyhow, but you may well need a GUI in the future, and this would be a fine example from which to learn. So you want to know about Event Driven Programming do ya? Well then, skip the boring lectures and the hours of eyeball parsing techno-babble-prose and listen up! You see, we, as humans, emulate a version of Event Driven Programming (or EDP) in our everyday lives as something i shall henceforth refer to as Event Driven Reactions (or EDR). And these EDRs are codified as culturally acceptable reactions to external stimuli during the course of interpersonal relations. For instance: If we meet someone for the first time and they extend their hand, then we should extend ours and engage in the hand shake or the fist bump (depending upon cultural norms). And if you're in one of those really freaky cultures you may have to kiss someone... YUCK! Or if someone insults us with a sexual advance, and we're of the female persuasion, and they're of the male persuasion: then we might react (as Manolo found out in that famous scene from Scarface) by slapping them *SMACK* The point is: The action of us reacting to external stimuli (based on predefined rules) is the exact nature of Event Driven GUIs. When we write GUI code under this paradigm, we need to follow a few design rules. (1) DEFINE/CREATE THE REQUIRED GUI COMPONENTS Here we define the window(s) and the required widgets that shall provide an interface between our users and our code. (2) DEFINE RULES FOR REACTIONS TO EXTERNAL STIMULI Here we bind events (keyboard, mouse, joystick, etc) to callbacks (aka: functions in Python) that our master control program (aka: Tkinter in this instance) will execute when the defined event is recieved. Now you may be asking yourself: But i did that already! Why does my code fail to produce required results? Hmm, it seems (as Christian pointed out) you made the fatal flaw of starting the event loop before your logic could execute. However. Even if your logic was allowed to execute, it would fail to produce the desired results. THE ROAD TO ENLIGHTENMENT: I have re-packaged Laura's basic example into a class format that utilizes a paradigm known as Object Oriented Programming (or OOP). Of course, you're not required to write code utilizing this format, but i feel it may be easier for a GUI novice to understand the entire structure of this program when the relevant bits are in near proximity to one another, rather than spread around a module like a spilled carton of toothpicks on the floor -- because, not all of us are blessed with the narrowly focused genius of the idiot savant! Now, conceptualize the entire class as representing the window whilst it's alive, and the methods defined in the class as personal reactions to events that the window encounters during it's lifetime. You should think of the window as a unique object in two dimensional space, just as you
Re: Keypress Input
Hello, all. Thanks to everyone who responded to my post. I decided to make sure I had something that worked with what I have now and used Curses to finish it. However, it turns out that the extra work and problems with using GPIO pins and wiring up controllers that way is a small amount of headaches and work compared to what I thought it would be and the software part is actually easier than doing it this way. So in the end I will hooking the Raspberry Pi up directly to the buttons and use the Raspberry Pi's GPIO library to do it all. For posterity and in case other beginners want to look at it, here is what I have with curses that works now. Tried to add a function to cause it to only work for a certain amount of time and that did not work. Will worry about that when I do the new programme based off of directly connected buttons and have those working. Thanks everyone. Here is the keyboard controls the colours script. (Raspberry Pi B+, Blinkstick Pro and LED Adapter, analouge RGB LED light strip.) import curses import atexit import time from datetime import datetime from blinkstick import blinkstick starttime = time.time() screen = curses.initscr() curses.noecho() curses.curs_set(0) screen.keypad(1) screen.nodelay(1) led = blinkstick.find_first() timered = 0 timeyellow = 0 timeblue = 0 timestamp = str(datetime.now()) colour = 0 screen.addstr(Eflag 1) while True: event = screen.getch() if event == ord(q): 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() curses.endwin() break elif event == ord(r): colour = 1 screen.addstr(Red Activated) elif event == ord(y): colour = 2 screen.addstr(Yellow Activated) elif event == ord(b): colour = 3 screen.addstr(Blue Activated) if colour == 1: led.pulse(red=255, green=0, blue=0, repeats=1, duration=3000, steps=50) timered += 1 print timered if colour == 2: led.pulse(red=255, green=255, blue=0, repeats=1, duration=3000, steps=50) timeyellow += 1 if colour == 3: led.pulse(red=0, green=0, blue=255, repeats=1, duration=2000, steps=50) timeblue += 1 if time.time() == (time.time() + 30): 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() curses.endwin() break -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 07/15/2015 01:05 PM, John McKenzie wrote: Hello, all. Thanks to everyone who responded to my post. I decided to make sure I had something that worked with what I have now and used Curses to finish it. However, it turns out that the extra work and problems with using GPIO pins and wiring up controllers that way is a small amount of headaches and work compared to what I thought it would be and the software part is actually easier than doing it this way. So in the end I will hooking the Raspberry Pi up directly to the buttons and use the Raspberry Pi's GPIO library to do it all. For posterity and in case other beginners want to look at it, here is what I have with curses that works now. Tried to add a function to cause it to only work for a certain amount of time and that did not work. Will worry about that when I do the new programme based off of directly connected buttons and have those working. Thanks everyone. Thanks for the update! Also I am very glad to hear that using GPIO doesn't look very difficult. Good luck on things! -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
Guys, thanks for the various code examples for GPIO and the warning about debouncing issues. I am still considering going the route of more complex wiring and doing it a more traditional GPIO way. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 06/20/2015 09:02 AM, John McKenzie wrote: Guys, thanks for the various code examples for GPIO and the warning about debouncing issues. I am still considering going the route of more complex wiring and doing it a more traditional GPIO way. You can wire up the button without a little breadboard or circuit board using this general diagram: https://www.cl.cam.ac.uk/projects/raspberrypi/tutorials/robot/buttons_and_switches/ Just solder the resistors to the wires themselves, and keep them close to the pi to keep them clean. Then you you just have to route one wire per switch, with one common wire hitting the other side of each switch. Probably you will want to use the pull-up version where the switch pulls the signal down to ground. You may want to use a header to plug into the rpi. But besides that should just be a matter of routing wires. But on the original track, you might want to ask on the kade forums if there's any way to interact with kade and get events besides HID emulation. For example, maybe you could communicate with it over a virtual serial port. Or some other protocol so you don't have to worry about ttys and Linux kernel HID handling for your program, especially in a headless environment. Using HID emulation makes sense in a MAME arcade environment but not for a headless raspberry pi application. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
Christian, are you suggesting I learn to do everything perfectly before I ask how to do everything perfectly? Despite your tone and insults I honestly appreciate the response. I know what to focus on and less than 5 minutes from now I will be looking for e- books on the specific subjects you point me to and will have a better idea of where the issues are. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
Am 15.06.15 um 07:15 schrieb 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) The nonsense starts here: === 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 it seems you don't understand event based programming. root.mainloop() never exits. It waits for the user input and does the dispatching, i.e. when a key is pressed, then according to your bindings, the functions red1, yellow1, blue1 are called, which set a variable but do not do nything else. To see that, just insert a print statement into these functions: def red1(event): colour = 1 print(Red ws called) Now your job is to also do the functionality there, i.e. you have to reformulate your task (waiting for red, then blue...) as a state machine. Alternatively you can circumvent to redo the logic in a state machine by using a coroutine. You should read a text about GUI programming, or more specifically event based programming, to understand your mistake. Christian 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) -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 06/18/2015 01:35 PM, Oscar Benjamin wrote: 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? Yes, that would be expected, given your code has a while loop that never exits. Just curious what you expect the code to do that it's not doing. You are probably right that debouncing isn't important in your application. So just add your poweroff command after the print() statement, and break out of the loop: ... while True: time.sleep(0.1) if not GPIO.input(PIN_NUM): print('Button pressed') # run shutdown command here os.system('/usr/sbin/shutdown') break -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Wed, 17 Jun 2015 at 02:23 Michael Torrie torr...@gmail.com wrote: On 06/16/2015 02:49 PM, Grant Edwards wrote: On 2015-06-16, John McKenzie dav...@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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
John McKenzie dav...@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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 2015-06-16, John McKenzie dav...@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.edwardsYow! FOOLED you! Absorb at EGO SHATTERING impulse gmail.comrays, polyester poltroon!! -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 06/16/2015 02:49 PM, Grant Edwards wrote: On 2015-06-16, John McKenzie dav...@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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 15 June 2015 at 06:23, John McKenzie dav...@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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 2015-06-15, Oscar Benjamin oscar.j.benja...@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.edwardsYow! Well, O.K. at I'll compromise with my gmail.comprinciples because of EXISTENTIAL DESPAIR! -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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) -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
In a message of Sat, 06 Jun 2015 18:28:29 +, 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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On Sun, Jun 7, 2015 at 4:28 AM, John McKenzie dav...@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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
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 -- https://mail.python.org/mailman/listinfo/python-list
Keypress Input
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. -- https://mail.python.org/mailman/listinfo/python-list