两块STM32串口通信使用RT-Thread邮箱例子
时间: 2023-07-20 15:05:23 浏览: 163
以下是两块STM32使用RT-Thread邮箱进行串口通信的简单示例:
在第一块STM32中,我们需要使用邮箱发送数据:
```c
#include <rtthread.h>
#include <rtdevice.h>
static rt_mailbox_t mb = RT_NULL;
void uart1_rx_thread_entry(void *parameter)
{
rt_device_t device;
rt_uint8_t buff[16];
rt_size_t size;
device = rt_device_find("uart1");
if(device == RT_NULL)
{
rt_kprintf("Can't find uart1\n");
return;
}
while(1)
{
rt_memset(buff, 0, sizeof(buff));
size = rt_device_read(device, 0, buff, sizeof(buff));
rt_mb_send(mb, (rt_uint32_t)buff, size);
}
}
int main(void)
{
rt_thread_t thread;
rt_kprintf("Starting uart1_rx_thread...\n");
mb = rt_mb_create("mb", 10, RT_IPC_FLAG_FIFO);
thread = rt_thread_create("uart1_rx", uart1_rx_thread_entry, RT_NULL, 1024, 8, 20);
if(thread != RT_NULL)
{
rt_thread_startup(thread);
}
while(1)
{
rt_kprintf("Hello, world!\n");
rt_thread_delay(1000);
}
}
```
在第二块STM32中,我们需要使用邮箱接收数据:
```c
#include <rtthread.h>
#include <rtdevice.h>
static rt_mailbox_t mb = RT_NULL;
void uart1_tx_thread_entry(void *parameter)
{
rt_device_t device;
rt_uint8_t buff[16];
rt_size_t size;
device = rt_device_find("uart1");
if(device == RT_NULL)
{
rt_kprintf("Can't find uart1\n");
return;
}
while(1)
{
rt_memset(buff, 0, sizeof(buff));
size = rt_mb_recv(mb, (rt_uint32_t *)buff, sizeof(buff), RT_WAITING_FOREVER);
rt_device_write(device, 0, buff, size);
}
}
int main(void)
{
rt_thread_t thread;
rt_kprintf("Starting uart1_tx_thread...\n");
mb = rt_mb_create("mb", 10, RT_IPC_FLAG_FIFO);
thread = rt_thread_create("uart1_tx", uart1_tx_thread_entry, RT_NULL, 1024, 8, 20);
if(thread != RT_NULL)
{
rt_thread_startup(thread);
}
while(1)
{
rt_kprintf("Hello, world!\n");
rt_thread_delay(1000);
}
}
```
当第一块STM32从串口接收到数据时,它会将数据发送到邮箱中。第二块STM32会从邮箱中接收数据并将其发送到串口中。这样,两块STM32就完成了串口通信。
阅读全文