100% found this document useful (3 votes)
995 views171 pages

Raspberry Pi Pico Guide A Complete Newbies To Expert Guide To Master The Use of Raspberry Pi Pico To The Max

dsfdsfdsf

Uploaded by

programe info
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
995 views171 pages

Raspberry Pi Pico Guide A Complete Newbies To Expert Guide To Master The Use of Raspberry Pi Pico To The Max

dsfdsfdsf

Uploaded by

programe info
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 171

Raspberry Pi Pico

guide

A complete newbies to expert


guide to master the use of
Raspberry Pi Pico to the max

John Ezekiel
Copyright 2021© John Ezekiel

All rights reserved. This book is copyright and


no part of it may be reproduced, distributed, or
transmitted in any form or by any means,
including photocopying, recording, or other
electronic or mechanical methods, without the
prior written permission of the publisher,
except in the case of brief quotations embodied
in critical reviews and certain other non-
commercial uses permitted by copyright law.

Printed in the United States of America


Copyright 2021 © John Ezekiel
Contents
INTRODUCTION ................................ 1
Chapter 1: Raspberry Pi Boards ......... 2
Chapter 2: The RP2040
Microprocessor ................................... 11
Chapter 3: Using the Raspberry Pi
Pico to Complete Tasks .................... 22
Chapter 4: Using the Raspberry Pi
Pico with a display that is 7-
segmented ......................................... 38
Chapter 5: Building a Raspberry Pi
Pico Weather Station ....................... 54
Chapter 6: Using a Raspberry Pi Pico
and an Ultrasonic Sensor ................. 79
Chapter 7: MicroPython Joystick
Programming for Raspberry Pi Pico
........................................................... 105
Chapter 8: Playing Musical Notes.. 123
Chapter 9: Making Use of the
Raspberry Pi Pico With an Arduino
Board ................................................ 150
Conclusion ....................................... 166
INTRODUCTION
This guide will teach you everything you need to
know about the Raspberry Pi Pico, a
microcontroller board based on the new RP2040
microcontroller. This guide will lead you on,
assisting you in understanding the system and
simplifying the processes for using it, allowing
newcomers to quickly achieve master’s status.

Before learning how to use the Raspberry Pi Pico,


it's a good idea to first understand how it works in
order to get a better understanding of what we're
dealing with.

1
Chapter 1: Raspberry Pi
Boards
The Raspberry Pi is a single-board computer that
runs the Linux operating system. You can use a
mouse, monitor, keyboard, and other accessories
to communicate with them through a prompt or
graphical user interface, such as the Raspberry Pi
OS desktop.

Over the years, Raspberry Pi boards have become


an important part of the work lives of students,
electricians, programmers, and even robotics
engineers. In reality, even the most inexperienced
members of the DIY community can use these
boards with ease. This is owing to the wide range
of hardware compatibilities available, such as

2
sensors, cameras, plugin modules, and so on. Its
programming capabilities also add to its flexibility.

Raspberry Pi boards are available in a variety of


versions, including the Raspberry Pi Zero,
Raspberry Pi 3 Model B+, and Raspberry Pi 4
Model B, each with its own capacity, features, and
specifications.

Pico Raspberry Pi

The Raspberry Pi Pico is not a Single Board


Computer like the other Raspberry Pi boards. It is,
instead, a microcontroller.

A microcontroller, in general, is a small integrated


circuit that controls the functions of an embedded

3
device. It's the unit in charge of controlling various
aspects of an electronic system.

Microcontrollers are controlled by a computer


and do not need a complete operating system to
operate. They don't need any boot time because
they start up immediately after being turned on.
They're virtually stable and predictable, which
makes them ideal for use.

The Raspberry Pi Pico is the company's first


microcontroller board. It was created with the
RP2040 Microcontroller chip from Raspberry Pi.

Analog to Digital Converters, also known as ADCs,


are integrated into the Pico. Different inputs and
sensors can be connected to these ADCs.

4
Other features include programmable IOs for
relaying computer instructions, GPIO pins, and so
on.

The following is a breakdown of the Pico's


features:

• On-chip SRAM of 264KB

• Microcontroller chip RP2040

• Three analog inputs on a 40-pin IO

• 2MB QSPI Flash onboard

• Dual-core Arm Cortex M0+ processor with up to


133MHz flexible running clock

5
• 16 PWM channels, 2 UART channels, 2 12C
controllers, and 2 SPI controllers

• 8 programmable input/output ports

• The 21mm x 51mm form factor

• Castellated modules that can be soldered


directly to carrier boards

• 1 controller USB 1.1

Design of the Raspberry Pi Pico


board

The images below show what can be found on


Pico's board.

6
Note that the 40 IO pins do not have headers;
instead, they have holes into which you can solder
headers.

On the Raspberry Pi Pico's topside, there are no


pin numbers. Instead, they're written on the
bottom of the board. As a consequence, a Pinout

7
Diagram of the unit might be useful for ease of
use.

The Raspberry Pi Pico’s Pinout

The Raspberry Pi Pico, as seen in the picture


above, has 20 pins on each long side of the board,

8
for a total of 40. The machine and power-related
pins account for 14 of the 40 pins, while the
remaining 26 are GPIO pins. Three additional pins
are also present, which are used for SWD
Debugging.

The Raspberry Pi Pico's operating voltage is 3.3V.


SPI, UART/Serial, and I2C communication
protocols can all be used with the GPIO pins. They
can also be used for pulse width modulation and
optical inputs/outputs.

The Pico's three analog inputs were not present in


previous Raspberry Pi versions. Variable voltages
are used to bind devices such as a light-dependent
resistor, potentiometer, or joystick to the inputs.

9
Additionally, as shown below, there are
Castellations in the GPIO pins that allow the Pico
to be soldered to a project or carrier board.

10
Chapter 2: The RP2040
Microprocessor

The RP2040 is the first microcontroller chip


designed specifically for the Raspberry Pi. It's built

11
on a 40nmsw node and has dual ARM-cortex-M0+
cores running at 133 MHz.

The following methods were used to arrive at the


name RP2040:

• RP stands for Raspberry Pi.

• 2 denotes the number of cores it has, which is


two due to the fact that it is a dual-core
processor.

12
• The core form is represented by 0 (zero). The
ARM Cortex-M0+ is the core form used here,
which is why the value is 0.

• The number 4 denotes the amount of On-Chip


RAM used. The formula used to calculate this
value is (log2 (ram size / 16k)). Since the RAM size
used here is 264k KB, the formulas yield a value of
4.

• 0 denotes Non-Volatile Storage, which is On-


Chip Flash. This is calculated using the formula
(log2 (Non-Volatile Storage Size / 16K)). The value
of 0 is obtained by applying the formula.

13
Putting the Raspberry Pi Pico
Board to Work

Now that we've covered the physical


characteristics of the Raspberry Pi Pico surface,
let's look at how to use it.

The Raspberry Pi Pico board can be used to


perform a variety of tasks, including playing
sounds, blinking LED bulbs, and a variety of other
tasks that will be discussed further down.
However, before all of this will happen, the board
must be programmed with lines of code.

C/C++ or MicroPython are used to write the lines


of code for the Raspberry Pi Pico. MicroPython is

14
the most widely used programming language for
the Pico, according to James Adams, the
Raspberry Pi's Chief Operating Officer.

C/C++

Either of the two approaches can be used to use


either of these programming languages.

The first method is to use a text editor to write


the codes, then create the files and flash them
onto the Pico.

Alternatively, you can handle the graphical


workflow, create, and then flash using a single app
like Microsoft Visual Studio Code.

15
MicroPython

Damien George developed MicroPython, which


was first used by the PyBoard Development Board
in 2014. It's the Pythion version 3 that's
specifically designed for microcontrollers.

The use of MicroPython in the Pico is widely


known. For beginners, it is most likely the best
choice. The Thonny Python IDE can be used to
write MicroPython codes for the Pico.

Furthermore, Adafruit has created a MicroPython


version called CircuitPython that is also suitable
for use with the Pico.

16
The Raspberry Pi Pico: Programming
and Setup

As previously mentioned, the Raspberry Pi Pico is


not your typical Linux-based Single Computer
Board. Instead, it functions as a programmable
microcontroller that can be controlled with C/C++
or MicroPython code.

For the purposes of this tutorial, we will use


MicroPython, which we consider to be the best
Python for beginners. There will however be some
cases where C/C++ will be used. This will be duly
identified.

17
In addition, we'll be using the Thonny IDE as a text
editor. MicroPython and the Thonny IDE are
available for download on the web.

MicroPython

1. Navigate to the MicroPython tab on the


Raspberry Pi Pico webpage, search for and select
the 'Download.UF2 File' option. The.UF2 file will
be downloaded if all is done correctly.

2. Next, connect the other end of the micro-USB


cable to the computer or Raspberry Pi by plugging
it into the Pico. After that, press and hold the
Raspberry Pi Pico's 'Bootsel' button to enter USB
Flash Mode. If all goes well, the Pico will appear
on your screen as ‘RPI-RP2'.
18
3. Finally, drag and drop the previously
downloaded.UF2 file from its original position to
the Raspberry Pi Pico drive. The Pico drive name
will vanish after you drop it there, and the
Raspberry Pi Pico will restart, allowing you to use
MicroPython.

Thonny

Simply go to the Thonny website and download


the version that is compatible with your operating
system.
19
We'll be using version 3.3.2 for Windows in this
tutorial. Simply download it, install it, restart
Thonny, and you're ready to go.

When you've finished downloading and installing


both packages, go to Thonny > Tools > Options
and click on the interpreter tab. If it doesn't
connect automatically, select MicroPython
(Raspberry Pi Pico) from the drop-down list.

When you complete the steps above, the Python


Shell, also known as REPL (Read, Eval, Print, Loop),
will be modified, indicating that MicroPython is
now operational and the Pico is linked.

Sure, we can write a simple ‘Hello World' program


like the one shown below.

20
We can begin carrying out various tasks once we
are confident in the MicroPython's functionality.

21
Chapter 3: Using the
Raspberry Pi Pico to
Complete Tasks
There are various tasks that can be carried out
with the Raspberry Pi Pico once it has been
completely set up and configured. We'll go over it
here in as much depth as possible in an easy-to-
understand manner for newcomers.

Let's start with the easy ones and work our way
up to the more difficult ones.

22
Soldering Pins to your Raspberry
Pi Pico

The Raspberry Pi Pico has 40 GPIO pin holes, as


previously mentioned. Actually, there are no pins
on the Raspberry Pi Pico, and without them, you
won't be able to attach it to any external devices.

As a result, you'll need to solder pins onto the


board before you can use it. Users with more

23
experience can simply solder single wires directly
to the board using female pin headers.

But, for the sake of convenience and comfort,


we'll show you how to solder with male pins. This
is the most popular and practical method.

Furthermore, if you are a beginner, you can start


learning how to solder by practicing with this
guide.

As a starting point, make sure you're well-


prepared. Set up your workspace and test your
soldering iron's functionality. Check to see if any
of the supplies you'll need are available.

The following materials are required for this


project:
24
• A strip of 40 male header pins

• Soldering iron and stand

• Solder that is free of lead

• Breadboard (full or half-size)

• Cutter on the side

• If applicable, safety glasses to cover the eyes

Soldering on the Raspberry Pi Pico: A


Step-by-Step Guide

25
• Clean and Prepare Your Workspace: Make sure
the area where you'll be staying in is clean, well-
ventilated, and free of dirt that might
contaminate the solder. Often, make sure that the
soldering iron and its stand are within reach of the
soldering side.

Switch on your soldering iron and wait for it to


heat up before cleaning the GPIO pin holes to
keep them dust-free.

• Remove the male header pins: A strip of male


header pins should normally have 40 pins. Since
the number of GPIO pin holes is also 40, break the
pins into two strips of 20 each using your side
cutters.

26
Before you cut it, double-check that the number is
right, and then cut.

• Attach the two strips to the Raspberry Pi Pico:


When moving the strips through the Raspberry Pi
Pico, make sure the shortest legs go through the
holes on the board.

The Raspberry Pi Pico's CPU will be facing up while


the long pins will be facing down when you do
this.

If you're not sure what each pin does, you can


always point the CPU in the direction of the
breadboard, which will display the GPIO pin
names.

27
Also, when the Raspberry Pi Pico is inserted in the
breadboard, make sure the long pins are at a 90-
degree angle to the Raspberry Pi Pico. Check that
all of the pins are properly seated and straight.

• Now is the time to apply the solder: eye


protection is recommended for this move. The
soldering iron should be hot by now; carefully
remove it from its stand and apply a small amount
of solder to its tip.

You may also clean the tip once more before


applying the solder to ensure it is clean.

• Transfer the soldering iron's tip to the first


pinhole you're working on: Heat the pin hole and

28
the pin with the soldering iron for a stronger
adhesive effect with the solder.

Apply the solder to the region and use the


soldering iron to melt it. Remove any excess
solder, let dry, and replace the soldering iron in its
stand.

• Check the Soldering: Look over what you've


soldered. Make sure the bond is strong. If it isn't,
the soldering process can be repeated.

• Solder the remaining pins: Repeat the procedure


for the remaining pins. Make sure the soldering is
neat and the adhesive bond is solid.

After that, tidy up your workspace and you're


ready to go.
29
Let's move on to learning how to use the
Raspberry Pi Pico for other tasks now that we've
learned how to solder the pins onto the frame.

Using the Raspberry Pi Pico to


make an LED bulb blink

This is one of the most simple tests that the


Raspberry Pi Pico can perform. It's mainly used to
test the Raspberry Pi Pico's functionality.

To do so, you'll need the following:

• A resistor with a resistance of 330 ohms

• An LED light bulb

30
• A bread board that is half the size of a full-size
bread board

The procedure

• Arrange the Raspberry Pi Pico on the


breadboard so that it sits on top of the central
channel. Also, make sure the Micro USB port is at
the breadboard's end.

31
• In the breadboard, position the 330 ohm
resistor. It should be positioned such that one of
its legs is parallel to Pin 38 and the other is simply
in the breadboard. The aim of this is to create a
GND rail on which all of the rail's pins can be
attached.

• In the breadboard, place the LED with its longest


leg in pin 34, which is the anode. Place the shorter
leg in the GND rail as well. By completing these
steps, we will have a full circuit.

32
The Operation’s Coding

After we've finished the circuit, we'll write the


codes that will cause the LED bulb to blink.

33
• Download and install the necessary library. The
code for it can be found in the largest space above
the REPL. We begin by importing two
MicroPython libraries. The first library is the Pin
class, which can be found in the Machine library,
and the second is utime, which is used to monitor
the code's speed.

from machine import Pin


import utime

• After that, you'll need to write an object. The


name of this object will be "led." This object is
being created in order to serve as a link between
the GPIO and our written code. This will make pin
28 of the GPIOs an output pin. It's worth noting
that GPIO pin 28 corresponds to breadboard pin
34
34. Current will flow from the GPIO to the LED
through this location. The object will then be used
to send a low signal to the GPIO pin.

The object, in layman's terms, keeps the GPIO pin


off as we start the project.

led = Pin(28, Pin.OUT)


led.low()

• The next step is to create a while True loop,


which is a loop that never ends. When you're
finished, use the Raspberry Pi Pico to save the
code. Save the file as blink.py and then click OK.

35
We included a sleep function in the image below
to make the code pause for a second while the
loop runs.

If you follow the steps above correctly, the LED


bulb will turn off and on in a split second.

while True :
led .toggle()
print(‘’Toggle’’)
utime.sleep(1)
• After completing all of the steps, your code
should look exactly like the image below. When
you run the code, the Python Shell will say the
word "TOGGLE" every second.

The LED bulb will blink as well.

36
The code is thus;

1. from machine import Pin


2. import utime
3. led = Pin(28, Pin.OUT)
4. led.low()
5. while True:
6. led.toggle()
7. print("Toggle")
8. utime.sleep(1)

37
Chapter 4: Using the
Raspberry Pi Pico with a
display that is 7-segmented

For projects that need a segmented display, you


can use a 7-segment display with the Raspberry Pi
Pico. Some digital alarm clocks and devices that

38
display numbers for keeping track of time,
distances, scores, and other things have this sort
of display.

7-segmented screens come in a variety of shapes,


colors, and even digit counts. There are also those
that come with controller boards, as well as those
that do not.

Furthermore, the ones that do not come with


controller boards use pins for each light, which is
a lot of pins given the number of digits.

Those who use controller boards, on the other


hand, use a 12V connection with just four pins.

39
We'll be connecting our Raspberry Pi Pico to a 7-
segment board with a TM1637 controller board
for this project.

Needed Materials

• Pin headers on the Raspberry Pi Pico are already


soldered.

• 7-segment display having a TM1637 controller


board.

• 4 jumper cables (female)

40
The Connection

The Pico should be linked to the following pins on


the 7-segment display:

• On the Pico, attach the DIO pin to GP17 (next-


to-last pin on the right side)

• Set the Pico's VCC pin to 3V3 (physical pin 36,


the fifth on the right side)

• On the Pico, attach the GND pin to GND


(physical pin 34, the third on the right side).

• On the Pico, attach the CLK pin to GP16 (last pin


on the right side).

41
You have the option of attaching the CLK and DIO
pins to either of the Raspberry Pi Pico's 12V SCL
and SDA pins.

How to Code a 7-Segment Display


Using MicroPython

This course will make extensive use of Mike


Causer's TM1637 MicroPython library to build a
script that will demonstrate various display
options that you can use in your projects.

tm1637.py can be found on the Mike Causer


TM1637 GitHub project. Other files are not
needed.

42
tm1637.py should be copied to your Pico's root
directory. Because the Pico with MicroPython
does not appear as a drive letter, the simplest
solution is to open tm1637.py in your preferred
IDE or Thonny and save it from there.

Create a new MicroPython script in Thonny or


your preferred MicroPython IDE.

Use these code;

import tm1637
from machine import Pin
from utime import sleep

43
We'll use the utime library to add a one-second
"sleep" delay between the various functions so
you can take your time looking at them on the
screen.

Make a new instance of the tm1637. The right pin


numbers for the DIO and CLK pins are then
inputted as parameters to the TM1637 object
called "mydisplay."

mydisplay = tm1637.TM1637(clk=Pin(16),
dio=Pin(17))

Use the "show" method to highlight any four


characters you want. These characters can be
numbers or letters, but a combination of several
letters, such as the letter W, will appear strange.

44
Only the first four characters will be shown if you
enter more than four. Make sure the parameter
string is enclosed in quotes.

mydisplay.show(“Pico”)
sleep

Use “show” to create four blank spaces on the


screen (if you have four digits displayed).

mydisplay.show(“ “)
sleep

Note that your display will remain on after your


program is done executing if you don’t blank the

45
display. When changing the display, you do not
have to blank it. However, if you make use of
another show command with a lesser than
maximum character number, then any character
that you do not replace will still be displayed on
the screen. As an instance, if you show(“halo”)
then show(“20”), 20lo will be displayed on the
screen.

mydisplay.number(-123)
sleep

If you don't blank the window after your program


has finished executing, it will stay on. It is not
necessary to blank the display while adjusting it.

46
However, if you use another show command with
a character count lower than the limit, any
characters that you do not replace will remain on
the screen. For example, if you show(“halo”) then
show(“20”), the screen will display 20lo.

To show an integer, use the "number" process.


Quotes should not be used around the parameter.
You may also show positive or negative numbers.
The minus sign must be represented by one
character in negative numbers. If you enter a
number that is greater than the number of digits
available, such as 12345 on a four-digit display,
the screen will display "-999" for negative
numbers or "9999" for positive numbers.

47
You may be wondering why you'd want to use the
number method alone when you can use the
"show" method to display letters or numbers. One
explanation for this is that integers do not need to
be converted to strings. Another explanation is
that the display can only show the number of
digits required. As a result, no blank spaces are
needed to match the number to the right side.

mydisplay.numbers(12,59)
sleep(1)

To show a time with visible color, use the


"numbers" process. Input two, two-digit numbers
as parameters and the colon will be shown in

48
between them if one is available for your phone.
12:59 is an example.

#adjust the brightness to make it lower


mydisplay.brightness(0)
sleep(1)
Make use of the "scroll" method to view scrolling
text. Input a string (in quotes) as the first
parameter, then add “delay=” and the number of
milliseconds to control the scroll speed. If you
leave the delay parameter blank, it will default to
250 milliseconds.

mydisplay.scroll("Hello World 123", delay=200)


sleep(1)

49
Use the "temperature" method to show the
temperature in Celsius. The letter C and the
degree symbol will be added together after your
digits using this form. You may also enter the
temperature as a one- or two-digit integer.
Negative temperatures can still be entered, but
only to a single digit.

mydisplay.show(“ “)

To change the brightness, use the brightness tool.


You may use any number as a parameter, ranging
from 0 (the lowest) to 7 (the highest) (the
highest).

#make it darker by adjusting the brightness.

50
mydisplay.brightness is a variable that controls
the brightness of my monitor

You must always blank the screen after the


program has been executed if you do not want
the screen to remain visible.

The final code is thus;

import tm1637
from machine import Pin
from utime import sleep
mydisplay = tm1637.TM1637(clk=Pin(16),
dio=Pin(17))

# Show a word
mydisplay.show("Pico")
sleep(1)

#blank the screen

51
mydisplay.show(" ")
sleep(1)

#show numbers
mydisplay.number(-123)
sleep(1)

#show a time with


colonmydisplay.numbers(12,59)
sleep(1)

#adjust the brightness to make it loewr


mydisplay.brightness(0)
sleep(1)

#show scrolling text


mydisplay.scroll("Hello World 123", delay=200)
sleep(1)

#show temperature
mydisplay.temperature(99)

52
sleep(1)

#blank the screen again


mydisplay.show(" ")

Let’s proceed to other interesting actions.

53
Chapter 5: Building a
Raspberry Pi Pico Weather
Station

Do you want to keep track of the humidity and


temperature in your office or home with a digital
hydrometer? Instead of buying one, you can make
one with the Raspberry Pi Pico microcontroller
board. When you're finished with the project,

54
simply position the DHT sensor through your
window to get accurate weather readings, or use
it to measure the temperature within your home.

For this project, we will be making use of the


C/C++ language.

Requirements

• Raspberry Pi Pico

• Raspberry Pi 4 or 3B+, or the brand-


new Raspberry Pi 400

• 8 GB (or larger) microSD card with a


fresh install of Raspberry Pi OS with
Desktop

55
• I2C backpack with 16x2 1602 LCD

• Temperature and Humidity Sensor


DHT22 (DHT11 may produce erroneous
readings)

• Jumper wires (M-to-F, M-to-M, and F-


to-F)

• a wooden breadboard

• Header Pins (for the Raspberry Pi Pico)

• a power supply, a monitor, a keyboard,


a mouse, and an HDMI cable (for your
Raspberry Pi)

56
• To transfer files from your Raspberry Pi
and Pico board, you'll need a MicroUSB
cable.

• USB wall adapter or power bank


charger (optional)

Timing: We estimate that this project will take


one hour to complete. Nonetheless, we have
included the UF2 file, which is the final package
file, as a shortcut method.

57
Getting your Raspberry Pi Pico up
and running

1. This project necessitates pin connections to the


Pico board. If you haven't a[lready done so, you'll
need to solder pins to your Raspberry Pi Pico.
Connect your Raspberry Pi to a monitor,
keyboard, and mouse.

2. Turn on the Raspberry Pi.

3. Update the Raspberry Pi's operating system.

4. Download the blink.uf2 file from the C/C++


Getting Started guide.

58
5. Connect your Pico's micro USB to your
Raspberry Pi while holding down the BOOTSEL
button on your Pico.

6. From your Downloads folder, drag the blink.uf2


file to the RPI-RP2 removable media. When you
do this, the on-board LED on your Pico board will
begin to blink. You can now detach your
Raspberry Pi and Pico board for the next move.

The next thing to do is to connect the LCD screen


and the DHT22 Temp and Humidity Sensor to your
Pico. To do this;

59
1.Place your Pico board on the breadboard to
begin.

2. Connect pin 36 / 3.3V to the power rail and


GND to the GND rail with your jumper wires.

3. Connect your DHT22 sensor to the breadboard,


then power, GND, and the OUT signal to GPIO15 /
Pin 20. (for the 3 pin DHT sensors). If you're using
a 4-pin DHT22, you'll need to install a 10K ohm
resistor as shown in the schematic.

4. Connect SCL to Pin 7 and SDA to Pin 6 for the


LCD screen.

60
5. To power your LCD screen, connect the LCD
GND to the GND rail on your breadboard and the
LCD VCC to the Pico's VBUS (pin 40).

In the same vein, you can also construct a


Raspberry Pi Pico Weather Station. Here is how to
do it.

If you need to get your Pico Weather Station up


and running quickly, you can download the
compiled UF2 construct file. Be aware that using
the compiled files prevents you from changing the
signal pins or changing the text.

1. Download weatherstation.uf2 from the web.

61
2. Disconnect the Raspberry Pi and Pico board
from each other.

3. While connecting your Pico board to your Pi,


hold down the BOOTSEL button. As removable
files, the RPI-RP2 and a pop up should be shown.

4. From your downloads folder in the file


manager, drag weatherstation.uf2 and drop it in
your Pico, which is labeled as RPI-RP2.

In a few minutes, the temperature and humidity


of your room should be reflected on the LCD
panel.

With this process, you'll get the same result: an


LCD that shows humidity and temperature. You

62
will, however, discover how to compile the Pico
board's source code. The pico-sdk simple
installation for beginners is also included in this
form. or users that are starting from the ground
up. Go to the “Getting started with Raspberry Pi
Pico C/C++ dev” PDF here to learn more about
the installation process with examples.

Carry out the following steps

1. On your Raspberry Pi desktop, open a Terminal


(or press Ctrl-T).

2. We'll start by creating a directory and


replicating the code required for the Pico board's
C/C++ compilation with the commands belo

63
mkdir weather-station
cd weather-station
git clone -b master
https://github.com/raspberrypi/pico-sdk.git
cd pico-sdk
git submodule update --init
cd ..
git clone https://github.com/carolinedunn/pico-
weather-station

3. Set up cmake to use the proper Pico


dependencies. This procedure can take up to 5
minutes on a Raspberry Pi 4.

sudo apt update

64
sudo apt install cmake gcc-arm-none-eabi build-
essential

4. Now is an excellent time to investigate the


source code for our weather station

Weatherstation.c Code Notes

• The main source file for our project


today is weatherstation.c.

• Line 17: We set up our Pico so that it


can read our DHT from GPIO15. You
can set up multiple DHTs or select a
different GPIO pin here.

65
• Line 199-200: Because this printf
statement is only for troubleshooting
purposes, it can only be accessed
through minicom. In the
troubleshooting section, we'll go over
accessing readings via minicom.

• Line 202: This weather station will


display Fahrenheit readings by default,
but you can change it to Celsius.

• Show an updated temperature at 2-


second intervals on line 211. (or 2000
milliseconds).

Compile the C/C++ code and transfer it to Pico

66
5. To create your UF2 file, use the commands
below in the same Step 3 terminal.

cd pico-weather-station
mkdir build
cd build
export PICO_SDK_PATH=../../pico-sdk
cmake ..
make

Afterward, carry out these steps

1. Navigate to the home>pi>weather-


station>pico-weather-station>build directory.

67
2. Disconnect your Raspberry Pi and Pico board
from each other.

3. While connecting your Pico board to your Pi,


keep the BOOTSEL button pressed. As removable
media, you should see RPI-RP2 and a pop-up.

4. Drag the weatherstation.uf2 file from your


downloads folder to your Pico, which is labeled
RPI-RP2, in your file manager.

Your room's humidity and temperature should


appear on the LCD screen in a matter of seconds.

68
Using DC Motors With Your
Raspberry Pi Pico

Despite its small size, the Raspberry Pi Pico is a


versatile board that can be used to build both
small and large projects. Robotics is an example of
this type of project, and it necessitates the use of
motors. So, how do we power DC motors with the

69
Raspberry Pi Pico? Is it possible to bind them
directly to the GPIO? No, it's not.

The GPIO pins on the Pico cannot deliver the


current required to drive a DC motor. Even if we
try, there is a good chance that the Pico will be
harmed. We'll need a motor controller to serve as
a link between the DC motor and the Pico to
accomplish our goal. Two Pico GPIO pins will be
turned off and on, and they will power the motor
controller, which will turn off and on two outputs
that will drive the motor.

This project will include the following items.

• MicroPython on a Raspberry Pi Pico


(see how to set up Raspberry Pi Pico)

70
• Thonny is already loaded on your
computer

• Breadboard, half-size or full-size

• Board for controlling a motor. A


DRV8833 chip was used for this
process. Chips such as the L9110S or
L298 are also suitable.

• 4 pairs of male-to-male jumper wires

• DC Motor, 5V / 6V A micro gear metal


motor was used in our trial, but a
normal DC hobby motor would also
work. The motor will need two male-

71
to-male jumper wires for the
breadboard link.

Hardware Setup of a DC Motor on


a Raspberry Pi Pico

The chip we're using is a DRV8833, and this


particular version was designed for breadboards.
Other models, such as the one for robot
embedding, are available. Other motor
controllers, such as the L9110S and L298D, are
available on the market and are inexpensive and
basic robotics components. It's worth noting that
all motor controllers use the same input and
output conventions. Place the Raspberry Pi Pico

72
on the breadboard with the micro USB port
hanging over the top.

1. Arrange the pins of the DRV8833 motor


controller on the breadboard so that they are on
either side of the central channel.

2. Connect the Pico's VBUS pin to the DRV8833's


VCC pin with a jumper wire. This will allow the
motor controller to be powered directly from the
USB 5V supply.

3. Connect the GND pin on the Pico to the GND


pin on the DRV8833.

4. Connect the DRV8833's IN1 to Pico's GPIO 14.

73
5. Connect GPIO 15 on the Pico to IN2 on the
DRV8833.

6. Connect the motor pins to OUT1 and OUT2. The


category does not matter in this project.

Software Setup of a DC Motor with the Raspberry


Pi Pico

Attach the Pico and launch the Thonny app


number that is used as outputs for the control of
the DRV8833 motor controller once the circuit is
complete.

motor1a = Pin(14, Pin.OUT)


motor1b = Pin(15, Pin.OUT)

74
Continue thus;

1. Make a function that causes the motor to move


forward. To perform this operation, we'll need
one pin to pull low and the other to pull high. This
will inform the motor controller of our desired
direction, causing the corresponding output pins
to obey the cue. The motor would then be forced
to drive in the desired direction.

def forward():
motor1a.high()
motor1b.low()

2. Make a function that allows you to go


“backward.” This sets the GPIO pin to the reverse
75
state, causing the motor to turn in the opposite
direction.

def backward():
motor1a.low()
motor1b.high()

3. Make a motor-stopping function. The motor


controller is told to avoid all motor activity by
pulling the two pins low.

def stop():
motor1a.low()
motor1b.low()

76
4. Create a final "test" function that will call up all
of the previous functions and run a test sequence
that will move the motor "forward" for two
seconds, then "backward" for another two
seconds before stopping it.

def test():
forward()
utime.sleep(2)
backward()
utime.sleep(2)
stop()

5. Make a for loop that repeats the test function


five times.

77
 for in range(5):
 test()

Save the code to the Pico as motor.py, then run it


by clicking the green arrow. The motor will spin in
both directions five times.

78
Chapter 6: Using a Raspberry Pi
Pico and an Ultrasonic Sensor

Ultrasonic sensors, use basic measurements and


sound waves to determine the distance between
their locations and the objects in front of them.
They are often used in robotics to ensure that
robots do not roll or walk into an obstacle. We'll
79
use an HC-SR04+, an ultrasonic distance sensor, to
quickly determine object distances from our
Raspberry Pi Pico in this tutorial.

This project will include the following items:

 A Raspberry Pi Pico with MicroPython


installed
 Thonny, already installed on your
computer
 Ultrasonic Sensor HC-SR04P or HC-
SR04+
 Breadboard, half-size or full-size
 4 pairs of male-to-male jumper wires
 Ultrasonic Sensor Hardware Setup on
Raspberry Pi Pico

80
Hardware Setup of Ultrasonic
Sensor on Raspberry Pi Pico

This build only uses an ultrasonic sensor that is


compatible with the Raspberry Pi Pico's GPIO's 3V
logic. The 3V and 5V logic are compatible with the
HC-SR04+ and HC-SR04P. This makes them perfect
for projects involving the Raspberry Pi, Arduino,
and Raspberry Pi Pico.

Ultrasonic Sensor Software Setup on Raspberry Pi


Pico

Attach your Raspberry Pi Pico after completing


the circuit and open the Thonny app.

81
1. Import the Pin class from the machine library,
followed by the utime library. The GPIO pins are
regulated by the Pin class, and the time library is a
time-based feature library.

from machine import Pin


import utime

2. Create two new objects: echo and trigger.


These objects allow the ultrasonic sensor to
communicate with the Pico's GPIO pins. Our
trigger pin, for example, is used to deliver the
current pulse, making it an output pin. Echo is our
input pin because it receives the pulse that has
been sent.

82
trigger = Pin(3, Pin.OUT)
echo = Pin(2, Pin.IN)

3. Create a function called ultra() that contains all


of the code needed to take a reading.

def ultra():

4. Perform a two-microsecond pause after pulling


the trigger pin low to ensure it is not active.

trigger.low()
utime.sleep_us(2)

83
5. Pull the trigger pin high for five microseconds
before lowering it. Before turning off the pulse,
this will send a short wave out of the ultrasonic
sensor.

trigger.high()
utime.sleep_us(5)
trigger.low()

6. To check the echo pin, create a while loop. If no


echo pulse is received, set the variable signal off
to a microseconds timestamp.

while echo.value() == 0:
signaloff = utime.ticks_us()

84
7. Create a new while loop to check for the receipt
of an echo. The present microseconds timestamp
will be stored in the signalon variable as a result
of this.

while echo.value() == 1:
signalon = utime.ticks_us()

8. Create a new variable called time passed that


will store the total time it took the pulse to leave
the sensor, travel to the object and return as an
echo.

timepassed = signalon - signaloff

85
9. Add a new variable called distance. The
response to the equation will be saved in this
variable. We multiply the journey time (343.2 m/s
= 0.0343 cm per microsecond) by the speed of
sound (343.2 m/s = 0.0343 cm per microsecond).
The product of the equation is then divided by
two because we don't need to know the total
distance traveled. All we care about is the
distance between the object and the sensor.

distance = (timepassed * 0.0343) / 2

10. Pring the distance in a message to the Python


Shell.

print("The distance from object is ",distance,"cm")

86
11. We now create a loop to run the function
every second outside of it.

while True:
ultra()
utime.sleep(1)

The Codes in its Complete Form

from machine import Pin

● import utime
● trigger = Pin(3, Pin.OUT)
● echo = Pin(2, Pin.IN)
● def ultra():
● trigger.low()

87
● utime.sleep_us(2)
● trigger.high()
● utime.sleep_us(5)
● trigger.low()
● while echo.value() == 0:
o signaloff = utime.ticks_us()
● while echo.value() == 1:
o signalon = utime.ticks_us()
● timepassed = signalon - signaloff
● distance = (timepassed * 0.0343) / 2
● print("The distance from object is
",distance,"cm")
● while True:
● ultra()
● utime.sleep(1)

88
Save the file to the Pico as code.py, then run it by
clicking the green arrow. In the Python Shell, the
distance will be printed every second.

How to Use a Raspberry Pi Pico


With a Motion Sensor

The Raspberry Pi Pico has many GPIO pins that we


can easily customize with code to create our
inputs and outputs. In this tutorial, we'll learn how

89
to work with outputs, such as an LED, and inputs,
such as a sensor. We'll end up with a 16-line
MicroPython motion detector in the end. Before
beginning this project, make sure your Pico is set
up and tested.

We'll learn how to use the Pico's GPIO pins as


digital outputs and inputs with low and high as a
simple control method in this section.

The circuit in this project has an additional


feature, a Passive Infrared (PIR) sensor, which is
commonly used in security systems to detect
movement. In this project, it will serve the same
purpose. Furthermore, when the sensor is
triggered, it will switch on the LED.

90
 A PIR sensor
 3 jumper wires (female to male)

Procedure

1. Position the Raspberry Pi Pico on the


breadboard so that it sits on top of the central
channel. Ensure that one of the breadboard's
ends has a Micro USB port.

2. In the breadboard, place a 330 Ohm resistor.


One of its legs should be connected to the
breadboard's – rail, while the other leg should be
connected to GND pin 38. By doing so, we'll have
a GND rail with all of the rail's pins attached to
GND.

91
3. Place the anode (long leg) of an LED on pin 34
of the breadboard, and the short leg on the GND
rail. The circuit is completed after these steps are
completed successfully.

The PIR sensor has three pins: GND, OUT, and


VCC. The VCC pin receives power from the Pico,
which is 33V.

4. Using a jumper wire, connect VCC from the PIR


to the 3.3V pin (pin 37). The resistor is right next
to Pin 37.

5. Connect the PIR's OUT pin to the Pico's pin 21


with another jumper wire.

92
6. Connect the PIR's GND pin to the GND rail on
the breadboard.

7. Once the circuit is complete, connect the


Raspberry Pi Pico to your computer with a micro
USB cable, then launch the Thonny app.

The project will then be coded. Here, we add our


PIR sensor, input, and a conditional test to see if
the sensor is activated.

The next step is coding the project. Here we build


on the code, to include our PIR sensor, input, and
a conditional test to ascertain if the sensor is
triggered.

93
1. Import the Pin class from the machine library,
then utime. These libraries help us to keep track
of the progress of our project and communicate
with the GPIO in a more productive manner.

from machine import Pin


import utime

2. Create an object called "led" that will be used


to connect our code to the physical GPIO pin. In
our case, it will make GPIO 28 (which corresponds
to pin 34 on the board) the output pin, from
which current will flow from the Raspberry Pi
Pico's GPIO to the LED. Then, using the piece, we'll
tell the GPIO pin to pull low. To put it another

94
way, we'll make sure the GPIO pin is turned off at
the start of the project.

led = Pin(28, Pin.OUT)

3. Create another object, “pir”. This object is used


to bind our code to the GPIO pin that was used for
the PIR OUT link. The PIR sensor OUT pin is pulled
high by default, but when motion is detected, the
PIR sensor pulls the OUT pin low. To make sure
the sensor is working properly, we must first set
the pin as an input and then pull the GPIO pin
high.

pir = Pin(16, Pin.IN, Pin.PULL_UP)

95
4. Make sure the LED is turned off at the start of
the project, then wait three seconds before
continuing. These two lines ensure that the LED
does not activate twice. It also gives the sensor a
chance to settle before being used.

led.low()
utime.sleep(3)

5. For a brief period of time The current value of


the GPIO pin that is used for the PIR sensor is
printed using a print feature in a true loop, which
has no end. If there is no movement, it will return
1, but if there is, it will return 0.

while True:

96
print(pir.value())

6. Write a conditional test to determine the value


stored in the pir.value variable. If the value is 0,
then the movement has been observed, and a
message will be printed to the Python Shell. As a
result, the LED will turn on (high) and then pause
for five seconds, remaining on for that time.

if pir.value() == 0:
print("LED On")
led.high()
utime.sleep(5)

97
7. If no movement is detected, the final part of
the conditional test will be activated. Add a line to
switch off (low) the LED, which then pauses for
0.2 seconds, and uses an Else condition to print a
message to the Python Shell. As the conditional
test runs again, the loop will repeat.

else:
print("Waiting for movement")
led.low()
utime.sleep(0.2)

8. Select to save the code to the Pico device by


clicking Save. Save the file as PIR.py after giving it
a name. Your code would look something like this:

98
from machine import Pin
import utime
led = Pin(28, Pin.OUT)
pir = Pin(16, Pin.IN, Pin.PULL_UP)
led.low()
utime.sleep(3)
while True:
print(pir.value())
if pir.value() == 0:
print("LED On")
led.high()

utime.sleep(5)
else:

99
print("Waiting for movement")
led.low()
utime.sleep(0.2)

9. To run the code, click the green play/arrow


button. The Python Shell will update, displaying
"LED On" and "Waiting for movement." PIR
sensors are extremely sensitive. It's possible that
you'll see some false triggers at first, but this will
pass.

100
Connecting a Raspberry Pi Pico to
an Analog Joystick

You might want to use an analog joystick in your


Raspberry Pi Pico project for a variety of reasons.
Perhaps as a navigational aid or for the creation of
a game. Whatever your motivation, attaching
your Raspberry Pi Pico to an analog stick is as easy
as coding in MicroPython.

101
Materials needed

Items needed

• Raspberry Pi Pico with pins.

• Analog thumb joystick with 5-pin


interface. There are various variations.

• Breadboard. This is optional because


you can attach your joystick directly to
the pins.

• Five female-to-female jumper cables. If


you’re using a breadboard, you'll need
a female-to-male.

102
The Process

1. Connect the 5 pins of the joystick to the Pico as


follows::

• +5V to 3V3 Out (physical pin 36). A 5V


joystick can fit with Pico's 3V3 power
rating.

• GND to GND (Any GND pin)

• VRy to GP26 / ADC0 (physical pin 31)

• VRx to GP27 / ADC1 (physical pin 32)

103
• SW to GP16 (physical pin 21). This
should work for the majority of GPIo
pins.

104
Chapter 7: MicroPython
Joystick Programming for
Raspberry Pi Pico
When you press down on an analog thumbstick,
you get three devices in one: an X axis
potentiometer, a Y axis potentiometer, and a
digital momentary button. We'll write some easy
code to see where the joystick is pointing in the
section below.

1. Open your MicroPython IDE and create a new


program, most likely Thonny.

105
2. Import the required modules, including Pin,
ADC from machine, and utime

from machine import Pin, ADC

import utime

Later, we'll use the utime.sleep function to add a


delay to a loop that reads the button state.

3. Assign the xAxis and yAxis variables to the GP


pins 27 and 26 for each.

xAxis = ADC(Pin(27))

106
yAxis = ADC(Pin(26))

4. Assign a button variable to a Pin object.

button = Pin(16,Pin.IN, Pin.PULL_UP)

The GP number, the mode (which in our case is


input), and whether it has a pull-up or pull-down
resistor are the three arguments for the Pin
object. It should be in input mode and pulling up.

5. Create a loop that checks and prints the x, y,


and button values.

while True:

107
xValue = xAxis.read_u16()

yValue = yAxis.read_u16()

buttonValue= button.value()

print(str(xValue) +", " + str(yValue) + " -- " +


str(buttonValue))

108
utime.sleep(0.1)

6. As you move the joystick and press the button,


run the code and watch the results in the
MicroPython shell. If you don't switch or click the
joystick, the X and Y values will most likely be
about 32,000 to 33,000, and the button value will
be 1. The X value would be in the 300 to 500
range if you move to the left, and about 65,000 if
you move to the right. If you point up, you'll be in
the 300 to 500 range, and if you point down, you'll
be about 65,000. When you press the button, it
will have a value of 0 for as long as you keep it
down.

109
7. To save space, halt the execution and delete
the print statement.

8. Create variables for the X, Y, and button status


in plain English. Put them in the loop and give
them the same default values as a joystick that
hasn't been touched.

xStatus = "middle"

yStatus = "middle"

buttonStatus = "not pressed"

110
9. Within the loop, use if/then statements to
correctly label the joystick and button status.

if xValue <= 600:

xStatus = "left"

elif xValue >= 60000:

xStatus = "right"

if yValue <= 600:

yStatus = "up"

elif yValue >= 60000:

yStatus = "down"

111
if buttonValue == 0:

buttonStatus = "pressed"

11. To print the variables, use a print statement


above the sleep command.

print("X: " + xStatus + ", Y: " + yStatus + " -- button


" + buttonStatus)

This is how the final code should look:

from machine import Pin, ADC

import utime

112
xAxis = ADC(Pin(27))

yAxis = ADC(Pin(26))

button = Pin(16,Pin.IN, Pin.PULL_UP)

while True:

xValue = xAxis.read_u16()

yValue = yAxis.read_u16()

buttonValue = button.value()

xStatus = "middle"

yStatus = "middle"
113
buttonStatus = "not pressed"

if xValue <= 600:

xStatus = "left"

elif xValue >= 60000:

xStatus = "right"

if yValue <= 600:

yStatus = "up"

elif yValue >= 60000:

yStatus = "down"

if buttonValue == 0:
114
buttonStatus = "pressed"

print("X: " + xStatus + ", Y: " + yStatus + " --


button " + buttonStatus)

utime.sleep(0.1)

Let us do more exciting things with our


Raspberry Pi Pico!

How to Play Music with a Buzzer


(Piezo) on a Raspberry Pi Pico

115
A low-cost piezo buzzer can be a great addition to
any Raspberry Pi Pico project, whether it's an
alarm clock that wakes you up to, a game that
beeps when you lose a turn or a beautiful display
that plays an 8-bit music. MicroPython makes
programming these low-cost buzzers a breeze.
They can also change the pitch to make musical
sounds.

Piezo buzzers come in two varieties: passive and


active. The active buzzers will create a noise if
they are connected to power without a
microcontroller, while the passive buzzers will
remain silent. As a result, even though both styles
worked for us, the Passive are favored because
they give a wider sound range.

116
The Pico can be connected to a Piezo buzzer and
programmed using MicroPython to generate a
short tune as shown below.

Items needed

• Raspberry Pi Pico.

• We used two jumper wires, one


female-to-female and the other male-
to-female. If you're using a
breadboard, you'll need male-to-male
jumpers.

• We used a passive piezo buzzer for our


case. It's also possible that an active
buzzer would function.

117
How to Attach a Buzzer to a
Raspberry Pi Pico

This is as straightforward as it comes. Connect the


ground pin of the buzzer to the GND pin of a Pico.
Attach the positive buzzer pin to either of the
Pico's regular GPIO pins; we used GP15 in our
case. The pins on the passive buzzer we used were
not labeled as positive or negative. With either
one plugged into either of the Pico pins, they
worke

Buzzer Programming

118
1. Import PWM and Pin from the machine library
first, followed by sleep from the utime library.

from machine import Pin, PWM

from utime import sleep

2. On Pin 15, initialize PWM (also known as pulse


width modulation) before assigning it to the
variable buzzer.

buzzer = PWM(Pin(15))

3. Give the buzzer a frequency property. You must


choose a number between ten and twelve
thousand. The higher the amount, the higher the

119
pitch of the sound will be. We have the option of
selecting 500.

buzzer.freq(500)

4. Set the duty u16 property of the buzzer object


to 1000. This raises the buzzer's volume to its full
level. A lower value lowers the volume, while 0
means there is no echo. When you know how
quiet these buzzers are, their full volume is not
actually that loud.

buzzer.duty_u16(1000)

5. After a one-second delay, set duty to 0 to turn


off the sound. If this is not set, the buzz will

120
continue to be heard even after the program has
finished running.

sleep(1)

buzzer.duty_u16(0)

The final code should look something like this:

• from machine import Pin, PWM

• from utime import sleep

• buzzer = PWM(Pin(15))

• buzzer.freq(500)

121
• buzzer.duty_u16(1000)

• sleep(1)

• buzzer.duty_u16(0)

122
Chapter 8: Playing Musical
Notes
You may use various frequencies to produce a
variety of musical notes and they are all possible.
A few lists of frequencies for musical notes can be
found online, and the majority of them can be
traced back to Brett Hagman’s Arduino tone
library on Github. These values will be used to
build a song list that we can use with our previous
code.

Let us begin!

1. Import the required libraries and set pin 15 to


PWM.
123
from machine import Pin, PWM
from utime import sleep

buzzer = PWM(Pin(15))

2. Create a dictionary called notes with the


following values.

● tones = {

● "B0": 31,

● "C1": 33,

124
● "CS1": 35,

● "D1": 37,

● "DS1": 39,

● "E1": 41,

● "F1": 44,

● "FS1": 46,

● "G1": 49,

● "GS1": 52,

● "A1": 55,

● "AS1": 58,
125
● "B1": 62,

● "C2": 65,

● "CS2": 69,

● "D2": 73,

● "DS2": 78,

● "E2": 82,

● "F2": 87,

● "FS2": 93,

● "G2": 98,

● "GS2": 104,
126
● "A2": 110,

● "AS2": 117,

● "B2": 123,

● "C3": 131,

● "CS3": 139,

● "D3": 147,

● "DS3": 156,

● "E3": 165,

● "F3": 175,

● "FS3": 185,
127
● "G3": 196,

● "GS3": 208,

● "A3": 220,

● "AS3": 233,

● "B3": 247,

● "C4": 262,

● "CS4": 277,

● "D4": 294,

● "DS4": 311,

● "E4": 330,
128
● "F4": 349,

● "FS4": 370,

● "G4": 392,

● "GS4": 415,

● "A4": 440,

● "AS4": 466,

● "B4": 494,

● "C5": 523,

● "CS5": 554,

● "D5": 587,
129
● "DS5": 622,

● "E5": 659,

● "F5": 698,

● "FS5": 740,

● "G5": 784,

● "GS5": 831,

● "A5": 880,

● "AS5": 932,

● "B5": 988,

● "C6": 1047,
130
● "CS6": 1109,

● "D6": 1175,

● "DS6": 1245,

● "E6": 1319,

● "F6": 1397,

● "FS6": 1480,

● "G6": 1568,

● "GS6": 1661,

● "A6": 1760,

● "AS6": 1865,
131
● "B6": 1976,

● "C7": 2093,

● "CS7": 2217,

● "D7": 2349,

● "DS7": 2489,

● "E7": 2637,

● "F7": 2794,

● "FS7": 2960,

● "G7": 3136,

● "GS7": 3322,
132
● "A7": 3520,

● "AS7": 3729,

● "B7": 3951,

● "C8": 4186,

● "CS8": 4435,

● "D8": 4699,

● "DS8": 4978

● }

133
3. Make a note list or an array for your song. Use
the letter P to represent the pauses in the song.
Each note should be enclosed in quotation marks.

Song =
["E5","G5","A5","P","E5","G5","B5","A5","P","E5",
"G5","A5","P","G5","E5"]

4. Make a play tone function that will play any


frequency at maximum volume.

def playtone(frequency):

buzzer.duty_u16(1000)

buzzer.freq(frequency)
134
5. Make a function called bequiet that sets
duty_u16 to 0 and turns off the buzzer.

def bequiet():

buzzer.duty_u16(0)

6. Make a playsong function that you can use to


navigate through the notes array, pausing or
playing when it reaches P.

def playsong(mysong):

135
for i in range(len(mysong)):

if (mysong[i] == "P"):

bequiet()

else:

playtone(tones[mysong[i]])

sleep(0.3)

bequiet()

The first step is to construct a loop that loops


through the values of the mysong list or array. It
will start, then go silent if the value is P. If it isn't,
a sound will be played. It's worth noting that a

136
numeric frequency value is needed before a tone
can be played. As a consequence, we must extract
each note number from the tonal list. For
example, if we just call playtone(mysong[i]), it will
fail because it will try to play the string "E5"
instead of the integer 659, which is required.

The machine will sleep for 0.3 seconds between


each pause or sound. If you want a quicker tempo,
lower the time. If you want a slower pace,
increase the speed.

7. Use the song parameter to call the playsong


function.

playsong(song)

137
When you run this code, the buzzer will play a
familiar sound. The full code should look like this:

from machine import Pin, PWM

from utime import sleep

buzzer = PWM(Pin(15))

● tones = {

● "B0": 31,

● "C1": 33,

● "CS1": 35,

138
● "D1": 37,

● "DS1": 39,

● "E1": 41,

● "F1": 44,

● "FS1": 46,

● "G1": 49,

● "GS1": 52,

● "A1": 55,

● "AS1": 58,

● "B1": 62,
139
● "C2": 65,

● "CS2": 69,

● "D2": 73,

● "DS2": 78,

● "E2": 82,

● "F2": 87,

● "FS2": 93,

● "G2": 98,

● "GS2": 104,

● "A2": 110,
140
● "AS2": 117,

● "B2": 123,

● "C3": 131,

● "CS3": 139,

● "D3": 147,

● "DS3": 156,

● "E3": 165,

● "F3": 175,

● "FS3": 185,

● "G3": 196,
141
● "GS3": 208,

● "A3": 220,

● "AS3": 233,

● "B3": 247,

● "C4": 262,

● "CS4": 277,

● "D4": 294,

● "DS4": 311,

● "E4": 330,

● "F4": 349,
142
● "FS4": 370,

● "G4": 392,

● "GS4": 415,

● "A4": 440,

● "AS4": 466,

● "B4": 494,

● "C5": 523,

● "CS5": 554,

● "D5": 587,

● "DS5": 622,
143
● "E5": 659,

● "F5": 698,

● "FS5": 740,

● "G5": 784,

● "GS5": 831,

● "A5": 880,

● "AS5": 932,

● "B5": 988,

● "C6": 1047,

● "CS6": 1109,
144
● "D6": 1175,

● "DS6": 1245,

● "E6": 1319,

● "F6": 1397,

● "FS6": 1480,

● "G6": 1568,

● "GS6": 1661,

● "A6": 1760,

● "AS6": 1865,

● "B6": 1976,
145
● "C7": 2093,

● "CS7": 2217,

● "D7": 2349,

● "DS7": 2489,

● "E7": 2637,

● "F7": 2794,

● "FS7": 2960,

● "G7": 3136,

● "GS7": 3322,

● "A7": 3520,
146
● "AS7": 3729,

● "B7": 3951,

● "C8": 4186,

● "CS8": 4435,

● "D8": 4699,

● "DS8": 4978

● }

● song =
["E5","G5","A5","P","E5","G5","B5","A5","P","E5",
"G5","A5","P","G5","E5"]

147
● def playtone(frequency):

● buzzer.duty_u16(1000)

● buzzer.freq(frequency)

● def bequiet():

● buzzer.duty_u16(0)

● def playsong(mysong):

● for i in range(len(mysong)):

● if (mysong[i] == "P"):

● bequiet()
148
● else:

● playtone(tones[mysong[i]])

● sleep(0.3)

● bequiet()

● playsong(song)

Since you now know how to play music using the


piezo buzzer and the Raspberry Pi Pico, you can
now make it play any song as far as you have the
notes.

149
Chapter 9: Making Use of
the Raspberry Pi Pico With
an Arduino Board
The Arduino IDE, which uses “Arduino Language,”
a variant of C++, is now a third way to write code
for our Raspberry Pi Pico. Since Arduino has been
around for so long, there are a plethora of pre-
existing "sketches" (the Arduino term for
programs) and tutorials available. If you've ever
worked with Arduino boards, you're probably
already familiar with the IDE and language. In this
guide, we'll show you how to set up your
Windows or Ubuntu computer so you can

150
program your Raspberry Pi Pico with Arduino
code.

Using the Arduino For Windows

1. On the web, search for, download, and Install


the pico-setup-windows package. This is a big file
to download.

2. Run the installation program.

3. Double-check that all of the components have


been chosen. This will download and install about
360MB of files and applications to your computer.
Included are the files needed to compile C/C++
files, as well as Visual Studio Code and Git version
control.

151
4. To install all of the applications, click Install.
This can take some time, and it can appear to be
stuck at times, but be patient.

5. Download and install the Arduino IDE on your


computer. We went with version 1.8.13, but the
beta of version 2.0 still works.

6. Navigate to File >> Preferences in the Arduino


application.

7. Add this weblink to the additional board’s


manager and click OK.

https://github.com/earlephilhower/arduino-
pico/releases/download/global/package rp2040
index.json

152
https://github.com/earlephilhower/arduino-
pico/releases/download/global/package rp2040
index.json

8. Select Tools >> Board >> Boards Manager from


the menu bar.

9. In the search box, type "pico" and then select


the Raspberry Pi Pico / RP2040 board to install.
Another massive update, about 300MB in size, will
be triggered as a result of this.

10. Select Raspberry Pi Pico from Tools >> Board


>> Raspberry Pi RP2040 Boards.

11. Plug in your Raspberry Pi Pico and look for the


COM port it's connected to in Device Manager.

153
Set the COM port for the Raspberry Pi Pico under
Tools >> Port.

13. Go to Files >> Examples >> Fundamentals >>


Blink to verify that we can program the Arduino.

14. To upload the code to the Raspberry Pi Pico,


click Upload. The default Blink sketch on the
Raspberry Pi Pico flashes the green LED next to
the micro USB port.

When the upload is done, the output window will


notify us. The green LED on your Raspberry Pi Pico
will flash once per second if you look at it closely.

154
Making Use of the Arduino For
Ubuntu

This guide was created with Ubuntu, but the same


instructions should operate with other Debian-
based distributions like Raspberry Pi OS.

1. Use wget to download the official Pico setup


script from a terminal.

https://raw.githubusercontent.com/raspberrypi/p
ico-setup/master/pico setup.sh

2. Modify the downloaded file in the same


terminal to make it executable.

$ chmod +x pico setup.sh

155
3. Start the installation with pico setup.sh. If
prompted, type your sudo password.

./pico setup.sh $./pico setup.sh $./pico setup.

4. Install the Arduino IDE on your computer after


downloading it. We went with version 1.8.13, but
the beta of version 2.0 still works.

5. Launch a terminal and add your user to the


"dialout" group. This community will interact with
Arduino-compatible devices. Your account will be
used automatically if you use "$USER."

usermod -a -G dialout "$USER" $ sudo usermod -a


-G dialout "$USER"

156
6. To make the changes take effect, log out or
restart your computer.

7. Go to File >> Preferences in the Arduino


application.

8. Add this line to the additional board’s manager


and click OK.

https://github.com/earlephilhower/arduino-
pico/releases/download/global/package rp2040
index.json

9. To manage your boards, go to Tools >> Board


>> Boards Manager.

157
10. In the search box, type "pico" and then select
the Raspberry Pi Pico / RP2040 board to install.
Another massive update, about 300MB in size, will
be triggered as a result of this.

11. Select Raspberry Pi Pico from Tools >> Board


>> Raspberry Pi RP2040 Boards.

12. Connect your Raspberry Pi Pico to your


computer

13. Use a command to look for a USB device that


says, Raspberry Pi Pico. It was ttyACM0 in our
case.

dmesg $

158
14. Go to Files >> Examples >> Fundamentals >>
Blink to verify that we can program the Arduino.

15. To upload the code to the Raspberry Pi Pico,


click Upload. The default Blink sketch on the
Raspberry Pi Pico flashes the green LED next to
the micro USB port.

When the upload is done, the output window will


notify us. The green LED on your Raspberry Pi Pico
will flash once per second if you look at it closely.

159
Resetting Your Raspberry Pi Pico
Using a Button

The Raspberry Pi Pico is a fantastic piece of


technology, but it does have one flaw: it lacks a
reset button. This function is critical because our
codes may be incorrect or the Pico firmware may
need to be flashed.

160
If this occurs, we must disconnect and reconnect
the Pico in order for it to reset. Pulling out the
micro USB lead repeatedly, which has a fixed
insertion number rating will wear it out. If the Pico
is connected to a powerful USB hub with off/on
buttons, we can simply press the off/on buttons.
What are our options if we don't want this?

We can make a simple button for resetting our


Pico without any code and just a few instruments.

Items needed

• 2 pairs of male-to-male jumper wires

• A Raspberry Pi Pico.

161
• Push-buttons

• A breadboard that is half the size of a


full-size breadboard

Procedure

1. Place the Raspberry Pi Pico on the breadboard


so that the micro USB port hangs over the end of
the breadboard.

2. Add a push button to allow it to sit over the


central break on the breadboard.

3. Connect the RUN pin to be in line with the


jumper wire. Then attach the wire's other end to
the top left corner of the button.

162
4. Connect the other jumper wire to be in line
with the GND. Then connect the wire's other end
to the top right corner of the button.

5.Connect your computer to your Raspberry Pi


Pico and start the Thonny app. MicroPython will
be started automatically by the Shell, which is
located at the bottom of the window.

The RUN pin will be pulled down and forced to


reset if the breadboard's button is pressed. Click
the Stop button to return to the MicroPython
shell. If something goes wrong with your code,
follow these measures to get back on.

163
This button makes flashing a C/C++ project or
MicroPython firmware much simpler.

1. Press and hold BOOTSEL and the push button at


the same time.

2. Press and hold the push button until the RPI-


RP2 drive appears, then press and hold the
BOOTSEL button.

164
3. Save your MicroPython firmware UF2 file or
your C/C++ project to the drive. This will cause it
to reboot automatically.

165
Conclusion
This guide has detailed extensively how to
maximize the Raspberry Pi Pico to its full
potential, especially for newbies. Hopefully, you
get acclimatized to the procedures and get
creative with your Raspberry Pi Pico.

166

You might also like