Godbolt - online C compiler and preprocessor
- Информация о материале
- Автор: Super User
- Родительская категория: Заметки
- Категория: Программирование микроконтроллеров
- Просмотров: 6
Understanding Function Queues in C
- Информация о материале
- Автор: Super User
- Родительская категория: Заметки
- Категория: Программирование микроконтроллеров
- Просмотров: 18
Understanding Function Queues in C
Function queues are a powerful programming construct, particularly useful in embedded systems and real-time applications. This article explains a set of macros implemented in C to handle various types of function queues, including standard queues, delayed queues, and parameterized queues.
1. Standard Function Queue
The fQ macro defines a basic circular queue to store and execute function pointers. It includes:
- q##_last and q##_first for managing queue indices.
- q##_Queue, an array of function pointers.
- q##_Push, which adds a function pointer to the queue.
- q##_Pull, which retrieves and executes a function from the queue.
#define fQ(q, Q_SIZE) \ volatile int q##_last = 0; \ int q##_first = 0; \ void (*q##_Queue[Q_SIZE])(void); \ int q##_Push(void (*pointerQ)(void)) { \ if ((q##_last + 1) % Q_SIZE == q##_first)\ return 1; /* Queue is full */ \ q##_Queue[q##_last++] = pointerQ; \ q##_last %= Q_SIZE; \ return 0; /* Success */ \ } \ int (*q##_Pull(void))(void) { \ if (q##_last == q##_first) \ return 1; /* Queue is empty */ \ q##_Queue[q##_first++](); \ q##_first %= Q_SIZE; \ return 0; /* Success */ \ }
2. Delayed Function Queue
The del_fQ macro extends the standard queue to support delayed execution:
- q##_del_fQueue stores delayed function pointers.
- q##_execTime and q##_time track execution times.
- q##_Push_delayed schedules a function for future execution.
- q##_Tick processes delayed functions when their time arrives.
- q##_Revoke cancels a scheduled function.
#define del_fQ(q, Q_SIZE) \ int q##_time = 0; \ void (*q##_del_fQueue[Q_SIZE])(void); \ int q##_execArr[Q_SIZE] = { 0 }; \ int q##_execTime[Q_SIZE]; \ fQ(q, Q_SIZE) \ int q##_Push_delayed(void (*pointerF)(void), int delayTime){ \ int q##_fullQ = 1; \ for (int i = 0; i < Q_SIZE; i++) { \ if (!q##_execArr[i]) { \ q##_del_fQueue[i] = pointerF; \ q##_execArr[i] = 1; \ q##_execTime[i] = q##_time + delayTime; \ q##_fullQ = 0; \ break; \ } \ } \ return q##_fullQ; \ } \ void q##_Tick(void){ \ for (int i = 0; i < Q_SIZE; i++) { \ if (q##_execTime[i] == q##_time) { \ if (q##_execArr[i]) { \ q##_Push(q##_del_fQueue[i]); \ q##_execArr[i] = 0; \ } \ } \ } \ q##_time++; /* Increment time */ \ } \ int q##_Revoke(void (*pointerF)(void)){ \ int result = 1; \ for (int i = 0; i < Q_SIZE; i++) { \ if (q##_del_fQueue[i] == pointerF) { \ q##_execArr[i] = 0; \ result = 0; \ } \ } \ return result; \ }
3. Parameterized Function Queue
The fQP macro allows parameterized function execution:
- q##_funcs stores function pointers.
- q##_params stores associated parameters.
- q##_Push and q##_Pull handle adding and executing functions with parameters.
#define fQP(q, Q_SIZE, param_type) \ void (*q##_funcs[Q_SIZE])(param_type); \ param_type q##_params[Q_SIZE]; \ volatile int q##_last = 0; \ int q##_first = 0; \ int q##_Push(void (*func)(param_type), param_type params) { \ if ((q##_last + 1) % Q_SIZE == q##_first) \ return 1; /* Queue is full */ \ q##_funcs[q##_last] = func; \ q##_params[q##_last++] = params; \ q##_last %= Q_SIZE; \ return 0; /* Success */ \ } \ int q##_Pull(void) { \ if (q##_last == q##_first) \ return 1; /* Queue is empty */ \ q##_funcs[q##_first](q##_params[q##_first++]); \ q##_first %= Q_SIZE; \ return 0; /* Success */ \ }
Key Features
These macros provide:
- Circular Buffers: Efficient storage and retrieval with wrap-around indices.
- Delayed Execution: Schedule functions to execute after a delay.
- Parameterized Queues: Pass parameters to queued functions.
Use Cases
Function queues are particularly useful in:
- Task scheduling in embedded systems or real-time applications.
- Managing callbacks or event-driven programming workflows.
- Efficient queuing and delayed execution in constrained environments.
find more here:
Conclusion
The macros presented here demonstrate a flexible and efficient way to manage function queues in C. By integrating these techniques into your projects, you can streamline task scheduling, improve resource management, and enhance the overall functionality of your software.
Кулон с имитацией движения жидкости
- Информация о материале
- Автор: Super User
- Родительская категория: Заметки
- Категория: Моделирование
- Просмотров: 23
ANTIRTOS: A Lightweight and Universal C++ Library for Task Management in Embedded Systems
- Информация о материале
- Автор: Super User
- Родительская категория: Заметки
- Категория: Программирование микроконтроллеров
- Просмотров: 44
Introduction
Embedded systems are ubiquitous, powering a wide array of devices from simple sensors to complex IoT hubs. Efficient task management in such systems is crucial, especially when resources are limited. Traditional Real-Time Operating Systems (RTOS) offer robust solutions but often come with significant overhead in terms of memory, complexity, and power consumption. This is where ANTIRTOS steps in, providing a lightweight, modular, and universal C++ library for task management in embedded applications.
What is ANTIRTOS?
ANTIRTOS (Anti-Real-Time Operating System) is not an RTOS in the traditional sense. Instead, it is a minimalistic task management library designed for scenarios where the overhead of a full RTOS is not justified. By offering basic scheduling and task management features, ANTIRTOS bridges the gap between bare-metal programming and the use of a full-fledged RTOS.
Key Features
- Lightweight Design: Minimal memory and CPU usage make ANTIRTOS ideal for resource-constrained systems.
- Modular Architecture: Developers can include only the modules they need, reducing overhead.
- Scalability: Suitable for small microcontrollers as well as more capable embedded platforms.
- Ease of Integration: Written in standard C++, ANTIRTOS integrates seamlessly with existing projects.
- Deterministic Behavior: Ensures predictable task execution, essential for time-sensitive applications.
Core Concepts
Task Management
At its core, ANTIRTOS provides mechanisms for managing tasks, which can be functions or callable objects. These tasks can be scheduled for immediate execution, delayed execution, or periodic execution.
Event-Driven Execution
ANTIRTOS employs an event-driven model, where tasks are executed based on predefined triggers such as time delays or external events. This approach reduces idle CPU usage and optimizes power consumption.
Simplicity and Flexibility
Unlike traditional RTOSes that require context switching, ANTIRTOS operates within a single-threaded environment. This design choice simplifies implementation and ensures that the library remains lightweight and efficient.
Key Components
Task Queue
The task queue is the backbone of ANTIRTOS. It manages the addition, removal, and execution of tasks. Tasks are stored in a queue, ensuring they are executed in the order they are added.
Delayed Task Execution
ANTIRTOS allows developers to schedule tasks with a delay. This feature is particularly useful for implementing time-based functionality without relying on blocking delays, which can waste CPU cycles.
Periodic Execution
Tasks can be scheduled for periodic execution. This is achieved using a simple tick mechanism, which updates the library's internal timer and triggers periodic tasks.
Minimal API
The ANTIRTOS API is intentionally minimal to reduce learning curves and development time. Key methods include:
-
push()
- Add a task to the queue for immediate execution. -
push_delayed()
- Schedule a task for delayed execution. -
tick()
- Update the library's internal timer. -
pull()
- Execute the next task in the queue.
functionality of ANTIRTOS is distributed across individual classes such as:
-
del_fQP
(for delayed functional pointers with parameters) -
del_fQ
(for delayed functional pointers without parameters) -
fQP
(for functional pointers with parameters) -
fQ
(for functional pointers without parameters)
Benefits of ANTIRTOS
Efficiency
By avoiding the overhead associated with traditional RTOSes, ANTIRTOS maximizes the efficiency of resource-constrained systems. Its event-driven model ensures that CPU cycles are spent only on meaningful computations.
Deterministic Behavior
Embedded systems often require precise timing. ANTIRTOS provides deterministic behavior by ensuring tasks are executed exactly when scheduled, without unpredictable delays.
Portability
Written in standard C++, ANTIRTOS is highly portable and can be used across a wide range of microcontroller platforms and development environments.
Developer-Friendly
The simple and intuitive API minimizes development time, allowing engineers to focus on application logic rather than system-level intricacies.
Use Cases
IoT Devices
In IoT applications, power efficiency and modularity are paramount. ANTIRTOS enables efficient task scheduling while keeping the firmware footprint small.
Sensor Nodes
For sensor nodes that perform periodic data acquisition, ANTIRTOS offers an ideal solution for managing periodic tasks without the complexity of an RTOS.
Consumer Electronics
In devices such as home appliances and wearables, ANTIRTOS can handle background tasks like monitoring inputs and controlling outputs efficiently.
Limitations
While ANTIRTOS is powerful, it is not a one-size-fits-all solution. Applications requiring multi-threading, advanced synchronization, or complex resource sharing may still need a full RTOS. However, for simpler applications, ANTIRTOS strikes an excellent balance between functionality and efficiency.
Getting Started
Installation
ANTIRTOS is distributed as a header-only library. To use it, simply include the necessary headers in your project. The library is compatible with most standard C++ compilers.
Example Code
#include "antirtos.h"
void task1() {
// Task logic here
}
void task2() {
// Task logic here
}
int main() {
del_fQ tm(10); // Create a TaskManager with a queue size of 10
tm.push(task1); // Add task1 for immediate execution
tm.push_delayed(task2, 100); // Schedule task2 to run after 100 ticks
while (true) {
tm.tick(); // Update the timer
tm.pull(); // Execute the next task
}
return 0;
}
Conclusion
ANTIRTOS is a compelling alternative to traditional RTOSes for embedded systems where simplicity, efficiency, and modularity are paramount. By providing essential task management features without unnecessary overhead, ANTIRTOS empowers developers to create high-performance, resource-efficient applications. Whether you’re building IoT devices, sensor nodes, or consumer electronics, ANTIRTOS offers a streamlined path to success.
Упражнения при астигматизме
- Информация о материале
- Автор: Super User
- Категория: Новости
- Просмотров: 51
Астигматизм — это нарушение зрения, при котором роговица или хрусталик имеют неправильную форму, что приводит к искажению изображения. Существуют упражнения для глаз, которые, как утверждается, могут помочь при астигматизме. Вот пять таких упражнений:
-
Расслабление прямых мышц глаза:
- Держите большой палец перед лицом на расстоянии около 10 см над носом.
- Медленно перемещайте палец по воображаемому циферблату: сначала к позиции 12 часов, задержитесь на 2–3 секунды.
- Возвращайтесь к исходной точке и повторяйте движение к позициям 1, 3, 5, 6, 7, 9, 11 и обратно к 12 часам.
- Не забывайте дышать ровно; медленный выдох поможет расслабить мышцы.
- Продолжительность: 2 минуты.
- Повторения: 2–4 раза в день.
-
Массаж глаз:
- Закройте глаза и поместите по два пальца на каждое веко.
- Аккуратно надавливая, выполняйте круговые движения пальцами: справа налево, сверху вниз.
- Делайте движения по часовой и против часовой стрелки по 10–15 раз в каждом направлении.
- Продолжительность: 1 минута.
- Повторения: 2–4 раза в день.
-
Чтение с переключением фокуса:
- Используя корректирующие линзы, возьмите книгу.
- После прочтения каждого абзаца переводите взгляд на объект сбоку (например, игральную карту).
- Чередуйте фокус между книгой и объектом до появления легкой усталости глаз.
- Продолжительность: 10 минут.
- Повторения: 2–4 раза в день.
-
Обращение к мануальному терапевту:
- Люди с астигматизмом часто наклоняют голову в одну сторону, что может привести к напряжению шеи и неправильной осанке.
- Рекомендуется посетить специалиста для коррекции осанки и расслабления мышц шеи и позвоночника.
-
Упражнение для периферического зрения:
- Возьмите лист бумаги, достаточно большой, чтобы закрыть оба глаза.
- Убедитесь, что боковые стороны остаются открытыми для периферического зрения.
- Наденьте корректирующие линзы и прикрепите бумагу к переносице.
- Поочередно перемещайте руки к периферийной области бумаги.
- Не поворачивая голову, старайтесь увидеть пальцы с каждой стороны.
- Продолжительность: 5 минут.
- Повторения: 2–4 раза в день.
Регулярное выполнение этих упражнений может помочь снизить напряжение глаз, вызванное астигматизмом. Однако научные данные о их эффективности ограничены. Перед началом любых упражнений рекомендуется проконсультироваться с офтальмологом для оценки их целесообразности в вашем случае.
Страница 1 из 186