Chatham Rabbit Hole Logo

Robot Buggy – Python Code

Robot Buggy Python Code is built atop the GPIOZERO library

Key to all code elements developed thus far is the class gpiozero.Robot(left, right, *, pwm=True, pin_factory=None).

Inputs to the class constructor are number pairs (i.e., “tuples”) designated “left” and “right” that designate the GPIO pins designated for motor control of a simple two-motor robot; an third boolean input “pwm” specfies whether or not the motor speed can be controlled using Pulse-Width-Modulation.  The last argument to the class, pin_factory, designates whether an alternate to the local default GPIO pins are to be used.

The essential elements in using the Robot class are shown in the code-snippet below. Note that the GPIO pin choice is arbitrary as long as the pins chosen are usable as outputs; also, the order in which a pair of pins is listed matters … reverse the order in the software reverses the direction of motor rotation.  Further, multiple instances of the robot class can be created; this could allow creation of robot controllers for 2, 4, 6 motors … limited by the availability of GPIO pins.


					#import and initialize essential libraries
import gpiozero 
import time 
# create an instance of the Robot Class and specify the GPIO pins it uses
robot = gpiozero.Robot(left=(9, 10), right=(7,8))
#try it out
try: # Robot actions here
robot.forward() time.sleep(1)
finally: robot.stop()