uart_sample.c 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-15 misonyo first implementation.
  9. */
  10. /*
  11. * 程序清单:这是一个 串口 设备使用例程
  12. * 例程导出了 uart_sample 命令到控制终端
  13. * 命令调用格式:uart_sample uart2
  14. * 命令解释:命令第二个参数是要使用的串口设备名称,为空则使用默认的串口设备
  15. * 程序功能:通过串口输出字符串"hello RT-Thread!",然后错位输出输入的字符
  16. */
  17. #include <rtthread.h>
  18. #define SAMPLE_UART_NAME "uart1" /* 串口设备名称 */
  19. /* 用于接收消息的信号量 */
  20. static struct rt_semaphore rx_sem;
  21. static rt_device_t serial;
  22. /* 接收数据回调函数 */
  23. static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
  24. {
  25. /* 串口接收到数据后产生中断,调用此回调函数,然后发送接收信号量 */
  26. rt_sem_release(&rx_sem);
  27. return RT_EOK;
  28. }
  29. static void serial_thread_entry(void *parameter)
  30. {
  31. char ch;
  32. while (1)
  33. {
  34. /* 从串口读取一个字节的数据,没有读取到则等待接收信号量 */
  35. while (rt_device_read(serial, -1, &ch, 1) != 1)
  36. {
  37. /* 阻塞等待接收信号量,等到信号量后再次读取数据 */
  38. rt_sem_take(&rx_sem, RT_WAITING_FOREVER);
  39. }
  40. /* 读取到的数据通过串口错位输出 */
  41. ch = ch + 1;
  42. rt_device_write(serial, 0, &ch, 1);
  43. }
  44. }
  45. static int uart_sample(int argc, char *argv[])
  46. {
  47. rt_err_t ret = RT_EOK;
  48. char uart_name[RT_NAME_MAX];
  49. char str[] = "hello RT-Thread!\r\n";
  50. if (argc == 2)
  51. {
  52. rt_strncpy(uart_name, argv[1], RT_NAME_MAX);
  53. }
  54. else
  55. {
  56. rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);
  57. }
  58. /* 查找串口设备 */
  59. serial = rt_device_find(uart_name);
  60. if (!serial)
  61. {
  62. rt_kprintf("find %s failed!\n", uart_name);
  63. return RT_ERROR;
  64. }
  65. /* 初始化信号量 */
  66. rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
  67. /* 以中断接收及轮询发送方式打开串口设备 */
  68. rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);
  69. /* 设置接收回调函数 */
  70. rt_device_set_rx_indicate(serial, uart_input);
  71. /* 发送字符串 */
  72. rt_device_write(serial, 0, str, (sizeof(str) - 1));
  73. /* 创建 serial 线程 */
  74. rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 1024, 25, 10);
  75. /* 创建成功则启动线程 */
  76. if (thread != RT_NULL)
  77. {
  78. rt_thread_startup(thread);
  79. }
  80. else
  81. {
  82. ret = RT_ERROR;
  83. }
  84. return ret;
  85. }
  86. /* 导出到 msh 命令列表中 */
  87. MSH_CMD_EXPORT(uart_sample, uart device sample);