Page 1 of 1

Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 9:04 am
by iphoneturn
Hi, I just made a RC car powered by a Raspberry Pi and a L293N dual h-bridge motor driver and I plan to control it with a 2.4 GHz keyboard but I can't get my code to run. Here is my code:

GPIO.setup(5, GPIO ,OUT)
GPIO.setup(6, GPIO ,OUT)
GPIO.setup(13, GPIO ,OUT)
GPIO.setup(19, GPIO ,OUT)

str = raw_input()
if str == 'w":
GPIO.output(13,True)

str = raw_input()
if str == 's":
GPIO.output(19,True)

str = raw_input()
if str == 'a":
GPIO.output(5,True)

str = raw_input()
if str == 'd":
GPIO.output(6,True)

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 10:42 am
by MarkHaysHarris777
When you share code, put your code in a Code block... its on the editor panel above, between Quote and List. That will preserve your indents and makes stuff look nicer for the people trying to make sense of it. tnx

raw_input is not generally something you want to use; in any case, your decision tree needs probably to be a little more robust. What happens ? What are you expecting to happen ?

marcus

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 11:34 am
by elParaguayo
This is very similar to a post I replied to a couple of days ago and then the thread was deleted.

As marcus says, raw_input probably isn't what you want here. Rather than reacting to a single keypress, it reads a line of input and returns that as a string. This means you would need to press enter after pressing your key for this to work using raw_input.

I think that there have been examples of reacting to keypresses using getch (have a search on the forum).

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 12:03 pm
by B.Goode

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 12:07 pm
by elParaguayo
Ah. That was the post I replied to in the python forum. They must have double posted.

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 12:13 pm
by B.Goode
elParaguayo wrote:Ah. That was the post I replied to in the python forum. They must have double posted.
No, I think you were right first time: you diagnosed the 'hit return' problem in a duplicate post that has now gone.

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 1:20 pm
by iphoneturn
My goal here is when I press "a" key for 1 second, GPIO 5 will be set to "HIGH" for 1 second and then go to "LOW". :)

Re: Keyboard input to GPIO output

Posted: Wed Jul 27, 2016 2:16 pm
by joan
iphoneturn wrote:My goal here is when I press "a" key for 1 second, GPIO 5 will be set to "HIGH" for 1 second and then go to "LOW". :)
So you want to wait for a key press, time how long it is before the key release and then set GPIO5 high for the same length of time.

Or do you mean when you press a key set GPIO5 high and when the key is released set GPIO5 low.

Re: Keyboard input to GPIO output

Posted: Thu Jul 28, 2016 1:13 am
by iphoneturn
Hi @joan, it is the first one. :D