uart_example.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * Copyright (c) 2020  Jinan Bosai Network Technology Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include "cmsis_os2.h"
  19. #include "iot_errno.h"
  20. #include "iot_uart.h"
  21. #include "ohos_init.h"
  22. #define UART_TASK_STACK_SIZE 1024 * 8
  23. #define UART_TASK_PRIO 25
  24. #define UART_BUFF_SIZE 1000
  25. #define WIFI_IOT_UART_IDX_1 1
  26. static const char* data = "Hello, BearPi!\r\n";
  27. /**
  28. * @brief uart task send data through uart1 and receive data through uart1
  29. *
  30. */
  31. static void UartTask(void)
  32. {
  33. uint8_t uart_buff[UART_BUFF_SIZE] = {0};
  34. uint8_t* uart_buff_ptr = uart_buff;
  35. uint32_t ret;
  36. IotUartAttribute uart_attr = {
  37. // baud_rate: 9600
  38. .baudRate = 9600,
  39. // data_bits: 8bits
  40. .dataBits = 8,
  41. .stopBits = 1,
  42. .parity = 0,
  43. };
  44. // Initialize uart driver
  45. ret = IoTUartInit(WIFI_IOT_UART_IDX_1, &uart_attr);
  46. if (ret != IOT_SUCCESS) {
  47. printf("Failed to init uart! Err code = %d\n", ret);
  48. return;
  49. }
  50. while (1) {
  51. printf("=======================================\r\n");
  52. printf("*************UART_example**************\r\n");
  53. printf("=======================================\r\n");
  54. // send data through uart1
  55. IoTUartWrite(WIFI_IOT_UART_IDX_1, (unsigned char*)data, strlen(data));
  56. // receive data through uart1
  57. IoTUartRead(WIFI_IOT_UART_IDX_1, uart_buff_ptr, UART_BUFF_SIZE);
  58. printf("Uart1 read data:%s\n", uart_buff_ptr);
  59. usleep(1000000);
  60. }
  61. }
  62. /**
  63. * @brief Main Entry of the UART Example
  64. *
  65. */
  66. static void UartExampleEntry(void)
  67. {
  68. osThreadAttr_t attr;
  69. attr.name = "UartTask";
  70. attr.attr_bits = 0U;
  71. attr.cb_mem = NULL;
  72. attr.cb_size = 0U;
  73. attr.stack_mem = NULL;
  74. attr.stack_size = UART_TASK_STACK_SIZE;
  75. attr.priority = UART_TASK_PRIO;
  76. if (osThreadNew((osThreadFunc_t)UartTask, NULL, &attr) == NULL) {
  77. printf("Failed to create UartTask!\n");
  78. }
  79. }
  80. APP_FEATURE_INIT(UartExampleEntry);