> 文档中心 > Bearpi开发板HarmonyOS之UART读写

Bearpi开发板HarmonyOS之UART读写


wifiiot_uart.h中包含声明UART接口函数

  • 初始化UART
    unsigned int UartInit(WifiIotUartIdx id, const WifiIotUartAttribute *param, const WifiIotUartExtraAttr *extraAttr);
  • 取消UART初始化
    unsigned int UartDeinit(WifiIotUartIdx id);
  • 从UART读取数据
    int UartRead(WifiIotUartIdx id, unsigned char *data, unsigned int dataLen);
  • 将数据写入UART
    int UartWrite(WifiIotUartIdx id, const unsigned char *data, unsigned int dataLen);
  • 设置UART流控制
    unsigned int UartSetFlowCtrl(WifiIotUartIdx id, WifiIotFlowCtrl flowCtrl);

uart读写测试代码,需要将GPIO5和GPIO6短接进行uart数据自发自收。

#include #include #include "ohos_init.h"#include #include "cmsis_os2.h"#include "wifiiot_gpio.h"#include "wifiiot_gpio_ex.h"#include "wifiiot_adc.h"#include "wifiiot_errno.h"#include "wifiiot_uart.h"static const char *data = "Hello, BearPi!\r\n";#define UART_BUFF_SIZE 1024static void uart_task(void){  uint8_t uart_buffer[UART_BUFF_SIZE] = {0};  uint8_t *pData = uart_buffer;  uint32_t ret;  WifiIotUartAttribute attr = {    .baudRate = 115200,    .dataBits = 8,    .stopBits = 1,    .parity = 0,    .pad = 0,  };  ret = UartInit(WIFI_IOT_UART_IDX_1,&attr,NULL);  if(ret != WIFI_IOT_SUCCESS)  {    printf("Failed to init uart! Err code = %d\n", ret);    return;  }   printf("UART Test Start\n");  while(1)  {      UartWrite(WIFI_IOT_UART_IDX_1,(uint8_t *)data,strlen(data));      UartRead(WIFI_IOT_UART_IDX_1,pData,UART_BUFF_SIZE);      printf("read data from uart1============>\r\n %s",pData);      osDelay(100);  }}static void my_led_example(void){     osThreadAttr_t attr;     attr.attr_bits = 0;     attr.name = "uart";     attr.cb_mem = NULL;     attr.cb_size = 0;     attr.priority = 24;     attr.stack_size = 1024*8;     if(osThreadNew((osThreadFunc_t)uart_task,NULL,&attr) == NULL)     { printf("Falied to create adc_func!\n");    }}SYS_RUN(my_led_example);
  • 运行效果
    在这里插入图片描述