Raspberry Pi Car

C4K recommends getting a Raspeberry Pi device and then attempting some of the projects on the official Raspberry Pi page or Ubuntu pit.

Ps. The Raspberry Pi is a tiny computer board that lets you build innovative computing projects at a very affordable price. The single-board computer is now in its third major version and is being widely used for numerous tech projects around the world.

Line following robot

To start with the line following robot follow these instructions

Before you begin make sure you are the first to know about new projects

Introduction

In this project you will build a robot buggy that you can program to move around using simple Python commands.

finished

What you will learn

  • How to set up a motor controller board with two motors
  • How to control motors using Python
  • How to build a robot chassis

This resource covers elements from the following strands of the Raspberry Pi Digital Making Curriculum:

What you will need

  • Note that not all of the following hardware is required to create the buggy. However, if you are planning to add autonomous capability (self-driving) to your robot buggy, then you will need additional bits in the ‘optional’ list.

Hardware

hardward

Basic buggy

Optional additional components

Software

  • The latest version of the Raspbian operating system
  • Once downloaded copy and run the following commands in the terminal (inn order)

sudo apt-get upgrade

sudo apt-get update

sudo restart

Additional extras

  • Small cardboard box
  • Adhesives (duct tape/putty/glue)

Assembling the motors and board

The first thing you will want to do is to connect your motor controller board to your Raspberry Pi, the battery pack, and your two motors, to test that they are all working.

The instructions here are for L298N Dual H Bridge DC Stepper Motor Driver Controller Board, and they will be pretty similar for most motor controller boards. Check the documentation for your board if you are using a different one. (contact us)

Soldering wires to your motors

Most motors you can buy don’t have wires, so you will need to solder these on. If you have never soldered before, then have a look at our Getting started with soldering resource.

Strip the ends of the wires to reveal the metal core.

strip wires

Remove the plastic clip from the motor to make soldering to the contacts easier. You can do this with a screwdriver.

remove clip

Solder the wires to each of the terminals on the motor. It doesn’t matter which wire goes to which terminal. The reattach the plastic clips.

solder wires

Trim the tips of the wires to ensure they do not touch the metal casing of the motor. It’s also a good idea to wrap the ends of the motors in tape, to stop the soldered joints from breaking.

Connect the motors to the board

You will need to connect the motors to the board. For this you will require a small screwdriver.

Using a screwdriver, loosen the screws in the terminal blocks labeled OUT1OUT2OUT3, and OUT4. Have a look at the documentation for your board if your labels are different. Strip the ends of the wires (you can snip off the male or female ends if you need to) and insert the stripped ends of wire into the terminal blocks.

inserted wires

Tighten the screws up so that the wires are held firmly in the terminal blocks.

terminal block

Powering the motors

The motors require more power than the Raspberry Pi can provide. Therefore, you will use four AA batteries to power them.

Loosen the screws in the terminal blocks labeled VCCGND, and 5V. Take the AA battery holder and insert the red wire into the VCC terminal block. The black wire goes into the GND block. It is important that you get this the correct way around.

battery holder

Tighten the screws so that the wires are held firmly in place.

battery terminals

Connecting the board to your Raspberry Pi

The board used in this project needs to be wired to the Raspberry Pi. Other boards may connect differently, and some boards can simply be placed onto the Raspberry Pi GPIO pins as a HAT. Make sure you look at the documentation for your board to see whether this is the case.

On the board used here there are pins labeled In1In2In3, and In4, as well as two GND pins. Which GPIO pins on your Pi that you use is up to you; in this project, GPIO 789, and 10 have been used.

Use five female-to-female jumper leads to connect the Raspberry Pi GPIO pins to the pins on the motor controller board.

GPIO pinconnects toboard pin
7<–>In1
8<–>In2
9<–>In3
10<–>In4
GND<–>GND

If your board does not have a GND pin, then strip the end of the female to female wire and secure it into the GND terminal block that your battery pack feeds into.

GPIO to board

Left, right, forward, backward

You need to figure out which is your left motor and which is your right motor. You also need to know which way they are driving to go forward, and which way they are driving to go backwards.

Choose one of the motors. Use a marker pen to label it ‘right’ and draw an arrow on it to indicate which way is forward. Label the other motor ‘left’ and draw an arrow on it pointing in the same direction as your first one.

labeled motors

Now open mu from the Raspberry Pi Programming menu.

Type the following to import the Robot class and create a Robot object. You can name it anything you like. In this resource, the robot is called robby.

from gpiozero import Robot
robby = Robot(left=(7,8), right=(9,10))

Save you file and call it robby.py or something similar. You can then run it by clicking Run.

Now open a python shell by clicking the terminal icon in the taskbar at the top of the screen, then type ‘python’ and press Enter. Now type the following to observe which way the motors turn.

robby.forward()

You can stop them by typing robot.stop().

motors turning

Now, type the following command, and note which motor changes direction on the second command.

robby.forward(0.4)
robby.right(0.4)

The 0.4 makes the motors go a little slower, so it is easy to see which way they turn.

The motor that changed direction is the right-hand motor. If that was the one you labeled ‘right’, then there’s nothing to change yet. If it was the one you labeled ‘left’, you need to alter your Robot object in your file to switch around the left and right pin numbers:

## e.g. change
robby = Robot(left=(7,8), right=(9,10))
## to
robby = Robot(left=(9,10), right=(7,8))

Now that you have the ‘left’ and ‘right’ sorted, you need to make sure you have forward and backward set up correctly.

Again drive both motors forward.

robby.forward(0.4)

Check that both motors are turning in the direction shown in the diagram below.

direction of motors

If the right-hand motor is turning in the wrong direction, alter your robot object by switching the order of the GPIO pin numbers. For instance:

## e.g. change
robby = Robot(left=(9,10), right=(7,8))
## to
robby = Robot(left=(9,10), right=(8,7))

If the left-hand motor is turning the wrong way, then do the same for its pin numbers.

Assemble your robot

There is no “right” way to build your prototype robot chassis, but there are a few things to bear in mind:

  • The chassis needs to house the Raspberry Pi, motor controller, and batteries.
  • The chassis needs to allow the mounting of a pair of wheels.
  • You may want to later add a couple of line sensors, and an ultrasonic distance sensor or a lidar sensor to the chassis.

It’s always a good idea to build a prototype chassis first. Eventually, you can learn how to laser-cut or 3D print a chassis, but in this project, a cardboard box is used as a temporary solution.

chassis-0

The first step is to place your motors into the chassis.

Place your motors inside the box, in roughly the position that you would like them to sit. Then use a pen to mark the place where the motors’ axle will need to pass through the walls of the box. Make sure you are giving your wheels enough room to spin around.
chassis-1

Use a sharp object to poke holes through the sides of the box so that the motors’ axles can fit through.
chassis-2
chassis-3

You will need to fix the motors in place. Use an adhesive putty or tape to hold them down.
chassis-4

Once the motors are in place, you can attach the wheels to the axles.
chassis-5

When the wheels are in place, you can screw a ball caster to the front of the container to act as a third wheel.
chassis-6
chassis-7

If you’re using a power bank, you can now power up your Raspberry Pi. If you want to make your own power bank, then follow the guide below.
chassis-8

Make your own power bank

Warning: LiPo batteries can be dangerous, and can cause chemical fires when treated incorrectly. If you have little or no experience handling them, you should use a commercial power bank with safety certification relevant for you locale.

To make your own power bank, you will need a charging protection board, an 18650 battery, and an 18650 battery clip.

components

You will also need access to a soldering iron and some solder.

  • Solder the black lead from the battery clip to the negative terminal of the board. Then solder the red lead to the positive terminal.soldering
  • Once you’ve soldered the board to the battery clip, insert an 18650 battery. Often the positive and negative terminals are not marked. The smaller metallic terminal is the positive.

The red LED should flash to indicate it is charging.

charging

To use your Raspberry Pi without connecting a mouse, monitor, or keyboard, you can remotely access it via SSH or VNC.

Accessing your Raspberry Pi via SSH

You can access a remote terminal on your Raspberry Pi using the Secure Shell tool (SSH).

SSH is disabled by default on the Raspberry Pi, so you first need to enable it.

  • Click on Menu > Preferences > Raspberry Pi Configuration.configuration
  • Click on the Interfaces tab. Then check the radio button next to SSH to enable it.enable
  • Click OK to finish.
  • To find the IP address of your Raspberry Pi, open a terminal and type:hostname -I
  • As you have now enabled SSH, it is a good idea to change your password. In a terminal window, type:passwd

Now you can access your Raspberry Pi via SSH from another networked computer using the instructions below.

Nix-based operating systems

  • If your are using macOS or a Linux-based OS, then SSH is native to the operating system.
  • Open a terminal and type the following, replacing 10.10.10.10 with the IP address of your Raspberry Pi.ssh pi@10.10.10.10
  • Type in the password when prompted; it is usually raspberry unless you have changed it.

Chrome OS and Chrome browser

  • If you are using Chrome OS or have access to the Chrome browser, then there’s a Chrome app that allows access over SSH. You can find the Secure Shell App in the Chrome Web Store.
  • Once installed, click on the app to open it.
  • Now you can access the Raspberry Pi by typing in the IP address:
  • Then type in the password:

PuTTY (on Windows)

  • PuTTY is an app that provides SSH access on Windows.
  • Download PuTTY from this site.
  • Once installed, open PuTTY from the Start menu and type in the IP address.
  • If it’s your first time connecting to this Raspberry Pi, you’ll get a warning dialogue box, so click Yes to connect:
  • Then you need to enter the username and password for the Raspberry Pi (usually pi and raspberry, unless you have changed them).

Accessing your Raspberry Pi via VNC

As long as your Raspberry Pi is networked either via WiFi or Ethernet, you can operate it remotely from any existing networked computer.

Virtual Network Computing (VNC) is a protocol that allows you to control one computer from another computer. The advantage of using VNC is that you gain access to the full desktop of the Raspberry Pi, meaning you can use graphical programs from the connected computer.

  • The first thing to do is to enable the VNC server on the Raspberry Pi. Raspbian comes pre-installed with RealVNC.
  • Click on Menu > Preferences > Raspberry Pi Configuration.
config menu
  • Enable the VNC server by clicking the respective radio button, and click OK.
preferences

You should then see the icon for the VNC server in your menu bar.

menu

Your VNC server will now start whenever the Pi is booted, and will continue to do so until you disable the VNC server again.

To connect to the Raspberry Pi from another computer, follow the instructions in one of the links below.

Connecting with Windows, Linux, or macOS

There are many VNC viewers that can be downloaded and used on your desktop computer. For simplicity’s sake, the instructions below are for using RealVNC.

  • Download the client for your preferred operating system from the RealVNC website.
  • Install the downloaded software.
  • When you run the software for the first time, you will be asked to accept the terms and conditions.
  • You can now connect remotely to your Raspberry Pi by typing its IP address into the connection bar. If you don’t know the IP address of your Raspberry Pi, you can find it by clicking on the RealVNC icon on the Raspberry Pi’s desktop.ip address
  • Next, you’ll be asked to authenticate. Type in your Raspberry Pi username and password (the defaults are pi and raspberry).authentication
  • You should now have a remote desktop session.remote

VNC with Chrome OS

You’ll need an app from the Chrome Web Store to use VNC on a Chromebook.

  • In the Chrome Web Store, search for ‘VNC Viewer for Google Chrome’ and add the application to Chrome.
  • With the app open, you can type in the IP address and desktop number for the Raspberry Pi.
  • Enter the password at the prompt.
  • You should now be connected to the Raspberry Pi.

Other platforms

Most mobile platforms (Android, iOS, Windows Mobile) have their own VNC apps, which are available in the respective app stores.

Challenge Program your robot to do …(Read More)

n addition to your Raspberry Pi buggy, you will need:

  • 8 female-to-female or female-to-male jumper leads
  • 2 line following sensors
  • Soldering iron and solder
  • Insulating tape
components

You can purchase the line following sensors used in this project via this buggy shopping list, although any line sensors will work here.

What you will learn

This project covers elements from the following strands of the Raspberry Pi Digital Making Curriculum:

Prepare the connectors

Your first step will be to connect your line sensors to your buggy. Normally, the type of line sensor used in this project needs to be connected to a 3V3 pin, but you’re going to run two sensors via the same power pin, so you’ll attach both of them to a 5V pin.

First, you’re going to prepare your leads!

  • Take three of your female-to-female jumper leads, remove a connector from each end, and then strip the plastic sheath to reveal about a centimeter of the multi-core wire beneath.
stripped
  • Take the three jumper leads and twist their multi-core wires together. Then use a soldering iron to bond the leads.
solder

Cover the join of the leads with a small amount of insulating tape.

soldered

Repeat the entire process with another three female-to-female jumper leads.

Connect the line sensors

Each line sensor has three pins: VCC for power, GND for ground, and DO for digital out.

line sensor

Take one of your soldered-together three-wire jumper leads, and connect two of its ends to the VCC pin on each of the two sensors.

power

Take the second of your soldered jumper leads, and connect two ends to the GND pin on each line sensor.

ground

Take your remaining two single jumper leads and connect each one to the DO pin on each line sensors.

digital out

Now connect the VCC pins of both line sensors to a 5V pin on your Raspberry Pi, and the GND pins of the sensors to a GND pin on your Raspberry Pi. Each of the two DO pins can be connected to any numbered GPIO pin. In this example, pins GPIO 17 and GPIO 27 are used.

connected

Test the line sensors
Next you’re going to test whether your line sensors are working, and you’ll tune them a little.

With the line sensor attached, boot up your Raspberry Pi.

Cut two small holes in the bottom of your buggy so that the sensor can view the line beneath it, and secure your sensors in place.

through-hole
When the sensors pass over a dark line, the LED on the sensor board should turn off.
tune

Use the small potentiometer on the board to tune your sensors, so that the LEDs turns off when over a dark line, and lights up when over white space.
tune
Once you have tuned the sensors, you can proceed to programming your robot.

Programming a line following algorithm

Note: In this example, the motor controller board is connected so that the left motor is on pins GPIO 7 and GPIO 8, and the right motor is on pins GPIO 9 and GPIO 10. The left line sensor is on pin GPIO 17, and the right line sensor is on pin GPIO 27.

Open up mu from the Raspberry Pi Programming menu, and begin by setting up your motor controller board and your sensors using gpiozero:

from gpiozero import Robot, LineSensor
from signal import pause
from time import sleep

robot = Robot(left=(7, 8), right=(9, 10))
left_sensor = LineSensor(17)
right_sensor= LineSensor(27)

To begin with, write a really simple line following algorithm, just to test that your robot is working.

The gpiozero module can call a function depending on whether or not a line has been detected. For example:

left_sensor.when_line = function_name_to_call
left_sensor.when_no_line = other_function_name_to_call

This will tell the robot to do something when the left_sensor detects that it is not above a line.
By telling the robot to go forward when no line has been detected, but to turn if a line is detected, you can produce very basic line following behavior.

Add four lines of code to your robot program to produce a basic line following algorithm.

I need a hint

Don’t worry if you’re robot tracks off its line a bit. Just observe if it attempts to stay on the line. Here’s an example of a robot running on a basic track with this algorithm.

final

Plan a better algorithm
The previous algorithm might be OK, it can easily be improved upon. Let’s see what a better algorithm might look like!
When a line sensor is above a line, it outputs a 1. When it’s off a line, it outputs a 0.
The motors work slightly differently though: the robot, whenever it receives a 1 signal to the right motor, drives that motor forwards. When it receives a -1, it drives the motor backwards.
Let’s have a look at an algorithm that takes into account the position of the robot, the states of the lines sensors, and the actions required of the motors.
The robot is perfectly on the line and should drive forwards:Both line sensors are off the line and outputting a 0
Both motors should receive 1 to drive forwards
The robot has drifted left and needs to turn right:The right sensor is on the line and outputting a 1
The left sensor is off the line and outputting a 0
The left motor should run backwards and so receive a -1
The right motor should run forwards and so receive a 1
The robot has drifted right and needs to turn left:The right sensor is off the line and outputting a 0
The left sensor is on the line and outputting a 1
The Left motor should run forwards and so receive a 1
The right motor should run backwards and so receive a -1
How can you make this happen in code? First of all, you’ll create an infinite loop to view the sensor values.

In a new file, add in the following lines of code and run it. Don’t forget to adjust the pin numbers if you’ve used different GPIO pins.
from gpiozero import Robot, LineSensor from time import sleep robot = Robot(left=(7, 8), right=(9, 10)) left_sensor = LineSensor(17) right_sensor= LineSensor(27) while True: left_detect = int(left_sensor.value) right_detect = int(right_sensor.value) print(left_detect, right_detect)
Now move the robot back and forth over the line to see what happens.
Hopefully, you should see the binary output from the sensors.
sensor_output
So now that you have the sensor output, you need to alter it a little before you send it to the motors. As per the algorithm above:
If both sensors output 0, then both motors should receive 1
If the right sensor outputs 1, then the left motor should receive -1
If the left sensor outputs 1, then the right motor should receive -1

Within the while True loop, create two new variables called left_mot and right_mot. These variables should have the same value that you would like the motors to receive. You can simply print out their values within the loop.
I need a hint
According to the above algorithm, if left_detect == 0 and right_detect == 0:, what do you want the values of left_mot and right_mot to be?
Here’s the code for the first condition:
while True: left_detect = int(left_sensor.value) right_detect = int(right_sensor.value) if left_detect == 0 and right_detect == 0: left_mot = 1 right_mot = 1
You need two more if statements to handle the sensors being triggered by a line.
Here’s the completed code, with the print statements:
while True: left_detect = int(left_sensor.value) right_detect = int(right_sensor.value) if left_detect == 0 and right_detect == 0: left_mot = 1 right_mot = 1 if left_detect == 0 and right_detect == 1: left_mot = -1 if left_detect == 1 and right_detect == 0: right_mot = -1 print(right_mot, left_mot)




When you are done, run your code and test how it works when you move the robot over the line.
sensor_output2.gif

The final algorithm

Now that you are outputting values that the motors can use, it is time to feed these values in.

To begin with you’re going to turn your while True loop into a generator. A generator is a little like a function, except that it will continually run and only yield values when it is asked for them.

Turn your loop into a generator like this:

def motor_speed():
    while True:
        left_detect  = int(left_sensor.value)
        right_detect = int(right_sensor.value)
        ## Stage 1
        if left_detect == 0 and right_detect == 0:
            left_mot = 1
            right_mot = 1
        ## Stage 2
        if left_detect == 0 and right_detect == 1:
            left_mot = -1
        if left_detect == 1 and right_detect == 0:
            right_mot = -1
        #print(r, l)
        yield (right_mot, left_mot)

Now all you need to do is to say that the source of the robot’s motor values is going to be the result of the generator.

Add in this line of code below the generator:

robot.source = motor_speed()

To make sure that the robot doesn’t keep running forever, and to close all the components connections cleanly, you can optionally add in these lines as well:

sleep(60)
robot.stop()
robot.source = None
robot.close()
left_sensor.close()
right_sensor.close()

Now run your code and test your robot over a track.

Sometimes the robot runs a little too fast, so you can tweak your code a bit as shown in the following completed script. This adds in a speed multiplier to slow the robot down a little.

from gpiozero import Robot, LineSensor
from time import sleep

robot = Robot(left=(7, 8), right=(9, 10))
left_sensor = LineSensor(17)
right_sensor= LineSensor(27)

speed = 0.65

def motor_speed():
    while True:
        left_detect  = int(left_sensor.value)
        right_detect = int(right_sensor.value)
        ## Stage 1
        if left_detect == 0 and right_detect == 0:
            left_mot = 1
            right_mot = 1
        ## Stage 2
        if left_detect == 0 and right_detect == 1:
            left_mot = -1
        if left_detect == 1 and right_detect == 0:
            right_mot = -1
        #print(r, l)
        yield (right_mot * speed, left_mot * speed)

robot.source = motor_speed()

sleep(60)
robot.stop()
robot.source = None
robot.close()
left_sensor.close()
right_sensor.close()

See video here of final product https://projects-static.raspberrypi.org/projects/rpi-python-line-following/55accf3567238b8da102d924414dc481f284a3aa/en/images/showcase.webm

See more here

0
    0
    Your Cart
    Your cart is emptyReturn to Shop