Reading view

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

Using Python with virtual environments | The MagPi #148

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 AI Kit projects

By: Phil King

This #MagPiMonday, we’re hoping to inspire you to add artificial intelligence to your Raspberry Pi designs with this feature by Phil King, from the latest issue of The MagPi.

With their powerful AI accelerator modules, Raspberry Pi’s Camera Module and AI Kit open up exciting possibilities in computer vision and machine learning. The versatility of the Raspberry Pi platform, combined with AI capabilities, opens up a world of new possibilities for innovative smart projects. From creative experiments to practical applications like smart pill dispensers, makers are harnessing the kit’s potential to push the boundaries of AI. In this feature, we explore some standout projects, and hope they inspire you to embark on your own.

Peeper Pam boss detector

By VEEB Projects

AI computer vision can identify objects within a live camera view. In this project, VEEB’s Martin Spendiff and Vanessa Bradley have used it to detect humans in the frame, so you can tell if your boss is approaching behind you as you sit at your desk!

The project comprises two parts. A Raspberry Pi 5 equipped with a Camera Module and AI Kit handles the image recognition and also acts as a web server. This uses web sockets to send messages wirelessly to the ‘detector’ part — a Raspberry Pi Pico W and a voltmeter whose needle moves to indicate the level of AI certainty for the ID.

Having got their hands on an AI Kit — “a nice intro into computer vision” — it took the pair just three days to create Peeper Pam. “The most challenging bit was that we’d not used sockets — more efficient than the Pico constantly asking Raspberry Pi ‘do you see anything?’,” says Martin. “Raspberry Pi does all the heavy lifting, while Pico just listens for an ‘I’ve seen something’ signal.”

While he notes that you could get Raspberry Pi 5 to serve both functions, the two-part setup means you can place the camera in a different position to monitor a spot you can’t see. Also, by adapting the code from the project’s GitHub repo, there are lots of other uses if you get the AI to deter other objects. “Pigeons in the window box is one that we want to do,” Martin says.

Monster AI Pi PC

By Jeff Geerling

Never one to do things by halves, Jeff Geerling went overboard with Raspberry Pi AI Kit and built a Monster AI Pi PC with a total of eight neural processors. In fact, with 55 TOPS (trillions of operations per second), it’s faster than the latest AMD, Qualcomm, and Apple Silicon processors!

The NPU chips — including the AI Kit’s Hailo-8L — are connected to a large 12× PCIe slot card with a PEX 8619 switch capable of handling 16 PCI Express Gen 2 lanes. The card is then mounted on a Raspberry Pi 5 via a Pineboards uPCIty Lite HAT, which has an additional 12V PSU to supply the extra wattage needed for all those processors.

With a bit of jiggery-pokery with the firmware and drivers on Raspberry Pi, Jeff managed to get it working.

Car detection & tracking system

By Naveen

As a proof of concept, Japanese maker Naveen aimed to implement an automated system for identifying and monitoring cars at toll plazas to get an accurate tally of the vehicles entering and exiting.

With the extra processing power provided by a Raspberry AI Kit, the project uses Edge Impulse computer vision to detect and count cars in the view from a Camera Module Wide. “We opted for a wide lens because it can capture a larger area,” he says, “allowing the camera to monitor multiple lanes simultaneously.” He also needed to train and test a YOLOv5 machine learning model. All the details can be found on the project page via the link above, which could prove useful for learning how to train custom ML models for your own AI project.

Safety helmet detection system

By Shakhizat Nurgaliyev

Wearing a safety helmet on a building site is essential and could save your life. This computer vision project uses Raspberry Pi AI Kit with the advanced YOLOv8 machine learning model to quickly and accurately identify objects within the camera view, running at an impressive inference speed of 30fps.

The project page has a guide showing how to make use of Raspberry Pi AI Kit to achieve efficient AI inferencing for safety helmet detection. This includes details of the software installation and model training process, for which the maker has provided a link to a dataset of 5000 images with bounding box annotations for three classes: helmet, person, and head.

Accelerating MediaPipe models

By Mario Bergeron

Google’s MediaPipe is an open-source framework developed for building machine learning pipelines, especially useful for working with videos and images.

Having used MediaPipe on other platforms, Mario Bergeron decided to experiment with it on a Raspberry Pi AI Kit. On the project page (linked above) he details the process, including using his Python demo application with options to detect hands/palms, faces, or poses.

Mario’s test results show how much better the AI Kit’s Hailo-8L AI accelerator module performs compared to running reference TensorFlow Lite models on Raspberry Pi 5 alone: up to 5.8 times faster. With three models running for hand and landmarks detection, the frame rate is 26–28fps with one hand detected, and 22–25fps for two.

The MagPi #147 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 Raspberry Pi AI Kit projects appeared first on Raspberry Pi.

Meet Kari Lawler: Classic computer and retro gaming enthusiast

Meet Kari Lawler, a YouTuber with a passion for collecting and fixing classic computers, as well as retro gaming. This interview first appeared in issue 147 of The MagPi magazine.

Kari Lawler has a passion for retro tech — and despite being 21, her idea of retro fits with just about everyone’s definition, as she collects and restores old Commodore 64s, Amiga A500s, and Atari 2600s. Stuff from before even Features Editor Rob was born, and he’s rapidly approaching 40. Kari has been involved in the tech scene for ten years though, doing much more than make videos on ’80s computers.

“I got my break into tech at around 11 years old, when I hacked together my very own virtual assistant and gained some publicity,” Kari says. “This inspired me to learn more, especially everything I could about artificial intelligence. Through this, I created my very own youth programme called Youth4AI, in which I engaged with and taught thousands of young people about AI. As well as my youth programme, I was lucky enough to work on many AI projects and branch out into government advisory work as well. Culminating, at 18 years old, in being entered into the West Midlands Women in Tech Hall of Fame, with a Lifetime Achievement Award of all things.”

What’s your history with making?

“Being brought up in a family of makers, I suppose it was inevitable I got the bug as well. From an early age, I fondly remember being surrounded by arts and crafts, and attending many sessions. From sewing to pottery and basic electronics to soldering, I enjoyed everything I did. Which resulted in me creating many projects, from a working flux capacitor (well, it lit up) for school homework, to utilising what I learned to make fun projects to share with others when I volunteered at my local Raspberry Pi Jam. Additionally, at around the age of 12 I was introduced to the wonderful world of 3D printing, and I’ve utilised that knowledge in many of the projects I’ve shared online. Starting with the well-received ’24 makes for Christmas’ I did over on X [formerly Twitter] in 2017, aged 14, which featured everything from coding Minecraft to robot sprouts. And I’ve been sharing what I make over on my socials ever since.”

Fun fact: The code listings in The MagPi are inspired by magazines from the 1980s, which also printed code listings. Although you can download all of ours as well

How did you get into retro gaming?

“Both my uncle and dad had a computer store in the ’90s, the PS1/N64 era, and while they have never displayed any of it, what was left of the shop was packed up and put into storage. And, me being me, I was quite interested in learning more about what was in those boxes. Additionally, I grew up with a working BBC Micro in the house, so have fond memories playing various games on it, especially Hangman — I think I was really into spelling bees at that point. So, with that and the abundance of being surrounded by old tech, I really got into learning about the history of computing and gaming. Which led me to getting the collecting bug, and to start adding to the collection myself so I could experience more and more tech from the past.”

One of Kari’s more recent projects was fixing a PSOne, the smaller release of the original PlayStation but with a screen attached

What’s your favourite video that you’ve made?

“Now that’s a hard one to answer. But if I go back to one of my first videos, Coding games like it’s the ’80s, it’s one that resonates with how I got my first interest in programming. My dad introduced me to Usborne computer books from the 1980s, just after I started learning Python, and said ‘try and convert some of these’. I accepted that challenge, and that’s what got me fascinated with ’80s programming books, hence the video I made. With the Usborne books specifically, there is artwork and a back story for each game. And while technically not great games, I just love how they explain the code and challenge the reader to improve. For which, I’m sure some of my viewers will be pleased to hear, I have in the works more videos exploring programming books/magazine type-in listings from the ’80s.”

Recreating classic NES Tetrinomoes with a 3D printer to make cool geometric magnets

The MagPi #147 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 Meet Kari Lawler: Classic computer and retro gaming enthusiast appeared first on Raspberry Pi.

DEC Flip-Chip tester | The MagPi #147

A brand new issue of The MagPi is out in the wild, and one of our favourite projects we read about involved rebuilding an old PDP-9 computer with a Raspberry Pi-based device that tests hundreds of components.

Anders Sandahl loves collecting old computers: “I really like to restore them and get them going again.” For this project, he wanted to build a kind of component tester for old DEC (Digital Equipment Corporation) Flip-Chip boards before he embarked on the lengthy task of restoring his 1966 PDP-9 computer — a two-foot-tall machine with six- to seven-hundred Flip-Chip boards inside — back to working order. 

DEC’s 1966 PDP-9 computer was two foot tall
Image credit: Wikipedia

His Raspberry Pi-controlled DEC Flip-Chip tester checks the power output of these boards using relay modules and signal clips, giving accurate information about each one’s power draw and output. Once he’s confident each component is working properly, Anders can begin to assemble the historic DEC PDP-9 computer, which Wikipedia advises is one of only 445 ever produced.

Logical approach

“Flip-Chip boards from this era implement simple logical functions, comparable to one 7400-series logic circuit,” Anders explains. “The tester uses Raspberry Pi and an ADC (analogue-to-digital converter) to measure and control analogue signals sent to the Flip-Chip, and digital signals used to control the tester’s circuits. PDP-7, PDP-8 (both 8/S and Straight-8), PDP-9, and PDP-10 (with the original KA processor) all use this generation of Flip-Chips. A testing device for one will work for all of them, which is pretty useful if you’re in the business of restoring old computers. 

The Flip-Chip tester uses Raspberry Pi 3B+, 4, or 5 to check the signal and relay the strength of each Flip-Chip by running a current across it, so restorers don’t attach a dud component

Rhode Island Computer Museum (RICM) is where The MagPi publisher Brian Jepson and friend Mike Thompson both volunteer. Mike is part of a twelve-year-project to rebuild RICM’s own DEC PDP-9 and, after working on a different Flip-Chip tester there, he got in touch with Anders about his Raspberry Pi-based version. He’s now busily helping write the user manual for the tester unit. 

Warning!
Frazzled Flip-Chips


Very old computers that use Flip-Chips have components operating at differing voltages, so there’s a high chance of shorting them. You need a level shifter to convert and step down voltages for safe operation. 

Mike explains: “Testing early transistor-only Flip-Chips is incredibly complicated because the voltages are all negative, and the Flip-Chips must be tested with varying input voltages and different loads on the outputs.” There are no integrated circuits, just discrete transistors. Getting such an old computer running again is “quite a task” because of the sheer number of broken components on each PCB, and Flip-Chip boards hold lots of transistors and diodes, “all of which are subject to failure after 55+ years”.

Anders previously used Raspberry Pi to recreate an old PDP-8 computer

Obstacles, of course

The Flip-Chip tester features 15 level-shifter boards. These step down the voltage so components with different power outputs and draws can operate alongside each other safely and without anything getting frazzled. Anders points out the disparity between the Flip-Chips’ 0 and -3V logic voltage levels and the +10 and -15V used as supply voltages. Huge efforts went into this level conversion to make it reliable and failsafe. Anders wrote the testing software himself, and built the hardware “from scratch” using parts from Mouser and custom-designed circuit boards. The project took around two years and cost around $500, of which the relays were a major part. 

This photo from the user manual shows just how huge the PDP-9 could get

Anders favours Raspberry Pi because “it offers a complete OS, file system, and networking in a neat and well-packaged way”, and says it is “a very good software platform that you really just have to do minor tweaks on to get right”. He’s run the tester on Raspberry Pi 3B, 4, and 5. He says it should also run on Raspberry Pi Zero as well, “but having Ethernet and the extra CPU power makes life easier”.

Although this is a fairly niche project for committed computer restorers, Anders believes his Flip-Chip tester can be built by anyone who can solder fairly small SMD components. Documenting the project so others can build it was quite a task, so it was quite helpful when Mike got in touch and was able to assist with the write-up. As a fellow computer restorer, Mike says the tester means getting RICM’s PDP-9 working again “won’t be such an overwhelming task. With the tester we can test and repair each of the boards instead of trying to diagnose a very broken computer as a whole.” 

The MagPi #147 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 DEC Flip-Chip tester | The MagPi #147 appeared first on Raspberry Pi.

Get started with Raspberry Pi Pico-series and VS Code

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.

Track Asian hornets with VespAI | #MagPiMonday

AI models are adept at distinguishing one winged creature from another. This #MagPiMonday, Rosie Hattersley goes beyond the buzz.

Once attracted to liquid in a Petri dish, VespAI identifies any Asian hornets and automatically alerts researchers who trace them back to their nest
Once attracted to liquid in a Petri dish, VespAI identifies any Asian hornets and automatically alerts researchers who trace them back to their nest

Fun fact that might get you a point in the local pub quiz: Vespa, Piaggio’s iconic scooter, is Italian for wasp, which its buzzing engine sounds a bit like. Less fun fact: nature’s counterpart to the speedy two-wheeler has an aggressive variant that has been seen in increasing numbers across western Europe and which is a direct threat to bees, which are one of their key food sources. Bees are great for biodiversity; Asian hornets (the largest type of eusocial wasp) are not. But it’s only particular hornet species that pose such a threat. Most citizen reports of Asian hornets are native species, and a key issue is ensuring that existing hornet species are not being destroyed on this mistaken assumption. To combat misinformation and alarm at the so-called ‘killer’ hornet (itself a subset of wasp), academics at the University of Exeter have developed a VespAI detector that presents a positive identification system showing where new colonies of the invasive hornet Vespa velutina nigrithorax have begun to spread. The system works by drawing the insects to a pad that is impregnated with tasty (to wasps) smelling foodstuffs.

Dr Thomas O’Shea-Weller, Juliet Osborne, and Peter Kennedy

Considerate response

VespAI provides a nonharmful alternative to traditional trapping surveys and can also be used for monitoring hornet behaviour and mapping distributions of both the Asian hornet (Vespa velutina) and European hornet (Vespa crabro), which is protected in some countries. “Live hornets can be caught and tracked back to the nest, which is the only effective way to destroy them,” explains the team’s research paper.

VespAI crosschecks a potential hornet against its 33,000-strong image database
Non-Asian hornets are discounted, meaning non-invasive native species are not destroyed in a bid to eradicate the destructive newcomers

Creepy feeling

VespAI features a camera positioned above a bait station that detects insects as they land to feed and gets to work establishing whether the curious mite is, in fact, an Asian hornet. The Exeter team developed the AI algorithm in Python, using YOLO image detection models. These identify whether Asian hornets are present and, if so, send an alert to users. Raspberry Pi proved a great choice because of its compact size, ability to run the hornet recognition algorithm, real-time clock, and support for peripherals such as an external battery. The prototype bait station design was made with items that the team had at hand in their lab, including a squirrel baffle for the weather shield, Petri dishes and sponges to hold hornet attractant, and a beehive stand for the monitor to rest on.

The VespAI system is inactive unless an insect of the correct size is detected on the bait station
The system is inactive unless an insect of the correct size is detected on the bait station

Design challenges included optimising the hornet detection algorithm for use on Raspberry Pi. “An AI algorithm may work well during training or when validated in the lab. However, field deployment is essential to expose it to potentially unforeseen scenarios that may return errors”, they note. The project also involved developing a monitor with an integrated camera, processor, and peripherals while minimising power consumption. To this end, the VespAI team is currently optimising their software to run on Raspberry Pi Zero, having watched footage of the AntVideoRecord device monitoring leafcutter ant (Acromyrmex lundi) foraging trails and been impressed by its ability to run for extended periods remotely due to its low power consumption.

As this interactive map shows, Asian hornets have quickly made inroads across Western Europe.

Asian hornets have rapidly spread from southern Europe and are now increasing in numbers in the UK

The Raspberry Pi-enabled setup is “intended to support national surveillance efforts, thus limiting hornet incursions into new regions,” explains Dr Thomas O’Shea-Wheller, a research fellow in the university’s Environment and Sustainability Institute. He and his colleagues have been working on the AI project since 2022, conducting additional fieldwork this summer with the National Bee Unit and the Government of Jersey (Channel Islands) mapping new locations and fine-tuning its accessibility to potential users ahead of a planned commercial version. 

Given Raspberry Pi’s extensive and enthusiastic users, they hope sharing their code on GitHub will help expand the number of VespAI detection stations and improve surveillance and reporting of hornet species.

This article originally featured in issue 146 of The MagPi magazine.

The MagPi #146 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.

The image you provided is the cover of "The MagPi" magazine, issue 146, from October 2024. This magazine is dedicated to Raspberry Pi enthusiasts. The cover design is orange with black and white elements, featuring a retro horror theme. Some of the key elements on the cover include: The main headline, "PLAY RETRO HORROR CLASSICS ON RASPBERRY PI 5," likely highlighting a feature on retro horror games. The text "Police Line Do Not Cross" in several places, adding to the spooky, horror theme, possibly in reference to crime or mystery-themed games. The imagery of a crow, a spooky-looking house, a cassette tape, and various retro gaming motifs, reinforcing the horror and retro gaming aesthetic. Additional highlights like "LEGO Card Shuffler," "Top 10 Spooky Projects," and "Recycle a Fighter Jet Joystick," suggesting other tech and DIY projects featured in this issue. The bottom of the cover mentions "TURN IT UP TO 11 WITH AUDIO UPGRADES," hinting at content related to enhancing audio experiences. The overall theme seems focused on retro horror gaming and tech projects for Raspberry Pi.

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 Track Asian hornets with VespAI | #MagPiMonday appeared first on Raspberry Pi.

Pilet: Mini Pi 5 modular computer

The new and improved MagPi magazine now houses one of my favourite sections of the late great HackSpace magazine: Top Projects. The feature showcases five or six spectacular builds using Raspberry Pi, and this was our favourite from the latest issue.

Do you want a portable mini modular computer based on Raspberry Pi 5? If so, you’re in luck. A small outfit (boasting one-and-a-half people) called Soulcircuit is working on one right now, called the Pilet (it was called Consolo, but is now called Pilet, which according to the maker “reflects the project’s aim to appeal to a wider global audience”). 

Two 8000mAh batteries give the device a claimed seven-hour lifespan, which if true will put a lot of computing power in your pocket for a productive day’s work. The basic unit houses a Raspberry Pi 5 and a touchscreen, running a full-fat version of the Linux operating system (it looks like Debian with a KDE desktop, which wouldn’t really have been practical with any model of Raspberry Pi until now). 

Soulcircuit claims that the Pilet is “built by open-source software for the open-source community,” and credits KiCad, FreeCAD, Blender, Linux, Raspberry Pi, and KDE. As we’ve seen so many times though, it’s not enough just to have the right software; a device this good takes expertise and imagination, and if it can come in at the expected price of under $200, we’re sure it’ll be popular with open-source geeks who want to get work done but also quite like leaving the house every now and then.

The MagPi #146 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.

The image you provided is the cover of "The MagPi" magazine, issue 146, from October 2024. This magazine is dedicated to Raspberry Pi enthusiasts. The cover design is orange with black and white elements, featuring a retro horror theme. Some of the key elements on the cover include: The main headline, "PLAY RETRO HORROR CLASSICS ON RASPBERRY PI 5," likely highlighting a feature on retro horror games. The text "Police Line Do Not Cross" in several places, adding to the spooky, horror theme, possibly in reference to crime or mystery-themed games. The imagery of a crow, a spooky-looking house, a cassette tape, and various retro gaming motifs, reinforcing the horror and retro gaming aesthetic. Additional highlights like "LEGO Card Shuffler," "Top 10 Spooky Projects," and "Recycle a Fighter Jet Joystick," suggesting other tech and DIY projects featured in this issue. The bottom of the cover mentions "TURN IT UP TO 11 WITH AUDIO UPGRADES," hinting at content related to enhancing audio experiences. The overall theme seems focused on retro horror gaming and tech projects for Raspberry Pi.

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 Pilet: Mini Pi 5 modular computer appeared first on Raspberry Pi.

Gugusse Roller transfers analogue film to digital with Raspberry Pi

This canny way to transfer analogue film to digital was greatly improved by using Raspberry Pi, as Rosie Hattersley discovered in issue 145 of The MagPi.

Gugusse is a French term meaning something ‘quite flimsy’, explains software engineer and photography fan Denis-Carl Robidoux. The word seemed apt to describe the 3D-printed project: a “flimsy and purely mechanical machine to transfer film.” 

The Gugusse Roller uses Raspberry Pi HQ camera and Pi 4B+ to import and digitise analogue film footage
Image credit: Al Warner

Denis-Carl created Gugusse as a volunteer at the Montreal museum where his girlfriend works. He was “their usual pro bono volunteer guy for anything special with media, [and] they asked me if I could transfer some rolls of 16mm film to digital.” Dissatisfied with the resulting Gugusse Roller mechanism, he eventually decided to set about improving upon it with a little help from Raspberry Pi. Results from the Gugusse Roller’s digitisation process can be admired on YouTube.

New and improved

Denis-Carl brought decades of Linux coding (“since the era when you had to write your own device drivers to make your accessories to work with it”), and a career making drivers for jukeboxes and high-level automation scripts, to the digitisation conundrum. Raspberry Pi clearly offered potential: “Actually, there was no other way to get a picture of this quality at this price level for this DIY project.” However, the Raspberry Pi Camera Module v2 Denis-Carl originally used wasn’t ideal for the macro photography approach and alternative lenses involved in transferring film. The module design was geared up for a lens in close proximity to the camera sensor, and Bayer mosaics aligned for extremities of incoming light were at odds with his needs. “But then came Raspberry Pi HQ camera, which didn’t have the Bayer mosaic alignment issue and was a good 12Mp, enough to perform 4K scans.” 

Gugusse Roller fan Al Warner built his own version
Image credit: Al Warner

Scene stealer

Denis-Carl always intended the newer Gugusse Roller design to be sprocketless, since this would allow it to scan any film format. This approach meant the device needed to be able to detect the film holes optically: “I managed this with an incoming light at 45 degrees and a light sensitive resistor placed at 45 degrees but in the opposite direction.” It was “a Eureka moment” when he finally made it work. Once the tension is set, the film scrolls smoothly past the HQ camera, which captures each frame as a DNG file once the system detects the controlling arms are correctly aligned and after an interval for any vibration to dissipate. 

Version 3.1 of Denis-Carl’s Gugusse Roller PCB

The Gugusse Roller uses Raspberry Pi 4 to control the HQ Camera, three stepper motors, and three GPIO inputs. So far it has scanned thousands of rolls of film, including trailers of classics such as Jaws, and other, lesser-known treasures. The idea has also caught the imagination of more than a dozen followers who have gone on to build their own Gugusse Roller using Denis-Carl’s instructions — check out other makers’ builds on Facebook.

Denis-Carl Robidoux beside his Gugusse Roller film digitiser

The post Gugusse Roller transfers analogue film to digital with Raspberry Pi appeared first on Raspberry Pi.

It’s all hands OFF deck with this Pi-powered LEGO card shuffler

Who needs to laboriously shuffle their own deck when Raspberry Pi can do it for you? In the latest issue of The MagPi, our recent intern, Louis Wood, tells us all about the nifty LEGO card shuffler he designed during his summer spent in the Maker Lab.

Maker and Cambridge engineering undergraduate Louis Wood first encountered Raspberry Pi while looking for a low-cost microcontroller that could be programmed with Python for an A-level project. Inspiring plenty of envy, he’s just spent six whole weeks ensconced in Raspberry Pi HQ’s very own maker space building a range of Raspberry Pi projects, including a LEGO card shuffler. Basing it around the LEGO Build HAT helped him evolve and improve upon a design that he and his Queens’ College Cambridge friends, Lucas Hoffman and Emily Wang, devised. The card shuffler idea was their response to a design and build challenge, based around a LEGO NXT system, to demonstrate an aspect of engineering science. The dual-motor design was in need of some reworking, which Louis undertook while working as an intern at Raspberry Pi Towers alongside Maker in Residence Toby Roberts.

A MicroPython script takes shuffling out of your hands by spinning these wheels alternately and pushing cards into the shuffled pile at random

Quirky and cool

Louis used a LEGO Spike education kit with Raspberry Pi’s LEGO Build HAT to create a simpler but more robust design. The kit includes cycle motors, which he attached directly to the Build HAT’s four connectors. “The Build HAT made it pretty easy to pick up all the motors and plug them in.” He then programmed Raspberry Pi 4 over SSH, “which made it easy to tweak code.”

The MicroPython code produces either a one or a zero and spins either the left or right motor accordingly: “When the motor turns on, the wheel spins a few cards into the middle.” The motors run on a loop, each powering on for a second or two, pushing cards from each side and randomly shuffling them into a central pile until the Build HAT colour sensors detect the black base of either card bay. The card shuffler then skips that side and only runs the opposite motor for a while to clear the rest of the cards. Once it notices it’s done shuffling, it stops.

The build took a couple of hours, and Louis spent a similar time coding and tweaking the build. “The hardest thing was making it so that it doesn’t just spit out the whole side [of cards] at once,” he says.

His simple-but-effective barrier is positioned such that only a single card at a time can (usually) be shuffled along by the motor. The setup doesn’t always work flawlessly, occasionally requiring the user to deftly flick a card back into place, but Louis aims to improve the design by moving apart the two card holding sides to prevent blockages.

The dynamic Raspberry Pi 4 × Build HAT duo at work

The Build HAT came into its own thanks to the colour sensor Raspberry Pi 4 used to detect whether there were still cards awaiting shuffling. The white background of the cards contrasted with the black base of the crates he’d created, which was visible only when the stack of cards was depleted. Other card decks — such as Uno ones, which usually have a black background — could be shuffled too, as long as the card holder base colour was changed.

Makers gonna make

Two weeks into his internship, Louis had already created and written about a ‘Pixie’ tube clock and had been building “a Raspberry Pi mount and cooling system for one of the engineers upstairs, so you can sort of be running eight Raspberry Pis at the same time, fans, and an enclosure,” as well as a remote control based on the brand-new Pico 2.

Louis’ Pixie clock (Pi-powered Nixie clock) has since been repurposed as a TikTok ‘likes’ counter

Given this prodigious rate of design, we asked whether an engineering career or one as a maker is in his future. “I’d like to be a maker, but I think it’s quite hard…” Louis said. “To be a maker YouTuber takes a lot of work and time, I think… probably a bit risky.”

Read the full story, including some extra tips and projects from maker Louis Wood, in The MagPi #146.

The MagPi #146 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.

The image you provided is the cover of "The MagPi" magazine, issue 146, from October 2024. This magazine is dedicated to Raspberry Pi enthusiasts. The cover design is orange with black and white elements, featuring a retro horror theme. Some of the key elements on the cover include: The main headline, "PLAY RETRO HORROR CLASSICS ON RASPBERRY PI 5," likely highlighting a feature on retro horror games. The text "Police Line Do Not Cross" in several places, adding to the spooky, horror theme, possibly in reference to crime or mystery-themed games. The imagery of a crow, a spooky-looking house, a cassette tape, and various retro gaming motifs, reinforcing the horror and retro gaming aesthetic. Additional highlights like "LEGO Card Shuffler," "Top 10 Spooky Projects," and "Recycle a Fighter Jet Joystick," suggesting other tech and DIY projects featured in this issue. The bottom of the cover mentions "TURN IT UP TO 11 WITH AUDIO UPGRADES," hinting at content related to enhancing audio experiences. The overall theme seems focused on retro horror gaming and tech projects for Raspberry Pi.

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 It’s all hands OFF deck with this Pi-powered LEGO card shuffler appeared first on Raspberry Pi.

Raspberry Pi Pico brings junked joysticks back to life | The MagPi #146

In the latest issue of The MagPi, out today, we talk to David Miles, who designed a Raspberry Pi Pico kit to bring junked joysticks back to life.

One of the many great things about the EMF Camp events is the swap shop tent, where all kinds of things are brought to be sold and exchanged. On one of my many visits there, I found a slightly worn (but very heavy) pair of joysticks which looked as if they had been part of a professional simulator at some point. In this article, I’ll talk about how I reverse-engineered them to create a fully fledged flight simulator controller. Along the way, I happened to create a Pico program that makes it easy to use any input device as a USB joystick. 

The image shows two gimbal joysticks resting on grass. These joysticks are industrial or military-grade, manufactured by "Ultra Electronics" (Electrical Division). They both have black bases with model information labels on them, identifying the joysticks as part of the Ultra Electronics line. Left Joystick: It appears worn, with patches of the original paint chipped away, revealing a lighter color underneath. The grip features several buttons and what looks like a control hat (small thumbstick). Right Joystick: This one appears to be in better condition, with a smoother and more consistent finish. It also has buttons and a control hat, similar to the left joystick, but the design is slightly more compact and less worn. Both joysticks are mounted on black gimbal bases, which allow for multidirectional movement, and each has a label with the Ultra Electronics branding. The labels contain text, including "Gimbal Joystick" and some part or batch numbers, but they are partially obscured or difficult to read due to the angle. These joysticks could be from fighter jets or advanced simulation setups.
Figure 1: The joysticks as I found them in the EMF Camp swap shop

Getting started

Figure 1 shows the joysticks as I found them. Ultra Electronics is a manufacturer of devices for the Ministry of Defence in the UK, so this looked like something interesting. My hope was to try and get them working so I could use them with a flight simulator for a plane that used joysticks like these. This meant I had two challenges:

  • Getting data out of the joystick
  • Making something which connects to a PC as a game controller

Follow the signals

To discover how to get data out of the joystick, I had a look at the wires that came out of it. The main unit has two plugs on the end of a (surprisingly long) wire — what looks like a nine-pin RS232 serial connector, and a 15-pin game port connector. The secondary joystick (the one on the right in Figure 1) has a 25-pin connector which plugs into the primary one, which suggests that it just contains switches, and that the first is the brains of the operation. The connector types fit the late-’90s feel of the hardware and give clues as to how we can talk to it, but we can take a look inside to confirm some assumptions.

Figure 2 shows the view inside the device. There are four screws holding the top part of the joystick inside the case. After removing these, the whole stick and gimbal assembly lifts out and we can see this circuit board. Some of the components on here give us some pointers on how this works.

The image shows the internal components of an electronic device, likely part of the control mechanism for the joysticks in the previous image. It features a printed circuit board (PCB) with various electronic components and wiring. Key elements visible in the image include: Integrated Circuits (ICs): Several IC chips are mounted on the PCB, including some marked with "H" and what appears to be part numbers like "CD74AC573E" and "1814306." These ICs likely control the logic and processing functions of the device. Dip Switches: A blue section of the board has multiple red dip switches, which are used to configure the device for various settings or functions. Wiring: Color-coded wires connect the board to a nearby connector, which suggests this component interfaces with other parts of a larger system. The wiring is neatly organized and secured in place with black ties. Labelled Component: One chip has a white label with "PRG_OBDO," which could indicate this is a programmable chip or ROM that stores specific instructions or firmware for the device. LEDs or Indicators: Several small red components, possibly LEDs, are mounted near the switches, likely serving as status indicators for the system. This appears to be a custom-built or specialized electronics module, possibly part of a control system for industrial or aviation-related equipment, given the context of the previous images. The wiring and the presence of programmable chips suggest it controls a complex system.
Figure 2: The PCB at the heart of the joystick. Look at all those carefully adjusted and sealed calibration resistors!

There’s a chip with a label covering it. This is normally a sign of some sort of microcontroller, indicating that there’s more going on than just a simple controller. This is backed up by seeing some chips with ‘ADC’ on them — this stands for ‘Analogue to Digital Converter’, and could be used to turn an analogue value (e.g. the position of a potentiometer in a joystick) into a digital value sent to a computer. 

Finally, in the middle, there is a chip with ‘MAX232’ written on it. This family of chips are used to convert 5v logic levels you often see used in microelectronics to the 15v levels used in RS232 communications. This is another sign that the nine-pin connector is probably a regular RS232 connector I can use to get data from the joystick.

This leaves the 15-pin connector. Is it a game port? Game port connectors were often used in the ’90s to connect a joystick to your PC (confusingly, often using a socket on your sound card). They allowed you to connect two joysticks to your computer, each with two buttons. We can see that this joystick has more than four buttons — doing a quick count, we seem to have about 30, so maybe it’s being used for something else.

The image shows the internal view of a joystick, likely the same worn joystick seen in a previous image. The outer casing has been removed to reveal the internal wiring and components. Key elements include: Wiring: A bundle of color-coded wires runs vertically inside the joystick housing. The wires are neatly organized and secured with black ties, indicating they are part of the internal control system that connects the buttons and control mechanisms of the joystick to the external interface. Capacitor: A large black cylindrical component marked "2I649" and "T2" appears to be a capacitor. Capacitors like this are used for energy storage within electrical circuits and are common in joystick designs to manage power surges or smooth out signals. Metal Shaft: A metal rod or shaft is visible running vertically through the center of the joystick, likely part of the gimbal system that allows for multidirectional movement. Green Component: Near the bottom, there's a small green component with what looks like a circular interface or sensor, possibly related to the joystick's motion tracking or button functionality. Buttons: The top of the image shows part of the joystick grip with external buttons still visible, including a red button and a few other black controls. These buttons are connected to the internal components via the wiring. This internal view reveals the intricate electronic design and mechanical structure of the joystick, highlighting its complexity as a precision control device, likely for industrial or aviation purposes.
Figure 3: All the wires have unique colour combinations

If we pull the back off the connector, we can see that there are only two pins connected using red and black wires. If we check those pins on the game port specification, we see that these are connected to ground and 5v.

This fits in with our earlier findings. There’s no way to power a device over a regular serial connection, but using a game port alongside a serial connector would allow you to connect to a PC and transfer power and data.

Plugging it in

Now that we think we know how this works, we can have a go at connecting it to a computer. To do this, I used a regular USB-to-serial converter and a power adapter connected to a USB power bank.

After connecting power, I could see a steady 100ma power draw, which felt reassuring, so I hooked up the serial connection and tried a few different configurations to see if I could receive anything sensible. Eventually, I found one which gave me a regular stream of data which changed as I moved the controls and pressed buttons. It turns out that these joysticks work at 9600 baud (around 100 characters per second) and send 8-bit data. 

The image shows two dialog boxes from the "Game Controllers" settings interface in a Windows operating system. These settings are used to configure and test game controllers connected to the computer. The controller being used appears to be recognized as a "CircuitPython HID" device. Left Dialog Box: Title: "Game Controllers" This box lists the connected game controllers and their status. One controller is listed: "CircuitPython HID," which has a status of "OK," indicating that the controller is recognized and functioning correctly. Buttons include "Advanced" and "Properties" for further configuration or testing of the device. Right Dialog Box: Title: "CircuitPython HID properties" This is the "Test" tab for the game controller, allowing the user to test and calibrate various inputs of the controller. Axes Section: There are visual indicators for the X Axis/Y Axis, Z Axis, and Z Rotation. The test allows movement of the joystick to see how the axes respond in real time. Buttons Section: A grid of red circles represents buttons on the controller, where each circle lights up when a corresponding button on the joystick is pressed. Currently, all the button indicators are off. Point of View Hat Section: This section represents the directional pad (or "POV hat") found on some controllers, allowing for testing of its functionality. Overall, this image shows the controller has been successfully recognized by the system and is being tested using the built-in Windows game controller settings. The "CircuitPython HID" designation suggests the controller is using the CircuitPython library, commonly used for custom hardware projects like joysticks.
Figure 4: This is how Windows sees the controller. The Raspberry Pi has a similar interface for joysticks

Now that I had data, the next thing was to decode it. I started by writing a Python program to read from the joystick and write it out. By starting to build something on the PC, I would have something I could then use on a Pico with CircuitPython.

Working through the controls on the joystick, I found that each button corresponds to a single bit in the data, and each of the axes (X and Y movements of the sticks) with a byte in the output, ranging from -128 to 127, and encoded using two’s complement.

Making a game controller

Now that I could read from the joystick, I needed to send these to the computer as a proper game controller that could be used by programs such as Microsoft Flight Simulator. Figure 3 shows what I was aiming for: I wanted all the abilities of the joystick to be exposed for use on the PC. 

A Raspberry Pi Pico was the perfect thing to use here as it has great IO options and support for working in Python. I needed to configure it to announce itself as a game controller over USB, and then adapt my code to run on the Pico and send the appropriate messages to the PC.

Fortunately, CircuitPython has great support for making custom devices like this. First, we need to define how we want our device to appear over USB, and write some Python to make sure this is registered whenever the Pico connects over USB.

The image shows a collection of electronic components and connectors laid out on a red surface, likely part of a hardware setup for interfacing with or powering a device. Key components include: USB Power Supply: A black external battery pack is powering the setup via a USB cable. The USB cable is connected to a small red "USB Power" module with an integrated display showing output values, including 4.94V and 0.18A. This module is likely monitoring the power draw of the connected components. DB9 Connectors: There are two separate DB9 (serial) connectors. One has a grey body and a blue breakout board at the top, while the other appears to be connected to a green terminal block for wiring. These connectors are typically used for RS-232 or other serial communication interfaces, often found in industrial or retro computing hardware. Breakout Boards: The setup includes at least two small breakout boards attached to the serial connectors. These boards seem to have small ICs and wiring that enable communication or power regulation between the connected devices. Wiring: Several wires, color-coded in yellow, black, and red, are connecting various parts of the setup. Some wires are plugged into a pin header at the left, likely for GPIO or serial communication. Overall Setup: The combination of serial connectors, breakout boards, and USB power monitoring suggests this setup is being used for testing or interfacing with an external device, perhaps an older serial-controlled system or custom hardware. The USB power module ensures that the components receive regulated power, while the serial connectors enable communication between devices. This configuration looks like a development or testing setup for a project involving serial communication and low-power electronics.
Figure 5: The system laid out on the desk. At the top is the power supply provided by a USB battery, at the left is a Raspberry Pi Pico connected to the PC using USB, in the middle is the RS232 interface, and on the right is the game port adapter

This involves digging into the world of USB HID descriptors. HID stands for Human Interface Device, and covers a wide range of gadgets which you can connect over USB, including mice, keyboards, and game controllers, even going as far as volume controls and exercise equipment. 

These descriptors contain information about the device, such as what class it is and which types of data it will send to the PC. By default, CircuitPython supports only a mouse and keyboard. We need to send a descriptor which contains the different axes, buttons, and hats the controller supports.

The full specification for this is on the official www.usb.org site, but we can extend the Adafruit example to increase the number of buttons to 32, and to add an additional entry for the joystick’s hats. 

Putting the boot in

When building CircuitPython projects, you will normally write Python in the code.py file. Code in this file runs after the Pico has initialised USB, so it’s too late to change anything about the device. To do this, we need to look at the lesser-known boot.py file. This file runs when CircuitPython first boots, and before USB is configured, which means that you can make changes to the USB devices that are registered. 

The image shows the interior of what appears to be an aircraft cockpit, with a focus on two joysticks. These joysticks are positioned in front of a set of displays and control panels. Key elements in the image: Joysticks: The foreground joystick is similar to the one seen in previous images, with visible paint wear and a weathered appearance, revealing a lighter color underneath. It has multiple buttons and controls, including a prominent red button and a thumbstick on top. The background joystick is in better condition, with less visible wear and a more uniform appearance. It has similar controls, including buttons and knobs. Cockpit Displays: Behind the joysticks, there are large digital displays, some of which show what appears to be radar or navigation information. The green display on the left is likely a radar or targeting screen, while the right display shows a similar visual. Control Panels: The cockpit is filled with various buttons, switches, and dials, typical of a fighter jet or advanced aircraft. These controls are likely used for navigation, communication, and weapon systems. This image suggests the joysticks are part of an aircraft control system, likely in a military or aviation simulation environment. The worn joystick in the foreground might be an older or heavily used unit, while the cockpit setup and display screens indicate advanced avionics and targeting systems common in modern fighter jets or flight simulators.
Figure 6: The EMF joystick with its virtual counterpart. This looks like a close match to the real thing

The program in the code.py file reads data packets from the joystick, decodes values from the data, and sends USB messages corresponding to the state of the joystick. The present version is in two parts. The first reads the data into a buffer, and the second pulls values out of this buffer and sends USB messages. 

Bringing it all together

Finally, we need to integrate our project which reads from the PC serial port with our game controller code. As the Pico only supports 5v logic levels, we can use our own MAX232 to map the RS232 voltages to something the Pico can handle. To do this, I used an integrated module with a DB-9 connector on one side and a pin header on the other, connected to the Pico. I could also power the joystick from the Pico’s 5v supply.

Now that I had the two halves of the project working together, it was a case of going through the buttons on the device and mapping them across to the controls defined for the controller. This was one of the more tedious parts of the project, but it was a good chance to make sure everything was working correctly.

The image shows a combination of a physical hardware setup and a simulation displayed on a monitor. Key elements: Monitor Display: The monitor displays a realistic aircraft cockpit, likely from a flight simulator. The cockpit features multiple digital screens with radar, navigation, and flight information, including a map, similar to what might be seen in a modern fighter jet. The design and layout of the cockpit are highly detailed, suggesting a realistic simulation environment, perhaps for military or aviation training or entertainment. Hardware Setup: In front of the monitor, there is a physical setup on a red desk, which includes: USB Power Module: A red USB power module similar to what was seen in previous images, connected to the external power source (a black battery pack) and other components. DB9 Serial Connectors and Breakout Boards: The serial connectors, wiring, and breakout boards are also present, part of an electronic interface setup, likely interfacing with the joystick and/or the simulator. Green Microcontroller Board: A small green board with headers and connections, possibly a microcontroller like a Raspberry Pi or an Arduino, is also connected to the system, likely controlling the joystick or interfacing with the simulator. Joystick: In the foreground, someone is holding the joystick (the same one seen in previous images). The person appears to be interacting with the simulation displayed on the monitor, suggesting that the joystick is being used as a control input for the flight simulator. The person is wearing gloves, which might be to protect the equipment or for comfort when handling the joystick during extended use. Context: This image seems to show a setup where a custom-built joystick (and related electronics) is being used to control a flight simulator. The combination of the joystick, the hardware setup on the desk, and the detailed simulator on the monitor points to a project involving custom hardware integration for flight control, possibly as part of a DIY or experimental setup. The physical electronics appear to enable the connection between the joystick and the simulator, allowing for real-time interaction with the simulated aircraft environment.
Figure 7: The joystick in action

Finally, I’ve got everything I need to use the joystick to control a plane running on the PC. Here I’m using it to control the McDonnell Douglas F/A-18 included with Flight Simulator, which has a similar stick to this, but with two hats swapped. I still don’t know precisely which plane (if any) this joystick is based on. The AV-8 Harrier has those hats in the correct order, but has an extra button just below them on the face of the joystick.

I’ve not been able to find any images of joysticks similar to the second stick anywhere, so if you have any idea where that could have come from, please let me know! 

Read the full story, including some extra tips from the maker David Miles, in The MagPi #146.

The MagPi #146 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.

The image you provided is the cover of "The MagPi" magazine, issue 146, from October 2024. This magazine is dedicated to Raspberry Pi enthusiasts. The cover design is orange with black and white elements, featuring a retro horror theme. Some of the key elements on the cover include: The main headline, "PLAY RETRO HORROR CLASSICS ON RASPBERRY PI 5," likely highlighting a feature on retro horror games. The text "Police Line Do Not Cross" in several places, adding to the spooky, horror theme, possibly in reference to crime or mystery-themed games. The imagery of a crow, a spooky-looking house, a cassette tape, and various retro gaming motifs, reinforcing the horror and retro gaming aesthetic. Additional highlights like "LEGO Card Shuffler," "Top 10 Spooky Projects," and "Recycle a Fighter Jet Joystick," suggesting other tech and DIY projects featured in this issue. The bottom of the cover mentions "TURN IT UP TO 11 WITH AUDIO UPGRADES," hinting at content related to enhancing audio experiences. The overall theme seems focused on retro horror gaming and tech projects for Raspberry Pi.

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 Raspberry Pi Pico brings junked joysticks back to life | The MagPi #146 appeared first on Raspberry Pi.

OUT NOW: The Official Raspberry Pi Handbook 2025 has landed

Hey folks, long time no speak! Thankfully I’m returning to the blog to bring tidings of good cheer: the brand new Official Raspberry Pi Handbook 2025 is out now! And with three months to spare before Christmas, wink wink, nudge nudge.

Our annual bumper book is lovingly made by us folks from The MagPi, the official Raspberry Pi magazine, and we’ve got another fantastic edition for you to read.

This is where the fun begins

Every year it’s my job to find the very best community projects, build guides, and essential kit reviews to fit into just 200 pages. It’s a bit of a squeeze but I think there’s something for everyone this year as always.

Front cover of the official raspberry pi handbook 2025 with a big raspberry pi 5 in the middle and seven pi-powered projects round the edges

Raspberry Pi Pico 2 deep dive

A month ago, Pico 2 debuted to the world, and we’re very excited by the possibilities of the extra power it (and the RP2350 microcontroller chip) will bring to future projects. In the book you’ll find an in-depth interview with the engineers behind Pico 2, and all the low-down on what makes it so special.

Let’s begin

As usual we have our quick Starter Guide for those wanting to set up their Raspberry Pi for the first time, or even if you need a refresher. It covers every model of Raspberry Pi, from Pi Zero to Pi 400 and Pi 5, and it’s boiled down the basics of what you need to know. Once you’re done with that, go on a quest with your Raspberry Pi and discover what you can do with it.

What an idea!

Need a bit of inspo for your next build? Not sure whether to use a classic Raspberry Pi computer or a Pico microcontroller board? We have you covered with a whole host of incredibly inspiring projects – from AI-powered fortune tellers and cinema-grade cameras to powered exoskeletons and remote-operated submersibles.

We’ll show you how

If you need more than ideas, we have a series of step-by-step guides for some of the very cool things you can do with a Raspberry Pi. Keen to take photos of the stars? We have you covered. Build your own personal automaton to do your bidding? Gotcha. Want to just sit back and relax with some classic video games or your movie library? Yeah, you can do that too.

There’s tons more to discover inside the book, including hardware reviews and fun arts-and-crafts projects. Buy one today and I personally will smile too!

Grab your copy of The Official Raspberry Pi Handbook 2025 for just £14 from the Raspberry Pi Press online store.

The post OUT NOW: The Official Raspberry Pi Handbook 2025 has landed appeared first on Raspberry Pi.

❌