Take the 2-minute tour ×
Raspberry Pi Stack Exchange is a question and answer site for users and developers of hardware and software for Raspberry Pi. It's 100% free, no registration required.

I have a python script that uses a library to talk to GPIO in a constant loop. How can I detect keyboard input inside the loop and choose to exit the loop?

while True:
        for item in pics[1:]:
                matrix.SetImage(item.im.id, 0, 0)
                time.sleep(.1)

matrix.Clear()
share|improve this question

2 Answers 2

up vote 2 down vote accepted

I suggest you use the curses module. It will let you check for keyboard input.

Here is an example. It uses my pigpio library to read the gpios but the gpio library you use will be irrelevant to curses.

#!/usr/bin/env python

# gpio_status.py
# 2015-03-04
# Public Domain

import time
import curses
import atexit

import pigpio 

GPIOS=32

MODES=["INPUT", "OUTPUT", "ALT5", "ALT4", "ALT0", "ALT1", "ALT2", "ALT3"]

def cleanup():
   curses.nocbreak()
   curses.echo()
   curses.endwin()
   pi.stop()

pi = pigpio.pi()

stdscr = curses.initscr()
curses.noecho()
curses.cbreak()

atexit.register(cleanup)

cb = []

for g in range(GPIOS):
   cb.append(pi.callback(g, pigpio.EITHER_EDGE))

stdscr.nodelay(1)

stdscr.addstr(0, 23, "Status of gpios 0-31", curses.A_REVERSE)

while True:

   for g in range(GPIOS):
      tally = cb[g].tally()
      mode = pi.get_mode(g)

      col = (g / 11) * 25
      row = (g % 11) + 2

      stdscr.addstr(row, col, "{:2}".format(g), curses.A_BOLD)

      stdscr.addstr(
         "={} {:>6}: {:<10}".format(pi.read(g), MODES[mode], tally))

   stdscr.refresh()

   time.sleep(0.1)

   c = stdscr.getch()

   if c != curses.ERR:
      break
share|improve this answer
    
I am not clear on how I would implement this. I updated my post to add more detail. I want the loop to end and the call to matrix.Clear(), and the script to end on input. Would I do this in def cleanup()? –  Roger Mar 4 at 14:41
    
The code is just an example of using the Python curses module. curses is used to draw to a terminal window and handle keyboard entry. You are only interested in keyboard entry so the getch method is of particular interest. If you search for Python curses and keyboard you should be able to find other examples/tutorials on-line. –  joan Mar 4 at 15:04

Can be done with ttyas well, like this:

import tty, sys

tty.setraw(sys.stdin.fileno())
while 1:
    ch = sys.stdin.read(1)
    if ch == 'a':
        print "Wohoo"

This will garble your tty, though, so if you need it for anything later, you need to restore it.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.