Skip to content

Contributed by ckdsx.cn, organized by Ai-Thinker

WB2 Example Code Tutorial---Peripheral UART

Click to expand full code
c
**#include** <stdio.h>
**#include** <string.h>
**#include** <FreeRTOS.h>
**#include** <task.h>
**#include** <blog.h> //
**#include** "bl_sys.h"
**#include** <stdio.h>
**#include** <cli.h>
**#include** <hosal_uart.h>
**#include** <blog.h>     //include 一遍头文件即可
**#include** <hosal_uart.h>

**void** **TaskUart**(**void** *param)  //新建无返回函数TaskUart
{

    **uint8_t** data[32]; //定义 数组data
    **int** ret; //定义变量 ret

hosal_uart_dev_t uart_dev_echo = {         .config = {             .uart_id = 0,             .tx_pin = 4, // TXD GPIO             .rx_pin = 3, // RXD GPIO             .cts_pin = 255,             .rts_pin = 255,             .baud_rate = 9600,   //波特率 9600,8,n,1             .data_width = HOSAL_DATA_WIDTH_8BIT,             .parity = HOSAL_NO_PARITY,             .stop_bits = HOSAL_STOP_BITS_1,             .mode = HOSAL_UART_MODE_POLL,         },     };

hosal_uart_dev_t uart_dev_log = {         .config = {             .uart_id = 1,             .tx_pin = 16, // TXD GPIO             .rx_pin = 7,  // RXD GPIO             .cts_pin = 255,             .rts_pin = 255,             .baud_rate = 115200,  //波特率9600,8,n,1             .data_width = HOSAL_DATA_WIDTH_8BIT,             .parity = HOSAL_NO_PARITY,             .stop_bits = HOSAL_STOP_BITS_1,             .mode = HOSAL_UART_MODE_POLL,         },

Click to expand full code
c
    };

    /* Uart init device */   
    hosal_uart_init(&uart_dev_log);  //初始化串口设备 日志
    /* Uart init device */
    hosal_uart_init(&uart_dev_echo); //初始化串口设备 回显
    blog_info("Uart Demo Start");  //日志输出串口示例开始
    **while** (1) //循环
    {
        /* Uart receive poll */ 串口接收
        ret = hosal_uart_receive(&uart_dev_log, data, **sizeof**(data)); //将串口接收到的数据赋值给ret
        **if** (ret > 0) //判断 如果ret大于0
        {
            /* Uart send poll */
            hosal_uart_send(&uart_dev_log, data, ret); //串口输出ret 数据
            blog_info("Get data ");  //日志输出 获得数据
        }
    }
}

/**
  • @brief main

*/

Click to expand full code
c
**void** **main**(**void**) //主函数
{

    xTaskCreate(TaskUart, "TaskUart", 1024, NULL, 15, NULL); //执行串口任务
}

The code already has comments added. If you still have questions, please leave a message! GPIO is the conventional way to operate pins; programs such as blinking an LED can all be implemented using GPIO.

Released under the MIT License. Build Time 2026-09-11 14:52:23