两块STM32使用RT-Thread的邮箱进行串口通信的例子
时间: 2023-12-14 21:35:40 浏览: 37
以下是两块STM32使用RT-Thread的邮箱进行串口通信的示例代码:
板子1:
```c
#include <rtthread.h>
#include <rtdevice.h>
/* 定义邮箱控制块 */
static struct rt_mailbox mbox;
/* 定义线程1 */
static void thread1_entry(void *parameter)
{
rt_uint32_t msg = 0;
rt_err_t result;
while (1)
{
/* 发送消息到邮箱 */
result = rt_mb_send(&mbox, msg);
if (result == RT_EOK)
{
rt_kprintf("Thread 1 send message: %d\n", msg);
}
msg++;
/* 线程挂起1秒钟 */
rt_thread_delay(1000);
}
}
/* 定义线程2 */
static void thread2_entry(void *parameter)
{
rt_uint32_t msg;
rt_err_t result;
while (1)
{
/* 从邮箱中接收消息 */
result = rt_mb_recv(&mbox, &msg, RT_WAITING_FOREVER);
if (result == RT_EOK)
{
rt_kprintf("Thread 2 receive message: %d\n", msg);
}
/* 线程挂起1秒钟 */
rt_thread_delay(1000);
}
}
int main(void)
{
/* 初始化邮箱 */
rt_mb_init(&mbox, "mbox", NULL, 10, RT_IPC_FLAG_FIFO);
/* 启动线程1 */
rt_thread_t thread1 = rt_thread_create("thread1", thread1_entry, RT_NULL, 512, 25, 10);
if (thread1 != RT_NULL)
{
rt_thread_startup(thread1);
}
/* 启动线程2 */
rt_thread_t thread2 = rt_thread_create("thread2", thread2_entry, RT_NULL, 512, 26, 10);
if (thread2 != RT_NULL)
{
rt_thread_startup(thread2);
}
/* 运行RT-Thread */
rt_thread_mdelay(RT_WAITING_FOREVER);
return 0;
}
```
板子2:
```c
#include <rtthread.h>
#include <rtdevice.h>
/* 定义邮箱控制块 */
static struct rt_mailbox mbox;
/* 定义线程1 */
static void thread1_entry(void *parameter)
{
rt_uint32_t msg;
rt_err_t result;
while (1)
{
/* 从邮箱中接收消息 */
result = rt_mb_recv(&mbox, &msg, RT_WAITING_FOREVER);
if (result == RT_EOK)
{
rt_kprintf("Thread 1 receive message: %d\n", msg);
}
/* 线程挂起1秒钟 */
rt_thread_delay(1000);
}
}
/* 定义线程2 */
static void thread2_entry(void *parameter)
{
rt_uint32_t msg = 0;
rt_err_t result;
while (1)
{
/* 发送消息到邮箱 */
result = rt_mb_send(&mbox, msg);
if (result == RT_EOK)
{
rt_kprintf("Thread 2 send message: %d\n", msg);
}
msg++;
/* 线程挂起1秒钟 */
rt_thread_delay(1000);
}
}
int main(void)
{
/* 初始化邮箱 */
rt_mb_init(&mbox, "mbox", NULL, 10, RT_IPC_FLAG_FIFO);
/* 启动线程1 */
rt_thread_t thread1 = rt_thread_create("thread1", thread1_entry, RT_NULL, 512, 25, 10);
if (thread1 != RT_NULL)
{
rt_thread_startup(thread1);
}
/* 启动线程2 */
rt_thread_t thread2 = rt_thread_create("thread2", thread2_entry, RT_NULL, 512, 26, 10);
if (thread2 != RT_NULL)
{
rt_thread_startup(thread2);
}
/* 运行RT-Thread */
rt_thread_mdelay(RT_WAITING_FOREVER);
return 0;
}
```