### BitPack Basic Usage Example Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Demonstrates basic operations of the BitPack library, including setting, reading, and clearing flags, as well as accessing bits via array notation and copying bit data. ```cpp #include "BitPack.h" // указываем количество флагов BitPack<10> flags; void setup() { Serial.begin(9600); flags.clearAll(); // опустить все flags.set(1); // поднять флаг flags.set(3); flags.write(3, 1); Serial.println(flags.read(0)); // прочитать флаг Serial.println(flags.read(1)); Serial.println(flags.read(2)); flags[3] = 0; // можно писать через [] Serial.println(flags[3]); // можно читать через [] BitPack<10> flags2; flags[0] = flags2[1]; // копировать бит flags.copyTo(flags2); // копировать весь пакет } void loop() { } ``` -------------------------------- ### BitPack Static Buffer Example Source: https://context7.com/gyverlibs/bitpack/llms.txt Demonstrates creating and manipulating a fixed-size bit array using BitPack. Specify the number of flags at compile time. Automatically clears all flags on creation. ```cpp #include // Создание битового массива на 10 флагов (займёт 2 байта) BitPack<10> flags; void setup() { Serial.begin(9600); // Установка флагов flags.set(0); // Установить флаг 0 flags.set(3); // Установить флаг 3 flags.set(7); // Установить флаг 7 // Чтение флагов Serial.print("Флаг 0: "); Serial.println(flags.read(0)); // Выведет: 1 Serial.print("Флаг 1: "); Serial.println(flags.read(1)); // Выведет: 0 Serial.print("Флаг 3: "); Serial.println(flags.read(3)); // Выведет: 1 // Запись значения напрямую flags.write(5, true); // Установить флаг 5 в true flags.write(3, false); // Сбросить флаг 3 // Переключение флага flags.toggle(0); // Флаг 0 теперь 0 flags.toggle(0); // Флаг 0 снова 1 // Сброс флага flags.clear(7); // Флаг 7 теперь 0 // Информация о массиве Serial.print("Количество флагов: "); Serial.println(flags.amount()); // Выведет: 10 Serial.print("Размер в байтах: "); Serial.println(flags.size()); // Выведет: 2 // Массовые операции flags.setAll(); // Установить все флаги flags.clearAll(); // Сбросить все флаги } void loop() {} ``` -------------------------------- ### BitPack - Static Buffer Source: https://context7.com/gyverlibs/bitpack/llms.txt Demonstrates the usage of the BitPack class for managing a static bit array with a compile-time defined size. Includes examples of setting, reading, writing, toggling, clearing flags, and obtaining array information. ```APIDOC ## BitPack - Static Buffer ### Description This section details the usage of the `BitPack` class, which manages a bit array with a fixed size determined at compile time. The buffer is stored internally within the object, and the size is specified in the number of flags (not bytes). All flags are automatically cleared upon creation. ### Methods - `set(index)`: Sets the flag at the specified index to true. - `read(index)`: Reads the boolean value of the flag at the specified index. - `write(index, value)`: Writes a boolean value directly to the flag at the specified index. - `toggle(index)`: Toggles the state of the flag at the specified index. - `clear(index)`: Clears the flag at the specified index (sets to false). - `amount()`: Returns the total number of flags in the bit array. - `size()`: Returns the size of the bit array in bytes. - `setAll()`: Sets all flags in the bit array to true. - `clearAll()`: Clears all flags in the bit array (sets to false). ### Example Usage ```cpp #include // Create a bit array for 10 flags (will occupy 2 bytes) BitPack<10> flags; void setup() { Serial.begin(9600); // Setting flags flags.set(0); flags.set(3); flags.set(7); // Reading flags Serial.print("Flag 0: "); Serial.println(flags.read(0)); // Output: 1 Serial.print("Flag 1: "); Serial.println(flags.read(1)); // Output: 0 Serial.print("Flag 3: "); Serial.println(flags.read(3)); // Output: 1 // Writing value directly flags.write(5, true); flags.write(3, false); // Toggling a flag flags.toggle(0); flags.toggle(0); // Clearing a flag flags.clear(7); // Array information Serial.print("Number of flags: "); Serial.println(flags.amount()); // Output: 10 Serial.print("Size in bytes: "); Serial.println(flags.size()); // Output: 2 // Bulk operations flags.setAll(); flags.clearAll(); } void loop() {} ``` ``` -------------------------------- ### BitPackDyn Dynamic Buffer Example Source: https://context7.com/gyverlibs/bitpack/llms.txt Demonstrates using BitPackDyn for a dynamically allocated bit array. The size can be set at runtime using init() or the constructor. Supports copy and move constructors, and memory is freed automatically. ```cpp #include BitPackDyn dynamicFlags; void setup() { Serial.begin(9600); // Инициализация с указанием количества флагов dynamicFlags.init(20); // Создать массив на 20 флагов // Альтернативный способ - через конструктор BitPackDyn flags2(15); // Массив на 15 флагов // Работа с флагами идентична BitPack dynamicFlags.set(0); dynamicFlags.set(5); dynamicFlags.set(19); Serial.print("Флаг 0: "); Serial.println(dynamicFlags.read(0)); // Выведет: 1 Serial.print("Флаг 10: "); Serial.println(dynamicFlags.read(10)); // Выведет: 0 Serial.print("Флаг 19: "); Serial.println(dynamicFlags.read(19)); // Выведет: 1 Serial.print("Количество флагов: "); Serial.println(dynamicFlags.amount()); // Выведет: 20 Serial.print("Размер в байтах: "); Serial.println(dynamicFlags.size()); // Выведет: 3 // Копирование объекта BitPackDyn copyFlags = dynamicFlags; Serial.print("Копия, флаг 5: "); Serial.println(copyFlags.read(5)); // Выведет: 1 // Переинициализация с новым размером dynamicFlags.init(8); // Теперь только 8 флагов Serial.print("Новое количество: "); Serial.println(dynamicFlags.amount()); // Выведет: 8 // Удаление буфера dynamicFlags.reset(); Serial.print("После reset: "); Serial.println(dynamicFlags.amount()); // Выведет: 0 } void loop() {} ``` -------------------------------- ### BitPack Core Methods Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Common methods for manipulating bit flags: set, clear, toggle, write, read, setAll, clearAll, copyTo, copyFrom. Also includes methods to get the number of flags and the buffer size in bytes. ```cpp // методы void set(uint16_t num); void clear(uint16_t num); void toggle(uint16_t num); void write(uint16_t num, bool state); bool read(uint16_t num); void setAll(); void clearAll(); bool copyTo(любой пак); bool copyFrom(любой пак); uint16_t amount(); uint16_t size(); uint8_t* pack; ``` -------------------------------- ### Disable Array Access in BitPack Source: https://context7.com/gyverlibs/bitpack/llms.txt Define BP_NO_ARRAY before including the library to disable array-like access (e.g., flags[0]) and save 2 bytes of RAM. This is useful for memory-constrained devices. Access must then be done via set(), get(), read(), write(), clear(), or toggle() methods. ```cpp // ВАЖНО: определить ДО подключения библиотеки #define BP_NO_ARRAY #include BitPack<10> flags; void setup() { Serial.begin(9600); // Доступ через [] недоступен, используем функции flags.set(0); flags.set(3); flags.write(5, true); Serial.print("Флаг 0: "); Serial.println(flags.read(0)); // Выведет: 1 Serial.print("Флаг 3: "); Serial.println(flags.read(3)); // Выведет: 1 Serial.print("Флаг 5: "); Serial.println(flags.read(5)); // Выведет: 1 flags.clear(3); flags.toggle(0); Serial.print("Флаг 0 после toggle: "); Serial.println(flags.read(0)); // Выведет: 0 Serial.print("Флаг 3 после clear: "); Serial.println(flags.read(3)); // Выведет: 0 // Следующий код НЕ скомпилируется с BP_NO_ARRAY: // flags[0] = 1; // Ошибка компиляции // bool x = flags[0]; // Ошибка компиляции } void loop() {} ``` -------------------------------- ### BitPack Initialization Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Demonstrates how to initialize BitPack objects with static, dynamic, or external buffers. ```APIDOC ## BitPack Initialization ### Description Initialize BitPack objects for static buffer, dynamic allocation, or with an external buffer. ### Method Constructor Overloads ### Endpoint N/A (Library Initialization) ### Request Body N/A ### Request Example ```cpp // Static buffer inside the object BitPack<10> pack; // Dynamic allocation BitPackDyn pack(10); // External buffer uint8_t buf[2]; // Buffer for 10 flags (approx. 2 bytes) BitPackExt pack(buf, 10); ``` ### Response N/A (Initialization) ### Response Example N/A ``` -------------------------------- ### Initialize and Use BitPackExt with External Buffer Source: https://context7.com/gyverlibs/bitpack/llms.txt Demonstrates initializing and using the BitPackExt class with a user-provided external buffer. Useful for managing memory in EEPROM or when full control over memory is needed. The buffer must exist for the lifetime of the object. ```cpp #include // Внешний буфер: 1 байт = 8 флагов, 2 байта = до 16 флагов uint8_t externalBuffer[3]; // Буфер на 24 флага BitPackExt extFlags; void setup() { Serial.begin(9600); // Способ 1: Инициализация через конструктор // Аргументы: буфер, количество флагов, очистить буфер (по умолчанию true) BitPackExt flags1(externalBuffer, 20, true); // Способ 2: Отложенная инициализация extFlags.setBuffer(externalBuffer, 20); // Работа с флагами extFlags.set(0); extFlags.set(10); extFlags.set(19); Serial.print("Флаг 0: "); Serial.println(extFlags.read(0)); // Выведет: 1 Serial.print("Флаг 10: "); Serial.println(extFlags.read(10)); // Выведет: 1 // Прямой доступ к буферу для сохранения/восстановления Serial.print("Байт 0: "); Serial.println(extFlags.pack[0], BIN); // Выведет содержимое первого байта Serial.print("Байт 1: "); Serial.println(extFlags.pack[1], BIN); // Выведет содержимое второго байта // Инициализация без очистки буфера (сохраняет предыдущие данные) uint8_t prefilledBuffer[2] = {0b00000101, 0b00000000}; // Флаги 0 и 2 установлены BitPackExt restoredFlags(prefilledBuffer, 10, false); // false - не очищать Serial.print("Восстановленный флаг 0: "); Serial.println(restoredFlags.read(0)); // Выведет: 1 Serial.print("Восстановленный флаг 2: "); Serial.println(restoredFlags.read(2)); // Выведет: 1 } void loop() {} ``` -------------------------------- ### Initialize BitPack with Static Buffer Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Use BitPack for a static buffer where N is the number of flags. This allocates memory at compile time. ```cpp BitPack<10> pack; // static буфер внутри ``` -------------------------------- ### BitPackDyn - Dynamic Buffer Source: https://context7.com/gyverlibs/bitpack/llms.txt Illustrates the use of the BitPackDyn class for creating a bit array with dynamically allocated memory, allowing the size to be determined at runtime. Covers initialization, flag manipulation, size retrieval, copying, and resetting. ```APIDOC ## BitPackDyn - Dynamic Buffer ### Description This section covers the `BitPackDyn` class, designed for creating bit arrays with dynamic memory allocation. The size can be specified during program execution. It supports copy and move constructors, and the allocated memory is automatically managed and freed when the object is destroyed. ### Methods - `init(num_flags)`: Initializes or reinitializes the bit array with the specified number of flags. - `read(index)`: Reads the boolean value of the flag at the specified index. - `set(index)`: Sets the flag at the specified index to true. - `write(index, value)`: Writes a boolean value directly to the flag at the specified index. - `toggle(index)`: Toggles the state of the flag at the specified index. - `clear(index)`: Clears the flag at the specified index (sets to false). - `amount()`: Returns the total number of flags in the bit array. - `size()`: Returns the size of the bit array in bytes. - `reset()`: Deallocates the memory and resets the number of flags to 0. ### Example Usage ```cpp #include BitPackDyn dynamicFlags; void setup() { Serial.begin(9600); // Initialize with a specific number of flags dynamicFlags.init(20); // Creates an array for 20 flags // Alternative initialization via constructor BitPackDyn flags2(15); // Array for 15 flags // Flag operations are identical to BitPack dynamicFlags.set(0); dynamicFlags.set(5); dynamicFlags.set(19); Serial.print("Flag 0: "); Serial.println(dynamicFlags.read(0)); // Output: 1 Serial.print("Flag 10: "); Serial.println(dynamicFlags.read(10)); // Output: 0 Serial.print("Flag 19: "); Serial.println(dynamicFlags.read(19)); // Output: 1 Serial.print("Number of flags: "); Serial.println(dynamicFlags.amount()); // Output: 20 Serial.print("Size in bytes: "); Serial.println(dynamicFlags.size()); // Output: 3 // Copying an object BitPackDyn copyFlags = dynamicFlags; Serial.print("Copy, flag 5: "); Serial.println(copyFlags.read(5)); // Output: 1 // Reinitializing with a new size dynamicFlags.init(8); // Now only 8 flags Serial.print("New count: "); Serial.println(dynamicFlags.amount()); // Output: 8 // Deallocating buffer dynamicFlags.reset(); Serial.print("After reset: "); Serial.println(dynamicFlags.amount()); // Output: 0 } void loop() {} ``` ``` -------------------------------- ### Initialize BitPack with External Buffer Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Use BitPackExt(buffer, N) to manage flags within a pre-allocated external buffer. N specifies the number of flags the buffer can hold (8 flags per byte). ```cpp uint8_t buf[2]; // 1 байт - 8 флагов BitPackExt pack(buf, 10); // 10 флагов ``` -------------------------------- ### BitFlags8, BitFlags16, BitFlags32 Usage with Macros Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Demonstrates using BitFlags8, BitFlags16, and BitFlags32 with bit masks and macros like 'bit(n)'. This allows for efficient setting, checking, and comparing of multiple flags at once. ```cpp #define MY_FLAG_0 bit(0) #define KEK_FLAG bit(1) #define SOME_F bit(2) BitFlags8 flags; flags.set(KEK_FLAG | SOME_F); // установить два флага if (flags.read(KEK_FLAG | SOME_F)); // проверить два флага // операция compare берёт маску по первому аргументу и сравнивает со вторым // фактически смысл такой: определение ситуации, когда из указанных флагов подняты только определённые // здесь - из флагов KEK_FLAG и SOME_F поднят только SOME_F (KEK_FLAG опущен) if (flags.compare(KEK_FLAG | SOME_F, SOME_F)); ``` -------------------------------- ### BitPackDyn Constructor and Init Method Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Constructs or initializes a BitPackDyn object, specifying the total number of flags. This method is used for dynamically allocating the buffer for flags. ```cpp BitPackDyn() {} // указать количество флагов BitPackDyn(uint16_t amount); // указать количество флагов void init(uint16_t amount); ``` -------------------------------- ### Initialize BitPack with Dynamic Allocation Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Use BitPackDyn(N) for dynamic memory allocation, where N is the number of flags. This is useful when the number of flags is determined at runtime. ```cpp BitPackDyn pack(10); // динамическое выделение ``` -------------------------------- ### BitPackDyn Specific Methods Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Methods specific to the BitPackDyn class for dynamic initialization. ```APIDOC ## BitPackDyn Specific Methods ### Description Methods for initializing and setting the number of flags for `BitPackDyn`. ### Method Constructor and `init` ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp BitPackDyn() {} // Constructor: Initialize with the desired number of flags BitPackDyn(uint16_t amount); // Method: Initialize or re-initialize with a new number of flags void init(uint16_t amount); ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Using BitFlags8/16/32 for Fixed-Size Flags Source: https://context7.com/gyverlibs/bitpack/llms.txt Demonstrates setting, checking, and clearing flags using BitFlags classes. Supports defining flags with #define or enum. Use this for managing multiple boolean states efficiently. ```cpp #include // Определение флагов как битовых масок #define FLAG_ACTIVE bit(0) // 0b00000001 #define FLAG_ENABLED bit(1) // 0b00000010 #define FLAG_VISIBLE bit(2) // 0b00000100 #define FLAG_SELECTED bit(3) // 0b00001000 // Альтернативный способ - через enum enum class State : uint8_t { Ready = bit(0), Running = bit(1), Paused = bit(2), Stopped = bit(3), }; BitFlags8 flags; BitFlags16 flags16; BitFlags32 flags32; void setup() { Serial.begin(9600); // Установка одного флага flags.set(FLAG_ACTIVE); Serial.print("ACTIVE установлен: "); Serial.println(flags.isSet(FLAG_ACTIVE)); // Выведет: 1 // Установка нескольких флагов одновременно flags.set(FLAG_ENABLED | FLAG_VISIBLE); // Проверка - установлен ли хотя бы один из флагов Serial.print("Хотя бы один (ENABLED|VISIBLE): "); Serial.println(flags.read(FLAG_ENABLED | FLAG_VISIBLE) != 0); // Выведет: 1 // Проверка - установлены ли ВСЕ указанные флаги Serial.print("Все (ENABLED и VISIBLE): "); Serial.println(flags.isSet(FLAG_ENABLED | FLAG_VISIBLE)); // Выведет: 1 Serial.print("Все (ENABLED и SELECTED): "); Serial.println(flags.isSet(FLAG_ENABLED | FLAG_SELECTED)); // Выведет: 0 // Очистка флагов flags.clear(FLAG_VISIBLE); Serial.print("VISIBLE после clear: "); Serial.println(flags.isSet(FLAG_VISIBLE)); // Выведет: 0 // Проверка - очищены ли флаги Serial.print("SELECTED очищен: "); Serial.println(flags.isClear(FLAG_SELECTED)); // Выведет: 1 // Сравнение - из указанных флагов подняты только определённые // compare(маска, ожидаемое_значение) flags.set(FLAG_ACTIVE | FLAG_ENABLED); flags.clear(FLAG_VISIBLE | FLAG_SELECTED); // Проверяем: из флагов ACTIVE и ENABLED оба установлены Serial.print("compare(ACTIVE|ENABLED, ACTIVE|ENABLED): "); Serial.println(flags.compare(FLAG_ACTIVE | FLAG_ENABLED, FLAG_ACTIVE | FLAG_ENABLED)); // Выведет: 1 // Проверяем: из флагов ACTIVE и VISIBLE установлен только ACTIVE Serial.print("compare(ACTIVE|VISIBLE, ACTIVE): "); Serial.println(flags.compare(FLAG_ACTIVE | FLAG_VISIBLE, FLAG_ACTIVE)); // Выведет: 1 // Работа с enum BitFlags8 state; state.set(static_cast(State::Ready)); state.set(static_cast(State::Running)); Serial.print("State Ready: "); Serial.println(state.isSet(static_cast(State::Ready))); // Выведет: 1 // Прямой доступ к значению флагов Serial.print("Все флаги (raw): "); Serial.println(flags.flags, BIN); // Выведет: 00000011 } void loop() {} ``` -------------------------------- ### BitPackExt Constructor and SetBuffer Method Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Constructs or initializes a BitPackExt object with an external buffer. Requires a pointer to the buffer, the total number of flags, and an optional flag to clear the buffer on initialization. ```cpp BitPackExt() {} // передать буфер и его размер в количестве флагов (8 флагов - 1 байт) BitPackExt(uint8_t* pack, uint16_t amount, bool clear = true); // передать буфер и его размер в количестве флагов (8 флагов - 1 байт) void setBuffer(uint8_t* pack, uint16_t amount, bool clear = true); ``` -------------------------------- ### BitPack Macros Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Provides macro versions (BP_SET, BP_CLEAR, BP_READ, BP_TOGGLE, BP_WRITE) for potentially faster bit manipulation, taking the pack instance and index as arguments. ```cpp // макросы BP_SET(pack, idx) BP_CLEAR(pack, idx) BP_READ(pack, idx) BP_TOGGLE(pack, idx) BP_WRITE(pack, idx) ``` -------------------------------- ### Direct Buffer Manipulation with BitPack Macros Source: https://context7.com/gyverlibs/bitpack/llms.txt Utilize macros like BP_SET, BP_READ, BP_CLEAR, BP_TOGGLE, and BP_WRITE for high-speed bit manipulation directly on a byte buffer. This method bypasses object creation but requires manual boundary checks. ```cpp #include // Внешний буфер: 2 байта = 16 флагов uint8_t buffer[2] = {0, 0}; void setup() { Serial.begin(9600); // Установка битов BP_SET(buffer, 0); // Установить бит 0 BP_SET(buffer, 5); // Установить бит 5 BP_SET(buffer, 12); // Установить бит 12 // Чтение битов Serial.print("Бит 0: "); Serial.println(BP_READ(buffer, 0)); // Выведет: 1 Serial.print("Бит 1: "); Serial.println(BP_READ(buffer, 1)); // Выведет: 0 Serial.print("Бит 5: "); Serial.println(BP_READ(buffer, 5)); // Выведет: 1 Serial.print("Бит 12: "); Serial.println(BP_READ(buffer, 12)); // Выведет: 1 // Сброс битов BP_CLEAR(buffer, 5); // Сбросить бит 5 Serial.print("Бит 5 после clear: "); Serial.println(BP_READ(buffer, 5)); // Выведет: 0 // Переключение битов BP_TOGGLE(buffer, 0); // Переключить бит 0 Serial.print("Бит 0 после toggle: "); Serial.println(BP_READ(buffer, 0)); // Выведет: 0 // Запись значения BP_WRITE(buffer, 3, 1); // Установить бит 3 в 1 BP_WRITE(buffer, 3, 0); // Установить бит 3 в 0 // Вывод содержимого буфера Serial.print("Буфер[0]: "); Serial.println(buffer[0], BIN); Serial.print("Буфер[1]: "); Serial.println(buffer[1], BIN); } void loop() {} ``` -------------------------------- ### BitPack Usage Methods Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Details the core methods for manipulating bit flags within a BitPack object. ```APIDOC ## BitPack Usage Methods ### Description Provides methods to set, clear, toggle, read, and manage bit flags within the BitPack. ### Method Various member functions ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp // Methods void set(uint16_t num); // Set a specific flag void clear(uint16_t num); // Clear a specific flag void toggle(uint16_t num); // Toggle a specific flag void write(uint16_t num, bool state); // Write a specific flag's state bool read(uint16_t num); // Read a specific flag's state void setAll(); // Set all flags void clearAll(); // Clear all flags bool copyTo(BitPack& other); // Copy flags to another BitPack bool copyFrom(const BitPack& other); // Copy flags from another BitPack uint16_t amount(); // Get the total number of flags uint16_t size(); // Get the size of the pack in bytes // Direct buffer access (use with caution) uint8_t* pack; // Macros for convenience BP_SET(pack, idx) BP_CLEAR(pack, idx) BP_READ(pack, idx) BP_TOGGLE(pack, idx) BP_WRITE(pack, idx) ``` ### Response N/A (Methods return values or modify state) ### Response Example N/A ``` -------------------------------- ### Copy Bit Arrays with BitPack Source: https://context7.com/gyverlibs/bitpack/llms.txt Use copyTo and copyFrom methods to duplicate bit array contents between BitPack objects of the same size. Returns true on success, false if sizes mismatch. Direct assignment with '=' is not supported. ```cpp #include BitPack<10> source; BitPack<10> destination; BitPack<8> wrongSize; void setup() { Serial.begin(9600); // Заполняем исходный массив source.set(0); source.set(3); source.set(7); source.set(9); Serial.println("До копирования:"); Serial.print("source[0]: "); Serial.println(source.read(0)); // Выведет: 1 Serial.print("destination[0]: "); Serial.println(destination.read(0)); // Выведет: 0 // Копирование из source в destination bool success = source.copyTo(destination); Serial.print("Копирование успешно: "); Serial.println(success); // Выведет: 1 Serial.println("После копирования:"); Serial.print("destination[0]: "); Serial.println(destination.read(0)); // Выведет: 1 Serial.print("destination[3]: "); Serial.println(destination.read(3)); // Выведет: 1 Serial.print("destination[7]: "); Serial.println(destination.read(7)); // Выведет: 1 // Попытка копирования в массив другого размера bool wrongCopy = source.copyTo(wrongSize); Serial.print("Копирование в другой размер: "); Serial.println(wrongCopy); // Выведет: 0 (ошибка) // Альтернативный метод - copyFrom BitPack<10> another; another.copyFrom(source); // Копировать source в another Serial.print("another[9]: "); Serial.println(another.read(9)); // Выведет: 1 } void loop() {} ``` -------------------------------- ### BitPackExt Specific Methods Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Methods specific to the BitPackExt class for managing external buffers. ```APIDOC ## BitPackExt Specific Methods ### Description Methods for initializing and setting the buffer for `BitPackExt`. ### Method Constructor and `setBuffer` ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp BitPackExt() {} // Constructor: Initialize with a buffer and its size in flags BitPackExt(uint8_t* pack, uint16_t amount, bool clear = true); // Method: Set or re-set the external buffer void setBuffer(uint8_t* pack, uint16_t amount, bool clear = true); ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### BitPack Array Access Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Explains the array-like access operator `[]` for BitPack and its performance implications. ```APIDOC ## BitPack Array Access ### Description Provides convenient access to individual flags using the `[]` operator, similar to array access. Note that this method is slightly slower than using dedicated functions like `set()` or `read()`. ### Method Array subscript operator `[]` ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp BitPack<10> flags; flags[0] = 1; // Set flag at index 0 Serial.println(flags[0]); // Read flag at index 0 bool f = flags[0]; // Assign flag state to a boolean variable BitPack<10> flags2; flags[0] = flags2[0]; // Copy flag state from one pack to another // Note: Direct assignment like 'flags = flags2;' is incorrect for BitPack objects. // Use copyTo() and copyFrom() for copying entire packs. flags.copyTo(flags2); // Copy all flags from flags to flags2 ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### BitPack Configuration: Disable Array Access Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Define BP_NO_ARRAY before including the library to remove the array-like access operator ([]), saving approximately 2 bytes of RAM. ```cpp // настройки (до подключения библиотеки) #define BP_NO_ARRAY // убрать доступ через [] - экономит 2 байта RAM ``` -------------------------------- ### Access Bits Using Array Operator [] in BitPack Source: https://context7.com/gyverlibs/bitpack/llms.txt Utilizes the overloaded array operator `[]` for convenient and readable bit access, similar to array indexing. This method is slightly slower than `set`/`read`/`write` functions. Define `BP_NO_ARRAY` before including the library to disable this feature and save 2 bytes of RAM. ```cpp #include BitPack<16> flags; void setup() { Serial.begin(9600); // Запись через [] flags[0] = 1; // Установить флаг 0 flags[1] = 1; // Установить флаг 1 flags[2] = 0; // Сбросить флаг 2 (уже 0 по умолчанию) flags[5] = 1; // Установить флаг 5 // Чтение через [] Serial.print("Флаг 0: "); Serial.println(flags[0]); // Выведет: 1 Serial.print("Флаг 1: "); Serial.println(flags[1]); // Выведет: 1 Serial.print("Флаг 2: "); Serial.println(flags[2]); // Выведет: 0 Serial.print("Флаг 5: "); Serial.println(flags[5]); // Выведет: 1 // Присваивание в bool переменную bool myFlag = flags[0]; Serial.print("myFlag: "); Serial.println(myFlag); // Выведет: 1 // Копирование битов между массивами BitPack<16> flags2; flags2[0] = flags[5]; // Копировать бит 5 из flags в бит 0 flags2 Serial.print("flags2[0]: "); Serial.println(flags2[0]); // Выведет: 1 // Использование в условиях if (flags[0]) { Serial.println("Флаг 0 установлен!"); } // Инверсия через [] и toggle() flags[0] = !flags[0]; // Инвертировать флаг 0 Serial.print("Флаг 0 после инверсии: "); Serial.println(flags[0]); // Выведет: 0 } void loop() {} ``` -------------------------------- ### BitFlags Class Methods Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Methods for manipulating flags using masks: set, clear, write, writeBits, read, isSet, isClear, compare. These methods allow for operating on multiple flags simultaneously. ```cpp // пакет флагов T flags{}; // установить биты маской void set(const T mask); // очистить биты маской void clear(const T mask); // записать биты маской void write(const T mask, const bool val); // записать биты по маске void writeBits(const T mask, const T bits); // прочитать маской T read(const T mask); // стоят все биты в маске bool isSet(const T mask); // очищены все биты в маске bool isClear(const T mask); // сравнить маску со значением bool compare(const T mask, const T val); ``` -------------------------------- ### BitPack Array Access Operator Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Provides array-like access (e.g., `flags[0]`) to individual bits. Note that this method is slightly slower than using the dedicated set/read/write functions. Direct assignment between different BitPack instances using '=' is incorrect; use copyTo/copyFrom instead. ```cpp BitPack<10> flags; flags[0] = 1; Serial.println(flags[0]); bool f = flags[0]; BitPack<10> flags2; flags[0] = flags2[0]; // примечание: // такое приравнивание некорректно! Используй copyTo/copyFrom flags = flags2; flags.copyTo(flags2); // копировать весь пакет ``` -------------------------------- ### Using writeBits to Modify Specific Flags Source: https://context7.com/gyverlibs/bitpack/llms.txt The `writeBits()` method allows modifying a group of flags defined by a mask without affecting other flags. Useful for updating related states atomically. Ensure the mask correctly identifies the bits to be changed. ```cpp #include // Флаги состояния #define STATUS_ERROR bit(0) #define STATUS_WARNING bit(1) #define STATUS_OK bit(2) #define STATUS_MASK (STATUS_ERROR | STATUS_WARNING | STATUS_OK) // Флаги режима (независимые от статуса) #define MODE_DEBUG bit(3) #define MODE_VERBOSE bit(4) BitFlags8 deviceState; void setup() { Serial.begin(9600); // Начальное состояние deviceState.set(MODE_DEBUG | MODE_VERBOSE); // Включаем режимы deviceState.set(STATUS_OK); // Статус OK Serial.print("Начальное состояние: "); Serial.println(deviceState.flags, BIN); // Выведет: 00011100 // Изменяем только статусные биты на ERROR, не трогая режимы deviceState.writeBits(STATUS_MASK, STATUS_ERROR); Serial.print("После writeBits на ERROR: "); Serial.println(deviceState.flags, BIN); // Выведет: 00011001 // Проверяем что режимы сохранились Serial.print("MODE_DEBUG сохранился: "); Serial.println(deviceState.isSet(MODE_DEBUG)); // Выведет: 1 Serial.print("MODE_VERBOSE сохранился: "); Serial.println(deviceState.isSet(MODE_VERBOSE)); // Выведет: 1 // Проверяем новый статус Serial.print("STATUS_ERROR: "); Serial.println(deviceState.isSet(STATUS_ERROR)); // Выведет: 1 Serial.print("STATUS_OK: "); Serial.println(deviceState.isSet(STATUS_OK)); // Выведет: 0 // Устанавливаем комбинацию ERROR + WARNING deviceState.writeBits(STATUS_MASK, STATUS_ERROR | STATUS_WARNING); Serial.print("После ERROR|WARNING: "); Serial.println(deviceState.flags, BIN); // Выведет: 00011011 } void loop() {} ``` -------------------------------- ### BitFlags Class Source: https://github.com/gyverlibs/bitpack/blob/main/README.md Details the BitFlags class and its variants (BitFlags8, BitFlags16, BitFlags32) for mask-based bit manipulation. ```APIDOC ## BitFlags Class ### Description The `BitFlags` class and its specialized versions (`BitFlags8`, `BitFlags16`, `BitFlags32`) provide efficient ways to manipulate groups of flags using bitmasks. They operate like registers, allowing multiple flags to be set, cleared, or read in a single operation. ### Method Various member functions for mask operations ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```cpp // Generic BitFlags template T flags{}; // Methods void set(const T mask); // Set bits specified by the mask void clear(const T mask); // Clear bits specified by the mask void write(const T mask, const bool val); // Write a state (true/false) to bits specified by the mask void writeBits(const T mask, const T bits); // Write specific bit values to the mask T read(const T mask); // Read the state of bits specified by the mask bool isSet(const T mask); // Check if all bits in the mask are set bool isClear(const T mask); // Check if all bits in the mask are clear bool compare(const T mask, const T val); // Compare bits specified by mask with a value // Example using BitFlags8 with defined bits BitFlags8 flags; #define MY_FLAG_0 bit(0) #define KEK_FLAG bit(1) #define SOME_F bit(2) flags.set(KEK_FLAG | SOME_F); // Set KEK_FLAG and SOME_F if (flags.read(KEK_FLAG | SOME_F)) { /* ... */ } // The compare method checks if, within the specified mask, only the bits in 'val' are set. // Example: Check if KEK_FLAG is off and SOME_F is on. if (flags.compare(KEK_FLAG | SOME_F, SOME_F)); ``` ### Response N/A ### Response Example N/A ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.