RT-Thread 文档中心
【1】常用函数:
rt_device_find() | 查找设备 |
rt_device_open() | 打开设备 |
rt_device_read() | 读取数据 |
rt_device_write() | 写入数据 |
rt_device_control() | 控制设备 |
rt_device_set_rx_indicate() | 设置接收回调函数 |
rt_device_set_tx_complete() | 设置发送完成回调函数 |
rt_device_close() | 关闭设备 |
【2】常用模式: 中断接收以及轮询发送:
#include "app_uart1.h"
#include <rtthread.h>
#include "rtdevice.h"#define PLC_UART_NAME "uart1"
static rt_device_t serial;串口数据报文的解析
static void app_uart1_API_Receive_Analay(char ch)
{
//解析函数
}
/* 接收数据回调函数 */
static rt_err_t uart_input(rt_device_t dev, rt_size_t size)
{char ch=0;rt_device_read(serial, -1, &ch, 1);app_uart1_API_Receive_Analay(ch);rt_device_write(serial, 0, &ch, 1);return RT_EOK;
}int app_uart1_API_init(void)
{struct serial_configure config = RT_SERIAL_CONFIG_DEFAULT; /* 初始化配置参数 *//* 查找系统中的串口设备 */serial = rt_device_find(PLC_UART_NAME);if (!serial){rt_kprintf("find %s failed!\n", PLC_UART_NAME);return RT_ERROR;}config.baud_rate = BAUD_RATE_9600; //修改波特率为 9600config.data_bits = DATA_BITS_8; //数据位 8config.stop_bits = STOP_BITS_1; //停止位 1config.bufsz = 128; //修改缓冲区 buff size 为 128config.parity = PARITY_NONE; //无奇偶校验位rt_device_control(serial, RT_DEVICE_CTRL_CONFIG, &config);/* 以中断接收及轮询发送模式打开串口设备 */rt_device_open(serial, RT_DEVICE_FLAG_INT_RX);/* 设置接收回调函数 */rt_device_set_rx_indicate(serial, uart_input);
}void app_uart1_API_send_strings( uint8_t* data, int len)
{rt_device_write(serial, 0, data, len);
}char str[] = "hello RT-Thread!\r\n";
/* 线程 1 的入口函数 */
static void uart_plc_thread_entry(void *parameter)
{rt_kprintf("Enter uart_plc_thread /r/n");app_uart1_API_init();//rt_device_write(serial, 0, str, (sizeof(str) - 1));app_uart1_API_send_strings("123456",6);while (1){//rt_device_write(serial, 0, str, (sizeof(str) - 1));rt_thread_mdelay(500);}
}#define THREAD_PRIORITY 25
#define THREAD_STACK_SIZE 1024
#define THREAD_TIMESLICE 5int app_uart_plc_thread_sample(void)
{static rt_thread_t tid1 = RT_NULL;/* 创建线程 1,名称是 thread1,入口是 thread1_entry*/tid1 = rt_thread_create("uart_plc_thread",uart_plc_thread_entry, RT_NULL,THREAD_STACK_SIZE,THREAD_PRIORITY, THREAD_TIMESLICE);/* 如果获得线程控制块,启动这个线程 */if (tid1 != RT_NULL) rt_thread_startup(tid1);return 0;
}INIT_APP_EXPORT(app_uart_plc_thread_sample);