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):

[Tab] GPIO.output(fwdright, True)

[Tab] GPIO.output(fwdleft, True)

[Tab] time.sleep(i)

[Tab] GPIO.output(fwdright, False)

[Tab] GPIO.output(fwdleft, False)

Remember that where we've put '[Tab]' just press the Tab key on your keyboard to indent the line. Our first function, forward(i) , will turn on fwdright and fwdleft pins and then wait for the value of i , our argument before turning the motors off.

On to our second function:

def right(i):

[Tab] GPIO.output(revright, True)

[Tab] GPIO.output(fwdleft, True)

[Tab] time.sleep(i)

[Tab] GPIO.output(revright, False)

[Tab] GPIO.output(fwdleft, False)

Our second function, right(i) , spins our robot on the spot in a clockwise direction for the duration provided as the argument (i) . To turn right we set the right motor to reverse and the left motor to forwards, wait for the user defined number of seconds and then turn off the motors.

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:


[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 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

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

import robot





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!