Python Key Press and Key Release Listener

I control a remote toy car using python code. Currently code below

def getkey(): fd = sys.stdin.fileno() old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~TERMIOS.ICANON & ~TERMIOS.ECHO new[6][TERMIOS.VMIN] = 1 new[6][TERMIOS.VTIME] = 0 termios.tcsetattr(fd, TERMIOS.TCSANOW, new) c = None try: c = os.read(fd, 1) finally: termios.tcsetattr(fd, TERMIOS.TCSAFLUSH, old) return c def car(): while True: key = getkey() if key == 's': #Down arrow print "Down" Backward() elif key == 'w': #Up arrow print "Up" forward() elif key == 'a': print "left" Left() elif key == 'd': print "Right" Right() elif key == 'q': #Quit print "That It" break def forward(): GPIO.output(11,True) #Move forward 

When I press the 'w' forward () method and the machine moves forward, but does not stop until i exit the program or call GPIO.output (11, Flase) from another method.

Is there any key listener that detects the key unlock of a particular key.

For example, if 'w' pressed, called this method, and if it was released, call another method

Ship code

 if w_isPressed() forward() else if w_isReleased() stop() 
+6
source share
1 answer

I saw Pygame a game development library that was previously used in similar scenarios, processing real-time systems and machines in production, and not just toy examples. I think this is also a suitable candidate. pygame.key open the pygame.key module, which can be done using keyboard input.

In short, if you are not familiar with the development of the game, you basically constantly conduct polls for events such as changes in input states inside the "endless" game cycle and react accordingly. Usually update system parameters using delta over time. There are many tutorials on this subject and Pygame is available and Pygame docs are pretty solid.

A simple example of how to do this:

 import pygame pygame.init() # to spam the pygame.KEYDOWN event every 100ms while key being pressed pygame.key.set_repeat(100, 100) while 1: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_w: print 'go forward' if event.key == pygame.K_s: print 'go backward' if event.type == pygame.KEYUP: print 'stop' 

You will need to play with pygame.KEYDOWN , pygame.KEYUP and pygame.key.set_repeat depending on how your carโ€™s movement is implemented.

+1
source

Source: https://habr.com/ru/post/971177/


All Articles