2121
2222/* 用于接收消息的信号量 */
2323static struct rt_semaphore rx_sem ;
24- static char uart_name [RT_NAME_MAX ];
24+ static rt_device_t serial ;
25+
2526/* 接收数据回调函数 */
2627static rt_err_t uart_input (rt_device_t dev , rt_size_t size )
2728{
@@ -34,43 +35,27 @@ static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
3435static void serial_thread_entry (void * parameter )
3536{
3637 char ch ;
37- rt_device_t serial ;
38- char str [] = "hello RT-Thread!\r\n" ;
39-
40- /* 查找系统中的串口设备 */
41- serial = rt_device_find (uart_name );
4238
43- if ( serial != RT_NULL )
39+ while ( 1 )
4440 {
45- rt_sem_init (& rx_sem , "rx_sem" , 0 , RT_IPC_FLAG_FIFO );
46- /* 以读写及中断接收方式打开串口设备 */
47- rt_device_open (serial , RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX );
48- /* 设置接收回调函数 */
49- rt_device_set_rx_indicate (serial , uart_input );
50- /* 发送字符串 */
51- rt_device_write (serial , 0 , str , (sizeof (str ) - 1 ));
52-
53- while (1 )
41+ /* 从串口读取一个字节的数据,没有读取到则等待接收信号量 */
42+ while (rt_device_read (serial , -1 , & ch , 1 ) != 1 )
5443 {
55- /* 从串口读取一个字节的数据,没有读取到则等待接收信号量 */
56- while (rt_device_read (serial , -1 , & ch , 1 ) != 1 )
57- {
58- /* 阻塞等待接收信号量,等到信号量后再次读取数据 */
59- rt_sem_take (& rx_sem , RT_WAITING_FOREVER );
60- }
61- /* 读取到的数据通过串口错位输出 */
62- ch = ch + 1 ;
63- rt_device_write (serial , 0 , & ch , 1 );
44+ /* 阻塞等待接收信号量,等到信号量后再次读取数据 */
45+ rt_sem_take (& rx_sem , RT_WAITING_FOREVER );
6446 }
65- }
66- else
67- {
68- rt_kprintf ("uart sample run failed! can't find %s device!\n" , uart_name );
47+ /* 读取到的数据通过串口错位输出 */
48+ ch = ch + 1 ;
49+ rt_device_write (serial , 0 , & ch , 1 );
6950 }
7051}
7152
72- static void uart_sample (int argc , char * argv [])
53+ static int uart_sample (int argc , char * argv [])
7354{
55+ rt_err_t res = RT_EOK ;
56+ char uart_name [RT_NAME_MAX ];
57+ char str [] = "hello RT-Thread!\r\n" ;
58+
7459 if (argc == 2 )
7560 {
7661 rt_strncpy (uart_name , argv [1 ], RT_NAME_MAX );
@@ -80,13 +65,36 @@ static void uart_sample(int argc, char *argv[])
8065 rt_strncpy (uart_name , SAMPLE_UART_NAME , RT_NAME_MAX );
8166 }
8267
68+ /* 查找系统中的串口设备 */
69+ serial = rt_device_find (uart_name );
70+ if (!serial )
71+ {
72+ rt_kprintf ("find %s failed!\n" , uart_name );
73+ return RT_ERROR ;
74+ }
75+
76+ /* 初始化信号量 */
77+ rt_sem_init (& rx_sem , "rx_sem" , 0 , RT_IPC_FLAG_FIFO );
78+ /* 以读写及中断接收方式打开串口设备 */
79+ rt_device_open (serial , RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX );
80+ /* 设置接收回调函数 */
81+ rt_device_set_rx_indicate (serial , uart_input );
82+ /* 发送字符串 */
83+ rt_device_write (serial , 0 , str , (sizeof (str ) - 1 ));
84+
8385 /* 创建 serial 线程 */
8486 rt_thread_t thread = rt_thread_create ("serial" , serial_thread_entry , RT_NULL , 1024 , 25 , 10 );
8587 /* 创建成功则启动线程 */
8688 if (thread != RT_NULL )
8789 {
8890 rt_thread_startup (thread );
8991 }
92+ else
93+ {
94+ res = RT_ERROR ;
95+ }
96+
97+ return res ;
9098}
9199/* 导出到 msh 命令列表中 */
92100MSH_CMD_EXPORT (uart_sample , uart device sample );
0 commit comments