usbd_cdc_vcom_echo.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**************************************************************************//**
  2. *
  3. * @copyright (C) 2019 Nuvoton Technology Corp. All rights reserved.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0
  6. *
  7. * Change Logs:
  8. * Date Author Notes
  9. * 2021-1-10 Wayne First version
  10. *
  11. ******************************************************************************/
  12. #include <rtthread.h>
  13. #if defined(RT_USB_DEVICE_CDC) && (defined(BSP_USING_USBD) || defined(BSP_USING_HSUSBD))
  14. static struct rt_semaphore rx_sem;
  15. static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
  16. {
  17. rt_err_t result = 0;
  18. result = rt_sem_release(&rx_sem);
  19. RT_ASSERT(result == RT_EOK);
  20. return RT_EOK;
  21. }
  22. static void serial_thread_entry(void *parameter)
  23. {
  24. rt_device_t serial = (rt_device_t)parameter;
  25. char ch;
  26. char szStr[64];
  27. while (1)
  28. {
  29. while (rt_device_read(serial, -1, &ch, 1) != 1)
  30. {
  31. if (rt_sem_take(&rx_sem, 3 * RT_TICK_PER_SECOND) == -RT_ETIMEOUT)
  32. {
  33. /* output current tick */
  34. rt_snprintf(szStr, sizeof(szStr), "%d\n", rt_tick_get());
  35. rt_device_write(serial, 0, &szStr[0], rt_strlen(szStr));
  36. continue;
  37. }
  38. }
  39. rt_device_write(serial, 0, &ch, 1);
  40. }
  41. }
  42. static int vcom_echo_init(void)
  43. {
  44. rt_err_t result = 0;
  45. rt_thread_t thread;
  46. rt_device_t serial;
  47. serial = rt_device_find("vcom");
  48. if (!serial)
  49. {
  50. rt_kprintf("find failed!\n");
  51. return RT_ERROR;
  52. }
  53. result = rt_device_init(serial);
  54. if (result)
  55. {
  56. rt_kprintf("init failed!\n");
  57. return -1;
  58. }
  59. result = rt_device_open(serial, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX/* | RT_DEVICE_FLAG_DMA_TX */);
  60. if (result)
  61. {
  62. rt_kprintf("open failed!\n");
  63. return -1;
  64. }
  65. result = rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
  66. RT_ASSERT(result == RT_EOK);
  67. result = rt_device_set_rx_indicate(serial, uart_input);
  68. RT_ASSERT(result == RT_EOK);
  69. thread = rt_thread_create("serial", serial_thread_entry, (void *)serial, 1024, 25, 10);
  70. if (thread != RT_NULL)
  71. {
  72. result = rt_thread_startup(thread);
  73. RT_ASSERT(result == RT_EOK);
  74. }
  75. return 0;
  76. }
  77. INIT_APP_EXPORT(vcom_echo_init);
  78. #endif