HOME
Shop
  • English
  • 简体中文
HOME
Shop
  • English
  • 简体中文
  • Product Series

    • FPGA+ARM

      • GM-3568JHF

        • Introduction

          • GM-3568JHF Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Notes
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing System Information
          • Test Commands
          • Application Compilation
          • Source Code Access
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • Serial Port
          • CAN
          • RTC
        • Application Development

          • UART Read/Write Demo
          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • GPS Debugging Demo
          • Ethernet Test Demo
          • RS485 Read/Write Demo
          • FPGA I2C Read/Write Demo
          • PN532 NFC Card-Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to Boot Auto-Start
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Services
        • Downloads

          • Downloads
      • MB-E30P

        • Introduction

          • MB-E30P Introduction
        • Quick Start

          • Preface
          • Environment Setup
          • Compilation Instructions
          • Flashing Guide
          • Debugging Tools
          • Software Update
          • Viewing Information
          • Test Commands
          • Application Compilation
          • Source Code Acquisition
        • Peripherals & Interfaces

          • USB
          • Display and Touch
          • Ethernet
          • WIFI
          • Bluetooth
          • TF-Card
          • Audio
          • RTC
        • Application Development

          • Key Detection Demo
          • LED Blink Demo
          • MIPI Screen Detection Demo
          • Read USB Device Information Demo
          • FAN Detection Demo
          • FPGA FSPI Communication Demo
          • FPGA DMA Read/Write Demo
          • Ethernet Test Demo
          • FPGA IIC Read/Write Demo
          • PN532 NFC Card Reading Demo
          • TF Card Read/Write Demo
        • QT Development

          • ARM64 Cross-Compiler Environment Setup
          • Adding a QT Program to the Boot Auto-Start Service
        • RKNN_NPU Development

          • RK3568 NPU Overview
          • Development Environment Setup
          • Run the Official YOLOv5 Example
          • Model Conversion In Detail
          • Run Custom Models on the Board
        • FPGA Development

          • ARM and FPGA Communication
          • FPGA Development Manual
        • Others

          • Modifying the Root Filesystem
          • System Auto-Start Service
        • Downloads

          • Downloads
    • ShimetaPi

      • M4-R1

        • Introduction

          • M4-R1 Introduction
        • Quick Start

          • OpenHarmony Overview
          • Image Burning
          • Application Development Quick Start
          • Device Development Quick Start
        • Application Development

          • ArkUI

            • ArkTS Language Overview
            • UI Components - Row Container Introduction
            • UI Components - Column Container Introduction
            • UI Components - Text Component
            • UI Components - Toggle Component
            • UI Components - Slider Component
            • UI Components - Animation Component & Transition Component
          • Documentation

            • OpenHarmony Official Materials
          • Development Notes

            • Full-SDK Replacement Tutorial
            • Introducing and Using Third-Party Libraries
            • HDC Debugging
            • Restore Factory Mode via Command Line
            • Upgrade App to System Permission
          • First App

            • Build Your First ArkTS Application - HelloWorld
          • Demos

            • Serial-Debug-Assistant Application Demo
            • Writing-Board Application Demo
            • Digital Clock Application Demo
            • Wi-Fi Information Acquisition Application Demo
        • Device Development

          • Ubuntu Development

            • Environment Setup
            • Download Source Code
            • Compile Source Code
          • DevEco Device Tool

            • Tool Introduction
            • Development Environment Construction
            • Import the SDK
            • HUAWEI DevEco Tool Function Introduction
        • Kernel Peripherals & Interfaces

          • Guide
          • Device Tree Introduction
          • NAPI Introduction
          • ArkTS Introduction
          • NAPI Development Hands-on Demo
          • GPIO Introduction
          • I2C Communication
          • SPI Communication
          • PWM Control
          • UART Communication
          • TF Card (MicroSD)
          • Screen (Display)
          • Touch
          • Ethernet
          • M.2 SSD
          • Audio
          • WIFI & BT
          • Camera
        • Downloads

          • Downloads
      • M5-R1

        • Introduction

          • M5-R1 Development Docs
        • Quick Start

          • Image Burning
          • Environment Setup
          • Download Source Code
        • Peripherals & Interfaces

          • Raspberry Pi Interfaces
          • GPIO Interface
          • I2C Interface
          • SPI Communication
          • PWM Control
          • Serial Port Communication
          • TF Card
          • Display
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI & BT
        • Downloads

          • Downloads
      • Pico-G1

        • Product Overview

          • Product Introduction
          • SDK Version Information
        • Quick Start

          • Development Environment Setup
          • Image Build
          • Image Flashing
          • System Login
          • Network Configuration
          • File Transfer
          • SDK Directory Structure
          • Deploying Your First Application
          • Deploying Your First Driver
          • Mounting an SD Card
        • Peripherals & Interfaces

          • GPIO Control
          • UART Serial Communication
          • I2C Communication
          • SPI Communication
        • MPP Media Development

          • MPP Media Processing Software
          • Image Processing Chain
          • Video Input
          • Image Encoding
        • NPU & AI

          • NPU Driver and Runtime Library Architecture
          • .xmm Model Loading
          • SVP Video Processing
          • AI Noise Reduction (AI_NR)
        • Application Samples

          • Encryption/Decryption Application
          • ADC Acquisition Application
          • Low-Power Application
          • Audio Processing Application
          • Video Encoding Application
          • Video Input Application
          • Video Graphics Subsystem (VGS) Application
          • 08 Region Overlay Application
          • 09 Intelligent Video Engine Application
          • 10 UVC Webcam Application
          • 11 All-in-One Quickstart Application
          • 12 FPN Correction Application
          • 13 Regional Motion Detection Application
          • 14 MTCNN Face Detection Application
        • Expansion Board Peripheral Examples

          • 00 - Pico Expansion Board Peripheral Examples Overview
          • 01 - OLED Display Application
          • 02 - TFT Display Application
          • 03 - MPU6050 Gyroscope Application
          • 04 - ADC Acquisition Application
          • 05 - Passive Buzzer Application
          • 06 - MQ Gas Sensor Application
          • 07 - GPS Positioning Application
          • 08 - SHT20 Temperature & Humidity Application
          • 09 - Ultrasonic Ranging Application
          • 10 - SpO2 Sensor Application
          • 11 - DC Motor Control Application
          • 12 - Servo Control Application
    • OpenHarmony

      • SC-3568HA

        • Introduction

          • SC-3568HA Overview
        • Quick Start Guide

          • OpenHarmony Overview
          • Image Flashing
          • Setting Up the Development Environment
          • Hello World Application and Deployment
        • Application Development

          • ArkUI

            • Introduction to ArkTS Language
            • Introduction to UI Components and Practical Applications (Part 1)
            • Introduction to UI Components and Practical Applications (Part 2)
            • Introduction to UI Components and Practical Applications (Part 3)
          • Expand

            • Getting Started Guide
            • Referencing and Using Third-Party Libraries
            • Application Compilation and Deployment
            • Command-Line Factory Reset
            • System Debugging -- HDC Debugging
            • APP Stability Testing
            • Chapter 7 Application Testing
        • Device Development

          • Environment Setup
          • Download Source Code
          • Compiling Source Code
        • Peripheral And Interface

          • Raspberry Pi interface
          • GPIO Interface
          • I2C Interface
          • SPI communication
          • PWM (Pulse Width Modulation) control
          • Serial port communication
          • TF Card
          • Display Screen
          • Touch
          • Audio
          • RTC
          • Ethernet
          • M.2
          • MINI-PCIE
          • Camera
          • WIFI&BT
          • Raspberry Pi expansion board
        • Downloads

          • Downloads
      • M-K1HSE

        • Introduction

          • M-K1HSE Introduction
        • Quick Start

          • Development environment construction
          • Source code acquisition
          • Compilation Notes
          • Burning Guide
        • Application Development

          • Application Development Environment Setup
          • First Application - Hello World
        • Peripherals and interfaces

          • 01 Audio
          • 02 RS485
          • 03 Display
        • System customization development

          • System transplant
          • System customization
          • Driver Development
          • System Debugging
          • OTA Update
        • Downloads

          • Downloads
    • HVS Camera

      • Quick Start

        • SDK Overview
        • Downloads
        • Your First C++ Program
        • Python Data Analysis
        • MultiVision Studio
      • Development

        • Programming Guides

          • Open Camera
          • Read Events
          • Recording & Replay
          • Event Processing (Denoising)
          • Display & Visualization
          • Tuning
          • Capture APS Image
        • Toolkit SDK

          • Hybrid Vision Toolkit
          • Quick Start
          • C++ API
          • Python API
        • Algorithm

          • Hybrid Vision Algo
          • Hybrid Vision Algo API
          • Windows Algo SDK
        • Samples Overview
        • Applications
      • Fundamentals

        • Event Camera Fundamentals
        • HVS Hybrid Vision
        • Event Visualization
        • Data Formats Reference
        • Glossary
        • Bias & Tuning
        • Video Tutorials
      • USB Cameras

        • HVS Camera Quick Start
        • Networking Capabilities

          • HVS Camera System Architecture
          • EVS Network Server
          • EVS Time Sync
          • Web Window
        • HVS Camera Compatibility Matrix
        • FAQ & Troubleshooting Guide
        • Products

          • CF-NRS1 (Lingguang No.1 Hybrid Vision Camera)
      • MIPI Modules

        • MIPI Module Quick Start
        • Carrier Boards

          • RDK X5 Carrier Board Adaptation
          • Raspberry Pi Carrier Board Adaptation
          • Digua Pi Carrier Board Adaptation
          • ShimeTai Board Carrier Board Adaptation
        • MIPI Module Compatibility Matrix
        • Products

          • EVS_003 Sensor Module
    • AI-model

      • 1684XB-32T

        • Introduction

          • AIBOX-1684XB-32 Introduction
        • Quick Start

          • First Use
          • Network Configuration
          • Disk Usage
          • Memory Allocation
          • Fan Control Strategy
          • Firmware Upgrade
          • Cross Compilation
          • Model Quantization
        • Application Development

          • Development Overview

            • Sophgo SDK Development
            • Sophgo Demo Introduction
          • Large Language Models

            • Deploying Llama3 Example
            • Sophon LLM_api_server Development
            • Deploying MiniCPM-V-2_6
            • Qwen-2-5-VL Image and Video Recognition Demo
            • Qwen3-chat Demo
            • Qwen3-Qwen Agent-MCP Development
            • Qwen3-langchain-AI Agent
          • Deep Learning

            • ResNet (Image Classification)
            • LPRNet (License Plate Recognition)
            • SAM (General Image Segmentation Foundation Model)
            • YOLOv5 (Object Detection)
            • OpenPose (Human Keypoint Detection)
            • PP-OCR (Optical Character Recognition)
        • Downloads

          • Downloads
      • 1684X-416T

        • Introduction

          • AIBOX-1684X-416 Introduction
        • Demo Quick Guide

          • ShimeTai Intelligent Monitoring Demo Quick Usage Guide
      • RDK-X5

        • Introduction

          • RDK-X5 Hardware Introduction
        • Quick Start

          • RDK-X5 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Color Recognition
            • Experiment 03 - Gesture Recognition
            • Experiment 04 - YOLOv5 Object Detection
      • RDK-S100

        • Introduction

          • RDK-S100 Hardware Introduction
        • Quick Start

          • RDK-S100 Quick Start
        • Application Development

          • AI Online Model Development

            • Experiment 01 - Access Volcengine Doubao AI
            • Experiment 02 - Image Analysis
            • Experiment 03 - Multimodal Visual Analysis & Localization
            • Experiment 04 - Multimodal Image-Text Comparison
            • Experiment 05 - Multimodal Document/Table Analysis
            • Experiment 06 - Camera-based AI Visual Analysis
          • Large Language Models

            • Experiment 01 - Speech Recognition
            • Experiment 02 - Voice Conversation
            • Experiment 03 - Multimodal Image Analysis - Voice
            • Experiment 04 - Multimodal Image Comparison - Voice
            • Experiment 05 - Multimodal Document Analysis - Voice
            • Experiment 06 - Multimodal Vision Application - Voice
          • ROS2 Basics

            • Experiment 01 - Environment Setup
            • Experiment 02 - Create & Build a Workspace Package
            • Experiment 03 - Run ROS2 Topic Communication Node
            • Experiment 04 - ROS2 Camera Application
          • 40-pin IO Development

            • Experiment 01 - GPIO Output (LED Blink)
            • Experiment 02 - GPIO Input
            • Experiment 03 - Button-controlled LED
            • Experiment 04 - PWM Output
            • Experiment 05 - Serial Output
            • Experiment 06 - I2C Experiment
            • Experiment 07 - SPI Experiment
          • USB Module Usage

            • Experiment 01 - USB Voice Module Usage
            • Experiment 02 - Sound Source Localization Module
          • Machine Vision Practice

            • Experiment 01 - Open USB Camera
            • Experiment 02 - Image Processing Basics
            • Experiment 03 - Object Detection
            • Experiment 04 - Image Segmentation
      • RK1828

        • Introduction

          • M5-182X-A1 AI Edge Box - Product Introduction
          • M5-182X-A1 Hardware Specifications
          • M5-182X-A1 Usage & Safety
        • Quick Start

          • M5-182X-A1 Image Flashing
          • RK182X Hardware Installation & Verification
          • RK182X Development Environment Quick Setup
          • RK182X SDK Overview
          • RK182X Environment Setup in Detail
          • RK182X Quick Start
          • Vendor SDK Data Extraction Record
        • Development Guide

          • ClawChips Architecture and Principles
          • SKILL User Manual
          • RK182X Series LLM Inference (RK1828 Model)
          • RK182X Series CNN Inference (RK1828 Model)
          • Model Conversion
          • RK182X AI Agent Application Development Guide
          • RK182X Industrial Anomaly Detection Application
        • SDK Reference

          • RKNN3-SDK Overview

            • RKNN3 SDK Overview
          • RKNN3-Toolkit

            • RKNN3 Toolkit Installation and Usage
          • RKLLM

            • RKLLM On-Device LLM Inference
          • RK182X Series NPU Overview and Architecture (RK1828 Model)
          • RK182X INT8 Quantized Inference Deployment
          • RK182X MPP Multimedia Framework
          • MPP Details

            • RK182X Video Decoding
            • RK182X Video Encoding
          • NPU Details

            • RKNN Model Conversion
            • RK182X NPU INT8 Quantized Inference
            • RK182X Multi-Model Parallel Inference
          • RGA Details

            • RK182X RGA 2D Graphics Acceleration
          • VPU Details

            • RK182X VPU Codec
        • Hardware Reference

          • RK182X Series Hardware Architecture Overview (RK1828 Model)
          • RK182X Pin Definitions and Multiplexing Configuration
          • RK182X Pin Definitions
          • RK182X Power Management
          • RK182X Clock and PLL Configuration
          • RK182X Clock and Frequency Configuration
        • Tutorials

          • Hello World
          • Hello RK1828 - The First Program
          • RTSP Streaming
          • RTSP Streaming + AI Analysis
          • ShiMetaPi AI Lobster One-Click Deployment
          • PaddleOCR-VL Text Recognition
          • Qwen3-1.7B LLM Text Chat
          • AI Multi-View Inspection (Qwen3-VL Wrapper)
          • YOLOv5 Object Detection
        • Downloads

          • Downloads
        • FAQ

          • FAQ
    • Core-Board

      • C-3568BQ

        • Introduction

          • C-3568BQ Overview
      • C-3588LQ

        • Introduction

          • C-3588LQ Overview
      • GC-3568JBAF

        • Introduction

          • GC-3568JBAF Overview
      • C-K1BA

        • Introduction

          • C-K1BA Overview
    • Software Platform

      • ShiMetaPi Workbench

        • Introduction

          • Product Overview
          • Core Architecture
          • Feature Entries
          • Supported Hardware
          • Release Notes
        • Quick Start

          • Install & Login
          • Connect the Device
          • Set Up the Environment
          • Connect to AIHub
          • First Inference
        • User Guide

          • Workspace Overview
          • Device Manager
          • Model Market
          • One-Click Deploy
          • Vision — SVP
          • Vision - Custom Models
          • shimeta-py IDE
          • Terminal
          • Agent Debug Assistant
          • Settings and Resources
        • FAQ

          • Installation & Login
          • Device Connection
          • Models & Deployment
          • Vision & Runtime
          • Settings & Other
      • ShimetaPi Repository

        • Introduction

          • ShimetaPi Software Repository
        • Pico G1 (GK7206)

          • Quick Start

            • Installation & First Inference
            • shimeta_infer — Image Inference
            • shimeta_camera — Real-time Camera Inference
            • SVP Scene Detection
            • File Transfer & Built-in Model Reference
            • FAQ
          • HTTP API & Python SDK

            • HTTP API Reference
      • Model Fine-tuning Platform

        • Introduction

          • Model Training Platform
        • Quick Start

          • Register & Login
          • Create Your First Model (30-Minute Quick Experience)
        • Training Guide

          • Data Preparation & Annotation
          • Training Parameter Configuration
          • Start & Monitor Training
          • Model Evaluation & Testing
        • Model Deployment

          • Export Model
          • Deploy to Edge Device

UART Communication

1 UART Introduction

For the basic concepts of UART communication, please refer to: https://zhuanlan.zhihu.com/p/657771076 . The Rockchip UART (Universal Asynchronous Receiver/Transmitter) is based on the 16550A serial standard. The complete module supports the following features:

  • Supports 5, 6, 7, 8 bits data length.
  • Supports 1, 1.5, 2 bits stop bits.
  • Supports odd parity and even parity; does not support mark parity or space parity.
  • Supports receive FIFO and transmit FIFO, generally 32 bytes or 64 bytes.
  • Supports baud rates up to 4M; the actual supported baud rate depends on the chip clock division strategy.
  • Supports both interrupt transfer mode and DMA transfer mode.
  • Supports hardware automatic flow control, RTS+CTS.

2 UART Board Interface

UART Board Interface

3 UART Usage — Command-Line Method

3.1 Device Tree Analysis

Tips

The file path below: out/kernel/src_tmp/linux-5.10/arch/arm64/boot/dts/rockchip/ requires the kernel source to be compiled first.

Base definition layer (rk3568.dtsi):

uart3: serial@fe670000 {
    compatible = "rockchip,rk3568-uart", "snps,dw-apb-uart";
    reg = <0x0 0xfe670000 0x0 0x100>;
    interrupts = <GIC_SPI 119 IRQ_TYPE_LEVEL_HIGH>;
    clocks = <&cru SCLK_UART3>, <&cru PCLK_UART3>;
    clock-names = "baudclk", "apb_pclk";
    reg-shift = <2>;
    reg-io-width = <4>;
    dmas = <&dmac0 6>, <&dmac0 7>;
    pinctrl-names = "default";
    pinctrl-0 = <&uart3m0_xfer>;
    status = "disabled";
};

We analyze some of the basic properties:

  • compatible: specifies compatibility, supports RK3568 UART and standard DW APB UART
  • reg: register address range (0xfe670000-0xfe6700ff)
  • interrupts: interrupt number 119, triggered on high level
  • clocks: baud rate clock (SCLK_UART3) and APB clock (PCLK_UART3)
  • dmas: DMA channels 6 (TX) and 7 (RX)
  • pinctrl-0: defaults to the uart3m0_xfer pin group
  • status: disabled by default

Pin configuration layer (rk3568-pinctrl.dtsi), where UART3 provides two pin configuration modes:

uart3m0_xfer: uart3m0-xfer {
    rockchip,pins =
        /* uart3_rxm0 */
        <1 RK_PA0 2 &pcfg_pull_up>,
        /* uart3_txm0 */
        <1 RK_PA1 2 &pcfg_pull_up>;
};

uart3m1_xfer: uart3m1-xfer {
    rockchip,pins =
        /* uart3_rxm1 */
        <3 RK_PC0 4 &pcfg_pull_up>,
        /* uart3_txm1 */
        <3 RK_PB7 4 &pcfg_pull_up>;
};
  • uart3m0_xfer: pin group 1, uses PA0 as RX and PA1 as TX
  • uart3m1_xfer: pin group 2, uses PC0 as RX and PB7 as TX

Board-level configuration layer (rk3568-toybrick-x0.dtsi)

&uart3 {
    status = "okay";
    pinctrl-names = "default";
    pinctrl-0 = <&uart3m1_xfer>;
};
  • &uart3: references the uart3 node in the base definition
  • status = "okay": enables the UART3 controller
  • pinctrl-0: selects M1 mode pins (GPIO3_C0/GPIO3_B7)

3.2 Application-Layer Method for Testing UART

In the past, when doing MCU development and debugging, we often used the CH340 series USB-to-serial modules from WCH (Qinheng Electronics); there is also the common FT232RL USB-to-serial chip. This test uses a USB-to-serial module equipped with the FT232RL chip. There is no difference in usage between the two. In practice, you only need to cross-connect the module's TX and RX with the board's RX and TX.

USB-to-Serial Module

In this experiment, we still choose this method to perform UART communication with the board via USB.

As before, the driver file is placed under the /dev directory. With the command

ls /dev/tty*

you can view all terminal devices as follows: UART Device List

The tty prefix is for virtual terminals, and the ttyS prefix is for the serial terminals we will study in this section.

(ttyS3 is UART3, ttyS8 is UART8 (this serial port is occupied by the Bluetooth module))

BusyBox is a single executable file that integrates hundreds of common Linux commands. stty in it is short for "set tty", a command dedicated to changing and printing terminal line settings. Common commands are as follows:

View a port

busybox stty -F /dev/ttySx     //ttyS is the specific port to view

Set baud rate

busybox stty -F /dev/ttyS3 baudrate

Set baud rate to 9600, 8 data bits, 1 stop bit, no parity

busybox stty -F /dev/ttyS3 9600 cs8 -cstopb -parenb

Disable hardware flow control

busybox stty -F /dev/ttyS3 -crtscts

microcom is a component of BusyBox; its core function is to open a specified serial device and receive data.

Run the serial port at a baud rate of 115200

microcom -s 115200 /dev/ttyS3

3.2 Functional Demonstration

Use the stty tool to query the UART3 parameters of the development board.

busybox stty -F /dev/ttyS3
UART Parameter Query

Use the stty tool to change the serial port baud rate to 115200, where ispeed is the input speed and ospeed is the output speed.

busybox stty -F /dev/ttyS3 ispeed 115200 ospeed 115200
UART Baud Rate Setting

(Note: each time the device is powered on, you need to set the baud rate again. A reboot resets the baud rate to 9600 by default.)

Note

Serial port tool download URL and path: https://pan.baidu.com/s/1ZUn2BNg-Sb6M-fWhDqAFMw?pwd=smcc Extraction code: smcc ShimetaPi OpenHarmony materials > 02-Software Tools > Rockchip > OpenHarmony > Serial Port Tools > sscom5.13.1.exe

After configuring the serial debug assistant as described above, use the following command on the board side to test whether serial data transmission succeeds:

#Run the following command in the terminal on the board
#Use the echo command to write the strings "Hello!" and "OpenHarmony!" to the terminal device file
echo Hello! > /dev/ttyS3
echo "OpenHarmony" > /dev/ttyS3
#The serial debug assistant on the PC will receive the content
UART Send Test

As shown in the figure, the PC side successfully received the data, so the board is transmitting data normally. Next, send data from the PC side to test whether the board's serial port can receive data normally. Using the microcom tool mentioned above, run the following command in the terminal on the board to connect to the serial device ttyS3 and perform bidirectional communication. At this point, the microcom command will wait for serial data and display the received data in the terminal.

microcom -s 115200 /dev/ttyS3
UART Receive Test

The board terminal successfully displays the received data. The PC side sent data and the board received it successfully, so the board is receiving data normally.

4. UART Usage — NAPI Method

Material Path

HAP package: \05-开发资料\01-OpenHarmory 开发资料\外设测试APP\HAP\UART_TEST.hap

Project source: \05-开发资料\01-OpenHarmory 开发资料\外设测试APP\SRC\UART_TEST

Here we build the NAPI by reading and writing the system node /dev/ttyS3.

4-1 Test Environment Preparation

First, set the permissions on the /dev/ttyS3 node:

chmod 777 /dev/ttyS3             //path

4-2 Test Program Usage

The following is the serial port test program we wrote. Its basic functions are to open/close the serial port and to send/receive data. Considering layout difficulty and to keep the overall complexity low, we did not put a parameter configuration feature on the program UI; instead it is annotated with a line of text. The provided C source already implements this part of the functionality. Anyone who is capable may add it to the ets file by themselves!

We connect the development board to the computer via a USB-to-TTL module. Open the application as shown below, and we open the serial port.

UART App Open Serial Port

After opening the serial port, click Start Receive, and use the PC serial assistant to send the text "ShiMeta Pi ,Hello!". The application successfully receives the text and displays it in the data reception area.

Then send the string "open harmony!" from the application, and the serial terminal also receives the data successfully, as shown in the following figure:

UART Data Exchange 1UART Data Exchange 2

4-3 Test Program Code Introduction

Since the knowledge points involved have all been introduced earlier, here we paste the test program napi_init.cpp code for reference by those who need it. You can also view it in the materials yourself.

#include "napi/native_api.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "hilog/log.h"

const int GLOBAL_RESMGR = 0xFF00;
const char *UART_TAG = "[UART]";
const char *UART_DEVICE = "/dev/ttyS3";  // 固定使用ttyS3串口

// 全局变量
static int uart_fd = -1;        // 串口文件描述符
static struct termios old_cfg;  // 保存原始配置
static bool uart_opened = false;

// 配置串口参数
static int configure_uart(int fd, int baudrate, int databits, int stopbits, char parity)
{
    struct termios cfg;

    // 获取当前配置
    if (tcgetattr(fd, &cfg) != 0) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, UART_TAG,
                   "Failed to get uart config: %{public}s", strerror(errno));
        return -1;
    }

    // 保存原始配置
    old_cfg = cfg;

    // 清除所有标志
    cfg.c_cflag &= ~CSIZE;
    cfg.c_cflag &= ~CSTOPB;
    cfg.c_cflag &= ~PARENB;
    cfg.c_cflag &= ~PARODD;

    // 设置数据位
    switch (databits) {
        case 5: cfg.c_cflag |= CS5; break;
        case 6: cfg.c_cflag |= CS6; break;
        case 7: cfg.c_cflag |= CS7; break;
        case 8: cfg.c_cflag |= CS8; break;
        default: cfg.c_cflag |= CS8; break;
    }

    // 设置停止位
    if (stopbits == 2) {
        cfg.c_cflag |= CSTOPB;
    }

    // 设置校验位
    switch (parity) {
        case 'O': case 'o': // 奇校验
            cfg.c_cflag |= PARENB;
            cfg.c_cflag |= PARODD;
            break;
        case 'E': case 'e': // 偶校验
            cfg.c_cflag |= PARENB;
            cfg.c_cflag &= ~PARODD;
            break;
        case 'N': case 'n': // 无校验
        default:
            cfg.c_cflag &= ~PARENB;
            break;
    }

    // 设置波特率
    speed_t speed;
    switch (baudrate) {
        case 4800: speed = B4800; break;
        case 9600: speed = B9600; break;
        case 19200: speed = B19200; break;
        case 38400: speed = B38400; break;
        case 57600: speed = B57600; break;
        case 115200: speed = B115200; break;
        case 230400: speed = B230400; break;
        case 460800: speed = B460800; break;
        case 921600: speed = B921600; break;
        case 1500000: speed = B1500000; break;
        default: speed = B115200; break;
    }

    cfsetispeed(&cfg, speed);
    cfsetospeed(&cfg, speed);

    // 设置控制模式
    cfg.c_cflag |= CLOCAL | CREAD;

    // 设置输入模式
    cfg.c_iflag &= ~(IXON | IXOFF | IXANY);
    cfg.c_iflag &= ~(INLCR | ICRNL | IGNCR);

    // 设置输出模式
    cfg.c_oflag &= ~OPOST;

    // 设置本地模式
    cfg.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);

    // 设置读取参数
    cfg.c_cc[VTIME] = 0; // 非阻塞读取
    cfg.c_cc[VMIN] = 0;

    // 应用配置
    if (tcsetattr(fd, TCSANOW, &cfg) != 0) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, UART_TAG,
                   "Failed to set uart config: %{public}s", strerror(errno));
        return -1;
    }

    // 清空缓冲区
    tcflush(fd, TCIOFLUSH);

    return 0;
}

// 打开串口
static napi_value Open_UART(napi_env env, napi_callback_info info)
{
    napi_value result;

    // 检查串口是否已经打开
    if (uart_opened) {
        OH_LOG_Print(LOG_APP, LOG_WARN, GLOBAL_RESMGR, UART_TAG,
                   "UART is already opened");
        napi_create_string_utf8(env, "UART already opened", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    // 打开串口设备
    uart_fd = open(UART_DEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (uart_fd < 0) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, UART_TAG,
                   "Failed to open %{public}s: %{public}s", UART_DEVICE, strerror(errno));
        napi_create_string_utf8(env, "Failed to open UART device", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    // 配置串口参数 (115200, 8N1)
    if (configure_uart(uart_fd, 115200, 8, 1, 'N') != 0) {
        close(uart_fd);
        uart_fd = -1;
        napi_create_string_utf8(env, "Failed to configure UART", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    uart_opened = true;
    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, UART_TAG,
               "UART opened successfully");

    napi_create_string_utf8(env, "UART opened successfully", NAPI_AUTO_LENGTH, &result);
    return result;
}

// 关闭串口
static napi_value Close_UART(napi_env env, napi_callback_info info)
{
    napi_value result;

    if (!uart_opened || uart_fd < 0) {
        OH_LOG_Print(LOG_APP, LOG_WARN, GLOBAL_RESMGR, UART_TAG,
                   "UART is not opened");
        napi_create_string_utf8(env, "UART is not opened", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    // 恢复原始配置
    tcsetattr(uart_fd, TCSANOW, &old_cfg);

    // 关闭串口
    close(uart_fd);
    uart_fd = -1;
    uart_opened = false;

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, UART_TAG,
               "UART closed successfully");

    napi_create_string_utf8(env, "UART closed successfully", NAPI_AUTO_LENGTH, &result);
    return result;
}

// 设置串口配置
static napi_value Set_UART_Config(napi_env env, napi_callback_info info)
{
    napi_value result;
    size_t argc = 4;
    napi_value args[4];

    // 获取参数
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    if (argc < 4) {
        napi_create_string_utf8(env, "Invalid parameters", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    if (!uart_opened || uart_fd < 0) {
        napi_create_string_utf8(env, "UART is not opened", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    // 解析参数
    int32_t baudrate, databits, stopbits;
    char parity_char;
    size_t parity_len;
    char parity_str[10];

    napi_get_value_int32(env, args[0], &baudrate);
    napi_get_value_int32(env, args[1], &databits);
    napi_get_value_int32(env, args[2], &stopbits);
    napi_get_value_string_utf8(env, args[3], parity_str, sizeof(parity_str), &parity_len);

    parity_char = (parity_len > 0) ? parity_str[0] : 'N';

    // 重新配置串口
    if (configure_uart(uart_fd, baudrate, databits, stopbits, parity_char) != 0) {
        napi_create_string_utf8(env, "Failed to configure UART", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, UART_TAG,
               "UART configured: %{public}d-%{public}d-%{public}d-%{public}c",
               baudrate, databits, stopbits, parity_char);

    napi_create_string_utf8(env, "UART configured successfully", NAPI_AUTO_LENGTH, &result);
    return result;
}

// 发送数据
static napi_value Send_Data(napi_env env, napi_callback_info info)
{
    napi_value result;
    size_t argc = 1;
    napi_value args[1];

    // 获取参数
    napi_get_cb_info(env, info, &argc, args, nullptr, nullptr);

    if (argc < 1) {
        napi_create_string_utf8(env, "Invalid parameters", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    if (!uart_opened || uart_fd < 0) {
        napi_create_string_utf8(env, "UART is not opened", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    // 获取要发送的字符串
    size_t str_len;
    napi_get_value_string_utf8(env, args[0], nullptr, 0, &str_len);

    char *send_data = (char*)malloc(str_len + 1);
    if (!send_data) {
        napi_create_string_utf8(env, "Memory allocation failed", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    napi_get_value_string_utf8(env, args[0], send_data, str_len + 1, &str_len);

    // 发送数据
    ssize_t bytes_written = write(uart_fd, send_data, str_len);

    if (bytes_written < 0) {
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, UART_TAG,
                   "Failed to send data: %{public}s", strerror(errno));
        free(send_data);
        napi_create_string_utf8(env, "Failed to send data", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, UART_TAG,
               "Sent %{public}zd bytes: %{public}s", bytes_written, send_data);

    free(send_data);

    char response[100];
    snprintf(response, sizeof(response), "Sent %zd bytes successfully", bytes_written);
    napi_create_string_utf8(env, response, NAPI_AUTO_LENGTH, &result);
    return result;
}

// 接收数据
static napi_value Receive_Data(napi_env env, napi_callback_info info)
{
    napi_value result;

    if (!uart_opened || uart_fd < 0) {
        napi_create_string_utf8(env, "UART is not opened", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    char buffer[1024];
    ssize_t bytes_read = read(uart_fd, buffer, sizeof(buffer) - 1);

    if (bytes_read < 0) {
        if (errno == EAGAIN || errno == EWOULDBLOCK) {
            // 非阻塞模式下没有数据可读
            napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
            return result;
        }
        OH_LOG_Print(LOG_APP, LOG_ERROR, GLOBAL_RESMGR, UART_TAG,
                   "Failed to read data: %{public}s", strerror(errno));
        napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    if (bytes_read == 0) {
        napi_create_string_utf8(env, "", NAPI_AUTO_LENGTH, &result);
        return result;
    }

    buffer[bytes_read] = '\0';

    OH_LOG_Print(LOG_APP, LOG_INFO, GLOBAL_RESMGR, UART_TAG,
               "Received %{public}zd bytes: %{public}s", bytes_read, buffer);

    napi_create_string_utf8(env, buffer, NAPI_AUTO_LENGTH, &result);
    return result;
}

// 检查串口状态
static napi_value Get_UART_Status(napi_env env, napi_callback_info info)
{
    napi_value result;

    if (uart_opened && uart_fd >= 0) {
        napi_create_string_utf8(env, "opened", NAPI_AUTO_LENGTH, &result);
    } else {
        napi_create_string_utf8(env, "closed", NAPI_AUTO_LENGTH, &result);
    }

    return result;
}

// 模块初始化
EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        { "Open_UART", nullptr, Open_UART, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Close_UART", nullptr, Close_UART, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Set_UART_Config", nullptr, Set_UART_Config, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Send_Data", nullptr, Send_Data, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Receive_Data", nullptr, Receive_Data, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "Get_UART_Status", nullptr, Get_UART_Status, nullptr, nullptr, nullptr, napi_default, nullptr }
    };

    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    return exports;
}
EXTERN_C_END

static napi_module demoModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "entry",
    .nm_priv = ((void*)0),
    .reserved = { 0 },
};

extern "C" __attribute__((constructor)) void RegisterEntryModule(void)
{
    napi_module_register(&demoModule);
}
Edit this page on GitHub
Prev
PWM Control
Next
TF Card (MicroSD)