Section 2.2 Compiling and running C code
The Pico SDK comes with a lot of example code. We will use some of it to get started. The example code is in the
pico-examples
directory. We will use the blink
example, which blinks the LED on the Pico board. The code is in the blink
subdirectory, in a file called blink.c
. We will compile it and run it.- Use the Explorer pane at left (click the icon that looks like two pages until you see it) to open the
pico/pico-examples/blink
directory. You should see a file calledblink.c
. If you don’t see the file, make sure you haven’t accidentally opened theblink
subdirectory of the toplevelbuild
folder. - Inspect the code and try to guess what it will do.
- To compile, press
F1
to bring up the Command Palette, typeCMake
, and selectCMake: Build Target
. Select the “blink (executable)” target from the dropdown list. If you selectCMake: Build
instead, it will try to compile all the targets in thepico-examples
directory, which will take a long time. If you are asked to selectCMakeLists.txt
file, you need to press Escape and use the Command Palette to r1un theCMake: Configure
command and choosegcc 9.2.1 (arm-none-eabi)
before runningCMake: Build Target
again. -
You will see a lot of output in the console. Even a simple program like this one makes use of many parts of the SDK, which themselves need to be compiled into machine code along with our
blink.c
file. Those bits of binary need to be linked together into a single executable file. The linker is a program that does this. The linker is invoked by the compiler, which is invoked by CMake, which is invoked by VS Code.On subsequent runs, the compiler will only compile the parts that have changed, and the linker will only link the parts that have changed, which is why the compile is so much faster the second time. - If you see a message like “Exit code 0” in the console, that is success. Go back to the Explorer pane and find the
build/blink/blink.uf2
file. Right-click to download this file. It is the executable file that we will run on the Pico. It is completely self-contained as a “bare metal” executable, also known as firmware. There is no operating system or any other code between theblink
program and the processor. - Plug your Pico into your laptop using a USB cable while holding down the white boot-select button on the Pico board. Only let go of the button once the board is plugged in. You should see a new drive appear in your file explorer (not the Explorer pane in VS Code). It should be called
RPI-RP2
. Drag the UF2 file from the file explorer to theRPI-RP2
drive. This will copy the file to the Pico. The Pico will automatically reboot and run the program. - You should see the LED blinking immediately (unlike with the CircuitPython examples, which take a second or two to begin executing). If you do, congratulations! You have successfully compiled and run your first C program on the Pico! If not, get some help.