|
本帖最后由 雷鹏 于 2018-7-12 22:14 编辑
/*
* 程序清单:串口设备操作例程
*
* 在这个例程中,将启动一个devt线程,然后打开串口1和2
* 当串口1和2有输入时,将读取其中的输入数据然后写入到
* 串口1设备中。
*
*/
#include <rtthread.h>
/* UART接收消息结构*/
struct rx_msg
{
rt_device_t dev;
rt_size_t size;
};
/* 消息队列控制块 */
static struct rt_messagequeue mq;
/* 消息队列中用到的放置消息的内存池 */
/* 数据到达回调函数*/
rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
struct rx_msg msg;
int result;
char buf[] = "this is message No.x";
msg.dev = dev;
msg.size = size;
/* 发送消息到消息队列中*/
rt_kprintf("Receive From :%s\r\n",dev->parent.name);
/* 发送消息到消息队列中 */
result = rt_mq_send(&mq, &msg, sizeof(msg));
if ( result == -RT_EFULL)
{
/* 消息队列满, 延迟1s时间 */
rt_kprintf("message queue full, delay 1s\n");
rt_thread_delay(1000);
}
return result;
}
void device_thread_entry(void* parameter)
{
struct rx_msg msg;
int count = 0;
rt_device_t device, write_device;
rt_err_t result = RT_EOK;
static char uart_rx_buffer[64];
/* 查找系统中的串口1设备 */
device = rt_device_find("uart1");
if (device!= RT_NULL)
{
/* 设置回调函数及打开设备*/
rt_device_set_rx_indicate(device, uart_input);
rt_device_open(device, RT_DEVICE_OFLAG_RDWR|RT_DEVICE_FLAG_INT_RX);
}
/* 设置写设备为uart1设备 */
write_device = device;
/* 查找系统中的串口2设备 */
device= rt_device_find("uart2");
if (device!= RT_NULL)
{
/* 设置回调函数及打开设备*/
rt_device_set_rx_indicate(device, uart_input);
rt_device_open(device, RT_DEVICE_OFLAG_RDWR|RT_DEVICE_FLAG_INT_RX);
}
while (1)
{
/* 从消息队列中读取消息*/
rt_memset(&msg, 0, sizeof(msg));
result = rt_mq_recv(&mq, &msg, sizeof(msg), 50);
if (result == -RT_ETIMEOUT)
{
/* 接收超时*/
rt_kprintf("timeout count:%d\n", ++count);
}
/* 从消息队列中接收消息 */
if (result == RT_EOK)
{
rt_uint32_t rx_length;
rx_length = (sizeof(uart_rx_buffer) - 1) > msg.size ?
msg.size : sizeof(uart_rx_buffer) - 1;
/* 读取消息*/
rx_length = rt_device_read(msg.dev, 0, &uart_rx_buffer[0],
rx_length);
uart_rx_buffer[rx_length] = '\0';
rt_kprintf("Receive data:");
/* 写到写设备中*/
if (write_device != RT_NULL)
rt_device_write(write_device, 0, &uart_rx_buffer[0],
rx_length);
rt_kprintf("\r\n");
}
}
}
int rt_application_init()
{
static char msg_pool[2048];
/* 初始化消息队列 */
rt_mq_init(&mq, "mqt",
&msg_pool[0], /* 内存池指向msg pool */
128 - sizeof(void*), /* 每个消息的大小是 128 - void* */
sizeof(msg_pool), /* 内存池的大小是msg pool的大小 */
RT_IPC_FLAG_FIFO); /* 如果有多个线程等待,按照先来先得到的方法分配消息 */
/* 创建devt线程*/
rt_thread_t thread = rt_thread_create("devt",
device_thread_entry, RT_NULL,
2048, 25, 7);
/* 创建成功则启动线程*/
if (thread!= RT_NULL)
rt_thread_startup(thread);
return 0;
}
|
|