[Raspberry Pi] How to Build a Robot: A Step-by-Step Guide for Beginners
Published | Last Update 📌
A blind run by some guy.
11,835 views, 4 RAMs, and 2 comments
- Part List
- Footnotes on Raspberry Pis
- Miscellaneous Household Supplies
- Assembling the Chassis
- Assembling the Chassis (v1)
- Creating Wheels (Optional)
- Creating the Body
- Affixing Wheels to the Body
- Assembling the Raspberry Pi
- Attaching a Raspberry Pi
- Assembling the Chassis (v2): Higher Quality Materials
- Previous Steps: Higher Quality Version
- The Raspberry Pi’s Power Supply
- The Raspberry Pi: Initial Setup
- Setting Up the Raspberry Pi
- Turning on the Raspberry Pi
- Troubleshooting the Raspberry Pi
- [Troubleshooting] Fixing the “Rainbow Screen” Error
- [Troubleshooting] Installing NOOBS to an SD Card
- [Troubleshooting] Booting a Raspberry Pi from USB
- [Troubleshooting] Switching Out the Raspberry Pi
- More Setup: How to Set up a Raspberry Pi (Without a Monitor)
- Connecting to a Raspberry Pi via SSH
- Raspberry Pi Terminal, Programming, and Circuitry Overview
- Using the Terminal
- Linux Terminal Crash Course
- Using the Raspberry Pi's GPIO with Python
- Writing a “Hello World” Test
- How Raspberry Pi’s GPIO Works
- Raspberry Pi GPIO “Hello World” (Controlling an LED)
- Overview of Circuitry Concepts
- How Breadboards Work
- Calculating Resistor Values and Identifying Resistors
- Setting Up the Wiring
- Batteries and Power Sources
- Powering Peripherals via Raspberry Pi vs. External/Separate Power Sources
- 6V AA Battery Holder Packs
- How AA Battery Packs Work
- Creating or Harvesting a 6V Battery Holder
- Plausible Alternative: Using a D Battery (9-Volt)
- Adding Power Lights
- Battery Pack Power Light (Red LED)
- "Program is Running" Light (Green LED)
- Servo Rotation
- Identifying Servo Wires
- Connecting a Servo to a Raspberry Pi
- Controlling Servos with a Raspberry Pi
- The Final Build
- The Full Script to Control the Robot
- Refining the Robot
- In Conclusion
Building robots seems expensive and complicated. However, it turns out that it’s relatively straightforward. Do you have an IQ higher than 90 andassorted random garbagelying around your house? Then you too can make a robot in a reasonably small amount of time.
Anyway, this post documents the process of throwing some parts together to make a High Quality robot. Since this is an introductory guide, parts are designed to be fairly minimal. Originally everything used in this tutorial was planned to be random shit that happened to be around my house, although I ended up picking up a few other parts halfway through. You’ll probably need to pick up a few things, unless you happen to have servos and a Raspberry Pi and/or Arduino lying around your house.
These parts (as well as their assembly process) aremore like guidelines than rules; you might make adjustments based on what you happen to have around, your budget, and your interests.
All of the parts involved in this project are listed below. It should be noted that there are a number of parts that can be skipped, as well as substitutions that can be made. Some parts can be assembled from household objects and/or are purely for convenience or luxury. Because of this, the parts are split into two categories: What was used for this original build in this guide and what I would recommend and/or what was upgraded to partway through this build.
Note that all links to Amazon here are affiliate links; you can click them if that's something that you want to do. There are potentially cheaper deals if you search for Chinese companies that will ship directly to you.
|Part||Original||Num Units||Cost Per Unit||Total Cost||Final or Recommended||Num Units||Cost Per Unit||Total Cost|
|Wheel Motors||Two Hi-Tec 31311S HS-311 Servos. These are the small motors used to turn the wheels. Wheels are a separate part.||2||$11.38||$22.76||While the ghetto hack involving standard servos + bottle lids works fine, you can actually get servos with actual wheels for cheaper, which should work fine for this project.||1||$12.99||$12.99|
|Wheels||While you will need some sort of wheels to go with the servos mentioned above, these can be assembled from various household objects, such as the bottle lids from some multivitamins (which is what is used below).||2||$0.00||$0.00||With the servos linked above.||0||$0.00||$0.00|
|Body||For this tutorial, we’re using cardboard from a Cup of Soup Six-Pack box to build the robot body. Any other arbitrary piece of sturdy, reasonably light material of similar dimensions could be substituted here.||1||$0.00||$0.00||For a more resilient body, you might purchase a sturdy piece of HDPE. While the exact dimensions might vary, you'll likely want a sheet that is roughly 1/8th of an inch thick, such as this one. The width and length can be cut down to size at your discretion.||1||$7.75||$7.75|
|Castor||This robot has two wheels. Casters (also spelled 'castors') are additional low-friction balance points. They can also be additional (non-powered) wheels. For this project, a caster was built out of the lid of one of these floss containers.||1||$0.00||$0.00||For "real" caster wheels, there are relatively cheap options like this set of four for $6.50.||1||$6.50||$6.50|
The specific model that we’re using here is the Raspberry Pi 3 B+, because that’s what I happened to have on hand. You could use basically any Raspberry Pi model.
Also, while in the process of writing this post, the Raspberry Pi 4 was released; you can find it on the Raspberry Pi website.
|1||$37.95||$37.95||For a robot this basic, the Raspberry Pi 3 B+ is more than excessive. One alternative option is to use a Raspberry Pi Zero, which is designed to be a stripped down, basic version of the Raspberry Pi.||1||$19.99||$19.99|
|"Brain" (Hard Drive)||Raspberry Pi motherboards use SD cards as their hard drives. The easiest option is to purchase an SD card with NOOBS preinstalled, which is an operating system installer designed to work with Raspberry Pis easily out of the box. You can alternatively use another SD card with an OS of your choice installed.||1||$14.40||$14.40||Same SD card recommended as what was actually used (this one). You might be able to get a better deal by purchasing as part of a bundle with a Raspberry Pi + case and power supply.||1||$14.40||$14.40|
|Power Supply (Battery)||A power supply solution for the Raspberry Pi. The easiest power supply solution is to purchase a battery pack that is specifically designed to work with the Raspberry Pi, such as one of these.||1||$25.95||$25.95||Same as actual.||1||$25.95||$25.95|
|Breadboard||See this pack of four (two larger boards and two smaller boards). You can find single boards for sale, but they tend to cost at best marginally ($1-$2) less to get one board instead of four.||1||$8.88||$8.88||Same as actual.||1||$8.88||$8.88|
|Velcro Strips||N/A. Instead used some crime-against-god ghetto hack involving a set of thumbtacks and rubber bands||0||$0.00||$0.00||There are a few parts to this robot (specifically the Raspberry Pi['s case], various batteries, and the breadboard) that you'll want to stay in place without physically screwing, gluing, or otherwise permanently affixing to the robot's body. Adhesive velcro strips are a solid solution here and you can get a bunch of this material for reasonably cheap:||1||$12.72||$12.72|
|Two 470 Ohm Resistors, Two LEDs, and Two 1k Ohm Resistors||A few assorted electronics parts are used in this tutorial. I happen to have already had a box of assorted electronics parts on hand--specifically this set--which is where I grabbed the transistors and LEDs used from.|
If you want a fair amount of flexibility in terms of general fucking around, this is a decent set of parts to pull from as-needed.
|1||$60.48||$60.48||While the box of parts linked in the "actual" column is a fine option, it also has other parts that aren't strictly needed for this project. You could opt to purchase assorted transistors directly:|
The LEDs can technically be skipped, or you can do the same as the resistors and look for a small set of assorted LEDs.
Together, this should probably be under $15 and you'll probably end up with a shit ton of extras of both, unless you find some Chinese company that is willing to ship you three individual transistors and one LED.
|Servo Battery Pack||In addition to the power supply for the Raspberry Pi, you'll want a separate power source for the servos. The one actually used in this article was scrapped from a childrens' toy. Probably just buy one of these.||1||$0.00||$0.00||While you can create your own battery pack, it is easier to acquire a 6V 5-Cell Battery Pack, such as this one.||1||$9.99||$9.99|
|Jumper Wires||To connect the servos to the Raspberry Pi, you'll need a few jumper wires. You can pick up basically infinite of these for extremely cheap in an assorted pack.||1||$5.79||$5.79||Same as actual.||1||$5.79||$5.79|
Footnotes on Raspberry Pis
Raspberry Pis are designed to be small, inexpensive, fully-functional computers. They are a solid "brain" for robots, as in addition to being cheap, they are also lightweight.
While other models besides the ones mentioned in the table above should work, note that you'll probably want to choose a model that has support for WiFi out of the box, as you'll be communicating with the decide remotely. If you do choose a model without WiFi, it can be added through the use of a USB wireless stick.
If you intend to use the Raspberry Pi for other projects, you may also want to pick up a case and a (non-battery-pack) power supply.
Also, you could alternatively use an even lighterweight solution by using a microcontroller like an Arduino rather than a Raspberry Pi, which is a full computer. Conceptually, working with an Arduino is similar; the main difference is that the programming for Arduinos is (essentially) C/C++, whereas programming with a Raspberry Pi is generally in Python.
Miscellaneous Household Supplies
Things that you probably already have:
- Electrical tape. Other tape works fine; electrical tape leaves very little residue on removal. Other types of tape should also work fine. Ended up switching this out for adhesive velcro strips in the final build, which is an even better option.
- Rubber bands. Assist in fastening various parts.
- Assorted screws and/or nuts and bolts. While you shouldn’t need too many of these, a few were used to fasten parts together. If you have literally no screws and/or nuts and bolts, you might pick some up.
Paperclips and thumbtacks were also used, although either of those could be omitted or substituted with other random supplies.
The tools for this project are extremely straightforward; you probably already have these things or suitable alternatives:
- Leatherman or other multitool. Since this project specifically involves a fair amount of ghetto-hacking, a multitool is a useful addition to get everything to fit together. I used a Leatherman fairly extensively for its pliers, for wire cutting/stripping, filing/sanding down rough edges, and so on. The specific model used during this guide (the Leatherman Core) is no longer built, but there are other comparable models that you can pick up if you want to spend more money on a multitool than the rest of this project combined. A random combination of other household tools could suffice instead.
- A small Phillips-head screwdriver. The multitool mentioned above (obviously) contained a screwdriver, but a smaller head was needed for working with the small screws used for servos and other small parts.
- Scissors. Presumably you also own these, unless you fucking break them while trying to cut a plastic bottle in half, which is what I did while writing this.
Assembling the Chassis
Assembling the Chassis (v1)
Once you have the physical parts required for the project, they can be assembled.
Creating Wheels (Optional)
If you have wheels that fit directly into your servo, you can skip this step. Otherwise, you’ll want to:
- Find suitable objects to use as wheels; and
- Then affix them to the servos
One option is to use the lids to jars, bottles, or similar, as shown in the photo below:
You could alternatively cut out wheels from cardboard or another material. The wheels that we’re using here are, realistically, a little smaller than is ideal, leaving the body of the robot almost touching the ground; you might search for something slightly larger. Once you have your wheels, to affix the wheels to the servos, you’ll want to:
- Unscrew the screw that connects the servo horn to the servo (pictured below)
- Rescrew the screw through the wheels you’re using and then back into the servo’s head.
Creating the Body
If you’re ghetto hacking your way to a robot, you can do what we’re doing here, which is to:
- Get some cardboard
- Cut it into a size that seems reasonable; the body shown below is 7.5 inches by 4 inches (approx. 9cm by 10cm)
- Get a second piece of cardboard of the same size and use duct tape, glue, and/or any other reasonable method to combine the two pieces of cardboard for increased stability
- If the cardboard is too bendy, you can also insert some partially-unwound paperclips (or similar) between the two sheets around the weak points to improve sturdiness further
This is pictured below:
If you’re using a sturdier body material, such as HDPE, essentially all you’ll need to do is cut it to a reasonable size.
Affixing Wheels to the Body
If you’re not fucking dumb as hell, you probably have servo mounts that can be used to screw your servos into your body material. If you are dumb as hell, you can:
- Put a circle of electrical tape between the servos and the body; and then
- Affix several rubber bands around the body and servo to secure it further.
Otherwise, you should be able to easily use the screws and mounts that come with your servos to attach them directly to the body.
Since the robot we’re building has two wheels, it will need a third point of contact with the ground that will be able to slide with minimal friction (or a third wheel, if you prefer). For this guide, we’ve taken the lid off of a small container of Glide dental floss and then:
- Used a screwdriver to screw a screw through it into the piece of cardboard
- Pushed a thumbtack through a second point in the lid and into the cardboard (for stability)
- Added a small piece of electrical tape over the edge of the lid that will make contact with the floor, to minimize friction.
The assembly process is pictured below:
And the result is shown in this image:
Basically any round-ish object could be substituted here, such certain jar or bottle lids, assorted pieces of plastic cut in half, and so on. There are also caster solutions that work more completely out of the box, such as the small wheels linked in the parts list.
Assembling the Raspberry Pi
Attaching a Raspberry Pi
Once the body is assembled, the Raspberry Pi will need to be attached somewhere. Ideally toward the center, so that it can easily be connected to the other parts.
- To affix the motherboard to the body, what we’ve done here is use two Q-tips cut in half and then pushed them through the four holes that would normally be used to screw down the motherboard. You could, of course, use actual screws here if you want a more permanent solution (and/or if your body is made of a material that isn’t cardboard).
- Insert your SD card into the Raspberry Pi’s SD card slot. If you’re using an SD card that is not preinstalled with an operating system, make sure to install one (scroll down to “Installing an Operating System to an SD Card”).
- Once the motherboard is in place, don’t plug the servos' header directly into the board’s general-purpose input/output (GPIO) pins on the Rasp. Pi (as shown in the two images below). At the wiring step of the process, the correct way to wire servo headers is discussed.
A top and bottom view of the robot with this process complete is shown here:
And a side view of the robot with the attached Raspberry Pi is shown here:
During this process, we’ve additionally added a few pieces of duct tape and a few additional rubber bands to stabilize the servos and body.
Assembling the Chassis (v2): Higher Quality Materials
At this point, I had to pause this project most of the way through to wait for a few additional parts to ship (specifically, jumper wires). Since this required waiting for Jeff regardless, I also picked up some of the the higher-quality materials recommended in the list of parts from the start of this guide
Previous Steps: Higher Quality Version
Here’s basically the same thing as the sections above, but with the slightly higher quality “recommended” materials. The short version::
- Cut down the 1/8" Thick x 4" Wide x 48" piece of HDPE to a comparable size to the piece of cardboard used originally. Cutting done with Letherman serrated edge blade. Sanded the edge down using the same Leatherman’s file/sanding tool.
- Added two castor wheels to the corners of the body. While there are four screw holes in each of these, the screws that would be closest to the center of the robot were left out to allow for more space to add components on top of the HDPE body.
- Used some velcro strips to attach the various parts to the HDPE body. The use of velcro also allowed for the Raspberry Pi to be placed on the bottom of the body, which was useful here since trying to fit a Raspberry Pi, a breadboard, a power source for the Raspberry Pi and a 6V battery pack for the servos is difficult to do at this body size (and probably would have been extremely ghetto on the original cardboard body)
- Switched out the ghetto wheels with “real” wheels.
The result of these steps is shown in the image below:
Other than those changes, the robot is essentially the same. Some pictures in the following sections jump between the original cardboard body and the higher-quality one shown above, since parts of this guide/article were written out of order. Regardless of the exact materials that you're using for the chassis, the rest of this guide is basically the same.
The Raspberry Pi’s Power Supply
Typically, a Raspberry Pi is powered through a cable plugged directly into a power strip or wall socket. There are a few ways to provide it with mobile power.
- The easiest way is to acquire a mobile power supply/battery pack (ex: this one, which is what I'm using here). You should also be able to use a comparable mobile battery pack with comparable specs, for example if you had an similar battery pack as a mobile phone charger/recharger.
- Alternatively, you could create a custom battery pack setup. Asmentioned by Penguin Tutor, a Raspberry Pi “takes a lot more power than a micro-controller (such as an Arduino), but it's still low enough to consider running it from batteries,” which you can do if you follow that article’s instructions.
Regardless of what you use for the Raspberry Pi's power source, it's probably going to be the heaviest component. The power supply that is being used here is also fairly large.
As shown in the picture above, it sticks over the edge of the HDPE sheet slightly.
The Raspberry Pi: Initial Setup
Setting Up the Raspberry Pi
Turning on the Raspberry Pi
If your battery is already set up and working, great. Otherwise, plug the Raspberry Pi’s power supply into a wall socket and then insert the the micro-USB plug into the Raspberry Pi’s micro-USB port. If you don’t have an “official” power supply,you probably have a suitable micro USB power supply that can be used instead(documentation). Plugging in the Raspberry Pi will also turn it on.
Troubleshooting the Raspberry Pi
If everything works smoothly during the setup process, you can ignore the sections tagged as “[Troubleshooting]” and skip to the next steps.
[Troubleshooting] Fixing the “Rainbow Screen” Error
After completing the step above, I ran into an error where the Raspberry Pi’s red LED would flash. According tothe Embedded Linux Wiki’s documentation, this indicates a problem with the power supply. I plugged a monitor into the device’s HDMI port and a rainbow screen with a lightning bolt appeared on the display (pictured below). As discussed inthis thread, this error also seems to be due to power supply errors. However, switching out the power supply did not in fact solve the problem.
Conveniently, the power supply’s box included the following note:
IMPORTANT NOTE: If you see a rainbow screen and lighting bolt during boot, It means you are using an Incompatible operating system. It is NOT related to the voltage. Ensure you are using “B+” compatible software (NOOBS 2.7.0 or later).
- The Power Supply’s Box
So we’re going to go ahead and reinstall an operating system to the SD card.
[Troubleshooting] Installing NOOBS to an SD Card
Keeping in mind the error above, we’re going to overwrite the SD card with the latest version of NOOBS. To install NOOBS onto an SD card:
- Download the latest version of NOOBS here
- Follow the instructions on this page from the Raspberry Pi documentation to install the file to your SD card
If you want to install a different operating system, the process is roughly identical.
[Troubleshooting] Booting a Raspberry Pi from USB
Unfortunately (part 2), my fucking computer does not have a slot for SD or micro SD cards and I don’t haveone of these cocksuckerseither. Fortunately, it turns out you can just fucking boot from USB by following the process coveredin the official documentation. LMAO, as they say. Except that’s actually more of a pain in the ass than just switching out this Raspberry Pi with a different one that I already had set up and running for a different project; JK LOL, that’s actually what happened here, not that it matters to you.
[Troubleshooting] Switching Out the Raspberry Pi
Since it happened to be easier here than updating the operating system on the micro SD card, we’re switching out the initially used Raspberry Pi (which was a Raspberry Pi 3 Model B+) with a Raspberry Pi 2 Model B V1.1. Changes made here were to:
- Added a case to the Raspberry Pi;
- Tilt the device diagonally to provide easier access to ports;
- Use several thumbtacks to create a slot to insert the Raspberry Pi, as well as a rubber band over the top of the device; and
- Add a Panda Wireless PAUO5 USB wireless adaptor, since the Raspberry Pi 2 has no built-in WiFi
The robot with the switched out device can be seen in this image:
This setup is roughly identical.
More Setup: How to Set up a Raspberry Pi (Without a Monitor)
Anyway, now that your Raspberry Pi fucking works, it’s time to SSH into it “headless” as they say. Or possibly no one says that in this context. IDK LOL. Anyway, normally, if you wanted to work on the Raspberry Pi directly, you would need:
- An HDMI-compatible monitor and cord
- A USB mouse; and
- A USB keyboard
You would connect all three of these into the Raspberry Pi, which would allow you to use the Raspberry Pi like a “normal” computer. You plug in those peripherals instead if for whatever reason you run into errors with connecting by SSH (see below) and are troubleshooting.
Connecting to a Raspberry Pi via SSH
Since we’re building a robot, it is impractical to attempt to wire the Raspberry Pi directly into a computer monitor. Instead, we’ll set up the Raspberry Pi so that we can useSSH(Raspberry Pi documentation) to connect to it remotely from another machine. Incidentally, this is why (as mentioned in the list of parts) you’re going to want a Raspberry Pi that has built in wireless support. To set up the Raspberry Pi for SSH:
- Power on the Raspberry Pi by plugging in the power supply. You should see a solid red LED; reference this wiki article on the Raspberry Pi LED statusesfor more information.
- Connect the Raspberry Pi to the same wireless Internet network as the computer that you want to SSH into it from. If necessary, the easiest way to connect the Raspberry Pi to your local WiFi network may be to briefly plug the Rasp. Pi directly into a keyboard and monitor. Alternatively, it should be possible to use an ethernet cord to directly wire the Raspberry Pi into your main computer so that you can do this initial setup via SSH without peripherals.
- Once the device is connected to the WiFi, use Nmap to detect the local IP address of the Raspberry Pi. If you don’t already have Nmap installed, install it. Then run
nmap -sP 192.168.1.1/24from the terminal on your local machine (not the Raspberry Pi). You’ll get a result that looks like the screenshot below:
- From the Nmap result, you should see a number of IP addresses for the devices connected to your local WiFi network. If it is not immediately apparent which IP address is associated with the Raspberry Pi, there are a few ways to identify it:
- Run the command “
hostname -I” locally on the Raspberry Pi to list the device’s IP address; and/or
- Run the Nmap command with the Raspberry Pi turned off or disconnected from the WiFi, then run it again with it connected; the new device is the one that you want.
- Run the command “
- If an IP address for the Raspberry Pi is not able to be found through any of these methods, make sure that Raspberry Pi is turned on, double check that it is a model that has built-in WiFi (or that you have a wireless card attached), and make sure it is connected to the same wireless network as the computer you’re using to SSH into it from.
- Once you’ve identified the IP address, you can SSH into the Raspberry Pi. This command will look something along the lines of “
ssh firstname.lastname@example.org”; replace with your IP address. You’ll also be prompted to insert the Raspberry Pi’s password. Note that, by default, these are the account credentials:
Assuming everything went correctly, you should now be at the point shown in the terminal screenshot above. Otherwise,fuck around some more until you get it right. Note that it is possible that the connection IP address will change; if you're able to connect fine but later get an error like this:
$ ssh email@example.com
ssh: connect to host 184.108.40.206 port 22: Connection timed out
Double check that the Raspberry Pi is still located at the same IP address.
Raspberry Pi Terminal, Programming, and Circuitry Overview
This entire section “Raspberry Pi Terminal, Programming, and Circuitry Overview” consists of background and context; if you already know the basics of how to use a Raspberry Pi, the Linux Terminal, and basic GPIO pin usage, you can skip this section.
Using the Terminal
Linux Terminal Crash Course
Since we’re connected to the Raspberry Pi via SSH, we have access to the operating system’s files, but without a graphical user interface. You can think of what you’re seeing as being similar to a text-based version of your file manager. Some basic commands you can type are:
pwd- Print out the (file) path to where you are currently located in the system’s directory (folder) structure
ls- List all files in the current directory
cd Downloads- Navigate into the directory named “Downloads”
cd ..- Navigate one level back up into the parent directory (e.g., if you’re in /home/Downloads, this will move you back to /home
nano file.txt- Open a file called “file.txt” into the text editor known as “Nano” (if file does not exist, it will create it)
These commands should cover basically everything you’ll need to do for this project. If you want to learn more about the Linux terminal,this Linux video courseis a good place to start.
Using the Raspberry Pi's GPIO with Python
Writing a “Hello World” Test
To control the robot, we’ll need to write a Python script. To do this:
- Type “nano robot.py” into the terminal and press enter
- Type or copy-paste the following line of code into the file:
print "Hello World"
- Save and exit the file
- Type “
python robot.py” into the terminal and press enter.
Assuming you managed to not fuck up, you should see a result that looks like the following:
$ pi@raspberrypi:~/robot $ python robot.py
Which verifies to us that Python is set up and working correctly.
How Raspberry Pi’s GPIO Works
There are (basically) four types of Raspberry Pi pins:
- 5V. Pins connected directly to the Raspberry Pi’s power source (in our case, a battery), which “will capably provide the full current of your mains adaptor, less that used by the Pi itself” [source].
- 3v3. Power supply pins that can supply less power than the 5V pins [more]. See this thread for more on the differences between these pins and GPIO pins.
- GND. Ground pins for grounding circuits.
- GPIO. The rest of the pins are general purpose input/output pins. While they can all be used as arbitrary input/output pins, some of these pins have specific additional specialized uses. More details are covered in this StackExchange thread.
Note that (as mentioned onthis page) you can use the command “
pinout” from the Raspberry Pi terminal as a reference for pins and to view the exact layout for the Raspberry Pi that you’re using. When run on the device that I’m using (Raspberry Pi 2 Model B V1.1), the putout of the
pinoutcommand is as shown below:
As indicated at the bottom of the screenshot, also seepinout.xyz.
Note that incorrect usage of the Raspberry Pi’s GPIO pins can potentially damage or destroy your device, so don’t fucking do that.
Raspberry Pi GPIO “Hello World” (Controlling an LED)
For the robot to work, your Python script will need to be able to interact with the device’s GPIO pins. The easiest way to do this is to use thegpiozerolibrary. If not already installed, run the following command:
sudo apt-get install python-rpi.gpio
Then, delete the contents of robot.py and replace them with the following:
# Import the main Python library used for GPIO interactions import RPi.GPIO as GPIO # Helper libraries import time import random # Specify how you are referring to pin numbers. See this thread: # https://raspberrypi.stackexchange.com/questions/12966/what-is-the-difference-between-board-and-bcm-for-gpio-pin-numbering GPIO.setmode(GPIO.BOARD) # Before a GPIO pin can be used, you must set it up. # Here, we are specifying that pin #7 will be used for output GPIO.setup(7,GPIO.OUT) for x in range(0,10): # Print a debugging message to the terminal print "LED on" # Send power from pin #7 (turns on the LED) GPIO.output(7, True) # Wait for a random amount of time between 0.2-1 seconds # You could also just use "time.sleep(1)" time.sleep( random.uniform(0.2, 1) ) # Print debugging statement and turn LED off print "LED off" GPIO.output(7,False) # Wait 0.2-1 seconds before continuing time.sleep( random.uniform(0.2, 1) ) # Un-set-up the GPIO pin and other settings at the end of the script # Otherwise, you can run into errors or warnings when running future scripts # You should/"should" have this in an "try/except" block so that it will # run even if the program crashes GPIO.cleanup()
Before running this script, proceed with the following steps to set up the wiring. If you want another example, this video is a useful resource.
Overview of Circuitry Concepts
To interact with the various hardware components, some basic circuitry will need to be set up.
How Breadboards Work
Before moving onto the hardware setup, consider how a breadboard works. In a breadboard, there will be a number of sets of rows and columns.
- Each of the rows on a breadboard are connected (e.g., plugging a wire into hole 1A and then plugging a resistor into hole 1B, 1C, 1D, or 1E would connect the wire and resistor)
- The full columns on the sides of the breadboard are also connected. While you can use those columns the same as the rows, by convention:
- The positive (+) columns on the side of a breadboard are generally used to connect power to the breadboard.
- The negative (-) columns, also on the side of the breadboard, are generally used for grounding
For another image showing how these rows/columns connect, look at the photo inthis article by W3Schools. Or look at the image below:
With this in mind, breadboards can then be used to easily test connections without soldering components together.
Calculating Resistor Values and Identifying Resistors
Note that, while you can create a circuit without a resistor, this will generally result in too much power being supplied to your component. For example, your LED can literally catch on fire. The circuit shown above uses a 470 Ohm resistor to prevent this. While you can use the resistor values mentioned in this guide (470 Ohms and 1k Ohms) without getting into the fine details as to why these values are chosen, it is helpful to understand the relatively simple math behind choosing a resistor.
To determine the exact resistor value to use, first look up these two values:
- The voltage of your power source. For example, if you're using a 9V battery, this would be 9 volts.
- The specified current for your LED (or other device). For most LEDs, this should be around 20mA, which is equivalent to 0.02A.
Then, plug them into this equation:
Resistor Value = Your Voltage / Specified Amps
With a 9V battery, this is:
- Resistor Value = 9V / 0.02A
- Resistor Value = 450 Ohms (which means we want a roughly 450 Ohm resistor)
This formula is Ohm’s Law and is generally written as:
I = V/R
You can also cheat and plug the voltage and specified current into this calculator (or use a “fuller” Ohm’s Law calculator) to determine the correct resistor value:
The resistor value does not necessarily have to be perfect; in fact, it probably won't be, since unless you go out of your way to find a perfect fit, you're probably going to have a resistor that fits somewhere along the standard resistor values table. If your resistor is stronger than necessary, the LEDs may be dimmer, but should still light up. However, if your resistor is too weak, you may damage or destroy your LED (or other components). Incidentally, this is why a 9V battery was used for the calculations here even though the voltage for the actual robot is lower (the battery pack is 6V and the Raspberry Pi provides 5V or 3.3V).
Most resistors are labeled through the use of four color-coded bands:
- 1st Band: The first digit of the resistance value
- 2nd Band: The second digit of the resistance value
- 3rd Band: The number to multiply the two digits by
- 4th Band: The resistor’s tolerance
The band colors correspond to a standard resistor color code chart. You can find a copy of this in this PDF. For a 470 Ohm resistor (which is what we're using), the math is as follows:
1st Band: Yellow = 4
2nd Band: Violet = 7
3rd Band: Brown = x10
4th Band: Gold = +/- 5%
- 47*10 = 470
- Which makes this a 470 Ohm resistor with a tolerance of plus or minus 5 percent.
This video guide on resistors is a decent explanation of how to read resistors, as well as other resistor basics.
Setting Up the Wiring
With this in mind, you can now set up the wiring, LED, and resistor:
- To light up an LED, three breadboard rows will be needed:
- In the first row/column, attach one end of the 470 Ohm resistor (or comparable) and the longer (anode/positive) end of the LED
- In the second row/column, attach the shorter (cathode/negative) end of the LED and the male end of one male-female jumper wire. This wire will be the ground wire; by convention, black is a common color for a jumper wire being used as a ground wire, but the color does not actually matter.
- In the third row/column, plug in the male end of another male-to-female jumper wire (this will be the positive wire, which is commonly red) and the other end of the resistor.
- On the Raspberry Pi, plug the ground wire into a ground pin (we’re using pin #6)
- On the Raspberry Pi, plug the positive wire into a GPIO pin (we’re using pin #7)
The image below shows the configuration of this wiring with two angles of the breadboard and a photo of the two wires plugging into the Raspberry Pi:
And then run the command “
sudo python robot.py” to run the script that was setup under "Raspberry Pi GPIO “Hello World” (Controlling an LED)." Assuming everything worked correctly, you should see a result along these lines:
This verifies that the device is able to correctly detect and interact with the GPIO pins and their attached LED.
Batteries and Power Sources
Powering Peripherals via Raspberry Pi vs. External/Separate Power Sources
There are two ways to power LEDs, servos, and basically anything from a Raspberry Pi:
- Power them directly from the Raspberry Pi
- Power Supply --> Rasp. Pi --> 5V GPIO pin --> jumper wire --> breadboard
- Use a separate battery pack/power source for the servos
- Battery Pack --> jumper wire --> breadboard; AND
- Power Supply --> Rasp. Pi
While the first option is hypothetically easier, there is a finite amount of power that can be supplied by the Raspberry Pi and attempting to pull too much power can cause the device to reset and potentially damage itself. While LEDs don't exactly require that much power, other peripherals (such as servos) can be more power intensive. Even devices that don't require that much power overall can in some cases require spikes of power, which can be more than the Raspberry Pi can provide directly. Because of this, using separate power sources for peripherals tends to be a good idea. Of course, while using a separate power source is “good practice,” you can alsodo whatever you wantprovided that youknow what you’re doing.
6V AA Battery Holder Packs
How AA Battery Packs Work
As you know, AA batteries provide voltage that can be used as a power source. To be more specific:
The nominal output voltage* of single-use AA batteries is 1.5 volts, while rechargeable batteries have a nominal voltage of 1.2V. The voltage of a AA battery is the same as a AAA battery, C cell or D cell. AA batteries, however, provide power for a longer period than AAA batteries, because their larger size allows them to store more electrolyte. C and D cells, being larger still, can be expected to last longer again.
- Encyc, Article on AA Batteries (emphasis added)
*"Nominal voltage" meaning that while the labeled voltage is 1.5V, it may fluctuate to some extent (particularly based on how much charge is remaining)
An AA battery has a voltage of 1.5V or 1.2V (depending on whether it is rechargeable or not). If you could somehow magically combine five rechargeable AA batteries or four standard AA batteries, you could have a voltage of 6V, which is what we're looking for. Conveniently, you can do that by creating a battery bank that allows these four or five batteries to run in series. Incidentally, this is what a 6V AA battery holder pack (e.g., these) does.
Creating or Harvesting a 6V Battery Holder
If you already have a 6V 5-cell battery pack (often sold as “6V RC Battery Packs” or similar), then you can skip this step. And you probably should, since the next step is a Fucking Bullshit Crime Against God. Anyway, two potential options for creating a 6V 5-cell battery pack are to:
- Build one with a quality hack, similarly to what is shown in this YouTube video. For more information on building your own battery packs, this document by Inland Hobby and this forum thread are good resource. Or:
- Go to your local Target to see if they sell these mother fuckers, find out that they don’t, then just buy some fucking childrens’ RC car sold for $9.99, since it has a 6V battery pack adapter that can be harvested
I went with the second option, since that was easier than finding another store. See the image below:
The basic process of harvesting the battery pack and converting it to a usable format was:
- Remove the part of the battery pack that the actual batteries go into
- Start unscrewing everything to get to the other half of the battery pack and its wires
- Cut the ends of the wires off that are soldered to the RC car’s microprocessor
- Put all the other random parts somewhere else, since they aren’t needed
- Strip the ends of the wires coming out of the battery pack
- Strip a few jumper wires and twist (or solder) them onto the wires coming out of the battery pack.
The end result of this is a functional 6V AA battery holder.
Plausible Alternative: Using a D Battery (9-Volt)
Another potential power source is to use a 9-volt battery as a power source. The image below shows a basic diagram of how to make a circuit to power an LED using a D battery:
The basic process is straightforward; basically all you need to do here is strip a jumper wire and touch the heads to the positive and negative sides of the battery to create a circuit. As shown in the image, there are also 9V battery clip connectors that make this process easier.
Adding Power Lights
While working with circuitry and/or Raspberry Pi projects in general, it is important to be able to determine whether problems that occur are due to your circuitry or whether they are problems with your code. One useful trick is to add a few LEDs as status indicators to determine whether or not power is flowing correctly.
Battery Pack Power Light (Red LED)
To make sure that the 6V battery pack is connected and providing power, adding an LED as a power indicator is one easy option. This is shown in the image below:
Note that this circuit should complete and light up when the 6V battery pack is connected, even if the Raspberry Pi is turned off. For more information on setting up this kind of basic LED circuit, scroll up to the section on basic circuits and LEDs.
"Program is Running" Light (Green LED)
Next, let's set up a green LED that will light when the robot.py script is running. To do this:
- Plug a wire into one of the Raspbery Pi's ground pins (use pinout) to find these, if needed. We're using pin #6. This will be a ground wire, so we're using black.
- Plug a wire into one of the Raspberry Pi's GPIO pins. We're using pin #10. Since this is a positive wire, we're using a red wire here.
- Take the ground wire that you've just plugged into the Raspberry Pi and plug it into the same column as your other ground wires for the battery pack red LED setup above.
- Take the active wire and plug it into an arbitrary (empty) row.
- Put one end of a 470 Ohm resistor into the same row as the active wire in the step above
- Put the other end of the resistor into the same row as the positive end of the green LED
The result of this is shown in the image below:
Note that this LED is set up to use the same ground wire as the red LED that was set up previously. While the LED could have its own ground wire, this setup is slightly simpler. Now that the circuitry is set up, we can write the following script:
# The main library used to work with Raspbery Pi GPIO pins import RPi.GPIO as GPIO # Helper libraries import time GPIO.setmode(GPIO.BOARD) # This is the GPIO pin being used to power the green LED GPIO.setup(10,GPIO.OUT) try: # Turn on an LED while the script is looping print "LED on" GPIO.output(10, True) # Main program loop would go here while True: print '...' time.sleep(0.25) # If/when CTRL+C is pressed, execute this code to cleanup the connections, # which will also turn off the green LED except KeyboardInterrupt: GPIO.cleanup()
Saving the script and running it with "
sudo python filename.py" will turn on the LED, then sit in an infinite loop until
CTRL+C is pressed at which point the script will end and the LED will turn off.
With the basic outline of a script and the basic wiring set up above, we can expand on this to allow for the servos to be controlled.
If applicable, modify your servos so that they can continuously rotate 360 degrees, out-of-the-box servos generally only rotate 180 degrees. See this guide, if this applies to you.
Identifying Servo Wires
Your servos should have a set of three female wires coming out of them. Regardless of the exact colors, these wires should be:
- A signal wire (generally yellow or orange);
- A positive wire (in our case, red); and
- A ground wire (generally black or brown)
You can also referencethis videofor more context. Check your specific servo model’s documentation, if you’re using something different.
Connecting a Servo to a Raspberry Pi
To wire a servo to a Raspberry Pi:
- Get three male-to-male jumper wires (ideally the same color as the servo’s wires) and plug them into the servo’s female connectors)
- Next, connect these three wires into your breadboard:
- Put the ground wire (black here) into the ground bus
- Put the positive wire (red here) into the power bus
- Put the signal wire (yellow here) into an arbitrary row
- Connect a power supply to the breadboard's power bus (if you haven't already done this earlier)
- Add a 1k Ohm resistor (band colors are brown --> black --> red --> gold) to the breadboard. Put one side of the resistor into the same row as your servo’s signal wire; put the other end of the resistor into some other arbitrary row.
- Plug another wire into an arbitrary GPIO pin on the Raspberry Pi. We're using pin #7 (and pin #8 when repeating this process for the second servo).
- Plug the male end of the wire plugged into the Raspberry Pi in the step above into the same row as the other end of the resistor mentioned earlier.
Since we’re wiring two servos, repeat this process with the second servo. Once these wires are set up, you should have a setup that looks similar to the image below:
You can also referencethis videoto clarify this process further.
Controlling Servos with a Raspberry Pi
Now that the servo wiring is complete, it’s time to write the code that will allow the robot to actually function and move. See the code below:
# The main library used to work with Raspbery Pi GPIO pins import RPi.GPIO as GPIO # Helper libraries import time GPIO.setmode(GPIO.BOARD) # This is the GPIO pin being used to power the green LED GPIO.setup(10,GPIO.OUT) # This is the GPIO pin to control the wheel on the right side (closer to the 6V battery pack) rp = 7 GPIO.setup(rp, GPIO.OUT) # This is the GPIO pin to control the wheel on the left side (closer to the Raspberry Pi power supply) lp = 8 GPIO.setup(lp, GPIO.OUT) # p is the GPIO pin number # Also see: https://rpi.science.uoit.ca/lab/servo/ def test_wheel(p): p = GPIO.PWM(p, 50) p.start(7.5) # Forward for right; backward for left print "Turning towards 90 degree" p.ChangeDutyCycle(7.5) time.sleep(1) # sleep 1 second # Backward for right; forward for left print "Turning towards 0 degree" p.ChangeDutyCycle(2.5) time.sleep(1) # sleep 1 second # [Also] forward for right; backward for left print "Turning towards 180 degree" p.ChangeDutyCycle(12.5) time.sleep(1) # sleep 1 second p.stop() try: # Turn on an LED while the script is on GPIO.output(10, True) while True: test_wheel(rp) test_wheel(lp) except KeyboardInterrupt: GPIO.cleanup()
This script will test both wheels until CTRL+C is pressed to stop the script. There is also a video here that is another good introductory resource to working with servos with a Raspberry Pi.
The Final Build
The Full Script to Control the Robot
With these general concepts in mind, we can now write the code to operate the robot. This code is below and is explained via comments:
# The main library used to work with Raspbery Pi GPIO pins import RPi.GPIO as GPIO # Helper libraries import time import random import curses GPIO.setmode(GPIO.BOARD) # This is the GPIO pin being used to power the green LED GPIO.setup(10,GPIO.OUT) # This is the GPIO pin to control the wheel on the right side (closer to the 6V battery pack) rp = 7 GPIO.setup(rp, GPIO.OUT) # This is the GPIO pin to control the wheel on the left side (closer to the Raspberry Pi power supply) lp = 8 GPIO.setup(lp, GPIO.OUT) # This "should"/should be replaced with a real event handling loop # https://stackoverflow.com/questions/3523174/raw-input-in-python-without-pressing-enter def get_input_without_enter(message): try: win = curses.initscr() win.addstr(0, 0, message) while True: ch = win.getch() if ch in range(32, 127): break time.sleep(0.05) except: raise finally: curses.endwin() return chr(ch) # lp is the left wheel's GPIO pin number # rp is the left wheel's GPIO pin number # 7.5 dc is forward for right; backward for left # 2.5 dc is backward for right; forward for left def move(lp, l_dc, rp, r_dc): if (lp > 0): l = GPIO.PWM(lp, 50) l.start(7.5) l.ChangeDutyCycle(l_dc) if (rp > 0): r = GPIO.PWM(rp, 50) r.start(7.5) r.ChangeDutyCycle(r_dc) # The amount of time the robot will move for with the specified movement/wheel settings time.sleep(0.05) if (lp > 0): l.stop() if (rp > 0): r.stop() try: # Turn on an LED while the script is looping print "LED on" GPIO.output(10, True) while True: print '...' input_char = get_input_without_enter("...") if input_char.upper() == 'W': move(lp, 2.5, rp, 7.5) # forwards elif input_char.upper() == 'A': move(lp, 2.5, 0, -1) # left elif input_char.upper() == 'S': move(lp, 7.5, rp, 2.5) # backwards elif input_char.upper() == 'D': move( 0, -1, rp, 7.5) # ) right else: print "Waiting..." except KeyboardInterrupt: GPIO.cleanup()
You can fuck around with this code, if that’s something that you want to do. Or, you can copy-paste it directly into your
robot.py file as-is and save it, then move on to the next step.
Now that the parts and programming are assembled, this robot can be run. To do this:
- Run the command “
sudo python robot.py” from an SSH session to the Raspberry Pi’s terminal
- To control the robot, use
- To end operation of the robot, press
While the script is running, you can use the arrow keys on your keyboard to control the robot’s wheels. The final result looks something along the lines of what is seen in the video below:
Refining the Robot
While the Quality Robot works as intended, at this point there are a number of potential improvements that could be made. These include, but are not limited to:
- Improving the durability and stability of the robot in general. If this thing fell down a flight of stairs, parts would definitely fall off on impact. The HDPE sheet used for the body is fairly thin; a thicker sheet might improve stability. Alternatively, adding a second “floor” with another layer of the same thickness could improve stability while also adding more space to store components or wires.
- Improving the main loop in the robot.py script. A real event handling loop should be used here..
- Improving the wheel alignment. As shown in the video, the robot's movement is not fully straight.
- Adding additional functionality beyond simple movement.
- Duct taping a gun to the robot.
If you build this robot or similar and make any of these updates, feel free to post in the comments. Or, perhaps they will be covered in future articles, like this article on how to add a seven-segment display to this robot to display various status codes.
Anyway, that’s how you can make a nice robot. What an epic win. I’m literally dabbing on the haters right now.
- 7 Internet Marketing/SEO Tricks from the Slack Chat
- [Video] 28+ Methods to Make Money Online: The Ultimate Tier List from S-Tier through F-Tier
- [Raspberry Pi] How to Add a Seven-Segment Display to a Robot
- [Raspberry Pi] How to Build a Robot: A Step-by-Step Guide for Beginners
- [Video] How to do Competitor Analysis for Internet Marketing
- [Video] The Ultimate Offpage SEO Tier List: 28+ Link Building Methods Ranked from S through F (and a Few Other...
- [BST - FH] 256 Kilobytes Web Development Sales Thread
- 5 Tasks You Didn't Know Could be Done from the Developer Console
- The Complete Guide to Discord Text Formatting, Syntax Highlighting, and Tricks for Adding Colors
- How to Parse a User Agent in PHP with Minimal Effort
August Garcia is some guy who used to sell Viagra on the Internet. He made this website to LARP as a sysadmin while posting about garbage like user-agent spoofing, spintax, the only good keyboard, virtual assitants from Pakistan, links with the rel="nofollow" attribute, proxies, sin, the developer console, literally every link building method, and other junk.
> Adding additional functionality beyond simple movement.
> Duct taping a gun to the robot.
Me and Scuffed Dog have inspiration for the 256kb robot.
Robot Andy streams (and his friends) stream here:
They have a web cam and people can control them through a web interface for a small $ fee. They can talk and robot andy 2.0 even fucked 2 girls on pornhub (search "robot andy").
The first robot andy was a savage, he lived with Ice Poseidon (a former popular YouTuber) and he would be on 24/7 in his apartment. Eventually viewers turned up and duck taped weapons to robot andy and started doing this.
Robot Andy was then replaced with Robot Andy 2.0, who had arms that viewers could control, he was much taller and stronger.
On day 1 of Robot Andy 2.0 viewers worked out they could turn on Ice Poseidons stove.
Another fun game was knocking expensive things off desks like monitors and laptops.
Eventually Ice Poseidon ended up crying to Robot Andy and then the FBI took him away.
The world needs another Robot Andy.
"THAT DOG IS GETTING RAPED" - Terry A. Davis
Anyone reading this article who is interested in similar things, check out this website by Ben Eater and his associated YouTube channel. Includes various videos on similar topics, such as circuitry, electonics, and programming. Most notably, there is a "build an 8-bit computer from scratch" series, which is high quality.
Sir, I can do you a nice SEO.
Post a New Comment
Do you like having a good time?
Register an Account
Read Quality Articles
Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.
Argue with People on the Internet
Use your account to explain why people are wrong on the Internet forum.
Vandalize the Wiki
Or don't. I'm not your dad.
Ask and/or Answer Questions
If someone asks a terrible question, post a LMGTFY link.
Make Some Money
Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.