Reputation: 25
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.)
How do I use the the keyboard arrows to execute parts of the script?
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.
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)
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!
I'm using adafruit motor hat with raspberry pi to power the motors if this makes a difference
Upvotes: 0
Views: 6641
Reputation: 1192
You only need one file for this. Make a new file.
You will need a infinite loop, I will suggest using a while(true)
loop. You then need
if(/*key was UP ARROW*/){
/*CODE TO MAKE MOVE FORWARD HERE*/
}else if(/*KEY WAS DOWN ARROW*/{
/*CODE TO MAKE MOVE DOWN HERE*/
} etc...
inside of that while(true)
loop. This way, you will be able to use ONE file to capture all keyboard data. So, it would look something similar to this
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...
}
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.
Try reading more about it here https://learn.pimoroni.com/tutorial/robots/controlling-your-robot-wireless-keyboard This should help you immensely
Upvotes: 0