usbd_cdc_vcom_echo.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <rtthread.h>
  2. #if defined(RT_USB_DEVICE_CDC) && (defined(BSP_USING_USBD) || defined(BSP_USING_HSUSBD))
  3. static struct rt_semaphore rx_sem;
  4. static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
  5. {
  6. rt_sem_release(&rx_sem);
  7. return RT_EOK;
  8. }
  9. static void serial_thread_entry(void *parameter)
  10. {
  11. rt_device_t serial = (rt_device_t)parameter;
  12. char ch;
  13. char szStr[64];
  14. while (1)
  15. {
  16. while (rt_device_read(serial, -1, &ch, 1) != 1)
  17. {
  18. if (rt_sem_take(&rx_sem, 3 * RT_TICK_PER_SECOND) == -RT_ETIMEOUT)
  19. {
  20. time_t now;
  21. /* output current time */
  22. now = time(RT_NULL);
  23. rt_snprintf(szStr, sizeof(szStr), "%.*s\n", 25, ctime(&now));
  24. rt_device_write(serial, 0, &szStr[0], rt_strlen(szStr));
  25. continue;
  26. }
  27. }
  28. rt_device_write(serial, 0, &ch, 1);
  29. }
  30. }
  31. static int vcom_echo_init(void)
  32. {
  33. int err = 0;
  34. rt_thread_t thread;
  35. rt_device_t serial;
  36. serial = rt_device_find("vcom");
  37. if (!serial)
  38. {
  39. rt_kprintf("find failed!\n");
  40. return RT_ERROR;
  41. }
  42. err = rt_device_init(serial);
  43. if (err)
  44. {
  45. rt_kprintf("find failed!\n");
  46. return -RT_ERROR;
  47. }
  48. err = rt_device_open(serial, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX/* | RT_DEVICE_FLAG_DMA_TX */);
  49. rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
  50. rt_device_set_rx_indicate(serial, uart_input);
  51. thread = rt_thread_create("serial", serial_thread_entry, (void *)serial, 1024, 25, 10);
  52. if (thread != RT_NULL)
  53. {
  54. rt_thread_startup(thread);
  55. }
  56. return RT_EOK;
  57. }
  58. INIT_APP_EXPORT(vcom_echo_init);
  59. #endif