Unlock Embedded Power: A Deep Dive into RT-Thread RTOS Core Libraries and Code Samples
This article provides a comprehensive overview of the RT-Thread real‑time operating system, detailing its core library features, modular components, typical IoT and industrial use cases, and includes practical C code examples for thread management, synchronization, UART drivers, file system operations, and TCP networking.
Introduction
RT-Thread is an open‑source real‑time operating system (RTOS) driven by the Chinese open‑source community, known for its high scalability, lightweight kernel, and rich component ecosystem, making it popular in embedded development for both resource‑constrained ARM Cortex‑M0 devices and high‑performance Cortex‑A processors.
RT-Thread Core Library Overview and Features
The core library is written in C under the GPLv2 license and follows a modular, cut‑down design, allowing developers to select only the components needed for their hardware and application requirements.
High scalability : Kernels range from a 3 KB minimal footprint to complex multi‑core systems.
Strong real‑time performance : Pre‑emptive multitasking with context‑switch times in the microsecond range.
Rich component set : Includes file system, network stack, GUI, and more, reducing the need to reinvent common functionality.
Easy portability : Supports ARM, RISC‑V, MIPS and other architectures with straightforward porting.
Active community : Large Chinese developer community provides extensive documentation and support.
RT-Thread Module Classification
2.1 Kernel Modules
The kernel handles task management, scheduling, synchronization, and communication. Key sub‑modules are:
Thread management : Supports up to 256 priority levels.
Semaphores and mutexes : For thread synchronization and resource protection.
Events and message queues : Enable inter‑thread communication.
Timers : Software timers and high‑precision hardware timers.
Memory management : Dynamic heap allocation and small‑block memory management.
2.2 Device Driver Framework
Provides a unified driver model for common peripherals:
UART (serial communication)
I2C / SPI (standard bus interfaces)
GPIO (general‑purpose I/O)
ADC / DAC (analog signal processing)
2.3 File System
Supported file systems include:
FAT : Compatible with SD cards and USB drives.
LittleFS : Lightweight, suited for constrained devices.
tmpfs : In‑memory file system for temporary data.
2.4 Network Protocol Stack
RT-Thread integrates a lightweight TCP/IP stack (lwIP) and supports common IoT protocols:
TCP/IP (lwIP)
MQTT / HTTP
BSD‑style socket API
2.5 Other Components
RT-Thread Studio : Integrated development environment for configuration and debugging.
RT‑AK : AI toolkit for embedded AI applications.
POSIX interface : Improves code portability across platforms.
Typical Application Scenarios
IoT devices : Smart home, smart meters, using MQTT and CoAP.
Industrial control : PLCs, sensor networks with hard real‑time requirements.
Consumer electronics : Wearables, audio devices.
Medical equipment : Pulse oximeters, monitors emphasizing stability and low power.
Automotive electronics : Infotainment, ADAS.
Functional Module Code Samples
4.1 Thread Management Example
#include <rtthread.h>
#define THREAD_PRIORITY 25
#define THREAD_STACK_SIZE 512
#define THREAD_TIMESLICE 5
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;
static void thread1_entry(void *parameter)
{
rt_uint32_t count = 0;
while (1)
{
rt_kprintf("Thread1 count: %d
", count++);
rt_thread_mdelay(500); // delay 500ms
}
}
static void thread2_entry(void *parameter)
{
rt_uint32_t count = 0;
while (1)
{
rt_kprintf("Thread2 count: %d
", count++);
rt_thread_mdelay(800); // delay 800ms
}
}
int main(void)
{
tid1 = rt_thread_create("thread1", thread1_entry, RT_NULL,
THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);
if (tid1 != RT_NULL)
rt_thread_startup(tid1);
tid2 = rt_thread_create("thread2", thread2_entry, RT_NULL,
THREAD_STACK_SIZE, THREAD_PRIORITY + 1, THREAD_TIMESLICE);
if (tid2 != RT_NULL)
rt_thread_startup(tid2);
return 0;
}Explanation: This example creates two threads that print counters at different intervals using rt_thread_mdelay for delays and rt_kprintf for output.
4.2 Semaphore Synchronization Example
#include <rtthread.h>
static rt_sem_t sem;
static rt_thread_t producer_tid, consumer_tid;
static void producer_thread_entry(void *parameter)
{
while (1)
{
rt_kprintf("Producer: produce an item
");
rt_sem_release(sem);
rt_thread_mdelay(1000);
}
}
static void consumer_thread_entry(void *parameter)
{
while (1)
{
rt_sem_take(sem, RT_WAITING_FOREVER);
rt_kprintf("Consumer: consume an item
");
}
}
int main(void)
{
sem = rt_sem_create("sem", 0, RT_IPC_FLAG_FIFO);
if (sem == RT_NULL)
{
rt_kprintf("Semaphore create failed!
");
return -1;
}
producer_tid = rt_thread_create("producer", producer_thread_entry, RT_NULL, 512, 20, 10);
if (producer_tid != RT_NULL)
rt_thread_startup(producer_tid);
consumer_tid = rt_thread_create("consumer", consumer_thread_entry, RT_NULL, 512, 21, 10);
if (consumer_tid != RT_NULL)
rt_thread_startup(consumer_tid);
return 0;
}Explanation: The producer releases the semaphore every second; the consumer blocks on rt_sem_take and processes each item.
4.3 UART Device Driver Example
#include <rtthread.h>
#include <rtdevice.h>
#define UART_NAME "uart1"
int main(void)
{
rt_device_t uart_dev;
char str[] = "Hello, RT-Thread!
";
uart_dev = rt_device_find(UART_NAME);
if (uart_dev == RT_NULL)
{
rt_kprintf("Failed to find UART device!
");
return -1;
}
if (rt_device_open(uart_dev, RT_DEVICE_OFLAG_RDWR) != RT_EOK)
{
rt_kprintf("Failed to open UART device!
");
return -1;
}
while (1)
{
rt_device_write(uart_dev, 0, str, sizeof(str));
rt_thread_mdelay(1000);
}
rt_device_close(uart_dev);
return 0;
}Explanation: The code locates the UART device, opens it, and repeatedly sends a string once per second.
4.4 File System Operation Example
#include <rtthread.h>
#include <dfs_posix.h>
int main(void)
{
int fd;
char buffer[] = "Hello, RT-Thread File System!
";
fd = open("/sd/test.txt", O_WRONLY | O_CREAT, 0);
if (fd >= 0)
{
write(fd, buffer, sizeof(buffer));
close(fd);
rt_kprintf("File written successfully!
");
}
else
{
rt_kprintf("Failed to open file!
");
}
return 0;
}Explanation: Uses the POSIX API to create and write a file on an SD card; requires DFS and FAT support to be enabled in the RT‑Thread configuration.
4.5 Network Stack Example (TCP Client)
#include <rtthread.h>
#include <lwip/sockets.h>
#include <lwip/api.h>
#define SERVER_IP "192.168.1.100"
#define SERVER_PORT 8080
int main(void)
{
int sock;
struct sockaddr_in server_addr;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
rt_kprintf("Socket creation failed!
");
return -1;
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));
if (connect(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) < 0)
{
rt_kprintf("Connect to server failed!
");
closesocket(sock);
return -1;
}
char *msg = "Hello from RT-Thread!
";
send(sock, msg, strlen(msg), 0);
rt_kprintf("Message sent to server!
");
closesocket(sock);
return 0;
}Explanation: Creates a TCP socket, connects to a remote server, sends a greeting, and closes the connection. Requires lwIP and network device support.
Advanced Development Tips
5.1 Using RT-Thread Studio
RT-Thread Studio is a powerful IDE that provides graphical configuration, code generation, and debugging capabilities, allowing developers to quickly set kernel parameters and add software packages.
5.2 Package Management
The built‑in package manager lets you fetch community packages (e.g., MQTT client, JSON parser) with commands such as pkgs --update, extending system functionality.
5.3 Debugging and Optimization
Log debugging : Use rt_kprintf to output diagnostic information.
Performance tuning : Adjust thread priorities and time slices to improve scheduling.
Memory optimization : Enable the small‑memory manager to reduce fragmentation.
Conclusion
Thanks to its modular architecture, extensive ecosystem, and active community, RT-Thread is an ideal choice for embedded development. This article has demonstrated its capabilities across threading, device drivers, file systems, and networking, providing practical code that can be adapted for simple sensor nodes or complex IoT products.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
