RT-Thread 21. 按键发送邮箱

本文详细介绍了如何在RT-Thread开发环境中创建线程、使用邮箱进行通信,以及初始化邮箱和处理接收到的邮件。示例代码展示了如何在两个线程间交换消息,直到特定条件触发停止。
摘要由CSDN通过智能技术生成
1.代码
#include <rtthread.h>
#include <rtdevice.h>
#include "drv_gpio.h"

#define THREAD_PRIORITY   30
#define THREAD_TIMESLICE  10

#define TASK_STACK_MAX    500


static struct rt_mailbox mb;
/* 用 于 放 邮 件 的 内 存 池 */
static char mb_pool[128];
static char mb_str1[] = "I'm a mail!";
static char mb_str2[] = "this is another mail!";
static char mb_str3[] = "over";

ALIGN(RT_ALIGN_SIZE)
static char thread41_stack[TASK_STACK_MAX];
static struct rt_thread thread41;

/* 线 程 1 入 口 */
static void thread41_entry(void *parameter)
{
  char *str;
  while (1)
  {
    rt_kprintf("thread1: try to recv a mail\n");
    /* 从 邮 箱 中 收 取 邮 件 */
    if (rt_mb_recv(&mb, (rt_ubase_t *)&str, RT_WAITING_FOREVER) == RT_EOK)
    {
      rt_kprintf("thread1: get a mail from mailbox, the content:%s\n", str);
      if (str == mb_str3)
      break;
      /* 延 时 100ms */
      rt_thread_mdelay(100);
    }
  }
  /* 执 行 邮 箱 对 象 脱 离 */
  rt_mb_detach(&mb);
}

void MbKeyScanCallBack(void)
{
  static rt_uint8_t count = 0;

//  while (count < 10)
//  {
    count ++;
    if (count & 0x1)
    {
      /* 发 送 mb_str1 地 址 到 邮 箱 中 */
      rt_mb_send(&mb, (rt_uint32_t)&mb_str1);
    }
    else
    {
      /* 发 送 mb_str2 地 址 到 邮 箱 中 */
      rt_mb_send(&mb, (rt_uint32_t)&mb_str2);
    }
//    /* 延 时 200ms */
//    rt_thread_mdelay(200);
//  }
//  /* 发 送 邮 件 告 诉 线 程 1, 线 程 2 已 经 运 行 结 束 */
//  rt_mb_send(&mb, (rt_uint32_t)&mb_str3);

}


int MbTaskInit(void)
{
  rt_err_t result;
  /* 初 始 化 一 个 mailbox */
  result = rt_mb_init(&mb,
                      "mbt", /* 名 称 是 mbt */
                      &mb_pool[0], /* 邮 箱 用 到 的 内 存 池 是 mb_pool */
                      sizeof(mb_pool) / 4, /* 邮 箱 中 的 邮 件 数 目, 因 为 一 封 邮
                      件 占 4 字 节 */
                      RT_IPC_FLAG_FIFO); /* 采 用 FIFO 方 式 进 行 线 程 等 待 */
  if (result != RT_EOK)
  {
    rt_kprintf("init mailbox failed.\n");
    return -1;
  }
  rt_thread_init(&thread41,
                "thread41",
                thread41_entry,
                RT_NULL,
                &thread41_stack[0],
                sizeof(thread41_stack),
                THREAD_PRIORITY, THREAD_TIMESLICE);
  rt_thread_startup(&thread41);
  return 0;

}
2.输出
key press val is 1
t3 take a static semaphore.
thread1: get a mail from mailbox, the content:I'm a mail!

thread1: try to recv a mail

key press val is 1
t3 take a static semaphore.
thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值