How to build a robot with Raspberry Pi

Boot your Raspberry Pi to the desktop and open a terminal, you can find the icon in the menu bar at the top left corner of the screen.

How to build a robot with Raspberry Pi

The Raspbian desktop

In the LXTerminal type the following and press Enter to run:

$ sudo raspi-config

Using the arrow keys navigate to Advanced Options and press Enter. In the Advanced menu navigate to the SSH Server option, press Enter and in the new screen choose to Enable the SSH server.

Exit from the menus and reboot your Raspberry Pi. Reboot back to the desktop and open another LXTerminal and type the following for your IP address and write the address down:

$ hostname -I

In the same terminal type the following to launch the Python 3 editor with superuser powers:

$ sudo idle3 &.

We'll start our code by importing two libraries, the first enables our code to talk to the GPIO pins on our Raspberry Pi while the second provides the time library:

import RPi.GPIO as GPIO

import time

When using the GPIO pins we will refer to them using their Broadcom pin numbering and we must, in turn, configure our code to use those numbers with GPIO.setmode(GPIO.BCM).

Rather than refer to each pin throughout our code we shall create four variables to store the GPIO pin connected to each of the inputs on the L298N:

fwdleft = 17

fwdright = 18

revleft = 22

revright = 23

In order to use each GPIO pin we need to instruct the code what each pin will be: an input or output. As we will be sending current from the GPIO pins they will be an output.

So using a list, known in other languages as an array, and a for loop, we shall iterate over each item in the list, which are our variables, and configure each GPIO pin as follows:

motors = [fwdleft,fwdright,revleft,revright]

for item in motors:

[Tab] GPIO.setup(item, GPIO.OUT)

Not that where we type '[Tab]' hit the Tab key on your keyboard to make the code indented for that line - this is important when using Python.

TOPICS