• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# USB Serial Configuration Management
2
3<!--Kit: Basic Services Kit-->
4<!--Subsystem: USB-->
5<!--Owner: @hwymlgitcode-->
6<!--Designer: @w00373942-->
7<!--Tester: @dong-dongzhen-->
8<!--Adviser: @w_Machine_cc-->
9
10## Overview
11
12In the USB serial configuration management, the baud rate, data bit, parity bit, and stop bit are the core parameters of the serial port communication protocol. They define the format and rules of data transmission. By properly setting these parameters, you can significantly improve the reliability and efficiency of serial port communication.
13
14### Basic Concepts
15
16Before developing the USB serial port, you should have a basic understanding of the following concepts:
17
18- Baud rate
19
20  The baud rate indicates the number of symbols transmitted by a serial port device per second. A symbol is a binary bit, including the data bit, start bit, stop bit, and parity bit. The unit is baud. For example, 9600 baud indicates that 9600 symbols are transmitted per second. The sender and receiver must use the same baud rate. Otherwise, data cannot be correctly parsed.
21
22
23- Data bit
24
25  The data bit indicates the number of valid binary bits actually transmitted in each data packet, which determines the data capacity of a single character. Commonly, a data bit may consist of five to eight digits. The data bit determines the amount of information transmitted at a time. The more the data bits, the larger the amount of information transmitted at a time, but more time is required for synchronization.
26
27
28- Parity bit
29
30  A parity bit is a 1-bit binary value appended to a data frame. It is generated based on the content of the data bit according to specific rules. Commonly, for an odd parity check, the total number of **1** in the data bits and parity bit is an odd number; for an even parity check, the total number of **1** is an even number; for no parity check, no parity bit is added to the data bit. By verifying the number of **1** in the data bit, the parity bit determines whether errors such as bit flipping and noise interference occur during data transfer. Increasing the parity bit slightly reduces the transfer efficiency but improves the error tolerance.
31
32
33- Stop bit
34
35  The stop bit is located at the end of a data frame. It is a logic high-level signal and is used to identify the end of a character (data packet) transfer. Its length can be 1 bit or 2 bits. (In actual development, 1 bit is most commonly used and 2 bits are mainly used in anti-interference scenarios.) A core function of this bit is to provide a space to tolerate the errors that may occur during time-sequence synchronization for a receiver and ensure data integrity.
36
37
38## Preparing the Environment
39
40For details, see [Preparing the Environment](usbSerial-overview.md#preparing-the-environment) in *USB Serial Communication Development Overview*.
41
42## How to Develop
43
44### Available APIs
45
46| API                                                                         | Description       |
47|------------------------------------------------------------------------------|-----------|
48| getAttribute(portId: number): Readonly&lt;SerialAttribute&gt;                      | Obtains the serial port device configuration.|
49| setAttribute(portId: number, attribute: SerialAttribute): void               | Sets the serial port device configuration.|
50
51### Development Procedure
52
53You can obtain and set the serial port configuration as follows:
54
55> **NOTE**
56>
57> The following sample code shows only a basic process. You should execute the code in a specific method.
58
591. Import the **usbManager** module.
60
61    ```ts
62    // Import the usbManager module.
63    import serial from '@ohos.usbManager.serial';
64    ```
65
662. Obtain the USB device list.
67
68    ```ts
69    // Obtain the list of USB devices connected to the host.
70    let portList: serial.SerialPort[] = serial.getPortList();
71    console.info(`usbSerial portList: ${portList}`);
72    if (portList === undefined || portList.length === 0) {
73      console.error('usbSerial portList is empty');
74      return;
75    }
76    ```
77
783. Obtain the device operation permissions.
79
80    ```ts
81    // Check whether the first USB device in the list has the access permission.
82    // Name the function based on the specific service.
83    async function serialDefault() {
84      let portId: number = portList[0].portId;
85      if (!serial.hasSerialRight(portId)) {
86        await serial.requestSerialRight(portId).then(result => {
87          if(!result) {
88            // If the device does not have the access permission and is not granted by the user, the device exits.
89            console.error('The user does not have permission to perform this operation');
90            return;
91          }
92        });
93      }
94    }
95    ```
96
974. Open the device based on the serial port.
98
99    ```ts
100    try {
101      serial.open(portId)
102      console.info(`open usbSerial success, portId: ${portId}`);
103    } catch (error) {
104      console.error(`open usbSerial error: ${error}`);
105    }
106    ```
107
1085. Obtain and modify serial port configurations.
109
110    ```ts
111    // Obtain the serial port configuration.
112    try {
113      let attribute: serial.SerialAttribute = serial.getAttribute(portId);
114      if (attribute === undefined) {
115        console.error('getAttribute usbSerial error, attribute is undefined');
116      } else {
117        console.info(`getAttribute usbSerial success, attribute: ${attribute}`);
118      }
119    } catch (error) {
120      console.error(`getAttribute usbSerial error: ${error}`);
121    }
122
123    // Set the serial port configuration.
124    try {
125      let attribute: serial.SerialAttribute = {
126        baudRate: serial.BaudRates.BAUDRATE_9600,
127        dataBits: serial.DataBits.DATABIT_8,
128        parity: serial.Parity.PARITY_NONE,
129        stopBits: serial.StopBits.STOPBIT_1
130      }
131      serial.setAttribute(portId, attribute);
132      console.info(`setAttribute usbSerial success, attribute: ${attribute}`);
133    } catch (error) {
134      console.error(`setAttribute usbSerial error: ${error}`);
135    }
136    ```
137
138### Debugging and Verification
139
1401. Prepare a USB-to-serial cable. Connect the USB port and the serial port of the cable to that of the OpenHarmony device.
1412. Execute the preceding sample code on the OpenHarmony device.
1423. Return **getAttribute usbSerial success** and **setAttribute usbSerial success** if related APIs are successfully called. You can view the current serial port configuration.
143