Robotics at Home with Raspberry Pi Pico - Danny Staple - E-Book

Robotics at Home with Raspberry Pi Pico E-Book

Danny Staple

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

The field of robotics is expanding, and this is the perfect time to learn how to create robots at home for different purposes. This book will help you take your first steps in planning, building, and programming a robot with Raspberry Pi Pico, an impressive controller bursting with I/O capabilities. After a quick tour of Pico, you’ll begin designing a robot chassis in 3D CAD. With easy-to-follow instructions, shopping lists, and plans, you’ll start building the robot. Further, you’ll add simple sensors and outputs to extend the robot, reinforce your design skills, and build your knowledge in programming with CircuitPython. You’ll also learn about interactions with electronics, standard robotics algorithms, and the discipline and process for building robots. Moving forward, you’ll learn how to add more complicated sensors and robotic behaviors, with increasing complexity levels, giving you hands-on experience. You’ll learn about Raspberry Pi Pico’s excellent features, such as PIO, adding capabilities such as avoiding walls, detecting movement, and compass headings. You’ll combine these with Bluetooth BLE for seeing sensor data and remotely controlling your robot with a smartphone. Finally, you’ll program the robot to find its location in an arena.
By the end of this book, you’ll have built a robot at home, and be well equipped to build more with different levels of complexity.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 450

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Robotics at Home with Raspberry Pi Pico

Build autonomous robots with the versatile low-cost Raspberry Pi Pico controller and Python

Danny Staple

BIRMINGHAM—MUMBAI

Robotics at Home with Raspberry Pi Pico

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rahul Nair

Publishing Product Manager: Rahul Nair

Content Development Editor: Sujata Tripathi

Technical Editor: Rajat Sharma

Copy Editor: Safis Editing

Project Coordinator: Sean Lobo

Proofreader: Safis Editing

Indexer: Pratik Shirodkar

Production Designer: Nilesh Mohite

Senior Marketing Coordinator: Nimisha Dua

Marketing Coordinator: Gaurav Christian

First published: March 2023

Production reference: 1170223

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80324-607-9

www.packtpub.com

To my amazing wife, Carol, who has supported all my robotics experiments with love, inspiration, and tolerance of a living room filled with robots. To my children, Helena and Jonathan, for all their ideas and enthusiasm and for encouraging me to take a break and play with them sometimes!

– Danny Staple

Contributors

About the author

Danny Staple is a robot builder and programmer. He has been a professional software engineer since 2000, uses Python professionally, and regularly contributes to open source projects.

Danny has been building robots at home since 2004 and has a cupboard full of projects, including robots with wheels, cameras, tank tracks, legs, and arms, made from plastic, cardboard, metal, kits, lunchboxes, and modified toys.

Danny authored Learn Robotics Programming, published in 2021 by Packt Publishing, and has written magazine articles for The MagPi. He runs the robotics YouTube channel Orionrobots and brings his robots to events such as Pi Wars and Arduino Day. Danny also mentors at CoderDojo KU, where he shows kids how to program in Python and has run Lego robotics clubs.

I would like to thank the Pi Wars and Adafruit communities for answering my tricky questions, Mike Moncrieffe for checking diagrams for me, and my review team for the great feedback throughout this book.

About the reviewer

Leo White is a professional software engineer and a graduate of the University of Kent. His interests include electronics, 3D printing, and robotics. He first started programming on the Commodore 64 and later wrote several applications for the Acorn Archimedes. He currently programs set-top boxes for his day job. Utilizing the Raspberry Pi as a foundation, he has mechanized children’s toys and driven robot arms, blogging about his experiences and processes along the way. He has given presentations at Raspberry Jams and entered a variety of robots in the Pi Wars competition.

Table of Contents

Preface

Part 1: The Basics – Preparing for Robotics with Raspberry Pi Pico

1

Planning a Robot with Raspberry Pi Pico

Technical requirements

What is Raspberry Pi Pico, and why is it suitable for robotics?

A microcontroller that runs Python

Raspberry Pi Pico’s interfaces for sensors and devices

What is CircuitPython?

Planning a Raspberry Pi Pico robot

An overview of robot planning

A note on trade-offs

Choosing a robot chassis

Choosing the power systems

Pin usage

Test fitting a Raspberry Pi Pico robot

Creating your first test-fit part

Motors

Power systems

Creating a rough chassis

Arranging the test-fit parts

A recommended shopping list for robot basics

Robot parts and where to find them

The robot workshop and makerspaces

Summary

Exercises

Further reading

2

Preparing Raspberry Pi Pico

Technical requirements

Getting CircuitPython onto Raspberry Pi Pico

Preparing the CircuitPython library for Pico

Coding on Pico – first steps

Downloading the Mu editor

Lighting the Pico LED with CircuitPython

Blinking the LED with code

Soldering headers to Raspberry Pi Pico

Summary

Exercises

Further reading

3

Designing a Robot Chassis in FreeCAD

Technical requirements

Introducing FreeCAD

The FreeCAD screen

Selecting workbenches

FreeCAD settings

Making robot chassis sketches in FreeCAD

Preparing the document

Sketching the chassis outline

Creating the upper parts main sketch

Sketching the motor holes

Designing the caster placement

Modeling chassis parts from sketches

Modeling the chassis plate

Modeling the other parts

Troubleshooting the model

Modeling the caster in 3D

Making FreeCAD technical drawings

Setting up the page

Adding parts to the drawing

Preparing the drawing for print

Summary

Exercises

Further reading

4

Building a Robot around Pico

Technical requirements

Cutting styrene parts

Transferring CAD measurements to a plastic sheet

Cutting the plastic sheet

Finishing and sanding the chassis plate

Assembling a robot chassis

Attaching the caster and battery box

Attaching the motors and wheels

Wiring a Raspberry Pi Pico robot

Wiring Pico and the motor controller into the breadboard

Adding the batteries

Wiring in the motors and encoders

Powering the robot up

Summary

Exercises

Further reading

5

Driving Motors with Raspberry Pi Pico

Technical requirements

Driving forward and back

Testing each motor with CircuitPython

Driving wheels in a straight line

Steering with two motors

An introduction to pulse width modulation speed control

Driving fast and slow

Turning while moving

Driving along a planned path

Putting line and turn moves together

The flaw with driving this way

Summary

Exercises

Further reading

Part 2: Interfacing Raspberry Pi Pico with Simple Sensors and Outputs

6

Measuring Movement with Encoders on Raspberry Pi Pico

Technical requirements

About encoders and odometry

Absolute and relative sensing

Types of encoders

Encoder pulse data

Wiring in encoders on a Raspberry Pi Pico robot

Examining the motors

Examining the wiring

Programming Raspberry Pi Pico PIO

Introduction to PIO programming

Introducing PIOASM

Detecting input with PIO

PIO instructions and registers

Making a counter with PIO

Measuring encoder count for movement

Making a simple PIO change detection loop

Making a bidirectional counter with PIO

Making reusable encoder code

Measure counts for a known time

Summary

Exercises

Further reading

7

Planning and Shopping for More Devices

Technical requirements

Introducing sensors

Analog sensor types

Timed pulses

Data bus sensors

The robot block diagram

Choosing device types

Distance sensors

Inertial measurement unit

Bluetooth devices

Device pin usage summary

Planning what to add and where

Bluetooth and IMU mounting plan

Distance sensor mounting plan

Shopping list – parts and where to find them

Preparing the robot

Designing the shelf

Cutting the shelf

Designing the front sensor brackets

Cutting the sensor brackets

Preparing the chassis plate

Assembling the robot

Summary

Exercises

Further reading

8

Sensing Distances to Detect Objects with Pico

Technical requirements

How distance sensing works

Soldering headers and attaching them to the robot

Soldering headers

Mounting the sensors

Introduction to I2C communication

Communicating with a single distance sensor

Wiring the distance sensors

VL53LX theory of operation

Reading a single distance sensor in CircuitPython

Troubleshooting

Connecting two distance sensors

Troubleshooting

Building a wall avoider with Raspberry Pi Pico

Preparing the robot library

Wall-avoiding theory of operation

Distance sensor wall avoider code

Troubleshooting

Summary

Exercises

Additional reading

9

Teleoperating a Raspberry Pi Pico Robot with Bluetooth LE

Technical requirements

Wireless robot connection options

Connecting Bluetooth LE to Raspberry Pi Pico

Attaching the Bluetooth module to the robot

Wiring the Bluetooth breakout to Raspberry Pi Pico

Connecting to the Bluefruit LE device with UART

Connecting a smartphone

Troubleshooting the Bluefruit module

Getting sensor data over Bluetooth LE on Raspberry Pi Pico

Graphing the data

Controlling the robot with Bluetooth LE

Printing what we got

Button control mode

Decoding button control packets to drive the robot

Troubleshooting

Summary

Exercises

Further reading

Part 3: Adding More Robotic Behaviors to Raspberry Pi Pico

10

Using the PID Algorithm to Follow Walls

Technical requirements

Introducing the PID algorithm

Control and feedback

Bang-bang control

Distance sensing with proportional control

Troubleshooting

Using the integral to handle small distances

Dealing with oscillations using the derivative

Using PID to follow a wall

Changing the sensor’s placement

Wall-following code

Troubleshooting

PID tuning – using graphs to tune the PID

Controlling motor speed

The proportional component

Adjusting the derivative gain

Tuning the integral

Closing notes on tuning

Summary

Exercises

Further reading

11

Controlling Motion with Encoders on Raspberry Pi Pico

Technical requirements

Converting an encoder count into a speed

Loose bolts and nuts

Robot wheel geometry

Encoder geometry

Measuring the speed of each wheel

Fixing the encoder glitches

Using PID to maintain speed and a straight line

The speed control system

Speed control code

Speed controller PID tuning

Driving a known distance

Theory of operation

Code to control distance and speed

Summary

Exercises

Further reading

12

Detecting Orientation with an IMU on Raspberry Pi Pico

Technical requirements

What is an IMU and how to choose one

Components of an IMU

Choosing an IMU module

Connecting the IMU to the robot

Preparing the BNO055

Attaching the BNO055

Wiring the BNO055 to Raspberry Pi Pico

Setting up the software and connecting

Troubleshooting

Calibrating and getting readings

Calibration code

The calibration process

Always face North behavior

CircuitPython code for the face North behavior

Troubleshooting

Making a known turn behavior

Summary

Exercises

Further reading

13

Determining Position Using Monte Carlo Localization

Technical requirements

Creating a training area for our robot

What we will make

How we will make the arena

Tips for cutting

Modeling the space

Representing the arena and robot position as numbers

Serving the arena from the robot

The Bleak library

Creating a Bluetooth LE wrapper library

Showing the robot’s data on the computer screen

Using sensors to track relative pose

Setting up poses

Displaying poses

Moving with collision avoidance

Moving poses with the encoders

Pose movement probabilities

Monte Carlo localization

Generating pose weights from a position

Resampling the poses

Incorporating distance sensors

Tuning and improving the Monte Carlo model

Summary

Exercises

Further reading

14

Continuing Your Journey – Your Next Robot

Technical requirements

A summary of what you have learned in this book

Basic robotics with Raspberry Pi Pico

Extending a Raspberry Pi Pico robot with sensors

Writing CircuitPython behavior code for Raspberry Pi Pico

Planning to extend this robot

Sensors you could add

Interacting with the robot

Chassis and form enhancements

Electronics enhancements

Outputs you could add

Extending the code and behaviors

Planning your next robot

Form, shape, and chassis

Electronics and sensors

Code and behavior

Further suggested areas to learn about

Electronics

Design and manufacturing

Robotic competitions and communities

Robotics systems and code

Summary

Exercises

Further reading

Index

Other Books You May Enjoy

Part 1: The Basics – Preparing for Robotics with Raspberry Pi Pico

In this part, you will take your first steps in learning about Raspberry Pi Pico, then plan and build a robot around it, and get the initial robot code to make the robot move.

This part contains the following chapters:

Chapter 1, Planning a Robot with Raspberry Pi PicoChapter 2, Preparing Raspberry Pi PicoChapter 3, Designing a Robot Chassis in FreeCADChapter 4, Building a Robot around PicoChapter 5, Driving Motors with Raspberry Pi Pico

1

Planning a Robot with Raspberry Pi Pico

When you plan, you create the best chance for a mission’s success. We want to build robots in an achievable way. Let’s start with a plan in mind! We’ll use this plan to explore why Raspberry Pi Pico is a great fit for this and make a shopping list!

In this chapter, you’ll learn about Raspberry Pi Pico’s capabilities. You’ll discover CircuitPython and understand why it is a great language for Raspberry Pi Pico. Additionally, we’ll plan a robot design and understand the trade-offs to make choices about the robot early in the project. We’ll check that our robot fits together, working out the parts and tools you’ll need with suggestions on how to get them.

At the end of the chapter, you’ll have both a plan and parts arriving so that you are ready to build a robot. Additionally, you’ll have a starting process for making other robots and setting yourself up for success with them.

In this chapter, we’ll cover the following main topics:

What is Raspberry Pi Pico, and why is it suitable for robotics?What is CircuitPython?Planning a Raspberry Pi Pico robotTest fitting a Raspberry Pi Pico robotA recommended shopping list for robot basics

Technical requirements

We’ll go into the necessary hardware and shopping list as we progress further in this chapter. So, in this section, we’ll just focus on what you will need physically and on your computer to get started.

You will require the following:

Some thin cardboardA ruler, pencil, and scissorsA good web browser with internet access

What is Raspberry Pi Pico, and why is it suitable for robotics?

At the heart of every robot is a controller. Usually, this is a computing device that is responsible for running the code for the robot to perform its tasks and behaviors. Choosing a controller is a key choice in robot design. You can either come from the I have this controller, what can I do with it? perspective or the which controllers have the capabilities I’ll want for a particular robot? perspective.

In this section, we’ll take a closer look at what Raspberry Pi Pico offers as a controller and the trade-offs it’s made. We’ll explore why it is good for robotics and why it could be part of a larger, more interesting system, too.

Additionally, we’ll delve into the details of its interfaces and how they’ll be useful to us.

A microcontroller that runs Python

Let’s start by taking a look at Raspberry Pi Pico, and discover what it has. The following photograph shows Raspberry Pi Pico:

Figure 1.1 – Raspberry Pi Pico

Raspberry Pi Pico, as shown in Figure 1.1, is an RP2040 microcontroller on a Raspberry Pi-designed board. This microcontroller is a small computing device that has been designed to interface closely with hardware. It has a USB connection on the right-hand side for power or programming on a computer. The LED is useful for debugging. Also, there are many input/output (IO) pins around the edges to connect things. It is with these IO pins that the magic happens when it comes to controlling robots!

Controllers use IO pins to write and read from attached hardware. They can group pins into buses (which we’ll cover in more detail later) to exchange data with other devices. Additionally, they can create waveforms on outputs for controlling motors and LEDs.

This sounds a lot like the other Raspberry Pi models. However, this is a different class of computer. Raspberry Pi Pico has more in common with an Arduino board. Let’s take a closer look at what that difference means with the following diagram:

Figure 1.2 – Microcontroller boards versus single-board computers

Figure 1.2 shows that while microcontroller boards such as Raspberry Pi Pico and Arduino might look similar to single-board computers (SBCs) such as Raspberry Pi 4 or BeagleBone, they have different key areas. For instance, they differ in storage, CPU speed, cost size, the complexity of software, and how closely your software runs to the hardware.

While Raspberry Pi Pico is brilliantly suited to controlling hardware, such as robots, it isn’t as suited to high-memory or CPU tasks such as AI or visual recognition. There’s a kind of robot system known as horse-and-rider, which combines an SBC (for example, Raspberry Pi 4) for complex processing with a microcontroller (for example, Pico) for controlling hardware.

The low complexity means that code on a microcontroller has nearly no boot time, which means your code doesn’t have to coexist with other software in an operating system. Take a look at the following block diagram:

Figure 1.3 – Running your code on Raspberry Pi versus Pico

This preceding diagram represents the software architecture on Raspberry Pi versus Raspberry Pi Pico. It shows how a Linux computer, such as Raspberry Pi, has additional layers of software along with competing apps running alongside your code.

In addition to this, controllers have interrupts. They can notify the code that something has changed, such as the state of an IO pin. You’ll find this on the other Raspberry Pi models, but they are controlled by that pesky operating system again. In Pico and other microcontrollers, you get more control over what happens or when something changes on an IO pin, allowing responsive code with predictable timing.

So, how does Raspberry Pi Pico compare with the Arduino Uno? The following table shows details from their specificationsand datasheets:

Table 1.1 – Comparing the Pico with the Arduino Uno

The preceding table shows that Raspberry Pi Pico has a faster multicore processor, along with more storage and digital IO pins. Additionally, Raspberry Pi Pico has a unique Programmable IO (PIO) system for extreme flexibility in organizing data to and from these pins. Official Pico boards are also cheaper than official Arduino boards.

Another place that Raspberry Pi Pico compares favorably with Arduino is in its use of Python (CircuitPython or MicroPython). Many microcontrollers, such as Arduino, require C/C++ to program, which can be difficult for beginners. Python is easier to understand, allows for complex and interesting data structures, and has access to many libraries of code, too.

In short, the key features of Raspberry Pi Pico are as follows:

A microcontroller—this offers low power and is small compared with SBCs.It has responsible and flexible IO options.It is low cost compared to many microcontroller boards and most SBCs.It is programmable in Python.

A number of the features I attribute to Raspberry Pi Pico are due to the RP2040—the chip that powers Pico and is available in forms other than Raspberry Pi Pico.

IO flexibility is Raspberry Pi Pico’s most interesting feature, so let’s take a look at that next.

Raspberry Pi Pico’s interfaces for sensors and devices

Raspberry Pi Pico has many interfaces for connecting to hardware, along with its unique PIO system. In this section, we’ll look at each type of interface.

A digital IO pin is the basic IO system for Raspberry Pi Pico. An output can be on or off, which is great for turning LEDs on or off, but you are unable to control their brightness. Similarly, an input can also detect on or off states. Raspberry Pi Pico has 26 of these pins.

Pulse-Width Modulation (PWM) is a waveform for controlling outputs such as LEDs and motors—including DC motors, stepper motors, and servo motors. PWM pins output square wave pulses, with a changing (modulating) on-off ratio (pulse widths). Changing pulse width results in changes to the brightness of an LED, the speed of a motor, or a servo motor’s position. Raspberry Pi Pico has 16 PWM channels, making it capable of controlling many such devices at once. These PWM pins still require a power control device to drive the motors.

Analog input pins detect levels of voltage between ground (GND) and 3.3V. This is good for interfacing with simple sensors, such as light sensors, joysticks, slider/knob controls, temperature sensors, and measuring currents (using a bit of additional circuitry). Raspberry Pi Pico has three of these inputs.

A universal asynchronous receiver-transmitter (UART) controls a serial port. It can send streams of data to and from devices using two pins: a TX transmit pin and an RX receive pin. With this, it is capable of sending/receiving data that is more complicated than just a varying level. Raspberry Pi Pico has two independent UART interfaces.

Pico has two Serial Peripheral Interface (SPI) bus controllers. SPI uses four pins, as shown in the following diagram:

Figure 1.4 – Raspberry Pi Pico SPI bus usage

The preceding diagram shows Raspberry Pi Pico using an SPI bus to connect to two devices—for example, displays or sensors. The bus has transmit (TX), also known as Controller Out/ Peripheral In (COPI) or Microcontroller Out/Sensor In (MOSI) for transmitting data from the controller, receive (RX) also known as Controller In/ Peripheral Out (CIPO) or Microcontroller In/Sensor Out (MISO) for receiving data back to the controller, SCK (a clock for timing the signal), and Chip Select (CSEL/CS) a chip selection pin for each peripheral. SPI uses chip selections to enable communication with multiple devices, as shown by the dashed lines of Device 1 CS and Device 2 CS. See https://makezine.com/article/maker-news/mosi-miso-and-140-years-of-wrong/ for details on the current SPI acronyms.

The Inter-Integrated Circuit (I2C) is a data bus designed for communicating between integrated circuits such as sensors, memory devices, and output devices. An I2C bus has a data pin (which is often called SDA – Serial Data) and a clock pin (which is often called SCL – Serial Clock) keeping things synchronized. Multiple devices share an I2C bus by sending/receiving data with addresses, such as those in the following diagram:

Figure 1.5 – I2C buses on Raspberry Pi Pico

Figure 1.5 shows Pico and then some child peripherals connected via two independent I2C buses, assignable to different pin configurations, with some devices having the same address but different I2C connections. Additionally, I2C can address registers (such as memory locations) within devices. We’ll use I2C later to communicate with sensors.

Finally, Raspberry Pi Pico has PIO. PIO is a feature that is unique to Pico. PIO consists of two blocks with four state machines. Each can run simple code independently of the main CPU and control one or more pins to send data to or from them. A single-state machine can control all the pins if that was useful for the code. Additionally, each state machine comes with buffers to hold data until it can be transferred. The following is an example block diagram of the PIO system:

Figure 1.6 – The Raspberry Pi Pico PIO system

The preceding diagram shows two PIO devices inside the Pico. Each has code storage memory, so you can have two independent functions. In each PIO device, there are state machines that can independently run the code from that local memory.

Since PIO state machines run independently, and their instructions are about shifting data to/from pins, they can create interfaces for many kinds of hardware. For example, is there a weird protocol device? Use PIO. Do you need rapid counting independent of the main CPU? Use PIO. People have made Video Graphics Array (VGA) outputs with PIO, so it’s capable of fast and complex data handling. Additionally, you can also get interrupts from PIOs to tell you when something has happened.

That was quite a lot of IO systems. Let’s summarize them in a table, as follows:

Table 1.2 – The Raspberry Pi Pico IO systems

These protocols share pins, so using an I2C bus consumes 2 pins from the 26-pin pool.

Now that we’ve had a tour of Raspberry Pi Pico’s features and interfaces, let’s take a look at how we’ll program it in this book, using CircuitPython.

What is CircuitPython?

Many microcontrollers require C/C++ or Assembler to program—for example, the popular Arduino ecosystem. However, in robotics, Python is rapidly becoming a de facto language. It is used for AI and data science and is great for rapidly trying out new ideas. Let’s examine why it is handy and, specifically, why I’ve chosen CircuitPython for this book.

Python does not require a compile step. Getting you quick feedback on your code and Python’s read-eval-print loop (REPL) allow you to start typing and experimenting with code instantly. The REPL allows you to see what works before using ideas in code that you’ll keep. Here’s a REPL session with CircuitPython:

Adafruit CircuitPython 6.2.0 on 2021-04-05; Raspberry Pi Pico with rp2040 >>> print("Hello, world!") Hello, world!

The preceding session shows a print running in a REPL on Raspberry Pi Pico. We’ll explore how to use the REPL for some Pico experiments. It even comes with built-in assistance; however, on Pico, not all of the help is left in, for size reasons.

Python has other things that help, such as being able to directly return multiple values from a function. Python has function calls and classes like C++, but functions can be used as data, and references to them can be stored in variables. Additionally, Python has functional programming elements that allow programmers to chain tools together for processing streams of data.

Python uses exceptions to handle errors, allowing you to choose how to respond to them or observe their output, leading you directly to a problem.

MicroPython is the original port of the Python language to run on small memory devices such as microcontrollers. It has a community working on it, and CircuitPython builds on it.

In CircuitPython, Raspberry Pi Pico mounts as a USB storage device, so you can copy your code and the libraries your code uses, directly onto the Pico. This makes composing code from multiple libraries or using third parties simple. Copying code over with the correct name is enough to run that code when Raspberry Pi Pico is powered up again.

CircuitPython has a huge library of device support for Neopixel LEDs, Bluetooth, many sensors, displays, and other devices. This library not only works with Pico but runs across many CircuitPython controllers, so familiarity with these library components will be useful when you are working with other controllers.

Now that we’ve chosen a language and the controller that we will build robots with in this book, it’s time to start planning a robot!

Planning a Raspberry Pi Pico robot

We’ve been fact-finding for our robot-building mission. Before we start our robot-building journey, we’ll make a rough plan of what we want to do, then refine it. We’ll make important decisions, which we can examine further as we start to build the robot.

An overview of robot planning

When planning the robot, there are several things we need to consider:

What do we want this robot to do? What is it for?What style of robot is suitable?What kinds of sensors or outputs will we need?What rough shape and size will it have?

Once we’ve answered these questions, we can make further decisions about what we build. These don’t require much detail. Robotics is full of interesting diversions, making it tempting to jump between ideas. By having a constrained plan and working to it, you can keep your pace on getting a robot built, saving distractions and cool ideas for the next robot or three!

What do we want this robot to do? What is it for?

Will the robot solve a problem, clean your kitchen, explore a space, deliver packages, impress guests at a conference, or compete in a robot competition?

The robot we’ll build in this book has several purposes:

Exploring Raspberry Pi Pico and its capabilitiesTrying out sensorsWriting algorithms guided a little by challenges in robot competitionsNavigating a known spaceBuilding a custom chassis, adaptable for future ideasKeeping it simple enough to get started

With these goals in mind, we can look at the specific details.

What style of robot is suitable?

There are many robot styles. We should choose one, probably the simplest possible for our goal. Take a look at the following diagram for a selection of different robot styles:

Figure 1.7 – Different robot styles

The first robot style is a robot arm used in industry. These are fascinating and fun to build. However, they do not satisfy our goals of building a robot chassis to try out sensors.

The next panel shows a quadcopter drone—an unmanned aerial vehicle (UAV). These are complicated to build and program, so they do not meet our goal of keeping it simple.

The third panel shows a walking robot—a hexapod. These require controlling many servo motors. Their power usage and complexity make them an unsuitable but exciting option for a follow-up robot!

The fourth panel shows a wheeled robot. Wheeled robots can be simple two-wheel-drive (2WD) robots with a roller, such as this one. 2WD rover platforms such as this satisfy our goals of building a chassis and getting to know sensors and algorithms. They can later be made more interesting, with tracks, mecanum wheels, rocker bogies, or individually steered wheels, allowing them to also meet the adaptable goal.

I recommend that we go ahead with a 2WD rover throughout this book but keep the other variations in mind for further robot builds!

What kinds of sensors or outputs will we need?

One of our goals is to try out different sensors. A robot made to navigate spaces will influence the sensors we’ll use. They all contribute to locating the robot.

Good sensors for this include the following:

Distance sensors: What is in front of the robot? How far are the nearest objects? We might want more than one of these devices.Encoders: How has the robot moved? How far did it go?Inertial Measurement Unit (IMU): Has the robot turned? What is its position relative to north?

Along with these sensors, we can have simple outputs—the motors that we drive wheels with. As a later extension, we could also add Bluetooth to give us some feedback on our robot’s status. We don’t need to plan all of this yet but leave space for it so that we can extend the robot later.

What rough shape and size will it have?

Now, we have a firm idea of a 2WD robot. We know it probably needs to support the following:

Raspberry Pi PicoA pair of motors with wheels and a casterMany sensors and, later, BluetoothPower for the system, including batteries plus voltage conversionA breadboard for wiring all of this together

Although we don’t want the robot to be too big, we are going to need some real estate to play with. Let’s start with a rough estimate of 150 mm x 200 mm.

So, we’ve answered some questions about what we want. We will use the next few sections to dive deeper into the planning of this robot, looking at the different aspects of the planning and the choices we’ll make. The first of those is to consider trade-offs.

A note on trade-offs

All designs make trade-offs. The truth is that no design fits all cases, and usually, no design is perfect but will be good enough in the right aspects where it works. We will need to make decisions and read datasheets for parts to also assist us.

One example is size and weight—we already mentioned that we don’t want a large robot. After all, we have a limited workbench size, and larger robots require more power, larger motors, and larger batteries. Additionally, we’d need to work with tougher and—likely—harder-to-cut materials. For a different context and goal, perhaps a large, heavier robot would be more suitable. So, the first trade-off is to keep the robot small but not too small—that is, to keep it simple.

We’ve suggested Raspberry Pi Pico, and the trade-offs from Raspberry Pi there, for example lighter weight, reduced cost, and power.

But what of sensor trade-offs? Every sensor has multiple types, which we will dive into in their respective chapters. They differ in price, features, and complexity.

In many aspects, we can trade having more complexity for reduced weight or cost or more features for a higher cost.

Choosing a robot chassis

We have many options for our 2WD robot chassis. Again, this depends on what we want to learn or achieve. We have stated our goal of building a flexible chassis. Some good options for doing this are as follows:

Buying a chassis kitAdapting a lunchbox or toyDoing a scratch build by hand3D printing or laser cutting a chassis

Chassis kits are an easy option but have limited flexibility. Many come with motors, wheels, batteries, and even a motor driver designed for a specific main controller. In this way, they can save time and money, allowing you to focus entirely on the code and sensors, but they offer less opportunity to learn design aspects. It’s often tricky to find a chassis kit with the right shape and size, and as they get larger, they quickly become more expensive.

You could also adapt a lunchbox into a robot chassis—cutting mounting holes for motors, sensors, boards, and other parts can be a good place to learn design skills. However, you’d need to fit your robot electronics and hardware in a constrained space. Note that the curved sides of lunchboxes can complicate things.

Scratch-building a chassis gives you great flexibility. You can learn how to design in CAD and how to use hand tools. Additionally, you need to make choices about the type and thickness of the material, and in doing so, you’ll be able to understand more about making strong robots. You’ll learn how to fit sensors and expand your robot if things get a bit tight. This requires more time and patience than the kits, but the rewards are great.

3D printing and laser cutting require precise designs, along with expensive and specialist tools or services. As you dive further into robotics, and progress beyond a simple 2WD robot, creating more interesting shapes and sensor mounts, it is likely to be an important area of exploration. If you are not confident with hand tools, finding a laser-cutting service for the same parts will achieve good results, but it can be costly.

In this book, so that you can get exposure to the design and hand tools while still giving us lots of flexibility, we will take the scratch-building option. We will learn CAD skills that are transferable to 3D printing. We’ll learn how to cut and drill parts, looking at some premade parts to save time. Additionally, we’ll size our design at approximately 150 mm x 200 mm and modify this if needed. But what about the motors?

Choosing motors

This 2WD motor requires two main drive motors. We could consider stepper motors, which move a little each time they are pulsed, although these bring a little extra complexity—perhaps an idea to keep for later. DC motors, which rotate continuously when powered, seem like the right choice. They will need to be geared so that they have enough power to move the robot, without being too quick and hard to control.

We should keep these motors small and at a low voltage. As we are unlikely to want to build an additional gearbox, geared motors are sensible. There are some options here in terms of the size we are working with. First is the yellow TT motor with plastic gears— however, these motors are not of great quality and take up a fair amount of space. Another option is to use servomotors that are adapted for continuous rotation—however, these can be a little expensive.

A small, common, high-quality but inexpensive option is N20 or micro-metal gear motors. To save space and effort, there are models of these that have encoders pre-fitted. We can use similarly common plastic brackets to attach them to our robot. That makes them convenient to use, too.

Robot wheels

For a 2WD robot, there are a few ways in which to lay the wheels out. One possibility is to have two driving wheels with two idler wheels (that is, unpowered). However, those wheels can drag, making it harder to turn the robot. A common way is to have a third wheel as a caster—either a ball that can roll in any direction or a swivel wheel such as a shopping trolley. Because of the size of the robot, a ball caster seems like a good idea.

The wheels themselves should have a hub that is compatible with the motors that we’ve chosen. A pair of N20 wheels with a diameter of 60-100 mm should be suitable.

So, we have a rough size for our robot, and we know the controllers, motors, and some of the sensors. The next item to choose is the power systems.

Choosing the power systems

A robot isn’t much fun without independent power—by which I mean its own source of power without needing to be plugged into a wall. Usually, this means batteries. It then needs ways to provide power to the control electronics, sensors, external boards, and motors. Take a look at the following diagram for an outline of power distribution in a 2WD robot:

Figure 1.8 – Power distribution in a 2WD robot

In Figure 1.8, the thicker lines show raw battery power connections. A 2WD chassis will need to drive at least two motors, which are power-hungry devices that require a battery connection.

This robot needs to power Raspberry Pi Pico and other sensors. Since we intend to add Bluetooth, we should leave power aside for that. So, the other thick line goes to a regulator for these, making more palatable power for these systems—the raw battery voltage would likely destroy them. The thinner solid lines show regulated power.

The Pico will be sending/receiving electronic control signals, designated by the thin dashed lines in the preceding diagram. These also go to the motor controller. The motor controller will provide PWM-controlled power from the batteries to the motor, modulated by the signals the Pico sends to them. The motor power is shown by the thick dashed lines to the motors on the left-hand side.

Here, we have a few considerations to bear in mind. We require an input voltage that is suitable for the motors and to drive a regulator. We need a regulator that can handle the power capacity requirements for the Pico, sensors, and Bluetooth, and we need batteries that can supply enough current to drive them.

Calculating power requirements

Let’s start with what we know—5V is a good output voltage for a regulator, and where needed, the Pico can further regulate down to 3.3V. A regulator for 5V likely requires 7V or more.

Important note

Voltage measures electrical pressure. A current measures how fast electrical energy flows. Combining both of them shows system power usage. A current in amps or milliamps can be used as a stand-in for power in watts when the voltage is known.

Let’s look up the specifications for the N20 gear motors. Perform an online search for the N20 motor datasheet. You’ll be looking for a PDF document. Usually, these have a picture or diagram of the product, followed by the specification and feature tables. If you look for Rated Voltage, they say 6V; however, further down the sheet, there is usually a table relating to the voltage of the motor speed. Based on the motors and regulator basics, an input voltage of 7V-12V would make sense.

Our electronics don’t operate on voltage alone and require a current to operate. So, a regulator will need to handle the minimum current requirements. We’ll need to look at some datasheets and specifications for the other parts. We will include sensors. For Bluetooth, we will include a low-power Bluetooth Low Energy (BLE) board using the highest current measurements from https://learn.adafruit.com/introducing-the-adafruit-bluefruit-le-uart-friend/current-measurements.

We’ll base it on worst-case values so that we can handle them. Let’s start by looking at datasheets and gathering numbers into a table, as follows:

Table 1.3 – Device power requirements

Chapter 3 of the datasheet for Raspberry Pi Pico (which can be found at https://datasheets.raspberrypi.com/pico/pico-datasheet.pdf) shows the electrical specification, with peak currents at a little under 92 mA (milliamps—a measure of current). We’ll round this up to 100 mA as a margin.

The Adafruit Bluetooth board uses only 15.2 mA when fully active, but we can round it up to 20 mA to be generous. The sensors need maybe 50 mA of extra room to accommodate them.

We can add these estimates together to suggest a minimum current specification. Based on these datasheets and estimates, any regulator capable of over 400 mA will be plenty.

Choosing a regulator

Motor control and power supplies can be totally separate concerns, giving great flexibility, but this can take up more space. There are boards designed for Raspberry Pi Pico that allow you to control motors while supplying power to Raspberry Pi Pico. However, will they supply 400 mA?

Kitronik has some neat Raspberry Pi Pico motor boards—a small motor only, along with a larger robotics board with servo motor outputs and a prototyping area. However, the supply for the Pico on the robotics board datasheet has 100 mA for peripherals, which won’t work.

Now, we understand that we need a regulator that is capable of outputting 5V, at a minimum of 400 mA. We want something small and simple. A suitable device for this is a Universal Battery Eliminator Circuit (UBEC). These can handle 3 A. We’d put this through a VSYS pin on the Pico.

Choosing a motor controller

The suggested motors are small. Motors have a stall current—that is, the power they draw if they are trying to move and block a logical maximum. For the N20s, their datasheet suggests 350 mA at 6V. It might be a little over that, perhaps 550 mA. A motor controller needs to handle a little over this peak per channel—motor controllers that are unable to handle motor load tend to go up in smoke! Take a look at the following two common simple motor controllers:

Figure 1.9 – An L298N motor controller next to a TB6612fng

In Figure 1.9, on the left-hand side, you can see the very common L298N—internet searches suggest this handles 2 A per channel. They are small, inexpensive, and easy to find. However, this is a 5V logic device. Raspberry Pi Pico outputs 3.3V logic, which might not work properly with this controller without logic-level conversion.