rtthread stm32的双串口程序
时间: 2023-06-23 09:10:04 浏览: 267
下面是一个基于 RT-Thread 的 STM32 双串口程序的示例:
```c
#include <rtthread.h>
#include <board.h>
#define USART1_BUFSZ 256
#define USART2_BUFSZ 256
#define USART1_NAME "uart1"
#define USART2_NAME "uart2"
static rt_uint8_t usart1_rx_buf[USART1_BUFSZ];
static rt_uint8_t usart1_tx_buf[USART1_BUFSZ];
static rt_uint8_t usart2_rx_buf[USART2_BUFSZ];
static rt_uint8_t usart2_tx_buf[USART2_BUFSZ];
static struct rt_serial_device usart1;
static struct rt_serial_device usart2;
static void usart1_rx_ind(rt_device_t dev, rt_size_t size)
{
rt_kprintf("usart1_rx_ind: size = %d\n", size);
}
static void usart2_rx_ind(rt_device_t dev, rt_size_t size)
{
rt_kprintf("usart2_rx_ind: size = %d\n", size);
}
int usart_init(void)
{
/* Init USART1 */
rt_memset(&usart1, 0, sizeof(usart1));
usart1.config.baud_rate = BAUD_RATE_115200;
usart1.config.data_bits = DATA_BITS_8;
usart1.config.parity = PARITY_NONE;
usart1.config.stop_bits = STOP_BITS_1;
usart1.config.bufsz = USART1_BUFSZ;
usart1.config.rx_indicate = usart1_rx_ind;
usart1.config.tx_complete = RT_NULL;
usart1.config.rx_buffer = usart1_rx_buf;
usart1.config.tx_buffer = usart1_tx_buf;
usart1.parent.user_data = RT_NULL;
return rt_serial_register(&usart1, USART1_NAME, RT_DEVICE_FLAG_RDWR);
/* Init USART2 */
rt_memset(&usart2, 0, sizeof(usart2));
usart2.config.baud_rate = BAUD_RATE_115200;
usart2.config.data_bits = DATA_BITS_8;
usart2.config.parity = PARITY_NONE;
usart2.config.stop_bits = STOP_BITS_1;
usart2.config.bufsz = USART2_BUFSZ;
usart2.config.rx_indicate = usart2_rx_ind;
usart2.config.tx_complete = RT_NULL;
usart2.config.rx_buffer = usart2_rx_buf;
usart2.config.tx_buffer = usart2_tx_buf;
usart2.parent.user_data = RT_NULL;
return rt_serial_register(&usart2, USART2_NAME, RT_DEVICE_FLAG_RDWR);
}
int main(void)
{
usart_init();
/* Open USART1 */
rt_device_t dev1 = rt_device_find(USART1_NAME);
rt_device_open(dev1, RT_DEVICE_FLAG_INT_RX);
/* Open USART2 */
rt_device_t dev2 = rt_device_find(USART2_NAME);
rt_device_open(dev2, RT_DEVICE_FLAG_INT_RX);
/* Send data through USART1 */
rt_device_write(dev1, 0, "Hello, USART1!", strlen("Hello, USART1!"));
/* Send data through USART2 */
rt_device_write(dev2, 0, "Hello, USART2!", strlen("Hello, USART2!"));
return RT_EOK;
}
```
在这个例子中,我们使用了 RT-Thread 的串口设备驱动,并且使用了两个串口设备 USART1 和 USART2。我们通过 `usart_init` 函数初始化了这两个设备,并且通过 `rt_serial_register` 函数注册到 RT-Thread 的设备管理器中。
在 `main` 函数中,我们打开了 USART1 和 USART2 设备,并且通过 `rt_device_write` 函数分别向这两个设备发送了一条消息。当接收到数据时,回调函数 `usart1_rx_ind` 和 `usart2_rx_ind` 会被调用,分别输出接收到的数据长度。
需要注意的是,在实际使用中,需要根据具体的硬件配置和需求进行修改。
阅读全文