本文基于wsl2搭建的ubuntu18.04 + vscode编辑器
很奇怪啊,找了半天居然没人发串口的教程,于是只能自己试一试了,在此发一个阻塞式的串口发送与接收的教程。并且,感谢.ACE彭洪权大佬在我配置环境遇到几十个报错的时候帮我远程搭建环境三四小时,非常感谢!
TIP:请确保您已经走到了官方教程中hb build -f这一步。
1.复制iot_peripheral文件夹
2.粘贴至ohosdemo文件夹
3.粘贴后的文件为iot_peripheral copy文件夹,右键重命名为uart文件夹。
4.打开uart里的BUILD.gn文件,修改红框内为app_uart
import("//device/xradio/xr806/liteos_m/config.gni")
static_library("app_uart") {
configs = []
sources = [
"src/main.c",
"src/test_flash.c",
"src/test_gpio.c",
"src/test_i2c.c",
"src/test_lowpower.c",
"src/test_pwm.c",
"src/test_reset.c",
"src/test_uart.c",
"src/test_watchdog.c",
]
cflags = board_cflags
include_dirs = board_include_dirs
include_dirs += [
"//kernel/liteos_m/kernel/arch/include",
"include",
"//base/iot_hardware/peripheral/interfaces/kits",
]
}
5.修改ohosdemo文件夹下的BUILD.gn文件,[]内添加"uart:app_uart",
group("ohosdemo") {
deps = [
"uart:app_uart",
#"ledpwm:app_ledpwm",
#"led:app_led",
#"hello_demo:app_hello",
#"iot_peripheral:app_peripheral",
#"wlan_demo:app_WlanTest",
]
}
6.打开uart/src/main.c,代码如下:
#include <stdio.h>
#include "ohos_init.h"
#include "kernel/os/os.h"
#include <string.h>
#include "iot_uart.h"
#include "driver/chip/hal_uart.h"
#define UARTID UART1_ID
#define UART_BUFFER_MAXSIZE 50
#define UART_RECEIVE_DATALEN 30
const uint8_t play_Buffer[4] = {0xAA,0x02,0x00,0xAC};
static OS_Thread_t g_main_thread;
static int uart_init(void)
{
HAL_Status status = HAL_ERROR;
UART_InitParam param;
param.baudRate = 9600; // 波特率为9600
param.dataBits = UART_DATA_BITS_8;
param.stopBits = UART_STOP_BITS_1;
param.parity = UART_PARITY_NONE;
param.isAutoHwFlowCtrl = 0;
status = HAL_UART_Init(UARTID, ¶m);
if (status != HAL_OK)
printf("uart init error %d\n", status);
return status;
}
static void MainThread(void *arg)
{
unsigned char uart_buffer[UART_BUFFER_MAXSIZE];
uart_init();
while (1) {
HAL_UART_Transmit_Poll(UARTID, (uint8_t *)play_Buffer, 4);
LOS_Msleep(1000);
HAL_UART_Receive_Poll(UARTID,uart_buffer,6,0x000f);
LOS_Msleep(1000);
HAL_UART_Transmit_Poll(UARTID, (uint8_t *)uart_buffer, 6);
LOS_Msleep(1000);
}
}
void UARTMain(void)
{
printf("UART Test Start\n");
if (OS_ThreadCreate(&g_main_thread, "MainThread", MainThread, NULL,
OS_THREAD_PRIO_APP, 4 * 1024) != OS_OK) {
printf("[ERR] Create MainThread Failed\n");
}
}
SYS_RUN(UARTMain); // Harmony线程入口
7.硬件接线
由于#define UARTID UART1_ID则使用UART1的收发组
本文作者使用USB转TTL接XR806,通过USB转TTL插入电脑,让电脑接收串口收发的信息。
接线如下:
USB转TTL XR806
3.3V-------------3.3V
TXD--------------B15
RXD--------------B14
GND--------------GND
8.代码修改完毕后,按下Ctrl+K再按S将代码全部保存,并再终端输入hb build -f
编译
9.将USB tpye C数据线接上XR806,进行烧录
10.测试串口接收
将USB转TTL接入电脑,打开串口助手,选择新增的COM,波特率选择9600,打开串口,可以接收到AA 02 00 AC即说明XR806能正常发送
11.测试串口发送
在发送框输入01 02 03 04 05 07,并勾选16进制发送,点击发送,可以看到本来的80 25 00 00 00 00改变成了所发送的数据,即说明XR806接收到了所发送的信息并且又将收到的信息发送到了串口助手上显示。若不希望出现80 25 00 00 00 00,则需要在代码中自行修改buffer数组全部改为0,或者设置条件,在接收到之后再发送,发送之后再清空buffer。
教程到这里就结束啦。