|
#include <rtthread.h>
#include "hal_data.h"
#include <rtdevice.h>
#define CTS_PIN BSP_IO_PORT_05_PIN_03 /* 485 Follow control pins */
#define SAMPLE_UART_NAME "uart5"
static rt_device_t serial;
struct rx_msg
{
rt_device_t dev;
rt_size_t size;
};
struct rt_ringbuffer rb;
rt_uint8_t pool[1024];
static rt_uint8_t buffer[BSP_UART4_RX_BUFSIZE + 1];
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{
rt_uint32_t rx_length;
rx_length = rt_device_read(dev, 0, buffer, size);
if(rx_length)
{
rt_ringbuffer_put(&rb, buffer, rx_length);
}
return RT_EOK;
}
static void serial_thread_entry(void *parameter)
{
rt_uint32_t rx_length;
static rt_uint8_t rx_buffer[1024];
while (1)
{
rx_length = rt_ringbuffer_data_len(&rb);
if(rx_length)
{
rx_length = rt_ringbuffer_get(&rb, rx_buffer, rx_length);
rt_kprintf("%s\n",rx_buffer);
rt_memset(rx_buffer, 0x00, rx_length);
}
rt_thread_mdelay(1);
}
}
static int uart_loop_sample(int argc, char *argv[])
{
rt_err_t ret = RT_EOK;
char uart_name[RT_NAME_MAX];
char str[] = "hello RT-Thread!\r\n";
if (argc == 2)
{
rt_strncpy(uart_name, argv[1], RT_NAME_MAX);
}
else
{
rt_strncpy(uart_name, SAMPLE_UART_NAME, RT_NAME_MAX);
}
serial = rt_device_find(uart_name);
if (!serial)
{
rt_kprintf("find %s failed!\n", uart_name);
return RT_ERROR;
}
rt_ringbuffer_init(&rb, pool, 1024);
rt_device_set_rx_indicate(serial, uart_input);
rt_device_open(serial, RT_DEVICE_FLAG_RX_NON_BLOCKING | RT_DEVICE_FLAG_TX_BLOCKING);
rt_pin_write(CTS_PIN, PIN_HIGH);
rt_device_write(serial, 0, str, (sizeof(str) - 1));
rt_pin_write(CTS_PIN, PIN_LOW);
rt_thread_t thread = rt_thread_create("serial", serial_thread_entry, RT_NULL, 2048, 25, 10);
if (thread != RT_NULL)
{
rt_thread_startup(thread);
}
else
{
ret = RT_ERROR;
}
return ret;
}
MSH_CMD_EXPORT(uart_loop_sample, uart device loop sample);