//uart.c
#include <getopt.h>
#include <string.h>
#include <rtthread.h>
#include <aic_core.h>
//#include "beep.h"
#define SAMPLE_UART_NAME "uart1"
#define TIMEOUT_NONE -4096
static struct rt_semaphore rx_sem;
static rt_device_t serial;
static char str_send[] = "12";
uint8_t g_recv_max = 128;
static int g_uart_test_result = 1;
static int g_exit = 0;
static int g_timeout = TIMEOUT_NONE;
static rt_timer_t uart1_rx_timeout = RT_NULL;
char str_receive[128 + 1] = {0};
typedef struct
{
uint8_t buf[128];
uint8_t len;
uint8_t rx_over;
} uart_rx_dat_t;
uart_rx_dat_t uart1_rx_dat = { 0 };
static void uart1_rx_timeout_cb(void *p)
{
rt_timer_stop(uart1_rx_timeout);
rt_kprintf("read_length: %d \n", uart1_rx_dat.len);
uart1_rx_dat.rx_over = RT_TRUE;
}
rt_err_t uart1_input(rt_device_t dev, rt_size_t size)
{
char ch;
//rt_sem_release(&rx_sem);
if(rt_device_read(serial, -1, &ch, 1)==1)
{
uart1_rx_dat.buf[uart1_rx_dat.len++] = ch;
rt_timer_start(uart1_rx_timeout);
}
return RT_EOK;
}
void serial_uart1_thread_entry(void *parameter)
{
uint8_t jx=0;
char ch;
int ret = 0;
int cnt = 0;
static int timeout_time = 0;
static uint8_t rx_one_byte_flag = 1;
while (1)
{
if(uart1_rx_dat.rx_over == RT_TRUE)
{
uart1_rx_dat.rx_over = RT_FALSE;
rt_kprintf("read_dat: ");
for(jx=0; jx<uart1_rx_dat.len; jx++)
{
rt_kprintf("%02x ", uart1_rx_dat.buf[jx]);
}
rt_kprintf("\n");
uart1_rx_dat.len=0;
if( uart1_rx_dat.buf[0]==0xff & uart1_rx_dat.buf[1]==0x2a)
{
if(uart1_rx_dat.buf[2]==0x01)
{
//beep_on();
rt_device_write(serial, 0, &uart1_rx_dat, 4);
}
else if(uart1_rx_dat.buf[2]==0x00)
{
//beep_off();
rt_device_write(serial, 0, &uart1_rx_dat, 4);
}
}
}
rt_thread_mdelay(5);
}
}
int test_uart_485(int argc, char *argv[])
{
int c = 0;
rt_err_t ret = RT_EOK;
static rt_uint8_t open_cnt = 0;
//查找串口设备
serial = rt_device_find(SAMPLE_UART_NAME);
if (!serial)
{
rt_kprintf("find %s failed!\n", SAMPLE_UART_NAME);
return -RT_ERROR;
}
//初始化信号量
rt_sem_init(&rx_sem, "rx_sem", 0, RT_IPC_FLAG_FIFO);
//打开串口设备
ret = rt_device_open(serial, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
if (ret != RT_EOK)
{
rt_kprintf("open %s failed : %d !\n", SAMPLE_UART_NAME, ret);
return -RT_ERROR;
}
//设置接收回调函数
rt_device_set_rx_indicate(serial, uart1_input);
//rt_device_write(serial, 0, str_send, (sizeof(str_send) - 1));
//创建 serial 线程
rt_thread_t thread = rt_thread_create("serial", serial_uart1_thread_entry, RT_NULL, 1024*2, 26, 10);
if (thread != RT_NULL) {
rt_thread_startup(thread);
} else {
rt_device_close(serial);
return -RT_ERROR;
}
//创建接收超时定时器
uart1_rx_timeout = rt_timer_create("serial_timer", uart1_rx_timeout_cb, RT_NULL, 50, RT_TIMER_FLAG_PERIODIC);
return ret;
}
MSH_CMD_EXPORT(test_uart_485, Uart Test);
非常感谢分享,受益匪浅,期待下次分享