How to build a robot with Raspberry Pi

We now create four functions that will handle driving our motors in a particular direction. Each of the functions will take an argument, a duration of time that's expressed as an integer or a float:

def forward(i):

How to build a Robot with Raspberry Pi

Our finished robot is simple yet elegant. Its utilitarian design enables easy access to all of the components for any last minute tweaks or fixes

For our left and reverse functions you can refer to the full code.

The last section of code is a try and except test:

try:

[Tab] print("R E A D Y")

except KeyboardInterrupt:

[Tab] print("E X I T")

[Tab] GPIO.cleanup()

This will print R E A D Y when the code is executed, but if we press CTRL+c it will print E X I T and then clean up the GPIO pins ready for use by another project:

Save your code as robot.py but we won't be running the code, rather we will now create a new file and save it as test. py in the same directory as robot.py.

Next, we'll import our robot.py code and use the functions inside of it to control our robot.

import robot

robot.forward(1)

robot.right(2)

robot.left(2)

robot.reverse(1)

Save the code and click Run > Run Module to test. Remember to pick up the robot before pressing Enter or you will have to chase after it!

TOPICS