大家好 !我又回來了,今天給大家寫個串口的使用教程吧,OK!開始吧,,
今天我們以串口2作為例子來操作,
使能串口2
Step1:在board.c檔案中添加串口2的使能代碼

Step2:下載到開發板,打開shell工具,可以看到uart2已經使能

新建UART2檔案
Step1:新建一個uasrt2的頭檔案

Step2:根據官方的開發實體, 撰寫代碼
#include <rtthread.h>
#define SAMPLE_UART_NAME "uart2" /* 需要操作的設備 */
static rt_device_t serial; /* 設備句柄 */
static char str[] = "hello RT-Thread!\r\n"; /* 需要發送的資料 */
static int uart_sample(void)
{
rt_err_t ret = RT_EOK;
rt_size_t send_len = 0;
/* 查找系統中的串口設備 */
serial = rt_device_find(SAMPLE_UART_NAME);
if (!serial)
{
rt_kprintf("find %s failed!\n", SAMPLE_UART_NAME);
return -RT_ERROR;
}
/* 以中斷接收及輪詢發送模式打開串口設備 */
ret = rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
if (ret != RT_EOK)
{
rt_kprintf("open device failed\r\n");
return -RT_ERROR;
}
/* 發送字串 */
send_len = rt_device_write(serial, 0, str, (sizeof(str) - 1));
if (send_len != sizeof(str) - 1)
{
rt_kprintf("send data failed\r\n");
return -RT_ERROR;
}
/* 關閉設備 */
ret = rt_device_close(serial);
if (ret != RT_EOK)
{
rt_kprintf("close device failed\r\n");
return -RT_ERROR;
}
rt_kprintf("serial device test successful\r\n");
return RT_EOK;
}
/* 匯出到 msh 命令串列中 */
MSH_CMD_EXPORT(uart_sample, uart device sample);
Step3:下載程式,除錯程式,可以看到測驗成功,我們打開串口看下


OK! 串口成功收到資料, 今天就到這里吧,下次再見,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/232521.html
標籤:其他
上一篇:Cyber UART通信學習
