drv_console.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2023-11-30 Meco Man First version
  9. */
  10. #include <board.h>
  11. #include <rtthread.h>
  12. #include <drv_common.h>
  13. static UART_HandleTypeDef console_uart;
  14. void rt_hw_console_init(void)
  15. {
  16. HAL_UART_DeInit(&console_uart);
  17. #ifdef USART1
  18. if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart1") == 0)
  19. {
  20. console_uart.Instance = USART1;
  21. }
  22. #endif /* USART1 */
  23. #ifdef USART2
  24. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart2") == 0)
  25. {
  26. console_uart.Instance = USART2;
  27. }
  28. #endif /* USART2 */
  29. #ifdef USART3
  30. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart3") == 0)
  31. {
  32. console_uart.Instance = USART3;
  33. }
  34. #endif /* USART3 */
  35. #ifdef USART4
  36. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart4") == 0)
  37. {
  38. console_uart.Instance = USART4;
  39. }
  40. #endif /* USART4 */
  41. #ifdef USART5
  42. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart5") == 0)
  43. {
  44. console_uart.Instance = USART5;
  45. }
  46. #endif /* USART5 */
  47. #ifdef USART6
  48. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart6") == 0)
  49. {
  50. console_uart.Instance = USART6;
  51. }
  52. #endif /* USART6 */
  53. #ifdef USART7
  54. else if (rt_strcmp(RT_CONSOLE_DEVICE_NAME, "uart7") == 0)
  55. {
  56. console_uart.Instance = USART7;
  57. }
  58. #endif /* USART7 */
  59. else
  60. {
  61. RT_ASSERT(0);
  62. }
  63. console_uart.Init.BaudRate = 115200;
  64. console_uart.Init.WordLength = UART_WORDLENGTH_8B;
  65. console_uart.Init.StopBits = UART_STOPBITS_1;
  66. console_uart.Init.Parity = UART_PARITY_NONE;
  67. console_uart.Init.Mode = UART_MODE_TX_RX;
  68. console_uart.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  69. if (HAL_UART_Init(&console_uart) != HAL_OK)
  70. {
  71. Error_Handler();
  72. }
  73. }
  74. void rt_hw_console_output(const char *str)
  75. {
  76. rt_size_t i = 0, size = 0;
  77. char a = '\r';
  78. __HAL_UNLOCK(&console_uart);
  79. size = rt_strlen(str);
  80. for (i = 0; i < size; i++)
  81. {
  82. if (*(str + i) == '\n')
  83. {
  84. HAL_UART_Transmit(&console_uart, (uint8_t *)&a, 1, 1);
  85. }
  86. HAL_UART_Transmit(&console_uart, (uint8_t *)(str + i), 1, 1);
  87. }
  88. }
  89. char rt_hw_console_getchar(void)
  90. {
  91. int ch = -1;
  92. if (HAL_UART_Receive(&console_uart, (uint8_t *)&ch, 1, 0) != HAL_OK)
  93. {
  94. ch = -1;
  95. rt_thread_mdelay(10);
  96. }
  97. return ch;
  98. }