UART使用实例

UART设备完整的使用示例如下所示,首先获取UART设备句柄,接着设置波特率、设备属性和传输模式,之后进行UART通信,最后销毁UART设备句柄。


1. #include "hdf_log.h"
2. #include "uart_if.h"

4. void UartTestSample(void)
5. {
6. int32_t ret;
7. uint32_t port;
8. struct DevHandle *handle = NULL;
9. uint8_t wbuff[5] = { 1, 2, 3, 4, 5 };
10. uint8_t rbuff[5] = { 0 };
11. struct UartAttribute attribute;
12. attribute.dataBits = UART_ATTR_DATABIT_7;   /* UART传输数据位宽,一次传输7个bit */
13. attribute.parity = UART_ATTR_PARITY_NONE;   /* UART传输数据无校检 */
14. attribute.stopBits = UART_ATTR_STOPBIT_1;   /* UART传输数据停止位为1位 */
15. attribute.rts = UART_ATTR_RTS_DIS;          /* UART禁用RTS */
16. attribute.cts = UART_ATTR_CTS_DIS;          /* UART禁用CTS */
17. attribute.fifoRxEn = UART_ATTR_RX_FIFO_EN;  /* UART使能RX FIFO */
18. attribute.fifoTxEn = UART_ATTR_TX_FIFO_EN;  /* UART使能TX FIFO */
19. /* UART设备端口号,要填写实际平台上的端口号 */
20. port = 1;
21. /* 获取UART设备句柄 */
22. handle = UartOpen(port);
23. if (handle == NULL) {
24. HDF_LOGE("UartOpen: failed!\n");
25. return;
26. }
27. /* 设置UART波特率为9600 */
28. ret = UartSetBaud(handle, 9600);
29. if (ret != 0) {
30. HDF_LOGE("UartSetBaud: failed, ret %d\n", ret);
31. goto _ERR;
32. }
33. /* 设置UART设备属性 */
34. ret = UartSetAttribute(handle, &attribute);
35. if (ret != 0) {
36. HDF_LOGE("UartSetAttribute: failed, ret %d\n", ret);
37. goto _ERR;
38. }
39. /* 设置UART传输模式为非阻塞模式 */
40. ret = UartSetTransMode(handle, UART_MODE_RD_NONBLOCK);
41. if (ret != 0) {
42. HDF_LOGE("UartSetTransMode: failed, ret %d\n", ret);
43. goto _ERR;
44. }
45. /* 向UART设备写入5字节的数据 */
46. ret = UartWrite(handle, wbuff, 5);
47. if (ret != 0) {
48. HDF_LOGE("UartWrite: failed, ret %d\n", ret);
49. goto _ERR;
50. }
51. /* 从UART设备读取5字节的数据 */
52. ret = UartRead(handle, rbuff, 5);
53. if (ret < 0) {
54. HDF_LOGE("UartRead: failed, ret %d\n", ret);
55. goto _ERR;
56. }
57. _ERR:
58. /* 销毁UART设备句柄 */
59. UartClose(handle);
60. }