Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

Using Python with virtual environments | The MagPi #148

22 November 2024 at 00:17

Raspberry Pi OS comes with Python pre-installed, and you need to use its virtual environments to install packages. The latest issue of The MagPi, out today, features this handy tutorial, penned by our documentation lead Nate Contino, to get you started.

Raspberry Pi OS comes with Python 3 pre-installed. Interfering with the system Python installation can cause problems for your operating system. When you install third-party Python libraries, always use the correct package-management tools.

On Linux, you can install python dependencies in two ways:

  • use apt to install pre-configured system packages
  • use pip to install libraries using Python’s dependency manager in a virtual environment
It is possible to create virtual environments inside Thonny as well as from the command line

Install Python packages using apt

Packages installed via apt are packaged specifically for Raspberry Pi OS. These packages usually come pre-compiled, so they install faster. Because apt manages dependencies for all packages, installing with this method includes all of the sub-dependencies needed to run the package. And apt ensures that you don’t break other packages if you uninstall.

For instance, to install the Python 3 library that supports the Raspberry Pi Build HAT, run the following command:

$ sudo apt install python3-build-hat

To find Python packages distributed with apt, use apt search. In most cases, Python packages use the prefix python- or python3-: for instance, you can find the numpy package under the name python3-numpy.

Install Python libraries using pip

In older versions of Raspberry Pi OS, you could install libraries directly into the system version of Python using pip. Since Raspberry Pi OS Bookworm, users cannot install libraries directly into the system version of Python.

Attempting to install packages with pip causes an error in Raspberry Pi OS Bookworm

Instead, install libraries into a virtual environment (venv). To install a library at the system level for all users, install it with apt.

Attempting to install a Python package system-wide outputs an error similar to the following:

$ pip install buildhat
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    For more information visit http://rptl.io/venv

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

Python users have long dealt with conflicts between OS package managers like apt and Python-specific package management tools like pip. These conflicts include both Python-level API incompatibilities and conflicts over file ownership.

Starting in Raspberry Pi OS Bookworm, packages installed via pip must be installed into a Python virtual environment (venv). A virtual environment is a container where you can safely install third-party modules so they won’t interfere with your system Python.

Use pip with virtual environments

To use a virtual environment, create a container to store the environment. There are several ways you can do this depending on how you want to work with Python:

per-project environments

Create a virtual environment in a project folder to install packages local to that project

Many users create separate virtual environments for each Python project. Locate the virtual environment in the root folder of each project, typically with a shared name like env. Run the following command from the root folder of each project to create a virtual environment configuration folder:

$ python -m venv env

Before you work on a project, run the following command from the root of the project to start using the virtual environment:

$ source env/bin/activate

You should then see a prompt similar to the following:

$ (.env) $

When you finish working on a project, run the following command from any directory to leave the virtual environment:

$ deactivate

per-user environments

Instead of creating a virtual environment for each of your Python projects, you can create a single virtual environment for your user account. Activate that virtual environment before running any of your Python code. This approach can be more convenient for workflows that share many libraries across projects.

When creating a virtual environment for multiple projects across an entire user account, consider locating the virtual environment configuration files in your home directory. Store your configuration in a folder whose name begins with a period to hide the folder by default, preventing it from cluttering your home folder.

Add a virtual environment to your home directory to use it in multiple projects and share the packages

Use the following command to create a virtual environment in a hidden folder in the current user’s home directory:

$ python -m venv ~/.env

Run the following command from any directory to start using the virtual environment:

$ source ~/.env/bin/activate

You should then see a prompt similar to the following:

$ (.env) $

To leave the virtual environment, run the following command from any directory:

$ deactivate

Create a virtual environment

Run the following command to create a virtual environment configuration folder, replacing <env-name> with the name you would like to use for the virtual environment (e.g. env):

$ python -m venv <env-name>

Enter a virtual environment

Then, execute the bin/activate script in the virtual environment configuration folder to enter the virtual environment:

$ source <env-name>/bin/activate

You should then see a prompt similar to the following:

$ (<env-name>) $

The (<env-name>) command prompt prefix indicates that the current terminal session is in a virtual environment named <env-name>.

To check that you’re in a virtual environment, use pip list to view the list of installed packages:

$ (<env-name>) $ pip list
Package    Version
---------- -------
pip        23.0.1
setuptools 66.1.1

The list should be much shorter than the list of packages installed in your system Python. You can now safely install packages with pip. Any packages you install with pip while in a virtual environment only install to that virtual environment. In a virtual environment, the python or python3 commands automatically use the virtual environment’s version of Python and installed packages instead of the system Python.

Top Tip
Pass the –system-site-packages flag before the folder name to preload all of the currently installed packages in your system Python installation into the virtual environment.

Exit a virtual environment

To leave a virtual environment, run the following command:

$ (<env-name>) $ deactivate

Use the Thonny editor

We recommend Thonny for editing Python code on the Raspberry Pi.

By default, Thonny uses the system Python. However, you can switch to using a Python virtual environment by clicking on the interpreter menu in the bottom right of the Thonny window. Select a configured environment or configure a new virtual environment with Configure interpreter.

The MagPi #148 out NOW!

You can grab the new issue right now from Tesco, Sainsbury’s, Asda, WHSmith, and other newsagents, including the Raspberry Pi Store in Cambridge. It’s also available at our online store, which ships around the world. You can also get it via our app on Android or iOS.

You can also subscribe to the print version of The MagPi. Not only do we deliver it globally, but people who sign up to the six- or twelve-month print subscription get a FREE Raspberry Pi Pico W!

The post Using Python with virtual environments | The MagPi #148 appeared first on Raspberry Pi.

Raspberry Pi product series explained

30 October 2024 at 18:31

As our product line expands, it can get confusing trying to keep track of all the different Raspberry Pi boards out there. Here is a high-level breakdown of Raspberry Pi models, including our flagship series, Zero series, Compute Module series, and Pico microcontrollers.

Raspberry Pi makes computers in several different series:

  • The flagship series, often referred to by the shorthand ‘Raspberry Pi’, offers high-performance hardware, a full Linux operating system, and a variety of common ports in a form factor roughly the size of a credit card.
  • The Zero series offers a full Linux operating system and essential ports at an affordable price point in a minimal form factor with low power consumption.
  • The Compute Module series, often referred to by the shorthand ‘CM’, offers high-performance hardware and a full Linux operating system in a minimal form factor suitable for industrial and embedded applications. Compute Module models feature hardware equivalent to the corresponding flagship models but with fewer ports and no on-board GPIO pins. Instead, users should connect Compute Modules to a separate baseboard that provides the ports and pins required for a given application.

Additionally, Raspberry Pi makes the Pico series of tiny, versatile microcontroller boards. Pico models do not run Linux or allow for removable storage, but instead allow programming by flashing a binary onto on-board flash storage.

Flagship series

Model B indicates the presence of an Ethernet port. Model A indicates a lower-cost model in a smaller form factor with no Ethernet port, reduced RAM, and fewer USB ports to limit board height.

ModelSoCMemoryGPIOConnectivity
Raspberry Pi Model BRaspberry Pi Model BBCM2835256MB, 512MB26-pin GPIO headerHDMI, 2 × USB 2.0, CSI camera port, DSI display port, 3.5mm audio jack, RCA composite video, Ethernet (100Mb/s), SD card slot, micro USB power
Raspberry Pi Model ARaspberry Pi Model ABCM2835256MB26-pin GPIO headerHDMI, USB 2.0, CSI camera port, DSI display port, 3.5mm audio jack, RCA composite video, SD card slot, micro USB power
Raspberry Pi Model B+Raspberry Pi Model B+BCM2835512MB40-pin GPIO headerHDMI, 4 × USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, Ethernet (100Mb/s), microSD card slot, micro USB power
Raspberry Pi Model A+Raspberry Pi Model A+BCM2835256MB, 512MB40-pin GPIO headerHDMI, USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, microSD card slot, micro USB power
Raspberry Pi 2 Model BRaspberry Pi 2 Model BBCM2836 (in version 1.2, switched to BCM2837)1 GB40-pin GPIO headerHDMI, 4 × USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, Ethernet (100Mb/s), microSD card slot, micro USB power
Raspberry Pi 3 Model BRaspberry Pi 3 Model BBCM28371 GB40-pin GPIO headerHDMI, 4 × USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, Ethernet (100Mb/s), 2.4GHz single-band 802.11n Wi-Fi (35Mb/s), Bluetooth 4.1, Bluetooth Low Energy (BLE), microSD card slot, micro USB power
Raspberry Pi 3 Model B+Raspberry Pi 3 Model B+BCM2837b01GB40-pin GPIO headerHDMI, 4 × USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, PoE-capable Ethernet (300Mb/s), 2.4/5GHz dual-band 802.11ac Wi-Fi (100Mb/s), Bluetooth 4.2, Bluetooth Low Energy (BLE), microSD card slot, micro USB power
Raspberry Pi 3 Model A+Raspberry Pi 3 Model A+BCM2837b0512 MB40-pin GPIO headerHDMI, USB 2.0, CSI camera port, DSI display port, 3.5mm AV jack, 2.4/5GHz dual-band 802.11ac Wi-Fi (100Mb/s), Bluetooth 4.2, Bluetooth Low Energy (BLE), microSD card slot, micro USB power
Raspberry Pi 4 Model BRaspberry Pi 4 Model BBCM27111GB, 2GB, 4GB, 8GB40-pin GPIO header2 × micro HDMI, 2 × USB 2.0, 2 × USB 3.0, CSI camera port, DSI display port, 3.5 mm AV jack, PoE-capable Gigabit Ethernet (1Gb/s), 2.4/5GHz dual-band 802.11ac Wi-Fi (120Mb/s), Bluetooth 5, Bluetooth Low Energy (BLE), microSD card slot, USB-C power (5V, 3A (15W))
Raspberry Pi 400Raspberry Pi 400BCM27114GB40-pin GPIO header2 × micro HDMI, 2 × USB 2.0, 2 × USB 3.0, Gigabit Ethernet (1Gb/s), 2.4/5GHz dual-band 802.11ac Wi-Fi (120Mb/s), Bluetooth 5, Bluetooth Low Energy (BLE), microSD card slot, USB-C power (5V, 3A (15W))
Raspberry Pi 5Raspberry Pi 5BCM2712 (2GB version uses BCM2712D0)2GB, 4GB, 8GB40-pin GPIO header2 × micro HDMI, 2 × USB 2.0, 2 × USB 3.0, 2 ×  CSI camera/DSI display ports, single-lane PCIe FFC connector, UART connector, RTC battery connector, four-pin JST-SH PWM fan connector, PoE+-capable Gigabit Ethernet (1Gb/s), 2.4/5GHz dual-band 802.11ac Wi-Fi 5 (300Mb/s), Bluetooth 5, Bluetooth Low Energy (BLE), microSD card slot, USB-C power (5V, 5A (25W) or 5V, 3A (15W) with a 600mA peripheral limit)

For more information about the ports on the Raspberry Pi flagship series, see the Schematics and mechanical drawings.

Zero series

Models with the H suffix have header pins pre-soldered to the GPIO header. Models that lack the H suffix do not come with header pins attached to the GPIO header; the user must solder pins manually or attach a third-party pin kit.

All Zero models have the following connectivity:

  • a microSD card slot
  • a CSI camera port (version 1.3 of the original Zero introduced this port)
  • a mini HDMI port
  • 2 × micro USB ports (one for input power, one for external devices)
ModelSoCMemoryGPIOWireless Connectivity
Raspberry Pi ZeroRaspberry Pi ZeroBCM2835512MB40-pin GPIO header (unpopulated)none
Raspberry Pi Zero WRaspberry Pi Zero WBCM2835512MB40-pin GPIO header (unpopulated)2.4GHz single-band 802.11n Wi-Fi (35Mb/s), Bluetooth 4.0, Bluetooth Low Energy (BLE)
Raspberry Pi Zero WHRaspberry Pi Zero WHBCM2835512MB40-pin GPIO header2.4GHz single-band 802.11n Wi-Fi (35Mb/s), Bluetooth 4.0, Bluetooth Low Energy (BLE)
Raspberry Pi Zero 2 WRaspberry Pi Zero 2 WRP3A0512MB40-pin GPIO header (unpopulated)2.4GHz single-band 802.11n Wi-Fi (35Mb/s), Bluetooth 4.2, Bluetooth Low Energy (BLE)

Compute Module series

ModelSoCMemoryStorageForm factorWireless Connectivity
Raspberry Pi Compute Module 1Raspberry Pi Compute Module 1BCM2835512MB4GBDDR2 SO-DIMMnone
Raspberry Pi Compute Module 3Raspberry Pi Compute Module 3BCM28371GB0GB (Lite), 4GBDDR2 SO-DIMMnone
Raspberry Pi Compute Module 3+Raspberry Pi Compute Module 3+BCM2837b01GB0GB (Lite), 8GB, 16GB, 32GBDDR2 SO-DIMMnone
Raspberry Pi Compute Module 4SRaspberry Pi Compute Module 4SBCM27111GB, 2GB, 4GB, 8GB0GB (Lite), 8GB, 16GB, 32GBDDR2 SO-DIMMnone
Raspberry Pi Compute Module 4Raspberry Pi Compute Module 4BCM27111GB, 2GB, 4GB, 8GB0GB (Lite), 8GB, 16GB, 32GBdual 100-pin high density connectorsoptional: 2.4/5GHz dual-band 802.11ac Wi-Fi 5 (300Mb/s), Bluetooth 5, Bluetooth Low Energy (BLE)

For more information about Raspberry Pi Compute Modules, see the Compute Module documentation.

Pico microcontrollers

Models with the H suffix have header pins pre-soldered to the GPIO header. Models that lack the H suffix do not come with header pins attached to the GPIO header; the user must solder pins manually or attach a third-party pin kit.

ModelSoCMemoryStorageGPIOWireless Connectivity
Raspberry Pi PicoRaspberry Pi PicoRP2040264KB2MBtwo 20-pin GPIO headers (unpopulated)none
Raspberry Pi Pico HRaspberry Pi Pico HRP2040264KB2MBtwo 20-pin GPIO headersnone
Raspberry Pi Pico WRaspberry Pi Pico WRP2040264KB2MBtwo 20-pin GPIO headers (unpopulated)2.4GHz single-band 802.11n Wi-Fi (10Mb/s), Bluetooth 5.2, Bluetooth Low Energy (BLE)
Raspberry Pi Pico WHRaspberry Pi Pico WHRP2040264KB2MBtwo 20-pin GPIO headers2.4GHz single-band 802.11n Wi-Fi (10Mb/s), Bluetooth 5.2, Bluetooth Low Energy (BLE)
Raspberry Pi Pico 2Raspberry Pi Pico 2RP2350520KB4MBtwo 20-pin GPIO headers (unpopulated)none

For more information about Raspberry Pi Pico models, see the Pico documentation.

If you’re interested in schematics, mechanical drawings, and information on thermal control, visit our documentation page.

The post Raspberry Pi product series explained appeared first on Raspberry Pi.

How to get started with your Raspberry Pi AI Camera

22 October 2024 at 22:29

If you’ve got your hands on the Raspberry Pi AI Camera that we launched a few weeks ago, you might be looking for a bit of help to get up and running with it – it’s a bit different from our other camera products. We’ve raided our documentation to bring you this Getting started guide. If you work through the steps here you’ll have your camera performing object detection and pose estimation, even if all this is new to you. Then you can dive into the rest of our AI Camera documentation to take things further.

This image shows a Raspberry Pi setup on a wooden surface, featuring a Raspberry Pi board connected to an AI camera module via an orange ribbon cable. The Raspberry Pi board is attached to several cables: a red one on the left for power and a white HDMI cable on the right. The camera module sits in the lower right corner, with its lens facing up. Part of a white and red keyboard is visible on the right side of the image, and a small plant in a white pot is partially visible on the left. The scene suggests a Raspberry Pi project setup in progress.

Here we describe how to run the pre-packaged MobileNet SSD (object detection) and PoseNet (pose estimation) neural network models on the Raspberry Pi AI Camera.

Prerequisites

We’re assuming that you’re using the AI Camera attached to either a Raspberry Pi 4 or a Raspberry Pi 5. With minor changes, you can follow these instructions on other Raspberry Pi models with a camera connector, including the Raspberry Pi Zero 2 W and Raspberry Pi 3 Model B+.

First, make sure that your Raspberry Pi runs the latest software. Run the following command to update:

sudo apt update && sudo apt full-upgrade

The AI Camera has an integrated RP2040 chip that handles neural network model upload to the camera, and we’ve released a new RP2040 firmware that greatly improves upload speed. AI Cameras shipping from now onwards already have this update, and if you have an earlier unit, you can update it yourself by following the firmware update instructions in this forum post. This should take no more than one or two minutes, but please note before you start that it’s vital nothing disrupts the process. If it does – for example, if the camera becomes disconnected, or if your Raspberry Pi loses power – the camera will become unusable and you’ll need to return it to your reseller for a replacement. Cameras with the earlier firmware are entirely functional, and their performance is identical in every respect except for model upload speed.

Install the IMX500 firmware

In addition to updating the RP2040 firmware if required, the AI camera must download runtime firmware onto the IMX500 sensor during startup. To install these firmware files onto your Raspberry Pi, run the following command:

sudo apt install imx500-all

This command:

  • installs the /lib/firmware/imx500_loader.fpk and /lib/firmware/imx500_firmware.fpk firmware files required to operate the IMX500 sensor
  • places a number of neural network model firmware files in /usr/share/imx500-models/
  • installs the IMX500 post-processing software stages in rpicam-apps
  • installs the Sony network model packaging tools

NOTE: The IMX500 kernel device driver loads all the firmware files when the camera starts, and this may take several minutes if the neural network model firmware has not been previously cached. The demos we’re using here display a progress bar on the console to indicate firmware loading progress.

Reboot

Now that you’ve installed the prerequisites, restart your Raspberry Pi:

sudo reboot
The image shows a Raspberry Pi AI Camera Module. It's a small, square-shaped green circuit board with four yellow mounting holes at each corner. In the center, there's a black camera lens marked with "MU2351." An orange ribbon cable is attached to the bottom of the board, used for connecting the camera to a Raspberry Pi. The Raspberry Pi logo, a white raspberry outline, is visible on the left side of the board.

Run example applications

Once all the system packages are updated and firmware files installed, we can start running some example applications. As mentioned earlier, the Raspberry Pi AI Camera integrates fully with libcamera, rpicam-apps, and Picamera2. This blog post concentrates on rpicam-apps, but you’ll find more in our AI Camera documentation.

rpicam-apps

The rpicam-apps camera applications include IMX500 object detection and pose estimation stages that can be run in the post-processing pipeline. For more information about the post-processing pipeline, see the post-processing documentation.

The examples on this page use post-processing JSON files located in /usr/share/rpicam-assets/.

Object detection

The MobileNet SSD neural network performs basic object detection, providing bounding boxes and confidence values for each object found. imx500_mobilenet_ssd.json contains the configuration parameters for the IMX500 object detection post-processing stage using the MobileNet SSD neural network.

imx500_mobilenet_ssd.json declares a post-processing pipeline that contains two stages:

  1. imx500_object_detection, which picks out bounding boxes and confidence values generated by the neural network in the output tensor
  2. object_detect_draw_cv, which draws bounding boxes and labels on the image

The MobileNet SSD tensor requires no significant post-processing on your Raspberry Pi to generate the final output of bounding boxes. All object detection runs directly on the AI Camera.

The following command runs rpicam-hello with object detection post-processing:

rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30

After running the command, you should see a viewfinder that overlays bounding boxes on objects recognised by the neural network:

To record video with object detection overlays, use rpicam-vid instead:

rpicam-vid -t 10s -o output.264 --post-process-file /usr/share/rpi-camera-assets/imx500_mobilenet_ssd.json --width 1920 --height 1080 --framerate 30

You can configure the imx500_object_detection stage in many ways.

For example, max_detections defines the maximum number of objects that the pipeline will detect at any given time. threshold defines the minimum confidence value required for the pipeline to consider any input as an object.

The raw inference output data of this network can be quite noisy, so this stage also performs some temporal filtering and applies hysteresis. To disable this filtering, remove the temporal_filter config block.

Pose estimation

The PoseNet neural network performs pose estimation, labelling key points on the body associated with joints and limbs. imx500_posenet.json contains the configuration parameters for the IMX500 pose estimation post-processing stage using the PoseNet neural network.

imx500_posenet.json declares a post-processing pipeline that contains two stages:

  1. imx500_posenet, which fetches the raw output tensor from the PoseNet neural network
  2. plot_pose_cv, which draws line overlays on the image

The AI Camera performs basic detection, but the output tensor requires additional post-processing on your host Raspberry Pi to produce final output.

The following command runs rpicam-hello with pose estimation post-processing:

rpicam-hello -t 0s --post-process-file /usr/share/rpi-camera-assets/imx500_posenet.json --viewfinder-width 1920 --viewfinder-height 1080 --framerate 30

You can configure the imx500_posenet stage in many ways.

For example, max_detections defines the maximum number of bodies that the pipeline will detect at any given time. threshold defines the minimum confidence value required for the pipeline to consider input as a body.

Picamera2

For examples of image classification, object detection, object segmentation, and pose estimation using Picamera2, see the picamera2 GitHub repository.

Most of the examples use OpenCV for some additional processing. To install the dependencies required to run OpenCV, run the following command:

sudo apt install python3-opencv python3-munkres

Now download the picamera2 repository to your Raspberry Pi to run the examples. You’ll find example files in the root directory, with additional information in the README.md file.

Run the following script from the repository to run YOLOv8 object detection:

python imx500_object_detection_demo.py --model /usr/share/imx500-models/imx500_network_yolov8n_pp.rpk --ignore-dash-labels -r

To try pose estimation in Picamera2, run the following script from the repository:

python imx500_pose_estimation_higherhrnet_demo.py

To explore further, including how things work under the hood and how to convert existing models to run on the Raspberry Pi AI Camera, see our documentation.

The post How to get started with your Raspberry Pi AI Camera appeared first on Raspberry Pi.

Get started with Raspberry Pi Pico-series and VS Code

18 October 2024 at 17:24

In the latest issue of The MagPi, Raspberry Pi Documentation Lead Nate Contino shows you how to attach a Raspberry Pi Pico-series device and start development with the new VS Code extension.

The following tutorial assumes that you are using a Pico-series device; some details may differ if you use a different Raspberry Pi microcontroller-based board. Pico-series devices are built around microcontrollers designed by Raspberry Pi itself. Development on the boards is fully supported with both a C/C++ SDK, and an official MicroPython port. This article talks about how to get started with the SDK, and walks you through how to build, install, and work with the SDK toolchain.

VS Code running on a Raspberry Pi computer. This IDE (integrated development environment) has an extension for Pico-series computers

To install Visual Studio Code (known as VS Code for short) on Raspberry Pi OS or Linux, run the following commands: 

$ sudo apt update
$ sudo apt install code

On macOS and Windows, you can install VS Code from magpi.cc/vscode. On macOS, you can also install VS Code with brew using the following command: 

$ brew install --cask visual-studio-code

The Raspberry Pi Pico VS Code extension helps you create, develop, run, and debug projects in Visual Studio Code. It includes a project generator with many templating options, automatic toolchain management, one-click project compilation, and offline documentation of the Pico SDK. The VS Code extension supports all Raspberry Pi Pico-series devices.

Creating a project in VS Code

Install dependencies

On Raspberry Pi OS and Windows no dependencies are needed.

Most Linux distributions come preconfigured with all of the dependencies needed to run the extension. However, some distributions may require additional dependencies.

The extension requires the following: 

  • Python 3.9 or later 
  • Git 
  • Tar 
  • A native C and C++ compiler (the extension supports GCC) 

You can install these with: 

$ sudo apt install python3 git tar build-essential

On macOS 

To install all requirements for the extension on macOS, run the following command: 

$ xcode-select --install

This installs the following dependencies:

  • Git
  • Tar 
  • A native C and C++ compiler (the extension supports GCC and Clang)

Install the extension 

You can find the extension in the VS Code Extensions Marketplace. Search for the Raspberry Pi Pico extension, published by Raspberry Pi. Click the Install button to add it to VS Code.

You can find the store entry at magpi.cc/vscodeext. You can find the extension source code and release downloads at magpi.cc/picovscodegit. When installation completes, check the Activity sidebar (by default, on the left side of VS Code). If installation was successful, a new sidebar section appears with a Raspberry Pi Pico icon, labelled “Raspberry Pi Pico Project”.

Create code to blink the LED on a Pico 2 board

Load and debug a project 

The VS Code extension can create projects based on the examples provided by Pico Examples. For an example, we’ll walk you through how to create a project that blinks the LED on your Pico-series device: 

  1. In the VS Code left sidebar, select the Raspberry Pi Pico icon, labelled Raspberry Pi Pico Project. 
  2. Select New Project from Examples. 
  3. In the Name field, select the blink example. 
  4. Choose the board type that matches your device. 
  5. Specify a folder where the extension can generate files. VS Code will create the new project in a sub-folder of the selected folder. 
  6. Click Create to create the project. The extension will now download the SDK and the toolchain, install them locally, and generate the new project. The first project may take five to ten minutes to install the toolchain. VS Code will ask you whether you trust the authors because we’ve automatically generated the .vscode directory for you. Select yes.

The CMake Tools extension may display some notifications at this point. Ignore and close them. 

two raspberry pi pico 2 boards on a yellow and a blue cutting board. both are connected via usb c with raspberry red cables
Pico’s Micro USB connector makes sending code easy

On the left Explorer sidebar in VS Code, you should now see a list of files. Open blink.c to view the blink example source code in the main window. The Raspberry Pi Pico extension adds some capabilities to the status bar at the bottom right of the screen:

  • Compile. Compiles the sources and builds the target UF2 file. You can copy this binary onto your device to program it. 
  • Run. Finds a connected device, flashes the code into it, and runs that code.

The extension sidebar also contains some quick access functions. Click on the Pico icon in the side menu and you’ll see Compile Project. Hit Compile Project and a terminal tab will open at the bottom of the screen displaying the compilation progress.

Compile and run blink 

To run the blink example: 

  1. Hold down the BOOTSEL button on your Pico-series device while plugging it into your development device using a Micro USB cable to force it into USB Mass Storage Mode. 
  2. Press the Run button in the status bar or the Run Project button in the sidebar. You should see the terminal tab at the bottom of the window open. It will display information concerning the upload of the code. Once the code uploads, the device will reboot, and you should see the following output:
The device was rebooted to start the application.

Your blink code is now running. If you look at your device, the LED should blink twice every second. 

The image shows a Raspberry Pi Pico 2, a small, rectangular microcontroller development board designed by the Raspberry Pi Foundation. This board is similar in appearance to the Raspberry Pi Pico, but it includes wireless connectivity features, as denoted by the "W" in its name. Here are some details visible in the image: Board Design: The board has a green printed circuit board (PCB) with gold-plated connections along the edges. These are pin headers designed for easy connection to other components or breadboards. Microcontroller: In the center of the board is a black integrated circuit chip, which is likely the RP2040 microcontroller. It features the Raspberry Pi logo on it. Labeling: The board is labeled "Pico" with the number "2" alongside it, indicating it is a Pico W model, a second version of the original Pico with enhanced features. The Raspberry Pi logo, a stylized raspberry with a leaf, is printed near the labeling. USB Connector: At the top end of the board, there is a micro USB connector, which is used for power supply and data transfer. Other Components: Visible components include a white reset button, small surface-mounted components like resistors and capacitors, and a black square component which is likely the wireless module for Wi-Fi connectivity. The board includes a small square chip next to the microcontroller, which could be the antenna or additional circuitry for the wireless module. Form Factor: The board has a compact form factor, designed for embedding into various projects, especially in IoT applications that require Wi-Fi connectivity. The Raspberry Pi Pico 2 is used for a wide range of applications, from simple programming projects to complex IoT systems, due to its small size, affordability, and ease of use with the MicroPython programming environment.
The new Raspberry Pi Pico 2 has upgraded capabilities over the original model

Make a code change and re-run 

To check that everything is working correctly, click on the blink.c file in VS Code. Navigate to the definition of LED_DELAY_MS at the top of the code: 

#ifndef LED_DELAY_MS
#define LED_DELAY_MS 250
#endif LED_DELAY_MS

Change the 250 (in ms, a quarter of a second) to 100 (a tenth of a second): #ifndef LED_DELAY_MS #define LED_DELAY_MS 100 #endif LED_DELAY_MS 

  1. Disconnect your device, then reconnect while holding the BOOTSEL button just as you did before. 
  2. Press the Run button in the status bar or the Run Project button in the sidebar. You should see the terminal tab at the bottom of the window open. It will display information concerning the upload of the code. Once the code uploads, the device will reboot, and you should see the following output: 
The device was rebooted to start the application.

Your blink code is now running. If you look at your device, the LED should flash faster, five times every second.

Top tip

Read the online guide

This tutorial also features in the Raspberry Pi Datasheet: Getting started with Pico. It also features information on using Raspberry Pi’s Debug Probe.

The post Get started with Raspberry Pi Pico-series and VS Code appeared first on Raspberry Pi.

❌
❌