Control robot by using keyboard
<p>I am new to Python and raspberry pi, I have created a wheeled robot and codes for forwards, backward, turn left and turn right! However every time I want to execute a differant script I have to open a new code and run it(eg open the file for forwards, then open the file for left etc etc.) </p>

<p>How do I use the the keyboard arrows to execute parts of the script? </p>

<p>I want to be able to press the up button and the robot move forward, then release the up button and the robot stop, then press the left arrow key and the robot turn left until I release the key etc.</p>

<p>Iv tried tons of forums and threads but they all relate to differant codes (iv found how to use keyboard events for turtle but they don't work on i2c or gpio)</p>

<p>Can anybody help me
I bet there's a real simple command code but I don't know what it is or where to find it! </p>

<p>I'm using adafruit motor hat with raspberry pi to power the motors if this makes a difference </p>

<p>You only need one file for this. Make a new file.</p>

<p>You will need a infinite loop, I will suggest using a <code>while(true)</code> loop. You then need</p>

<pre><code>if(/*key was UP ARROW*/){
/*CODE TO MAKE MOVE FORWARD HERE*/
}else if(/*KEY WAS DOWN ARROW*/{
/*CODE TO MAKE MOVE DOWN HERE*/
} etc...
</code></pre>

<p>inside of that <code>while(true)</code> loop. This way, you will be able to use ONE file to capture all keyboard data. So, it would look something similar to this</p>

<pre><code>while(true){
//read key input
if(/*key was UP ARROW*/){
    /*CODE TO MAKE MOVE FORWARD HERE*/
    }else if(/*KEY WAS DOWN ARROW*/{
    /*CODE TO MAKE MOVE DOWN HERE*/
    } etc...
}
</code></pre>

<p>This should do what you need. You already said you have the code to move it, so this shouldn't take long to transfer over.</p>

<p>Try reading more about it here <a href="https://learn.pimoroni.com/tutorial/robots/controlling-your-robot-wireless-keyboard" rel="nofollow">https://learn.pimoroni.com/tutorial/robots/controlling-your-robot-wireless-keyboard</a> This should help you immensely</p>

python keyboard raspberry-pi control keyboard-events