#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
/* 串口设备句柄 */
rt_device_t uart5_dev;
rt_timer_t timer;
static struct rt_semaphore rx_sem5;
static struct rt_semaphore end_sem;
static char rx_buf[100];
static int num = 0;
/* 消息队列控制块 */
volatile rt_size_t rx_size;
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
rt_timer_stop(timer);
rt_sem_release(&rx_sem5);
return RT_EOK;
}
static void uart5_rx_thread(void *parameter)
{
rt_size_t size = 0;
char ch = 0;
while (1)
{
rt_sem_take(&rx_sem5, RT_WAITING_FOREVER);
size = rt_device_read(uart5_dev, 0, &ch, 1);
if(size == 0)
{
rt_kprintf("read uart5 fail\n");
continue;
}
rx_buf[num++] = ch;
rt_timer_start(timer);
rt_kprintf("%d\n", (uint16_t )ch);
}
rt_device_close(uart5_dev);
}
static void uart5_tx_thread(void *parameter)
{
rt_size_t size = 0;
while(1)
{
rt_sem_take(&end_sem, RT_WAITING_FOREVER);
size = rt_device_write(uart5_dev, 0, rx_buf, num);
if(size == 0)
{
rt_kprintf("write uart5 fail\n");
continue;
}
rt_memset(rx_buf, 0, sizeof(rx_buf));
num = 0;
}
return ;
}
static void timeout(void *parameter)
{
rt_sem_release(&end_sem);
rt_timer_stop(timer);
}
int main(void)
{
rt_err_t ret;
char str[] = "hello RT-Thread!";
uart5_dev= rt_device_find("uart5");
if(uart5_dev == RT_NULL)
{
rt_kprintf("find uart5 fail\n");
return RT_ERROR;
}
ret = rt_device_open(uart5_dev, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM);
if(ret != RT_EOK)
{
rt_kprintf("open uart5 fail\n");
return RT_ERROR;
}
rt_sem_init(&end_sem, "end_sem", 0, RT_IPC_FLAG_FIFO);
rt_sem_init(&rx_sem5, "rx_sem5", 0, RT_IPC_FLAG_FIFO);
/* 设置接收回调函数 */
rt_device_set_rx_indicate(uart5_dev, uart_input);
/* 发送字符串 */
rt_size_t size = rt_device_write(uart5_dev, 0, str, (sizeof(str) - 1));
if(size == 0)
{
rt_kprintf("write uart fail\n");
return RT_ERROR;
}
/* 创建 serial 线程 */
rt_thread_t rx_thread = rt_thread_create("serial", uart5_rx_thread, RT_NULL, 1024, 25, 10);
if (rx_thread == RT_NULL)
{
rt_kprintf("thread create fail\n");
return RT_ERROR;
}
rt_thread_startup(rx_thread);
rt_thread_t tx_thread = rt_thread_create("serial", uart5_tx_thread, RT_NULL, 1024, 25, 10);
if (tx_thread == RT_NULL)
{
rt_kprintf("thread create fail\n");
return RT_ERROR;
}
rt_thread_startup(tx_thread);
/* 创建 周期定时器 */
timer = rt_timer_create("timer", timeout,
RT_NULL, 200,
RT_TIMER_FLAG_PERIODIC);
if(timer == RT_NULL)
{
rt_kprintf("timer create fail\n");
return RT_ERROR;
}
return RT_EOK;
}
注意:数据接收最好使用中断+DMA方式,不然在接收大量数据时,容易出现数据丢失问题!!!