How it works...

Once you have built the robot and wired up the wheels to the motor controller, you can work out how to control it.

Start by importing time (which will allow you to put pauses in the motor control) and wiringpi2 (to allow control of the GPIO pins). Use wiringpi2 here, since it makes it much easier to make use of I/O expanders and other I2C devices, if you want to later on.

Define values to use for setting the pins ON/OFF, for the direction IN/OUT, as well as the duration of each motor STEP. Also, define which PINS are wired to the motor controls, and our movements, FWD, RIGHT, and LEFT. The movement is defined in such a way that by switching both motors ON, you will move forward, and by switching just one motor ON, you will turn. By setting these values at the start of the file using variables, our code is easier to maintain and understand.

We define a motor class that will allow us to reuse it in other code, or easily swap it with alternative motor classes so that we can use other hardware if we want to. We set the default pins we are using and our steptime value (the steptime object defines how long we drive the motor(s) for in each step). However, both can still be specified when initializing the object, if desired.

Next, we call GPIOsetup(); it selects the physical pin numbering mode (so we can refer to the pins as they are located on the board). We also set all of the pins we are using to output.

Finally, for the motor class, we define the following three functions:

  • The first function we define (called off()) will allow us to switch off the motors, so we cycle through the pins list and set each GPIO pin to low (and therefore switch the motors off).
  • The drive() function allows us to provide a list of drive actions (a combination of ON and OFF for each of the GPIO pins). Again, we cycle through each of the pins and set them to the corresponding drive action, wait for the step time, and then switch the motors off using the off() function.
  • The last function we define (called cmd()) simply allows us to send char (a single character) and use it to select the set of drive actions we want to use (FWD, RIGHT or LEFT, or wait (#)).

For testing, main() allows us to specify a list of actions that need to be performed from the command line using the following command:

sudo CMD=f#lrr##fff python3 rover_drivefwd.py
  

Using os.environ (by importing the os module so we can use it), we can check for CMD in the command and use it as our list of drive actions. If no CMD command has been provided, we can use the input() function to directly prompt for a list of drive actions. To use the motor class, we set roverPi=motor(); this allows us to call the cmd() function (of the motor class) with each character from the list of drive actions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.254.151