1

I want to be able to control some motors that are hooked up to my raspberry pi through keyboard presses. I have code that turns the motors one direction for 5 seconds and then the other direction for 5 seconds before turning them off. I want to use the key listener function of pygame to control the motors through keyboard presses. I am using the following as a test on the keyboard press aspect.

import pygame

pygame.init()

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'

When I run this script, I do not get any errors, so I know it runs. However, when I press either the 'w' or 's' key, what displays is either a 'w' or an 's' as if I was just typing. All I want is to be able to execute a function by pressing a key. If there is a different/better way to do it that would be fine.

Jared
  • 11
  • 2
  • 1
    All fixed. Did not realize you needed to tell pygame to make a window, even if the window is not used. – Jared Apr 27 '16 at 00:57

1 Answers1

0

Pygame KEYDOWN events are looking for key presses in the active window.

You must create a window to tell Pygame where to read events from.

Another solution would be to hook keyboard events from the terminal so you wouldn't have to have a window initialized or in focus, using something like this: Python Key Binding or using the pyHook library to make global keyboard event hooks.

P.S - I realise you solved the problem yourself, I'm including this for completeness.

Community
  • 1
  • 1
DCA-
  • 1,262
  • 2
  • 18
  • 33