RT-Thread Stm32f103開啓UART2(中斷接收及輪詢發送) 使用RT-Thread Studio

RT-Thread Stm32f103開啓UART2 使用RT-Thread Studio

1. 使用RT-Thread Studio新建RT-Thread項目

在這裏插入圖片描述在這裏插入圖片描述

2. 修改dricer->doard.h

  • 增加UART2的宏定義
  • 設置gpio接口
    在這裏插入圖片描述

3. mian.c

串口設備使用示例

中斷接收及輪詢發送

示例代碼的主要步驟如下所示:

首先查找串口設備獲取設備句柄。
初始化回調函數發送使用的信號量,然後以讀寫及中斷接收方式打開串口設備。
設置串口設備的接收回調函數,之後發送字符串,並創建讀取數據線程。
讀取數據線程會嘗試讀取一個字符數據,如果沒有數據則會掛起並等待信號量,當串口設備接收到一個數據時會觸發中斷並調用接收回調函數,此函數會發送信號量喚醒線程,此時線程會馬上讀取接收到的數據。
此示例代碼不侷限於特定的 BSP,根據 BSP 註冊的串口設備,修改示例代碼宏定義 SAMPLE_UART_NAME 對應的串口設備名稱即可運行。
在這裏插入圖片描述

#include <rtthread.h>
#include <board.h>
#include <rtdevice.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>


#define SAMPLE_UART_NAME       "uart2"

/* 用於接收消息的信號量 */
static struct rt_semaphore rx_sem;
static rt_device_t serial;

/* 接收數據回調函數 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
    /* 串口接收到數據後產生中斷,調用此回調函數,然後發送接收信號量 */
    rt_sem_release(&rx_sem);

    return RT_EOK;
}

static void serial_thread_entry(void *parameter)
{
    char ch;

    while (1)
    {
        /* 從串口讀取一個字節的數據,沒有讀取到則等待接收信號量 */
        while (rt_device_read(serial, -1, &ch, 1) != 1)
        {
            /* 阻塞等待接收信號量,等到信號量後再次讀取數據 */
            rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
        }
        /* 讀取到的數據通過串口錯位輸出 */
        ch = ch;
        rt_device_write(serial, 0, &ch, 1);
    }
}

static int uart_sample()
{
    rt_err_t ret = RT_EOK;
    char uart_name[RT_NAME_MAX];
    char str[] = "hello RT-Thread!\r\n";


    /* 查找系統中的串口設備 */
    serial = rt_device_find(SAMPLE_UART_NAME);
    if (!serial)
    {
        rt_kprintf("find %s failed!\n", uart_name);
        return RT_ERROR;
    }

    /* 初始化信號量 */
    rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
    /* 以中斷接收及輪詢發送模式打開串口設備 */
    rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
    /* 設置接收回調函數 */
    rt_device_set_rx_indicate(serial, uart_input);
    /* 發送字符串 */
    rt_device_write(serial, 0, str, (sizeof(str) - 1));

    /* 創建 serial 線程 */
    rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 25, 10);
    /* 創建成功則啓動線程 */
    if (thread != RT_NULL)
    {
        rt_thread_startup(thread);
    }
    else
    {
        ret = RT_ERROR;
    }

    return ret;
}

int main(void)
{
    uart_sample();
    return RT_EOK;
}

4. 運行結果

默認波特率爲115200

  • 串口調試工具
    在這裏插入圖片描述
  • 也可以用RT-Thread Studio自帶的串口調試工具
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述

5. 具體使用可以查看RT-Thread提供串口應用開發文檔

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章