RT-Thread Studio实现静态线程

发布于:2024-06-27 ⋅ 阅读:(156) ⋅ 点赞:(0)

1创建项目 (STM32F03ZET6)

RT-Thread项目与RT-Thread Nano 项目区别

  1. RT-Thread:

    • 完整版:这是RT-Thread的完整形态,适用于资源较丰富的物联网设备。
    • 功能:它提供了全面的中间件组件,如文件系统、网络协议栈、GUI等,支持复杂的物联网应用开发。
    • 资源占用:相对较大,因为它包含了更多的功能组件。
  2. RT-Thread Nano:(个别函数也去掉了)

    • 精简版:这是一个精简的硬实时内核,设计用于资源受限的微控制器,如ARM Cortex-M0。
    • 功能:它去掉了完整版中的许多高级特性,保留了最核心的多线程管理和调度功能。
    • 资源占用:非常小,适用于内存和存储空间有限的小型设备。

2选择板子(根据自己的板子选择)

3找到主函数

4编写代码

4-1创建必要的变量

// 定义线程控制块
static struct rt_thread thread1;
// 定义线程栈
static rt_uint8_t thread1_stack[1024];

4-2创建入口函数

// 线程入口函数
static void thread1_entry(void *parameter)
{
    while (1)
    {
        // 线程执行的代码
        rt_kprintf("Thread 2 is running\n");
        rt_thread_delay(1000); // 线程延时,单位为毫秒
    }
}

4-3在主函数中启动线程

// 初始化线程
        rt_thread_init(&thread1,              // 线程控制块
                       "thread1",             // 线程名字
                       thread1_entry,         // 线程入口函数
                       RT_NULL,               // 线程入口参数
                       &thread1_stack[0],     // 线程栈起始地址
                       sizeof(thread1_stack), // 线程栈大小
                       10,                    // 线程优先级
                       20);                   // 线程时间片
        // 启动线程
        rt_thread_startup(&thread1);

4-4全部代码

/*
 * Copyright (c) 2006-2024, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2024-06-26     RT-Thread    first version
 */

#include <rtthread.h>

#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>



// 定义线程控制块
static struct rt_thread thread1;
// 定义线程栈
static rt_uint8_t thread1_stack[1024];

// 线程入口函数
static void thread1_entry(void *parameter)
{
    while (1)
    {
        // 线程执行的代码
        rt_kprintf("Thread 2 is running\n");
        rt_thread_delay(1000); // 线程延时,单位为毫秒
    }
}

int main(void)
{
    int count = 1;
    // 初始化线程
        rt_thread_init(&thread1,              // 线程控制块
                       "thread1",             // 线程名字
                       thread1_entry,         // 线程入口函数
                       RT_NULL,               // 线程入口参数
                       &thread1_stack[0],     // 线程栈起始地址
                       sizeof(thread1_stack), // 线程栈大小
                       10,                    // 线程优先级
                       20);                   // 线程时间片
        // 启动线程
        rt_thread_startup(&thread1);

    while (count++)
    {
        LOG_D("Hello RT-Thread!");
        rt_thread_mdelay(1000);
    }

    return RT_EOK;
}

其中rt_kprintf()与LOG_D()作用一样都是串口输出文本


网站公告

今日签到

点亮在社区的每一天
去签到