### Platform-Specific Build Configuration Example Source: https://deepwiki.com/gin66/FastAccelStepper/4 Shows examples of platform-specific build configurations, including GitHub Actions workflows for ESP32 IDF projects and Arduino sketch includes for specific FastAccelStepper implementations. ```yaml # .github/workflows/build_examples_esp_idf_project.yml name: Build ESP-IDF Examples on: push: branches: [ main ] pull_request: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Set up ESP-IDF uses: espressif/setup-esp-idf@v3 with: esp_idf_version: 'release/v4.4' - name: Build Example run: | cd examples/ESP32_IDF_Example idf.py build ``` ```c++ // examples/UsageExample/UsageExample.ino #include #include // Include platform-specific implementations if needed // #include // #include FastAccelStepper stepper; ``` -------------------------------- ### PlatformIO Configuration for FastAccelStepper Source: https://deepwiki.com/gin66/FastAccelStepper/1 Example PlatformIO configurations for ESP32 and ATmega328 boards, specifying platform, board, framework, and build flags. These configurations are essential for compiling the library on different development environments. ```ini [env:esp32] platform = espressif32 board = esp32dev framework = arduino build_flags = -Wall board_build.f_cpu = 240000000L [env:nanoatmega328] platform = atmelavr board = nanoatmega328 framework = arduino build_flags = -Werror -Wall ``` -------------------------------- ### Install FastAccelStepper with PlatformIO Source: https://deepwiki.com/gin66/FastAccelStepper/1 This snippet shows how to add the FastAccelStepper library to a PlatformIO project by specifying it in the `platformio.ini` file. This method is suitable for advanced build configurations and multi-platform projects. ```ini [env:your_board] lib_deps = gin66/FastAccelStepper ``` -------------------------------- ### Typical FastAccelStepper API Usage Flow Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Illustrates the standard sequence of operations when using the FastAccelStepper library, from initialization to movement commands. This provides a practical guide for developers. ```cpp // 1. Initialize the engine FastAccelStepperEngine::init(); // 2. Create a stepper instance // For example, connect to pin 2 FastStepper* stepper = stepperConnectToPin(2); // 3. Configure stepper properties (optional but recommended) stepper->setAcceleration(500); stepper->setSpeedInHz(2000); // 4. Perform a movement // Move 1000 steps forward, blocking until completion stepper->move(1000, true); // 5. Query status (optional) if (stepper->isRunning()) { // Motor is still moving } else { // Motor has stopped } ``` -------------------------------- ### Basic Stepper Initialization and Movement (C++) Source: https://deepwiki.com/gin66/FastAccelStepper/1-home Demonstrates the fundamental steps to initialize the FastAccelStepper engine, connect a stepper motor to pins, configure speed and acceleration, and issue a basic movement command. This example assumes pre-defined pin variables `stepPinStepper` and `dirPinStepper`. ```cpp FastAccelStepperEngine engine = FastAccelStepperEngine(); FastAccelStepper *stepper = NULL; void setup() { engine.init(); stepper = engine.stepperConnectToPin(stepPinStepper); stepper->setDirectionPin(dirPinStepper); stepper->setSpeedInHz(500); stepper->setAcceleration(100); stepper->moveTo(1000); } ``` -------------------------------- ### ESP32 Driver Selection Example Source: https://deepwiki.com/gin66/FastAccelStepper/4 Demonstrates how to select the hardware-accelerated driver for ESP32 using stepperConnectToPin() with an optional FasDriver parameter. This allows runtime selection of different hardware drivers. ```cpp Stepper.connectToPin(STEP_PIN, DIR_PIN, ENABLE_PIN); // Or with driver selection: Stepper.connectToPin(STEP_PIN, DIR_PIN, ENABLE_PIN, FasDriver::ESP32_RMT); // Or: Stepper.connectToPin(STEP_PIN, DIR_PIN, ENABLE_PIN, FasDriver::ESP32_MCPWM); // Or: Stepper.connectToPin(STEP_PIN, DIR_PIN, ENABLE_PIN, FasDriver::ESP32_PCNT); ``` -------------------------------- ### Low-Level Queue Access with FastAccelStepper (C++) Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Provides advanced control over stepper motor movement by directly manipulating the command queue using the FastAccelStepper library. This allows for custom motion profiles and precise timing. The example demonstrates building a variable speed profile and executing synchronized starts for multiple motors. ```cpp #include FastAccelStepper *stepper = engine.stepperConnectToPin(9); void rawQueueAccess() { stepper->setDirectionPin(8); stepper->setAutoEnable(true); // Disable high-level motion control for raw access stepper->setForwardPlanningTimeInMs(0); // Build custom step sequence with precise timing // Each queue entry specifies: ticks per step, number of steps, flags // Example: Variable speed profile (acceleration simulation) uint32_t speeds[] = {500, 400, 300, 250, 200, 180, 160, 150}; // ticks per step for (int i = 0; i < 8; i++) { struct stepper_command_s cmd; cmd.ticks = speeds[i]; cmd.steps = 100; // 100 steps at each speed level cmd.count_up = true; // Direction: forward int8_t result = stepper->addQueueEntry(&cmd); if (result != AQE_OK) { Serial.print("Queue error: "); Serial.println(result); break; } } // Wait for queue to empty while (stepper->queueEntries() > 0) { delay(1); } // Re-enable high-level control stepper->setForwardPlanningTimeInMs(10); } void synchronizedStart() { FastAccelStepper *motor1 = engine.stepperConnectToPin(9); FastAccelStepper *motor2 = engine.stepperConnectToPin(10); // Prepare commands with start flag struct stepper_command_s cmd1, cmd2; cmd1.ticks = 200; cmd1.steps = 1000; cmd1.count_up = true; cmd2.ticks = 200; cmd2.steps = 1000; cmd2.count_up = true; // Add commands but don't start yet (using start flag mechanism) motor1->addQueueEntry(&cmd1, true); // true = apply start flag motor2->addQueueEntry(&cmd2, true); // Both motors start on next interrupt cycle (within microseconds) Serial.println("Synchronized start executed"); } ``` -------------------------------- ### FastAccelStepper Library Properties Source: https://deepwiki.com/gin66/FastAccelStepper/1 This JSON snippet displays the properties of the FastAccelStepper library as defined in its `library.properties` file. It includes the library name, version, supported architectures, and category, which are crucial for library managers like the Arduino IDE. ```json { "name": "FastAccelStepper", "version": "0.33.4", "architectures": [ "avr", "esp32", "sam", "rp2040", "rp2350" ], "category": "Device Control" } ``` -------------------------------- ### Example Stepper Demo Commands for ESP32 Source: https://deepwiki.com/gin66/FastAccelStepper/5 Demonstrates a pulse counter test sequence using StepperDemo command syntax for configuring and controlling the stepper motor. Includes parameters for pulse counter range, velocity, acceleration, and movement commands. ```shell # Pulse counter test with range limits M1 p7,-32767,32767 V40 A1000 R54 W R-54 W # Expected response pattern >> M1: @0 [0] ``` -------------------------------- ### AVR Timer Module Configuration Source: https://deepwiki.com/gin66/FastAccelStepper/1 Configuration for selecting the timer module on ATmega2560 using a preprocessor definition. This is relevant for PlatformIO users needing to specify timer module overrides. ```c++ build_flags = -DFAS_TIMER_MODULE=3 ``` -------------------------------- ### Configure Platform-Specific Pins for FastAccelStepper Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt This code snippet demonstrates how to configure stepper motor pins based on the target platform (AVR, ESP32, RP2040). It initializes the FastAccelStepper engine and connects to specific pins, handling platform limitations and capabilities for step output. The common configuration for direction and acceleration is applied after platform-specific setup. ```cpp FastAccelStepperEngine engine = FastAccelStepperEngine(); void platformSpecificSetup() { engine.init(); #if defined(ARDUINO_ARCH_AVR) // AVR: Limited to specific timer pins // ATmega328P: pins 9, 10 only (Timer1) // ATmega2560: pins 6, 7, 8 only (Timer4) FastAccelStepper *stepper = engine.stepperConnectToPin(9); Serial.println("AVR platform - using Timer1"); #elif defined(ARDUINO_ARCH_ESP32) // ESP32: Any GPIO can be used for step output FastAccelStepper *stepper = engine.stepperConnectToPin(25); Serial.println("ESP32 platform - using RMT or MCPWM"); // ESP32 supports higher speeds stepper->setSpeedInHz(50000); // Up to 200kHz possible #elif defined(ARDUINO_ARCH_RP2040) // RP2040: Any GPIO 0-31, uses PIO state machines FastAccelStepper *stepper = engine.stepperConnectToPin(16); Serial.println("RP2040 platform - using PIO"); #else FastAccelStepper *stepper = engine.stepperConnectToPin(9); Serial.println("Generic platform"); #endif // Common configuration works across all platforms stepper->setDirectionPin(8); stepper->setAcceleration(1000); stepper->move(5000); } ``` -------------------------------- ### ESP-IDF Common Header Configuration (IDF 5.3+) Source: https://deepwiki.com/gin66/FastAccelStepper/1 This C++ header configuration file (`common_esp32_idf5.h`) shows the definition for ESP32 platform compatibility with ESP-IDF version 5.3 and above. It specifies the number of steppers and hardware modules that can be utilized, reflecting changes in driver support compared to older ESP-IDF versions. ```cpp #define FAS_ESP32_IDF5_STEPS_RMT 8 #define FAS_ESP32_IDF5_STEPS_MCPWM 0 #define FAS_ESP32_IDF5_STEPS_PCNT 0 #define FAS_ESP32_IDF5_QUEUE_DEPTH 32 ``` -------------------------------- ### Continuous Stepper Movement Control Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Starts continuous movement of the stepper motor either forward or backward. Returns a MoveResultCode indicating the outcome of initiating the continuous run. ```cpp runForward(); runBackward(); ``` -------------------------------- ### Multi-Axis Synchronization with FastAccelStepper (C++) Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Synchronizes the movement of multiple stepper motors (X, Y, Z) using the FastAccelStepper library. It configures identical speed and acceleration for all axes and executes coordinated moves. The code includes a basic example of circular motion simulation. ```cpp FastAccelStepperEngine engine = FastAccelStepperEngine(); FastAccelStepper *stepperX = NULL; FastAccelStepper *stepperY = NULL; FastAccelStepper *stepperZ = NULL; void setup() { engine.init(); // Initialize three-axis system stepperX = engine.stepperConnectToPin(9); stepperY = engine.stepperConnectToPin(10); stepperZ = engine.stepperConnectToPin(11); // Configure all axes with same speed/acceleration FastAccelStepper* axes[] = {stepperX, stepperY, stepperZ}; for (int i = 0; i < 3; i++) { axes[i]->setDirectionPin(5 + i); axes[i]->setSpeedInHz(5000); axes[i]->setAcceleration(2000); } // Coordinated move - issue commands sequentially // Motors start nearly simultaneously due to interrupt timing stepperX->move(10000); stepperY->move(8000); stepperZ->move(5000); // Wait for all axes to complete while (stepperX->isRunning() || stepperY->isRunning() || stepperZ->isRunning()) { Serial.print("X:"); Serial.print(stepperX->getCurrentPosition()); Serial.print(" Y:"); Serial.print(stepperY->getCurrentPosition()); Serial.print(" Z:"); Serial.println(stepperZ->getCurrentPosition()); delay(100); } Serial.println("Coordinated move complete"); } void loop() { // Circular motion example (approximate circle) for (int angle = 0; angle < 360; angle += 10) { float rad = angle * 3.14159 / 180.0; int32_t x = (int32_t)(1000.0 * cos(rad)); int32_t y = (int32_t)(1000.0 * sin(rad)); stepperX->moveTo(x); stepperY->moveTo(y); while (stepperX->isRunning() || stepperY->isRunning()) { delay(1); } } delay(1000); } ``` -------------------------------- ### External Pin Control Callback Example Source: https://deepwiki.com/gin66/FastAccelStepper/4 Illustrates the use of callback functions for controlling pins via external hardware like shift registers or I/O expanders. The callback must execute within the 4ms stepper task cycle to prevent queue underruns. ```cpp // Define external pin control functions void setExtStepPin(const bool HIGH) { // Implementation to control step pin via external hardware } void setExtDirPin(const bool HIGH) { // Implementation to control direction pin via external hardware } // Assign callbacks stepper.setExtPins(setExtStepPin, setExtDirPin); ``` -------------------------------- ### Get Queued Execution Time Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Calculates and returns the total time (in ticks) that the queued commands will take to execute. Useful for estimating future motor state. Returns a uint32_t. ```cpp ticksInQueue(); ``` -------------------------------- ### Get Current Stepper Position Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Retrieves the current position of the stepper motor in steps. This is useful for tracking the motor's state. Returns an int32_t representing the position. ```cpp getCurrentPosition(); ``` -------------------------------- ### Get Command Queue Fill Level Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Returns the current number of commands queued for execution by the stepper motor controller. This helps in managing the command flow. Returns a uint8_t. ```cpp queueEntries(); ``` -------------------------------- ### Get Current Stepper Speed Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Retrieves the current speed of the stepper motor in microseconds per step. The 'realtime' parameter may affect how the speed is calculated. Returns an int32_t. ```cpp getCurrentSpeedInUs(realtime); ``` -------------------------------- ### Set Stepper Speed (mHz) Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Sets the stepper motor's speed in milliHertz (steps per 1000 seconds). This unit is suitable for controlling very slow movements. The range starts from 1000+. Returns void. ```cpp setSpeedInMilliHz(uint32_t mhz); ``` -------------------------------- ### Control Stepper Pins Externally with Shift Registers Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt This C++ code demonstrates how to control stepper motor driver pins (step, direction, enable) using an external shift register. It defines pins for the shift register and a callback function `externalPinCallback` that maps stepper control pins to specific bits in the shift register's state. This callback is registered with the FastAccelStepper engine, allowing the library to control the pins via the shift register instead of direct `digitalWrite` calls. The setup initializes the shift register pins and registers the callback before connecting the stepper. ```cpp // Shift register configuration const int SHIFT_DATA = 2; const int SHIFT_CLOCK = 3; const int SHIFT_LATCH = 4; uint8_t shiftRegisterState = 0; // Callback function for external pin control void externalPinCallback(uint8_t pin, uint8_t value) { // Map stepper control pins to shift register bits if (pin == 9) { // Step pin if (value) { shiftRegisterState |= (1 << 0); } else { shiftRegisterState &= ~(1 << 0); } } else if (pin == 8) { // Direction pin if (value) { shiftRegisterState |= (1 << 1); } else { shiftRegisterState &= ~(1 << 1); } } else if (pin == 7) { // Enable pin if (value) { shiftRegisterState |= (1 << 2); } else { shiftRegisterState &= ~(1 << 2); } } // Update shift register digitalWrite(SHIFT_LATCH, LOW); shiftOut(SHIFT_DATA, SHIFT_CLOCK, MSBFIRST, shiftRegisterState); digitalWrite(SHIFT_LATCH, HIGH); } void setup() { pinMode(SHIFT_DATA, OUTPUT); pinMode(SHIFT_CLOCK, OUTPUT); pinMode(SHIFT_LATCH, OUTPUT); engine.init(); // Register external pin callback before connecting stepper engine.setExternalCallForPin(externalPinCallback); // Now connect stepper - library will use callback instead of digitalWrite FastAccelStepper *stepper = engine.stepperConnectToPin(9); stepper->setDirectionPin(8); stepper->setEnablePin(7); // Normal operation - library calls externalPinCallback for all pin changes stepper->setSpeedInHz(2000); stepper->setAcceleration(1000); stepper->move(5000); } ``` -------------------------------- ### GitHub Actions CI/CD Pipeline for FastAccelStepper Source: https://deepwiki.com/gin66/FastAccelStepper/5-development-and-testing This snippet represents the GitHub Actions workflow configuration for the FastAccelStepper CI/CD pipeline. It automates testing across a matrix of supported platforms and framework versions, ensuring code compatibility and stability. ```yaml # Continuous Integration Pipeline # Uses GitHub Actions to automatically test code changes across the supported platform matrix. # The pipeline is split into parallel workflows for optimized build times and granular failure isolation. ``` -------------------------------- ### PlatformIO Build Configuration for FastAccelStepper Source: https://deepwiki.com/gin66/FastAccelStepper/5-development-and-testing This snippet shows the PlatformIO configuration file used to manage cross-platform compilation and testing for the FastAccelStepper library. It defines environments for various microcontroller architectures and framework versions, enabling extensive testing. ```ini ; Build System Architecture ; This file configures PlatformIO for cross-platform compilation and testing. ; It supports over 80 different platform/version combinations. ``` -------------------------------- ### ESP32 Build Commands for FastAccelStepper Source: https://deepwiki.com/gin66/FastAccelStepper/5 Commands to build and upload FastAccelStepper firmware for different ESP32 configurations and ESP-IDF versions using PlatformIO. These commands are essential for deploying the test firmware onto ESP32 hardware. ```shell pio run -e esp32_V6_8_1 pio run -e esp32_idf_V5_3_0 pio run -e esp32_idf_V6_8_1 ``` -------------------------------- ### Platform-Specific Build Configuration Source: https://deepwiki.com/gin66/FastAccelStepper/4 Information on how the library adapts to different build environments and frameworks for specific platforms. ```APIDOC ## Platform-Specific Build Configuration ### Description Details how the FastAccelStepper library adapts its build configuration for various platforms and build environments. ### Usage Notes Refer to the `.github/workflows/` directory for CI/CD configurations and `examples/` for platform-specific build setups. ``` -------------------------------- ### Makefile for FastAccelStepper ESP32 Hardware Tests Source: https://deepwiki.com/gin66/FastAccelStepper/5 Makefile targets for orchestrating the ESP32 hardware testing process for FastAccelStepper. It includes commands for running all tests, compiling firmware, and cleaning test artifacts. ```makefile # Run all tests for motors M1 and M7 make test # Compile and upload firmware make compile # Clean test artifacts make clean ``` -------------------------------- ### Basic Motion Control with FastAccelStepper Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Illustrates basic stepper motor control including setting direction, enable pins, speed, and acceleration. It shows how to execute relative and absolute movements and monitor the motor's position and running status. Auto-enable functionality is also demonstrated. ```cpp FastAccelStepperEngine engine = FastAccelStepperEngine(); FastAccelStepper *stepper = NULL; void setup() { Serial.begin(115200); engine.init(); stepper = engine.stepperConnectToPin(9); // Configure direction pin (optional, for Step+Dir mode) stepper->setDirectionPin(8); // Configure enable pin (optional, active-low in this example) stepper->setEnablePin(7, true); // true = enable is active low stepper->setAutoEnable(true); // Automatically enable/disable motor // Set motion parameters stepper->setSpeedInHz(2000); // 2000 steps/second max speed stepper->setAcceleration(1000); // 1000 steps/s² acceleration // Execute movements stepper->move(5000); // Move 5000 steps relative (non-blocking) while (stepper->isRunning()) { delay(10); } stepper->moveTo(0); // Return to position 0 (absolute positioning) while (stepper->isRunning()) { Serial.print("Position: "); Serial.println(stepper->getCurrentPosition()); delay(100); } } void loop() { // Continuous forward motion stepper->runForward(); delay(3000); // Decelerate to stop stepper->stopMove(); while (stepper->isRunning()) delay(10); delay(1000); // Continuous backward motion stepper->runBackward(); delay(3000); // Immediate stop (no deceleration) stepper->forceStop(); delay(1000); } ``` -------------------------------- ### Platform-Specific Header for ESP32 IDF 5 Source: https://deepwiki.com/gin66/FastAccelStepper/5-development-and-testing This C++ header file provides platform-specific configurations for ESP32 microcontrollers using ESP-IDF version 5. It is part of the FastAccelStepper library's strategy to maintain compatibility across different framework versions. ```c++ // Platform-Specific Implementations - ESP32 IDF 5 // Common definitions specifically for ESP32 family microcontrollers using ESP-IDF version 5. // Facilitates conditional compilation and hardware abstraction. ``` -------------------------------- ### Initialize FastAccelStepper Engine and Stepper Motors Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Demonstrates how to initialize the FastAccelStepper engine and connect stepper motor instances to specific GPIO pins. It includes error handling for invalid or used pins. The engine must be initialized before any steppers can be used. ```cpp #include FastAccelStepperEngine engine = FastAccelStepperEngine(); FastAccelStepper *stepper1 = NULL; FastAccelStepper *stepper2 = NULL; void setup() { // Initialize the engine (must be called before any steppers are used) engine.init(); // Connect steppers to specific GPIO pins // Returns NULL if pin is invalid or already in use stepper1 = engine.stepperConnectToPin(9); // AVR: pin 9 (Timer1 OC1A) stepper2 = engine.stepperConnectToPin(10); // AVR: pin 10 (Timer1 OC1B) if (stepper1 == NULL || stepper2 == NULL) { Serial.println("Failed to initialize steppers - check pin assignments"); while(1); } Serial.println("Engine initialized successfully"); } void loop() { // Engine runs in background via interrupts } ``` -------------------------------- ### ESP32 Driver Selection Logic (C++) Source: https://deepwiki.com/gin66/FastAccelStepper/3-platform-specific-implementations Demonstrates how the FastAccelStepper library routes method calls to specific hardware drivers (RMT or MCPWM/PCNT) on ESP32 platforms based on configuration. This allows for flexible use of available peripherals on different ESP32 variants. ```cpp bool StepperQueue::isReadyForCommands() { if (use_rmt) { return isReadyForCommands_rmt(); } return isReadyForCommands_mcpwm_pcnt(); } ``` -------------------------------- ### Initialize FastAccelStepper Engine Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference Initializes the stepper motor control engine. This is a prerequisite for creating and controlling stepper instances. It returns void and has no direct dependencies shown here. ```cpp FastAccelStepperEngine::init(); ``` -------------------------------- ### Platform Timing Characteristics Source: https://deepwiki.com/gin66/FastAccelStepper/4 Overview of timing characteristics for different platforms, including TICKS_PER_S, MIN_CMD_TICKS, MIN_DIR_DELAY_US, and MAX_DIR_DELAY_US. ```APIDOC ## Platform Timing Characteristics ### Description Provides timing constraints and capabilities for various platforms supported by the library. ### Data Table | Platform | TICKS_PER_S | MIN_CMD_TICKS | MIN_DIR_DELAY_US | MAX_DIR_DELAY_US | |---------------|--------------|---------------|------------------|------------------| | AVR | 16,000,000 | 640 | 40 | 4095 | | ESP32 | 16,000,000 | 3200 | 200 | 4095 | | SAM DUE | 21,000,000 | 4200 | 200 | 3120 | ### Usage Notes These values are crucial for determining the minimum achievable step rates and timing precision for each platform. ``` -------------------------------- ### FastAccelStepper API Reference Source: https://deepwiki.com/gin66/FastAccelStepper/4-api-reference This page provides comprehensive documentation for all public APIs in the FastAccelStepper library. It covers the complete interface from high-level motor control operations down to low-level command queue management. ```APIDOC ## API Reference This page provides comprehensive documentation for all public APIs in the FastAccelStepper library. It covers the complete interface from high-level motor control operations down to low-level command queue management. For implementation details of specific platforms, see Platform-Specific APIs. For advanced timing control, see MoveTimed Functionality. For direct command queue access, see Raw Access Mode. ### API Architecture Overview The FastAccelStepper library provides a layered API architecture that progresses from simple high-level motor control to sophisticated low-level command management: ## Core API Classes The API is organized around two primary classes that work together to provide stepper motor control: ## API Categories by Usage Pattern ### Engine Initialization and Stepper Creation | Function | Purpose | Returns | |--------------------------------|---------------------------------------|---------------| | `FastAccelStepperEngine::init()` | Initialize the stepper engine | `void` | | `stepperConnectToPin(uint8_t pin)` | Create stepper instance for pin | `FastAccelStepper*` | | `setExternalCallForPin(func)` | Set callback for external pins | `void` | | `setDebugLed(uint8_t pin)` | Configure debug LED | `void` | ### Configuration APIs | Function | Purpose | Returns | |----------------------------------|-------------------------------------|---------| | `setDirectionPin(pin, polarity, delay)` | Configure direction control | `void` | | `setEnablePin(pin, low_active)` | Configure enable control | `void` | | `setAutoEnable(bool enable)` | Enable automatic motor control | `void` | | `setSpeedInHz(uint32_t hz)` | Set maximum speed in Hz | `int8_t` | | `setAcceleration(int32_t accel)` | Set acceleration in steps/s² | `int8_t` | ### Movement Control APIs | Function | Purpose | Returns | |----------------------------------|------------------------|----------------| | `move(int32_t steps, bool blocking)` | Relative movement | `MoveResultCode` | | `moveTo(int32_t pos, bool blocking)` | Absolute movement | `MoveResultCode` | | `runForward()` / `runBackward()` | Continuous movement | `MoveResultCode` | | `stopMove()` | Decelerated stop | `void` | | `forceStop()` | Immediate stop | `void` | ### Status and Query APIs | Function | Purpose | Returns | |----------------------------------|-----------------------------|---------| | `getCurrentPosition()` | Get current motor position | `int32_t` | | `isRunning()` | Check if motor is moving | `bool` | | `getCurrentSpeedInUs(bool realtime)` | Get current speed | `int32_t` | | `queueEntries()` | Get queue fill level | `uint8_t` | | `ticksInQueue()` | Get queued execution time | `uint32_t` | ## Return Code Definitions The API uses several enumerated return codes to indicate operation status: ## API Usage Flow The typical sequence for using the FastAccelStepper API follows this pattern: ## Speed and Acceleration Configuration | Method | Unit | Range | Usage | |----------------------------------|-----------|-----------------------|----------------------------| | `setSpeedInUs(uint32_t us)` | µs/step | Device dependent | Precise timing | | `setSpeedInHz(uint32_t hz)` | steps/s | 1 to ~25kHz | Intuitive frequency | | `setSpeedInMilliHz(uint32_t mhz)`| steps/1000s| 1000+ | Very slow speeds | | `setSpeedInTicks(uint32_t ticks)`| ticks/step| Platform dependent | Low-level control | ``` -------------------------------- ### Platform-Specific Header for ESP32 Source: https://deepwiki.com/gin66/FastAccelStepper/5-development-and-testing This C++ header file contains platform-specific definitions and configurations for ESP32 microcontrollers within the FastAccelStepper library. It enables conditional compilation based on hardware features and framework versions. ```c++ // Platform-Specific Implementations - ESP32 // Common definitions for ESP32 family microcontrollers. // This header file is used for conditional compilation, ensuring relevant hardware drivers are included. ``` -------------------------------- ### Queue Status Monitoring with FastAccelStepper (C++) Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Demonstrates how to monitor the command queue status for a stepper motor using the FastAccelStepper library. It retrieves the number of queued commands, total time represented by queued commands, and checks if the queue has space for new commands. This is useful for performance tuning and diagnostics. ```cpp FastAccelStepper *stepper = engine.stepperConnectToPin(9); void monitorQueue() { stepper->setSpeedInHz(10000); stepper->setAcceleration(5000); stepper->move(50000); // Long move while (stepper->isRunning()) { // Get number of commands in queue (0-32 on ESP32, 0-16 on AVR) uint8_t entries = stepper->queueEntries(); // Get total time represented by queued commands (in ticks) uint32_t ticks = stepper->ticksInQueue(); // Check if queue has space for more commands bool ready = stepper->hasValidQueueEntry(); Serial.print("Queue entries: "); Serial.print(entries); Serial.print(" Ticks: "); Serial.print(ticks); Serial.print(" Ready: "); Serial.println(ready ? "YES" : "NO"); delay(10); } // Queue statistics Serial.print("Final position: "); Serial.println(stepper->getCurrentPosition()); Serial.print("Target reached: "); Serial.println(stepper->targetPos() == stepper->getCurrentPosition() ? "YES" : "NO"); } ``` -------------------------------- ### RampGenerator: Motion Planning and State Structures (C++) Source: https://deepwiki.com/gin66/FastAccelStepper/2-core-architecture The RampGenerator class implements motion planning algorithms for smooth acceleration and deceleration profiles. It translates high-level commands into timed step commands, maintaining three key data structures: _parameters for user-configured targets, _ro (read-only state) for safe application access, and _rw (read-write state) for current execution status. ```cpp #include "RampGenerator.h" // Define structures for RampGenerator state struct RampGenParameters { // Speed, acceleration, motion targets, etc. // ... }; struct RampGenReadOnlyState { // Configuration and target position data // ... }; struct RampGenReadWriteState { // Current execution state, step timings, etc. // ... }; class RampGenerator { private: RampGenParameters _parameters; RampGenReadOnlyState _ro; RampGenReadWriteState _rw; public: // Methods for generating ramp profiles and step commands // ... }; // ... (implementation details for RampGenerator methods) ``` -------------------------------- ### Platform Pin Constraints Source: https://deepwiki.com/gin66/FastAccelStepper/4 Details on pin constraints for stepper control on different platforms. ```APIDOC ## Platform Pin Constraints ### Description Highlights the varying constraints on which pins can be used for stepper control on different hardware platforms. ### Usage Notes Consult platform-specific documentation or examples for precise pin assignments and limitations. ``` -------------------------------- ### Handle Movement and Queue Errors in FastAccelStepper Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt This C++ snippet illustrates how to handle errors returned by stepper movement commands and queue operations. It configures stepper speed and acceleration, then executes a move command. A switch statement checks the result of the move operation and provides feedback or corrective actions for common errors like missing pins or undefined speed. It also demonstrates adding entries to the command queue and handling potential queue full or general error conditions. ```cpp FastAccelStepper *stepper = engine.stepperConnectToPin(9); void handleErrors() { stepper->setSpeedInHz(5000); stepper->setAcceleration(2000); // Movement commands return status codes int8_t result = stepper->move(10000); switch (result) { case MOVE_OK: Serial.println("Move command accepted"); break; case MOVE_ERR_NO_DIRECTION_PIN: Serial.println("Error: Direction pin not configured"); stepper->setDirectionPin(8); break; case MOVE_ERR_SPEED_IS_UNDEFINED: Serial.println("Error: Speed not set"); stepper->setSpeedInHz(1000); break; case MOVE_ERR_ACCELERATION_IS_UNDEFINED: Serial.println("Error: Acceleration not set"); stepper->setAcceleration(500); break; default: Serial.print("Unknown error: "); Serial.println(result); } // Queue commands return different codes struct stepper_command_s cmd; cmd.ticks = 200; cmd.steps = 100; cmd.count_up = true; int8_t queueResult = stepper->addQueueEntry(&cmd); switch (queueResult) { case AQE_OK: Serial.println("Queue entry added"); break; case AQE_FULL: Serial.println("Queue full - wait before adding more commands"); while (stepper->queueEntries() > 16) delay(1); break; case AQE_ERROR: Serial.println("Queue error - check command parameters"); break; } } ``` -------------------------------- ### Log File Analysis Patterns for Stepper Control Source: https://deepwiki.com/gin66/FastAccelStepper/5 Illustrates log file output patterns generated during stepper motor operation, indicating motor status and position. These patterns are used for automated validation of test outcomes. ```text M1: @1234 [1234] # Running motor: API position, PCNT value >> M1: @0 [0] # Stopped motor: Final position verification ``` -------------------------------- ### ESP32 Pulse Counter Integration Source: https://deepwiki.com/gin66/FastAccelStepper/4 Integrate the ESP32's Pulse Counter (PCNT) peripheral for hardware-based step counting and position feedback. ```APIDOC ## ESP32 Pulse Counter Integration ### Description Attaches the stepper to an ESP32's Pulse Counter (PCNT) unit for hardware-based step counting and position feedback. ### Methods #### ESP-IDF v5 Implementation `attachToPulseCounter(uint8_t unused_pcnt_unit = 0, int16_t low_value = -16384, int16_t high_value = 16384, uint8_t dir_pin_readback = PIN_UNDEFINED)` #### ESP-IDF v4 Implementation `attachToPulseCounter(uint8_t pcnt_unit, int16_t low_value = -16384, int16_t high_value = 16384, uint8_t dir_pin_readback = PIN_UNDEFINED)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **pcnt_unit** (uint8_t) - The PCNT unit to use (ESP-IDF v4). - **unused_pcnt_unit** (uint8_t) - Placeholder for ESP-IDF v5, typically 0. - **low_value** (int16_t) - The low threshold for the counter. - **high_value** (int16_t) - The high threshold for the counter. - **dir_pin_readback** (uint8_t) - The pin to read direction from (optional). ### Request Example ```cpp // Example usage (actual code may vary) FastAccelStepperEngine stepperEngine; FastAccelStepper *stepper = nullptr; void setup() { // ... initialization ... // For ESP-IDF v5: // stepper = stepperEngine.stepperConnectToPin(PIN_STEPPER_ENABLE); // stepper->attachToPulseCounter(0, -1000, 1000, PIN_DIR_READBACK); // For ESP-IDF v4: // stepper = stepperEngine.stepperConnectToPin(PIN_STEPPER_ENABLE); // stepper->attachToPulseCounter(PCNT_UNIT_0, -1000, 1000, PIN_DIR_READBACK); // ... } ``` ### Response #### Success Response (200) - **success** (bool) - True if the pulse counter was attached successfully, false otherwise. #### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Logarithmic Reciprocal for Efficient Division Source: https://deepwiki.com/gin66/FastAccelStepper/2 Implements an efficient reciprocal calculation using base-2 logarithms. This method allows for division by converting it into a subtraction in the logarithmic domain, significantly speeding up the process on microcontrollers. It takes a divisor as input and returns its reciprocal in logarithmic representation. ```c uint32_t log2_reciprocal(uint32_t divisor) { // Implementation details for log2_reciprocal // ... return reciprocal_log; } ``` -------------------------------- ### FastAccelStepper: Motion Control and State Variables (C++) Source: https://deepwiki.com/gin66/FastAccelStepper/2-core-architecture Each FastAccelStepper instance represents an individual stepper motor, providing the primary user interface for motion control. It integrates motion planning via RampGenerator (_rg), queue management (_queue_num), and hardware pin configurations (_stepPin, _dirPin, etc.). It manages timing parameters like acceleration profiles and direction change delays. ```cpp #include "FastAccelStepper.h" #include "RampGenerator.h" class FastAccelStepper { private: RampGenerator _rg; uint8_t _queue_num; uint8_t _stepPin; uint8_t _dirPin; bool _enablePinHighActive; bool _enablePinLowActive; uint32_t _forward_planning_in_ticks; uint32_t _dir_change_delay_ticks; uint32_t _on_delay_ticks; public: // Constructor and other methods for motion control // ... }; // ... (implementation details for FastAccelStepper methods) ``` -------------------------------- ### ESP32 Task Configuration Source: https://deepwiki.com/gin66/FastAccelStepper/4 Configure the behavior of the stepper control task on ESP32, including CPU core assignment and repetition rate. ```APIDOC ## ESP32 Task Configuration ### Description Allows fine-tuning of the stepper control task behavior on the ESP32 platform. ### Methods - `init(uint8_t cpu_core)`: Pin stepper task to a specific CPU core. - `task_rate(uint8_t delay_ms)`: Configure the stepper task repetition rate. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **cpu_core** (uint8_t) - The CPU core (0 or 1) to which the stepper task should be pinned. - **delay_ms** (uint8_t) - The delay in milliseconds between task repetitions. ### Request Example ```cpp // Example usage (actual code may vary) FastAccelStepperEngine stepperEngine; void setup() { // ... initialization ... stepperEngine.init(0); // Pin stepper task to CPU core 0 stepperEngine.task_rate(5); // Set task repetition rate to 5ms // ... } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the configuration. #### Response Example ```json { "status": "Task configuration updated" } ``` ``` -------------------------------- ### FastAccelStepperEngine: Resource Management and Pin Validation (C++) Source: https://deepwiki.com/gin66/FastAccelStepper/2-core-architecture The FastAccelStepperEngine acts as a central factory and manager for stepper motor instances. It handles resource allocation, validates pin assignments using _isValidStepPin(), and coordinates multiple steppers to prevent conflicts, including shared direction pins via isDirPinBusy(). It also supports external pin configurations through a callback mechanism. ```cpp #include "FastAccelStepper.h" #include "FastAccelStepperEngine.h" // ... (implementation details for FastAccelStepperEngine) bool FastAccelStepperEngine::_isValidStepPin(uint8_t pin) { // Implementation to validate if a step pin is hardware compatible // ... return true; // Placeholder } bool FastAccelStepperEngine::isDirPinBusy(uint8_t pin) { // Implementation to check if a direction pin is already in use by another stepper // ... return false; // Placeholder } // ... (external pin handling via _externalCallForPin callback) ``` -------------------------------- ### ESP32 Driver Type Selection Source: https://deepwiki.com/gin66/FastAccelStepper/4 ESP32 supports two hardware-accelerated drivers that can be selected at runtime using the `stepperConnectToPin()` method with an optional `FasDriver` parameter. ```APIDOC ## ESP32 Driver Type Selection ### Description Selects between different hardware-accelerated drivers on the ESP32 platform. ### Method `stepperConnectToPin()` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **FasDriver** (enum) - Optional - Specifies the driver type to use. ### Request Example ```cpp // Example usage (actual code may vary) FastAccelStepperEngine stepperEngine; FastAccelStepper *stepper = nullptr; void setup() { // ... initialization ... stepper = stepperEngine.stepperConnectToPin(PIN_STEPPER_ENABLE, FasDriver::ESP32_RMT); // or // stepper = stepperEngine.stepperConnectToPin(PIN_STEPPER_ENABLE); // ... } ``` ### Response #### Success Response (200) - **stepper** (FastAccelStepper*) - A pointer to the initialized stepper object. #### Response Example ```json { "message": "Stepper initialized successfully" } ``` ``` -------------------------------- ### Advanced Speed Configuration in FastAccelStepper Source: https://context7.com/context7/deepwiki_gin66_fastaccelstepper/llms.txt Details various methods for configuring stepper motor speed, including frequency (Hz), microseconds per step, milliHertz, and platform-specific ticks. It also covers setting acceleration and linear acceleration, and querying the current speed in different formats. ```cpp FastAccelStepper *stepper = engine.stepperConnectToPin(9); void configureSpeed() { // Method 1: Frequency in Hz (most intuitive) int8_t result = stepper->setSpeedInHz(5000); // 5000 steps/second if (result != 0) { Serial.println("Speed out of range for this platform"); } // Method 2: Period in microseconds (precise timing) result = stepper->setSpeedInUs(200); // 200µs per step = 5000 Hz // Method 3: Very slow speeds using milliHz (steps per 1000 seconds) stepper->setSpeedInMilliHz(500); // 0.5 steps/second // Method 4: Platform ticks (low-level control) // Tick duration varies by platform (typically 1µs or 0.5µs) stepper->setSpeedInTicks(200); // Configure acceleration independently stepper->setAcceleration(2000); // 2000 steps/s² // Advanced: Linear acceleration for smoother motion stepper->setLinearAcceleration(1500); // Cubic speed ramp // Query current speed (real-time or calculated) int32_t currentSpeed = stepper->getCurrentSpeedInUs(true); // true = real-time Serial.print("Current speed: "); Serial.print(1000000 / currentSpeed); Serial.println(" Hz"); } ```