rtthread 双串口程序
时间: 2023-06-25 21:02:16 浏览: 96
RT-Thread开发的网络串口转换模块
5星 · 资源好评率100%
下面是一个基于 RT-Thread 操作系统的双串口程序示例:
```c
#include <rtthread.h>
#include <rtdevice.h>
/* 定义串口设备对象指针 */
static struct rt_device *uart1;
static struct rt_device *uart2;
/* 定义接收缓冲区 */
#define RECV_BUFSZ 64
static char recv_buf1[RECV_BUFSZ];
static char recv_buf2[RECV_BUFSZ];
/* 定义接收缓冲区读写指针 */
static rt_uint32_t recv_buf1_readptr = 0;
static rt_uint32_t recv_buf1_writeptr = 0;
static rt_uint32_t recv_buf2_readptr = 0;
static rt_uint32_t recv_buf2_writeptr = 0;
/* 定义互斥锁 */
static struct rt_mutex mutex;
/* 定义线程栈和控制块 */
#define THREAD_STACK_SIZE 512
static char thread1_stack[THREAD_STACK_SIZE];
static char thread2_stack[THREAD_STACK_SIZE];
static struct rt_thread thread1;
static struct rt_thread thread2;
/* 定义线程1函数 */
static void thread1_entry(void *parameter)
{
while (1)
{
/* 获取串口1接收到的数据 */
rt_device_read(uart1, 0, &recv_buf1[recv_buf1_writeptr], 1);
recv_buf1_writeptr = (recv_buf1_writeptr + 1) % RECV_BUFSZ;
/* 释放互斥锁 */
rt_mutex_release(&mutex);
}
}
/* 定义线程2函数 */
static void thread2_entry(void *parameter)
{
while (1)
{
/* 获取串口2接收到的数据 */
rt_device_read(uart2, 0, &recv_buf2[recv_buf2_writeptr], 1);
recv_buf2_writeptr = (recv_buf2_writeptr + 1) % RECV_BUFSZ;
/* 释放互斥锁 */
rt_mutex_release(&mutex);
}
}
int uart_recv(rt_uint8_t *buf, rt_uint32_t len)
{
rt_uint32_t i;
/* 等待互斥锁 */
rt_mutex_take(&mutex, RT_WAITING_FOREVER);
/* 复制串口1缓冲区数据 */
for (i = 0; i < len; i++)
{
if (recv_buf1_readptr != recv_buf1_writeptr)
{
buf[i] = recv_buf1[recv_buf1_readptr];
recv_buf1_readptr = (recv_buf1_readptr + 1) % RECV_BUFSZ;
}
else
{
break;
}
}
/* 复制串口2缓冲区数据 */
for (; i < len; i++)
{
if (recv_buf2_readptr != recv_buf2_writeptr)
{
buf[i] = recv_buf2[recv_buf2_readptr];
recv_buf2_readptr = (recv_buf2_readptr + 1) % RECV_BUFSZ;
}
else
{
break;
}
}
/* 返回实际读取的字节数 */
return i;
}
int main(void)
{
/* 初始化互斥锁 */
rt_mutex_init(&mutex, "mutex", RT_IPC_FLAG_FIFO);
/* 查找并打开串口设备 */
uart1 = rt_device_find("uart1");
uart2 = rt_device_find("uart2");
rt_device_open(uart1, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
rt_device_open(uart2, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
/* 创建线程1和线程2 */
rt_thread_init(&thread1, "thread1", thread1_entry, RT_NULL, thread1_stack, sizeof(thread1_stack), 10, 5);
rt_thread_init(&thread2, "thread2", thread2_entry, RT_NULL, thread2_stack, sizeof(thread2_stack), 10, 5);
/* 启动线程1和线程2 */
rt_thread_startup(&thread1);
rt_thread_startup(&thread2);
/* 运行 RT-Thread 线程调度器 */
rt_thread_mdelay(RT_TICK_PER_SECOND);
return 0;
}
```
该程序包含两个线程,分别用于读取串口1和串口2接收到的数据,并将数据存储到接收缓冲区中。同时,该程序实现了一个名为 `uart_recv` 的函数,该函数可用于读取接收缓冲区中的数据。在读取接收缓冲区数据时,该函数会先读取串口1接收缓冲区中的数据,然后再读取串口2接收缓冲区中的数据,直到读取指定长度的数据或者两个接收缓冲区中的数据都被读取完为止。注意,在读取接收缓冲区数据前,该函数会等待互斥锁,以确保多个线程不会同时读取接收缓冲区导致数据错误。
阅读全文