Raspberry Pi Pico UART protocol via serial USB
One of Pico’s key features is the ability to communicate with others devices via UART. In this post, i will covering the concepts, pinout, guide with sample code about UART.
Serial Communication
Serial communication, oftern reffered to as UART comm, is a method of transmitting and receiving data between two devices. The ‘serial’ means that this protocol sends data one by one consequently over a single wire. It uses two wires for communication: one for transmit (TX) and other for receiving (RX). That makes this protocol so simple and efficient way to communicate between two devices.
Pico's UART
The Raspberry Pi Pico (RP2040) microcontroller has 2x UARTs mmodules for serial communication: UART0 and UART1. And the UART pins can remappable (which means you can assign it to different GPIO of the MCU). However, the default uart0 pins is GPIO0(TX) and GPIO1(RX).
However, this MCU also have a native hardware USB modules (CDC class) to act as a serial port and could be viewed by any PC as a Virtual COM port. So we dont need to use a USB-TTL converter (which is less convenient to communicate with a PC).
Serial Print
Enable USB CDC
To enable serial print, you need to add the below code into the CMakeLists.txt file:
1
2
pico_enable_stdio_usb(main 1)
pico_enable_stdio_uart(main 0)
That will enable the stdio funcions over USB instead of UART. main here is the name of the excutable C-code file (when you compile the main.c). After enabling the stdio functions over USB, we will now able to use the printf() function to send strings over the USB port. And here is the example to print a message over USB port
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include "pico/stdlib.h"
int main()
{
stdio_init_all();
while (1)
{
printf("It's From Pico USB CDC\n");
sleep_ms(100);
}
}
Examples
We’ll set a IO pin as an output to a LED (the built-in LED GPIO2). And we’ll enable stdio operations over USB CDC. Then a message will be printed to the user with the bit 0 or 1 to express the output LED status (OFF/ON).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
#include "pico/stdlib.h"
#define LED_PIN 2
int LED_STATE = 0;
int main()
{
uint8_t state = 0;
gpio_init(LED_PIN);
gpio_set_dir(LED_PIN, GPIO_OUT);
stdio_init_all();
while (1)
{
state = gpio_get(LED_PIN);
gpio_put(LED_PIN, state);
sleep_ms(500);
}
}
and the full source code of CMakeLists.
1
2
3
4
5
6
7
8
9
cmake_minimum_required(VERSION 3.13)
include(pico_sdk_import.cmake)
project(HELLO_WORLD C CXX ASM)
pico_sdk_init()
add_executable(main main.c)
target_link_libraries(main pico_stdlib)
pico_enable_stdio_usb(main 1)
pico_enable_stdio_uart(main 0)
pico_add_extra_outputs(main)