0

I would like to create a python program to detect when a certain key (W,A,S,D) is pressed so for example, while the w key is pressed, the def forward() is activated and when it is let go, it stops the motor. How would I do this so that as soon as the pi boots up, my keystrokes are detected and the program responds accordingly?

Example program

#!/usr/bin/python
import explorerhat
import sys, tty, termios, time

def left():
    explorerhat.motor.one.forward(75)
def right():
    explorerhat.motor.one.backward(75)


while True:
    char = input()

    if(char=="a"):
            left()

    if(char=="d"):
            right()

    if(char=="x"):
            break

    char = ""

explorerhat.motor.one.stop()

Thanks! This is to control a little robot I'm building.

1

Using input(), you will need to press Enter after every keystroke. Instead, you might want to use a function that accepts keypresses, rather than lines of input. A starting point is in this question.

There are various ways to get your programme to start when the RPi boots up. Some of them are listed here.

0

What about:

#!/usr/bin/python
import explorerhat
import sys, tty, termios, time

def left():
    explorerhat.motor.one.forward(75)
def right():
    explorerhat.motor.one.backwatd(75)


while True:
    char = input()

    if(char=="a"):
        left()
    else:
        if(char != "a")
             explorerhat.motor.one.stop()

    if(char=="d"):
        right()
    else:
        if(char != "d")
           explorerhat.motor.one.stop()

    if(char=="x"):
        break

    char = ""

explorerhat.motor.one.stop()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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