0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

RaspberryPiPicoのUARTでエコーバック

Posted at

やりたこと

RaspberryPiPicoのUARTでエコーバック。

手順

main.c
#include "pico/stdlib.h"
#include "hardware/uart.h"
#include "hardware/irq.h"

// UART RXのIRQハンドラ
void on_uart_rx() {
    while(uart_is_readable(uart0)) {
        // 1文字読む
        uint8_t c = uart_getc(uart0);
        if(uart_is_writable(uart0)) {
            // 読み込んだ文字を書き込み
            uart_putc(uart0, c);
        }
    }
}

// main
int main() {
    
    // GPIOの初期化
    gpio_init(PICO_DEFAULT_LED_PIN);
    // 入出力の設定
    gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);

    // UART0の初期化
    uart_init(uart0, 115200);
    // GPIOの設定
    gpio_set_function(0, GPIO_FUNC_UART);
    gpio_set_function(1, GPIO_FUNC_UART);
    
    // ボーレートの設定
    // 第2引数: CTSを使うかどうか
    // 第3引数: RTSを使うかどうか
    uart_set_hw_flow(uart0, false, false);
    // データフォーマットの設定
    // 第2引数: データビット数
    // 第3引数: ストップビット
    // 第4引数: パリティビットを使うかどうか
    uart_set_format(uart0, 8, 1, UART_PARITY_NONE);
    // FIFOバッファを使うかどうか
    uart_set_fifo_enabled(uart0, false);
    // IRQハンドラの設定
    irq_set_exclusive_handler(UART0_IRQ, on_uart_rx);
    // IRQの有効化
    irq_set_enabled(UART0_IRQ, true);
    // RXのみ設定
    // 第2引数: RXのIRQ
    // 第3引数: TXのIRQ
    uart_set_irq_enables(uart0, true, false);

    while (true) {
        // HIGHを出力
        gpio_put(PICO_DEFAULT_LED_PIN, 1);
        sleep_ms(300);
        // LOWを出力
        gpio_put(PICO_DEFAULT_LED_PIN, 0);
        sleep_ms(300);
    }
}
CMakeLists.txt
# CMakeのバージョン
cmake_minimum_required(VERSION 3.12)

# SDKパス/pico_sdk_init()の定義のパス
set(PICO_SDK_PATH $ENV{PICO_SDK_PATH})
set(PICO_SDK_INIT_CMAKE_FILE ${PICO_SDK_PATH}/pico_sdk_init.cmake)

# PICO SDKのCMakeを読み込み
include(${PICO_SDK_INIT_CMAKE_FILE})

# プロジェクト名
project(sample_blink CXX C ASM)

# C Compilerのバージョン
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)

# PICO SDK CMakeの初期化
pico_sdk_init()

# コンパイルターゲット
add_executable(main
        main.c
        )

# リンクターゲット
target_link_libraries(main pico_stdlib hardware_uart)

# USBシリアルの設定
pico_enable_stdio_usb(main 0)
pico_enable_stdio_uart(main 1)

# 出力ファイル
pico_add_extra_outputs(main)

割り込みハンドラで1文字読み込んで1文字書き込むを繰り返すことで、エコーバックする。

動かすための手順はこちら。

screenコマンドでエンターキーを入力すると、CRが入力され、Ctrl-jでLFが入力される。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?