How to Write your First C++ Program on the Raspberry Pi Pico
Tags: raspberrypi, sdk, programming, cpp
Published: 2024-06-26 00:13:45

{% embed https://www.youtube.com/watch?v=fqgeUPL7Z6M %}

Welcome to this comprehensive tutorial on setting up, building, and flashing a C++ project for the Raspberry Pi Pico W on macOS. The Raspberry Pi Pico W is a powerful microcontroller board based on the RP2040 microcontroller, featuring dual-core ARM Cortex-M0+ processors, flexible I/O options, and built-in Wi-Fi connectivity. This tutorial will guide you through the entire process, from installing the necessary tools to running a “Hello, World!” program that communicates over USB serial.

In this guide, you will learn how to:

- Set up the development environment on macOS, including installing Homebrew, CMake, and the ARM GCC toolchain.
- Clone and initialize the Pico SDK, which provides essential libraries and tools for developing applications for the Raspberry Pi Pico W.
- Create a simple C++ project that prints “Hello, World!” to the serial console.
- Build and flash your project to the Pico W.
- Connect to the Pico W’s serial output using terminal applications such as screen and minicom.

Whether you’re a seasoned developer or just getting started with microcontrollers, this tutorial will provide you with the knowledge and skills to begin developing applications for the Raspberry Pi Pico W on macOS.

— — -

**Before we delve into the topic, we invite you to support our ongoing efforts and explore our various platforms dedicated to enhancing your IoT projects:**

1. **Subscribe to our YouTube Channel:** Stay updated with our latest tutorials and project insights by subscribing to our channel at [YouTube — Shilleh](https://www.youtube.com/@mmshilleh).
2. **Support Us:** Your support is invaluable. Consider buying me a coffee at [Buy Me A Coffee](https://buymeacoffee.com/mmshilleh) to help us continue creating quality content.
3. **Hire Expert IoT Services:** For personalized assistance with your IoT projects, hire me on [UpWork](https://www.upwork.com/freelancers/~017060e77e9d8a1157).

**ShillehTek Website (Exclusive Discounts):**

[https://shillehtek.com/collections/all](https://shillehtek.com/collections/all)

**ShillehTekAmazon Store:**

[ShillehTek Amazon Store — US](https://www.amazon.com/stores/page/F0566360-4583-41FF-8528-6C4A15190CD6?channel=yt)

[ShillehTek Amazon Store — Canada](https://www.amazon.ca/stores/page/036180BA-2EA0-4A49-A174-31E697A671C2?channel=canada)

[ShillehTek Amazon Store — Japan](https://www.amazon.co.jp/stores/page/C388A744-C8DF-4693-B864-B216DEEEB9E3?channel=japan)

## Step 1: Set Up the Environment

**Install Prerequisites:**

Homebrew: Install Homebrew if you haven’t already:

```
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```

CMake and ARM GCC Toolchain:

```
brew install cmake gcc-arm-none-eabi
```

**Clone the Pico SDK:**

```
mkdir -p ~/pico
cd ~/pico
git clone -b master https://github.com/raspberrypi/pico-sdk.git
cd pico-sdk
git submodule update --init
```

**Set the Environment Variable:**

Set the PICO_SDK_PATH environment variable in your shell configuration file (~/.zshrc for Zsh or ~/.bashrc for Bash):

```
echo 'export PICO_SDK_PATH=~/pico/pico-sdk' >> ~/.zshrc
source ~/.zshrc
```

## Step 2: Create a C++ Project

**Create a Project Directory:**

```
mkdir -p ~/pico/my_project
cd ~/pico/my_project
```

**Create a CMakeLists.txt File:**

```

cmake_minimum_required(VERSION 3.13)

# Include the Pico SDK initialization script
include($ENV{PICO_SDK_PATH}/pico_sdk_init.cmake)

project(my_project)

# Initialize the Pico SDK
pico_sdk_init()

# Add your executable and source files
add_executable(my_project
    main.cpp
)

# Enable USB stdio and disable UART stdio
pico_enable_stdio_usb(my_project 1)
pico_enable_stdio_uart(my_project 0)

# Link the Pico SDK to your project
target_link_libraries(my_project pico_stdlib)

# Create map/bin/hex/uf2 files
pico_add_extra_outputs(my_project)
```

**Create a main.cpp File:**

```
#include "pico/stdlib.h"
#include <cstdio> // Include the C standard IO functions

int main() {
    stdio_init_all(); // Initialize standard IO

    while (true) {
        printf("Hello, World!\n");
        sleep_ms(1000);
    }
}
```

## Step 3: Build and Flash the Project
**Navigate to the Build Directory and Clean it:**

```
mkdir -p build
cd build
rm -rf *
```
**Run CMake to Generate Build Files:**

```
cmake ..
```

**Build the Project:**

```
make
```

**Flash the Firmware:**

- Unplug the Pico W from your Mac.
- Hold down the BOOTSEL button.
- While holding the BOOTSEL button, plug the Pico W back into your Mac. The Pico should appear as a mass storage device (RPI-RP2).
- Copy the generated .uf2 file to the Pico:

```
cp my_project.uf2 /Volumes/RPI-RP2/
```
Now that your UF2 file is on the device, your Pico W should start running it and logging to serial output. The next step shows you commands you can utilize to view the output of the program!

## Verify Serial Connection

## Using screen
**Set the TERM Environment Variable:**

If you encounter issues with the $TERM too long - sorry. error in screen, set the TERM environment variable to vt100 to ensure compatibility with screen:

```
export TERM=vt100
```
Check for Serial Device:

```
ls /dev/tty.*
```
Look for a device like 

`/dev/tty.usbmodemXXXX`.

**Connect Using `screen`:**

```
screen /dev/tty.usbmodemXXXX 115200
```
**View the Output:**

- If the Pico W is running your program correctly, you should see the “Hello, World!” messages being printed to the terminal every second.
**Exit screen:**

- To exit screen, press Ctrl+A followed by K, and then confirm by pressing Y.

## Conclusion
Congratulations! You have successfully set up your development environment, created and built a C++ project, and flashed it to your Raspberry Pi Pico W. You also learned how to connect to the Pico W’s serial output using screen and minicom, ensuring you can monitor and interact with your running programs.

With these foundational skills, you’re now ready to explore the full potential of the Raspberry Pi Pico W. Whether you want to build IoT applications, create interactive devices, or experiment with embedded systems, the knowledge gained from this tutorial will serve as a solid starting point.

Continue experimenting and building more complex projects, and don’t hesitate to explore the extensive documentation and resources available for the Raspberry Pi Pico W. Happy coding!