diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..aa5fb2c --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,21 @@ +name: Build and test + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + linux: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - name: Configure + run: cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug + - name: Build + run: cmake --build build --parallel 2 + - name: Test + run: ctest --test-dir build --output-on-failure diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1dc1563 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/build/ +/firmware/esp32/build/ +/firmware/esp32/sdkconfig +/firmware/esp32/sdkconfig.old +/firmware/esp32/dependencies.lock +/firmware/esp32/managed_components/ +.DS_Store diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..78e8693 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,17 @@ +cmake_minimum_required(VERSION 3.20) + +if(ESP_PLATFORM) + idf_component_register( + SRC_DIRS src src/pd_esp32 src/fas_ramp src/log2 src/fas_queue + INCLUDE_DIRS src + REQUIRES esp_driver_gpio esp_driver_rmt esp_driver_mcpwm esp_driver_pcnt esp_driver_i2s + ) + return() +endif() + +project(StepperMotionWorkbench LANGUAGES CXX) + +include(CTest) +if(BUILD_TESTING) + add_subdirectory(tests/host) +endif() diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..0453d6e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,16 @@ +# Contributing + +Stepper Motion Workbench welcomes fixes and improvements to its motion +planner, command queue, drivers, and examples. + +1. Create a topic branch from the default branch and keep the pull request + focused on one change. +2. Follow the surrounding C++ style. Add a host test for changes to planning + or queue behavior when that behavior can be simulated. +3. Run the host build and CTest commands in [README.md](README.md). +4. For changes to a hardware backend, state the target and SDK version. For + hardware runs, include the driver and board, test inputs, and observed + pulse timing or position. + +The project is distributed under [LICENSE](LICENSE). Keep the source and +third-party attributions in [NOTICE](NOTICE) intact. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..a0c294f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 J.Kiemes + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..ec7474a --- /dev/null +++ b/NOTICE @@ -0,0 +1,35 @@ +Stepper Motion Workbench +======================== + +The motion library, Arduino examples, and host test sources were adapted +from FastAccelStepper by Jochen Kiemes and contributors. +Source: https://github.com/gin66/FastAccelStepper +Imported commit: 8e55103cf1af98d89be1710ee220844c0cd178f4 +Copyright (c) 2020 J.Kiemes +License: MIT (see LICENSE for the full terms) + +The original project credits the following contributions: + +- ixil: ATmega2560 support +- gagank1: ESP-IDF integration +- clazarowitz: Atmel SAM Due port +- HeldeReis: ESP32-S3 port +- DaAwesomeP: ATmega168/168P/328 support +- turley: stepper count initialization +- GarmischWg: ESP32-S3 RMT support +- SHWotever: AVR direction pin handling +- HalfVoxel: documentation and preprocessor fixes +- pvginkel: engine initialization race fix +- freelancer1845: ESP-IDF integration documentation +- viteo: pulse counter direction pin support +- Magnus: Pico SDK support and implementation suggestions +- Sam W: SAM3X queue allocation fix +- drayde: ESP-IDF 6 RMT header fix +- Loriland: Microchip SAMD51 port +- seifemad (ARDUTECH0): experimental Teensy 4.0/4.1 port and bring-up + +The Teensy 4.x backend adapts QuadTimer register sequencing from TMR.h +and dynamic-pin GPIO handling from stepperbase.h/.cpp in TeensyStep4. +Source: https://github.com/luni64/TeensyStep4 +Copyright (c) 2022 luni64 +License: MIT (see licenses/TeensyStep4-MIT.txt for the full terms) diff --git a/README.md b/README.md index 245b4b7..6a5ca59 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,68 @@ -# stepper-motion-workbench -Build and validate embedded STEP/DIR motion control. +# Stepper Motion Workbench + +Stepper Motion Workbench is an embedded C++ library for driving stepper drivers +through STEP and DIR signals. It queues pulse commands ahead of the timer +peripherals and provides acceleration ramps, timed segments, and coordinated +multi-axis movement. + +## Host build + +On Linux with GCC or Clang, install CMake 3.20 or newer and a C++17 compiler. + +```sh +git clone https://github.com/cpp-hardtech/stepper-motion-workbench.git +cd stepper-motion-workbench +cmake -S . -B build -DCMAKE_BUILD_TYPE=Debug +cmake --build build --parallel +ctest --test-dir build --output-on-failure +``` + +The tests use a simulated stepper queue. They exercise ramp calculations, +position tracking, timed moves, coordinated paths, and the ESP32 I2S and RMT +pulse encoders without connecting a motor. To run the timed-move example +against the simulator and see its output, use +`ctest --test-dir build -V -R '^test_29$'`. + +## ESP32 quick start + +The [ESP-IDF example](firmware/esp32/) builds against this checkout as a local +component. Use an ESP-IDF 5.x environment, version 5.3 or newer, with the +`esp32` target tools installed. + +```sh +cd firmware/esp32 +idf.py set-target esp32 +idf.py build +idf.py -p PORT flash monitor +``` + +The example commands 200 steps with GPIO 17 for STEP, GPIO 18 for DIR, and +GPIO 26 for active-low ENABLE. Adjust the pins and enable polarity in +[main.cpp](firmware/esp32/main/main.cpp) for your board and driver. Connect the +signals and common ground to a compatible external stepper driver. The serial +monitor reports the commanded position from the step queue. + +To use the library in an existing ESP-IDF application, add the checkout to +`EXTRA_COMPONENT_DIRS` before including the ESP-IDF project CMake file. In an +Arduino project, install this checkout as a local library named +`StepperMotionWorkbench` and open [UsageExample](examples/UsageExample/UsageExample.ino). + +## API + +- [StepperMotionEngine](src/StepperMotionEngine.h) binds a STEP output to a + driver queue and manages steppers. +- [StepperMotion](src/StepperMotion.h) sets speed and acceleration, starts + point-to-point and continuous moves, and queues step or pause commands. +- [FasTimed](src/FasTimed.h) queues coordinated segments with caller-supplied + timing. [FasNAxis](src/FasNAxis.h) plans coordinated motion along waypoints. +- [Examples](examples/) include single-axis, timed, and multi-axis sketches. + Backend availability and usable pins depend on the board and SDK. + +## Contributing + +See [CONTRIBUTING.md](CONTRIBUTING.md). + +## License + +MIT. See [LICENSE](LICENSE) and [NOTICE](NOTICE) for the license and source +attribution, including the Teensy timer code. diff --git a/examples/ExternalCall/ExternalCall.ino b/examples/ExternalCall/ExternalCall.ino new file mode 100644 index 0000000..3a431e4 --- /dev/null +++ b/examples/ExternalCall/ExternalCall.ino @@ -0,0 +1,86 @@ +#include "StepperMotion.h" + +#ifdef SIMULATOR +#include +#endif +#if defined(ARDUINO_ARCH_ESP32) +#include +#endif + +// As in StepperDemo for Motor 1 on AVR +#define dirPinStepper1 5 +#define enablePinStepper1 6 +#define stepPinStepper1 9 // OC1A in case of AVR + +// As in StepperDemo for Motor 2 on AVR +#define dirPinStepper2 7 +#define enablePinStepper2 8 +#define stepPinStepper2 10 // OC1B in case of AVR + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper1 = NULL; +StepperMotion *stepper2 = NULL; + +void setup() { + Serial.begin(115200); + Serial.println("External call test"); + Serial.println("Stepper 1 uses external dir pin"); + Serial.println("Stepper 2 uses direct dir pin"); + + engine.init(); + engine.setExternalCallForPin(setExternalPin); + stepper1 = engine.stepperConnectToPin(stepPinStepper1); + if (stepper1) { + stepper1->setDirectionPin(dirPinStepper1 | PIN_EXTERNAL_FLAG); + stepper1->setEnablePin(enablePinStepper1); + stepper1->setAutoEnable(true); + + stepper1->setSpeedInUs(10000); // the parameter is us/step !!! + stepper1->setAcceleration(1000); + } + + stepper2 = engine.stepperConnectToPin(stepPinStepper2); + if (stepper2) { + stepper2->setDirectionPin(dirPinStepper2); + stepper2->setEnablePin(enablePinStepper2); + stepper2->setAutoEnable(true); + + stepper2->setSpeedInUs(10000); // the parameter is us/step !!! + stepper2->setAcceleration(1000); + } +} + +bool setExternalPin(uint8_t pin, uint8_t value) { + // This example returns the previous value of the output. + // Consequently, StepperMotion needs to call setExternalPin twice + // in order to successfully change the output value. + pin = pin & ~PIN_EXTERNAL_FLAG; + pinMode(pin, OUTPUT); + bool oldValue = digitalRead(pin); + digitalWrite(pin, value); + return oldValue; +} + +void loop() { + // Blocking moves are used. + if (stepper1) { + stepper1->move(1000, true); + stepper1->move(-900, true); + stepper1->move(500, true); + stepper1->move(-450, true); + stepper1->move(40, true); + } + if (stepper2) { + stepper2->move(1000, true); + stepper2->move(-900, true); + stepper2->move(500, true); + stepper2->move(-450, true); + stepper2->move(40, true); + } + +#ifdef SIMULATOR + delay(1000); + noInterrupts(); + sleep_cpu(); +#endif +} diff --git a/examples/LinearAcceleration/LinearAcceleration.ino b/examples/LinearAcceleration/LinearAcceleration.ino new file mode 100644 index 0000000..1f0f141 --- /dev/null +++ b/examples/LinearAcceleration/LinearAcceleration.ino @@ -0,0 +1,143 @@ +#include "StepperMotion.h" + +// As in StepperDemo for Motor 1 on AVR +// #define dirPinStepper 5 +// #define enablePinStepper 6 +// #define stepPinStepper 9 // OC1A in case of AVR + +// As in StepperDemo for Motor 1 on ESP32 +#define dirPinStepper 18 +#define enablePinStepper 26 +#define stepPinStepper 17 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + Serial.println("START"); + engine.init(); + +#ifdef SUPPORT_SELECT_DRIVER_TYPE +// The code below is only relevant for original esp32 +// #define TEST_DONT_CARE_RMT +#ifdef TEST_DONT_CARE_RMT + // here occupy first all mcpwm/pcnt modules, then uses rmt + stepper = engine.stepperConnectToPin(19, DRIVER_DONT_CARE); + stepper = engine.stepperConnectToPin(16, DRIVER_DONT_CARE); + stepper = engine.stepperConnectToPin(15, DRIVER_DONT_CARE); + stepper = engine.stepperConnectToPin(14, DRIVER_DONT_CARE); + stepper = engine.stepperConnectToPin(13, DRIVER_DONT_CARE); + stepper = engine.stepperConnectToPin(12, DRIVER_DONT_CARE); + // now I get the rmt, I want + stepper = engine.stepperConnectToPin(stepPinStepper, DRIVER_DONT_CARE); +#else + // This is uses the new interface to enforce usage of RMT + stepper = engine.stepperConnectToPin(stepPinStepper, DRIVER_RMT); +#endif +#else + stepper = engine.stepperConnectToPin(stepPinStepper); +#endif + if (stepper) { + Serial.println("HAVE STEPPER"); + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + // If auto enable/disable need delays, just add (one or both): + // stepper->setDelayToEnable(50); + // stepper->setDelayToDisable(1000); + + // speed up in ~0.025s, which needs 625 steps without linear mode + stepper->setSpeedInHz(50000); + stepper->setAcceleration(2000000); + } else { + while (true) { + Serial.println("NO STEPPER"); + delay(1000); + } + } +} + +enum struct modes_e { + start_with_linear, + start_stop_with_linear, + start_stop_without_linear, + only_linear, + done +} modes[] = { + modes_e::start_with_linear, + // repeat the next for better comparison + modes_e::start_stop_with_linear, modes_e::start_stop_without_linear, + modes_e::start_stop_with_linear, modes_e::start_stop_without_linear, + modes_e::only_linear, modes_e::done}; +uint8_t mode_i = 0; +bool need_clear_linear = false; + +void loop() { + // we are using non-blocking mode to demonstrate, how to use that + + if (!stepper->isRunning()) { + // Only is stepper is not running + int32_t pos = stepper->getCurrentPosition(); + + if (pos > 0) { + // next mode + mode_i = mode_i + 1; + if (modes[mode_i] == modes_e::done) { + mode_i = 0; + } + + // now we have plenty of time to write to the Serial + switch (modes[mode_i]) { + case modes_e::start_with_linear: + Serial.println("start with linear and stop without"); + break; + case modes_e::start_stop_with_linear: + Serial.println("start and stop with linear"); + break; + case modes_e::start_stop_without_linear: + Serial.println("start and stop without linear"); + break; + case modes_e::only_linear: + Serial.println("no constant acceleration"); + break; + case modes_e::done: + break; + } + // let the user read the message + delay(2000); + } + + // we are just going back and forth + if (pos < 0) { + pos = 3200; + } else { + pos = -3200; + } + need_clear_linear = false; + switch (modes[mode_i]) { + case modes_e::start_with_linear: + need_clear_linear = true; + __attribute__((fallthrough)); + case modes_e::start_stop_with_linear: + // 100 steps linear, then constant acceleration + stepper->setLinearAcceleration(100); + break; + case modes_e::start_stop_without_linear: + stepper->setLinearAcceleration(0); + break; + case modes_e::only_linear: + stepper->setLinearAcceleration(100000); // just big enough value + break; + case modes_e::done: + break; + } + stepper->moveTo(pos); + } + if (need_clear_linear && (stepper->rampState() == RAMP_STATE_COAST)) { + // if needed, as soon as coasting is reached, turn of linear acceleration + need_clear_linear = false; + stepper->setLinearAcceleration(0); + } +} diff --git a/examples/MoveTimed/MoveTimed.ino b/examples/MoveTimed/MoveTimed.ino new file mode 100644 index 0000000..506e207 --- /dev/null +++ b/examples/MoveTimed/MoveTimed.ino @@ -0,0 +1,164 @@ +#if defined(ARDUINO_ARCH_AVR) +#include "AVRStepperPins.h" +#include "StepperMotion.h" +#ifdef SIMULATOR +#include +#endif + +// As in StepperDemo for Motor 1 on AVR +#define dirPinStepperX 5 +#define enablePinStepperX 6 +#define stepPinStepperX stepPinStepper1A + +// As in StepperDemo for Motor 2 on AVR +#define dirPinStepperY 7 +#define enablePinStepperY 8 +#define stepPinStepperY stepPinStepper1B + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepperX = NULL; +StepperMotion *stepperY = NULL; + +struct control_s { + uint64_t time; + uint16_t phi; + uint16_t drift; // time delta in ticks +}; +struct control_s controlX = {.time = 0, .phi = 0, .drift = 0}; +struct control_s controlY = {.time = 0, .phi = 90, .drift = 0}; + +// This means, the circle is executed in 360*4ms = 1440ms +#ifndef TIMESTEP_TICKS +#define TIMESTEP_TICKS (TICKS_PER_S / 250) +#endif + +// Table generated by python: +// [int(math.sin(x*math.pi/180)*1600) for x in range(0,91)] +int16_t step_list[91] = { + 0, 27, 55, 83, 111, 139, 167, 194, 222, 250, 277, 305, + 332, 359, 387, 414, 441, 467, 494, 520, 547, 573, 599, 625, + 650, 676, 701, 726, 751, 775, 799, 824, 847, 871, 894, 917, + 940, 962, 985, 1006, 1028, 1049, 1070, 1091, 1111, 1131, 1150, 1170, + 1189, 1207, 1225, 1243, 1260, 1277, 1294, 1310, 1326, 1341, 1356, 1371, + 1385, 1399, 1412, 1425, 1438, 1450, 1461, 1472, 1483, 1493, 1503, 1512, + 1521, 1530, 1538, 1545, 1552, 1558, 1565, 1570, 1575, 1580, 1584, 1588, + 1591, 1593, 1596, 1597, 1599, 1599, 1600}; + +void setup() { + Serial.begin(115200); + Serial.println("Init"); + engine.init(); + stepperX = engine.stepperConnectToPin(stepPinStepperX); + stepperY = engine.stepperConnectToPin(stepPinStepperY); + if (!stepperX || !stepperY) { + while (true) { + Serial.println("Cannot initialize steppers"); + } + } + stepperX->setDirectionPin(dirPinStepperX); + stepperX->setEnablePin(enablePinStepperX); + stepperX->setAutoEnable(false); + stepperY->setDirectionPin(dirPinStepperY); + stepperY->setEnablePin(enablePinStepperY); + stepperY->setAutoEnable(false); + + stepperY->setCurrentPosition(step_list[90]); + + // Without auto enable, need to enable manually both steppers + stepperX->enableOutputs(); + stepperY->enableOutputs(); + + // Fill the queue with 1ms delay and start the queues. + stepperX->moveTimed(0, TICKS_PER_S / 1000, NULL, false); + stepperY->moveTimed(0, TICKS_PER_S / 1000, NULL, false); + + // Start the queues. Currently best but not perfect synchronicity + stepperX->moveTimed(0, 0, NULL, true); + stepperY->moveTimed(0, 0, NULL, true); +} + +void moveStepper(StepperMotion *stepper, struct control_s *control) { + uint16_t phi = control->phi % 360; + + // The table contains only one quadrant + uint16_t index = phi; + bool negate = false; + if (index > 180) { + negate = true; + index = 360 - index; + } + if (index > 90) { + index = 180 - index; + } + int16_t position = step_list[index]; + if (negate) { + position = -position; + } + int32_t current_position = stepper->getPositionAfterCommandsCompleted(); + int32_t steps = position - current_position; + uint32_t actual; + MoveTimedResultCode rc; + uint32_t duration = TIMESTEP_TICKS + control->drift; + rc = stepper->moveTimed(steps, duration, &actual, true); + switch (rc) { + case MOVE_TIMED_EMPTY: + Serial.print("Empty:"); + Serial.println(stepper->getStepPin() == dirPinStepperX ? 'X' : 'Y'); + __attribute__((fallthrough)); + case MOVE_TIMED_OK: + control->drift = duration - actual; + control->time += actual; + control->phi += 1; + break; + case MOVE_TIMED_BUSY: + // Serial.println("Busy"); + break; + case MOVE_TIMED_TOO_LARGE_ERROR: + Serial.println("Too large"); + break; + case MoveTimedResultCode::ErrorTicksTooLow: + Serial.print("Ticks too low:"); + Serial.print(duration / steps); + Serial.print(" steps:"); + Serial.println(steps); + __attribute__((fallthrough)); + default: + Serial.println(toString(rc)); + } +} + +uint32_t last_millis = 0; + +void loop() { + if (last_millis != millis()) { + Serial.print(uint32_t(controlX.time)); + Serial.print(' '); + Serial.print(uint32_t(controlY.time)); + Serial.print(' '); + Serial.print(stepperX->getPositionAfterCommandsCompleted()); + Serial.print(' '); + Serial.print(stepperY->getPositionAfterCommandsCompleted()); + Serial.print(' '); + Serial.println(millis()); + last_millis = millis(); + } + + if (controlX.time < controlY.time) { + moveStepper(stepperX, &controlX); + } else { + moveStepper(stepperY, &controlY); + } + if ((controlX.phi != 361) && (controlY.phi != 451)) { + return; + } + // Full round should be completed +#ifdef SIMULATOR + delay(1000); + noInterrupts(); + sleep_cpu(); +#endif +} +#else +void setup() {} +void loop() {} +#endif diff --git a/examples/NaxesAFAP/NaxesAFAP.ino b/examples/NaxesAFAP/NaxesAFAP.ino new file mode 100644 index 0000000..1a9f2e6 --- /dev/null +++ b/examples/NaxesAFAP/NaxesAFAP.ino @@ -0,0 +1,268 @@ +// NaxesAFAP — a three-axis FasNAxis example. +// One StepperMotion per axis X/Y/Z, no +// gantry, driven in time-synchronized lockstep by a single FasNAxis planner. +// +// The path is fixed and deterministic so a run is comparable to the next: +// +// helix -> hexagon -> square -> return to origin +// +// A compile-time switch (NAXES_HW) drops the third axis on the ATmega168/328/ +// 328p, which expose only two step channels (OC1A / OC1B); every other +// platform wires three axes. +// +// The stepper pin table is selected by architecture, following the StepperDemo +// pattern: each platform header provides the NaxesAFAP_config_0[] array. + +// StepperMotion.h must come first: it defines PIN_UNDEFINED / FasDriver, +// which StepperConfig.h (pulled in by every pin table) uses. +#include "StepperMotion.h" + +#if defined(ARDUINO_ARCH_AVR) +#include "StepperPins_NaxesAFAP_avr.h" +#elif defined(ARDUINO_ARCH_SAMD) +#include "StepperPins_NaxesAFAP_sam.h" +#elif defined(ARDUINO_ARCH_SAM) +#include "StepperPins_NaxesAFAP_sam.h" +#elif defined(ARDUINO_ARCH_RP2040) +#include "StepperPins_NaxesAFAP_pico.h" +#elif defined(ARDUINO_ARCH_RP2350) +#include "StepperPins_NaxesAFAP_pico.h" +#elif defined(ARDUINO_ARCH_ESP32) +#include "StepperPins_NaxesAFAP_esp32.h" +#else +#error "NaxesAFAP: no pin table for this platform" +#endif + +#include "StepperConfig.h" +#include "generic.h" +#include "FasNAxis.h" +#include "NaxesAFAP_path.h" + +#ifdef SIMULATOR +#include +#endif + +// ATmega168/328/328p have two step channels, so the third axis is compiled +// out. Everything else wires three axes. The #undef-then-define form keeps +// PlatformIO's prototype pass (which preprocesses with -fpreprocessed and so +// does not evaluate the #if) from warning about a redefinition. +#define NAXES_HW 3 +#define NAXES_HORIZON 64 +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || \ + defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) +#undef NAXES_HW +#undef NAXES_HORIZON +#define NAXES_HW 2 +#define NAXES_HORIZON 64 +#endif + +// StepperMotionEngine owns the steppers and the cyclic fill ISR that keeps +// the planner-fed queues alive. +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion* NaxesAFAP_s[NAXES_HW] = {NULL}; + +// The planner. HORIZON must hold enough of the path for a smooth ramp while +// still fitting the small AVR parts; NAXES_HORIZON is 64 points on the +// two-axis build and 48 on the three-axis one. +FasNAxis NaxesAFAP_planner(FasNAxisConfig{}, engine); + +// Index of the waypoint currently being commanded. 0 is the first addWaypoint +// after the origin; the run finishes when it reaches total_waypoints(). +static uint16_t NaxesAFAP_wp_index = 0; +// The path is fully emitted and the queues have drained. +static bool NaxesAFAP_done = false; + +// Quarter index q in 0..3, within-quarter sample k in 0..NAXES_QSAMPLES-1. +// mag = R*sin(k*90/Q), rad = R*cos(k*90/Q). The four quarters place a vertex +// on the circle of radius R at angle (q*90 + k*90/Q) degrees: +// q0: x = R*sin, y = R*cos +// q1: x = R*cos, y = -R*sin +// q2: x = -R*sin, y = -R*cos +// q3: x = -R*cos, y = R*sin +// Vertex 0 is (R, 0), so the initial move from the origin is a straight line +// along +X at Z=0 (outside the helix-radius window). +static int32_t q_axis(int q, int16_t mag, int16_t rad, bool x_axis) { + if (x_axis) { + switch (q) { + case 0: + return rad; + case 1: + return -mag; + case 2: + return -rad; + default: + return mag; + } + } + switch (q) { + case 0: + return mag; + case 1: + return rad; + case 2: + return -mag; + default: + return -rad; + } +} + +// Absolute target (one entry per axis) of the i-th waypoint of the fixed path, +// computed on the fly so the whole curve costs only a few words of RAM. The +// origin (index 0 of the addWaypoint sequence) is established by +// setCurrentPosition in setup(); total_waypoints() counts the addWaypoint +// targets that follow. +void waypoint_target(uint16_t i, int32_t* t) { + t[0] = 0; + t[1] = 0; +#if NAXES_HW >= 3 + t[2] = 0; +#endif + const uint32_t per_turn = 4u * NAXES_QSAMPLES; + const uint32_t helix_len = (uint32_t)NAXES_HELIX_TURNS * per_turn; + + if (i < helix_len) { + uint32_t rem = i % per_turn; + int q = (int)(rem / NAXES_QSAMPLES); + int k = (int)(rem % NAXES_QSAMPLES); + int16_t mag = NAXES_SIN_Q[k]; + int16_t rad = NAXES_COS_Q[k]; + t[0] = q_axis(q, mag, rad, true); + t[1] = q_axis(q, mag, rad, false); +#if NAXES_HW >= 3 + // Climb Z smoothly over the whole helix, reaching Z_MAX at its end. + t[2] = (int32_t)((uint32_t)i * NAXES_HELIX_Z_PER_TURN / per_turn); +#endif + return; + } + + i -= (uint16_t)helix_len; + + // ---- hexagon: six corners of a regular hexagon in the XY plane. + const int32_t hex_x[6] = {NAXES_RADIUS, NAXES_RADIUS / 2, -NAXES_RADIUS / 2, + -NAXES_RADIUS, -NAXES_RADIUS / 2, NAXES_RADIUS / 2}; + const int32_t hex_y[6] = {0, NAXES_HEX_Y, NAXES_HEX_Y, + 0, -NAXES_HEX_Y, -NAXES_HEX_Y}; + if (i < 6) { + t[0] = hex_x[i]; + t[1] = hex_y[i]; +#if NAXES_HW >= 3 + t[2] = NAXES_HELIX_TURNS * NAXES_HELIX_Z_PER_TURN; +#endif + return; + } + i -= 6; + + // ---- square: four corners of an axis-aligned square in the XY plane. On a + // 2-axis build this is the cube footprint (four corners). + const int32_t h = NAXES_SQUARE_HALF; + static const int32_t sq[4][2] = {{h, h}, {-h, h}, {-h, -h}, {h, -h}}; + if (i < 4) { + t[0] = sq[i][0]; + t[1] = sq[i][1]; +#if NAXES_HW >= 3 + t[2] = NAXES_HELIX_TURNS * NAXES_HELIX_Z_PER_TURN; +#endif + return; + } + // i -= 4; + + // ---- return to origin. + t[0] = 0; + t[1] = 0; +#if NAXES_HW >= 3 + t[2] = 0; +#endif +} + +uint16_t total_waypoints() { + uint16_t n = + (uint16_t)((uint32_t)NAXES_HELIX_TURNS * 4 * NAXES_QSAMPLES + 6 + 4 + 1); + return n; +} + +void setup() { + engine.init(); + + // Connect one stepper per axis. The pin table carries NAXES_HW valid + // entries followed by the STEPPER_CONFIG_END sentinel. + const struct stepper_config_s* cfg = NaxesAFAP_config_0; + for (uint8_t i = 0; i < NAXES_HW; i++) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + NaxesAFAP_s[i] = + engine.stepperConnectToPin(cfg[i].step, cfg[i].driver_type); +#else + NaxesAFAP_s[i] = engine.stepperConnectToPin(cfg[i].step); +#endif + if (NaxesAFAP_s[i] == NULL) { + // No Serial here: it would drag Print/println into the flash image and + // the small AVR parts have no room for it. + while (1) { + } + } + NaxesAFAP_s[i]->setDirectionPin(cfg[i].direction, + cfg[i].direction_high_count_up); + if (cfg[i].enable_low_active != PIN_UNDEFINED) { + NaxesAFAP_s[i]->setEnablePin(cfg[i].enable_low_active); + } + NaxesAFAP_s[i]->setAutoEnable(cfg[i].auto_enable); + // A gentle but brisk profile so the whole path runs in a few seconds. + NaxesAFAP_s[i]->setSpeedInHz(400); + NaxesAFAP_s[i]->setAcceleration(1200); + } + + // Without auto enable the outputs must be enabled and settled before the + // planner kicks off (whitepaper section 4.5): a short delay lets the enable + // pin reach its active state so addQueueEntry() is not bounced off the + // WaitForEnablePinActive path. + if (cfg[0].on_delay_us != 0) { + DELAY_US(cfg[0].on_delay_us); + } + for (uint8_t i = 0; i < NAXES_HW; i++) { + NaxesAFAP_s[i]->enableOutputs(); + } + DELAY_US(100); + NaxesAFAP_planner.addAxis(0, NaxesAFAP_s[0]); +#if NAXES_HW >= 2 + NaxesAFAP_planner.addAxis(1, NaxesAFAP_s[1]); +#endif +#if NAXES_HW >= 3 + NaxesAFAP_planner.addAxis(2, NaxesAFAP_s[2]); +#endif + NaxesAFAP_planner.setLimitsFromSteppers(); + + // Start at the origin and open the path. + int32_t origin[NAXES_HW] = {0}; + NaxesAFAP_planner.setCurrentPosition(origin); +} + +void loop() { + if (!NaxesAFAP_done) { + // Feed the next waypoint target, but only when the planner's ring has room. + // addWaypoint() drains as the queues run, so this one target per pass keeps + // the ring from filling. + if (NaxesAFAP_wp_index < total_waypoints()) { + int32_t t[NAXES_HW] = {0}; + waypoint_target(NaxesAFAP_wp_index, t); + if (NaxesAFAP_planner.addWaypoint(t)) { + NaxesAFAP_wp_index++; + if (NaxesAFAP_wp_index >= total_waypoints()) { + NaxesAFAP_planner.endPath(); + } + } + } + } + + // Plan and feed the committed path into the stepper queues. The engine's + // cyclic ISR (manageSteppers, via the timer) emits the step / dir pins; + // pump() keeps the queues fed. + NaxesAFAP_planner.pump(); + + if (!NaxesAFAP_planner.isBusy() && NaxesAFAP_wp_index >= total_waypoints()) { +#ifdef SIMULATOR + noInterrupts(); + sleep_cpu(); +#else + NaxesAFAP_done = true; +#endif + } +} diff --git a/examples/NaxesAFAP/NaxesAFAP_path.h b/examples/NaxesAFAP/NaxesAFAP_path.h new file mode 100644 index 0000000..390fd60 --- /dev/null +++ b/examples/NaxesAFAP/NaxesAFAP_path.h @@ -0,0 +1,72 @@ +#ifndef NAXES_AFAP_PATH_H +#define NAXES_AFAP_PATH_H + +#include + +// Fixed, deterministic path for the NaxesAFAP example. Coordinates are absolute +// stepper positions in steps. The path runs, in order: +// +// 1. helix - a full circle in the XY plane while Z climbs steadily, +// approximated by NAXES_HELIX_SEGMENTS straight chords. +// 2. hexagon - six straight sides in the XY plane (Z held at the helix +// end). +// 3. square - four straight sides (a square in the XY plane; on a 2-axis +// build this is the "cube" degenerate, still four corners). +// 4. return - a direct line back to the origin, the start of the path. +// +// The geometry is exact-chord (Line mode): each addWaypoint() target is a +// vertex, so the realized curve is the polygon through the vertices. The +// simavr/PC test reconstructs this polygon from the Step/Dir pin traces and +// checks that the realized vertices match NAXES_PATH[] and that the run ends at +// the origin. + +// Circle / polygon radius in steps. +#define NAXES_RADIUS 400 +// Number of straight chords per quarter of the helix circle. A full turn is +// 4 * NAXES_QSAMPLES vertices. +#define NAXES_QSAMPLES 12 +// Number of full turns during the helix. +#define NAXES_HELIX_TURNS 3 +// Z climb per helix turn, in steps. +#define NAXES_HELIX_Z_PER_TURN 100 + +// Hexagon vertices (XY, at Z = end-of-helix Z). +// A regular hexagon has six vertices at angles 0, 60, 120, 180, 240, 300. +// int(400*cos(a)), int(400*sin(a)) for a in {0,60,120,180,240,300} degrees. +// 0 deg: ( 400, 0) +// 60 deg: ( 200, 346) sin60=0.8660 -> 346 +// 120 deg: (-200, 346) +// 180 deg: (-400, 0) +// 240 deg: (-200,-346) +// 300 deg: ( 200,-346) + +// Square vertices (XY, at Z = end-of-helix Z), radius NAXES_SQUARE_HALF=300. +// A square inscribed on the axes: (+/-300, +/-300). +#define NAXES_SQUARE_HALF 300 + +// Short-side height of the hexagon corners, in steps: int(R * sin(60)) = +// int(R * 866 / 1000). The L keeps the product in 32 bits so it does not +// overflow on 16-bit-int platforms (AVR). +#define NAXES_HEX_Y (NAXES_RADIUS * 866L / 1000) + +// The path is built at runtime in NaxesAFAP.ino from these constants so the +// same constants drive both the commanded addWaypoint() targets and the +// expected reconstruction, keeping the two sides identical. + +// The helix is emitted as a table of vertices by the caller; this file only +// carries the constants. The caller (NaxesAFAP.ino) generates the helix +// vertices with a fixed quarter-sine table (NAXES_SIN_QUAD, 91 entries, like +// MoveTimed.ino) so it stays float-free and deterministic. + +// Quarter sine / cosine tables for a radius of NAXES_RADIUS, sampled at +// x = k * 90 / NAXES_QSAMPLES degrees for k in 0..NAXES_QSAMPLES-1: +// NAXES_SIN_Q[k] = int(NAXES_RADIUS * sin(x*PI/180)) +// NAXES_COS_Q[k] = int(NAXES_RADIUS * cos(x*PI/180)) +// Together they place every helix vertex exactly on the circle of radius +// NAXES_RADIUS (a rounding error of well under one step). +static const int16_t NAXES_SIN_Q[NAXES_QSAMPLES] = { + 0, 52, 104, 153, 200, 244, 283, 317, 346, 370, 386, 397}; +static const int16_t NAXES_COS_Q[NAXES_QSAMPLES] = { + 400, 397, 386, 370, 346, 317, 283, 244, 200, 153, 104, 52}; + +#endif diff --git a/examples/NaxesAFAP/StepperConfig.h b/examples/NaxesAFAP/StepperConfig.h new file mode 100644 index 0000000..a6cd8fe --- /dev/null +++ b/examples/NaxesAFAP/StepperConfig.h @@ -0,0 +1,57 @@ +#ifndef STEPPER_CONFIG_H +#define STEPPER_CONFIG_H + +#include + +struct stepper_config_s { + uint8_t step; + uint8_t enable_low_active; + uint8_t enable_high_active; + uint8_t direction; + uint16_t dir_change_delay; + bool direction_high_count_up; + bool auto_enable; + uint32_t on_delay_us; + uint16_t off_delay_ms; +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + FasDriver driver_type; +#endif +}; + +struct stepper_config_set_s { + const char* name; + const struct stepper_config_s* config; +}; + +// Last entry of a config list (step == PIN_UNDEFINED). All fields are set so +// -Wmissing-field-initializers stays quiet. +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0, \ + driver_type : DRIVER_DONT_CARE \ + } +#else +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0 \ + } +#endif + +#endif diff --git a/examples/NaxesAFAP/StepperPins_NaxesAFAP_avr.h b/examples/NaxesAFAP/StepperPins_NaxesAFAP_avr.h new file mode 100644 index 0000000..c3d2734 --- /dev/null +++ b/examples/NaxesAFAP/StepperPins_NaxesAFAP_avr.h @@ -0,0 +1,82 @@ +#ifndef NAXES_AFAP_PINS_AVR_H +#define NAXES_AFAP_PINS_AVR_H + +#include "StepperConfig.h" + +// One unified config array, NaxesAFAP_config_0, regardless of platform. +// ATmega168/328/328p expose only two step channels (OC1A / OC1B), so the third +// axis is omitted and NAXES_HW becomes 2. ATmega2560 and the 32U4 expose +// OC1A/OC1B/OC1C, giving a full three-axis config. + +#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) || \ + defined(__AVR_ATmega168__) +const uint8_t NaxesAFAP_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesAFAP_config_0[] = { + { + step : stepPinStepper1A, // OC1A, digital 9 + enable_low_active : 6, // PD6 + enable_high_active : PIN_UNDEFINED, + direction : 5, // PD5 + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : stepPinStepper1B, // OC1B, digital 10 + enable_low_active : 8, // PB0 + enable_high_active : PIN_UNDEFINED, + direction : 7, // PD7 + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; +#define NAXES_AXES_WIRED 2 + +#else +// ATmega2560 / ATmega32U4: three step channels OC1A / OC1B / OC1C. +const uint8_t NaxesAFAP_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesAFAP_config_0[] = { + { + step : stepPinStepper1A, // OC1A + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 5, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : stepPinStepper1B, // OC1B + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 7, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : stepPinStepper1C, // OC1C + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 6, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; +#define NAXES_AXES_WIRED 3 + +#endif + +#endif diff --git a/examples/NaxesAFAP/StepperPins_NaxesAFAP_esp32.h b/examples/NaxesAFAP/StepperPins_NaxesAFAP_esp32.h new file mode 100644 index 0000000..a0223df --- /dev/null +++ b/examples/NaxesAFAP/StepperPins_NaxesAFAP_esp32.h @@ -0,0 +1,55 @@ +#ifndef NAXES_AFAP_PINS_ESP32_H +#define NAXES_AFAP_PINS_ESP32_H + +#include "StepperConfig.h" + +// ESP32 / ESP32-C3 / ESP32-S2 / ESP32-S3: the RMT/LEDC driver is not limited +// to fixed pins, so three independent axes are wired freely. These are +// placeholder GPIO assignments to be adapted to the actual board wiring. +const uint8_t NaxesAFAP_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesAFAP_config_0[] = { + { + step : 17, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 15, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 2, + enable_low_active : 12, + enable_high_active : PIN_UNDEFINED, + direction : 22, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesAFAP/StepperPins_NaxesAFAP_pico.h b/examples/NaxesAFAP/StepperPins_NaxesAFAP_pico.h new file mode 100644 index 0000000..4bd46d2 --- /dev/null +++ b/examples/NaxesAFAP/StepperPins_NaxesAFAP_pico.h @@ -0,0 +1,46 @@ +#ifndef NAXES_AFAP_PINS_PICO_H +#define NAXES_AFAP_PINS_PICO_H + +#include "StepperConfig.h" + +// Raspberry Pi Pico / Pico W / nanorp2040connect: GPIO is not fixed to a timer +// channel, so three axes are wired freely. Placeholder assignments to be +// adapted to the actual wiring. +const uint8_t NaxesAFAP_led_pin = LED_BUILTIN; +const struct stepper_config_s NaxesAFAP_config_0[] = { + { + step : 14, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 15, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : 18, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : 20, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 21, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesAFAP/StepperPins_NaxesAFAP_sam.h b/examples/NaxesAFAP/StepperPins_NaxesAFAP_sam.h new file mode 100644 index 0000000..f2d980c --- /dev/null +++ b/examples/NaxesAFAP/StepperPins_NaxesAFAP_sam.h @@ -0,0 +1,45 @@ +#ifndef NAXES_AFAP_PINS_SAM_H +#define NAXES_AFAP_PINS_SAM_H + +#include "StepperConfig.h" + +// Atmel SAM / SAMD (Due, Feather M4): TCC waveform outputs. Three axes wired +// to TCC outputs. Placeholder assignments to be adapted to the actual board. +const uint8_t NaxesAFAP_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesAFAP_config_0[] = { + { + step : 10, // TCC0/WO + enable_low_active : 21, + enable_high_active : PIN_UNDEFINED, + direction : 23, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000 + }, + { + step : 5, // TCC1/WO + enable_low_active : 22, + enable_high_active : PIN_UNDEFINED, + direction : 24, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000 + }, + { + step : 6, // TCC1/WO + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 12, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000 + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesAFAP/generic.h b/examples/NaxesAFAP/generic.h new file mode 100644 index 0000000..4f4ce34 --- /dev/null +++ b/examples/NaxesAFAP/generic.h @@ -0,0 +1,99 @@ +#ifndef GENERIC_H +#define GENERIC_H + +#if defined(ARDUINO_ARCH_AVR) +#include +#endif + +#if defined(ARDUINO_ARCH_AVR) +#define get_char(x) pgm_read_byte(x) +#define MSG_TYPE PGM_P +#elif defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_SAM) || \ + defined(ARDUINO_ARCH_SAMD) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(ESP_PLATFORM) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +#define get_char(x) *x +#define MSG_TYPE const char* +#else +#error "Unsupported derivate" +#endif + +#if !defined(ESP_PLATFORM) || defined(ARDUINO_ARCH_ESP32) + +#define PRINT_INIT() Serial.begin(115200); +#define PRINTLN Serial.println +#define PRINTCH Serial.print +#define PRINTU8 Serial.print +#define PRINTU16 Serial.print +#define PRINTI16 Serial.print +#define PRINTU32 Serial.print +#define PRINTI32 Serial.print +#define PRINT Serial.print +#define POLL_CHAR_IF_ANY(ch) \ + if (Serial.available()) { \ + ch = Serial.read(); \ + } +#define MILLIS() millis() +#define DELAY_US(v) delayMicroseconds(v) + +#else + +#include +#include +#include +#include +#include + +const uart_port_t uart_num = UART_NUM_0; + +#define PRINT_INIT() +#ifdef OLD +uart_config_t config; +config.baud_rate = 115200; +config.data_bits = UART_DATA_8_BITS; +config.parity = UART_PARITY_DISABLE; +config.stop_bits = UART_STOP_BITS_1; +config.flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS; +config.rx_flow_ctrl_thresh = 122; +uart_param_config(uart_num, &config); +#endif + +#define PRINTLN puts +#define PRINTU8(v) printf("%u", v) +#define PRINTU16(v) printf("%u", v) +#define PRINTI16(v) printf("%d", v) +#define PRINTU32(v) printf("%" PRIu32, v) +#define PRINTI32(v) printf("%" PRIi32, v) +#define PRINTCH(ch) printf("%c", ch) +#define PRINT(s) printf("%s", s) +#define POLL_CHAR_IF_ANY(ch) \ + { \ + uint8_t _ch = getchar(); \ + if (_ch != 255) { \ + ch = _ch; \ + } \ + } +#ifdef OLD +#define POLL_CHAR_IF_ANY(ch) \ + uint8_t _ch; \ + int n = uart_read_bytes(uart_num, &_ch, 1, 0); \ + if (n == 1) { \ + ch = _ch; \ + } +#endif +#define MILLIS() (esp_timer_get_time() / 1000) +#define DELAY_US(v) std::this_thread::sleep_for(std::chrono::microseconds(v)) +#define NEED_APP_MAIN + +#endif + +#if defined(ESP_PLATFORM) +#define PROGMEM +#define DELAY_MS(v) vTaskDelay(pdMS_TO_TICKS(v)) +#endif + +#endif diff --git a/examples/NaxesTimed/NaxesTimed.ino b/examples/NaxesTimed/NaxesTimed.ino new file mode 100644 index 0000000..f04ae5f --- /dev/null +++ b/examples/NaxesTimed/NaxesTimed.ino @@ -0,0 +1,190 @@ +// NaxesTimed — a two-axis FasTimed example. +// +// The head draws a diamond in the XY plane. Each of the four sides is one +// motor-speed ladder: it accelerates from rest through the pitch ladder in +// NaxesTimed_ramp.h, then decelerates back to rest. Both axes move together +// on every chunk (the diagonal keeps |dx| == |dy|), so the two motors share +// one clock and arrive at every corner at the same time. +// +// FasTimed does not invent the ramp: the caller asks for a rate and a +// duration per chunk. The ladder here is the one tests/host/test_29.cpp +// verifies; its RampMap does not depend on the platform's getMaxSpeedInTicks() +// because the periods stay well above it, so it is legal on AVR, Pico, SAM +// and ESP32. +// +// Acceleration must stay kNaxesTimedAccel (100000 steps/s^2). A different +// acceleration changes the ramp map and addDelta then returns +// TimingNotAchievable. +// +// Reversals at the corners need the axis at ramp-step 0, which the ladder +// provides by ending each side back at rest. A buffered driver that injects +// its own direction-change pause (ESP32 RMT/MCPWM/I2S) reports that as +// TimedStatus::Error; the timer-based AVR and Pico drivers do not. + +// StepperMotion.h must come first: it defines PIN_UNDEFINED / FasDriver, +// which StepperConfig.h (pulled in by every pin table) uses. +#include "StepperMotion.h" + +#if defined(ARDUINO_ARCH_AVR) +#include "StepperPins_NaxesTimed_avr.h" +#elif defined(ARDUINO_ARCH_SAMD) +#include "StepperPins_NaxesTimed_sam.h" +#elif defined(ARDUINO_ARCH_SAM) +#include "StepperPins_NaxesTimed_sam.h" +#elif defined(ARDUINO_ARCH_RP2040) +#include "StepperPins_NaxesTimed_pico.h" +#elif defined(ARDUINO_ARCH_RP2350) +#include "StepperPins_NaxesTimed_pico.h" +#elif defined(ARDUINO_ARCH_ESP32) +#include "StepperPins_NaxesTimed_esp32.h" +#else +#error "NaxesTimed: no pin table for this platform" +#endif + +#include "StepperConfig.h" +#include "generic.h" +#include "FasTimed.h" +#include "NaxesTimed_ramp.h" + +#ifdef SIMULATOR +#include +#endif + +#define NAXES_HW 2 +#define NAXES_TIMED_HORIZON 8 + +// StepperMotionEngine owns the steppers and the cyclic fill ISR. +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion* NaxesTimed_s[NAXES_HW] = {NULL}; + +// The planner. Each chunk is already one queue command, so the ring is small. +FasTimed NaxesTimed_planner(engine); + +// Diamond sides: (+1,+1), (-1,+1), (-1,-1), (+1,-1). Both axes use the same +// step count, so they share the ladder's ramp-step exactly. +static const int8_t kSideSign[4][2] = {{1, 1}, {-1, 1}, {-1, -1}, {1, -1}}; + +static uint8_t g_side = 0; +static uint8_t g_phase = 0; +static uint8_t g_stage = 0; +static uint8_t g_hold = 0; +static bool g_done = false; + +// One chunk of this period: as many steps as fit in 65535 ticks. The step +// count is shared by both axes so the diagonal stays at 45 degrees. +static void timed_chunk(uint16_t period, int16_t* steps, uint16_t* ticks) { + uint32_t n = 65535u / period; + if (n > 128) { + n = 128; + } + if (n < 1) { + n = 1; + } + *steps = (int16_t)n; + *ticks = (uint16_t)(n * period); +} + +// Submit the next chunk if the ring has room. Returns false when addDelta +// back-pressured (ring full): pump() drains and the next call retries. +static bool timed_next(void) { + uint16_t period; + uint8_t repeats; + uint8_t stages; + if (g_phase == 0) { + stages = + (uint8_t)(sizeof(kNaxesTimedUpPeriod) / sizeof(kNaxesTimedUpPeriod[0])); + period = kNaxesTimedUpPeriod[g_stage]; + repeats = kNaxesTimedUpHold; + } else { + stages = (uint8_t)(sizeof(kNaxesTimedDownPeriod) / + sizeof(kNaxesTimedDownPeriod[0])); + period = kNaxesTimedDownPeriod[g_stage]; + repeats = kNaxesTimedDownHold; + } + int16_t nsteps = 0; + uint16_t ticks = 0; + timed_chunk(period, &nsteps, &ticks); + int16_t d[NAXES_HW]; + d[0] = (int16_t)(kSideSign[g_side][0] * nsteps); + d[1] = (int16_t)(kSideSign[g_side][1] * nsteps); + if (NaxesTimed_planner.addDelta(d, ticks) != TimedAdd::Ok) { + return false; + } + g_hold++; + if (g_hold >= repeats) { + g_hold = 0; + g_stage++; + if (g_stage >= stages) { + g_stage = 0; + g_phase++; + if (g_phase > 1) { + g_phase = 0; + g_side++; + if (g_side >= 4) { + g_side = 0; + g_done = true; + } + } + } + } + return true; +} + +void setup() { + engine.init(); + + const struct stepper_config_s* cfg = NaxesTimed_config_0; + for (uint8_t i = 0; i < NAXES_HW; i++) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + NaxesTimed_s[i] = + engine.stepperConnectToPin(cfg[i].step, cfg[i].driver_type); +#else + NaxesTimed_s[i] = engine.stepperConnectToPin(cfg[i].step); +#endif + if (NaxesTimed_s[i] == NULL) { + // No Serial here: it would drag Print/println into the flash image. + while (1) { + } + } + NaxesTimed_s[i]->setDirectionPin(cfg[i].direction, + cfg[i].direction_high_count_up); + if (cfg[i].enable_low_active != PIN_UNDEFINED) { + NaxesTimed_s[i]->setEnablePin(cfg[i].enable_low_active); + } + NaxesTimed_s[i]->setAutoEnable(cfg[i].auto_enable); + // The ladder was chosen for this acceleration at 16 MHz ticks. FasTimed + // ignores the configured speed limit; only the acceleration feeds the + // ramp map. + NaxesTimed_s[i]->setAcceleration(kNaxesTimedAccel); + } + + // Enable and settle the outputs before the planner kicks off (whitepaper + // section 4.5), so addQueueEntry() is not bounced off the enable wait. + if (cfg[0].on_delay_us != 0) { + DELAY_US(cfg[0].on_delay_us); + } + for (uint8_t i = 0; i < NAXES_HW; i++) { + NaxesTimed_s[i]->enableOutputs(); + } + DELAY_US(100); + NaxesTimed_planner.addAxis(0, NaxesTimed_s[0]); + NaxesTimed_planner.addAxis(1, NaxesTimed_s[1]); + + int32_t origin[NAXES_HW] = {0, 0}; + NaxesTimed_planner.setCurrentPosition(origin); +} + +void loop() { + if (!g_done) { + timed_next(); + } + + NaxesTimed_planner.pump(); + + if (g_done && !NaxesTimed_planner.isBusy()) { +#ifdef SIMULATOR + noInterrupts(); + sleep_cpu(); +#endif + } +} diff --git a/examples/NaxesTimed/NaxesTimed_ramp.h b/examples/NaxesTimed/NaxesTimed_ramp.h new file mode 100644 index 0000000..edc0417 --- /dev/null +++ b/examples/NaxesTimed/NaxesTimed_ramp.h @@ -0,0 +1,30 @@ +#ifndef NAXES_TIMED_RAMP_H +#define NAXES_TIMED_RAMP_H + +// Pitch ladder for FasTimed at 100000 steps/s^2 and 16 MHz ticks. +// Each value is the step period in driver ticks. The chunk uses as many +// steps as fit in 65535 ticks. The rising list is coarse. The falling list +// steps the ramp map one ramp-step at a time, which is what a legal +// deceleration from the top period requires. +// +// kNaxesTimedUpHold / kNaxesTimedDownHold repeats make each direction last +// about a second, so both the rise and the fall are audible. +// +// The RampMap of these periods is independent of the platform's +// getMaxSpeedInTicks() as long as the periods stay well above it, so the +// same ladder is legal on AVR, Pico, SAM and ESP32. The PC test +// tests/host/test_29.cpp renders it as test_29.wav. + +static const uint16_t kNaxesTimedUpPeriod[] = {36000, 25000, 18000, 14000, + 11000, 9000, 7500, 6400}; +static const uint16_t kNaxesTimedDownPeriod[] = { + 6500, 6600, 6700, 6800, 6900, 7100, 7200, 7400, 7500, 7700, 7900, + 8100, 8300, 8500, 8700, 9000, 9300, 9600, 10000, 10400, 10900, 11400, + 12000, 12700, 13600, 14700, 16100, 18000, 20700, 25400, 35900}; + +static const uint8_t kNaxesTimedUpHold = 36; +static const uint8_t kNaxesTimedDownHold = 8; + +static const uint32_t kNaxesTimedAccel = 100000; + +#endif diff --git a/examples/NaxesTimed/StepperConfig.h b/examples/NaxesTimed/StepperConfig.h new file mode 100644 index 0000000..a6cd8fe --- /dev/null +++ b/examples/NaxesTimed/StepperConfig.h @@ -0,0 +1,57 @@ +#ifndef STEPPER_CONFIG_H +#define STEPPER_CONFIG_H + +#include + +struct stepper_config_s { + uint8_t step; + uint8_t enable_low_active; + uint8_t enable_high_active; + uint8_t direction; + uint16_t dir_change_delay; + bool direction_high_count_up; + bool auto_enable; + uint32_t on_delay_us; + uint16_t off_delay_ms; +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + FasDriver driver_type; +#endif +}; + +struct stepper_config_set_s { + const char* name; + const struct stepper_config_s* config; +}; + +// Last entry of a config list (step == PIN_UNDEFINED). All fields are set so +// -Wmissing-field-initializers stays quiet. +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0, \ + driver_type : DRIVER_DONT_CARE \ + } +#else +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0 \ + } +#endif + +#endif diff --git a/examples/NaxesTimed/StepperPins_NaxesTimed_avr.h b/examples/NaxesTimed/StepperPins_NaxesTimed_avr.h new file mode 100644 index 0000000..986a5b1 --- /dev/null +++ b/examples/NaxesTimed/StepperPins_NaxesTimed_avr.h @@ -0,0 +1,35 @@ +#ifndef NAXES_TIMED_PINS_AVR_H +#define NAXES_TIMED_PINS_AVR_H + +#include "StepperConfig.h" + +// Two axes on the AVR Timer 1 channels OC1A (digital 9) / OC1B (digital 10). +// The ATmega168/328/328p expose exactly these two step channels, and the +// larger AVRs are used with the same two so one config array fits all. +const uint8_t NaxesTimed_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesTimed_config_0[] = { + { + step : stepPinStepper1A, // OC1A, digital 9 + enable_low_active : 6, // PD6 + enable_high_active : PIN_UNDEFINED, + direction : 5, // PD5 + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : stepPinStepper1B, // OC1B, digital 10 + enable_low_active : 8, // PB0 + enable_high_active : PIN_UNDEFINED, + direction : 7, // PD7 + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesTimed/StepperPins_NaxesTimed_esp32.h b/examples/NaxesTimed/StepperPins_NaxesTimed_esp32.h new file mode 100644 index 0000000..46ca2a2 --- /dev/null +++ b/examples/NaxesTimed/StepperPins_NaxesTimed_esp32.h @@ -0,0 +1,41 @@ +#ifndef NAXES_TIMED_PINS_ESP32_H +#define NAXES_TIMED_PINS_ESP32_H + +#include "StepperConfig.h" + +// ESP32 / ESP32-C3 / ESP32-S2 / ESP32-S3: the RMT/LEDC driver is not limited +// to fixed pins, so the two axes are wired freely. These are placeholder +// GPIO assignments to be adapted to the actual board wiring. +const uint8_t NaxesTimed_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesTimed_config_0[] = { + { + step : 17, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 15, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesTimed/StepperPins_NaxesTimed_pico.h b/examples/NaxesTimed/StepperPins_NaxesTimed_pico.h new file mode 100644 index 0000000..ef5a219 --- /dev/null +++ b/examples/NaxesTimed/StepperPins_NaxesTimed_pico.h @@ -0,0 +1,35 @@ +#ifndef NAXES_TIMED_PINS_PICO_H +#define NAXES_TIMED_PINS_PICO_H + +#include "StepperConfig.h" + +// Raspberry Pi Pico / Pico W / nanorp2040connect: GPIO is not fixed to a timer +// channel, so the two axes are wired freely. Placeholder assignments to be +// adapted to the actual wiring. +const uint8_t NaxesTimed_led_pin = LED_BUILTIN; +const struct stepper_config_s NaxesTimed_config_0[] = { + { + step : 14, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 15, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + { + step : 18, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesTimed/StepperPins_NaxesTimed_sam.h b/examples/NaxesTimed/StepperPins_NaxesTimed_sam.h new file mode 100644 index 0000000..36ea80a --- /dev/null +++ b/examples/NaxesTimed/StepperPins_NaxesTimed_sam.h @@ -0,0 +1,34 @@ +#ifndef NAXES_TIMED_PINS_SAM_H +#define NAXES_TIMED_PINS_SAM_H + +#include "StepperConfig.h" + +// Atmel SAM / SAMD (Due, Feather M4): TCC waveform outputs. Two axes wired +// to TCC outputs. Placeholder assignments to be adapted to the actual board. +const uint8_t NaxesTimed_led_pin = PIN_UNDEFINED; +const struct stepper_config_s NaxesTimed_config_0[] = { + { + step : 10, // TCC0/WO + enable_low_active : 21, + enable_high_active : PIN_UNDEFINED, + direction : 23, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000 + }, + { + step : 5, // TCC1/WO + enable_low_active : 22, + enable_high_active : PIN_UNDEFINED, + direction : 24, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 1000 + }, + STEPPER_CONFIG_END}; + +#endif diff --git a/examples/NaxesTimed/generic.h b/examples/NaxesTimed/generic.h new file mode 100644 index 0000000..4f4ce34 --- /dev/null +++ b/examples/NaxesTimed/generic.h @@ -0,0 +1,99 @@ +#ifndef GENERIC_H +#define GENERIC_H + +#if defined(ARDUINO_ARCH_AVR) +#include +#endif + +#if defined(ARDUINO_ARCH_AVR) +#define get_char(x) pgm_read_byte(x) +#define MSG_TYPE PGM_P +#elif defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_SAM) || \ + defined(ARDUINO_ARCH_SAMD) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(ESP_PLATFORM) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +#define get_char(x) *x +#define MSG_TYPE const char* +#else +#error "Unsupported derivate" +#endif + +#if !defined(ESP_PLATFORM) || defined(ARDUINO_ARCH_ESP32) + +#define PRINT_INIT() Serial.begin(115200); +#define PRINTLN Serial.println +#define PRINTCH Serial.print +#define PRINTU8 Serial.print +#define PRINTU16 Serial.print +#define PRINTI16 Serial.print +#define PRINTU32 Serial.print +#define PRINTI32 Serial.print +#define PRINT Serial.print +#define POLL_CHAR_IF_ANY(ch) \ + if (Serial.available()) { \ + ch = Serial.read(); \ + } +#define MILLIS() millis() +#define DELAY_US(v) delayMicroseconds(v) + +#else + +#include +#include +#include +#include +#include + +const uart_port_t uart_num = UART_NUM_0; + +#define PRINT_INIT() +#ifdef OLD +uart_config_t config; +config.baud_rate = 115200; +config.data_bits = UART_DATA_8_BITS; +config.parity = UART_PARITY_DISABLE; +config.stop_bits = UART_STOP_BITS_1; +config.flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS; +config.rx_flow_ctrl_thresh = 122; +uart_param_config(uart_num, &config); +#endif + +#define PRINTLN puts +#define PRINTU8(v) printf("%u", v) +#define PRINTU16(v) printf("%u", v) +#define PRINTI16(v) printf("%d", v) +#define PRINTU32(v) printf("%" PRIu32, v) +#define PRINTI32(v) printf("%" PRIi32, v) +#define PRINTCH(ch) printf("%c", ch) +#define PRINT(s) printf("%s", s) +#define POLL_CHAR_IF_ANY(ch) \ + { \ + uint8_t _ch = getchar(); \ + if (_ch != 255) { \ + ch = _ch; \ + } \ + } +#ifdef OLD +#define POLL_CHAR_IF_ANY(ch) \ + uint8_t _ch; \ + int n = uart_read_bytes(uart_num, &_ch, 1, 0); \ + if (n == 1) { \ + ch = _ch; \ + } +#endif +#define MILLIS() (esp_timer_get_time() / 1000) +#define DELAY_US(v) std::this_thread::sleep_for(std::chrono::microseconds(v)) +#define NEED_APP_MAIN + +#endif + +#if defined(ESP_PLATFORM) +#define PROGMEM +#define DELAY_MS(v) vTaskDelay(pdMS_TO_TICKS(v)) +#endif + +#endif diff --git a/examples/PrintPosition/PrintPosition.ino b/examples/PrintPosition/PrintPosition.ino new file mode 100644 index 0000000..f10647a --- /dev/null +++ b/examples/PrintPosition/PrintPosition.ino @@ -0,0 +1,57 @@ +#include "StepperMotion.h" + +// As in StepperDemo for Motor 1 on AVR +#define dirPinStepper 17 +#define enablePinStepper 25 +#define stepPinStepper 16 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + + Serial.println("Starting"); + Serial.flush(); + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + Serial.println("Starting"); + Serial.print("Stepper Pin:"); + Serial.println(stepPinStepper); + Serial.flush(); + Serial.println((unsigned int)stepper); + Serial.println((unsigned int)&engine); + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + stepper->setSpeedInUs(5); // the parameter is us/step !!! + stepper->setAcceleration(1000); + delay(5000); + // stepper->move(7000); + stepper->runBackward(); + } else { + Serial.println("Stepper Not initialized!"); + delay(1000); + } + Serial.print(" F_CPU="); + Serial.println(F_CPU); + Serial.print(" TICKS_PER_S="); + Serial.println(TICKS_PER_S); + Serial.flush(); +} + +void loop() { + delay(100); + if (stepper) { + if (stepper->isRunning()) { + Serial.print("@"); + Serial.println(stepper->getCurrentPosition()); + } + } else { + Serial.println("Stepper died?"); + Serial.flush(); + delay(10000); + } +} diff --git a/examples/Pulses/Pulses.ino b/examples/Pulses/Pulses.ino new file mode 100644 index 0000000..075de1d --- /dev/null +++ b/examples/Pulses/Pulses.ino @@ -0,0 +1,139 @@ +#include "StepperMotion.h" + +// +// This is for TEST PURPOSES +// + +// As in StepperDemo for Motor 1 on AVR +// #define dirPinStepper 5 +// #define enablePinStepper 6 +// #define stepPinStepper 9 // OC1A in case of AVR + +// As in StepperDemo for Motor 7 on ESP32 +#define dirPinStepper 19 +#define enablePinStepper 26 +#define stepPinStepper 14 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + + if (false) { + pinMode(stepPinStepper, OUTPUT); + digitalWrite(stepPinStepper, HIGH); + delay(1); + digitalWrite(stepPinStepper, LOW); + delay(1); + digitalWrite(stepPinStepper, HIGH); + delay(1); + digitalWrite(stepPinStepper, LOW); + delay(1); + } + if (false) { + pinMode(18, OUTPUT); + digitalWrite(18, HIGH); + delay(1000); + digitalWrite(18, LOW); + delay(1000); + digitalWrite(18, HIGH); + delay(1000); + digitalWrite(18, LOW); + delay(1000); + } + + engine.init(); +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + stepper = engine.stepperConnectToPin(stepPinStepper, DRIVER_RMT); +#else + stepper = engine.stepperConnectToPin(stepPinStepper); +#endif +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + stepper->attachToPulseCounter(QUEUES_MCPWM_PCNT, 0, 0); + stepper->clearPulseCounter(); +#endif +} + +void loop1() { + const struct stepper_command_s cmd_step1 = { + .ticks = 6000, .steps = 1, .count_up = true}; + const struct stepper_command_s cmd_step2 = { + .ticks = 3000, .steps = 2, .count_up = true}; + const struct stepper_command_s cmd_step3 = { + .ticks = 2000, .steps = 3, .count_up = true}; + const struct stepper_command_s cmd_pause = { + .ticks = 6000, .steps = 0, .count_up = true}; + + stepper->addQueueEntry(&cmd_step3); + stepper->addQueueEntry(&cmd_step1); + stepper->addQueueEntry(&cmd_step2); + stepper->addQueueEntry(&cmd_pause); + stepper->addQueueEntry(&cmd_step3); + while (stepper->isRunning()) { + } + delayMicroseconds(150); + + stepper->addQueueEntry(&cmd_step3); + stepper->addQueueEntry(&cmd_step1); + stepper->addQueueEntry(&cmd_step2); + stepper->addQueueEntry(&cmd_pause); + stepper->addQueueEntry(&cmd_step3); + stepper->addQueueEntry(&cmd_pause); + delay(300); +} +void loop() { + uint16_t min_ticks = 0; + if (stepper) { + min_ticks = stepper->getMaxSpeedInTicks(); + } + //min_ticks = 30000; + const struct stepper_command_s cmd_step2 = { + .ticks = MIN_CMD_TICKS, .steps = 2, .count_up = true}; + const struct stepper_command_s cmd_step10 = { + .ticks = min_ticks, .steps = 10, .count_up = true}; + // const struct stepper_command_s cmd_step5 = { + // .ticks = 45000, .steps = 5, .count_up = true}; + // const struct stepper_command_s cmd_pause = { + // .ticks = 5000, .steps = 0, .count_up = true}; + AqeResultCode res[20]; + AqeResultCode *r = res; + if (stepper) { +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + stepper->clearPulseCounter(); +#endif + *r++ = stepper->addQueueEntry(&cmd_step2, false); + *r++ = stepper->addQueueEntry(&cmd_step10, false); + // stepper->addQueueEntry(&cmd_step2); + // stepper->addQueueEntry(&cmd_step2); + //*r++ = stepper->addQueueEntry(&cmd_step5, false); + //*r++ = stepper->addQueueEntry(&cmd_step10, false); + //*r++ = stepper->addQueueEntry(&cmd_step5, false); + //*r++ = stepper->addQueueEntry(&cmd_step10, false); + //*r++ = stepper->addQueueEntry(&cmd_step5, false); + //*r++ = stepper->addQueueEntry(&cmd_step10, false); + //*r++ = stepper->addQueueEntry(&cmd_pause); + *r++ = stepper->addQueueEntry(NULL); + Serial.print(toString(res[0])); + Serial.print('-'); + Serial.print(toString(res[1])); + Serial.print('-'); + Serial.println(toString(res[2])); + } + while (stepper->isRunning()) { + } +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + int16_t pc = stepper->readPulseCounter(); + digitalWrite(dirPinStepper, pc == 12 ? HIGH : LOW); + Serial.print(pc); + Serial.println(pc == 12 ? " OK" : " FAIL"); + digitalWrite(dirPinStepper, LOW); + delay(100); + digitalWrite(dirPinStepper, pc == 12 ? HIGH : LOW); + Serial.print(pc); + Serial.println(pc == 12 ? " OK" : " FAIL"); + delay(100); + digitalWrite(dirPinStepper, LOW); +#endif + delay(100); +} diff --git a/examples/RawAccess/RawAccess.ino b/examples/RawAccess/RawAccess.ino new file mode 100644 index 0000000..d86573e --- /dev/null +++ b/examples/RawAccess/RawAccess.ino @@ -0,0 +1,95 @@ +#include "StepperMotion.h" + +// for avr: either use pin 9 or 10 aka OC1A or OC1B +#define stepPinStepper 17 +#define enablePinStepper 26 +#define dirPinStepper 18 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper; + +void setup() { + Serial.begin(115200); + Serial.println("Demo RawAccess"); + + engine.init(); + + stepper = engine.stepperConnectToPin(stepPinStepper); + + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + } +} + +// This loop drives the stepper up to 50000 microsteps/s. +// For a NEMA-17 with 200 steps/revolution and 16 microsteps driver setting, +// this means 15.6 revolutions/s + +bool direction = false; + +void loop() { + if (!stepper) { + return; + } +#define STEPS 500 + Serial.println("Start"); + for (uint32_t step = 1; step < STEPS; step++) { + // Ticks at start/end: 10ms + // @step = STEPS/2: it is 10ms/STEPS for STEPS=500 => 20us + uint32_t k = max(step, STEPS - step); + uint32_t ticks = TICKS_PER_S / 100 / (STEPS - k); + uint16_t curr_ticks; + uint8_t steps; + if (ticks > 65535) { + curr_ticks = 32768; + steps = 1; + } else { + steps = 65535 / ticks; + curr_ticks = ticks; + } + ticks -= curr_ticks; + struct stepper_command_s cmd = { + .ticks = curr_ticks, .steps = steps, .count_up = direction}; + while (true) { + AqeResultCode rc = stepper->addQueueEntry(&cmd); + if (rc == AQE_OK) { + break; + } + // adding a delay(1) causes problems + delayMicroseconds(1000); + } + while (ticks > 0) { + if (ticks > 65535) { + curr_ticks = 32768; + } else { + curr_ticks = ticks; + } + ticks -= curr_ticks; + struct stepper_command_s cmd2 = { + .ticks = curr_ticks, .steps = 0, .count_up = direction}; + while (true) { + AqeResultCode rc = stepper->addQueueEntry(&cmd2); + if (rc == AQE_OK) { + break; + } + // adding a delay(1) causes problems + delayMicroseconds(1000); + } + } + } + + Serial.println("no more commands to be created"); + while (!stepper->isQueueEmpty()) { + } + Serial.println("queue is empty"); + + while (stepper->isRunning()) { + } + + Serial.println("stepper has stopped"); + + delay(1000); + direction = !direction; +} diff --git a/examples/RawAccessTest/RawAccessTest.ino b/examples/RawAccessTest/RawAccessTest.ino new file mode 100644 index 0000000..456b827 --- /dev/null +++ b/examples/RawAccessTest/RawAccessTest.ino @@ -0,0 +1,89 @@ +#include "StepperMotion.h" + +#ifdef SIM_TEST_INPUT +#include +#endif + +// Exclusively for test purposes ! + +// for avr: either use pin 9 or 10 aka OC1A or OC1B + +// platformio does not manage cpp directives well +// #define are always executed +#if defined(ARDUINO_ARCH_AVR) +const uint8_t stepPinStepper = 9; +const uint8_t enablePinStepper = 6; +const uint8_t dirPinStepper = 5; +#elif defined(ARDUINO_ARCH_ESP32) +const uint8_t stepPinStepper = 17; +const uint8_t enablePinStepper = 26; +const uint8_t dirPinStepper = 18; +#elif defined(ARDUINO_ARCH_SAM) +const uint8_t stepPinStepper = 1; // only defined to satisfy compiler +const uint8_t enablePinStepper = 2; +const uint8_t dirPinStepper = 3; +#elif defined(ARDUINO_ARCH_SAMD) +const uint8_t stepPinStepper = 10; // TCC0 output on Feather M4 +const uint8_t enablePinStepper = 21; +const uint8_t dirPinStepper = 23; +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +const uint8_t stepPinStepper = 15; // only defined to satisfy compiler +const uint8_t enablePinStepper = 13; +const uint8_t dirPinStepper = 14; +#endif + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper; + +void setup() { + Serial.begin(115200); + Serial.println("Demo RawAccess"); + + engine.init(); + + stepper = engine.stepperConnectToPin(stepPinStepper); + + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + Serial.println("Start"); + uint32_t _start = micros(); + uint32_t cnt = 0; + for (uint32_t delay = 0; delay < 20000; delay += 100) { + // just issue a step with 1ms pause + struct stepper_command_s cmd = { + .ticks = 16000, .steps = 2, .count_up = true}; + AqeResultCode rc = stepper->addQueueEntry(&cmd); + if (rc != AQE_OK) { + Serial.print("Queue error:"); + Serial.println(toString(rc)); + } else { + cnt++; + while (stepper->isRunning()) { + } + } + uint32_t x = micros() + delay; + while (micros() < x) { + } + _start += delay; + } + uint32_t _end = micros(); + Serial.println(_start); + Serial.println(_end); + Serial.println("Done. "); + Serial.print(cnt); + Serial.print(" Stepper commands executed within us="); + Serial.print((_end - _start) / cnt); + Serial.println(". Expected ~1000"); + } +} + +void loop() { + delay(1000); +#ifdef SIM_TEST_INPUT + noInterrupts(); + sleep_cpu(); +#endif +} diff --git a/examples/RawAccessWithPause/RawAccessWithPause.ino b/examples/RawAccessWithPause/RawAccessWithPause.ino new file mode 100644 index 0000000..201b1c6 --- /dev/null +++ b/examples/RawAccessWithPause/RawAccessWithPause.ino @@ -0,0 +1,67 @@ +#include "StepperMotion.h" + +// for avr: either use pin 9 or 10 aka OC1A or OC1B +#define stepPinStepper 17 +#define enablePinStepper 26 +#define dirPinStepper 18 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper; + +void setup() { + Serial.begin(115200); + Serial.println("Demo RawAccessWithDelay"); + + engine.init(); + + stepper = engine.stepperConnectToPin(stepPinStepper); + + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(false); + stepper->enableOutputs(); + } +} + +// This loop should use the new pause only command to generate steps every 0.1 s + +void loop() { + // in case the stepper has not gotten initialized + if (!stepper) { + return; + } + // every loop will create one step and then pause 0.1 s = 25 * 4ms + const struct stepper_command_s cmd_step = { + .ticks = 64000, .steps = 1, .count_up = true}; // one step with pause 4ms + const struct stepper_command_s cmd_pause = { + .ticks = 64000, .steps = 0, .count_up = true}; // only pause 4ms + + // create one step + 4 ms pause + while (true) { + // This loop repeats a command, in case the queue is full + AqeResultCode rc = stepper->addQueueEntry(&cmd_step); + // Serial.println(rc); + if (rc == AQE_OK) { + Serial.println("STEP"); + break; + } + // adding a delay(1) causes problems + delayMicroseconds(1000); + } + + // this creates 24*4ms pauses + for (uint16_t i = 0; i < 24; i++) { + // This loop repeats a command, in case the queue is full + while (true) { + AqeResultCode rc = stepper->addQueueEntry(&cmd_pause); + // Serial.println(rc); + if (rc == AQE_OK) { + Serial.print("."); + break; + } + // adding a delay(1) causes problems + delayMicroseconds(1000); + } + } +} diff --git a/examples/RawOneTurn/RawOneTurn.ino b/examples/RawOneTurn/RawOneTurn.ino new file mode 100644 index 0000000..9a4dcb6 --- /dev/null +++ b/examples/RawOneTurn/RawOneTurn.ino @@ -0,0 +1,136 @@ +#include "pinning.h" +#ifdef ARDUINO_ARCH_AVR +#include +#endif + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper; + +void setup() { + Serial.begin(115200); + + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + stepper->enableOutputs(); + } + + const uint16_t lframes[] = {107, 107, 107, 107, 107, 107, 107, 107, 107, 107, + 107, 107, 107, 107, 107, 107, 107, 107, 107, 107, + 107, 107, 107, 107, 107, 107, 107, 107, 107, 97}; + // a representation of a 360 degree rot at 30 fps + uint16_t lenAnim = 30; + +#define TICKS_PER_FRAME (TICKS_PER_S / 30) + for (uint16_t i = 0; i < lenAnim; i++) { // for each frame + + uint16_t steps = lframes[i]; + + // THIS WORKS ONLY, IF STEPS > 0 + uint32_t ticks_per_step = TICKS_PER_FRAME / steps; + uint32_t this_frame_steps = 0; + + while (this_frame_steps < steps) { + // repeat as long as not all steps for this frame created... + + if (ticks_per_step < 65535) { // does it fit into an uint16_t ? + // Yes, so every command will generate at least one step + uint8_t this_cmd_steps = 1; + if ((uint32_t)this_cmd_steps * ticks_per_step < TICKS_PER_S / 500) { + // in order to have ~2ms long command, this command should issue + // multiple steps + this_cmd_steps = TICKS_PER_S / 500 / ticks_per_step; + } + if (this_cmd_steps + this_frame_steps > steps) { + this_cmd_steps = steps - this_frame_steps; + } + struct stepper_command_s cmd_step = {.ticks = (uint16_t)ticks_per_step, + .steps = this_cmd_steps, + .count_up = true}; + + // add command to the queue + AqeResultCode rc; + do { + rc = stepper->addQueueEntry(&cmd_step); + if (aqeRetry(rc)) { + // so the queue is busy => put the task to sleep for + // portTICK_PERIOD_MS + vTaskDelay(1); + } + } while (aqeRetry(rc)); // repeat addQueueEntry, if queue is busy + + // sum up the generated steps + this_frame_steps += this_cmd_steps; + } else { + // For one step, one command with a step + one or several pauses are + // needed + + // let's remember how many ticks still to be generated + uint32_t remaining_ticks = ticks_per_step; + + // Let's first do the step + struct stepper_command_s cmd_step = { + .ticks = 16384, .steps = 1, .count_up = true}; + + // add command to the queue + AqeResultCode rc; + do { + rc = stepper->addQueueEntry(&cmd_step); + if (aqeRetry(rc)) { + // so the queue is busy => put the task to sleep for + // portTICK_PERIOD_MS + vTaskDelay(1); + } + } while (aqeRetry(rc)); // repeat addQueueEntry, if queue is busy + + // sum up this one step + this_frame_steps += 1; + + // and reduce the remaining ticks + remaining_ticks -= 16384; + + // Now create the pauses until remaining_ticks is 0 + while (remaining_ticks > 0) { + uint16_t this_cmd_ticks; + + // do remaining ticks fit into an uint16_t + if (remaining_ticks > 65535) { + // nope, so make a pause of 32768 ticks + this_cmd_ticks = 32768; + } else { + // yeah, fits. So use that value + this_cmd_ticks = (uint16_t)remaining_ticks; + } + + // make a pause command + struct stepper_command_s cmd_pause = { + .ticks = this_cmd_ticks, .steps = 0, .count_up = true}; + + // and add it to the queue + do { + rc = stepper->addQueueEntry(&cmd_pause); + if (aqeRetry(rc)) { + // so the queue is busy => put the task to sleep for + // portTICK_PERIOD_MS + vTaskDelay(1); + } + } while (aqeRetry(rc)); // repeat addQueueEntry, if queue is busy + + // reduce the remaining ticks + remaining_ticks -= this_cmd_ticks; + } + } + } + } +} + +void loop() { + Serial.println("DONE"); + Serial.println(stepper->getPositionAfterCommandsCompleted()); + // delay(1000); + // noInterrupts(); + // sleep_cpu(); +} diff --git a/examples/RawOneTurn/pinning.h b/examples/RawOneTurn/pinning.h new file mode 100644 index 0000000..fda1760 --- /dev/null +++ b/examples/RawOneTurn/pinning.h @@ -0,0 +1,22 @@ +#include "StepperMotion.h" + +#if defined(ARDUINO_ARCH_AVR) +#include "AVRStepperPins.h" +#define vTaskDelay(xx) \ + { \ + } +#define stepPinStepper stepPinStepper1A +#define enablePinStepper 6 +#define dirPinStepper 5 +#elif defined(ARDUINO_ARCH_ESP32) +#define stepPinStepper 17 +#define enablePinStepper 26 +#define dirPinStepper 18 +#else +#define vTaskDelay(xx) \ + { \ + } +#define stepPinStepper 17 +#define enablePinStepper 26 +#define dirPinStepper 18 +#endif diff --git a/examples/StepperDemo/StepperConfig.h b/examples/StepperDemo/StepperConfig.h new file mode 100644 index 0000000..a6cd8fe --- /dev/null +++ b/examples/StepperDemo/StepperConfig.h @@ -0,0 +1,57 @@ +#ifndef STEPPER_CONFIG_H +#define STEPPER_CONFIG_H + +#include + +struct stepper_config_s { + uint8_t step; + uint8_t enable_low_active; + uint8_t enable_high_active; + uint8_t direction; + uint16_t dir_change_delay; + bool direction_high_count_up; + bool auto_enable; + uint32_t on_delay_us; + uint16_t off_delay_ms; +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + FasDriver driver_type; +#endif +}; + +struct stepper_config_set_s { + const char* name; + const struct stepper_config_s* config; +}; + +// Last entry of a config list (step == PIN_UNDEFINED). All fields are set so +// -Wmissing-field-initializers stays quiet. +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0, \ + driver_type : DRIVER_DONT_CARE \ + } +#else +#define STEPPER_CONFIG_END \ + { \ + step : PIN_UNDEFINED, \ + enable_low_active : PIN_UNDEFINED, \ + enable_high_active : PIN_UNDEFINED, \ + direction : PIN_UNDEFINED, \ + dir_change_delay : 0, \ + direction_high_count_up : true, \ + auto_enable : false, \ + on_delay_us : 0, \ + off_delay_ms : 0 \ + } +#endif + +#endif diff --git a/examples/StepperDemo/StepperDemo.ino b/examples/StepperDemo/StepperDemo.ino new file mode 100644 index 0000000..855dd44 --- /dev/null +++ b/examples/StepperDemo/StepperDemo.ino @@ -0,0 +1,1491 @@ +#include "AVRStepperPins.h" +#include "StepperMotion.h" +#include "test_seq.h" + +#ifdef SIM_TEST_INPUT +#include +#endif +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) +#include +#include +#endif + +#define VERSION "post-4f2e1e4" + +#include "StepperConfig.h" +#if defined(ARDUINO_ARCH_AVR) +#include "StepperPins_avr.h" +#elif defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) +#if defined(CONFIG_IDF_TARGET_ESP32C3) +#include "StepperPins_esp32C3.h" +#elif defined(CONFIG_IDF_TARGET_ESP32C6) +#include "StepperPins_esp32C6.h" +#else +#include "StepperPins_esp32.h" +#endif +#elif defined(ARDUINO_ARCH_SAM) +#include "StepperPins_sam.h" +#elif defined(ARDUINO_ARCH_SAMD) +#include "StepperPins_samd.h" +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +#include "StepperPins_pico.h" +#endif + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion* steppers[MAX_STEPPER]; +const struct stepper_config_s* active_stepper_config = NULL; + +enum { normal, test, config } mode = normal; +bool test_ongoing = false; +struct test_seq_s test_seq[MAX_STEPPER]; + +// Forward declaration +void usage(); +void output_info(bool only_running); + +#define _NL_ "\n" +#define _SEP_ "|" +#define _SEP_CHAR_ '|' + +// clang-format off +const static char messages[] PROGMEM = +#define _Move_ "\200" + "Move " _SEP_ +#define _Output_driver_ "\201" + "Output driver " _SEP_ +#define _Cannot_set_ "\202" + "Cannot set " _SEP_ +#define _pin_ "\203" + "pin " _SEP_ +#define _step "\204" + "step" _SEP_ +#define _to_ "\205" + "to " _SEP_ +#define _LOW_ "\206" + "LOW " _SEP_ +#define _HIGH_ "\207" + "HIGH " _SEP_ +#define _to_LOW_nl "\210" + _to_ _LOW_ _NL_ _SEP_ +#define _to_HIGH_nl "\211" + _to_ _HIGH_ _NL_ _SEP_ +#define _Toggle_ "\212" + "Toggle " _SEP_ +#define _ERROR_ "\213" + "ERROR " _SEP_ +#define _high_counts_ "\214" + "high counts " _SEP_ +#define _enable_ "\215" + "enable " _SEP_ +#define _disable "\216" + "disable" _SEP_ +#define _direction_ "\217" + "direction " _SEP_ +#define _pulse_counter_ "\220" + "pulse counter " _SEP_ +#define _attach "\221" + "attach" _SEP_ +#define _set_ "\222" + "set " _SEP_ +#define _time_to_ "\223" + "time" _to_ _SEP_ +#define _is_not_defined_nl "\224" + "is not defined" _NL_ _SEP_ +#define _run_ "\225" + "run " _SEP_ +#define _forward "\226" + "forward" _SEP_ +#define _backward "\227" + "backward" _SEP_ +#define _Stepped_ "\230" + "Stepped " _SEP_ +#define _acceleration_ "\231" + "acceleration " _SEP_ +#define _speed_ "\232" + "speed " _SEP_ +#define _test_ "\233" + "test " _SEP_ +#define _erroneous_ "\234" + "erroneous " _SEP_ +#define _digitalRead_ "\235" + "digitalRead() " _SEP_ +#define ____ "\236" + " " _SEP_ +#define ________ "\237" + ____ ____ _SEP_ +#define _ooo_ "\240" + " ... " _SEP_ +#define _Enter_ "\241" + "Enter " _SEP_ +#define _mode "\242" + "mode" _SEP_ +#define _clear_ "\243" + "clear " _SEP_ +#define _stepper "\244" + _step "per" _SEP_ +#define _select "\245" + "select" _SEP_ +#define _selected_stepper "\246" + _select "ed " _stepper _SEP_ +#define _usage_ "\247" + "usage " _SEP_ +#define _steps_ "\250" + _step "s " _SEP_ +#define _output_ "\251" + " output " _SEP_ +#define _test_sequence_ "\252" + _test_ "sequence " _SEP_ +#define _Perform_ "\253" + "Perform " _SEP_ +#define _configuration_ "\254" + "configuration " _SEP_ +#define _delay_ "\255" + "delay " _SEP_ +#define _step_pin_ "\256" + _step " " _pin_ _SEP_ +#define _one_step_ "\257" + "one " _step " " _SEP_ +#define _position_ "\260" + "position " _SEP_ +#define __of_the_ "\261" + " of the " _SEP_ +#define _Turn_ "\262" + "Turn " _SEP_ +#define _stop "\263" + "stop" _SEP_ +#define _from_ "\264" + "from " _SEP_ +#define _comma__counting_ "\265" + ", counting " _SEP_ +#define __disable_auto_enable_nl "\266" + " " _disable " auto " _enable_ _NL_ _SEP_ +#define _ooo_set_selected_stepper_s_ "\267" + _ooo_ _set_ _selected_stepper "'s " _SEP_ +#define _m1_m2_to_select_stepper_ "\270" + ____ "M1/M2/.. " _ooo_ _to_ _select " " _stepper _NL_ _SEP_ +#define _print_this_usage_ "\271" + ____ "?" ________ _ooo_ "Print this usage" _NL_ _NL_ _SEP_ +#define _toggle_print_usage_after_stepper_stop "\272" + ____ "Q" ________ _ooo_ _Toggle_ "print " _usage_ "on " _stepper " " _stop _NL_ _SEP_ +#define _I_speed_I_ "\273" + " " _SEP_ +#define _I_accel_I_ "\274" + " " _SEP_ +#define _Enter_command_separated_by_space_carriage_return_or_newline_NL "\275" + _Enter_ "commands separated by space, carriage return or newline:" _NL_ _SEP_ +#define MSG_OFFSET 62 +#define MSG_SELECT_STEPPER 0+MSG_OFFSET + "Select " _stepper " " _SEP_ +#define MSG_TOGGLE_MOTOR_INFO 1+MSG_OFFSET + _Toggle_ _stepper " info" _NL_ _SEP_ +#define MSG_TOGGLE_USAGE_INFO 2+MSG_OFFSET + _Toggle_ _usage_ "info" _NL_ _SEP_ +#define MSG_ENTER_TEST_MODE 3+MSG_OFFSET + _Enter_ _test_ _mode _NL_ _SEP_ +#define MSG_SET_ACCELERATION_TO 4+MSG_OFFSET + _set_ _acceleration_ _to_ _SEP_ +#define MSG_SET_SPEED_TO_US 5+MSG_OFFSET + _set_ _speed_ "(us/" _step ") " _to_ _SEP_ +#define MSG_MOVE_STEPS 6+MSG_OFFSET + _Move_ _steps_ _SEP_ +#define MSG_MOVE_TO_POSITION 7+MSG_OFFSET + _Move_ _to_ _position_ _SEP_ +#define MSG_RETURN_CODE 8+MSG_OFFSET + "returncode = " _SEP_ +#define MSG_SET_POSITION 9+MSG_OFFSET + _set_ _position_ _SEP_ +#define MSG_SET_ENABLE_TIME 10+MSG_OFFSET + _set_ _enable_ _time_to_ _SEP_ +#define MSG_SET_DISABLE_TIME 11+MSG_OFFSET + _set_ _disable " " _time_to_ _SEP_ +#define MSG_OUTPUT_DRIVER_ON 12+MSG_OFFSET + _Output_driver_ "on" _NL_ _SEP_ +#define MSG_OUTPUT_DRIVER_OFF 13+MSG_OFFSET + _Output_driver_ "off" _NL_ _SEP_ +#define MSG_OUTPUT_DRIVER_AUTO 14+MSG_OFFSET + _Output_driver_ "automatic " _mode _NL_ _SEP_ +#define MSG_STOP 15+MSG_OFFSET + _stop _NL_ _SEP_ +#define MSG_KEEP_RUNNING 16+MSG_OFFSET + "Keep running" _NL_ _SEP_ +#define MSG_RUN_FORWARD 17+MSG_OFFSET + _run_ _forward _NL_ _SEP_ +#define MSG_RUN_BACKWARD 18+MSG_OFFSET + _run_ _backward _NL_ _SEP_ +#define MSG_IMMEDIATE_STOP 19+MSG_OFFSET + "immediate " _stop _NL_ _SEP_ +#define MSG_UPDATE_SPEED_ACCELERATION 20+MSG_OFFSET + "Update " _speed_ " / " _acceleration_ _NL_ _SEP_ +#define MSG_BLOCKING_WAIT 21+MSG_OFFSET + "Blocking wait for running " _stepper " " _to_ _stop _NL_ _SEP_ +#define MSG_TEST_DIRECT_DRIVE 22+MSG_OFFSET + _test_ "direct drive" _NL_ _SEP_ +#define MSG_STEPPED_FORWARD 23+MSG_OFFSET + _Stepped_ _forward _NL_ _SEP_ +#define MSG_STEPPED_BACKWARD 24+MSG_OFFSET + _Stepped_ _backward _NL_ _SEP_ +#define MSG_WAIT_MS 25+MSG_OFFSET + " ms wait" _NL_ _SEP_ +#define MSG_SELECT_TEST_SEQUENCE 26+MSG_OFFSET + "Select " _test_ "sequence: " _SEP_ +#define MSG_EXIT_TO_MAIN_MENU 27+MSG_OFFSET + "Exit " _to_ "main menu" _NL_ _SEP_ +#define MSG_RUN_TESTS 28+MSG_OFFSET + _run_ _test_ _NL_ _SEP_ +#define MSG_WAIT_COMPLETE 29+MSG_OFFSET + "Wait complete" _NL_ _SEP_ +#define MSG_FAILED_STATUS 30+MSG_OFFSET + "Failed status " _from_ _test_ _NL_ _SEP_ +#define MSG_ENABLE_LOW_PIN_IS_NOT_LOW 31+MSG_OFFSET + _Cannot_set_ _enable_ _LOW_ _pin_ _to_LOW_nl _SEP_ +#define MSG_ENABLE_LOW_PIN_IS_NOT_HIGH 32+MSG_OFFSET + _Cannot_set_ _enable_ _LOW_ _pin_ _to_HIGH_nl _SEP_ +#define MSG_ENABLE_HIGH_PIN_IS_NOT_LOW 33+MSG_OFFSET + _Cannot_set_ _enable_ _HIGH_ _pin_ _to_LOW_nl _SEP_ +#define MSG_ENABLE_HIGH_PIN_IS_NOT_HIGH 34+MSG_OFFSET + _Cannot_set_ _enable_ _HIGH_ _pin_ _to_HIGH_nl _SEP_ +#define MSG_STEP_PIN_IS_NOT_LOW 35+MSG_OFFSET + _Cannot_set_ _step_pin_ _to_LOW_nl _SEP_ +#define MSG_STEP_PIN_IS_NOT_HIGH 36+MSG_OFFSET + _Cannot_set_ _step_pin_ _to_HIGH_nl _SEP_ +#define MSG_CANNOT_SET_DIRECTION_PIN 37+MSG_OFFSET + _Cannot_set_ _direction_ _pin_ _to_ _SEP_ +#define MSG_STEPPER_VERSION 38+MSG_OFFSET + "StepperDemo Version " VERSION + _NL_ _SEP_ +#define MSG_ATTACH_PULSE_COUNTER 39+MSG_OFFSET + _attach " " _pulse_counter_ _SEP_ +#define MSG_ERROR_ATTACH_PULSE_COUNTER 40+MSG_OFFSET + _ERROR_ _attach "ing " _pulse_counter_ _NL_ _SEP_ +#define MSG_ERROR_INVALID_VALUE 41+MSG_OFFSET + _ERROR_ "invalid value" _NL_ _SEP_ +#define MSG_ERROR_MOVE_ERR_ACCELERATION_IS_UNDEFINED__MINUS_3 42+MSG_OFFSET + _ERROR_ _acceleration_ _is_not_defined_nl _SEP_ +#define MSG_ERROR_MOVE_ERR_SPEED_IS_UNDEFINED__MINUS_2 43+MSG_OFFSET + _ERROR_ _speed_ _is_not_defined_nl _SEP_ +#define MSG_ERROR_MOVE_ERR_NO_DIRECTION_PIN__MINUS_1 44+MSG_OFFSET + _ERROR_ "no " _direction_ _pin_ "=> impossible move" _NL_ _SEP_ +#define MSG_MOVE_OK 45+MSG_OFFSET + "OK" _NL_ _SEP_ +#define MSG_STRAY_DIGITAL_READ_TOGGLE 46+MSG_OFFSET + _Toggle_ _erroneous_ _digitalRead_ _to_ _step_pin_ _NL_ _SEP_ +#define MSG_STRAY_DIGITAL_READ_ENABLED 47+MSG_OFFSET + _erroneous_ _digitalRead_ _to_ _step_pin_ "IS ON !!!" _NL_ _SEP_ +#define MSG_LONG_INTERRUPT_BLOCK_TOGGLE 48+MSG_OFFSET + _Toggle_ _erroneous_ "100 µs ISR block" _NL_ _SEP_ +#define MSG_LONG_INTERRUPT_BLOCK_ENABLED 49+MSG_OFFSET + _erroneous_ "100 µs ISR BLOCK IS ON" _NL_ _SEP_ +#define MSG_SET_UNIDIRECTIONAL_STEPPER 50+MSG_OFFSET + _set_ "unidirectional " _stepper _NL_ _SEP_ +#define MSG_CLEAR_PULSE_COUNTER 51+MSG_OFFSET + _clear_ _pulse_counter_ _NL_ _SEP_ +#define MSG_SET_SPEED_TO_HZ 52+MSG_OFFSET + _set_ _speed_ "(" _steps_ "/s) " _to_ _SEP_ +#define MSG_PASS_STATUS 53+MSG_OFFSET + _test_ "passed" _NL_ _SEP_ +#define MSG_TEST_COMPLETED 54+MSG_OFFSET + _test_ "completed" _NL_ _SEP_ +#define MSG_ENTER_CONFIG_MODE 55+MSG_OFFSET + _Enter_ "config " _mode _NL_ _SEP_ +#define MSG_DIRECTION_PIN 56+MSG_OFFSET + _direction_ _pin_ _SEP_ +#define MSG_SET_TO_PIN 57+MSG_OFFSET + _set_ _to_ _pin_ _SEP_ +#define MSG_DISABLED 58+MSG_OFFSET + _disable "d" _NL_ _SEP_ +#define MSG_HIGH_COUNT_UP 59+MSG_OFFSET + _high_counts_ "up" _SEP_ +#define MSG_HIGH_COUNT_DOWN 60+MSG_OFFSET + _high_counts_ "down" _SEP_ +#define MSG_DELAY 61+MSG_OFFSET + _delay_ "in us = " _SEP_ +#define MSG_UNKNOWN_COMMAND 62 + MSG_OFFSET + "Unknown command: " _SEP_ +#define MSG_SET_SPEED_TO_MILLI_HZ 63+MSG_OFFSET + _set_ _speed_ "(" _steps_ "/1000s) " _to_ _SEP_ +#define MSG_ACCELERATION_STATUS 64+MSG_OFFSET + " " _acceleration_ " [" _step "s/s^2]=" _SEP_ +#define MSG_SPEED_STATUS_FREQ 65+MSG_OFFSET + " " _speed_ "[m" _step "/s]=" _SEP_ +#define MSG_SPEED_STATUS_TIME 66+MSG_OFFSET + " " _speed_ "[us/" _step "]=" _SEP_ +#define MSG_LINEAR_ACCELERATION 67+MSG_OFFSET + "linear " _acceleration_ _step "s=" _SEP_ +#define MSG_JUMP_START 68+MSG_OFFSET + "jump start " _step "s=" _SEP_ +#define MSG_USAGE_NORMAL 69+MSG_OFFSET +#define MSG_USAGE_TEST 70+MSG_OFFSET +#define MSG_USAGE_CONFIG 71+MSG_OFFSET +#if MSG_USAGE_CONFIG >= 128+32 +#error "TOO MANY ENTRIES" +#endif + /* USAGE NORMAL */ + _Enter_command_separated_by_space_carriage_return_or_newline_NL + _m1_m2_to_select_stepper_ + ____ "c" ________ _ooo_ _Enter_ _configuration_ _mode _NL_ + ____ "V" _I_speed_I_ _ooo_set_selected_stepper_s_ _speed_ "in us/" _step _NL_ + ____ "H" _I_speed_I_ _ooo_set_selected_stepper_s_ _speed_ "in " _steps_ "/s" _NL_ + ____ "h" _I_speed_I_ _ooo_set_selected_stepper_s_ _speed_ "in " _steps_ "/1000s" _NL_ + ____ "A" _I_accel_I_ _ooo_set_selected_stepper_s_ _acceleration_ _NL_ + ____ "a" _I_accel_I_ _ooo_ _acceleration_ "control with +/-" _acceleration_ "values" _NL_ + ____ "J<" _step "s> " _ooo_set_selected_stepper_s_ "linear " _acceleration_ " for <" _step "s>" _NL_ + ____ "j<" _step "s> " _ooo_set_selected_stepper_s_ "jump start to <" _step "s>" _NL_ + ____ "U" ________ _ooo_ "Update " _selected_stepper "'s " _speed_ "/ " _acceleration_ "while " + "running" _NL_ + ____ "P " _ooo_ _Move_ _selected_stepper " " _to_ "+/- " _position_ _NL_ + ____ "R " ____ _ooo_ _Move_ _selected_stepper " by +/- n " _steps_ _NL_ + ____ "f" ________ _ooo_ _run_ _forward _comma__counting_ "up" _NL_ + ____ "b" ________ _ooo_ _run_ _backward _comma__counting_ "down" _NL_ + ____ "K" ________ _ooo_ "Keep " _selected_stepper " running in current " _direction_ _NL_ + ____ "@ " _ooo_ _set_ _selected_stepper " " _to_ _position_ "(can be " + "negative)" _NL_ + ____ "E" ____ _ooo_set_selected_stepper_s_ _delay_ _from_ _enable_ _to_ _steps_ _NL_ + ____ "D" ____ _ooo_set_selected_stepper_s_ _delay_ _from_ _steps_ _to_ _disable _NL_ + ____ "N" ________ _ooo_ _Turn_ _selected_stepper _output_ "on, " __disable_auto_enable_nl + ____ "F" ________ _ooo_ _Turn_ _selected_stepper _output_ "off," __disable_auto_enable_nl + ____ "O" ________ _ooo_ "Put " _selected_stepper " into auto " _enable_ _mode _NL_ + ____ "S" ________ _ooo_ _stop " " _selected_stepper " with deceleration" _NL_ + ____ "X" ________ _ooo_ "Immediately " _stop " " _stepper " and " _set_ "zero position" _NL_ + ____ "I" ________ _ooo_ _Toggle_ _stepper " info, while any " _stepper " is running" _NL_ +#if !defined(__AVR_ATmega32U4__) + ____ "W" ________ _ooo_ "Blocking wait until " _selected_stepper " is " _stop "ped, will " + "deadlock if " _stepper " never " _stop "s" _NL_ + ____ "w" ____ _ooo_ "Wait time in ms" _NL_ + ____ "+" ________ _ooo_ _Perform_ _one_step_ _forward __of_the_ _selected_stepper _NL_ + ____ "-" ________ _ooo_ _Perform_ _one_step_ _backward __of_the_ _selected_stepper _NL_ + ____ "T" ________ _ooo_ _test_ _select "ed " _stepper " with direct port access" _NL_ +#endif +#if defined(ARDUINO_ARCH_ESP32) + ____ "r" ________ _ooo_ "Call ESP.restart()" _NL_ + ____ "reset" ____ _ooo_ _Perform_ "reset" _NL_ + ____ "p " ____ _ooo_ _attach " " _pulse_counter_ "n<=7" _NL_ + ____ "p,l,h " _ooo_ _attach " " _pulse_counter_ "n<=7 with low,high limits" _NL_ + ____ "pi" ____ _ooo_ "like p with inverted step pulse" _NL_ + ____ "pi,l,h" _NL_ + ____ "pc " ____ _ooo_ _clear_ _pulse_counter_ _NL_ +#endif +#if !defined(__AVR_ATmega32U4__) + ____ "t" ________ _ooo_ _Enter_ _test_ _mode _NL_ + ____ "u" ________ _ooo_ "Unidirectional " _mode " (need reset " _to_ "restore)" _NL_ +#endif +#if defined(ARDUINO_ARCH_AVR) + ____ "r" ________ _ooo_ _Toggle_ _erroneous_ _digitalRead_ __of_the_ _stepper " pin" _NL_ +#endif + ____ "e" ________ _ooo_ _Toggle_ _erroneous_ "long 100us interrupt block" _NL_ + _toggle_print_usage_after_stepper_stop + _print_this_usage_ + _SEP_ + + + /* USAGE TEST */ +#if !defined(SIM_TEST_INPUT) && !defined(__AVR_ATmega32U4__) + _Enter_command_separated_by_space_carriage_return_or_newline_NL + _m1_m2_to_select_stepper_ + ____ "R" ________ _ooo_ "start all " _select "ed tests" _NL_ + ____ "I" ________ _ooo_ _Toggle_ _stepper " info, while " _test_sequence_ "is running" _NL_ + ____ "01 " ____ _ooo_ _select " " _test_sequence_ "01 for " _selected_stepper _NL_ + ____ ":" _NL_ + ____ "14 " ____ _ooo_ _select " " _test_sequence_ "14 for " _selected_stepper _NL_ + ____ "W" ________ _ooo_ "Blocking wait until test is finished" _NL_ + ____ "x" ________ _ooo_ "Exit test mode" _NL_ + _toggle_print_usage_after_stepper_stop + _print_this_usage_ +#endif + _SEP_ + + + /* USAGE CONFIG */ +#if !defined(SIM_TEST_INPUT) && !defined(__AVR_ATmega32U4__) + _Enter_command_separated_by_space_carriage_return_or_newline_NL + _m1_m2_to_select_stepper_ + ____ "d

" ____ _ooo_ _set_ _direction_ _pin_ _NL_ + ____ "d" _NL_ + ____ "d" _NL_ + ________ ________ ________ "p" _ooo_ _pin_ "number" _NL_ + ________ ________ ________ "n" _ooo_ "1: " _high_counts_ "up 0: " _high_counts_ "down" _NL_ + ________ ________ ________ "t" _ooo_ _delay_ _from_ "dir change " _to_ "step in us, 0 means " + "off" _NL_ + ____ "dc " ____ _ooo_ _clear_ _direction_ _pin_ "(unidirectional)" _NL_ + ____ "x" ________ _ooo_ "Exit " _configuration_ _mode _NL_ + _print_this_usage_ +#endif + _SEP_ +; +// clang-format on + +// The preprocessor for .ino is buggy +#include "generic.h" + +void output_msg(uint8_t x) { + char ch; + MSG_TYPE p = messages; + while (x > 0) { + ch = get_char(p); + p++; + if (ch == _SEP_CHAR_) { + x--; + } + } + for (;;) { + ch = get_char(p); + p++; + if (ch == _SEP_CHAR_) { + break; + } + uint8_t y = (uint8_t)(ch ^ 0x80); + if (y <= MSG_USAGE_CONFIG) { + output_msg(y); + } else { + PRINTCH(ch); + } + } +} + +#if !defined(__AVR_ATmega32U4__) +void delay10us() { DELAY_US(10); } +void do3200Steps(uint8_t step) { + for (uint16_t i = 0; i < 3200; i++) { + digitalWrite(step, HIGH); + delay10us(); + if (digitalRead(step) != HIGH) { + output_msg(MSG_STEP_PIN_IS_NOT_HIGH); + } + digitalWrite(step, LOW); + DELAY_US(190); + if (digitalRead(step) != LOW) { + output_msg(MSG_STEP_PIN_IS_NOT_LOW); + } + } +} +void setDirectionPin(uint8_t direction, bool polarity) { + // Pico resets the I/O-Port on pinMode(pin, OUTPUT)... feature ? + // so we move it to test_direct_drive + if (direction != PIN_UNDEFINED) { + digitalWrite(direction, polarity); + delay10us(); + if (digitalRead(direction) != polarity) { + output_msg(MSG_CANNOT_SET_DIRECTION_PIN); + PRINTLN(polarity ? "HIGH" : "LOW"); + } + } +} +void test_direct_drive(const struct stepper_config_s* stepper) { + // Check stepper motor+driver is operational + // This is not done via StepperMotion-Library for test purpose only + uint8_t step = stepper->step; + uint8_t enableLow = stepper->enable_low_active; + uint8_t enableHigh = stepper->enable_high_active; + uint8_t direction = stepper->direction; + bool direction_high_count_up = stepper->direction_high_count_up; + + pinMode(step, OUTPUT); + + if (enableLow != PIN_UNDEFINED) { + digitalWrite(enableLow, LOW); + pinMode(enableLow, OUTPUT); + delay10us(); + if (digitalRead(enableLow) != LOW) { + output_msg(MSG_ENABLE_LOW_PIN_IS_NOT_LOW); + } + } + if (enableHigh != PIN_UNDEFINED) { + digitalWrite(enableHigh, HIGH); + pinMode(enableHigh, OUTPUT); + delay10us(); + if (digitalRead(enableHigh) != HIGH) { + output_msg(MSG_ENABLE_HIGH_PIN_IS_NOT_HIGH); + } + } + if (direction != PIN_UNDEFINED) { + pinMode(direction, OUTPUT); + setDirectionPin(direction, direction_high_count_up); + do3200Steps(step); + setDirectionPin(direction, !direction_high_count_up); + } + do3200Steps(step); + if (enableLow != PIN_UNDEFINED) { + digitalWrite(enableLow, HIGH); + delay10us(); + if (digitalRead(enableLow) != HIGH) { + output_msg(MSG_ENABLE_LOW_PIN_IS_NOT_HIGH); + } + } + if (enableHigh != PIN_UNDEFINED) { + digitalWrite(enableHigh, LOW); + delay10us(); + if (digitalRead(enableHigh) != LOW) { + output_msg(MSG_ENABLE_HIGH_PIN_IS_NOT_LOW); + } + } + // Done +} +#endif + +void setup() { + PRINT_INIT(); +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) || \ + defined(PICO_RP2040) || defined(PICO_RP2350) + PRINTLN("Select pin configuration:"); + for (uint8_t i = 0; i < NUM_CONFIGS; i++) { + PRINT(" "); + PRINTU8(i); + PRINT(": "); + PRINTLN(stepper_configs[i].name); + } + PRINTLN("Press number to select, else 0"); + uint8_t selected_config = 0; + uint32_t start = MILLIS(); + while (MILLIS() - start < 5000) { + char ch = 0; + POLL_CHAR_IF_ANY(ch); + if (ch >= '0' && ch <= '9') { + uint8_t n = ch - '0'; + if (n < NUM_CONFIGS) { + selected_config = n; + } + break; + } +#if defined(ESP_PLATFORM) && !defined(ARDUINO_ARCH_ESP32) + DELAY_MS(10); + esp_task_wdt_reset(); +#else + delay(10); +#endif + } + active_stepper_config = stepper_configs[selected_config].config; + PRINT("Using config "); + PRINTU8(selected_config); + PRINT(": "); + PRINTLN(stepper_configs[selected_config].name); +#else + active_stepper_config = stepper_config; +#endif +#if defined(ARDUINO_ARCH_ESP32) + printf("LOG start\n"); + esp_log_level_set("*", ESP_LOG_INFO); + esp_log_level_set("rmt", ESP_LOG_INFO); + ESP_LOGI("StepperDemo", "Started INFO"); + PRINTLN(""); +#endif +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) + PRINT("ESP-IDF: "); + PRINTI16((int16_t)ESP_IDF_VERSION_MAJOR); + PRINTCH('.'); + PRINTI16((int16_t)ESP_IDF_VERSION_MINOR); + PRINTLN(""); +#endif + +#ifndef __AVR_ATmega32U4__ + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + test_seq[i].test = NULL; + } +#endif + + output_msg(MSG_STEPPER_VERSION); +#ifdef F_CPU + PRINT(" F_CPU="); + PRINTU32(F_CPU); + PRINTLN(""); +#endif + PRINT(" TICKS_PER_S="); + PRINTU32((uint32_t)TICKS_PER_S); + PRINTLN(""); + PRINT(" Steppers="); + PRINTU8(MAX_STEPPER); + PRINTLN(""); + + // If you are not sure, that the stepper hardware is working, + // then try first direct port manipulation and uncomment the next line. + // Alternatively use e.g. M1 T by serial command + // test_direct_drive(&active_stepper_config[0]); + + // delay(10000); + engine.init(); + + if (led_pin != PIN_UNDEFINED) { + engine.setDebugLed(led_pin); + } + + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + StepperMotion* s = NULL; + const struct stepper_config_s* config = &active_stepper_config[i]; + if (config->step != PIN_UNDEFINED) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + s = engine.stepperConnectToPin(config->step, config->driver_type); +#else + s = engine.stepperConnectToPin(config->step); +#endif + if (s) { + s->setDirectionPin(config->direction, config->direction_high_count_up, + config->dir_change_delay); + s->setEnablePin(config->enable_low_active, true); + s->setEnablePin(config->enable_high_active, false); + s->setAutoEnable(config->auto_enable); + s->setDelayToEnable(config->on_delay_us); + s->setDelayToDisable(config->off_delay_ms); + } else { + break; + } + } else { + break; + } + steppers[i] = s; + } + + usage(); +} + +#ifdef SIM_TEST_INPUT +const char* input = SIM_TEST_INPUT + " "; // final space is too easy forgotten in platformio.ini test +#else +const char* input = NULL; +#endif +uint8_t write_ptr = 0; +uint8_t read_ptr = 0; +char in_buffer[256]; // This allows to let in/out_ptr wrap around +uint8_t out_ptr = 0; +char out_buffer[256]; +bool stopped = true; +bool verbose = true; +bool usage_info = true; +bool speed_in_milli_hz = false; +uint32_t last_time = 0; +int16_t selected = 0; +uint32_t pause_ms = 0; +uint32_t pause_start = 0; +#if defined(ARDUINO_ARCH_AVR) +bool simulate_digitalRead_error = false; +#endif +bool simulate_blocked_ISR = false; + +void info(StepperMotion* s, bool long_info) { + PRINTCH('@'); +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + if (s->pulseCounterAttached()) { + int16_t pcnt_pos_1 = s->readPulseCounter(); + int32_t pos = s->getCurrentPosition(); + int16_t pcnt_pos_2 = s->readPulseCounter(); + PRINTI32(pos); + PRINT(" ["); + PRINTI16(pcnt_pos_1); + PRINTCH(']'); + if (pcnt_pos_1 != pcnt_pos_2) { + PRINT(" ["); + PRINTI16(pcnt_pos_2); + PRINTCH(']'); + } + } else { + int32_t pos = s->getCurrentPosition(); + PRINTI32(pos); + } +#else + int32_t pos = s->getCurrentPosition(); + PRINTI32(pos); +#endif + if (s->isRunning()) { + if (s->isRunningContinuously()) { + PRINT(" nonstop"); + } else { + PRINT(" => "); + PRINTI32(s->targetPos()); + } + PRINT(" QueueEnd="); + PRINTI32(s->getPositionAfterCommandsCompleted()); + PRINT(" v="); + if (speed_in_milli_hz) { + PRINTI32(s->getCurrentSpeedInMilliHz()); + PRINT("mSteps/s"); + } else { + PRINTU32(s->getPeriodInUsAfterCommandsCompleted()); + PRINT("us/"); + PRINTU32(s->getPeriodInTicksAfterCommandsCompleted()); + PRINT("ticks"); + } + if (s->isRampGeneratorActive()) { + switch (s->rampState() & RAMP_STATE_MASK) { + case RAMP_STATE_IDLE: + PRINT(" IDLE "); + break; + case RAMP_STATE_ACCELERATE: + PRINT(" ACC "); + break; + case RAMP_STATE_DECELERATE: + PRINT(" RED "); // Reduce + break; + case RAMP_STATE_COAST: + PRINT(" COAST"); + break; + case RAMP_STATE_REVERSE: + PRINT(" REV "); + break; + default: + PRINTU8(s->rampState()); + } + } else { + PRINT(" MANU"); + } + } else { + if (long_info) { + output_msg(MSG_ACCELERATION_STATUS); + PRINTU32(s->getAcceleration()); + if (speed_in_milli_hz) { + output_msg(MSG_SPEED_STATUS_FREQ); + PRINTU32(s->getSpeedInMilliHz()); + } else { + output_msg(MSG_SPEED_STATUS_TIME); + PRINTU32(s->getSpeedInUs()); + } + } + } + PRINTCH(' '); +} + +void stepper_info() { + output_info(false); + if (simulate_blocked_ISR) { + output_msg(MSG_LONG_INTERRUPT_BLOCK_ENABLED); + } +#if defined(ARDUINO_ARCH_AVR) + if (simulate_digitalRead_error) { + output_msg(MSG_STRAY_DIGITAL_READ_ENABLED); + } +#endif +} + +void usage() { + switch (mode) { + case normal: + output_msg(MSG_USAGE_NORMAL); + break; + case test: + output_msg(MSG_USAGE_TEST); + break; + case config: + output_msg(MSG_USAGE_CONFIG); + break; + } + stepper_info(); +} + +void output_info(bool only_running) { + bool need_ln = false; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (steppers[i]) { + if (!only_running) { + if (i == selected) { + PRINT(">> "); + } else { + PRINT(" "); + } + } + if (!only_running || steppers[i]->isRunning()) { + PRINTCH('M'); + PRINTU8(i + 1); + PRINT(": "); + info(steppers[i], !only_running); +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (!steppers[i]->isRunning()) { + PRINT(" "); + PRINT(steppers[i]->driverTypeString()); + } +#endif + if (!only_running) { + PRINTLN(""); + } else { + need_ln = true; + } + } + } + } + if (need_ln) { + PRINTLN(""); + } +} + +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) +void esp_reset() { +#if ESP_IDF_VERSION_MAJOR >= 5 + const esp_task_wdt_config_t wdt_config = { + .timeout_ms = 1, .idle_core_mask = 1, .trigger_panic = true}; + + esp_task_wdt_reconfigure(&wdt_config); +#else + esp_task_wdt_init(1, true); + esp_task_wdt_add(NULL); +#endif + while (true) { + } +} +#endif + +#define MODE(mode, CMD) ((mode << 8) + CMD) + +int32_t val_n[3]; +int8_t get_val1_val2_val3(const char* cmd) { + char* endptr; + for (uint8_t i = 0; i < 3; i++) { + val_n[i] = strtol(cmd, &endptr, 10); + if (endptr == cmd) { + return -1; + } + cmd = endptr; + if (*cmd == 0) { + return i + 1; + } + if ((i < 2) && (*cmd++ != ',')) { + return -1; + } + } + return -1; +} + +bool process_cmd(const char* cmd) { + StepperMotion* stepper_selected = steppers[selected]; + uint16_t s = *cmd++; + char* endptr; + int8_t res; +#if !defined(__AVR_ATmega32U4__) + int8_t gv; +#endif + switch (MODE(mode, s)) { + case MODE(normal, 'M'): + case MODE(test, 'M'): + case MODE(config, 'M'): + if (get_val1_val2_val3(cmd) == 1) { + if ((val_n[0] > 0) && (val_n[0] <= (int32_t)MAX_STEPPER) && + steppers[val_n[0] - 1] != NULL) { + output_msg(MSG_SELECT_STEPPER); + selected = val_n[0] - 1; + PRINTI16(selected + 1); + PRINTLN(""); + return true; + } + } + break; + case MODE(normal, 'r'): +#if defined(ARDUINO_ARCH_ESP32) || defined(ESP_PLATFORM) + if (strcmp(cmd, "eset") == 0) { + PRINTLN("ESP reset"); + esp_reset(); + } + if (*cmd == 0) { +#if defined(ARDUINO_ARCH_ESP32) + PRINTLN("ESP restart"); + ESP.restart(); +#else + esp_reset(); +#endif + } +#endif +#if defined(ARDUINO_ARCH_AVR) + if (*cmd == 0) { + output_msg(MSG_STRAY_DIGITAL_READ_TOGGLE); + simulate_digitalRead_error ^= true; + return true; + } +#endif + break; + case MODE(normal, 'I'): + case MODE(test, 'I'): + if (*cmd == 0) { + output_msg(MSG_TOGGLE_MOTOR_INFO); + verbose = !verbose; + return true; + } + break; + case MODE(normal, 'Q'): + case MODE(test, 'Q'): + if (*cmd == 0) { + output_msg(MSG_TOGGLE_USAGE_INFO); + usage_info = !usage_info; + return true; + } + break; + case MODE(normal, '?'): + case MODE(test, '?'): + case MODE(config, '?'): + if (*cmd == 0) { + usage(); + return true; + } + break; + case MODE(normal, 't'): + if (*cmd == 0) { + output_msg(MSG_ENTER_TEST_MODE); + mode = test; + usage(); + return true; + } + break; + case MODE(normal, 'c'): + if (*cmd == 0) { + output_msg(MSG_ENTER_CONFIG_MODE); + mode = config; + usage(); + return true; + } + break; + case MODE(normal, 'e'): + if (*cmd == 0) { + output_msg(MSG_LONG_INTERRUPT_BLOCK_TOGGLE); + simulate_blocked_ISR ^= true; + return true; + } + break; + case MODE(normal, 'A'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_SET_ACCELERATION_TO); + PRINTI32(val_n[0]); + PRINTLN(""); + res = stepper_selected->setAcceleration(val_n[0]); + if (res < 0) { + output_msg(MSG_ERROR_INVALID_VALUE); + } + return true; + } + break; + case MODE(normal, 'J'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_LINEAR_ACCELERATION); + PRINTI32(val_n[0]); + PRINTLN(""); + stepper_selected->setLinearAcceleration(val_n[0]); + return true; + } + break; + case MODE(normal, 'j'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_JUMP_START); + PRINTI32(val_n[0]); + PRINTLN(""); + stepper_selected->setJumpStart(val_n[0]); + return true; + } + break; + case MODE(normal, 'V'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + speed_in_milli_hz = false; + output_msg(MSG_SET_SPEED_TO_US); + PRINTI32(val_n[0]); + PRINTLN(""); + res = stepper_selected->setSpeedInUs(val_n[0]); + if (res < 0) { + output_msg(MSG_ERROR_INVALID_VALUE); + } + return true; + } + break; + case MODE(normal, 'H'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + speed_in_milli_hz = true; + output_msg(MSG_SET_SPEED_TO_HZ); + PRINTI32(val_n[0]); + PRINTLN(""); + res = stepper_selected->setSpeedInHz(val_n[0]); + if (res < 0) { + output_msg(MSG_ERROR_INVALID_VALUE); + } + return true; + } + break; + case MODE(normal, 'h'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + speed_in_milli_hz = true; + output_msg(MSG_SET_SPEED_TO_MILLI_HZ); + PRINTI32(val_n[0]); + PRINTLN(""); + res = stepper_selected->setSpeedInMilliHz(val_n[0]); + if (res < 0) { + output_msg(MSG_ERROR_INVALID_VALUE); + } + return true; + } + break; + case MODE(normal, 'a'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_SET_ACCELERATION_TO); + PRINTI32(val_n[0]); + PRINTLN(""); + res = + static_cast(stepper_selected->moveByAcceleration(val_n[0])); + output_msg(MSG_MOVE_OK + res); + return true; + } + break; + case MODE(normal, 'R'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_MOVE_STEPS); + PRINTI32(val_n[0]); + PRINTLN(""); + res = static_cast(stepper_selected->move(val_n[0])); + output_msg(MSG_MOVE_OK + res); + return true; + } + break; + case MODE(normal, 'P'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_MOVE_TO_POSITION); + PRINTI32(val_n[0]); + PRINTLN(""); + res = static_cast(stepper_selected->moveTo(val_n[0])); + output_msg(MSG_MOVE_OK + res); + return true; + } + break; + case MODE(normal, '@'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_SET_POSITION); + PRINTI32(val_n[0]); + PRINTLN(""); + stepper_selected->setCurrentPosition(val_n[0]); + return true; + } + break; + case MODE(normal, 'E'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_SET_ENABLE_TIME); + PRINTI32(val_n[0]); + PRINTLN(""); + res = static_cast(stepper_selected->setDelayToEnable(val_n[0])); + output_msg(MSG_RETURN_CODE); + PRINTU8(res); + PRINTLN(""); + return true; + } + break; + case MODE(normal, 'D'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + output_msg(MSG_SET_DISABLE_TIME); + PRINTI32(val_n[0]); + PRINTLN(""); + stepper_selected->setDelayToDisable(val_n[0]); + return true; + } + break; + case MODE(normal, 'w'): + val_n[0] = strtol(cmd, &endptr, 10); + if (*endptr == 0) { + PRINTI32(val_n[0]); + output_msg(MSG_WAIT_MS); + pause_ms = val_n[0]; + pause_start = MILLIS(); + return true; + } + break; +#if !defined(__AVR_ATmega32U4__) + case MODE(config, 'd'): + if (strcmp(cmd, "c") == 0) { + output_msg(MSG_DISABLED); + stepper_selected->setDirectionPin(PIN_UNDEFINED); + return true; + } + gv = get_val1_val2_val3(cmd); + switch (gv) { + case 1: + output_msg(MSG_DIRECTION_PIN); + output_msg(MSG_SET_TO_PIN); + PRINTI32(val_n[0]); + PRINTLN(""); + stepper_selected->setDirectionPin(val_n[0]); + return true; + case 2: + case 3: + output_msg(MSG_DIRECTION_PIN); + output_msg(MSG_SET_TO_PIN); + PRINTI32(val_n[0]); + PRINTLN(""); + output_msg(MSG_DIRECTION_PIN); + if (val_n[1] != 0) { + output_msg(MSG_HIGH_COUNT_DOWN); + } else { + output_msg(MSG_HIGH_COUNT_UP); + } + PRINTLN(""); + if (gv == 2) { + stepper_selected->setDirectionPin(val_n[0], val_n[1]); + } else { + output_msg(MSG_DELAY); + PRINTI32(val_n[2]); + PRINTLN(""); + stepper_selected->setDirectionPin(val_n[0], val_n[1], val_n[2]); + } + return true; + default: + break; + } + break; +#endif + case MODE(normal, 'N'): + if (*cmd == 0) { + output_msg(MSG_OUTPUT_DRIVER_ON); + stepper_selected->setAutoEnable(false); + stepper_selected->enableOutputs(); + return true; + } + break; + case MODE(normal, 'F'): + if (*cmd == 0) { + output_msg(MSG_OUTPUT_DRIVER_OFF); + stepper_selected->setAutoEnable(false); + stepper_selected->disableOutputs(); + return true; + } + break; + case MODE(normal, 'O'): + if (*cmd == 0) { + output_msg(MSG_OUTPUT_DRIVER_AUTO); + stepper_selected->setAutoEnable(true); + return true; + } + break; + case MODE(normal, 'S'): + if (*cmd == 0) { + output_msg(MSG_STOP); + stepper_selected->stopMove(); + return true; + } + break; + case MODE(normal, 'K'): + if (*cmd == 0) { + output_msg(MSG_KEEP_RUNNING); + stepper_selected->keepRunning(); + return true; + } + break; + case MODE(normal, 'f'): + if (*cmd == 0) { + output_msg(MSG_RUN_FORWARD); + res = static_cast(stepper_selected->runForward()); + output_msg(MSG_RETURN_CODE); + PRINTU8(res); + PRINTLN(""); + return true; + } + break; + case MODE(normal, 'b'): + if (*cmd == 0) { + output_msg(MSG_RUN_BACKWARD); + res = static_cast(stepper_selected->runBackward()); + output_msg(MSG_RETURN_CODE); + PRINTU8(res); + PRINTLN(""); + return true; + } + break; + case MODE(normal, 'X'): + if (*cmd == 0) { + output_msg(MSG_IMMEDIATE_STOP); + stepper_selected->forceStopAndNewPosition(0); + return true; + } + break; + case MODE(normal, 'U'): + if (*cmd == 0) { + output_msg(MSG_UPDATE_SPEED_ACCELERATION); + stepper_selected->applySpeedAcceleration(); + return true; + } + break; + case MODE(normal, 'u'): + if (*cmd == 0) { + output_msg(MSG_SET_UNIDIRECTIONAL_STEPPER); + stepper_selected->setDirectionPin(PIN_UNDEFINED); + return true; + } + break; + case MODE(normal, 'W'): + case MODE(test, 'W'): + if (*cmd == 0) { +#ifdef SIM_TEST_INPUT + if (stepper_selected->isRunning() || test_ongoing) { + read_ptr -= 2; + } +#else + output_msg(MSG_BLOCKING_WAIT); + if (!stepper_selected->isRunningContinuously() || + stepper_selected->isStopping()) { + // Wait for stepper stop + while (stepper_selected->isRunning()) { + // do nothing +#if !defined(ARDUINO_ARCH_ESP32) && defined(ESP_PLATFORM) + esp_task_wdt_reset(); + DELAY_MS(2); +#endif + } + PRINTLN("STOPPED"); + } +#endif + return true; + } + break; +#if !defined(__AVR_ATmega32U4__) + case MODE(normal, 'T'): + if (*cmd == 0) { + if (!stepper_selected->isRunning()) { + output_msg(MSG_TEST_DIRECT_DRIVE); + stepper_selected->detachFromPin(); + test_direct_drive(&active_stepper_config[selected]); + stepper_selected->reAttachToPin(); + } + return true; + } + break; +#endif + case MODE(normal, '+'): + if (*cmd == 0) { + if (!stepper_selected->isRunning()) { + stepper_selected->forwardStep(true); + output_msg(MSG_STEPPED_FORWARD); + } + return true; + } + break; + case MODE(normal, '-'): + if (*cmd == 0) { + if (!stepper_selected->isRunning()) { + stepper_selected->backwardStep(true); + output_msg(MSG_STEPPED_BACKWARD); + } + return true; + } + break; + case MODE(test, 'x'): + case MODE(config, 'x'): + if (*cmd == 0) { + output_msg(MSG_EXIT_TO_MAIN_MENU); + test_ongoing = false; + mode = normal; + usage(); + return true; + } + break; + case MODE(test, 'R'): + if (*cmd == 0) { + output_msg(MSG_RUN_TESTS); + test_ongoing = true; + return true; + } + break; +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + case MODE(normal, 'p'): + if (strcmp(cmd, "c") == 0) { + output_msg(MSG_CLEAR_PULSE_COUNTER); + stepper_selected->clearPulseCounter(); + return true; + } + gv = 0; + if (*cmd == 'i') { + gv = 1; + cmd++; + } + if (get_val1_val2_val3(cmd) == 3) { + output_msg(MSG_ATTACH_PULSE_COUNTER); + PRINTI32(val_n[0]); + PRINTLN(""); + if (!stepper_selected->attachToPulseCounter( + val_n[0], val_n[1], val_n[2], PIN_UNDEFINED, gv != 0)) { + output_msg(MSG_ERROR_ATTACH_PULSE_COUNTER); + } + return true; + } + if (get_val1_val2_val3(cmd) == 1) { + output_msg(MSG_ATTACH_PULSE_COUNTER); + PRINTI32(val_n[0]); + PRINTLN(""); + if (!stepper_selected->attachToPulseCounter(val_n[0], -16384, 16384, + PIN_UNDEFINED, gv != 0)) { + output_msg(MSG_ERROR_ATTACH_PULSE_COUNTER); + } + return true; + } + break; +#endif + case MODE(test, '0'): + case MODE(test, '1'): + for (uint8_t i = 0; i < NUM_TEST_SEQUENCE; i++) { + const struct test_seq_def_s* ts = &test_sequence[i]; + if (strcmp(out_buffer, ts->code) == 0) { + output_msg(MSG_SELECT_TEST_SEQUENCE); + PRINTLN(out_buffer); + test_seq[selected].test = ts->test; + test_seq[selected].state = 0; + return true; + } + } + break; + } + + return false; +} + +void loop() { + char ch = 0; + if (input == NULL) { + POLL_CHAR_IF_ANY(ch) + } else { + ch = *input; + if (ch == 0) { + if (read_ptr == write_ptr) { + input = NULL; +#ifdef SIM_TEST_INPUT + delay(1000); + noInterrupts(); + sleep_cpu(); +#endif + } + } else { + input++; + } + } + + if (ch != 0) { + if ((uint8_t)(write_ptr + 1) == read_ptr) { + read_ptr++; + } + in_buffer[write_ptr++] = ch; + } + if (pause_ms > 0) { + if ((uint32_t)(MILLIS() - pause_start) >= pause_ms) { + pause_ms = 0; + output_msg(MSG_WAIT_COMPLETE); + } + } else if (read_ptr != write_ptr) { + ch = in_buffer[read_ptr++]; + if ((ch != ' ') && (ch != '\n') && (ch != '\r')) { + if (out_ptr == 255) { + out_ptr = 0; + } + out_buffer[out_ptr++] = ch; + } else if ((ch == ' ') || (ch == '\n') || (ch == '\r')) { + out_buffer[out_ptr] = 0; + + if (out_ptr > 0) { + if (!process_cmd(out_buffer)) { + output_msg(MSG_UNKNOWN_COMMAND); + PRINTLN(out_buffer); + } + } + out_ptr = 0; + } + } + + uint32_t ms = MILLIS(); + +#if defined(ARDUINO_ARCH_AVR) + if (simulate_digitalRead_error) { + digitalRead(stepPinStepperA); + digitalRead(stepPinStepperB); +#ifdef stepPinStepperC + digitalRead(stepPinStepperC); +#endif + } +#endif + if (simulate_blocked_ISR) { + if ((ms & 0xff) < 0x40) { + fasDisableInterrupts(); + DELAY_US(100); + fasEnableInterrupts(); + } + } + + if (mode == test) { + if (test_ongoing) { + bool finished = true; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + struct test_seq_s* s = &test_seq[i]; + if ((s->test != NULL) && (s->state != TEST_STATE_ERROR)) { + bool res = s->test(steppers[i], &test_seq[i], ms); + if (res) { + s->test = NULL; + } + finished &= res; + } + } + if (finished) { + test_ongoing = false; + bool test_failed = false; + stepper_info(); + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + struct test_seq_s* s = &test_seq[i]; + s->test = NULL; + if (s->state == TEST_STATE_ERROR) { + test_failed = true; + } + } + if (test_failed) { + output_msg(MSG_FAILED_STATUS); + } else { + output_msg(MSG_PASS_STATUS); + } + output_msg(MSG_TEST_COMPLETED); + } else { + uint32_t now = MILLIS(); + if (now - last_time >= 100) { + if (verbose) { + output_info(true); + } + last_time = now; + } + } + } + } else { + bool running = false; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (steppers[i]) { + running |= steppers[i]->isRunning(); + } + } + if (running) { + if (ms - last_time >= 100) { + if (verbose) { + output_info(true); + } + last_time = ms; + } + } + if (!stopped && !running) { + output_info(true); + if (usage_info) { + usage(); + } + } + stopped = !running; + } +} + +#ifdef NEED_APP_MAIN +#include "hal/wdt_hal.h" +extern "C" void app_main() { +#if ESP_IDF_VERSION_MAJOR >= 5 + esp_task_wdt_deinit(); + esp_task_wdt_config_t config = { + .timeout_ms = 1000, .idle_core_mask = 0, .trigger_panic = true}; + esp_task_wdt_init(&config); +#else + esp_task_wdt_init(1000, true); + esp_task_wdt_add(NULL); +#endif + esp_task_wdt_add(NULL); + + printf("Non-arduino version\n"); + setup(); + while (true) { + loop(); + esp_task_wdt_reset(); + DELAY_MS(2); + } +} +#endif diff --git a/examples/StepperDemo/StepperPins_avr.h b/examples/StepperDemo/StepperPins_avr.h new file mode 100644 index 0000000..2bdb44a --- /dev/null +++ b/examples/StepperDemo/StepperPins_avr.h @@ -0,0 +1,104 @@ +#ifndef STEPPER_PINS_AVR_H +#define STEPPER_PINS_AVR_H + +#include "StepperConfig.h" + +#if (defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || \ + defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) +// Example hardware configuration for Arduino Nano +// Please adapt to your configuration +const uint8_t led_pin = 13; // turn off with PIN_UNDEFINED +const struct stepper_config_s stepper_config[MAX_STEPPER] = { + { + // stepper 1 shall be connected to OC1A + step : stepPinStepper1A, + enable_low_active : 6, + enable_high_active : PIN_UNDEFINED, + direction : 5, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + { + // stepper 2 shall be connected to OC1B + step : stepPinStepper1B, + enable_low_active : 8, + enable_high_active : PIN_UNDEFINED, + direction : 7, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }}; +#elif defined(__AVR_ATmega2560__) +// Example hardware configuration for Arduino ATmega2560 +// Please adapt to your configuration +const uint8_t led_pin = PIN_UNDEFINED; // turn off with PIN_UNDEFINED +const struct stepper_config_s stepper_config[MAX_STEPPER] = { + { + step : stepPinStepperA, + enable_low_active : 19, + enable_high_active : PIN_UNDEFINED, + direction : 21, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + { + step : stepPinStepperB, + enable_low_active : 18, + enable_high_active : PIN_UNDEFINED, + direction : 20, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }, + { + // stepper 3 shall be connected to OC4C + step : stepPinStepperC, + enable_low_active : 43, + enable_high_active : PIN_UNDEFINED, + direction : 42, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }}; +#elif defined(__AVR_ATmega32U4__) +// Example hardware configuration for Arduino ATmega32u4 +// Please adapt to your configuration +const uint8_t led_pin = PIN_UNDEFINED; // turn off with PIN_UNDEFINED +const struct stepper_config_s stepper_config[MAX_STEPPER] = { + { + step : stepPinStepperA, + enable_low_active : 16, + enable_high_active : PIN_UNDEFINED, + direction : 26, // PB4 + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + { + step : stepPinStepperB, + enable_low_active : 15, + enable_high_active : PIN_UNDEFINED, + direction : 14, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }}; +#endif + +#endif diff --git a/examples/StepperDemo/StepperPins_esp32.h b/examples/StepperDemo/StepperPins_esp32.h new file mode 100644 index 0000000..42c0faf --- /dev/null +++ b/examples/StepperDemo/StepperPins_esp32.h @@ -0,0 +1,281 @@ +#ifndef STEPPER_PINS_ESP32_H +#define STEPPER_PINS_ESP32_H + +#include "StepperConfig.h" + +const uint8_t led_pin = PIN_UNDEFINED; + +// clang-format off + // Test-HW + // Position 01 linked to atmega nano + // 2: Enable Left Pin 13 GPIO13 , DIR Right Pin 7 GPIO18, Step Right Pin 13 GPIO15 + // 3: Enable Left Pin 12 GPIO12 , DIR Right Pin 6 GPIO19, Step Right Pin 12 GPIO2 blue LED + // 4: Enable Left Pin 11 GPIO14 , DIR Right Pin 5 GPIO21, Step Right Pin 11 GPIO4 + // 5: Enable Left Pin 10 GPIO27 , DIR Right Pin 4 GPIO3 RX0, Step Right Pin 10 GPIO16 RX2 + // 6: Enable Left Pin 9 GPIO26 A9, DIR Right Pin 3 GPIO1 TX0, Step Right Pin 9 GPIO17 TX2 + // 7: Enable Left Pin 8 GPIO25 A8, DIR Right Pin 2 GPIO22, Step Right Pin 8 GPIO5 + // ALL Enable: Right Pin 1 GPIO23 + // Left Pin 15: +5V +// clang-format on +const struct stepper_config_s esp32_config_0[] = { + { + step : 17, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 50, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 15, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#if MAX_STEPPER > 2 + { + step : 2, + enable_low_active : 12, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 5, + enable_low_active : 25, + enable_high_active : PIN_UNDEFINED, + direction : 22, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#endif +#if MAX_STEPPER > 4 + { + step : 16, + enable_low_active : 27, + enable_high_active : PIN_UNDEFINED, + direction : 21, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 4, + enable_low_active : 14, + enable_high_active : PIN_UNDEFINED, + direction : 21, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#endif +#if MAX_STEPPER > 6 + { + step : 14, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 23, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#endif +#if MAX_STEPPER > 8 + { + step : 32, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 33, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : PIN_UNDEFINED, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#endif +#if MAX_STEPPER == 14 + { + step : 25, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 26, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 22, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 21, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, +#endif + STEPPER_CONFIG_END}; +const struct stepper_config_s esp32_config_1[] = { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(QUEUES_RMT) && \ + (QUEUES_RMT > 0) + { + step : 17, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0, + driver_type : DRIVER_RMT, + }, +#endif +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_ESP32_I2S) && \ + defined(QUEUES_I2S_DIRECT) && (QUEUES_I2S_DIRECT > 0) + { + step : 15, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0, + driver_type : DRIVER_I2S_DIRECT, + }, +#endif +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(QUEUES_MCPWM_PCNT) && \ + (QUEUES_MCPWM_PCNT > 0) + { + step : 2, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0, + driver_type : DRIVER_MCPWM_PCNT, + }, +#endif + STEPPER_CONFIG_END}; +#define NUM_CONFIGS 2 +const struct stepper_config_set_s stepper_configs[NUM_CONFIGS] = { + {"Test-HW", esp32_config_0}, + {"Driver-Types", esp32_config_1}, +}; + +#endif diff --git a/examples/StepperDemo/StepperPins_esp32C3.h b/examples/StepperDemo/StepperPins_esp32C3.h new file mode 100644 index 0000000..9cffb9d --- /dev/null +++ b/examples/StepperDemo/StepperPins_esp32C3.h @@ -0,0 +1,43 @@ +#ifndef STEPPER_PINS_ESP32C3_H +#define STEPPER_PINS_ESP32C3_H + +#include "StepperConfig.h" + +const uint8_t led_pin = 8; + +const struct stepper_config_s esp32_config_0[] = { + { + step : 6, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : PIN_UNDEFINED, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 50, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 7, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : PIN_UNDEFINED, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + STEPPER_CONFIG_END}; +#define NUM_CONFIGS 1 +const struct stepper_config_set_s stepper_configs[NUM_CONFIGS] = { + {"C3-Test", esp32_config_0}, +}; + +#endif diff --git a/examples/StepperDemo/StepperPins_esp32C6.h b/examples/StepperDemo/StepperPins_esp32C6.h new file mode 100644 index 0000000..e29959f --- /dev/null +++ b/examples/StepperDemo/StepperPins_esp32C6.h @@ -0,0 +1,43 @@ +#ifndef STEPPER_PINS_ESP32C6_H +#define STEPPER_PINS_ESP32C6_H + +#include "StepperConfig.h" + +const uint8_t led_pin = 8; + +const struct stepper_config_s esp32_config_0[] = { + { + step : 6, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 7, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 50, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + { + step : 15, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000, +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + driver_type : DRIVER_DONT_CARE, +#endif + }, + STEPPER_CONFIG_END}; +#define NUM_CONFIGS 1 +const struct stepper_config_set_s stepper_configs[NUM_CONFIGS] = { + {"C6-Test", esp32_config_0}, +}; + +#endif diff --git a/examples/StepperDemo/StepperPins_pico.h b/examples/StepperDemo/StepperPins_pico.h new file mode 100644 index 0000000..b8fdef9 --- /dev/null +++ b/examples/StepperDemo/StepperPins_pico.h @@ -0,0 +1,48 @@ +#ifndef STEPPER_PINS_PICO_H +#define STEPPER_PINS_PICO_H + +#include "StepperConfig.h" + +const uint8_t led_pin = LED_BUILTIN; + +const struct stepper_config_s pico_config_0[] = { + { + step : 14, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 15, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + { + step : 18, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : PIN_UNDEFINED, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + { + step : 19, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : PIN_UNDEFINED, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500000, + off_delay_ms : 5000 + }, + STEPPER_CONFIG_END}; +#define NUM_CONFIGS 1 +const struct stepper_config_set_s stepper_configs[NUM_CONFIGS] = { + {"Default", pico_config_0}, +}; + +#endif diff --git a/examples/StepperDemo/StepperPins_sam.h b/examples/StepperDemo/StepperPins_sam.h new file mode 100644 index 0000000..943e3e9 --- /dev/null +++ b/examples/StepperDemo/StepperPins_sam.h @@ -0,0 +1,79 @@ +#ifndef STEPPER_PINS_SAM_H +#define STEPPER_PINS_SAM_H + +#include "StepperConfig.h" + +// Hardware configuration copied from esp32 board. Not used on due board +// Please adapt to your configuration +const uint8_t led_pin = PIN_UNDEFINED; +const struct stepper_config_s stepper_config[MAX_STEPPER] = { + { + step : 17, + enable_low_active : 26, + enable_high_active : PIN_UNDEFINED, + direction : 18, // was GPIO 1 in conflict with TXD, via wire to Dir of + // next stepper + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 50, + off_delay_ms : 1000 + }, + { + step : 15, + enable_low_active : 13, + enable_high_active : PIN_UNDEFINED, + direction : 18, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000 + }, + { + step : 2, + enable_low_active : 12, + enable_high_active : PIN_UNDEFINED, + direction : 19, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000 + }, + { + step : 5, + enable_low_active : 25, + enable_high_active : PIN_UNDEFINED, + direction : 22, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }, + { + step : 16, + enable_low_active : 27, + enable_high_active : PIN_UNDEFINED, + direction : 21, // was GPIO 3 in conflict with RXD, via wire to GPIO21 + // (Dir next stepper) + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }, + { + step : 4, + enable_low_active : 14, + enable_high_active : PIN_UNDEFINED, + direction : 21, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 5000, + off_delay_ms : 10 + }}; + +#endif diff --git a/examples/StepperDemo/StepperPins_samd.h b/examples/StepperDemo/StepperPins_samd.h new file mode 100644 index 0000000..a1e6965 --- /dev/null +++ b/examples/StepperDemo/StepperPins_samd.h @@ -0,0 +1,69 @@ +#ifndef STEPPER_PINS_SAMD_H +#define STEPPER_PINS_SAMD_H + +#include "StepperConfig.h" + +// Hardware configuration for the Adafruit Feather M4 (SAMD51J19A). +// Step pins need a TCC waveform output in the variant pin table; the +// Feather M4 breaks out TCC0 (pins 0/1/10/11/12/13) and TCC1 (pins 5/6/9). +// Only the first two entries below connect; the remaining ones are placeholders +// for boards that expose more TCC outputs (stepperConnectToPin() returns NULL). +const uint8_t led_pin = PIN_LED_13; +const struct stepper_config_s stepper_config[MAX_STEPPER] = { + { + step : 10, // TCC0/WO[0] + enable_low_active : 21, + enable_high_active : PIN_UNDEFINED, + direction : 23, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 50, + off_delay_ms : 1000 + }, + { + step : 5, // TCC1/WO[0] + enable_low_active : 22, + enable_high_active : PIN_UNDEFINED, + direction : 24, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : true, + on_delay_us : 500, + off_delay_ms : 1000 + }, + { + step : 6, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 12, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0 + }, + { + step : 9, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 11, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0 + }, + { + step : 4, + enable_low_active : PIN_UNDEFINED, + enable_high_active : PIN_UNDEFINED, + direction : 23, + dir_change_delay : 0, + direction_high_count_up : true, + auto_enable : false, + on_delay_us : 0, + off_delay_ms : 0 + }}; + +#endif \ No newline at end of file diff --git a/examples/StepperDemo/generic.h b/examples/StepperDemo/generic.h new file mode 100644 index 0000000..5559b45 --- /dev/null +++ b/examples/StepperDemo/generic.h @@ -0,0 +1,99 @@ +#ifndef GENERIC_H +#define GENERIC_H + +#if defined(ARDUINO_ARCH_AVR) +#include +#endif + +#if defined(ARDUINO_ARCH_AVR) +#define get_char(x) pgm_read_byte(x) +#define MSG_TYPE PGM_P +#elif defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_SAM) || \ + defined(ARDUINO_ARCH_SAMD) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(ESP_PLATFORM) +#define get_char(x) *x +#define MSG_TYPE const char* +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +#define get_char(x) *x +#define MSG_TYPE const char* +#else +#error "Unsupported derivate" +#endif + +#if !defined(ESP_PLATFORM) || defined(ARDUINO_ARCH_ESP32) + +#define PRINT_INIT() Serial.begin(115200); +#define PRINTLN Serial.println +#define PRINTCH Serial.print +#define PRINTU8 Serial.print +#define PRINTU16 Serial.print +#define PRINTI16 Serial.print +#define PRINTU32 Serial.print +#define PRINTI32 Serial.print +#define PRINT Serial.print +#define POLL_CHAR_IF_ANY(ch) \ + if (Serial.available()) { \ + ch = Serial.read(); \ + } +#define MILLIS() millis() +#define DELAY_US(v) delayMicroseconds(v) + +#else + +#include +#include +#include +#include +#include + +const uart_port_t uart_num = UART_NUM_0; + +#define PRINT_INIT() +#ifdef OLD +uart_config_t config; +config.baud_rate = 115200; +config.data_bits = UART_DATA_8_BITS; +config.parity = UART_PARITY_DISABLE; +config.stop_bits = UART_STOP_BITS_1; +config.flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS; +config.rx_flow_ctrl_thresh = 122; +uart_param_config(uart_num, &config); +#endif + +#define PRINTLN puts +#define PRINTU8(v) printf("%" PRIu8, (uint8_t)(v)) +#define PRINTU16(v) printf("%" PRIu16, (uint16_t)(v)) +#define PRINTI16(v) printf("%" PRId16, (int16_t)(v)) +#define PRINTU32(v) printf("%" PRIu32, (uint32_t)(v)) +#define PRINTI32(v) printf("%" PRIi32, (int32_t)(v)) +#define PRINTCH(ch) printf("%c", ch) +#define PRINT(s) printf("%s", s) +#define POLL_CHAR_IF_ANY(ch) \ + { \ + uint8_t _ch = getchar(); \ + if (_ch != 255) { \ + ch = _ch; \ + } \ + } +#ifdef OLD +#define POLL_CHAR_IF_ANY(ch) \ + uint8_t _ch; \ + int n = uart_read_bytes(uart_num, &_ch, 1, 0); \ + if (n == 1) { \ + ch = _ch; \ + } +#endif +#define MILLIS() (esp_timer_get_time() / 1000) +#define DELAY_US(v) std::this_thread::sleep_for(std::chrono::microseconds(v)) +#define NEED_APP_MAIN + +#endif + +#if defined(ESP_PLATFORM) +#define PROGMEM +#define DELAY_MS(v) vTaskDelay(pdMS_TO_TICKS(v)) +#endif + +#endif diff --git a/examples/StepperDemo/test_seq.cpp b/examples/StepperDemo/test_seq.cpp new file mode 100644 index 0000000..b3ab41f --- /dev/null +++ b/examples/StepperDemo/test_seq.cpp @@ -0,0 +1,21 @@ +#include "test_seq.h" + +struct test_seq_def_s test_sequence[NUM_TEST_SEQUENCE] = { + {{'0', '1', 0, 0}, test_seq_01}, + {{'0', '2', 0, 0}, test_seq_02}, + {{'0', '3', 0, 0}, test_seq_03}, + {{'0', '4', 0, 0}, test_seq_04}, + {{'0', '5', 0, 0}, test_seq_05}, + {{'0', '6', 0, 0}, test_seq_06}, + {{'0', '7', 0, 0}, test_seq_07}, + {{'0', '8', 0, 0}, test_seq_08}, + {{'0', '9', 0, 0}, test_seq_09}, + {{'1', '0', 0, 0}, test_seq_10}, + {{'1', '1', 0, 0}, test_seq_11}, + {{'1', '2', 0, 0}, test_seq_12} +#if !defined(__AVR_ATmega32U4__) + , + {{'1', '3', 0, 0}, test_seq_13}, + {{'1', '4', 0, 0}, test_seq_14} +#endif +}; diff --git a/examples/StepperDemo/test_seq.h b/examples/StepperDemo/test_seq.h new file mode 100644 index 0000000..fcd26fa --- /dev/null +++ b/examples/StepperDemo/test_seq.h @@ -0,0 +1,92 @@ +#include "StepperMotion.h" +#include "generic.h" + +#define TEST_STATE_ERROR 0xffff +struct test_seq_s { + bool (*test)(StepperMotion* stepper, struct test_seq_s*, uint32_t time_ms); + uint16_t state; + uint32_t u32_1; + int32_t s32_1; + int16_t s16_1; + int16_t s16_2; +}; + +#if !defined(__AVR_ATmega32U4__) +#define NUM_TEST_SEQUENCE 14 +#else +#define NUM_TEST_SEQUENCE 12 +#endif +extern struct test_seq_def_s { + char code[4]; + bool (*test)(StepperMotion* stepper, struct test_seq_s*, uint32_t time_ms); +} test_sequence[]; + +// a test_seq should return true, if finished. + +// This sequence turns stepper like a clock's second hand +bool test_seq_01(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// Run the stepper towards positive position and back to zero repeatedly +bool test_seq_02(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// same like 02, both different speed/acceleration +bool test_seq_03(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// same like 02, both different speed/acceleration +bool test_seq_04(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// Perform 800 times a single step and then 800 steps back in one command +bool test_seq_05(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// Run 32000 steps with speed changes every 100ms in order to reproduce issue +// #24 +bool test_seq_06(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// measures timing of several moveByAcceleration(). Should stop at position +// zero. (should be started from position 0). +bool test_seq_07(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// is an endless running test to check on esp32, if the generated pulses are +// successfully counted by a second pulse counter. The moves should be all +// executed in one second with alternating direction and varying +// speed/acceleration +bool test_seq_08(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// is an endless running test with starting a ramp with random +// speed/acceleration/direction, which after 1s is stopped with +// forceStopAndNewPosition(). It contains no internal test criteria, but looking +// at the log, the match of generated and sent pulses can be checked. And the +// needed steps for a forceStopAndNewPosition() can be derived out of this +bool test_seq_09(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// runs the stepper forward and every 200 ms changes speed with increasing +// positive speed deltas and then decreasing negative speed deltas. +bool test_seq_10(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// runs the stepper to position 1000000 and back to 0. This tests, if +// getCurrentPosition() is counting monotonously up or down respectively. +bool test_seq_11(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// test case for one stepper to reproduce issue #103 +bool test_seq_12(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// test case for one stepper to reproduce issue #113 +bool test_seq_13(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); + +// Issue370 sampled stroke via moveTimed(). ESP32 pulse counter only: PCNT must +// be -592 and the running ramp must finish in < 1s. +bool test_seq_14(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms); diff --git a/examples/StepperDemo/test_seq_01.cpp b/examples/StepperDemo/test_seq_01.cpp new file mode 100644 index 0000000..5452219 --- /dev/null +++ b/examples/StepperDemo/test_seq_01.cpp @@ -0,0 +1,50 @@ +#include "test_seq.h" + +// u32_1 shall be milliseconds from last tick + +bool test_seq_01(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state & 15) { + case 0: // INIT + stepper->setSpeedInUs(40); + stepper->setAcceleration(1000000); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: // Wait 1s pass + case 3: + case 5: + if (time_ms - seq->u32_1 >= 1000) { + seq->state++; + if ((seq->state >> 4) == 60 / 3) { + seq->state = 7; + } + } + break; + case 2: + case 4: + // second pass, run motor + // 3200steps = 40*53steps + 20*54steps + seq->u32_1 += 1000; + stepper->move(53); + seq->state++; + break; + case 6: + seq->u32_1 += 1000; + stepper->move(54); + seq->state = (seq->state & 0xfff0) + 17; + break; + case 7: + stepper->setSpeedInUs(1000); + stepper->setAcceleration(10000); + stepper->move(-3200); + seq->state++; + break; + case 8: + if (!stepper->isRunning()) { + return true; // finished + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_02.cpp b/examples/StepperDemo/test_seq_02.cpp new file mode 100644 index 0000000..11054f8 --- /dev/null +++ b/examples/StepperDemo/test_seq_02.cpp @@ -0,0 +1,41 @@ +#include "test_seq.h" + +// u32_1 shall be number of steps + +bool test_seq_02(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t) { + int32_t steps = seq->u32_1; + switch (seq->state) { + case 0: // INIT + stepper->setSpeedInUs(40); + stepper->setAcceleration(1000); + seq->u32_1 = 1; + seq->state++; + break; + case 1: + // Turn + stepper->move(steps); + seq->state++; + break; + case 3: + // Turn back + stepper->move(-steps); + seq->state++; + break; + case 2: + case 4: + if (!stepper->isRunning()) { + seq->state++; + } + break; + case 5: + if (seq->u32_1 >= 6400) { + return true; // finished + } + seq->u32_1++; + seq->u32_1 += seq->u32_1 >> 2; + seq->state = 1; + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_03.cpp b/examples/StepperDemo/test_seq_03.cpp new file mode 100644 index 0000000..bdac531 --- /dev/null +++ b/examples/StepperDemo/test_seq_03.cpp @@ -0,0 +1,13 @@ +#include "test_seq.h" + +// u32_1 shall be number of steps + +bool test_seq_03(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t) { + stepper->setSpeedInUs(40); + stepper->setAcceleration(10000); + seq->u32_1 = 1; + seq->state++; + seq->test = test_seq_02; + return false; +} diff --git a/examples/StepperDemo/test_seq_04.cpp b/examples/StepperDemo/test_seq_04.cpp new file mode 100644 index 0000000..bda7512 --- /dev/null +++ b/examples/StepperDemo/test_seq_04.cpp @@ -0,0 +1,13 @@ +#include "test_seq.h" + +// u32_1 shall be number of steps + +bool test_seq_04(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t) { + stepper->setSpeedInUs(40); + stepper->setAcceleration(100000); + seq->u32_1 = 1; + seq->state++; + seq->test = test_seq_02; + return false; +} diff --git a/examples/StepperDemo/test_seq_05.cpp b/examples/StepperDemo/test_seq_05.cpp new file mode 100644 index 0000000..2282665 --- /dev/null +++ b/examples/StepperDemo/test_seq_05.cpp @@ -0,0 +1,42 @@ +#include "test_seq.h" + +// u32_1 shall be milliseconds from last tick +// +// Perform 800 times a single step and then 800 steps back in one command. + +#define DT 200 +bool test_seq_05(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state & 15) { + case 0: // INIT + stepper->setSpeedInUs(40); + stepper->setAcceleration(1000000); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: // Wait 1s pass + if (time_ms - seq->u32_1 >= DT) { + if ((seq->state & 0xfff0) == (16 * 800)) { + seq->state = 7; + stepper->setSpeedInUs(1000); + stepper->setAcceleration(10000); + stepper->move(-800); + break; + } + seq->state++; + } + break; + case 2: + // second pass, run motor + seq->u32_1 += DT; + stepper->move(1); + seq->state += 16 - 1; + break; + case 7: + if (!stepper->isRunning()) { + return true; // finished + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_06.cpp b/examples/StepperDemo/test_seq_06.cpp new file mode 100644 index 0000000..8f94363 --- /dev/null +++ b/examples/StepperDemo/test_seq_06.cpp @@ -0,0 +1,57 @@ +#include "test_seq.h" + +// u32_1 shall be milliseconds from last tick +// +// Run 320000 steps with speed changes every 100ms +// in order to reproduce issue #24 + +#define SPEED_1_US 100 +#define SPEED_2_US 90 +#define SPEED_HOME_US 100 + +bool test_seq_06(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + if (stepper->getPositionAfterCommandsCompleted() > 32000) { + seq->state = TEST_STATE_ERROR; + return true; + } + switch (seq->state) { + case 0: // INIT + stepper->setSpeedInUs(SPEED_1_US); + stepper->setAcceleration(10000); + stepper->move(32000); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if (time_ms - seq->u32_1 >= 100) { + stepper->setSpeedInUs(SPEED_2_US); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 2: + if (time_ms - seq->u32_1 >= 100) { + stepper->setSpeedInUs(SPEED_1_US); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + seq->state--; + } + if (!stepper->isRunning()) { + seq->state = 3; + } + break; + case 3: // Return to start position + stepper->setSpeedInUs(SPEED_HOME_US); + stepper->move(-32000); + seq->state++; + break; + case 4: + if (!stepper->isRunning()) { + return true; // finished + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_07.cpp b/examples/StepperDemo/test_seq_07.cpp new file mode 100644 index 0000000..3ddae0f --- /dev/null +++ b/examples/StepperDemo/test_seq_07.cpp @@ -0,0 +1,63 @@ +#include "test_seq.h" + +// u32_1 shall be milliseconds from last tick +// +bool test_seq_07(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state) { + case 0: // INIT + stepper->setSpeedInUs(40); + stepper->moveByAcceleration(30000); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if ((stepper->rampState() & RAMP_STATE_MASK) == RAMP_STATE_COAST) { + int32_t dt = time_ms - seq->u32_1; + PRINTI32(dt); + PRINTLN(""); + // 805 avr (neu 810 avr), 820: esp32 with rmt, + // 812: esp32 with rmt second channel, 827 with i2s, + // 849: esp32 IDF5/6 RMT translator. Center of 805..849. + if (abs(dt - 827) > 30) { + seq->state = TEST_STATE_ERROR; + return true; + } + stepper->moveByAcceleration(-30000); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 2: + if (time_ms - seq->u32_1 >= 3000) { + stepper->moveByAcceleration(40000); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 3: // Return to start position + if (time_ms - seq->u32_1 >= 1000) { + stepper->moveTo(0); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 4: + if (!stepper->isRunning()) { + int32_t dt = time_ms - seq->u32_1; + PRINTI32(dt); + PRINTLN(""); + if (abs(dt - 1495) > 30) { + seq->state = TEST_STATE_ERROR; + } + PRINTI32(stepper->getPositionAfterCommandsCompleted()); + PRINTLN(""); + if (stepper->getPositionAfterCommandsCompleted() != 0) { + seq->state = TEST_STATE_ERROR; + } + return true; // finished + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_08.cpp b/examples/StepperDemo/test_seq_08.cpp new file mode 100644 index 0000000..f40243a --- /dev/null +++ b/examples/StepperDemo/test_seq_08.cpp @@ -0,0 +1,95 @@ +#include "test_seq.h" + +#if defined(SUPPORT_ESP32_PULSE_COUNTER) +struct command_s { + uint32_t accel; + uint32_t speed; + uint32_t move; +} commands[] = {{.accel = 0, .speed = 0, .move = 0}}; + +int16_t old = 0; + +bool test_seq_08(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state) { + case 0: // INIT + srand(135); + if (!stepper->attachToPulseCounter(7)) { + PRINTLN("Error attaching to pulse counter"); + seq->state = TEST_STATE_ERROR; + return true; + } + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if (!stepper->isRunning()) { + int16_t pcnt = stepper->readPulseCounter(); + int32_t spos = stepper->getPositionAfterCommandsCompleted(); + if ((pcnt & 0x3fff) != (spos & 0x3fff)) { + PRINT("stepper pos="); + PRINTI32(spos); + PRINT(" real pos="); + PRINTI16(pcnt); + PRINTLN(""); + + seq->state = TEST_STATE_ERROR; + return true; + } +#define VMIN 40 +#define VMAX 16384 + uint16_t speed = rand() % (VMAX * 4); + speed = speed >> ((speed % 4) + 2); + speed = speed + VMIN; + +#define AMIN 10 +#define AMAX (4 * 65536) + uint32_t accel = rand() % (AMAX * 4); + accel = accel >> ((accel % 4) + 2); + accel = accel + AMIN; + + // s = a * tr² + v * tc with t = 2*tr+tc + // + // v = a * tr => tr = v/a + // + // s = v²/a + v * (t-2*tr) + // + // = v²/a + v * (t-2*v/a) + // + // = v²/a + v * t - 2*v²/a + // + // = v * t - v²/a + // + // = v * (t - v/a) + // + // = t/tv - 1/(tv²*a) + // + // With t = 1s + int32_t move = 1000000 / speed; + if (move & 2) { + move = -move; + } + + PRINT("speed="); + PRINTU16(speed); + PRINT(" accel="); + PRINTU32(accel); + PRINT(" move="); + PRINTI32(move); + PRINTLN(""); + stepper->setSpeedInUs(speed); + stepper->setAcceleration(accel); + stepper->move(move); + seq->u32_1 = time_ms; + } + break; + } + return false; +} + +#else +bool test_seq_08(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + return test_seq_01(stepper, seq, time_ms); +} +#endif diff --git a/examples/StepperDemo/test_seq_09.cpp b/examples/StepperDemo/test_seq_09.cpp new file mode 100644 index 0000000..6a5814e --- /dev/null +++ b/examples/StepperDemo/test_seq_09.cpp @@ -0,0 +1,82 @@ +#include "test_seq.h" + +bool test_seq_09(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state) { + case 0: // INIT + srand(135); +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + if (!stepper->attachToPulseCounter(7)) { + PRINTLN("Error attaching to pulse counter"); + seq->state = TEST_STATE_ERROR; + return true; + } +#endif + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if (!stepper->isRunning()) { +#define VMIN 40 +#define VMAX 16384L + uint32_t speed = rand() % (VMAX * 4); + speed = speed >> ((speed % 4) + 2); + speed = speed + VMIN; + +#define AMIN 10 +#define AMAX (4 * 65536) + uint32_t accel = rand() % (AMAX * 4); + accel = accel >> ((accel % 4) + 2); + accel = accel + AMIN; + PRINT("speed="); + PRINTU32(speed); + PRINT(" accel="); + PRINTU32(accel); + PRINTLN(""); + stepper->setSpeedInUs(speed); + stepper->setAcceleration(accel); + if (rand() & 1) { + stepper->runForward(); + } else { + stepper->runBackward(); + } + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 2: + if (time_ms - seq->u32_1 >= 1000) { +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + seq->s16_1 = stepper->readPulseCounter(); +#endif + stepper->forceStopAndNewPosition(0); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 3: + if (!stepper->isRunning()) { +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + int16_t old = seq->s16_1; + seq->s16_1 = stepper->readPulseCounter(); + PRINT("Steps needed for stop="); + PRINTU16(old - seq->s16_1); + PRINTLN(""); +#endif + seq->state++; + } + break; + case 4: + if (time_ms - seq->u32_1 >= 100) { +#if defined(SUPPORT_ESP32_PULSE_COUNTER) + if (seq->s16_1 != stepper->readPulseCounter()) { + PRINTLN("Step AFTER stop"); + } +#endif + seq->u32_1 = time_ms; + seq->state = 1; + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_10.cpp b/examples/StepperDemo/test_seq_10.cpp new file mode 100644 index 0000000..0c4c980 --- /dev/null +++ b/examples/StepperDemo/test_seq_10.cpp @@ -0,0 +1,68 @@ +#include "test_seq.h" + +// +// This test sequence is to reproduce issue #44 + +bool test_seq_10(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state) { + case 0: // INIT + stepper->setSpeedInUs(64); + stepper->setAcceleration(1000); + stepper->runForward(); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if (stepper->getPeriodInUsAfterCommandsCompleted() == 64) { + stepper->setAcceleration(100000000); + seq->s16_1 = 0; + seq->s16_2 = 0; + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 2: + if (time_ms - seq->u32_1 >= 200) { + stepper->setSpeedInUs(64 + seq->s16_1); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 3: + if (time_ms - seq->u32_1 >= 200) { + stepper->setSpeedInUs(64); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + if (seq->s16_2 < 10) { + seq->s16_2++; + seq->state = 2; + } else { + seq->s16_1 = -seq->s16_1; + seq->s16_2 = 0; + if (seq->s16_1 >= 0) { + seq->s16_1++; + } + if (seq->s16_1 == 25) { + seq->state = 4; + stepper->setAcceleration(1000); + stepper->applySpeedAcceleration(); + stepper->stopMove(); + } else { + PRINT("Speed changes 64us <=> "); + PRINTU16(64 + seq->s16_1); + PRINTLN("us"); + seq->state = 2; + } + } + } + break; + case 4: + if (!stepper->isRunning()) { + return true; + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_11.cpp b/examples/StepperDemo/test_seq_11.cpp new file mode 100644 index 0000000..f34453a --- /dev/null +++ b/examples/StepperDemo/test_seq_11.cpp @@ -0,0 +1,79 @@ +#include "test_seq.h" + +// +// This test sequence is to reproduce issue #68 + +bool test_seq_11(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t) { + uint32_t prev_pos; + switch (seq->state) { + case 0: // INIT + seq->s32_1 = stepper->getCurrentPosition(); + if (seq->s32_1 != 0) { + seq->state = TEST_STATE_ERROR; + return true; + } + stepper->setSpeedInUs(43); + stepper->setAcceleration(10000); + stepper->moveTo(1000000); + seq->state++; + break; + case 1: + if (!stepper->isRunning()) { + stepper->moveTo(0); + seq->state++; + break; + } + prev_pos = seq->s32_1; + for (uint16_t i = 0; i <= 1000; i++) { + int32_t pos = stepper->getCurrentPosition(); + if (pos < seq->s32_1) { + PRINT("i="); + PRINTU16(i); + if (i != 0) { + PRINT(" prev pos="); + PRINTI32(prev_pos); + } + PRINT(" old pos="); + PRINTI32(seq->s32_1); + PRINT(" curr pos="); + PRINTI32(pos); + PRINTLN(""); + stepper->stopMove(); + seq->state = TEST_STATE_ERROR; + return true; + } + prev_pos = seq->s32_1; + seq->s32_1 = pos; + } + break; + case 2: + if (!stepper->isRunning()) { + return true; + } + prev_pos = seq->s32_1; + for (uint16_t i = 0; i <= 1000; i++) { + int32_t pos = stepper->getCurrentPosition(); + if (pos > seq->s32_1) { + PRINT("i="); + PRINTU16(i); + if (i != 0) { + PRINT(" prev pos="); + PRINTI32(prev_pos); + } + PRINT(" old pos="); + PRINTI32(seq->s32_1); + PRINT(" curr pos="); + PRINTI32(pos); + PRINTLN(""); + stepper->stopMove(); + seq->state = TEST_STATE_ERROR; + return true; + } + prev_pos = seq->s32_1; + seq->s32_1 = pos; + } + break; + } + return false; +} diff --git a/examples/StepperDemo/test_seq_12.cpp b/examples/StepperDemo/test_seq_12.cpp new file mode 100644 index 0000000..a4a7aa9 --- /dev/null +++ b/examples/StepperDemo/test_seq_12.cpp @@ -0,0 +1,73 @@ +#include "test_seq.h" + +// +// This test sequence is to reproduce issue #103 + +bool test_seq_12(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + (void)stepper; + (void)seq; + (void)time_ms; +#if !defined(__AVR_ATmega32U4__) + switch (seq->state) { + case 0: // INIT + stepper->setSpeedInUs(64); + stepper->setAcceleration(1000); + stepper->moveTo(10000000); + seq->u32_1 = time_ms; + seq->state++; + break; + case 1: + if (stepper->getPeriodInUsAfterCommandsCompleted() == 64) { + stepper->setAcceleration(10000); + seq->s16_1 = 0; + seq->s16_2 = 0; + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 2: + if (time_ms - seq->u32_1 >= 20) { + stepper->setSpeedInUs(64 + seq->s16_1); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 3: + if (time_ms - seq->u32_1 >= 20) { + stepper->setSpeedInUs(64); + stepper->applySpeedAcceleration(); + seq->u32_1 = time_ms; + if (seq->s16_2 < 10) { + seq->s16_2++; + seq->state = 2; + } else { + seq->s16_1 = -seq->s16_1; + seq->s16_2 = 0; + if (seq->s16_1 >= 0) { + seq->s16_1++; + } + if (seq->s16_1 >= 10000) { + seq->state = 4; + stepper->setAcceleration(1000); + stepper->applySpeedAcceleration(); + stepper->stopMove(); + } else { + PRINT("Speed changes 64us <=> "); + PRINTU16(64 + seq->s16_1); + PRINTLN("us"); + seq->state = 2; + } + } + } + break; + case 4: + if (!stepper->isRunning()) { + return true; + } + break; + } +#endif + return false; +} diff --git a/examples/StepperDemo/test_seq_13.cpp b/examples/StepperDemo/test_seq_13.cpp new file mode 100644 index 0000000..8046f49 --- /dev/null +++ b/examples/StepperDemo/test_seq_13.cpp @@ -0,0 +1,41 @@ +#include "test_seq.h" + +// +// This test sequence is to reproduce issue #103 + +#if !defined(__AVR_ATmega32U4__) +bool test_seq_13(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + AqeResultCode aqe; + struct stepper_command_s cmd_step = { + .ticks = 50000, .steps = 1, .count_up = true}; + switch (seq->state) { + case 0: // INIT + stepper->setAutoEnable(false); + stepper->enableOutputs(); + // fall through + case 1: + case 2: + case 3: + aqe = stepper->addQueueEntry(&cmd_step); + if (aqeRetry(aqe)) { + PRINTU8(static_cast(aqe)); + PRINTCH(' '); + } else { + seq->u32_1 = time_ms; + seq->state++; + } + break; + case 4: + if (time_ms - seq->u32_1 >= 20) { + if (stepper->getCurrentPosition() != 4) { + PRINTLN("not all raw commands executed"); + seq->state = TEST_STATE_ERROR; + } + return true; + } + break; + } + return false; +} +#endif diff --git a/examples/StepperDemo/test_seq_14.cpp b/examples/StepperDemo/test_seq_14.cpp new file mode 100644 index 0000000..e049c79 --- /dev/null +++ b/examples/StepperDemo/test_seq_14.cpp @@ -0,0 +1,116 @@ +#include "test_seq.h" + +#if defined(SUPPORT_ESP32_PULSE_COUNTER) +#include "test_seq_14_pattern.h" + +#define SEQ14_TIME_LIMIT_MS 1000 + +// Feed one command to the stepper. A successful append (MOVE_TIMED_OK / +// MOVE_TIMED_EMPTY) updates the drift; every other result is handed back to the +// caller so it can decide what to do on the next loop() tick. +static MoveTimedResultCode seq14_feed(StepperMotion* stepper, int16_t steps, + uint32_t ticks, int32_t* drift, + bool start) { + uint32_t duration = ticks + *drift; + uint32_t actual = 0; + MoveTimedResultCode rc = stepper->moveTimed(steps, duration, &actual, start); + if ((rc == MOVE_TIMED_OK) || (rc == MOVE_TIMED_EMPTY)) { + *drift = (int32_t)(duration - actual); + } + return rc; +} + +bool test_seq_14(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + switch (seq->state) { + case 0: + if (!stepper->attachToPulseCounter(7)) { + PRINTLN("Error attaching to pulse counter"); + seq->state = TEST_STATE_ERROR; + return true; + } + PRINTLN("Attached to pulse counter 7"); + stepper->setAutoEnable(false); + stepper->enableOutputs(); + stepper->setCurrentPosition(0); + stepper->clearPulseCounter(); + seq->u32_1 = MILLIS(); + seq->s16_1 = 0; // next command index into REPLAY_PATTERN + seq->s16_2 = 0; // 0: filling (start=false), 1: running top-up + seq->s32_1 = 0; // drift + seq->state++; + break; + case 1: { + // Replay the recorded #370 stroke one command per loop() tick. The + // command index and the fill/run mode live in the sequence state, so + // nothing ever blocks: a busy or transient result simply leaves the + // state unchanged and the main loop feeds the next command on the + // following tick, keeping the task watchdog happy. + int16_t idx = seq->s16_1; + if (idx < REPLAY_PATTERN_LEN) { + bool start = (seq->s16_2 != 0); + MoveTimedResultCode rc = + seq14_feed(stepper, REPLAY_PATTERN[idx].steps, + REPLAY_PATTERN[idx].ticks, &seq->s32_1, start); + switch (rc) { + case MOVE_TIMED_OK: + case MOVE_TIMED_EMPTY: + seq->s16_1++; + break; + case MOVE_TIMED_BUSY: + case MoveTimedResultCode::QueueFull: + // Queue is full: the move was not appended. Switch from the + // pure fill phase (start=false) to running top-up mode + // (start=true, which auto-restarts the queue) and retry the + // same command on the next tick without advancing. + if (seq->s16_2 == 0) { + stepper->moveTimed(0, 0, NULL, true); // start the queue + } + seq->s16_2 = 1; + break; + case MoveTimedResultCode::DirPinIsBusy: + case MoveTimedResultCode::DirPin2msPauseAdded: + case MoveTimedResultCode::DirChangePauseInjected: + case MoveTimedResultCode::WaitForEnablePinActive: + case MoveTimedResultCode::DeviceNotReady: + // Transient: keep the index and mode for the next tick. + break; + default: + PRINTLN(toString(rc)); + seq->state = TEST_STATE_ERROR; + break; + } + if (seq->s16_1 >= REPLAY_PATTERN_LEN) { + seq->state++; + } + } + break; + } + case 2: + if (!stepper->isRunning()) { + uint32_t dt = MILLIS() - seq->u32_1; + int16_t pcnt = stepper->readPulseCounter(); + PRINT("pcnt="); + PRINTI16(pcnt); + PRINT(" pos="); + PRINTI32(stepper->getCurrentPosition()); + PRINT(" ramp_ms="); + PRINTU32(dt); + PRINTLN(""); + if ((pcnt != REPLAY_PATTERN_NET_STEPS) || (dt >= SEQ14_TIME_LIMIT_MS)) { + seq->state = TEST_STATE_ERROR; + } + return true; + } + break; + } + (void)time_ms; + return false; +} + +#else +bool test_seq_14(StepperMotion* stepper, struct test_seq_s* seq, + uint32_t time_ms) { + return test_seq_01(stepper, seq, time_ms); +} +#endif diff --git a/examples/StepperDemo/test_seq_14_pattern.h b/examples/StepperDemo/test_seq_14_pattern.h new file mode 100644 index 0000000..15e2008 --- /dev/null +++ b/examples/StepperDemo/test_seq_14_pattern.h @@ -0,0 +1,87 @@ +// Generated by commands-to-pattern.mjs — do not edit by hand. +// Source: sent-commands-left.json role: left +// 350 commands, net -592 steps, sum|steps| 8304, +// total 15198614 ticks @16MHz = 0.950 s +#pragma once +#include + +#define REPLAY_PATTERN_LEN 350 +#define REPLAY_PATTERN_NET_STEPS -592 + +struct ReplayCmd { + int16_t steps; + uint32_t ticks; +}; + +static const ReplayCmd REPLAY_PATTERN[REPLAY_PATTERN_LEN] = { + {-26, 505964}, {-26, 209577}, {-26, 160814}, {-27, 135573}, {-26, 119442}, + {-26, 107984}, {-26, 99301}, {-26, 92427}, {-26, 86810}, {-26, 82107}, + {-27, 78094}, {-26, 74618}, {-26, 71568}, {-26, 68865}, {-26, 66446}, + {-26, 64266}, {-26, 62287}, {-26, 60480}, {-27, 58823}, {-26, 57294}, + {-26, 55879}, {-26, 54563}, {-26, 53337}, {-26, 52189}, {-27, 51113}, + {-26, 50100}, {-26, 49146}, {-26, 48244}, {-26, 47390}, {-26, 46579}, + {-26, 45809}, {-27, 45076}, {-26, 44377}, {-26, 43710}, {-26, 43072}, + {-26, 42461}, {-26, 41875}, {-26, 41313}, {-27, 40773}, {-26, 40253}, + {-26, 39753}, {-26, 39271}, {-26, 38806}, {-26, 38358}, {-26, 37924}, + {-27, 37505}, {-26, 37100}, {-26, 36707}, {-26, 36327}, {-26, 35958}, + {-26, 35600}, {-27, 35253}, {-26, 34915}, {-26, 34587}, {-26, 34269}, + {-26, 33958}, {-26, 33657}, {-26, 33363}, {-27, 33076}, {-26, 32797}, + {-26, 32525}, {-26, 32259}, {-26, 32064}, {-26, 32000}, {-27, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-27, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-27, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-27, 32000}, + {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {-26, 32000}, {-26, 32000}, {-27, 32000}, {-26, 32000}, {-26, 32000}, + {10, 32000}, {22, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {21, 32000}, {22, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {21, 32000}, {21, 32000}, {22, 32000}, {21, 32000}, + {22, 32000}, {21, 32000}, {22, 32070}, {21, 32271}, {21, 32537}, + {22, 32810}, {21, 33089}, {21, 33376}, {22, 33670}, {21, 33972}, + {22, 34283}, {21, 34602}, {21, 34930}, {22, 35268}, {21, 35616}, + {22, 35974}, {21, 36344}, {21, 36725}, {22, 37118}, {21, 37524}, + {21, 37944}, {22, 38378}, {21, 38827}, {21, 39293}, {22, 39775}, + {21, 40276}, {21, 40797}, {22, 41338}, {21, 41901}, {21, 42488}, + {22, 43100}, {21, 43739}, {21, 44408}, {22, 45109}, {21, 45843}, + {21, 46615}, {21, 47427}, {22, 48284}, {21, 49188}, {21, 50145}, + {22, 51160}, {21, 52240}, {21, 53390}, {21, 54621}, {22, 55940}, + {21, 57361}, {21, 58895}, {22, 60559}, {21, 62373}, {21, 64360}, + {21, 66550}, {22, 68981}, {21, 71699}, {21, 74766}, {21, 78263}, + {21, 82304}, {22, 87042}, {21, 92709}, {21, 99650}, {21, 108433}, + {22, 120052}, {21, 136468}, {21, 162323}, {21, 213021}, {21, 494369}, +}; diff --git a/examples/TeensyBringUp/TeensyBringUp.ino b/examples/TeensyBringUp/TeensyBringUp.ino new file mode 100644 index 0000000..83db35c --- /dev/null +++ b/examples/TeensyBringUp/TeensyBringUp.ino @@ -0,0 +1,109 @@ +#include "StepperMotion.h" + +// Minimal bring-up/test sketch for the EXPERIMENTAL Teensy 4.0/4.1 backend +// (src/pd_teensy). This backend has NOT been verified on real hardware - +// see the warning at the top of src/pd_teensy/pd_config.h. Use this sketch +// to check it on your board before relying on it in a real project. +// +// What to check: +// 1. Does it compile and upload at all? +// 2. Does the stepper actually move back and forth, the right number of +// steps (watch the position printed to Serial, or count physical steps)? +// 3. Put a scope/logic analyzer on the STEP pin: pulse HIGH time should be +// close to FAS_TEENSY_PULSE_WIDTH_US (default 3us, see pd_config.h), and +// the step-to-step period should ramp smoothly (S-curve corners from +// setLinearAcceleration(), see below) without jitter or missed edges, +// especially near the top speed configured below. +// 4. Try raising setSpeedInHz()/setAcceleration() to find where it actually +// breaks (missed steps, hangs) - the 50k steps/s ceiling in +// _pd_initVars() is an untested guess, not a measurement. +// +// Any digital pin works for step/dir/enable on this backend (unlike +// SAMD/SAM, it's not restricted to specific muxed pins) - change the pin +// numbers below to whatever you've actually wired up. + +#define stepPinStepper 2 +#define dirPinStepper 3 +#define enablePinStepper 4 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 3000) { + // wait for the USB serial monitor, but don't hang forever if none is + // attached + } + Serial.println("START - StepperMotion Teensy 4.x bring-up test"); + + engine.init(); + + stepper = engine.stepperConnectToPin(stepPinStepper); + if (stepper) { + Serial.println("HAVE STEPPER"); + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + stepper->setSpeedInHz(2000); // start conservative, raise later + stepper->setAcceleration(4000); + stepper->setLinearAcceleration(50); // small S-curve corners to check + + Serial.print("TICKS_PER_S="); + Serial.println((uint32_t)TICKS_PER_S); + Serial.print("max_speed getMaxSpeedInHz()="); + Serial.println(stepper->getMaxSpeedInHz()); + Serial.print("enablePin state right after setEnablePin() (expect HIGH=1, disabled): "); + Serial.println(digitalRead(enablePinStepper)); + } else { + while (true) { + Serial.println("NO STEPPER - check stepPinStepper is a valid pin"); + delay(1000); + } + } +} + +uint32_t last_report_ms = 0; + +void loop() { + if (!stepper->isRunning()) { + int32_t pos = stepper->getCurrentPosition(); + Serial.print("Reached standstill at position "); + Serial.println(pos); + + int32_t target = (pos <= 0) ? 3200 : -3200; + Serial.print("Moving to "); + Serial.println(target); + MoveResultCode res = stepper->moveTo(target); + if (!moveIsOk(res)) { + Serial.print("moveTo() error: "); + Serial.println(toString(res)); + } + } + + // Periodic status while running, so you can watch position/speed advance + // in the Serial Monitor without needing a scope for a first sanity check. + uint32_t now = millis(); + if (stepper->isRunning() && (now - last_report_ms >= 200)) { + last_report_ms = now; + Serial.print("pos="); + Serial.print(stepper->getCurrentPosition()); + Serial.print(" target="); + Serial.print(stepper->targetPos()); + Serial.print(" stepsToStop="); + Serial.print(stepper->stepsToStop()); + Serial.print(" speed(mHz)="); + Serial.print(stepper->getCurrentSpeedInMilliHz()); + Serial.print(" rampState="); + Serial.print(stepper->rampState()); + Serial.print(" queueRunning="); + Serial.print(stepper->isQueueRunning()); + Serial.print(" queueEmpty="); + Serial.print(stepper->isQueueEmpty()); + Serial.print(" enablePin="); + Serial.print(digitalRead(enablePinStepper)); + Serial.print(" queueEntries="); + Serial.println(stepper->queueEntries()); + } +} diff --git a/examples/TeensyEnableBlinkTest/TeensyEnableBlinkTest.ino b/examples/TeensyEnableBlinkTest/TeensyEnableBlinkTest.ino new file mode 100644 index 0000000..15638c6 --- /dev/null +++ b/examples/TeensyEnableBlinkTest/TeensyEnableBlinkTest.ino @@ -0,0 +1,70 @@ +#include "StepperMotion.h" + +// Minimal, decisive test of StepperMotion's enable-pin control, +// completely decoupled from auto-enable timing and from any driver board - +// wire an LED directly to enablePinStepper (through a resistor to GND) to +// watch it. +// +// This calls the library's own public enableOutputs()/disableOutputs() +// directly, alternating every 2 seconds, printing what it did and what +// digitalRead() sees right after. If the LED doesn't change in sync with +// these prints, the problem is confirmed to be in the library's pin +// control - if it does, the library is fine and something else (timing, +// wiring, or how another sketch used it) was the real cause. + +#define stepPinStepper 2 +#define dirPinStepper 3 +#define enablePinStepper 4 + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 3000) { + } + Serial.println("START - enable pin blink test"); + + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + if (!stepper) { + while (true) { + Serial.println("NO STEPPER - check stepPinStepper is a valid pin"); + delay(1000); + } + } + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + // NOT calling setAutoEnable() - we're driving enable manually here so + // there's no ambiguity about when it fires. + + Serial.print("Right after setEnablePin(), digitalRead(pin)="); + Serial.println(digitalRead(enablePinStepper)); + Serial.println( + "Expect HIGH=1 here (disabled is the safe default) - the LED should " + "be ON now if wired pin->resistor->LED->GND."); +} + +bool enabled = false; +uint32_t lastToggleMs = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastToggleMs >= 2000) { + lastToggleMs = now; + enabled = !enabled; + bool ok; + if (enabled) { + ok = stepper->enableOutputs(); + Serial.print("enableOutputs() -> "); + } else { + ok = stepper->disableOutputs(); + Serial.print("disableOutputs() -> "); + } + Serial.print(ok ? "true" : "false"); + Serial.print(" digitalRead(pin) now = "); + Serial.print(digitalRead(enablePinStepper)); + Serial.println(enabled ? " (expect LOW=0, LED should turn OFF)" + : " (expect HIGH=1, LED should turn ON)"); + } +} diff --git a/examples/TeensyMaxSpeedFinder/TeensyMaxSpeedFinder.ino b/examples/TeensyMaxSpeedFinder/TeensyMaxSpeedFinder.ino new file mode 100644 index 0000000..fb273f1 --- /dev/null +++ b/examples/TeensyMaxSpeedFinder/TeensyMaxSpeedFinder.ino @@ -0,0 +1,255 @@ +#include "StepperMotion.h" + +// Finds the real maximum reliable step rate on YOUR board/motor/driver +// combination, for the EXPERIMENTAL Teensy 4.0/4.1 backend (src/pd_teensy). +// +// WHY THIS EXISTS: software alone cannot detect missed steps on an open-loop +// stepper (no encoder feedback) - the queue/ramp generator will happily +// report "move complete" even if the motor physically stalled or skipped +// pulses under load. So this test relies on YOU watching the shaft. +// +// HOW TO USE: +// 1. Mark the motor shaft (piece of tape, paint dot, anything visible) so +// you can see its exact rotational position. +// 2. Upload this sketch and open the Serial Monitor at 115200 baud. +// 3. Type 'y' to start. For each speed level, the motor moves +// forward far enough to actually reach and briefly cruise at that +// speed (see stepsForLeg()), pauses, then moves back the same +// distance - ending exactly where it started IF (and only if) no +// steps were lost in either direction. Watch the mark. +// While it runs, status lines print every 200ms - if those stop +// appearing, the last line printed pinpoints exactly where it got +// stuck; share it. +// 4. After each leg finishes, the sketch asks: +// y - shaft returned to the exact same position -> try the +// next (faster) speed level +// n - shaft did NOT return to the same position (steps were +// lost) -> stop here; the LAST speed that answered 'y' +// is your real, hardware-verified ceiling +// 5. Whatever speed you stopped at, set that as the argument to +// setAbsoluteSpeedLimit() in your real project (see pd_teensy/pd_config.h +// for SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING), with a safety margin below +// it (e.g. 80% of the last good value) - don't run right at the edge. +// +// This tests SPEED only, at a fixed, modest acceleration - it does not by +// itself find the max acceleration your motor/load can handle. If a leg +// fails, it could be losing steps because of the acceleration ramp too fast +// for your motor/load's torque, not the step rate itself. If you suspect +// that, lower ACCELERATION below and re-run from the same speed level. + +#define stepPinStepper 2 +#define dirPinStepper 3 +#define enablePinStepper 4 + +// Distance per leg is computed per speed level (see stepsForLeg()) - a +// FIXED step count can't reach a high target speed at all: too short a +// distance silently turns a high-speed level into a low triangular blip +// that never actually reaches the speed being "tested", making the result +// meaningless. Higher ACCELERATION here means less distance/time needed +// to reach a given speed level (e.g. at 200000 steps/s^2, the 200000 Hz +// level needs ~300000 steps and ~1.5s per leg; lower this and the +// distance/time grows a lot - d,t ~ 1/ACCELERATION for a given speed). +// This is a test default, not a claim about your motor's real max +// acceleration - lower it if you suspect losses are from acceleration +// being too aggressive for your torque, not from the step rate itself. +// Lowered from 200000 to 20000 for round 2: round 1 (200000 steps/s^2) +// found steps lost at 125000 Hz with a hard/fast ramp - this checks +// whether that was a motor torque/acceleration limit rather than a real +// step-rate ceiling, by giving the motor a much gentler ramp to the same +// speeds. Legs will take longer now (t ~ 1/ACCELERATION for a given +// speed) - expect several seconds per leg at the higher levels. +#define ACCELERATION 20000 // steps/s^2 + +// Round 2: 5000-100000 Hz already confirmed good in round 1 (with an even +// harder ramp), so start straight at 100000 to save time. +const uint32_t speedLevels[] = {100000, 125000, 150000, 175000, 200000}; +const uint8_t numLevels = sizeof(speedLevels) / sizeof(speedLevels[0]); + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +enum class TestState { + waitingToStart, + movingForward, + pausing, + movingBack, + waitingConfirm, + stopped, + done +}; +TestState state = TestState::waitingToStart; +uint8_t level = 0; +uint32_t stateChangeMs = 0; +uint32_t lastReportMs = 0; +int32_t currentLegSteps = 0; + +// Distance needed to accelerate up to speedHz and back down to 0 is +// speedHz^2 / ACCELERATION (both phases together); add 50% more so there +// is an actual cruise segment at speedHz to observe, not just a triangular +// peak that brushes the target speed for an instant. +int32_t stepsForLeg(uint32_t speedHz) { + uint32_t accelDecelSteps = + (uint32_t)(((uint64_t)speedHz * speedHz) / ACCELERATION); + uint32_t steps = accelDecelSteps + accelDecelSteps / 2; + if (steps < 200) { + steps = 200; // sane minimum for the lowest test levels + } + return (int32_t)steps; +} + +void printStatus(const char *label) { + Serial.print(label); + Serial.print(" pos="); + Serial.print(stepper->getCurrentPosition()); + Serial.print(" target="); + Serial.print(stepper->targetPos()); + Serial.print(" stepsToStop="); + Serial.print(stepper->stepsToStop()); + Serial.print(" speed(mHz)="); + Serial.print(stepper->getCurrentSpeedInMilliHz()); + Serial.print(" rampState="); + Serial.print(stepper->rampState()); + Serial.print(" queueRunning="); + Serial.print(stepper->isQueueRunning()); + Serial.print(" queueEmpty="); + Serial.print(stepper->isQueueEmpty()); + Serial.print(" queueEntries="); + Serial.println(stepper->queueEntries()); +} + +void startLeg() { + currentLegSteps = stepsForLeg(speedLevels[level]); + Serial.println(); + Serial.print("=== Testing "); + Serial.print(speedLevels[level]); + Serial.print(" Hz, "); + Serial.print(currentLegSteps); + Serial.println(" steps per leg ==="); + Serial.println("Watch the shaft mark now."); + stepper->setSpeedInHz(speedLevels[level]); + stepper->setAcceleration(ACCELERATION); + MoveResultCode res = stepper->move(currentLegSteps); + Serial.print("move() forward returned: "); + Serial.println(toString(res)); + state = TestState::movingForward; + stateChangeMs = millis(); +} + +void checkSerialForYesNo() { + while (Serial.available()) { + char c = Serial.read(); + if (c == 'y' || c == 'Y') { + if (state == TestState::waitingConfirm) { + Serial.println("-> continuing to next speed level"); + level++; + if (level >= numLevels) { + state = TestState::done; + return; + } + } else { + Serial.println("-> starting"); + } + startLeg(); + return; + } + if (c == 'n' || c == 'N') { + Serial.println( + "-> stopping here. The last speed that printed 'y' is your " + "hardware-verified ceiling."); + state = TestState::stopped; + return; + } + } +} + +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 3000) { + } + Serial.println("START - Teensy max-speed finder (non-blocking)"); + + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + if (!stepper) { + while (true) { + Serial.println("NO STEPPER - check stepPinStepper is a valid pin"); + delay(1000); + } + } + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + // Raise the ceiling so setSpeedInHz() up to the top test level is even + // accepted - see pd_teensy/pd_config.h, SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING. + // Guarded here because this method only exists on platforms that define + // that macro (e.g. not atmelsam) - the CI build matrix compiles every + // example against every platform. +#if defined(SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING) + stepper->setAbsoluteSpeedLimit( + (uint16_t)fas_max((uint32_t)1, TICKS_PER_S / 400000)); +#endif + + Serial.println( + "Mark the shaft now if you haven't. Type 'y' when ready to " + "start."); +} + +void loop() { + uint32_t now = millis(); + bool wantReport = (now - lastReportMs >= 200); + + switch (state) { + case TestState::waitingToStart: + case TestState::waitingConfirm: + checkSerialForYesNo(); + break; + + case TestState::movingForward: + if (wantReport) { + lastReportMs = now; + printStatus("[fwd]"); + } + if (!stepper->isRunning()) { + Serial.println("Forward leg finished."); + state = TestState::pausing; + stateChangeMs = now; + } + break; + + case TestState::pausing: + if (now - stateChangeMs >= 300) { + MoveResultCode res = stepper->move(-currentLegSteps); + Serial.print("move() back returned: "); + Serial.println(toString(res)); + state = TestState::movingBack; + } + break; + + case TestState::movingBack: + if (wantReport) { + lastReportMs = now; + printStatus("[back]"); + } + if (!stepper->isRunning()) { + Serial.println("Back leg finished."); + Serial.println( + "Did the shaft mark return to EXACTLY the same position as " + "before this leg started? (y/n)"); + state = TestState::waitingConfirm; + } + break; + + case TestState::stopped: + break; + + case TestState::done: + if (wantReport) { + lastReportMs = now; + Serial.println( + "All speed levels passed! Add higher values to speedLevels[] " + "and re-flash to keep narrowing in."); + } + break; + } +} diff --git a/examples/TeensyMoveAndPause/TeensyMoveAndPause.ino b/examples/TeensyMoveAndPause/TeensyMoveAndPause.ino new file mode 100644 index 0000000..afd8dd5 --- /dev/null +++ b/examples/TeensyMoveAndPause/TeensyMoveAndPause.ino @@ -0,0 +1,77 @@ +#include "StepperMotion.h" + +// Move, sit idle for a few seconds, move again - repeating. Unlike +// TeensyBringUp.ino (which starts the next move the instant the previous +// one finishes, so the enable pin never gets a chance to go back to +// "disabled"), this sketch has a real idle gap between moves, so you can +// actually watch the enable pin (and, if wired, an LED on it) switch: +// HIGH (disabled) while idle <-> LOW (enabled) while moving +// (default polarity - LOW enables the motor. See setEnablePin() docs if +// your driver needs the opposite.) + +#define stepPinStepper 2 +#define dirPinStepper 3 +#define enablePinStepper 4 + +#define IDLE_MS 3000 // how long to sit still between moves + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 3000) { + } + Serial.println("START - move, pause, move"); + + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + if (!stepper) { + while (true) { + Serial.println("NO STEPPER - check stepPinStepper is a valid pin"); + delay(1000); + } + } + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + // Disable (almost) as soon as the motor stops, instead of waiting for + // the default delay, so the HIGH/disabled state during the idle gap + // below is easy to see. + stepper->setDelayToDisable(50); + + stepper->setSpeedInHz(2000); + stepper->setAcceleration(4000); +} + +void printEnableState(const char *label) { + Serial.print(label); + Serial.print(" enablePin="); + Serial.println(digitalRead(enablePinStepper)); +} + +void loop() { + int32_t pos = stepper->getCurrentPosition(); + int32_t target = (pos <= 0) ? 3200 : -3200; + + Serial.print("Moving to "); + Serial.print(target); + Serial.println(" ..."); + MoveResultCode res = stepper->moveTo(target, true); // built-in blocking mode + Serial.print("moveTo() returned: "); + Serial.println(toString(res)); + Serial.print("Reached "); + Serial.println(stepper->getCurrentPosition()); + + Serial.print("Idling for "); + Serial.print(IDLE_MS); + Serial.println(" ms - watch the enable pin/LED now."); + uint32_t idleStart = millis(); + while (millis() - idleStart < IDLE_MS) { + static uint32_t lastPrint = 0; + if (millis() - lastPrint >= 500) { + lastPrint = millis(); + printEnableState("[idle]"); + } + } +} diff --git a/examples/TeensyMultiStepperTest/TeensyMultiStepperTest.ino b/examples/TeensyMultiStepperTest/TeensyMultiStepperTest.ino new file mode 100644 index 0000000..81748f5 --- /dev/null +++ b/examples/TeensyMultiStepperTest/TeensyMultiStepperTest.ino @@ -0,0 +1,146 @@ +#include "StepperMotion.h" + +// Multi-stepper test for the EXPERIMENTAL Teensy 4.0/4.1 backend +// (src/pd_teensy). Defaults to the FULL claimed capacity - 16 steppers, +// spanning all 4 QuadTimer modules (TMR1..TMR4) - to find out how many +// this board actually drives, not just how many the code claims to +// support. +// +// WHY THIS MATTERS: this backend allocates one QuadTimer channel per +// stepper, 4 channels per module, in connection order. Steppers 0-3 land +// on module 0 (TMR1), 4-7 on module 1 (TMR2), 8-11 on module 2 (TMR3), +// 12-15 on module 3 (TMR4) - each module has its own register block and +// NVIC interrupt vector. A bug specific to a given module, or a resource +// conflict once all 4 are active simultaneously, would only show up once +// every module is actually exercised. +// +// Real motors are NOT required - this tests software correctness (do all +// 16 channels across all 4 modules run independently, with no missed +// deadlines even under the combined interrupt load of all of them at +// once), not torque/missed-steps under load (measured separately per +// axis with examples/TeensyMaxSpeedFinder). Driving raw pins into LEDs, +// a logic analyzer, or nothing at all is enough. +// +// PINS: 16 unique step pins and 16 unique dir pins are needed (step pins +// specifically MUST be unique - each one claims its own QuadTimer +// channel); the enable pin is shared across all 16 here (this library +// supports sharing enable/dir pins between motors) to keep the pin count +// within Teensy 4.0's 40 available pins. Change ENABLE_PIN or the arrays +// below to match your wiring; set NUM_STEPPERS lower if you don't have +// (or don't want to wire up) all 16. +// +// HOW TO USE: +// 1. Set NUM_STEPPERS below (up to 16) and check the pin arrays match +// your wiring (or that the pins are simply safe to toggle/unconnected). +// 2. Upload, open the Serial Monitor at 115200. +// 3. Every stepper immediately starts an independent, continuous +// back-and-forth move at its own speed/acceleration/distance +// (deliberately different per axis, computed from its index so no two +// are ever in lockstep) - this maximizes the chance of exposing any +// cross-talk between channels/modules. +// 4. A status table prints every 500 ms: one row per stepper, showing +// which TMR module/channel it's on, position, live speed, and +// queue/ramp state. Every row should keep updating independently; +// none should ever show a stuck rampState or frozen position while +// queueRunning=1 (that pattern is exactly the "stuck ramp" bug this +// library had - see CHANGELOG). Let it run for several minutes and +// confirm every row - especially the ones on modules 2-4 (index +// >= 4) - keeps moving smoothly the whole time. + +#define NUM_STEPPERS 16 // up to 16 (4 QuadTimer modules x 4 channels) + +// clang-format off +const uint8_t STEP_PIN[16] = { + 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 14, 15, 16, 17, 18, // 13 skipped (onboard LED) +}; +const uint8_t DIR_PIN[16] = { + 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 33, 34, +}; +// clang-format on +#define ENABLE_PIN 35 // shared by all steppers - this library supports that + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *steppers[NUM_STEPPERS]; +int32_t travelSteps[NUM_STEPPERS]; + +void setup() { + Serial.begin(115200); + while (!Serial && millis() < 3000) { + } + Serial.println("START - Teensy multi-stepper test"); + Serial.print("NUM_STEPPERS="); + Serial.println(NUM_STEPPERS); + + engine.init(); + + for (uint8_t i = 0; i < NUM_STEPPERS; i++) { + StepperMotion *s = engine.stepperConnectToPin(STEP_PIN[i]); + steppers[i] = s; + Serial.print("stepper "); + Serial.print(i); + Serial.print(" (step pin "); + Serial.print(STEP_PIN[i]); + Serial.print(") -> TMR module "); + Serial.print(i >> 2); + Serial.print(" channel "); + Serial.print(i & 0x03); + Serial.print(": "); + if (!s) { + Serial.println("FAILED to connect - pin busy or out of queues?"); + continue; + } + Serial.println("OK"); + s->setDirectionPin(DIR_PIN[i]); + s->setEnablePin(ENABLE_PIN); + s->setAutoEnable(true); + + // Deliberately different per axis, and not simple multiples of each + // other, so the steppers are never in lockstep - makes any timing + // cross-talk between channels/modules much easier to notice. + uint32_t speedHz = 2000 + (uint32_t)i * 733; + uint32_t accel = 4000 + (uint32_t)i * 1500; + travelSteps[i] = 1800 + (int32_t)(i % 5) * 300; + + s->setSpeedInHz(speedHz); + s->setAcceleration(accel); + s->moveTo(travelSteps[i]); + } + Serial.println(); +} + +uint32_t lastReportMs = 0; + +void loop() { + uint32_t now = millis(); + if (now - lastReportMs < 500) { + return; + } + lastReportMs = now; + + Serial.println( + "ax mod ch pos target speed(mHz) rampState qRun qEmpty " + "qEntries"); + for (uint8_t i = 0; i < NUM_STEPPERS; i++) { + StepperMotion *s = steppers[i]; + if (!s) { + continue; + } + if (!s->isRunning()) { + // reverse direction and go again + int32_t target = + (s->getCurrentPosition() <= 0) ? travelSteps[i] : -travelSteps[i]; + s->moveTo(target); + } + char line[110]; + snprintf(line, sizeof(line), + "%2d %1d %1d %8ld %8ld %10ld %9d %4d %6d %8d", (int)i, + (int)(i >> 2), (int)(i & 0x03), (long)s->getCurrentPosition(), + (long)s->targetPos(), (long)s->getCurrentSpeedInMilliHz(), + (int)s->rampState(), (int)s->isQueueRunning(), + (int)s->isQueueEmpty(), (int)s->queueEntries()); + Serial.println(line); + } + Serial.println(); +} diff --git a/examples/UsageEspI2S/UsageEspI2S.ino b/examples/UsageEspI2S/UsageEspI2S.ino new file mode 100644 index 0000000..41a70c0 --- /dev/null +++ b/examples/UsageEspI2S/UsageEspI2S.ino @@ -0,0 +1,85 @@ +#include "StepperMotion.h" + +#ifdef SUPPORT_ESP32_I2S + +// I2S_DIRECT example: one stepper per I2S peripheral, bit-level resolution +#define i2sDirectStepPin 15 + +// I2S_MUX example: multiple steppers via 74HC595 shift register chain +// Directly connect to ESP32 GPIOs: +#define i2sMuxDataPin 32 +#define i2sMuxBclkPin 33 +#define i2sMuxWsPin 14 + +// 74HC595 output slot layout (directly usable as step pins with PIN_I2S_FLAG): +// Slot 0: Stepper 0 STEP +// Slot 1: Stepper 0 DIR (active-high) +// Slot 2: Stepper 0 ENABLE (active-low) +// Slot 3: Stepper 1 STEP +// Slot 4: Stepper 1 DIR (active-high) +// Slot 5: Stepper 1 ENABLE (active-low) + +StepperMotionEngine engine = StepperMotionEngine(); + +// I2S_DIRECT stepper +StepperMotion* stepperDirect = NULL; + +// I2S_MUX steppers +StepperMotion* stepperMux0 = NULL; +StepperMotion* stepperMux1 = NULL; + +void setup() { + Serial.begin(115200); + engine.init(); + + // --- I2S_DIRECT: one stepper, bit-level resolution (up to ~200kHz) --- + stepperDirect = + engine.stepperConnectToPin(i2sDirectStepPin, DRIVER_I2S_DIRECT); + if (stepperDirect) { + stepperDirect->setDirectionPin(18); + stepperDirect->setAutoEnable(true); + stepperDirect->setSpeedInUs(10); + stepperDirect->setAcceleration(50000); + } + + // --- I2S_MUX: multiple steppers via 74HC595, frame-level resolution --- + bool mux_ok = engine.initI2sMux(i2sMuxDataPin, i2sMuxBclkPin, i2sMuxWsPin); + + if (mux_ok) { + // Connect stepper 0 to MUX slot 0 + stepperMux0 = engine.stepperConnectToPin(PIN_I2S_FLAG, DRIVER_I2S_MUX); + if (stepperMux0) { + stepperMux0->setAutoEnable(true); + stepperMux0->setSpeedInUs(100); + stepperMux0->setAcceleration(10000); + } + + // Connect stepper 1 to MUX slot 3 + stepperMux1 = engine.stepperConnectToPin(3 | PIN_I2S_FLAG, DRIVER_I2S_MUX); + if (stepperMux1) { + stepperMux1->setAutoEnable(true); + stepperMux1->setSpeedInUs(200); + stepperMux1->setAcceleration(5000); + } + } + + // Start moving + if (stepperDirect) { + stepperDirect->move(10000); + } + if (stepperMux0) { + stepperMux0->move(1000); + } + if (stepperMux1) { + stepperMux1->move(2000); + } +} + +void loop() {} + +#else + +void setup() {} +void loop() {} + +#endif diff --git a/examples/UsageExample/UsageExample.ino b/examples/UsageExample/UsageExample.ino new file mode 100644 index 0000000..ea9cbf7 --- /dev/null +++ b/examples/UsageExample/UsageExample.ino @@ -0,0 +1,43 @@ +#include "StepperMotion.h" + +// As in StepperDemo for Motor 1 on AVR +// #define dirPinStepper 5 +// #define enablePinStepper 6 +// #define stepPinStepper 9 // OC1A in case of AVR + +// As in StepperDemo for Motor 1 on ESP32 +#define dirPinStepper 18 +#define enablePinStepper 26 +#define stepPinStepper 17 + +#if defined(PICO_RP2040) || defined(PICO_RP2350) +#undef dirPinStepper +#undef enablePinStepper +#undef stepPinStepper +#define dirPinStepper 15 +#define enablePinStepper 13 +#define stepPinStepper 14 +#endif + +StepperMotionEngine engine = StepperMotionEngine(); +StepperMotion *stepper = NULL; + +void setup() { + engine.init(); + stepper = engine.stepperConnectToPin(stepPinStepper); + if (stepper) { + stepper->setDirectionPin(dirPinStepper); + stepper->setEnablePin(enablePinStepper); + stepper->setAutoEnable(true); + + // If auto enable/disable need delays, just add (one or both): + // stepper->setDelayToEnable(50); + // stepper->setDelayToDisable(1000); + + stepper->setSpeedInUs(1000); // the parameter is us/step !!! + stepper->setAcceleration(100); + stepper->move(1000); + } +} + +void loop() {} diff --git a/firmware/esp32/CMakeLists.txt b/firmware/esp32/CMakeLists.txt new file mode 100644 index 0000000..8ad8977 --- /dev/null +++ b/firmware/esp32/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 3.20) + +get_filename_component(STEPPER_MOTION_DIR "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +list(APPEND EXTRA_COMPONENT_DIRS "${STEPPER_MOTION_DIR}") +include($ENV{IDF_PATH}/tools/cmake/project.cmake) +project(stepper_motion_example) diff --git a/firmware/esp32/main/CMakeLists.txt b/firmware/esp32/main/CMakeLists.txt new file mode 100644 index 0000000..060e411 --- /dev/null +++ b/firmware/esp32/main/CMakeLists.txt @@ -0,0 +1 @@ +idf_component_register(SRCS "main.cpp") diff --git a/firmware/esp32/main/main.cpp b/firmware/esp32/main/main.cpp new file mode 100644 index 0000000..274eec5 --- /dev/null +++ b/firmware/esp32/main/main.cpp @@ -0,0 +1,46 @@ +#include + +#include "StepperMotion.h" +#include "esp_log.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +namespace { + +constexpr char TAG[] = "stepper_motion"; +constexpr uint8_t STEP_PIN = 17; +constexpr uint8_t DIR_PIN = 18; +constexpr uint8_t ENABLE_PIN = 26; +constexpr int32_t TARGET_STEPS = 200; +StepperMotionEngine engine; + +} // namespace + +extern "C" void app_main() { + engine.init(); + StepperMotion* axis = engine.stepperConnectToPin(STEP_PIN); + if (axis == nullptr) { + ESP_LOGE(TAG, "No pulse output available on GPIO %u", STEP_PIN); + return; + } + + axis->setDirectionPin(DIR_PIN); + axis->setEnablePin(ENABLE_PIN, true); + axis->setAutoEnable(true); + if (axis->setSpeedInHz(400) != 0 || axis->setAcceleration(800) != 0) { + ESP_LOGE(TAG, "Motion settings rejected"); + return; + } + + ESP_LOGI(TAG, "Moving to %" PRId32 " steps", TARGET_STEPS); + const MoveResultCode result = axis->moveTo(TARGET_STEPS); + if (result != MoveResultCode::OK) { + ESP_LOGE(TAG, "Move rejected (%d)", static_cast(result)); + return; + } + while (axis->isRunning()) { + vTaskDelay(pdMS_TO_TICKS(10)); + } + ESP_LOGI(TAG, "Motion ended at %" PRId32 " commanded steps", + axis->getCurrentPosition()); +} diff --git a/firmware/esp32/sdkconfig.defaults b/firmware/esp32/sdkconfig.defaults new file mode 100644 index 0000000..879d223 --- /dev/null +++ b/firmware/esp32/sdkconfig.defaults @@ -0,0 +1 @@ +CONFIG_FREERTOS_HZ=1000 diff --git a/library.properties b/library.properties new file mode 100644 index 0000000..94876b4 --- /dev/null +++ b/library.properties @@ -0,0 +1,11 @@ +name=StepperMotionWorkbench +version=0.1.0 +author=Stepper Motion Workbench contributors +maintainer=cpp-hardtech +sentence=Buffered STEP/DIR pulse generation with acceleration ramps and coordinated motion. +paragraph=Provides point-to-point moves, timed segments, and multi-axis planning with microcontroller-specific pulse backends. +category=Device Control +url=https://github.com/cpp-hardtech/stepper-motion-workbench +architectures=avr,esp32,sam,samd,rp2040,rp2350,teensy +includes=StepperMotion.h +dot_a_linkage=true diff --git a/licenses/TeensyStep4-MIT.txt b/licenses/TeensyStep4-MIT.txt new file mode 100644 index 0000000..9d7085d --- /dev/null +++ b/licenses/TeensyStep4-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 luni64 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/AVRStepperPins.h b/src/AVRStepperPins.h new file mode 100644 index 0000000..4c32b27 --- /dev/null +++ b/src/AVRStepperPins.h @@ -0,0 +1,80 @@ +#ifndef AVRSTEPPERPINS_H +#define AVRSTEPPERPINS_H + +#if defined(ARDUINO_ARCH_AVR) +#include + +/** * Warning: Other libraries may also use the timers! + * + * For example Serial library and delay() functions for example. + * Using the same timer may cause strange effects, you are best to avoid using + * those other libraries at the some time or use a different pin where + * possible! + */ + +#if !(defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || \ + defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__) || \ + defined(__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__)) +#error "Unsupported AVR derivate" +#endif + +// The ATmega328P has one 16 bit timer: Timer 1 +// The ATmega2560 has four 16 bit timers: Timer 1, 3, 4 and 5 +#if (defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || \ + defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) +#define FAS_TIMER_MODULE 1 +#define stepPinStepper1A 9 /* OC1A */ +#define stepPinStepper1B 10 /* OC1B */ +#elif defined(__AVR_ATmega2560__) +#ifndef FAS_TIMER_MODULE +#define FAS_TIMER_MODULE 4 +#endif +#define stepPinStepper1A 11 /* OC1A */ +#define stepPinStepper1B 12 /* OC1B */ +#define stepPinStepper1C 13 /* OC1C */ +#define stepPinStepper3A 5 /* OC3A */ +#define stepPinStepper3B 2 /* OC3B */ +#define stepPinStepper3C 3 /* OC3C */ +#define stepPinStepper4A 6 /* OC4A */ +#define stepPinStepper4B 7 /* OC4B */ +#define stepPinStepper4C 8 /* OC4C */ +#define stepPinStepper5A 46 /* OC5A */ +#define stepPinStepper5B 45 /* OC5B */ +#define stepPinStepper5C 44 /* OC5C */ + +#elif defined(__AVR_ATmega32U4__) +#define FAS_TIMER_MODULE 1 +#define stepPinStepper1A 9 /* OC1A */ +#define stepPinStepper1B 10 /* OC1B */ +#define stepPinStepper1C 11 /* OC1C */ +#endif + +#if (FAS_TIMER_MODULE == 1) +#define stepPinStepperA stepPinStepper1A +#define stepPinStepperB stepPinStepper1B +#if defined(__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) +#define stepPinStepperC stepPinStepper1C +#endif +#elif (FAS_TIMER_MODULE == 3) +#define stepPinStepperA stepPinStepper3A +#define stepPinStepperB stepPinStepper3B +#if defined(__AVR_ATmega2560__) +#define stepPinStepperC stepPinStepper3C +#endif +#elif (FAS_TIMER_MODULE == 4) +#define stepPinStepperA stepPinStepper4A +#define stepPinStepperB stepPinStepper4B +#if defined(__AVR_ATmega2560__) +#define stepPinStepperC stepPinStepper4C +#endif +#elif (FAS_TIMER_MODULE == 5) +#define stepPinStepperA stepPinStepper5A +#define stepPinStepperB stepPinStepper5B +#if defined(__AVR_ATmega2560__) +#define stepPinStepperC stepPinStepper5C +#endif +#endif + +#endif // ARDUINO_ARCH_AVR + +#endif // AVRSTEPPERPINS_H diff --git a/src/FasNAxis.h b/src/FasNAxis.h new file mode 100644 index 0000000..cc23271 --- /dev/null +++ b/src/FasNAxis.h @@ -0,0 +1,1350 @@ +#ifndef FAS_NAXIS_H +#define FAS_NAXIS_H + +#include + +#include "fas_arch/common.h" +#include "fas_naxis/overshoot.h" +#include "fas_naxis/ramp_law.h" +#include "fas_naxis/ramp_map.h" +#include "fas_naxis/remaining.h" + +// The default stepper and engine types. Only their names are needed to parse +// the template (tests supply SimPort/TestStepperMotionEngine; production +// supplies the real StepperMotion/StepperMotionEngine from +// , which this header deliberately does not include). +class StepperMotion; +class StepperMotionEngine; + +// FasNAxis — a multi-axis planner that drives N StepperMotion queues from +// one polyline so the axes stay time-synchronized. Include this header +// explicitly when using the planner with StepperMotion. The hot path performs +// no float, double, integer division, or +// 64-bit integer type; ramp math lives in fas_naxis/ramp_map.h +// (log2_value_t) and RampCalculator. +// +// Step 7 is the Linear lookahead planner: addWaypoint() commits points into a +// block ring of up to HORIZON n-dim points, and pump() feeds the committed +// Linear path through addQueueEntry(). The DDA master is the longest |delta| of +// the current block; R is Remaining-style remaining master steps to the next +// Linear path-stop: a master-sense reversal or the path end. P carries across +// every other joint, including a master-role change (section 6.3/8.5); the 2 +// deg collinear test is diagnostic only. The last buffered point of an open +// path is rest, so the ramp always stops there. +// +// Step 8 makes the feeder fault-tolerant: feed_one() stores a held command per +// axis (one slice) and flush_held() sends it, retrying on a retryable +// addQueueEntry result on the next pump() without re-planning the slice, and +// reserving QUEUE_LEN - 2 slots so a pause-stuffed entry always fits. +// +// Step 13 adds dwells and the lookahead diagnostics: addDwellTicks() commits a +// zero-motion block whose pauses run on every axis from rest to rest (a +// path-stop, whitepaper section 8.1), isSpeedLimitedByLookahead() reports the +// live R < P_stop cap of an open path (F11/F19, never an error), and +// lookaheadHint() fills the diagnostic outs. + +// PumpStatus is the result of a pump() tick. Deliberately NO LookaheadTooShort: +// a short lookahead slows the track (speed cap, G4/F11/F19) instead of +// erroring. +enum class PumpStatus : int { + Idle = 0, // no block pending, queue settled + Running = 1, // a block is being planned / fed + Underrun = 2, // queue ran dry after a kick-off (F13) + Error = 3, // a contract violation the caller must fix + Stopped = 4 // a member axis was stopped outside the planner (stopMove / + // forceStop / e-stop); the plan is aborted, positions + // untrusted. Recover with syncFromSteppers(). +}; + +// Configuration. Default member initializers make FasNAxisConfig{} a valid +// Linear config. The constructor recovers 0 to the default so a raw zeroed +// struct still means "default slice / default threshold", not a zero-duration +// slice or a zero diagnostic threshold. +struct FasNAxisConfig { + enum Mode { + Linear, // snaps to every vertex; path speed 0 at a non-collinear vertex + Overshoot // may leave the chord within overshoot_max (Step 11+) + }; + + uint32_t dt_ticks = 32000; // 2 ms at 16 MHz; 0 means this default + uint16_t kappa_stop_q8 = 320; // 1.25 in Q8; 0 means this default + uint16_t overshoot_max = 8; // steps; ignored in Linear + uint16_t dir_before_ticks = 0; // 0 = use stepper getDirChangeBeforeTicks() + uint16_t dir_after_ticks = 0; // 0 = use stepper getDirChangeAfterTicks() + Mode mode = Linear; +}; + +// Per-axis frozen limits, read from the stepper at addAxis (and on +// setLimitsFromSteppers). ticks_cfg is the configured period; P_stop is the +// performed ramp-up steps (calculate_ramp_steps(ticks_cfg)). +struct AxisLimits { + uint32_t ticks_cfg = 0; + uint32_t P_stop = 0; + uint32_t accel = 0; // steps/s^2, read from the stepper at addAxis + // DIR pause budget (whitepaper section 4.4), read from the stepper: + // one dir_before pause (old DIR), then dir_after (new DIR). + uint16_t dir_before = 0; + uint16_t dir_after = 0; +}; + +template +class FasNAxis { + public: + explicit FasNAxis(const FasNAxisConfig& cfg, Engine& engine) + : _engine(&engine), _law(1, 1, 0) { + FasNAxisConfig c = cfg; // copy so the default recovery is observable + if (c.dt_ticks == 0) { + c.dt_ticks = 32000; + } + if (c.kappa_stop_q8 == 0) { + c.kappa_stop_q8 = 320; + } + for (uint8_t i = 0; i < NAXES; i++) { + _s[i] = NULL; + _registered[i] = false; + _lim[i].ticks_cfg = 0; + _lim[i].P_stop = 0; + _lim[i].accel = 0; + _lim[i].dir_before = 0; + _lim[i].dir_after = 0; + _tick_cfg[i] = 0; + _p[i] = 0; + _dir[i] = true; + _err[i] = 0; + _held[i].waiting = false; + _held[i].ticks = 0; + _held[i].steps = 0; + _held[i].count_up = true; + _carve_axis[i].active = false; + _carve_axis[i].phase = 0; + _carve_axis[i].step_left = 0; + _carve_axis[i].before = 0; + _carve_axis[i].after = 0; + _carve_axis[i].old_up = true; + _carve_axis[i].new_up = true; + for (uint16_t b = 0; b < HORIZON; b++) { + _blk[b][i] = 0; + _dwell[b] = 0; + } + } + _cfg = c; + _position_synced = false; + _block_count = 0; + _n_blk = 0; + _head = 0; + _path_closed = false; + _feeding = false; + _done = true; + _kicked_off = false; + _underrun = false; + _slice_open = false; + _error = false; + _fault = false; + _carve_then_advance = false; + _master = 0; + _abs_master = 0; + _block_left = 0; + _pause_left = 0; + _ticks_law = 1; + _Pramp = 0; + _Rstop = 0; + _ticks_last = 0; + } + + // Read-back of the recovered config defaults. + uint32_t dt_ticks() const { return _cfg.dt_ticks; } + uint16_t kappa_stop_q8() const { return _cfg.kappa_stop_q8; } + + // Register axis i to stepper s. Fails (returns false, no state change) when + // i is out of range, the pointer is null, or the stepper's ramp generator is + // active or the stepper is running — the feeder must never race a prior + // moveTo / manageSteppers. A small HORIZON relative to P_stop is NOT a + // failure: HORIZON only caps the planned ramp later (F19). + bool addAxis(uint8_t i, Stepper* s) { + if (i >= NAXES) { + return false; + } + if (s == NULL) { + return false; + } + if (s->isRampGeneratorActive() || s->isRunning()) { + return false; + } + // Discard any stop cause left over from pre-registration use (e.g. the + // homing stopMove), so pump() does not fault on it. + s->takeStopCause(); + _s[i] = s; + _registered[i] = true; + _lim[i].ticks_cfg = s->getMaxSpeedInTicks(); + _lim[i].accel = s->getAcceleration(); + read_dir_budget(i); + _tick_cfg[i] = _lim[i].ticks_cfg; + RampMap map(_lim[i].ticks_cfg, _lim[i].accel); + _lim[i].P_stop = map.P_coast(); + return true; + } + + // Re-read ticks_cfg / accel from every registered stepper and refresh P_stop. + void setLimitsFromSteppers() { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL) { + _lim[i].ticks_cfg = _s[i]->getMaxSpeedInTicks(); + _lim[i].accel = _s[i]->getAcceleration(); + read_dir_budget(i); + _tick_cfg[i] = _lim[i].ticks_cfg; + RampMap map(_lim[i].ticks_cfg, _lim[i].accel); + _lim[i].P_stop = map.P_coast(); + } + } + } + + // Set the current position from the steppers and open addWaypoint. + void syncFromSteppers() { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL) { + _p[i] = _s[i]->getCurrentPosition(); + } + } + clear_path(); + _position_synced = true; + } + + // Set the current position from a caller-supplied array and open addWaypoint. + void setCurrentPosition(const int32_t p[NAXES]) { + for (uint8_t i = 0; i < NAXES; i++) { + _p[i] = p[i]; + } + clear_path(); + _position_synced = true; + } + + // Queue an absolute target position (steps) by appending its delta to the + // block ring. Illegal (returns false) before the position is synced or when + // the ring is full (HORIZON points committed but not yet executed). A target + // equal to the current position (every delta 0) is a no-op that records no + // block and returns true. Appending after the plan already caught up with + // the buffer re-opens the plan (R may grow; section 8.7). + bool addWaypoint(const int32_t p[NAXES]) { + if (!_position_synced) { + return false; + } + bool any = false; + for (uint8_t i = 0; i < NAXES; i++) { + if (p[i] != _p[i]) { + any = true; + } + } + if (!any) { + return true; // L = 0: dwell of 0 ticks, no block recorded + } + if (_n_blk >= (int)HORIZON) { + compact_ring(); // drop executed blocks so the ring slides + if (_n_blk >= (int)HORIZON) { + return false; // ring full: backpressure until pump() drains + } + } + for (uint8_t i = 0; i < NAXES; i++) { + _blk[_n_blk][i] = p[i] - _p[i]; + _p[i] = p[i]; + } + _dwell[_n_blk] = 0; + _n_blk++; + _block_count++; + // A plan that had caught up to the buffer now has more path: feed the + // unexecuted tail on the next pump() (replan, section 8.7). + _done = false; + return true; + } + + // Number of motion blocks recorded by addWaypoint (0 after a no-op / a sync). + uint32_t block_count() const { return _block_count; } + + // Queue a dwell: a zero-motion block that issues pauses totalling `ticks` + // (split at 65535 like any long period) on every axis, from rest to rest + // (P is 0 on the way in and on the way out; the next addWaypoint starts from + // rest). It is a planned stop-and-wait, not a pause stuffed into a moving + // slice. Legal only when the position is synced; ticks == 0 is a no-op. + bool addDwellTicks(uint32_t ticks) { + if (!_position_synced) { + return false; + } + if (ticks == 0) { + return true; + } + if (_n_blk >= (int)HORIZON) { + compact_ring(); // drop executed blocks so the ring slides + if (_n_blk >= (int)HORIZON) { + return false; // ring full: backpressure until pump() drains + } + } + for (uint8_t i = 0; i < NAXES; i++) { + _blk[_n_blk][i] = 0; + } + _dwell[_n_blk] = ticks; + _n_blk++; + _block_count++; + _done = false; + return true; + } + + // Close the path: the last committed point is rest and R will not grow + // (section 10.3). + void endPath() { _path_closed = true; } + + // Plan and feed the committed Linear path (section 10.4). Prefill every axis + // with start=false, then kick off with the engine's synchronized start + // (StepperMotionEngine::synchronizedStart()): all active queues are + // released in one engine operation instead of one addQueueEntry(NULL, true) + // per axis. Later commands use start=true. An empty queue during prefill is + // expected and is not underrun; after kick-off an empty queue while the plan + // still moves is underrun (section 10.5). + PumpStatus pump() { + // An external stop of a member axis (manual stopMove, forceStop, e-stop) + // invalidates the coordinated plan: abort and report Stopped. Positions + // are untrusted until the caller re-homes and syncFromSteppers(). + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && _s[i]->takeStopCause() != StepperStopCause::None) { + _fault = true; + _feeding = false; + } + } + if (_fault) { + return PumpStatus::Stopped; + } + if (!_feeding && _head < _n_blk) { + feeder_start(); + feed_loop(); + if (!_error) { + Stepper* active[NAXES]; + uint8_t n_active = 0; + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && !_s[i]->isQueueEmpty()) { + active[n_active++] = _s[i]; + } + } + AqeResultCode rc = _engine->synchronizedStart(active, n_active); + _kicked_off = (n_active > 0); + if (rc != AqeResultCode::OK) { + _error = true; + } + } + } + if (!_error && _kicked_off && !_done) { + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && _s[i]->isQueueEmpty()) { + _underrun = true; + } + } + } + feed_loop(); + if (_error) { + return PumpStatus::Error; + } + if (_underrun) { + return PumpStatus::Underrun; + } + if (_done && !any_queue_nonempty()) { + _feeding = false; + _n_blk = 0; + _head = 0; + _path_closed = false; + _slice_open = false; + return PumpStatus::Idle; + } + if (!_feeding && !any_queue_nonempty()) { + return PumpStatus::Idle; + } + return PumpStatus::Running; + } + + bool isBusy() const { + if (_head < _n_blk || !_done) { + return true; + } + return any_queue_nonempty(); + } + + bool hasUnderrun() const { + if (_underrun) { + return true; + } + if (!_kicked_off || _done) { + return false; // prefill empty or plan settled: not an underrun + } + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && _s[i]->isQueueEmpty()) { + return true; // starved after kick-off with the plan still moving + } + } + return false; + } + + // True after a detected external stop (pump() returned Stopped) until the + // caller re-syncs with syncFromSteppers() or setCurrentPosition(), both of + // which go through clear_path(). + // + // There is deliberately no way to clear this without re-syncing. The planner + // reads getCurrentPosition() in exactly one place -- syncFromSteppers() -- so + // _p[] is otherwise a purely *commanded* model advanced by planned deltas. + // An external stop leaves it diverged from the hardware by whatever motion + // was lost, and the blocks still queued are deltas from _p[], so feeding them + // would resume toward a target offset by that error, silently. A + // clearFault() existed for that and has been removed: it could only ever + // resume a plan whose position model was known-wrong. + bool isFaulted() const { return _fault; } + + // Group emergency stop: forceStop() every member immediately, abort the plan + // and mark positions untrusted. Re-entrancy safe: it does not call pump(). + void emergencyStop() { + _fault = true; + _feeding = false; + _kicked_off = false; + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i]) { + _s[i]->forceStop(); + } + } + } + + // Section 8.2 / 14.7: short lookahead is a speed cap, not an error. True + // while the path is still open (!_path_closed, executing head not past the + // buffer) and the live remaining-to-stop of the DDA master is below its + // P_stop (the configured max is unreachable from this buffer). False on a + // closed path and when R is large enough to coast. + bool isSpeedLimitedByLookahead() const { + if (_path_closed || _head >= _n_blk) { + return false; + } + uint8_t m = (uint8_t)_master; + return _Rstop < _lim[m].P_stop; + } + + // Diagnostic outs (no string, no heap): the DDA master axis, its live + // remaining-to-stop R, its P_stop, and the template HORIZON. + void lookaheadHint(uint8_t* axis, uint32_t* R, uint32_t* P_stop, + uint16_t* horizon) const { + if (axis != NULL) { + *axis = (uint8_t)_master; + } + if (R != NULL) { + *R = _Rstop; + } + if (P_stop != NULL) { + *P_stop = _lim[_master].P_stop; + } + if (horizon != NULL) { + *horizon = HORIZON; + } + } + + // Performed ramp-up steps of the current segment's DDA master (section 7.1). + uint32_t performedRampUp() const { return _Pramp; } + // Live remaining-to-stop of the master in path steps (section 8.2). + uint32_t remainingToStop() const { return _Rstop; } + // Per-axis diagnostics for the plots. Overshoot keeps one persistent P per + // axis (section 8.6), so two axes can differ at the same instant and a single + // scalar is only the binder's; Linear's P is the shared path ramp, so every + // axis reports the same value. + uint32_t performedRampUpAxis(uint8_t i) const { + if (i >= NAXES) { + return 0; + } + return overshoot_mode() ? _ovs.P[i] : _law.P; + } + uint32_t remainingToStopAxis(uint8_t i) const { + if (i >= NAXES) { + return 0; + } + return overshoot_mode() ? _ovs.R[i] : _law.R; + } + // Period (ticks) of the last issued step entry. + uint32_t lastTicks() const { return _ticks_last; } + // DDA master axis of the current block (longest |delta|). + uint8_t masterAxis() const { return (uint8_t)_master; } + // Number of blocks committed but not yet fully executed. + int pendingBlocks() const { return _n_blk - _head; } + + private: + bool any_queue_nonempty() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && !_s[i]->isQueueEmpty()) { + return true; + } + } + return false; + } + + // Reserve two slots on every queue (QUEUE_LEN - 2) so a coordinated slice -- + // and the pause-stuffed entry a long period may split into -- always fits. + // isQueueFull() alone allows QUEUE_LEN - 1 and cannot express this reserve. + bool all_have_room() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && + ((uint32_t)_s[i]->queueEntries() + 2) >= (uint32_t)QUEUE_LEN) { + return false; + } + } + return true; + } + + // Drop blocks the feeder has fully executed, rebasing the executing head to + // 0 so the block array is a sliding window of at most HORIZON *pending* + // points (whitepaper section 8). Without this the array only grows, + // addWaypoint backpressures once HORIZON points have *ever* been appended, + // and a path longer than HORIZON runs in chunks that each ramp to rest. Live + // state indexes _blk[_head] / _blk[_head + 1] by the rebased head, so it + // stays valid across the shift. + void compact_ring() { + if (_head <= 0) { + return; + } + int pending = _n_blk - _head; + for (int b = 0; b < pending; b++) { + for (uint8_t i = 0; i < NAXES; i++) { + _blk[b][i] = _blk[_head + b][i]; + } + _dwell[b] = _dwell[_head + b]; + } + _n_blk = pending; + _head = 0; + } + + // Read the DIR pause budget from the stepper (whitepaper section 4.4). The + // config override is applied at use time in reverse_budget(), not here. + void read_dir_budget(uint8_t i) { + _lim[i].dir_before = _s[i]->getDirChangeBeforeTicks(); + _lim[i].dir_after = _s[i]->getDirChangeAfterTicks(); + } + + // Resolve the reverse budget for axis i: config override when non-zero, else + // the stepper getter. + void reverse_budget(uint8_t i, uint16_t* before, uint16_t* after) const { + *before = + _cfg.dir_before_ticks != 0 ? _cfg.dir_before_ticks : _lim[i].dir_before; + *after = + _cfg.dir_after_ticks != 0 ? _cfg.dir_after_ticks : _lim[i].dir_after; + } + + uint32_t reverse_tau(uint8_t i) const { + uint16_t before = 0; + uint16_t after = 0; + reverse_budget(i, &before, &after); + return (uint32_t)before + (uint32_t)after; + } + + // Axis i reverses between block b and the next buffered block. + bool reverses_at_end(int b, uint8_t i) const { + if (b + 1 >= _n_blk) { + return false; + } + int32_t cur = _blk[b][i]; + int32_t nxt = _blk[b + 1][i]; + if (cur == 0 || nxt == 0) { + return false; + } + return (cur > 0) != (nxt > 0); + } + + // One axis's pending DIR carve: a shortened last step (old DIR) plus the + // before-pause (old DIR) plus one after-pause (new DIR), tick sum unchanged. + struct Carve { + bool active; + uint8_t phase; // 0 shortened step, 1 before-pause, 2 after-pause + uint32_t step_left; // remaining wait of the shortened step + uint16_t before; + uint16_t after; + bool old_up; + bool new_up; + }; + + bool any_carve() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_carve_axis[i].active) { + return true; + } + } + return false; + } + + // Arm the carve on axis i for the last old-direction step of period T. The + // step keeps its period T and the DIR pause (tau) is inserted after it, so + // the period never jumps and the reversing axis's timeline grows by tau. This + // matches the normal ramp generator (which injects a DIR pause rather than + // shortening a step). Section 4.4.2. + void start_carve(uint8_t i, uint32_t T, bool new_up) { + uint16_t before = 0; + uint16_t after = 0; + reverse_budget(i, &before, &after); + uint32_t tau = (uint32_t)before + (uint32_t)after; + if (tau == 0) { + return; + } + Carve& c = _carve_axis[i]; + c.active = true; + c.phase = 0; + c.step_left = T; + c.before = before; + c.after = after; + c.old_up = _dir[i]; + c.new_up = new_up; + } + + // Emit one command of axis i's carve (at most one per call). `held` reports + // whether a command was placed in the slice. + void carve_emit(uint8_t i, bool* held) { + Carve& c = _carve_axis[i]; + if (!c.active) { + return; + } + if (c.phase == 0) { + uint32_t left = c.step_left; + uint16_t t; + if (left > 65535) { + uint32_t half = left >> 1; + if (half > 65535) { + half = 65535; + } + if (half < _ticks_law) { + half = _ticks_law; + } + if (half > 65535) { + half = 65535; + } + t = (uint16_t)half; + } else { + t = (uint16_t)left; + } + hold(i, t, 1, c.old_up); + c.step_left -= t; + if (c.step_left == 0) { + c.phase = 1; + } + *held = true; + return; + } + if (c.phase == 1) { + if (c.before > 0) { + hold(i, c.before, 0, c.old_up); + c.before = 0; + *held = true; + return; + } + c.phase = 2; + } + if (c.phase == 2) { + if (c.after > 0) { + hold(i, c.after, 0, c.new_up); + c.after = 0; + *held = true; + return; + } + c.phase = 3; + } + if (c.phase >= 3) { + _dir[i] = c.new_up; + c.active = false; + } + } + + // Drive every active carve one command per pass until at least one command is + // held. Only the carving axes are sent; every other axis keeps the command it + // was already given for those ticks. + void feed_carve() { + bool held = false; + for (uint8_t guard = 0; guard < 8; guard++) { + bool any = false; + for (uint8_t i = 0; i < NAXES; i++) { + if (_carve_axis[i].active) { + any = true; + carve_emit(i, &held); + } + } + if (!any || held) { + break; + } + } + if (!any_carve() && _carve_then_advance) { + _carve_then_advance = false; + advance_block(); + } + _slice_open = held; + } + + void clear_path() { + _n_blk = 0; + _head = 0; + _path_closed = false; + _feeding = false; + _done = true; + _kicked_off = false; + _underrun = false; + _block_count = 0; + _block_left = 0; + _pause_left = 0; + _Pramp = 0; + _Rstop = 0; + _ticks_last = 0; + _slice_open = false; + _error = false; + _fault = false; + // Rearm the queue admission latches. A member force-stopped outside the + // planner left its queue refusing every addQueueEntry() with + // AQE_ERROR_COMMANDS_SUSPENDED, so without this a re-planned path would + // queue nothing. This is the only place it is safe: clear_path() is + // reached solely from syncFromSteppers() / setCurrentPosition(), i.e. the + // caller has just re-synced and is about to build a new plan. + // + // Deliberately NOT in feeder_start(). That is also reachable from a bare + // _fault reset, which would resume the *old* blocks with positions the + // caller never re-synced; rearming there would make that unsafe recovery + // succeed silently instead of failing with PumpStatus::Error. + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i]) { + _s[i]->resumeCommands(); + } + } + _carve_then_advance = false; + for (uint8_t i = 0; i < NAXES; i++) { + _held[i].waiting = false; + _carve_axis[i].active = false; + // Drain any pending stop cause. Without this a re-sync is not + // self-sufficient: clear_path() clears _fault, but the cause is still + // unread, so the next pump() sees takeStopCause() != None and re-faults + // the plan. It only worked because pump() happened to drain the cause on + // its way to reporting Stopped -- so the ordering + // forceStop() -> syncFromSteppers() -> pump() stayed faulted forever, + // while sync-after-pump() recovered. + if (_registered[i]) { + _s[i]->takeStopCause(); + } + } + } + + // Store one axis's slot of the slice currently being emitted (Step 8). The + // command is not sent until flush_held(); that lets the paired axes re-send a + // held command without re-planning the slice. + void hold(uint8_t i, uint16_t ticks, uint8_t steps, bool count_up) { + _held[i].ticks = ticks; + _held[i].steps = steps; + _held[i].count_up = count_up; + _held[i].waiting = true; + } + + bool any_waiting() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i] && _held[i].waiting) { + return true; + } + } + return false; + } + + // Send the held slice to every axis still waiting. AQE_OK clears waiting; a + // retryable code (QueueFull / DirPinIsBusy / WaitForEnablePinActive / + // DeviceNotReady) leaves it set so the next pump() re-sends the same command. + // The error codes are terminal: set _error and report it. + AqeResultCode flush_held() { + AqeResultCode retry = AqeResultCode::OK; + for (uint8_t i = 0; i < NAXES; i++) { + if (!_registered[i] || !_held[i].waiting) { + continue; + } + struct stepper_command_s cmd = {_held[i].ticks, _held[i].steps, + _held[i].count_up}; + AqeResultCode rc = _s[i]->addQueueEntry(&cmd, _kicked_off); + if (rc == AqeResultCode::OK) { + _held[i].waiting = false; + } else if (aqeIsPauseInjected(rc)) { + // Injected DIR pause: planner failure (whitepaper §4.4.3). + _error = true; + } else if (aqeRetry(rc)) { + retry = rc; + } else { + _error = true; // TicksTooLow and any other terminal code + } + } + if (!any_waiting()) { + _slice_open = false; + } + return retry; + } + + // Emit slices while there is room and the path is live. Building is one + // feed_one() per open slice; flushing is one flush_held() per slice. A + // retryable flush stops this pump() call (the held slice is retried on the + // next call) so a single pump never plans past an unaccepted command. + void feed_loop() { + while (!_error) { + if (!_slice_open) { + if (_done || !all_have_room()) { + break; + } + feed_one(); + if (!_slice_open) { + break; + } + } + AqeResultCode rc = flush_held(); + if (rc != AqeResultCode::OK || _done) { + break; + } + } + } + + // Remaining master steps from `head` to the next Linear hard stop + // (section 8.5): master-sense reversal, outgoing master that was idle, + // dwell, or the last buffered point. P carries across every other joint. + uint32_t remaining_path_steps(int head) const { + uint32_t acc[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + acc[i] = _lim[i].accel; + } + return Remaining::linear_remaining(head, _n_blk, NAXES, _tick_cfg, + acc, 0xFFFFFFFFU, _blk); + } + + // Section 8.6 per-axis scan from `head`: sum |delta_i| while axis i keeps its + // sign, stopping at the first axis reversal or idle-after-moving, or at the + // last buffered block. This is the Overshoot R_i (remaining steps in the + // current direction), independent of the other axes. + uint32_t remaining_axis_steps(int axis, int head) const { + uint32_t s = 0; + int sign = 0; + for (int b = head; b < _n_blk; b++) { + int32_t d = _blk[b][axis]; + if (d == 0) { + if (sign != 0) { + break; // axis went idle after moving + } + continue; + } + int sg = d > 0 ? 1 : -1; + if (sign == 0) { + sign = sg; + } + if (sg != sign) { + break; // reversal + } + s += fas_abs(d); + } + return s; + } + + // Set up the ramp law and DDA state for block `b`. `reset_P` is false when + // the joint is not a hard stop (P carries); R is recomputed from `b`. + void start_block(int b, bool reset_P) { + _head = b; + _master = Remaining::longest_axis(_blk[b], _tick_cfg, NAXES); + uint32_t t_law = Remaining::ticks_floor(_blk[b], _tick_cfg, NAXES); + if (t_law == 0) { + t_law = _tick_cfg[_master] != 0 ? _tick_cfg[_master] : 1; + } + _ticks_law = t_law; + int binder = Remaining::binder_axis(_blk[b], _tick_cfg, NAXES); + // The DIR pause is inserted *after* the last step (like the normal ramp + // generator), not carved out of it, so no acceleration cap is needed: the + // step keeps the period the ramp reaches and the pause is added (§4.4.2). + uint32_t accel = _lim[binder].accel; + uint32_t R_new = remaining_path_steps(b); + if (R_new == 0) { + R_new = fas_abs(_blk[b][_master]); + } + uint32_t carry = reset_P ? 0 : _law.P; + _law = RampLaw(t_law, accel, R_new); + uint32_t coast = _law.map.P_coast(); + if (carry > coast) { + carry = coast; + } + if (carry > R_new) { + carry = R_new; + } + _law.P = carry; + _abs_master = fas_abs(_blk[b][_master]); + _block_left = fas_abs(_blk[b][_master]); + for (uint8_t i = 0; i < NAXES; i++) { + _err[i] = 0; + } + _pause_left = _dwell[b]; // a dwell block emits its pauses, then advances + _Pramp = _law.P; + _Rstop = _law.R; + _ticks_last = 0; + } + + // Overshoot is selected only for the explicit mode with a non-zero cap + // (overshoot_max == 0 is the Linear limit, whitepaper section 6.5). + bool overshoot_mode() const { + return _cfg.mode == FasNAxisConfig::Overshoot && _cfg.overshoot_max != 0; + } + + // Set up an Overshoot block from `b`: per-axis ramps decide the binding axis + // (largest T_opt) and every command lasts one of its periods. P carries + // across a continuing vertex and resets at a reversal/idle (section 8.6); + // the non-binding axes ride along on the same tick sum (sections 6.4 / 7.3). + void start_overshoot(int b) { + int32_t d[NAXES] = {0}; + uint32_t rr[NAXES] = {0}; + for (uint8_t i = 0; i < NAXES; i++) { + d[i] = _blk[b][i]; + rr[i] = remaining_axis_steps(i, b); + } + _ovs.start_block(d, rr); + _head = b; + _master = _ovs.binder; + _ticks_law = Remaining::ticks_floor(_blk[b], _tick_cfg, NAXES); + if (_ticks_law == 0) { + _ticks_law = _tick_cfg[_master] != 0 ? _tick_cfg[_master] : 1; + } + _pause_left = 0; + _Pramp = _ovs.P[_ovs.binder]; + _Rstop = _ovs.R[_ovs.binder]; + _ticks_last = 0; + for (uint8_t i = 0; i < NAXES; i++) { + _err[i] = 0; + } + } + + // The current block's walk is exhausted. + bool block_done() const { + if (_dwell[_head] > 0) { + return _pause_left == 0; // dwell: done once its pauses are emitted + } + if (overshoot_mode()) { + return _ovs.done(); + } + return _block_left == 0; + } + + // Move to the next committed block. Overshoot carries P per axis + // (section 8.6). Linear resets P only at a hard stop (section 8.5) and + // carries it across every other joint, including a master-role change. + void advance_block() { + int prev = _head; + _head++; + if (_head >= _n_blk) { + _done = true; // last buffered point is rest + return; + } + if (overshoot_mode()) { + start_overshoot(_head); + if (_dwell[_head] > 0) { + _pause_left = _dwell[_head]; + } + return; + } + bool stop = Remaining::linear_joint_stops(_blk[prev], _blk[_head], + _tick_cfg, NAXES); + start_block(_head, stop); + } + + void feeder_start() { + _feeding = true; + _done = false; + _underrun = false; + for (uint8_t i = 0; i < NAXES; i++) { + _dir[i] = true; + } + if (overshoot_mode()) { + uint32_t ac[NAXES] = {0}; + for (uint8_t i = 0; i < NAXES; i++) { + ac[i] = _lim[i].accel; + } + _ovs.configure(NAXES, _tick_cfg, ac, _cfg.overshoot_max); + start_overshoot(_head); + if (_dwell[_head] > 0) { + _pause_left = _dwell[_head]; + } + return; + } + start_block(_head, true); + } + + // True when a DIR carve must keep the block's last master step as its own + // one-step command. + bool leave_last_for_carve() const { + if (_block_left <= 1) { + return false; + } + for (uint8_t i = 0; i < NAXES; i++) { + if (!_registered[i] || !reverses_at_end(_head, i)) { + continue; + } + if (reverse_tau(i) > 0) { + return true; + } + } + return false; + } + + // Per-axis per-step ticks for a batch of `n` master steps at period `T` + // with signed net `net[i]`. Idle axes get one pause of `n * T`. A moving + // axis gets `ticks * |net| == n * T` exactly (multiply check, no `/`). + // Returns false when that product is not exact or does not fit in 16 bits. + bool linear_batch_ticks(const int32_t* net, uint32_t n, uint32_t T, + uint16_t* ticks_out) const { + uint32_t total = n * T; + if (n == 0 || total == 0 || total > 65535u) { + return false; + } + for (uint8_t i = 0; i < NAXES; i++) { + if (!_registered[i]) { + continue; + } + int32_t v = net[i]; + if (v == 0) { + ticks_out[i] = (uint16_t)total; + continue; + } + uint32_t k = v > 0 ? (uint32_t)v : (uint32_t)(-v); + if (k > 255u) { + return false; + } + uint32_t ts = T; + if (k != n) { + ts = log2_to_u32(log2_divide(log2_from(total), log2_from(k))); + if (ts == 0 || ts * k != total) { + return false; + } + } + if (ts > 65535u || ts < _tick_cfg[i]) { + return false; + } + ticks_out[i] = (uint16_t)ts; + } + return true; + } + + // One Bresenham step of the current block, applied to `err` / `net`. + void linear_dda_step(int32_t* err, int32_t* net) const { + int master_sign = _blk[_head][_master] > 0 ? 1 : -1; + net[_master] += master_sign; + for (uint8_t i = 0; i < NAXES; i++) { + if (i == (uint8_t)_master) { + continue; + } + uint32_t ad = fas_abs(_blk[_head][i]); + if (ad == 0) { + continue; + } + err[i] += (int32_t)ad; + if (err[i] > 0 && + Remaining::u32_twice_ge((uint32_t)err[i], _abs_master)) { + net[i] += _blk[_head][i] > 0 ? 1 : -1; + err[i] -= (int32_t)_abs_master; + } + } + } + + void law_restore(uint32_t p, uint32_t r, uint32_t total) { + _law.P = p; + _law.R = r; + _law.total_ticks = total; + } + + // Ramp-generator batch: when the step period is under 1 ms, pack equal + // periods into one command of about 2 ms (TICKS_PER_S / 500), and stop + // before a DIR carve or a period change. Returns 0 when fewer than two + // steps fit, leaving the law and the DDA untouched. The law is stepped + // and rolled back; there is no second copy of the ramp state. + uint32_t plan_linear_batch(int st[NAXES], uint16_t* ticks_out, + uint32_t* period_out) { + if (_block_left < 2) { + return 0; + } + uint32_t p0 = _law.P; + uint32_t r0 = _law.R; + uint32_t tot0 = _law.total_ticks; + uint32_t T = _law.step(); + law_restore(p0, r0, tot0); + uint32_t one_ms = (uint32_t)(TICKS_PER_S / 1000); + if (T == 0 || T >= one_ms || T > 65535u) { + return 0; + } + uint32_t budget = (uint32_t)(TICKS_PER_S / 500); + if (budget > 65535u) { + budget = 65535u; + } + uint32_t room = _block_left; + if (leave_last_for_carve() && room > 0) { + room--; + } + if (room < 2) { + return 0; + } + uint32_t max_n = 1; + uint32_t acc_ticks = T; + while (max_n < room && max_n < 255u && acc_ticks + T <= budget) { + max_n++; + acc_ticks += T; + } + if (max_n < 2) { + return 0; + } + + int32_t err[NAXES]; + int32_t net[NAXES]; + uint16_t ticks_ok[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + err[i] = _err[i]; + net[i] = 0; + ticks_ok[i] = 0; + } + uint32_t n_ok = 0; + for (uint32_t s = 0; s < max_n; s++) { + uint32_t ps = _law.P; + uint32_t rs = _law.R; + uint32_t ts = _law.total_ticks; + uint32_t t = _law.step(); + if (t != T) { + law_restore(ps, rs, ts); + break; + } + int32_t err_try[NAXES]; + int32_t net_try[NAXES]; + uint16_t ticks_try[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + err_try[i] = err[i]; + net_try[i] = net[i]; + } + linear_dda_step(err_try, net_try); + if (!linear_batch_ticks(net_try, s + 1, T, ticks_try)) { + law_restore(ps, rs, ts); + break; + } + for (uint8_t i = 0; i < NAXES; i++) { + err[i] = err_try[i]; + net[i] = net_try[i]; + ticks_ok[i] = ticks_try[i]; + } + n_ok = s + 1; + } + if (n_ok < 2) { + law_restore(p0, r0, tot0); + return 0; + } + for (uint8_t i = 0; i < NAXES; i++) { + _err[i] = err[i]; + st[i] = net[i]; + ticks_out[i] = ticks_ok[i]; + } + _block_left -= n_ok; + *period_out = T; + return n_ok; + } + + // Emit at most one queue entry per registered axis per call, so the axes stay + // in lockstep. A fast coast is one multi-step command (section 4.3.1). A + // master step with a period above 65535 is a half-period step entry followed + // by pause entries covering the remainder (sections 4.2 / 9.3). + void feed_one() { + if (_done || _slice_open) { + return; + } + if (any_carve()) { + feed_carve(); + return; + } + if (_pause_left > 0) { + uint32_t chunk = _pause_left; + if (chunk > 65535) { + chunk >>= 1; + if (chunk > 65535) { + chunk = 65535; + } + } + for (uint8_t i = 0; i < NAXES; i++) { + if (_registered[i]) { + hold(i, (uint16_t)chunk, 0, _dir[i]); + } + } + _slice_open = true; + _pause_left -= chunk; + if (_pause_left == 0 && block_done()) { + advance_block(); + } + return; + } + if (block_done()) { + advance_block(); + if (_done) { + return; + } + } + + uint32_t T; + int st[NAXES]; + uint16_t batch_ticks[NAXES]; + bool batched = false; + for (uint8_t i = 0; i < NAXES; i++) { + st[i] = 0; + batch_ticks[i] = 0; + } + if (overshoot_mode()) { + // Overshoot: one command per binding RampLaw step; the non-binding axes + // ride along on the same tick sum (whitepaper sections 6.4 / 7.3). + T = _ovs.step(st); + if (T == 0) { + _done = true; + return; + } + _Pramp = _ovs.P[_ovs.binder]; + _Rstop = _ovs.R[_ovs.binder]; + _ticks_last = T; + } else if (plan_linear_batch(st, batch_ticks, &T) >= 2) { + batched = true; + _Pramp = _law.P; + _Rstop = _law.R; + _ticks_last = T; + } else { + T = _law.step(); + _Pramp = _law.P; + _Rstop = _law.R; + _ticks_last = T; + int32_t net[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + net[i] = 0; + } + linear_dda_step(_err, net); + for (uint8_t i = 0; i < NAXES; i++) { + st[i] = net[i]; + } + } + + uint32_t t_step = T; + if (T > 65535) { + t_step = T >> 1; + if (t_step > 65535) { + t_step = 65535; + } + if (t_step < _ticks_law) { + t_step = _ticks_law; // keep the step entry at or above the envelope + if (t_step > 65535) { + t_step = 65535; + } + } + _pause_left = T - t_step; + } + + // At the last binder step before a reversal with a DIR budget, carve the + // pause out of the reversing axis's own last step (whitepaper section 4.4). + // Only the 16-bit-representable tail is carved here; a longer tail keeps + // the §9.3 stuffing path unchanged. + bool last_cmd = + batched ? false + : (overshoot_mode() ? _ovs.last_command() : (_block_left == 1)); + bool carving = false; + if (last_cmd && T <= 65535) { + for (uint8_t i = 0; i < NAXES; i++) { + if (!_registered[i] || st[i] == 0 || !reverses_at_end(_head, i)) { + continue; + } + if (reverse_tau(i) == 0) { + continue; + } + if (overshoot_mode() && (st[i] > 1 || st[i] < -1)) { + continue; // a carve is a one-step split + } + start_carve(i, T, _blk[_head + 1][i] > 0); + carving = true; + } + } + + for (uint8_t i = 0; i < NAXES; i++) { + if (!_registered[i]) { + continue; + } + if (_carve_axis[i].active) { + bool h = false; + carve_emit(i, &h); + continue; + } + uint8_t steps = st[i] > 0 ? (uint8_t)st[i] : (uint8_t)(-st[i]); + bool up = st[i] != 0 ? (st[i] > 0) : _dir[i]; + if (st[i] != 0) { + _dir[i] = up; + } + // Overshoot catch-up: `steps` pulses in this slice must span the same + // t_step ticks as every other axis, so each pulse is t_step / steps + // (log2 divide, section 9.3), floored to the axis envelope. + uint16_t ticks_i = batched ? batch_ticks[i] : (uint16_t)t_step; + if (overshoot_mode() && steps > 1) { + uint32_t tt = log2_to_u32( + log2_divide(log2_from((uint32_t)t_step), log2_from(steps))); + if (tt < _tick_cfg[i]) { + tt = _tick_cfg[i]; + } + if (tt < (uint32_t)MIN_CMD_TICKS) { + tt = (uint32_t)MIN_CMD_TICKS; + } + if (tt > 65535) { + tt = 65535; + } + ticks_i = (uint16_t)tt; + } + hold(i, ticks_i, steps, up); + } + _slice_open = true; + if (!overshoot_mode() && !batched) { + _block_left--; + } + if (carving) { + // The carve sequence is flushed over the next feed_one() calls; the next + // block only starts once every carving axis has finished. + _carve_then_advance = true; + return; + } + if (_pause_left == 0 && block_done()) { + advance_block(); + } + } + + // One held command per axis (Step 8): the slice being emitted. waiting stays + // set until addQueueEntry returns AQE_OK, so a retryable fault re-sends the + // same command on the next pump without re-planning the slice. + struct Held { + bool waiting; + uint16_t ticks; + uint8_t steps; + bool count_up; + }; + + Stepper* _s[NAXES]; + AxisLimits _lim[NAXES]; + uint32_t _tick_cfg[NAXES]; + int32_t _p[NAXES]; + int32_t _err[NAXES]; + bool _dir[NAXES]; + int32_t _blk[HORIZON][NAXES]; + uint32_t _dwell[HORIZON]; + FasNAxisConfig _cfg; + bool _registered[NAXES]; + bool _position_synced; + uint32_t _block_count; + int _n_blk; + int _head; + bool _path_closed; + bool _feeding; + bool _done; + bool _kicked_off; + Engine* _engine; + bool _underrun; + bool _slice_open; + bool _error; + bool _fault; + Held _held[NAXES]; + Carve _carve_axis[NAXES]; + bool _carve_then_advance; + int _master; + uint32_t _abs_master; + uint32_t _block_left; + uint32_t _pause_left; + uint32_t _ticks_law; + uint32_t _Pramp; + uint32_t _Rstop; + uint32_t _ticks_last; + RampLaw _law; + OvershootRun _ovs; +}; + +#endif /* FAS_NAXIS_H */ diff --git a/src/FasTimed.h b/src/FasTimed.h new file mode 100644 index 0000000..66f3cbc --- /dev/null +++ b/src/FasTimed.h @@ -0,0 +1,659 @@ +#ifndef FAS_TIMED_H +#define FAS_TIMED_H + +#include + +#include "fas_arch/common.h" +#include "fas_naxis/ramp_map.h" + +// Default template arguments. The header does not include StepperMotion.h; +// production callers pass the real types, PC tests pass SimPort. +class StepperMotion; +class StepperMotionEngine; + +// Result of FasTimed::addDelta. Rejected is a bad call (not synced, ring +// full, |steps| > 128, ticks < MIN_CMD_TICKS). TimingNotAchievable is a +// feasible-rate failure: faster than the axis limit, a ramp-step jump the +// chunk cannot cover, or a duration the queue cannot emit within |delta| +// ticks of the request. A too-slow request is not rewritten into a faster +// one. +enum class TimedAdd : uint8_t { Ok = 0, Rejected = 1, TimingNotAchievable = 2 }; + +// Result of FasTimed::pump. Underrun latches until syncFromSteppers / +// setCurrentPosition. Stopped latches the same way after an external stop. +enum class TimedStatus : uint8_t { + Idle = 0, + Running = 1, + Underrun = 2, + Error = 3, + Stopped = 4 +}; + +// Faithful timed trajectory (whitepaper section 3.3 problem 2). Not a +// FasNAxis mode: each waypoint is one constant rate, and the planner does +// not invent a ramp between waypoints. +// +// TimedAdd addDelta(const int16_t steps[NAXES], uint16_t ticks); +// +// steps[i] is in [-128, 128]. ticks is the shared duration of those steps, +// in driver ticks, and must lie in [MIN_CMD_TICKS, 65535]. All-zero steps +// are a dwell on that common clock. One call has one sign per axis. +// +// The feeder emits one or two addQueueEntry commands per axis whose tick +// sums are equal. When the requested duration is not an exact legal command +// split, the shared sum moves to the nearest duration that is, and no +// farther than the longest |delta| of the call. actualTicks() is that sum. +// +// HORIZON is only the number of chunks waiting to be queued. Each chunk is +// already one command, so the ring stays small (default 8). A longer path +// streams: addDelta until it returns Rejected, pump, and add again. +template +class FasTimed { + public: + explicit FasTimed(Engine& engine) : _engine(&engine), _chunk{} { + for (uint8_t i = 0; i < NAXES; i++) { + _s[i] = NULL; + _min_period[i] = 0; + _accel[i] = 0; + _p[i] = 0; + _ramp_p[i] = 0; + _sign[i] = 0; + _count_up[i] = true; + _held[i].waiting = false; + _held[i].ticks = 0; + _held[i].steps = 0; + _held[i].count_up = true; + } + _count = 0; + _actual = 0; + _synced = false; + _kicked = false; + _underrun = false; + _error = false; + _fault = false; + } + + // Register axis i. Fails when i is out of range, s is null, or the + // stepper's ramp generator is active or the queue is already running. + // Speed and acceleration are read here and stay until the next addAxis. + bool addAxis(uint8_t i, Stepper* s) { + if (i >= NAXES || s == NULL) { + return false; + } + if (s->isRampGeneratorActive() || s->isRunning()) { + return false; + } + s->takeStopCause(); + _s[i] = s; + _min_period[i] = s->getMaxSpeedInTicks(); + _accel[i] = s->getAcceleration(); + return true; + } + + void syncFromSteppers() { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL) { + _p[i] = _s[i]->getCurrentPosition(); + } + } + clear_plan(); + _synced = true; + } + + void setCurrentPosition(const int32_t p[NAXES]) { + for (uint8_t i = 0; i < NAXES; i++) { + _p[i] = p[i]; + } + clear_plan(); + _synced = true; + } + + // Queue one constant-rate chunk. See the file comment for the waypoint + // shape. On Ok the planned position advances by steps and actualTicks() + // grows by the duration that will be issued. + TimedAdd addDelta(const int16_t steps[NAXES], uint16_t ticks) { + if (_fault || _error || !_synced || !all_registered()) { + return TimedAdd::Rejected; + } + if (ticks < MIN_CMD_TICKS) { + return TimedAdd::Rejected; + } + uint16_t mag[NAXES]; + int sign[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + if (steps[i] > 128 || steps[i] < -128) { + return TimedAdd::Rejected; + } + if (steps[i] < 0) { + mag[i] = (uint16_t)(-steps[i]); + sign[i] = -1; + } else if (steps[i] > 0) { + mag[i] = (uint16_t)steps[i]; + sign[i] = 1; + } else { + mag[i] = 0; + sign[i] = 0; + } + } + if (_count >= HORIZON) { + return TimedAdd::Rejected; + } + if (!speed_ok(mag, ticks)) { + return TimedAdd::TimingNotAchievable; + } + uint16_t issued = 0; + if (!find_duration(mag, ticks, &issued)) { + return TimedAdd::TimingNotAchievable; + } + uint32_t p_act[NAXES]; + for (uint8_t i = 0; i < NAXES; i++) { + p_act[i] = 0; + if (mag[i] == 0) { + if (!change_ok(i, 0, 0, 0, &p_act[i])) { + return TimedAdd::TimingNotAchievable; + } + continue; + } + uint16_t tau_req = 0; + uint16_t tau_act = 0; + uint16_t rem = 0; + udiv_u16(ticks, mag[i], &tau_req, &rem); + udiv_u16(issued, mag[i], &tau_act, &rem); + uint32_t ignore = 0; + if (!change_ok(i, mag[i], sign[i], tau_req, &ignore)) { + return TimedAdd::TimingNotAchievable; + } + if (tau_act != tau_req && + !change_ok(i, mag[i], sign[i], tau_act, &p_act[i])) { + return TimedAdd::TimingNotAchievable; + } + if (tau_act == tau_req) { + p_act[i] = ignore; + } + } + + Chunk chunk; + clear_chunk(&chunk); + for (uint8_t i = 0; i < NAXES; i++) { + fill_axis(&chunk, i, steps[i], mag[i], issued); + } + _chunk[_count] = chunk; + _count++; + _actual += issued; + for (uint8_t i = 0; i < NAXES; i++) { + _p[i] += steps[i]; + _ramp_p[i] = p_act[i]; + if (mag[i] != 0) { + _sign[i] = (int8_t)sign[i]; + _count_up[i] = steps[i] > 0; + } + } + return TimedAdd::Ok; + } + + int32_t plannedPosition(uint8_t i) const { + if (i >= NAXES) { + return 0; + } + return _p[i]; + } + + // Sum of the durations actually committed, in driver ticks. + uint32_t actualTicks() const { return _actual; } + + bool isBusy() const { + if (_count > 0 || any_waiting()) { + return true; + } + return any_queue_nonempty(); + } + + // Prefill with start=false, then one engine synchronizedStart. A retryable + // addQueueEntry stops this call; the held command is sent again on the + // next pump. An injected DIR pause the plan did not emit is Error. + TimedStatus pump() { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL && _s[i]->takeStopCause() != StepperStopCause::None) { + _fault = true; + } + } + if (_fault) { + return TimedStatus::Stopped; + } + if (_kicked && !any_waiting() && _count > 0 && any_queue_empty()) { + _underrun = true; + } + feed_loop(); + if (!_error && !_kicked && any_queue_nonempty()) { + Stepper* active[NAXES]; + uint8_t n_active = 0; + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL && !_s[i]->isQueueEmpty()) { + active[n_active++] = _s[i]; + } + } + AqeResultCode rc = _engine->synchronizedStart(active, n_active); + _kicked = n_active > 0; + if (rc != AqeResultCode::OK) { + _error = true; + } + } + if (_error) { + return TimedStatus::Error; + } + if (_underrun) { + return TimedStatus::Underrun; + } + if (_count == 0 && !any_waiting() && !any_queue_nonempty()) { + _kicked = false; + return TimedStatus::Idle; + } + return TimedStatus::Running; + } + + private: + struct Qcmd { + uint16_t ticks; + uint8_t steps; + bool count_up; + }; + struct Chunk { + Qcmd cmd[NAXES][2]; + uint8_t ncmd[NAXES]; + uint8_t sent[NAXES]; + }; + struct Held { + bool waiting; + uint16_t ticks; + uint8_t steps; + bool count_up; + }; + + Engine* _engine; + Stepper* _s[NAXES]; + uint32_t _min_period[NAXES]; + uint32_t _accel[NAXES]; + int32_t _p[NAXES]; + uint32_t _ramp_p[NAXES]; + int8_t _sign[NAXES]; + bool _count_up[NAXES]; + Chunk _chunk[HORIZON]; + uint16_t _count; + uint32_t _actual; + bool _synced; + bool _kicked; + bool _underrun; + bool _error; + bool _fault; + Held _held[NAXES]; + + static void udiv_u16(uint16_t n, uint16_t d, uint16_t* q_out, + uint16_t* r_out) { + uint16_t q = 0; + uint16_t r = 0; + if (d == 0) { + *q_out = 0; + *r_out = 0; + return; + } + for (int8_t bit = 15; bit >= 0; bit--) { + r = (uint16_t)(r << 1); + if ((n & (uint16_t)(1u << bit)) != 0) { + r = (uint16_t)(r | 1u); + } + if (r >= d) { + r = (uint16_t)(r - d); + q = (uint16_t)(q | (uint16_t)(1u << bit)); + } + } + *q_out = q; + *r_out = r; + } + + // A queue command is legal when its span is at least MIN_CMD_TICKS. + // steps == 1 uses the period alone; steps > 1 uses period * steps. + static bool command_ok(uint16_t period, uint16_t n) { + if (n == 0) { + return true; + } + if (period == 0 || n > 255) { + return false; + } + uint32_t span = (n > 1) ? (uint32_t)period * n : (uint32_t)period; + return span >= (uint32_t)MIN_CMD_TICKS; + } + + static bool realizable(uint16_t steps, uint16_t dur, uint32_t min_period) { + if (dur < MIN_CMD_TICKS) { + return false; + } + if (steps == 0) { + return true; + } + if (min_period > 65535u) { + return false; + } + if ((uint32_t)steps * min_period > dur) { + return false; + } + uint16_t q = 0; + uint16_t r = 0; + udiv_u16(dur, steps, &q, &r); + if ((uint32_t)q < min_period) { + return false; + } + if (r == 0) { + return command_ok(q, steps); + } + if (q == 65535) { + return false; + } + return command_ok((uint16_t)(q + 1), r) && + command_ok(q, (uint16_t)(steps - r)); + } + + bool realizable_all(const uint16_t mag[NAXES], uint16_t dur) const { + for (uint8_t i = 0; i < NAXES; i++) { + if (!realizable(mag[i], dur, _min_period[i])) { + return false; + } + } + return true; + } + + // Nearest duration every axis can emit, searched downward first so a tie + // keeps the shorter sum. The search stops once it is farther than the + // longest |delta|: a bigger stretch would be a different rate. + bool find_duration(const uint16_t mag[NAXES], uint16_t requested, + uint16_t* issued) const { + if (realizable_all(mag, requested)) { + *issued = requested; + return true; + } + uint16_t cap = 0; + uint32_t lo = MIN_CMD_TICKS; + for (uint8_t i = 0; i < NAXES; i++) { + if (mag[i] > cap) { + cap = mag[i]; + } + uint32_t need = (uint32_t)mag[i] * _min_period[i]; + if (need > lo) { + lo = need; + } + } + if (cap == 0 || lo > 65535u) { + return false; + } + for (uint16_t dist = 1; dist != 0; dist++) { + if (dist > cap) { + return false; + } + bool down = requested >= dist; + bool up = (uint32_t)requested + dist <= 65535u; + if (down) { + uint16_t a = (uint16_t)(requested - dist); + if ((uint32_t)a >= lo && realizable_all(mag, a)) { + *issued = a; + return true; + } + } + if (up) { + uint16_t a = (uint16_t)(requested + dist); + if ((uint32_t)a >= lo && realizable_all(mag, a)) { + *issued = a; + return true; + } + } + if (!down && !up) { + return false; + } + } + return false; + } + + bool speed_ok(const uint16_t mag[NAXES], uint16_t ticks) const { + for (uint8_t i = 0; i < NAXES; i++) { + if (mag[i] == 0) { + continue; + } + if ((uint32_t)mag[i] * _min_period[i] > ticks) { + return false; + } + } + return true; + } + + uint32_t ramp_at(uint8_t i, uint16_t tau) const { + RampMap map(_min_period[i], _accel[i]); + return map.calculate_ramp_steps(tau); + } + + // |P(tau) - P_prev| must fit in this chunk's steps. A sign change, and a + // zero-step axis, are legal only from ramp-step 0 (already at rest). + bool change_ok(uint8_t i, uint16_t steps, int sign, uint16_t tau, + uint32_t* p_out) const { + if (steps == 0) { + if (_ramp_p[i] != 0) { + return false; + } + *p_out = 0; + return true; + } + uint32_t p_new = ramp_at(i, tau); + uint32_t prev = _ramp_p[i]; + uint32_t diff = (p_new > prev) ? (p_new - prev) : (prev - p_new); + if (diff > steps) { + return false; + } + if (_sign[i] != 0 && sign != _sign[i] && prev != 0) { + return false; + } + *p_out = p_new; + return true; + } + + static void clear_chunk(Chunk* c) { + for (uint8_t i = 0; i < NAXES; i++) { + c->ncmd[i] = 0; + c->sent[i] = 0; + for (uint8_t k = 0; k < 2; k++) { + c->cmd[i][k].ticks = 0; + c->cmd[i][k].steps = 0; + c->cmd[i][k].count_up = true; + } + } + } + + void fill_axis(Chunk* c, uint8_t i, int16_t steps, uint16_t mag, + uint16_t dur) const { + if (mag == 0) { + c->cmd[i][0].ticks = dur; + c->cmd[i][0].steps = 0; + c->cmd[i][0].count_up = _count_up[i]; + c->ncmd[i] = 1; + return; + } + bool up = steps > 0; + uint16_t q = 0; + uint16_t r = 0; + udiv_u16(dur, mag, &q, &r); + if (r == 0) { + c->cmd[i][0].ticks = q; + c->cmd[i][0].steps = (uint8_t)mag; + c->cmd[i][0].count_up = up; + c->ncmd[i] = 1; + return; + } + c->cmd[i][0].ticks = (uint16_t)(q + 1); + c->cmd[i][0].steps = (uint8_t)r; + c->cmd[i][0].count_up = up; + c->cmd[i][1].ticks = q; + c->cmd[i][1].steps = (uint8_t)(mag - r); + c->cmd[i][1].count_up = up; + c->ncmd[i] = 2; + } + + bool all_registered() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] == NULL) { + return false; + } + } + return true; + } + + bool any_waiting() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_held[i].waiting) { + return true; + } + } + return false; + } + + bool any_queue_nonempty() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL && !_s[i]->isQueueEmpty()) { + return true; + } + } + return false; + } + + bool any_queue_empty() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL && _s[i]->isQueueEmpty()) { + return true; + } + } + return false; + } + + bool all_have_room() const { + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL && _s[i]->isQueueFull()) { + return false; + } + } + return true; + } + + static bool chunk_done(const Chunk* c) { + for (uint8_t i = 0; i < NAXES; i++) { + if (c->sent[i] < c->ncmd[i]) { + return false; + } + } + return true; + } + + void pop_front() { + if (_count == 0) { + return; + } + for (uint16_t i = 1; i < _count; i++) { + _chunk[i - 1] = _chunk[i]; + } + _count--; + } + + void clear_plan() { + _count = 0; + _actual = 0; + _kicked = false; + _underrun = false; + _error = false; + _fault = false; + // Rearm the queue admission latches. A member force-stopped outside the + // planner left its queue refusing every addQueueEntry() with + // AQE_ERROR_COMMANDS_SUSPENDED, which flush() reads as a terminal error. + // clear_plan() is the recovery boundary -- it is reached solely from + // syncFromSteppers() / setCurrentPosition(), where the caller has just + // re-synced and is about to plan again -- so this is the one place the + // rearm belongs. It is deliberately not in prepare_round(), which runs on + // every round of a normal feed rather than at a reset. + for (uint8_t i = 0; i < NAXES; i++) { + if (_s[i] != NULL) { + _s[i]->resumeCommands(); + } + } + for (uint8_t i = 0; i < NAXES; i++) { + _ramp_p[i] = 0; + _sign[i] = 0; + _count_up[i] = true; + _held[i].waiting = false; + // Drain any pending stop cause, so a re-sync is self-sufficient. Same + // ordering trap as FasNAxis::clear_path(): clearing _fault without + // draining the cause lets the next pump() re-fault the plan. + if (_s[i] != NULL) { + _s[i]->takeStopCause(); + } + } + } + + // Hold the next unsent command of chunk 0 on every axis that still has + // one. Returns false when there is nothing left to send. + bool prepare_round() { + while (_count > 0 && chunk_done(&_chunk[0])) { + pop_front(); + } + if (_count == 0 || !all_have_room()) { + return false; + } + Chunk* c = &_chunk[0]; + bool any = false; + for (uint8_t i = 0; i < NAXES; i++) { + if (c->sent[i] >= c->ncmd[i]) { + continue; + } + uint8_t k = c->sent[i]; + _held[i].ticks = c->cmd[i][k].ticks; + _held[i].steps = c->cmd[i][k].steps; + _held[i].count_up = c->cmd[i][k].count_up; + _held[i].waiting = true; + any = true; + } + return any; + } + + // False means this pump must stop (retry or hard error). + bool flush() { + bool retry = false; + for (uint8_t i = 0; i < NAXES; i++) { + if (!_held[i].waiting || _s[i] == NULL) { + continue; + } + struct stepper_command_s cmd = {_held[i].ticks, _held[i].steps, + _held[i].count_up}; + AqeResultCode rc = _s[i]->addQueueEntry(&cmd, _kicked); + if (rc == AqeResultCode::OK) { + _held[i].waiting = false; + _chunk[0].sent[i]++; + } else if (aqeIsPauseInjected(rc)) { + _error = true; + } else if (aqeRetry(rc)) { + retry = true; + } else { + _error = true; + } + } + return !_error && !retry; + } + + void feed_loop() { + while (!_error) { + if (!any_waiting()) { + if (!prepare_round()) { + break; + } + } + if (!flush()) { + break; + } + } + } +}; + +#endif // FAS_TIMED_H diff --git a/src/StepperMotion.cpp b/src/StepperMotion.cpp new file mode 100644 index 0000000..e59f9af --- /dev/null +++ b/src/StepperMotion.cpp @@ -0,0 +1,716 @@ +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" +#include "fas_member/move_timed.h" + +// This define in order to not shoot myself. +#ifndef TEST +#define printf DO_NOT_USE_PRINTF +#define puts DO_NOT_USE_PUTS +#endif + +// Here are the global variables to interface with the interrupts + +StepperQueue* StepperMotion::_queue() const { + return FAS_QUEUE_PTR(_queue_num); +} + +// To realize the 1 Hz debug led + +//************************************************************************************************* +//************************************************************************************************* +// +// StepperMotion provides: +// - movement control +// either raw access to the stepper command queue +// or ramp generator driven by speed/acceleration and move +// - stepper position +// +// This implements auto enable and delay from direction change to first step +// +//************************************************************************************************* +//************************************************************************************************* + +//************************************************************************************************* +bool StepperMotion::handleExternalDirectionPin(StepperQueue* q, + bool count_up) { + if (_pendingExternalDirState != ExtDirPendingState::None) { + if (_engine->_externalCallForPin) { + uint8_t desiredPinState = + (_pendingExternalDirState == ExtDirPendingState::High) ? HIGH : LOW; + bool newState = _engine->_externalCallForPin(_dirPin, desiredPinState); + if (newState == (desiredPinState == HIGH)) { + _pendingExternalDirState = ExtDirPendingState::None; +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + q->clear_pause_stats(); +#endif + } + } + if (_pendingExternalDirState != ExtDirPendingState::None) { + return false; + } + } + if (q->queue_end.count_up != count_up) { + if (q->hasStepsInQueue()) { + return false; + } + if (_engine->_externalCallForPin) { + uint8_t desiredPinState = (count_up == _dirHighCountsUp) ? HIGH : LOW; + bool newState = _engine->_externalCallForPin(_dirPin, desiredPinState); + if (newState != (desiredPinState == HIGH)) { + _pendingExternalDirState = (desiredPinState == HIGH) + ? ExtDirPendingState::High + : ExtDirPendingState::Low; + return false; + } +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + q->clear_pause_stats(); +#endif + } + } + return true; +} + +//************************************************************************************************* +#include "fas_member/add_queue_entry.h" + +//************************************************************************************************* +// fill_queue generates commands to the stepper for executing a ramp +// +// Plan is to fill the queue with commmands summing up to approx. 10 ms in the +// future (or more). For low speeds, this results in single stepping For high +// speeds (40kSteps/s) approx. 400 Steps to be created using 3 commands +// +//************************************************************************************************* + +void StepperMotion::fill_queue() { + // Check preconditions to be allowed to fill the queue + if (!_rg.isRampGeneratorActive()) { + return; + } + if (!_rg.hasValidConfig()) { +#ifdef TEST + assert(false); +#endif + return; + } + // check if addition of commands is suspended (due to forceStopAndNewPosition) + StepperQueue* q = _queue(); + // if force stop has been called, then the queue's admission latch is set and + // the ramp is stopped. So the ramp generator will not create a new command, + // unless a new move command has been given after forceStop..(). So we just + // clear the latch. + q->resumeCommands(); + + // preconditions are fulfilled, so create the command(s) + NextCommand cmd; + // Plan ahead for max. 20 ms and minimum two commands. + // This is now configurable using _forward_planning_in_ticks. + bool delayed_start = !q->isRunning(); + bool need_delayed_start = false; + uint32_t ticksPrepared = q->ticksInQueue(); + while (!isQueueFull() && + ((ticksPrepared < _forward_planning_in_ticks) || + (q->queueEntries() <= 1)) && + _rg.isRampGeneratorActive()) { +#if (TEST_MEASURE_ISR_SINGLE_FILL == 1) + // For run time measurement + uint32_t runtime_us = micros(); +#endif + AqeResultCode res = AQE_OK; + _rg.getNextCommand(&q->queue_end, &cmd); + if (cmd.command.ticks != 0) { + do { + res = addQueueEntry(&cmd.command, !delayed_start); + } while (aqeRetryImmediately(res)); + } + if (res == AQE_OK) { + _rg.afterCommandEnqueued(&cmd); + need_delayed_start = delayed_start; + if (cmd.command.steps <= 1) { + ticksPrepared += cmd.command.ticks; + } else { + uint32_t tmp = cmd.command.ticks; + tmp *= cmd.command.steps; + ticksPrepared += tmp; + } + } + +#if (TEST_MEASURE_ISR_SINGLE_FILL == 1) + // For run time measurement + runtime_us = micros() - runtime_us; + max_micros = fas_max(max_micros, runtime_us); +#endif + if (cmd.command.ticks == 0) { + break; + } + if (res != AQE_OK) { + if (aqeRetry(res)) { + // try later again + break; + } else { +#ifdef SIM_TEST_INPUT + Serial.println("Abort ramp due to queue error res="); + Serial.print(static_cast(res)); + Serial.print(" Steps="); + Serial.print(cmd.command.steps); + Serial.print(" ticks="); + Serial.print(cmd.command.ticks); + Serial.print(" min_cmd_ticks="); + Serial.println(MIN_CMD_TICKS); +#endif +#ifdef TEST + printf("ERROR: Abort ramp due to queue error: %s\n", toString(res)); + printf("steps=%d ticks=%d limit=%ld state=%d\n", cmd.command.steps, + cmd.command.ticks, MIN_CMD_TICKS, cmd.rw.ramp_state); + assert(false); +#endif + _rg.stopRamp(); + delayed_start = false; + } + } + } + if (need_delayed_start) { + addQueueEntry(NULL, true); + } +} + +void StepperMotion::updateAutoDisable() { + // StepperMotionEngine will call with interrupts disabled + // fasDisableInterrupts(); + if (_auto_disable_delay_counter > 1) { + if (!isRunning()) { + _auto_disable_delay_counter--; + } + } + // fasEnableInterrupts(); +} + +bool StepperMotion::agreeWithAutoDisable() { + bool agree = true; + // StepperMotionEngine will call with interrupts disabled + // fasDisableInterrupts(); + if (isRunning()) { + agree = false; + } + if (_auto_disable_delay_counter > 1) { + agree = false; + } + // fasEnableInterrupts(); + return agree; +} + +bool StepperMotion::needAutoDisable() { + bool need_disable = false; + // StepperMotionEngine will call with interrupts disabled + // fasDisableInterrupts(); + if (_auto_disable_delay_counter == 1) { + if (!isRunning()) { + need_disable = true; + } + } + // fasEnableInterrupts(); + return need_disable; +} + +bool StepperMotion::usesAutoEnablePin(uint8_t pin) { + if (pin != PIN_UNDEFINED) { + if ((pin == _enablePinHighActive) || (pin == _enablePinLowActive)) { + return true; + } + } + return false; +} + +void StepperMotion::init(StepperMotionEngine* engine, uint8_t num, + uint8_t step_pin) { + __builtin_memset(this, 0, sizeof(*this)); + _engine = engine; + _off_delay_count = 1; + _stepPin = step_pin; + _dirHighCountsUp = true; + _dirPin = PIN_UNDEFINED; + _enablePinHighActive = PIN_UNDEFINED; + _enablePinLowActive = PIN_UNDEFINED; + _forward_planning_in_ticks = TICKS_PER_S / 50; + _pendingExternalDirState = ExtDirPendingState::None; + _rg.init(); + _queue_num = num; +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR >= 5) + _attached_pulse_unit = NULL; +#endif +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 4) + _attached_pulse_cnt_unit = -1; +#endif +} +uint8_t StepperMotion::getStepPin() const { return _stepPin; } + +uint16_t StepperMotion::getDirChangeBeforeTicks() const { + if (_dirPin == PIN_UNDEFINED) { + return 0; + } + StepperQueue* q = _queue(); + uint16_t t = 0; +#if defined(SUPPORT_ESP32) + t = esp32_before_pause_ticks(q); +#endif +#if defined(BEFORE_DIR_CHANGE_DELAY_TICKS) + if (t == 0) { + t = BEFORE_DIR_CHANGE_DELAY_TICKS(q); + } +#endif + (void)q; + if (t == 0) { + return 0; + } + return fas_max(t, (uint16_t)MIN_CMD_TICKS); +} + +uint16_t StepperMotion::getDirChangeAfterTicks() const { + if (_dirPin == PIN_UNDEFINED) { + return 0; + } + if (_dirPin & PIN_EXTERNAL_FLAG) { + return US_TO_TICKS((uint16_t)2000); + } + uint16_t t = _dir_change_delay_ticks; +#if defined(SUPPORT_ESP32) + t = fas_max(t, esp32_after_pause_ticks(_queue())); +#endif +#if defined(AFTER_DIR_CHANGE_DELAY_TICKS) + t = fas_max(t, AFTER_DIR_CHANGE_DELAY_TICKS(_queue())); +#endif + if (t == 0) { + return 0; + } + return fas_max(t, (uint16_t)MIN_CMD_TICKS); +} + +void StepperMotion::setDirectionPin(uint8_t dirPin, bool dirHighCountsUp, + uint16_t dir_change_delay_us) { +#if defined(SUPPORT_ESP32_I2S) && defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_queue()->_driver_type == FasDriver::I2S_DIRECT) { + dirPin &= (uint8_t)~PIN_I2S_FLAG; + } +#endif + _dirPin = dirPin; + _dirHighCountsUp = dirHighCountsUp; + if (_dirPin != PIN_UNDEFINED) { + if (_dirPin & PIN_EXTERNAL_FLAG) { + if (_engine->_externalCallForPin) { + _engine->_externalCallForPin(_dirPin, dirHighCountsUp ? HIGH : LOW); + } + } else if (!isI2sMuxPin(_dirPin)) { + // An I2S mux direction slot is not a GPIO. PIN_OUTPUT() on + // `PIN_I2S_FLAG | slot` addresses pin 0x40+slot, which does not exist -- + // measured on an ESP32-DevKitC, one + // "gpio_set_direction: GPIO number error" and one + // "gpio_set_level: GPIO output gpio_num error" per stepper, from a + // CONFIG the host had every right to send. The flag is kept in `_dirPin` + // (the queue needs it to find the bit, and I2S_DIRECT is masked above), + // so the test has to be here rather than on the argument: nothing else + // distinguishes a mux slot from an external pin. + // + // Skipping the write is not a loss of the initial level: setDirPin() + // below applies it through i2sMuxSetBit() for exactly this case. + PIN_OUTPUT(dirPin, dirHighCountsUp ? HIGH : LOW); + } + } + _queue()->setDirPin(dirPin, dirHighCountsUp); + if (dir_change_delay_us != 0) { + if (dir_change_delay_us > MAX_DIR_DELAY_US) { + dir_change_delay_us = MAX_DIR_DELAY_US; + } + if (dir_change_delay_us < MIN_DIR_DELAY_US) { + dir_change_delay_us = MIN_DIR_DELAY_US; + } + _dir_change_delay_ticks = US_TO_TICKS(dir_change_delay_us); + } else { + _dir_change_delay_ticks = 0; + } +} +void StepperMotion::setEnablePin(uint8_t enablePin, + bool low_active_enables_stepper) { + // An I2S mux enable slot is not a GPIO either, so PIN_OUTPUT() on + // `PIN_I2S_FLAG | slot` would address pin 0x40+slot. The level is applied + // through the mux by esp32_set_enable_pin_state() instead -- see the same + // guard in setDirectionPin(). + const bool mux_pin = isI2sMuxPin(enablePin); + if (low_active_enables_stepper) { + _enablePinLowActive = enablePin; + if (enablePin != PIN_UNDEFINED) { + if (enablePin & PIN_EXTERNAL_FLAG) { + if (_engine->_externalCallForPin) { + _engine->_externalCallForPin(enablePin, HIGH); + } + } else if (!mux_pin) { + PIN_OUTPUT(enablePin, HIGH); + if (_enablePinHighActive == enablePin) { + _enablePinHighActive = PIN_UNDEFINED; + } + } + } + } else { + _enablePinHighActive = enablePin; + if (enablePin != PIN_UNDEFINED) { + if (enablePin & PIN_EXTERNAL_FLAG) { + if (_engine->_externalCallForPin) { + _engine->_externalCallForPin(enablePin, LOW); + } + } else if (!mux_pin) { + PIN_OUTPUT(enablePin, LOW); + if (_enablePinLowActive == enablePin) { + _enablePinLowActive = PIN_UNDEFINED; + } + } + } + } +} +void StepperMotion::setAutoEnable(bool auto_enable) { + _autoEnable = auto_enable; + if (auto_enable && (_off_delay_count == 0)) { + _off_delay_count = 1; + } +} +DelayResultCode StepperMotion::setDelayToEnable(uint32_t delay_us) { + uint32_t delay_ticks = US_TO_TICKS(delay_us); + if (delay_ticks > 0) { + if (delay_ticks < MIN_CMD_TICKS) { + return DELAY_TOO_LOW; + } + } + if (delay_ticks > MAX_ON_DELAY_TICKS) { + return DELAY_TOO_HIGH; + } + _on_delay_ticks = delay_ticks; + return DELAY_OK; +} +void StepperMotion::setDelayToDisable(uint16_t delay_ms) { + uint16_t delay_count = delay_ms / DELAY_MS_BASE; + if ((delay_ms > 0) && (delay_count < 2)) { + // ensure minimum time + delay_count = 2; + } + _off_delay_count = fas_max(delay_count, (uint16_t)1); +} +MoveResultCode StepperMotion::runForward() { return _rg.startRun(true); } +MoveResultCode StepperMotion::runBackward() { return _rg.startRun(false); } +MoveResultCode StepperMotion::moveTo(int32_t position, bool blocking) { + MoveResultCode res = _rg.moveTo(position, &_queue()->queue_end); + if ((res == MOVE_OK) && blocking) { + while (isRunning()) { + noop_or_wait; + } + } + return res; +} +MoveResultCode StepperMotion::move(int32_t move, bool blocking) { + if ((move < 0) && (_dirPin == PIN_UNDEFINED)) { + return MOVE_ERR_NO_DIRECTION_PIN; + } + MoveResultCode res = _rg.move(move); + if ((res == MOVE_OK) && blocking) { + while (isRunning()) { + noop_or_wait; + } + } + return res; +} +void StepperMotion::keepRunning() { _rg.setKeepRunning(); } +void StepperMotion::stopMove() { + _stop_cause = (uint8_t)StepperStopCause::StopMove; + _rg.initiateStop(); +} +void StepperMotion::applySpeedAcceleration() { + _rg.applySpeedAcceleration(); +} +MoveResultCode StepperMotion::moveByAcceleration(int32_t acceleration, + bool allow_reverse) { + MoveResultCode res = MOVE_OK; + if (acceleration > 0) { + setAcceleration(acceleration); + res = runForward(); + } else if (acceleration < 0) { + setAcceleration(-acceleration); + if (allow_reverse && (_dirPin != PIN_UNDEFINED)) { + res = runBackward(); + } else { + applySpeedAcceleration(); + stopMove(); + } + } else { + uint32_t max_speed = _rg.getSpeedInTicks(); + setSpeedInTicks(getPeriodInTicksAfterCommandsCompleted()); + setAcceleration(1); // ensure increase, so the speed is kept + applySpeedAcceleration(); + setSpeedInTicks(max_speed); + } + return res; +} +// Defined here rather than inline in the header: StepperQueue is only +// forward-declared there. +void StepperMotion::resumeCommands() { _queue()->resumeCommands(); } +bool StepperMotion::areCommandsSuspended() const { + return _queue()->areCommandsSuspended(); +} +void StepperMotion::forceStop() { + StepperQueue* q = _queue(); + + _stop_cause = (uint8_t)StepperStopCause::ForceStop; + + // ensure no more commands are added to the queue + q->suspendCommands(); + + // inform ramp generator to force stop + _rg.forceStop(); +} +void StepperMotion::forceStopAndNewPosition(int32_t new_pos) { + StepperQueue* q = _queue(); + + _stop_cause = (uint8_t)StepperStopCause::ForceStopAndNewPosition; + + // ensure no more commands are added to the queue + q->suspendCommands(); + + // stop ramp generator + _rg.stopRamp(); + + // stop the stepper interrupt and empty the queue + q->forceStop(); + + // set the new position. This should be safe + q->queue_end.pos = new_pos; + _rg.setTargetPosition(new_pos); +} +StepperStopCause StepperMotion::takeStopCause() { + StepperStopCause cause = (StepperStopCause)_stop_cause; + _stop_cause = (uint8_t)StepperStopCause::None; + return cause; +} +bool StepperMotion::setEnablePinState(uint8_t pin, uint8_t active_state) { + if (pin == PIN_UNDEFINED) { + return true; + } + if (pin & PIN_EXTERNAL_FLAG) { + if (_engine->_externalCallForPin != NULL) { + return _engine->_externalCallForPin(pin, active_state) == active_state; + } + return true; + } + SET_ENABLE_PIN_STATE(_queue(), pin, active_state); + return true; +} +bool StepperMotion::disableOutputs() { + if (isRunning() && _autoEnable) { + return false; + } + bool disabled = setEnablePinState(_enablePinLowActive, HIGH) & + setEnablePinState(_enablePinHighActive, LOW); + if (disabled) { + _auto_disable_delay_counter = 0; + } + return disabled; +} +bool StepperMotion::enableOutputs() { + return setEnablePinState(_enablePinLowActive, LOW) & + setEnablePinState(_enablePinHighActive, HIGH); +} +int32_t StepperMotion::getPositionAfterCommandsCompleted() const { + return _queue()->queue_end.pos; +} +uint32_t StepperMotion::getPeriodInTicksAfterCommandsCompleted() const { + if (_rg.isRampGeneratorActive()) { + return _rg.getCurrentPeriodInTicks(); + } + return 0; +} +uint32_t StepperMotion::getPeriodInUsAfterCommandsCompleted() const { + if (_rg.isRampGeneratorActive()) { + return _rg.getCurrentPeriodInUs(); + } + return 0; +} +void StepperMotion::getCurrentSpeedInTicks(struct actual_ticks_s* speed, + bool realtime) const { + bool valid; + if (realtime) { + valid = _queue()->getActualTicksWithDirection(speed); + } else { + valid = false; + } + if (!valid) { + if (_rg.isRampGeneratorActive()) { + _rg.getCurrentSpeedInTicks(speed); + } else { + speed->ticks = 0; + } + } +} +int32_t StepperMotion::getCurrentSpeedInUs(bool realtime) const { + struct actual_ticks_s speed; + getCurrentSpeedInTicks(&speed, realtime); + int32_t speed_in_us = speed.ticks / (TICKS_PER_S / 1000000); + if (speed.count_up) { + return speed_in_us; + } + return -speed_in_us; +} +int32_t StepperMotion::getCurrentSpeedInMilliHz(bool realtime) const { + struct actual_ticks_s speed; + getCurrentSpeedInTicks(&speed, realtime); + if (speed.ticks > 0) { + int32_t speed_in_mhz = ((uint32_t)250 * TICKS_PER_S) / speed.ticks * 4; + if (speed.count_up) { + return speed_in_mhz; + } + return -speed_in_mhz; + } + return 0; +} +uint16_t StepperMotion::getMaxSpeedInTicks() const { + return _queue()->getMaxSpeedInTicks(); +} +uint16_t StepperMotion::getMaxSpeedInUs() const { + uint16_t ticks = getMaxSpeedInTicks(); + uint16_t speed_in_us = ticks / (TICKS_PER_S / 1000000); + return speed_in_us; +} +uint32_t StepperMotion::getMaxSpeedInHz() const { + uint16_t ticks = getMaxSpeedInTicks(); + uint32_t speed_in_hz = TICKS_PER_S / ticks; + return speed_in_hz; +} +uint32_t StepperMotion::getMaxSpeedInMilliHz() const { + uint16_t ticks = getMaxSpeedInTicks(); + uint32_t speed_in_milli_hz = ((uint32_t)250 * TICKS_PER_S) / ticks * 4; + return speed_in_milli_hz; +} +#if defined(SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING) +void StepperMotion::setAbsoluteSpeedLimit(uint16_t max_speed_in_ticks) { + _queue()->setAbsoluteSpeedLimit(max_speed_in_ticks); +} +#endif +int8_t StepperMotion::setSpeedInTicks(uint32_t min_step_ticks) { + if (min_step_ticks < getMaxSpeedInTicks()) { + return -1; + } + if (min_step_ticks == TICKS_FOR_STOPPED_MOTOR) { + return -1; + } + _rg.setSpeedInTicks(min_step_ticks); + return 0; +} +int8_t StepperMotion::setSpeedInUs(uint32_t min_step_us) { + if (min_step_us >= TICKS_TO_US(0xffffffff)) { + return -1; + } + uint32_t min_step_ticks = US_TO_TICKS(min_step_us); + return setSpeedInTicks(min_step_ticks); +} +int8_t StepperMotion::setSpeedInHz(uint32_t speed_hz) { + if (speed_hz == 0) { + return -1; + } + uint32_t ticks = _rg.divForHz(speed_hz); + return setSpeedInTicks(ticks); +} +int8_t StepperMotion::setSpeedInMilliHz(uint32_t speed_mhz) { + if (speed_mhz <= (1000LL * TICKS_PER_S / 0xffffffff + 1)) { + return -1; + } + uint32_t ticks = _rg.divForMilliHz(speed_mhz); + return setSpeedInTicks(ticks); +} +void StepperMotion::setCurrentPosition(int32_t new_pos) { + int32_t delta = new_pos - getCurrentPosition(); + if (delta != 0) { + StepperQueue* q = _queue(); +#if defined(SUPPORT_RP_PICO) + q->pos_offset += delta; +#endif + struct queue_end_s* queue_end = &q->queue_end; + fasDisableInterrupts(); + queue_end->pos = queue_end->pos + delta; + _rg.advanceTargetPosition(delta); + fasEnableInterrupts(); + } +} +void StepperMotion::setPositionAfterCommandsCompleted(int32_t new_pos) { + StepperQueue* q = _queue(); + struct queue_end_s* queue_end = &q->queue_end; + fasDisableInterrupts(); + int32_t delta = new_pos - q->queue_end.pos; + queue_end->pos = new_pos; + if (delta != 0) { +#if defined(SUPPORT_RP_PICO) + q->pos_offset += delta; +#endif + _rg.advanceTargetPosition(delta); + } + fasEnableInterrupts(); +} +uint8_t StepperMotion::queueEntries() const { + return _queue()->queueEntries(); +} +uint32_t StepperMotion::ticksInQueue() const { + return _queue()->ticksInQueue(); +} +bool StepperMotion::hasTicksInQueue(uint32_t min_ticks) const { + return _queue()->hasTicksInQueue(min_ticks); +} +bool StepperMotion::isQueueFull() const { return _queue()->isQueueFull(); } +bool StepperMotion::isQueueEmpty() const { return _queue()->isQueueEmpty(); } +bool StepperMotion::isQueueRunning() const { return _queue()->isRunning(); } +bool StepperMotion::isRunning() const { + StepperQueue* q = _queue(); + return q->isRunning() || _rg.isRampGeneratorActive() || !isQueueEmpty(); +} +void StepperMotion::performOneStep(bool count_up, bool blocking) { + if (!isRunning()) { + if (count_up || (_dirPin != PIN_UNDEFINED)) { + StepperQueue* q = _queue(); + q->resumeCommands(); + struct stepper_command_s cmd = { + .ticks = MIN_CMD_TICKS, .steps = 1, .count_up = count_up}; + addQueueEntry(&cmd); + if (blocking) { + while (isRunning()) { + } + } + } + } +} +void StepperMotion::forwardStep(bool blocking) { + performOneStep(true, blocking); +} +void StepperMotion::backwardStep(bool blocking) { + performOneStep(false, blocking); +} +int32_t StepperMotion::getCurrentPosition() const { + return _queue()->getCurrentPosition(); +} +void StepperMotion::detachFromPin() { _queue()->disconnect(); } +void StepperMotion::reAttachToPin() { _queue()->connect(); } + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +FasDriver StepperMotion::driverType() const { + return _queue()->_driver_type; +} +const char* StepperMotion::driverTypeString() const { + switch (_queue()->_driver_type) { +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + case FasDriver::MCPWM_PCNT: + return "MCPWM_PCNT"; +#endif + case FasDriver::RMT: + return "RMT"; +#if defined(SUPPORT_ESP32_I2S) + case FasDriver::I2S_DIRECT: + return "I2S_DIRECT"; + case FasDriver::I2S_MUX: + return "I2S_MUX"; +#endif + default: + return "UNSPECIFIED"; + } +} +#endif diff --git a/src/StepperMotion.h b/src/StepperMotion.h new file mode 100644 index 0000000..fabbdf9 --- /dev/null +++ b/src/StepperMotion.h @@ -0,0 +1,1026 @@ +#ifndef STEPPERMOTION_H +#define STEPPERMOTION_H +#include +#include "fas_arch/common.h" +#include "StepperMotionEngine.h" + +enum class ExtDirPendingState : uint8_t { None = 0xff, Low = 0, High = 1 }; + +class StepperMotion; + +// ### Return codes of calls to `move()` and `moveTo()` +// +// The defined preprocessor macros are MOVE_xxx: +// MOVE_OK: All is OK: +// MOVE_ERR_NO_DIRECTION_PIN: Negative direction requested, but no direction pin +// MOVE_ERR_SPEED_IS_UNDEFINED: The maximum speed has not been set yet +// MOVE_ERR_ACCELERATION_IS_UNDEFINED: The acceleration to use has not been set +// yet + +// ### Return codes of `rampState()` +// +// The return value is an uint8_t, which consist of two fields: +// +// | Bit 7 | Bits 6-5 | Bits 4-0 | +// |:--------|:----------|:---------| +// |Always 0 | Direction | State | +// +// The bit mask for direction and state: +#define RAMP_DIRECTION_MASK (32 + 64) +#define RAMP_STATE_MASK (1 + 2 + 4 + 8 + 16) + +// The defined ramp states are: +#define RAMP_STATE_IDLE 0 +#define RAMP_STATE_COAST 1 +#define RAMP_STATE_ACCELERATE 2 +#define RAMP_STATE_DECELERATE 4 +#define RAMP_STATE_REVERSE (4 + 8) +#define RAMP_STATE_ACCELERATING_FLAG 2 +#define RAMP_STATE_DECELERATING_FLAG 4 + +// And the two directions of a move +#define RAMP_DIRECTION_COUNT_UP 32 +#define RAMP_DIRECTION_COUNT_DOWN 64 + +// A ramp state value of 2 is set after any move call on a stopped motor +// and until the stepper task is serviced. The stepper task will then +// control the direction flags + +#include "fas_ramp/RampGenerator.h" + +// +// ## Timing values - Architecture dependent +// +// ### AVR +// |VARIABLE | Value | Unit | +// |:----------------|------------:|:------------------------| +// |TICKS_PER_S | 16_000_000 | [ticks/s] | +// |MIN_CMD_TICKS | 640 | [1/TICKS_PER_S seconds] | +// |MIN_DIR_DELAY_US | 40 | [µs] | +// |MAX_DIR_DELAY_US | 4095 | [µs] | +// +// ### ESP32 +// |VARIABLE | Value | Unit | +// |:----------------|------------:|:------------------------| +// |TICKS_PER_S | 16_000_000 | [ticks/s] | +// |MIN_CMD_TICKS | 3200 | [1/TICKS_PER_S seconds] | +// |MIN_DIR_DELAY_US | 200 | [µs] | +// |MAX_DIR_DELAY_US | 4095 | [µs] | +// +// ### SAM DUE +// |VARIABLE | Value | Unit | +// |:----------------|------------:|:------------------------| +// |TICKS_PER_S | 21_000_000 | [ticks/s] | +// |MIN_CMD_TICKS | 4200 | [1/TICKS_PER_S seconds] | +// |MIN_DIR_DELAY_US | 200 | [µs] | +// |MAX_DIR_DELAY_US | 3120 | [µs] | +// +// # StepperMotion + +#define MAX_ON_DELAY_TICKS ((uint32_t)(65535 * (QUEUE_LEN - 1))) + +#define PIN_UNDEFINED 255 +#define PIN_EXTERNAL_FLAG 128 + +// Is this pin number an I2S mux slot rather than a GPIO? +// +// The low five bits are the slot and PIN_I2S_FLAG marks it, so a mux slot is +// `0x40 | slot` -- 64 and up, which is not a pin on any ESP32. Callers that +// would otherwise hand such a value to the GPIO driver have to ask this first: +// the flag is *kept* on a mux direction/enable pin (the queue needs it to find +// the bit in the frame), so stripping it on the way in would lose the slot. +// Every platform without I2S answers false, so the call sites need no #if. +// +// Off ESP32 there is no PIN_I2S_FLAG at all, so nothing can be a mux slot. +static inline bool isI2sMuxPin(uint8_t pin) { +#if defined(PIN_I2S_FLAG) + return (pin & PIN_I2S_FLAG) != 0; +#else + (void)pin; + return false; +#endif +} + +class StepperMotion { +#ifdef TEST + public: +#else + private: +#endif + void init(StepperMotionEngine* engine, uint8_t num, uint8_t step_pin); + + public: + // ## Step Pin + // step pin is defined at creation. Here can retrieve the pin + uint8_t getStepPin() const; + + // ## Direction Pin + // if direction pin is connected, call this function. + // + // If the pin number is >= 128, then the direction pin is assumed to be + // external and the external callback function (set by + // `setExternalCallForPin()`) is used to set the pin. For direction pin, this + // is implemented for esp32 and its supported derivates, and avr and its + // derivates except atmega32u4 + // + // For slow driver hardware the first step after any polarity change of the + // direction pin can be delayed by the value dir_change_delay_us. The allowed + // range is MIN_DIR_DELAY_US and MAX_DIR_DELAY_US. The special value of 0 + // means, that no delay is added. Values 1 up to MIN_DIR_DELAY_US will be + // clamped to MIN_DIR_DELAY_US. Values above MAX_DIR_DELAY_US will be clamped + // to MAX_DIR_DELAY_US. For external pins, dir_change_delay_us is ignored, + // because the mechanism applied for external pins provides already pause + // in the range of ms or more. + // + // ESP32 I2S_DIRECT requires a GPIO (or external pin >= 128). I2S mux slots + // (`pin | PIN_I2S_FLAG`) are valid only with I2S_MUX. + // + // ESP32 MCPWM/PCNT inserts one MIN_CMD_TICKS pause (old DIR) before a + // direction change. apply_command() runs at MCPWM compare (tick 1, TEA), + // when STEP has just gone high; STEP stays high until TEP. The pause + // defers the DIR toggle to TEA of that pause, with STEP already low + // independent of dir_change_delay_us. + // + // ESP-IDF 5+ also latches generator actions at TEZ/TEP (one-command + // pipeline). startQueue applies the first command with immediate update + // so leftover utea=2 cannot pulse during a leading pause. + void setDirectionPin(uint8_t dirPin, bool dirHighCountsUp = true, + uint16_t dir_change_delay_us = 0); + inline uint8_t getDirectionPin() const { return _dirPin; } + inline bool directionPinHighCountsUp() const { return _dirHighCountsUp; } + + // Ticks of the pause to issue *before* a direction change (old DIR), for + // pipeline drain (RMT/I2S/MCPWM). 0 means none, so it is also the pause + // count: one pause of this length, or none. Coordinated n-axis planners + // should emit it on every axis, not wait for inject. + uint16_t getDirChangeBeforeTicks() const; + // Ticks of the pause that carries the new DIR: max of the user + // `dir_change_delay_us` from `setDirectionPin()` and the driver's + // after-delay. External DIR pins return 2 ms. 0 means none. + uint16_t getDirChangeAfterTicks() const; + + // ## Enable Pin + // if enable pin is connected, then use this function. + // + // If the pin number is >= 128, then the enable pin is assumed to be + // external and the external callback function (set by + // `setExternalCallForPin()`) is used to set the pin. + // + // In case there are two enable pins: one low and one high active, then + // these calls are valid and both pins will be operated: + // setEnablePin(pin1, true); + // setEnablePin(pin2, false); + // If pin1 and pin2 are same, then the last call will be used. + void setEnablePin(uint8_t enablePin, bool low_active_enables_stepper = true); + inline uint8_t getEnablePinHighActive() const { return _enablePinHighActive; } + inline uint8_t getEnablePinLowActive() const { return _enablePinLowActive; } + + // using enableOutputs/disableOutputs the stepper can be enabled and disabled + // For a running motor with autoEnable set, disableOutputs() will return false + bool enableOutputs(); // returns true, if enabled + bool disableOutputs(); // returns true, if disabled + + // In auto enable mode, the stepper is enabled before stepping and disabled + // afterwards. The delay from stepper enabled till first step and from + // last step to stepper disabled can be separately adjusted. + // + // setDelayToEnable() sets the delay from enable to first step. + // Return values: + // - DelayResultCode::OK: Delay accepted + // - DelayResultCode::TOO_LOW: Delay is 0 (minimum is 1µs) + // - DelayResultCode::TOO_HIGH: Delay exceeds MAX_ON_DELAY_TICKS + // (~120ms ESP32, ~60ms AVR @ 16MHz) + // + // setDelayToDisable() sets the delay from last step to disable. + // This is executed in the periodic stepper task (~4-10ms rate) and thus + // has several ms of jitter. + void setAutoEnable(bool auto_enable); + DelayResultCode setDelayToEnable(uint32_t delay_us); + void setDelayToDisable(uint16_t delay_ms); + + // ## Stepper Position + // Retrieve the current position of the stepper. + // + // While a move is running, this value leads the step pin. The driver + // accepts steps into its pipeline before those pulses are emitted. At + // high speed the lead is large: on ESP32 RMT one step can be a single + // symbol, and a full symbol block plus the next chunk can already be + // committed. getCurrentPosition() does not estimate how far that + // pipeline has played out. + // + // If the pulses that have already left the pin are what matters, + // attach a pulse counter and use readPulseCounter(). Counters 6 and 7 + // are not used by the stepper drivers. + int32_t getCurrentPosition() const; + + // Set the current position of the stepper - either in standstill or while + // moving. + // for esp32: the implementation uses getCurrentPosition(), which does not + // consider the steps of the current command + // => recommend to use only in standstill + void setCurrentPosition(int32_t new_pos); + + // ## Stepper running status + // is true while the stepper is running or ramp generation is active + bool isRunning() const; + + // ## Speed + // For stepper movement control by StepperMotion's ramp generator + // + // Speed can be defined in four different units: + // - In Hz: This means steps/s + // - In millHz: This means in steps/1000s + // - In us: This means in us/step + // + // For the device's maximum allowed speed, the following calls can be used. + uint16_t getMaxSpeedInUs() const; + uint16_t getMaxSpeedInTicks() const; + uint32_t getMaxSpeedInHz() const; + uint32_t getMaxSpeedInMilliHz() const; + + // For esp32 and avr, the device's maximum allowed speed can be overridden. + // Allocating a new stepper will override any absolute speed limit. + // This is absolutely untested, no error checking implemented. + // Use at your own risk ! +#if defined(SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING) + void setAbsoluteSpeedLimit(uint16_t max_speed_in_ticks); +#endif + + // Setting the speed can be done with the four `setSpeed...()` calls. + // The new value will be used only after call of these functions: + // + // - `move()` + // - `moveTo()` + // - `runForward()` + // - `runBackward()` + // - `applySpeedAcceleration()` + // - `moveByAcceleration()` + // + // Note: no update on `stopMove()` + // + // Returns 0 on success, or -1 on invalid value. + // Invalid is faster than MaxSpeed or slower than ~250 Mio ticks/step. + int8_t setSpeedInUs(uint32_t min_step_us); + int8_t setSpeedInTicks(uint32_t min_step_ticks); + int8_t setSpeedInHz(uint32_t speed_hz); + int8_t setSpeedInMilliHz(uint32_t speed_mhz); + + // To retrieve current set speed. This means, while accelerating and/or + // decelerating, this is NOT the actual speed ! + inline uint32_t getSpeedInUs() const { return _rg.getSpeedInUs(); } + inline uint32_t getSpeedInTicks() const { return _rg.getSpeedInTicks(); } + inline uint32_t getSpeedInMilliHz() const { return _rg.getSpeedInMilliHz(); } + + // If the current speed is needed, then use `getCurrentSpeed...()`. This + // retrieves the actual speed. + // + // | value | description | + // |:-----:|:-----------------------------| + // | = 0 | while not moving | + // | > 0 | while position counting up  | + // | < 0 | while position counting down | + // + // If the parameter realtime is true, then the most actual speed + // from the stepper queue is derived. This works only, if the queue + // does not contain pauses, which is normally the case for slow speeds. + // Otherwise the speed from the ramp generator is reported, which is + // done always in case of `realtime == false`. That speed is typically + // the value of the speed a couple of milliseconds later. + // + // The drawback of `realtime == true` is, that the reported speed + // may either come from the queue or from the ramp generator. + // This means the returned speed may have jumps during + // acceleration/deceleration. + // + // For backward compatibility, the default is true. + int32_t getCurrentSpeedInUs(bool realtime = true) const; + int32_t getCurrentSpeedInMilliHz(bool realtime = true) const; + + // ## Acceleration + // setAcceleration() expects as parameter the change of speed + // as step/s². + // If for example the speed should ramp up from 0 to 10000 steps/s within + // 10s, then the acceleration is 10000 steps/s / 10s = 1000 steps/s² + // + // New value will be used after call to + // move/moveTo/runForward/runBackward/applySpeedAcceleration/moveByAcceleration + // + // note: no update on stopMove() + // + // Returns 0 on success, or -1 on invalid value (<=0) + inline int8_t setAcceleration(int32_t step_s_s) { + return _rg.setAcceleration(step_s_s); + } + inline uint32_t getAcceleration() const { return _rg.getAcceleration(); } + + // getCurrentAcceleration() retrieves the actual acceleration. + // = 0 while idle or coasting + // > 0 while speed is changing towards positive values + // < 0 while speed is changing towards negative values + inline int32_t getCurrentAcceleration() const { + return _rg.getCurrentAcceleration(); + } + + // ## Linear Acceleration + // setLinearAcceleration expects as parameter the number of steps, + // where the acceleration is increased linearly from standstill up to the + // configured acceleration value. If this parameter is 0, then there will be + // no linear acceleration phase + // + // If for example the acceleration should ramp up from 0 to 10000 steps/s^2 + // within 100 steps, then call setLinearAcceleration(100) + // + // The speed at which linear acceleration turns into constant acceleration + // can be calculated from the parameter linear_acceleration_steps. + // Let's call this parameter `s_h` for handover steps. + // Then the speed is: + // `v_h = sqrt(1.5 * a * s_h)` + // + // New value will be used after call to + // move/moveTo/runForward/runBackward/applySpeedAcceleration/moveByAcceleration + // + // note: no update on stopMove() + inline void setLinearAcceleration(uint32_t linear_acceleration_steps) { + _rg.setLinearAcceleration(linear_acceleration_steps); + } + + // ## Jump Start + // setJumpStart expects as parameter the ramp step to start from standstill. + // + // The speed at which the stepper will start can be calculated like this: + // - If linear acceleration is not in use: + // start speed `v = sqrt(2 * a * jump_step)` + // - If linear acceleration is in use and `jump_step <= s_h`: + // start speed `v = sqrt(1.5*a)/s_h^(1/6) * jump_step^(2/3)` + // - If linear acceleration is in use and `jump_step > s_h`: + // start speed `v = sqrt(2 * a * (jump_step - s_h/4))` + // + // + // New value will be used after call to + // move/moveTo/runForward/runBackward + inline void setJumpStart(uint32_t jump_step) { _rg.setJumpStart(jump_step); } + + // ## Apply new speed/acceleration value + // This function applies new values for speed/acceleration. + // This is convenient especially, if the stepper is set to continuous running. + void applySpeedAcceleration(); + + // ## Move commands + // ### move() and moveTo() + // start/move the stepper for (move) steps or to an absolute position. + // + // If the stepper is already running, then the current running move will be + // updated together with any updated values of acceleration/speed. The move is + // relative to the target position of any ongoing move ! If the new + // move/moveTo for an ongoing command would reverse the direction, then the + // command is silently ignored. + // return values are the MOVE_... constants + MoveResultCode move(int32_t move, bool blocking = false); + MoveResultCode moveTo(int32_t position, bool blocking = false); + + // ### keepRunning() + // This command flags the stepper to keep run continuously into current + // direction. It can be stopped by stopMove. + // Be aware, if the motor is currently decelerating towards reversed + // direction, then keepRunning() will speed up again and not finish direction + // reversal first. + void keepRunning(); + bool isRunningContinuously() const { return _rg.isRunningContinuously(); } + + // ### runForward() and runBackwards() + // These commands just let the motor run continuously in one direction. + // If the motor is running in the opposite direction, it will reverse + // return value as with move/moveTo + MoveResultCode runForward(); + MoveResultCode runBackward(); + + // ### forwardStep() and backwardStep() + // forwardStep()/backwardstep() can be called, while stepper is not moving + // If stepper is moving, this is a no-op. + // backwardStep() is a no-op, if no direction pin defined + // It will immediately let the stepper perform one single step. + // If blocking = true, then the routine will wait till isRunning() is false + void forwardStep(bool blocking = false); + void backwardStep(bool blocking = false); + + // ### moveByAcceleration() + // moveByAcceleration() can be called, if only the speed of the stepper + // is of interest and that speed to be controlled by acceleration. + // The maximum speed (in both directions) to be set by setSpeedInUs() before. + // The behaviour will be: + // acceleration > 0 => accelerate towards positive maximum speed + // acceleration = 0 => keep current speed + // acceleration < 0 + // => accelerate towards negative maximum speed if allow_reverse + // => decelerate towards motor stop if allow_reverse = false + // return value as with move/moveTo + MoveResultCode moveByAcceleration(int32_t acceleration, + bool allow_reverse = true); + + // ### stopMove() + // Stop the running stepper with normal deceleration. + // This only sets a flag and can be called from an interrupt ! + void stopMove(); + inline bool isStopping() const { return _rg.isStopping(); } + + // ### stepsToStop() + // This returns the current step value of the ramp. + // This equals the number of steps for a motor to + // reach the current position and speed from standstill + // and to come to standstill with deceleration if stopped + // immediately. + // This value is valid with or without linear acceleration + // being used. + // Primary use is to forecast possible stop position. + // The stop position is: + // getCurrentPosition() + stepsToStop() + // in case of a motor running in positive direction. + uint32_t stepsToStop() const { return _rg.stepsToStop(); } + + // ### forceStop() + // Abruptly stop the running stepper without deceleration. + // This can be called from an interrupt ! + // + // The stepper command queue will be processed, but no further commands are + // added. This means, that the stepper can be expected to stop within approx. + // 20ms. + void forceStop(); + + // abruptly stop the running stepper without deceleration. + // This can be called from an interrupt ! + // + // No further step will be issued. As this is aborting all commands in the + // queue, the actual stop position is lost (recovering this position cannot be + // done within an interrupt). So the new position after stop has to be + // provided and will be set as current position after stop. + void forceStopAndNewPosition(int32_t new_pos); + + // Return the cause of the last stop and clear it. For a planner that shares + // the queue with the ramp API: it polls this to notice that a member axis + // was stopped manually (stopMove) or abruptly (forceStop / + // forceStopAndNewPosition) and then aborts the coordinated plan. + StepperStopCause takeStopCause(); + StepperStopCause getStopCause() const { + return (StepperStopCause)_stop_cause; + } + + // ### resumeCommands() + // Rearm the queue after forceStop() or forceStopAndNewPosition(). + // + // Both stops set a queue admission latch: addQueueEntry() then refuses every + // command with AQE_ERROR_COMMANDS_SUSPENDED, including + // addQueueEntry(NULL, start). The latch is a backstop against a planner whose + // own stop flag is wrong, so it stays set until a caller explicitly rearms. + // + // This is the public key to it, and it is required by the low-level + // addQueueEntry() API: without it, a caller that aborted cannot queue again + // on the same connection. The high-level API needs no call -- the ramp clears + // the latch itself on the next fill_queue() pass. + // + // Note this does not resume motion. After forceStopAndNewPosition() the queue + // was emptied and the position was overwritten, so the caller owns the + // coordinate from here (see setCurrentPosition()). + // + // Not for clearing a stop mid-flight: to abort, use forceStop() or + // forceStopAndNewPosition(). + void resumeCommands(); + + // True while commands are refused. See resumeCommands(). + bool areCommandsSuspended() const; + + // get the target position for the current move. + // As of now, this position is the view of the stepper task. + // This means, the value will stay unchanged after a move/moveTo until the + // stepper task is executed. + // In keep running mode, the targetPos() is not updated + inline int32_t targetPos() const { return _rg.targetPosition(); } + + // ### Task planning + // The stepper task adds commands to the stepper queue until + // either at least two commands are planned, or the commands + // cover sufficient time into the future. Default value for that time is 20ms. + // + // The stepper task is cyclically executed every ~4ms. + // Especially for avr, the step interrupts puts a significant load on the uC, + // so the cyclical stepper task can even run for 2-3 ms. On top of that, + // other interrupts caused by the application could increase the load even + // further. + // + // Consequently, the forward planning should fill the queue for ideally two + // cycles, this means 8ms. This means, the default 20ms provide a sufficient + // margin and even a missed cycle is not an issue. + // + // The drawback of the 20ms is, that any change in speed/acceleration are + // added after those 20ms and for an application, requiring fast reaction + // times, this may impact the expected performance. + // + // Due to this the forward planning time can be adjusted with the following + // API call for each stepper individually. + // + // ### Driver in-flight (read-ahead) contract + // `fill_queue()` fills the queue to `_forward_planning_in_ticks` (default + // 20 ms), and while a move is running the queue MUST NOT run low. A pulse + // driver, though, drains commands out of the queue into its own hardware + // pipeline "in flight" ahead of the pin, so the queue only needs to keep + // commands for *that* pipeline fed. The contract is therefore: + // + // forward_planning_ticks > driver's maximum in-flight time + // + // Otherwise the driver can drain the whole queue mid-move, find it empty + // and stop/under-run. Each driver must state how much it will drain at + // most (in flight): + // - AVR / SAM / SAMD / Teensy / Pico: no buffered pipeline; at most one + // command at a time is consumed, so in-flight is one command. + // - ESP32 I2S: the DMA blocks, I2S_BLOCK_COUNT*I2S_BLOCK_TICKS = 1 ms. + // - ESP32 MCPWM/PCNT: generator actions latch at TEZ/TEP, so the timer + // holds about one command in its shadow/active registers plus the + // period being generated; in-flight is ~one command. + // - ESP32 RMT (IDF4): the half filler ping-pongs one PART_SIZE-symbol + // half per threshold; the RMT memory holds two halves, so in-flight is + // the playback time of 2*PART_SIZE symbols (bounded by the command + // periods, which the fill routine limits). + // - ESP32 RMT (IDF5/6): rmt_encode_fill() caps every RMT sub-entry (the + // step high and every low chunk) at RMT_MAX_SYMBOL_TICKS + // (= RMT_BLOCK_TICKS/(2*PART_SIZE)). A symbol holds TWO sub-entries, so a + // symbol is at most 2*RMT_MAX_SYMBOL_TICKS and one RMT half + // (PART_SIZE symbols) spans at most RMT_BLOCK_TICKS = 8000 ticks = + // 0.5 ms. The channel's mem_block_symbols = 2*PART_SIZE buffer therefore + // holds at most RMT_BUFFER_TICKS = 16000 ticks = 1 ms, and that is the + // driver's in-flight. The direction-change drain must exceed it, because + // the DIR toggle is executed while encoding, not while playing: see + // esp32_before_pause_ticks(). + // + // Attention: + // - This is only for advanced users: no error checking is implemented. + // - Only change the forward planning time, if the stepper is not running. + // - It must stay above the used driver's maximum in-flight time, otherwise + // the queue can drain mid-move. + // - Too small values bear the risk of a stepper running at full speed + // suddenly stopping + // due to lack of commands in the queue. + inline void setForwardPlanningTimeInMs(uint8_t ms) { + _forward_planning_in_ticks = ms; + _forward_planning_in_ticks *= TICKS_PER_S / 1000; // ticks per ms + } + + // ## Intermediate Level Stepper Control for Advanced Users + // + // Bypass the ramp generator to run consecutive moves at a fixed speed. + // The parameters are steps (which can be 0) and duration in ticks. + // steps=0 makes sense in order to keep the time running and not + // getting out of sync. + // Due to integer arithmetics the actual duration may be off by a small value. + // That's why the actual_duration in TICKS is returned. + // The application should consider this for the next runTimed move. + // + // The optional parameter is a boolean called start. This allows for the first + // invocation to not start the queue yet. This is for managing steppers in + // parallel. It allows to fill all steppers' queues and then kick it off by a + // call to `moveTimed(0,0,NULL,true)`. Successive invocations can keep true. + // + // In order to not have another lightweight ramp generator running in + // background interrupt, the expecation to the application is, that this + // function is frequently enough called without the queue being emptied. + // + // The current implementation immediately starts with a step, if there should + // be one. Perhaps performing the step in the middle of the duration is more + // appropriate ? + // + // A pause (steps = 0, duration > 0) uses the last queued direction, XOR + // prepare_revert (default false). So a normal pause does not toggle DIR; + // moveTimed(0, dt, ..., true) is a pause in the opposite direction. + // + // A move that changes direction makes the queue driver inject a pause command + // (see "Capacity and direction-change pauses" below). These pauses extend the + // time the move takes and they consume queue slots. If a pause is injected, + // moveTimed() returns AQE_DIR_CHANGE_PAUSE_INJECTED or + // AQE_DIR_PIN_2MS_PAUSE_ADDED and the command was NOT enqueued; in this case + // *actual_duration carries the ticks of the one injected pause. The + // application accumulates this value per retry (e.g. an "extra" variable) and + // computes the drift only after the move is accepted. The application has to + // account for the pauses - e.g. when scheduling the next timed move or when + // deciding that a stepper has finished - in order to not get out of sync with + // the stepper timing. Coordinated multi-axis motion can issue a + // prepare_revert pause on the reversing axis and the same duration as a + // normal pause on the others. + // + // Recommended retry pattern: + // uint32_t actual = 0, extra = 0; + // for (;;) { + // rc = stepper.moveTimed(steps, duration, &actual); + // if (rc == DirChangePauseInjected || rc == DirPin2msPauseAdded) { + // extra += actual; + // continue; + // } + // if (rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY) { + // drift = (int32_t)(duration - (actual + extra)); + // break; + // } + // ... other retry codes unchanged ... + // } + // + // ### MoveTimedResultCode - Return codes for moveTimed() + // + // This enum extends AqeResultCode with additional codes: + // + // Positive values (retry later): + // - MOVE_TIMED_BUSY (7): Queue too full to append this timed move + // - MOVE_TIMED_EMPTY (8): Queue ran empty, but move was appended + // - AQE_DIR_CHANGE_PAUSE_INJECTED (6): Direction-change pause injected, the + // move command was NOT enqueued. *actual_duration holds the injected pause + // ticks. Accumulate and retry the same move. + // - AQE_DIR_PIN_2MS_PAUSE_ADDED (5): 2ms pause for an external direction pin + // inserted, the move command was NOT enqueued. *actual_duration holds the + // injected pause ticks. Accumulate and retry the same move. + // - (plus AQE_QUEUE_FULL, AQE_DIR_PIN_IS_BUSY, + // AQE_WAIT_FOR_ENABLE_PIN_ACTIVE, AQE_DEVICE_NOT_READY from + // AqeResultCode) + // + // Zero: + // - MOVE_TIMED_OK (0): Move successfully appended + // + // Negative values (errors): + // - MOVE_TIMED_TOO_LARGE_ERROR (-4): Move exceeds queue capacity. + // Queue depth is 32 (ESP32/SAM) or 16 (AVR). Each entry emits max 255 + // steps. For slow speeds (>65535 ticks/step), pauses are needed, reducing + // capacity. Recommendation: keep duration in the range of milliseconds. + // + // ### Capacity and direction-change pauses + // + // A direction change makes the queue driver inject pause commands on top of + // the step command itself: buffered drivers (ESP32 RMT, I2S) first drain + // their output pipeline so no step in the old direction is emitted after the + // change, and every driver enforces a configured direction-pin delay with a + // pause command that carries the change. At most one pause is injected per + // addQueueEntry()/moveTimed() call; the total number over the course of a + // move is driver dependent (e.g. the ESP32 RMT driver needs up to three + // pauses across retries). moveTimed() therefore reserves two extra slots up + // front and only admits a move when the whole move plus the reserved slots + // fits into the queue at once (atomic append). Otherwise it returns + // MOVE_TIMED_BUSY instead of silently dropping steps mid-append (see + // Issue 370). + // + // As a consequence a single move may use at most QUEUE_LEN - 2 queue + // entries. For streaming at fixed speed it is recommended to keep the number + // of queue commands a move generates well below QUEUE_LEN/2 and to split + // larger moves on the application side, so the reserved slots never block a + // steady feed. + // - (plus AQE_ERROR_TICKS_TOO_LOW, AQE_ERROR_EMPTY_QUEUE_TO_START, + // AQE_ERROR_NO_DIR_PIN_TO_TOGGLE from AqeResultCode) + MoveTimedResultCode moveTimed(int16_t steps, uint32_t duration, + uint32_t* actual_duration, bool start = true, + bool prepare_revert = false); + + // ## Low Level Stepper Queue Management (low level access) + // + // This interface bypasses the ramp generator and writes raw commands into + // the per-stepper queue. It gives full control over position, speed and + // direction, but the application is responsible for the ramp. It is meant + // for applications doing their own motion planning, e.g. a G-code + // interpreter. + // + // The high level interface always ends a move at speed ~0 at the target + // position and does not expose the exact position/speed/acceleration + // relation while running. To chain segments without stopping in between, + // this low level interface (or a planner built on it) is required. + // + // For coordinated multi-axis motion prefer the planners that sit on top of + // this interface: FasNAxis (polyline, as fast as possible) and FasTimed + // (constant speed for a given duration). They use the queues below and + // complement the raw interface, so they should be the first choice unless + // fully custom commands are needed. + // + // To stay tick-exact, the queue must not run empty and interrupts must be + // serviced in time. Do not block interrupts for long. On esp32, do not write + // to flash while a stepper is running (e.g. an OTA update): motion continues + // but is noticeably bumpy. + // + // If the queue is already running, then the start parameter is obsolete. + // But the queue may run out of commands while executing addQueueEntry, + // so it is better to set start=true to automatically restart/continue + // a running queue. + // + // If the queue is not running, then the start parameter defines starting it + // or not. The latter case is of interest to first fill the queue and then + // start it. + // + // The call addQueueEntry(NULL, true) just starts the queue. A synchronized + // start of several steppers is the single engine operation + // StepperMotionEngine::synchronizedStart(), which releases the listed + // queues in one engine operation. The per-stepper call should still return + // very fast, too, in case the queue is full and not started. + // ### Direction Change Delay Enforcement + // + // If the new command's direction differs from the previous command, + // addQueueEntry() will automatically insert pause commands to ensure + // sufficient delay before the first step in the new direction: + // + // - For external direction pins (pin >= 128): The direction pin is controlled + // via an external callback (e.g., to an I/O expander). To avoid steps in + // the wrong direction, the queue must be empty of steps before the + // direction change. If steps are present or the external callback is still + // pending, a 2ms pause is inserted and AQE_DIR_PIN_2MS_PAUSE_ADDED is + // returned. The caller should retry until the queue drains and the callback + // completes. + // + // - For regular direction pins: If a pause is required (a configured + // dir_change_delay_us > 0 and/or the driver needs to drain its output + // pipeline before the change), one or more pause commands are queued and + // AQE_DIR_CHANGE_PAUSE_INJECTED is returned WITHOUT enqueueing the + // submitted command. The caller must retry (the same as for + // AQE_DIR_PIN_2MS_PAUSE_ADDED); moveTimed() and the internal queue fill + // do so automatically. On the retry the direction already matches, or the + // pauses are skipped, and the command is enqueued. + // + // ESP32 I2S GPIO DIR is async at fill time, so both DMA blocks must be + // pause (2*I2S_BLOCK_TICKS before the change). I2S mux-slot DIR is valid + // only with I2S_MUX and needs I2S_BLOCK_TICKS after the change (the mask + // applies to the next buffer). I2S_DIRECT direction pins are GPIO. + // + // - For autoEnable mode: The enable-on delay is extended to at least + // dir_change_delay_ticks if a direction change occurs. + // + // ### stepper_command_s structure + // + // This structure defines a low-level stepper motor command for + // addQueueEntry(): + // + // - `ticks`: Number of ticks between each step. Must be >= + // getMaxSpeedInTicks(). + // There are TICKS_PER_S ticks per second (platform dependent). + // + // - `steps`: Number of steps to send. If 0, this is a pause command lasting + // for `ticks` ticks. + // + // - `count_up`: Direction. True = direction pin HIGH, False = direction pin + // LOW. + // + // Constraint: `ticks * steps` must be >= MIN_CMD_TICKS. + // + // Example: ticks=TICKS_PER_S/1000, steps=3, count_up=true means: + // 1. Direction pin set to HIGH + // 2. One step is generated + // 3. Exactly 1ms after the first step, the second step + // 4. Exactly 1ms after the second step, the third step + // 5. The stepper waits for 1ms + // 6. The next command is processed + // + // A command with steps=N and ticks=T occupies N*T ticks: N steps spaced T + // apart, plus a trailing wait of T after the last step. The next command + // then starts right after that, so its first step is T ticks after the last + // step of the previous command. + // + // ### Slow step rates and the uint16_t ticks limit + // + // `ticks` is a uint16_t, so the longest gap between two steps is 65535 + // ticks (~4.1ms at 16MHz). Slower stepping is done by inserting pause + // commands (steps = 0) between steps, because the queue time is the sum of + // all commands. Example: 3 steps every 10ms at TICKS_PER_S=16MHz: + // + // - ticks=40000, steps=1, count_up=true (first step) + // - ticks=40000, steps=0, count_up=true (pause) + // - ticks=40000, steps=0, count_up=true (pause) + // - ticks=40000, steps=0, count_up=true (pause) + // - ticks=40000, steps=1, count_up=true (second step) + // - ... and so on for the third step + // + // The 16 bit limit is deliberate: the esp32 pulse generator registers are + // 16 bit and this keeps AVR and esp32 on the same code path. The queue holds + // only ~10ms of commands, so the application can react to position, speed + // and acceleration changes almost instantly; wider tick values would only + // make the driver slower. + // + // ### AqeResultCode - Return codes for addQueueEntry() + // + // Positive values indicate the caller should retry later: + // - AQE_OK (0): Command added successfully + // - AQE_QUEUE_FULL (1): Queue is full, retry later + // - AQE_DIR_PIN_IS_BUSY (2): Direction pin is busy, retry later + // - AQE_WAIT_FOR_ENABLE_PIN_ACTIVE (3): Waiting for enable delay, retry later + // - AQE_DEVICE_NOT_READY (4): Device not ready, retry later + // - AQE_DIR_PIN_2MS_PAUSE_ADDED (5): 2ms pause queued for an external dir + // pin; retry until the callback completes + // - AQE_DIR_CHANGE_PAUSE_INJECTED (6): dir-change pause(s) queued; retry to + // enqueue the submitted command + // + // Negative values indicate errors (do not retry): + // - AQE_ERROR_TICKS_TOO_LOW (-1): the command is too fast to be + // queued. Two separate checks, and the second is the one that surprises: + // ticks must be >= getMaxSpeedInTicks(), AND the command's total duration + // must be >= MIN_CMD_TICKS (200us, i.e. TICKS_PER_S / 5000). The duration + // is ticks * steps for a multi-step command, so a command of `steps` steps + // at period `ticks` is accepted when ticks * steps >= MIN_CMD_TICKS. A + // pause (steps == 0) and a single-step command have duration == ticks, so + // for those two the period itself must clear MIN_CMD_TICKS: a single step + // cannot be queued faster than 200us, however fast the driver is. + // Consequence: getMaxSpeedInTicks() is the fastest *period*, not the + // fastest value that can appear as `ticks` on its own. To run at that + // period, put enough steps in the command to reach MIN_CMD_TICKS. + // - AQE_ERROR_EMPTY_QUEUE_TO_START (-2): Empty command with start=true, but + // queue empty + // - AQE_ERROR_NO_DIR_PIN_TO_TOGGLE (-3): count_up=false without direction pin + // + // ### aqeRetry() / aqeRetryImmediately() / aqeIsOk() - helpers for + // AqeResultCode + // + // aqeRetry(code) returns true for all positive codes, i.e. every code that + // indicates the caller should retry addQueueEntry() later. Negative codes + // (errors) and AQE_OK return false. + // + // aqeRetryImmediately(code) returns true only for + // AQE_DIR_CHANGE_PAUSE_INJECTED. This code means a direction-change pause + // was queued but the submitted command was not yet enqueued, so the caller + // should retry addQueueEntry() immediately (without waiting) to enqueue it. + // All other codes return false. + // + // aqeIsOk(code) returns true only for AQE_OK, i.e. the command was added + // successfully. + AqeResultCode addQueueEntry(const struct stepper_command_s* cmd, + bool start = true); + + // ### check functions for command queue being empty, full or running. + bool isQueueEmpty() const; + bool isQueueFull() const; + bool isQueueRunning() const; + + // ### functions to get the fill level of the queue + // + // To retrieve the forward planning time in the queue, ticksInQueue() + // can be used. It sums up all ticks of the not yet processed commands. + // For commands defining pauses, the summed up value is entry.ticks. + // For commands with steps, the summed up value is entry.steps*entry.ticks + uint32_t ticksInQueue() const; + + // This function can be used to check, if the commands in the queue + // will last for ticks. This is again without the + // currently processed command. + bool hasTicksInQueue(uint32_t min_ticks) const; + + // This function allows to check the number of commands in the queue. + // This is including the currently processed command. + uint8_t queueEntries() const; + + // Get the future position of the stepper after all commands in queue are + // completed + int32_t getPositionAfterCommandsCompleted() const; + + // Get the future speed of the stepper after all commands in queue are + // completed. This is in µs. Returns 0 for stopped motor + // + // This value comes from the ramp generator and is not valid for raw command + // queue + // ==> Will be renamed in future release + uint32_t getPeriodInUsAfterCommandsCompleted() const; + uint32_t getPeriodInTicksAfterCommandsCompleted() const; + + // Set the future position of the stepper after all commands in queue are + // completed. This has immediate effect to getCurrentPosition(). + void setPositionAfterCommandsCompleted(int32_t new_pos); + + // This function provides info, in which state the high level stepper control + // is operating. The return value is an `or` of RAMP_STATE_... and + // RAMP_DIRECTION_... flags. Definitions are above + inline uint8_t rampState() const { return _rg.rampState(); } + + // returns true, if the ramp generation is active + inline bool isRampGeneratorActive() const { + return _rg.isRampGeneratorActive(); + } + + // These functions allow to detach and reAttach a step pin for other use. + // Pretty low level, use with care or not at all + void detachFromPin(); + void reAttachToPin(); + + // ## ESP32 only: Free pulse counter + // These four functions are only available on esp32. + // The first can attach any of the eight pulse counters to this stepper. + // The second then will read the current pulse counter value + // + // The user is responsible to not use a pulse counter, which is occupied by a + // stepper and by this render the stepper or even blow up the uC. + // + // Pulse counter 6 and 7 are not used by the stepper library and are judged as + // available. If only five steppers are defined, then 5 gets available. If + // four steppers are defined, then 4 is usable,too. + // + // These functions are the way to read the pulses that have already left + // the step pin. getCurrentPosition() leads that pin while a move is + // running, because the driver pipelines steps. readPulseCounter() is + // the count of edges already emitted. The same hooks are used by the + // hardware tests. + // + // The pulse counter counts up towards high_value. + // If the high_value is reached, then the pulse counter is reset to 0. + // Similarly, if direction pin is configured and set to count down, + // then the pulse counter counts towards low_value. When the low value is hit, + // the pulse counter is reset to 0. + // + // If low_value and high_value are set to zero, then the pulse counter is just + // counting like any int16_t counter: 0...32767,-32768,-32767,...,0 and + // backwards accordingly + // + // Possible application: + // Assume the stepper, to which the pulse counter attached to, needs 3200 + // steps/revolution. If now attachToPulseCounter is called with -3200 and 3200 + // for the low and high values respectively, then the momentary angle of the + // stepper (at exact this moment) can be retrieved just by reading the pulse + // counter. If the value is negative, then just add 3200. + // + // In case external direction pin is used and the dir pin is available on one + // of the GPIOs, then the additional dir_pin_readback parameter informs + // about this pin. + // + // By default the pulse counter increments on the rising edge of the step + // pulse (low-to-high). Set invert_step_pulse to true to increment on the + // falling edge instead, for inverted step polarity. + // + // Update for idf5/idf6 version: + // The pcnt_unit value is not used, because the available units are managed + // by the system. The parameter is kept for compatibility. + // +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR >= 5) + bool attachToPulseCounter(uint8_t unused_pcnt_unit = 0, + int16_t low_value = -16384, + int16_t high_value = 16384, + uint8_t dir_pin_readback = PIN_UNDEFINED, + bool invert_step_pulse = false); + int16_t readPulseCounter(); + void clearPulseCounter(); + inline bool pulseCounterAttached() { return _attached_pulse_unit != NULL; } +#endif +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 4) + bool attachToPulseCounter(uint8_t pcnt_unit, int16_t low_value = -16384, + int16_t high_value = 16384, + uint8_t dir_pin_readback = PIN_UNDEFINED, + bool invert_step_pulse = false); + int16_t readPulseCounter(); + void clearPulseCounter(); + inline bool pulseCounterAttached() { return _attached_pulse_cnt_unit >= 0; } +#endif + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + // Get the driver type (RMT, MCPWM_PCNT, I2S_DIRECT, I2S_MUX) used by this + // stepper. Only available on ESP32 when multiple driver types are supported. + FasDriver driverType() const; + const char* driverTypeString() const; +#endif + + private: + void performOneStep(bool count_up, bool blocking = false); + void fill_queue(); + void updateAutoDisable(); + void blockingWaitForForceStopComplete(); + bool needAutoDisable(); + bool agreeWithAutoDisable(); + bool usesAutoEnablePin(uint8_t pin); + void getCurrentSpeedInTicks(struct actual_ticks_s* speed, + bool realtime) const; + bool handleExternalDirectionPin(class StepperQueue* q, bool count_up); + class StepperQueue* _queue() const; + bool setEnablePinState(uint8_t pin, uint8_t active_state); + + StepperMotionEngine* _engine; + RampGenerator _rg; + uint8_t _stepPin; + uint8_t _dirPin; + bool _dirHighCountsUp; + bool _autoEnable; + uint8_t _enablePinLowActive; + uint8_t _enablePinHighActive; + uint8_t _queue_num; + + uint16_t _dir_change_delay_ticks; + uint32_t _on_delay_ticks; + uint16_t _off_delay_count; + uint16_t _auto_disable_delay_counter; + + uint32_t _forward_planning_in_ticks; + + ExtDirPendingState _pendingExternalDirState; + +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR >= 5) + pcnt_unit_handle_t _attached_pulse_unit; +#endif +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 4) + int16_t _attached_pulse_cnt_unit; +#endif +#if (TEST_MEASURE_ISR_SINGLE_FILL == 1) + uint32_t max_micros; +#endif + + // Last stop cause, set by the stop API and cleared by takeStopCause(). + // volatile because stopMove()/forceStop() may be called from an interrupt. + // + // Keep this at the end of the member list. Adding it in the middle shifted + // the byte members above and measurably changed AVR FillISR/StepISR timing + // (test_sd_04_timing_2560: StepA Total High 355083us -> 451756us). Layout is + // semantically irrelevant, so it lives at the tail to keep the hot members' + // offsets stable. + volatile uint8_t _stop_cause; + + friend class StepperMotionEngine; + friend class StepperMotionTest; +}; + +#endif diff --git a/src/StepperMotionEngine.cpp b/src/StepperMotionEngine.cpp new file mode 100644 index 0000000..a77cfd6 --- /dev/null +++ b/src/StepperMotionEngine.cpp @@ -0,0 +1,237 @@ +#include "StepperMotionEngine.h" +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_I2S) +#include "pd_esp32/i2s_manager.h" +#endif + +#ifndef TEST +#define printf DO_NOT_USE_PRINTF +#define puts DO_NOT_USE_PUTS +#endif + +static uint8_t fas_ledPin = PIN_UNDEFINED; +static uint16_t fas_debug_led_cnt = 0; + +#if !defined(SUPPORT_DYNAMIC_ALLOCATION) +StepperMotion fas_stepper[MAX_STEPPER]; +#endif + +#if defined(SUPPORT_CPU_AFFINITY) +void StepperMotionEngine::init(uint8_t cpu_core) { + _externalCallForPin = NULL; + _stepper_cnt = 0; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + _stepper[i] = NULL; + } + for (uint8_t i = 0; i < NUM_QUEUES; i++) { +#if defined(SUPPORT_DYNAMIC_ALLOCATION) + fas_queue[i] = NULL; +#else + fas_queue[i]._initVars(); +#endif + } + fas_init_engine(this, cpu_core); +} +#else +void StepperMotionEngine::init() { + _externalCallForPin = NULL; + _stepper_cnt = 0; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + _stepper[i] = NULL; + } + for (uint8_t i = 0; i < NUM_QUEUES; i++) { +#if defined(SUPPORT_DYNAMIC_ALLOCATION) + fas_queue[i] = NULL; +#else + fas_queue[i]._initVars(); +#endif + } + + fas_init_engine(this); +} +#endif + +void StepperMotionEngine::setExternalCallForPin( + bool (*func)(uint8_t pin, uint8_t value)) { + _externalCallForPin = func; +} + +bool StepperMotionEngine::isDirPinBusy(uint8_t dir_pin, + uint8_t except_stepper) { + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (i != except_stepper) { + const StepperMotion* s = _stepper[i]; + if (s) { + if (s->getDirectionPin() == dir_pin) { + if (s->isQueueRunning()) { + return true; + } + } + } + } + } + return false; +} + +#if defined(SUPPORT_ESP32_I2S) && defined(SUPPORT_DYNAMIC_ALLOCATION) +bool StepperMotionEngine::initI2sMux(uint8_t data_pin, uint8_t bclk_pin, + uint8_t ws_pin) { + if (StepperQueue::_i2s_mux_initialized) { + return false; + } + I2sManager* mgr = I2sManager::create( + (gpio_num_t)data_pin, (gpio_num_t)bclk_pin, (gpio_num_t)ws_pin); + if (mgr == nullptr) { + return false; + } + mgr->_is_mux = true; + StepperQueue::_i2s_mux_manager = mgr; + StepperQueue::_i2s_mux_initialized = true; + return true; +} + +void StepperMotionEngine::i2sMuxSetBit(uint8_t slot, bool value) { + if (StepperQueue::_i2s_mux_manager != nullptr) { + StepperQueue::_i2s_mux_manager->i2sMuxSetBit(slot, value); + } +} + +bool StepperMotionEngine::i2sMuxGetBit(uint8_t slot) { + if (StepperQueue::_i2s_mux_manager != nullptr) { + return StepperQueue::_i2s_mux_manager->i2sMuxGetBit(slot); + } + return false; +} +#endif + +#if defined(SUPPORT_DYNAMIC_ALLOCATION) +// Dynamic allocation (ESP32 with IDF >= 5.3) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +StepperMotion* StepperMotionEngine::stepperConnectToPin( + uint8_t step_pin, FasDriver driver_type) { + StepperQueue* q = StepperQueue::tryAllocateQueue(this, driver_type, step_pin); +#else +StepperMotion* StepperMotionEngine::stepperConnectToPin( + uint8_t step_pin) { + StepperQueue* q = StepperQueue::tryAllocateQueue(this, step_pin); +#endif + if (q == nullptr) { + return nullptr; + } + + uint8_t fas_stepper_num = _stepper_cnt; + _stepper_cnt++; + fas_queue[fas_stepper_num] = q; + + StepperMotion* s = new StepperMotion(); + s->init(this, fas_stepper_num, step_pin); + _stepper[fas_stepper_num] = s; + return s; +} +#else +// Static allocation (AVR, SAM, Pico, TEST, ESP32 IDF 4.x) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +StepperMotion* StepperMotionEngine::stepperConnectToPin( + uint8_t step_pin, FasDriver driver_type) { + StepperQueue* q = StepperQueue::tryAllocateQueue(this, driver_type, step_pin); +#else +StepperMotion* StepperMotionEngine::stepperConnectToPin( + uint8_t step_pin) { + const StepperQueue* q = StepperQueue::tryAllocateQueue(this, step_pin); +#endif + if (q == nullptr) { + return nullptr; + } + + uint8_t fas_stepper_num = (uint8_t)(q - fas_queue); + _stepper_cnt++; + + StepperMotion* s = &fas_stepper[fas_stepper_num]; + s->init(this, fas_stepper_num, step_pin); + _stepper[fas_stepper_num] = s; + +#if defined(NEED_ADJUSTABLE_MAX_SPEED_DEPENDING_ON_STEPPER_COUNT) + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + const StepperMotion* sx = _stepper[i]; + if (sx) { + sx->_queue()->adjustSpeedToStepperCount(_stepper_cnt); + } + } +#endif + + return s; +} +#endif + +void StepperMotionEngine::setDebugLed(uint8_t ledPin) { + fas_ledPin = ledPin; + PIN_OUTPUT(fas_ledPin, LOW); +} + +void StepperMotionEngine::manageSteppers() { +#ifdef DEBUG_LED_HALF_PERIOD + if (fas_ledPin != PIN_UNDEFINED) { + fas_debug_led_cnt++; + if (fas_debug_led_cnt == DEBUG_LED_HALF_PERIOD) { + digitalWrite(fas_ledPin, HIGH); + } + if (fas_debug_led_cnt == 2 * DEBUG_LED_HALF_PERIOD) { + digitalWrite(fas_ledPin, LOW); + fas_debug_led_cnt = 0; + } + } +#endif + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + StepperMotion* s = _stepper[i]; + if (s) { + s->fill_queue(); + } + } + + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + StepperMotion* s = _stepper[i]; + if (s) { + if (s->needAutoDisable()) { + uint8_t high_active_pin = s->getEnablePinHighActive(); + uint8_t low_active_pin = s->getEnablePinLowActive(); + + bool agree = true; + for (uint8_t j = 0; j < MAX_STEPPER; j++) { + if (i != j) { + StepperMotion* other = _stepper[j]; + if (other) { + if (other->usesAutoEnablePin(high_active_pin) || + other->usesAutoEnablePin(low_active_pin)) { + if (!other->agreeWithAutoDisable()) { + agree = false; + break; + } + } + } + } + } + if (agree) { + for (uint8_t j = 0; j < MAX_STEPPER; j++) { + StepperMotion* current = _stepper[j]; + if (current) { + if (current->usesAutoEnablePin(high_active_pin) || + current->usesAutoEnablePin(low_active_pin)) { + current->disableOutputs(); + } + } + } + } + } + } + } + + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + StepperMotion* s = _stepper[i]; + if (s) { + fasDisableInterrupts(); + s->updateAutoDisable(); + fasEnableInterrupts(); + } + } +} diff --git a/src/StepperMotionEngine.h b/src/StepperMotionEngine.h new file mode 100644 index 0000000..7ea2e7e --- /dev/null +++ b/src/StepperMotionEngine.h @@ -0,0 +1,206 @@ +#ifndef STEPPERMOTION_ENGINE_H +#define STEPPERMOTION_ENGINE_H +#include +#include "fas_arch/common.h" + +// Controls buffered STEP/DIR pulse generation on supported microcontrollers. +// +// Here is a basic example to run a stepper from position 0 to 1000 and back +// again to 0. +// ``` +// #include +// +// StepperMotionEngine engine = StepperMotionEngine(); +// StepperMotion *stepper = NULL; +// +// #define dirPinStepper 5 +// #define enablePinStepper 6 +// #define stepPinStepper 9 +// void setup() { +// engine.init(); +// stepper = engine.stepperConnectToPin(stepPinStepper); +// if (stepper) { +// stepper->setDirectionPin(dirPinStepper); +// stepper->setEnablePin(enablePinStepper); +// stepper->setAutoEnable(true); +// +// stepper->setSpeedInHz(500); +// stepper->setAcceleration(100); +// stepper->moveTo(1000, true); +// stepper->moveTo(0, true); +// } +// } +// +// void loop() {} +// ``` + +class StepperMotion; + +class StepperMotionEngine { + // + // ## StepperMotionEngine + // + // This engine - actually a factory - provides you with instances of steppers. + + public: + // ### Initialization + // + // The StepperMotionEngine is declared with StepperMotionEngine(). + // This is to occupy the needed memory. + // ```cpp + // StepperMotionEngine engine = StepperMotionEngine(); + // ``` + // But it still needs to be initialized. + // For this init shall be used: + // ```cpp + // void setup() { + // engine.init(); + // } + // ``` + +#if defined(SUPPORT_CPU_AFFINITY) + // In a multitasking and multicore system like ESP32, the steppers are + // controlled by a continuously running task. This task can be fixed to one + // CPU core with this modified init()-call. ESP32 implementation detail: For + // values 0 and 1, xTaskCreatePinnedToCore() is used, or else xTaskCreate() + void init(uint8_t cpu_core = 255); +#else + void init(); +#endif + + // ### Creation of StepperMotion + // + // Using a call to `stepperConnectToPin()` a StepperMotion instance is + // created. This call tells the stepper, which step pin to use. As the + // hardware may have limitations - e.g. no stepper resources anymore, or the + // step pin cannot be used, then NULL is returned. So it is advised to check + // the return value of this call. +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + // For e.g. esp32, there are two types of driver. + // One using mcpwm and pcnt module. And another using rmt module. + // This call allows to select the respective driver +#define DRIVER_MCPWM_PCNT FasDriver::MCPWM_PCNT +#define DRIVER_RMT FasDriver::RMT +#if defined(SUPPORT_ESP32_I2S) + // For esp32, there is also an I2S based driver available. + // DRIVER_I2S_DIRECT uses the I2S module directly. + // DRIVER_I2S_MUX uses the I2S module with a multiplexer. + // initI2sMux() must be called before using DRIVER_I2S_MUX. +#define DRIVER_I2S_DIRECT FasDriver::I2S_DIRECT +#define DRIVER_I2S_MUX FasDriver::I2S_MUX + bool initI2sMux(uint8_t data_pin, uint8_t bclk_pin, uint8_t ws_pin); + void i2sMuxSetBit(uint8_t slot, bool value); + bool i2sMuxGetBit(uint8_t slot); +#endif +#define DRIVER_DONT_CARE FasDriver::DONT_CARE + StepperMotion* stepperConnectToPin( + uint8_t step_pin, FasDriver driver_type = DRIVER_DONT_CARE); +#else + StepperMotion* stepperConnectToPin(uint8_t step_pin); +#endif + + // Comments to valid pins: + // + // clang-format off + // | Device | Comment | + // |:----------------|:--------------------------------------------------------------------------------------------------| + // | ESP32 | Every output capable GPIO can be used | + // | ESP32S2 | Every output capable GPIO can be used | + // | Atmega168/328/p | Only the pins connected to OC1A and OC1B are allowed | + // | Atmega2560 | Only the pins connected to OC4A, OC4B and OC4C are allowed. | + // | Atmega32u4 | Only the pins connected to OC1A, OC1B and OC1C are allowed | + // | Atmel SAM | This can be one of each group of pins: 34/67/74/35, 17/36/72/37/42, 40/64/69/41, 9, 8/44, 7/45, 6 | + // clang-format on + +#if defined(SUPPORT_TASK_RATE_CHANGE) + // For e.g. esp32 the repetition rate of the stepper task can be changed. + // The default delay is 4ms. + // + // The steppertask is looping with: + // manageSteppers() + // wdt_reset() + // delay() + // + // The actual repetition rate of the stepper task is delay + execution time of + // manageSteppers() + // + // This function is primary of interest in conjunction with + // setForwardPlanningTimeInMs(). If the delay is larger then forward planning + // time, then the stepper queue will always run out of commands, which lead to + // a sudden stop of the motor. If the delay is 0, then the stepper task will + // constantly looping, which may lead to the task blocking other tasks. + // Consequently, this function is intended for advanced users. + // + // There is not planned to test this functionality, because automatic testing + // is only available for avr devices and those continue to use fixed 4ms rate. + // + // Please be aware, that the configured tick rate aka portTICK_PERIOD_MS is + // relevant. Apparently, arduino-esp32 has FreeRTOS configured to have a + // tick-rate of 1000Hz + inline void task_rate(uint8_t delay_ms) { _delay_ms = delay_ms; }; + inline uint8_t _task_rate() const { return _delay_ms; }; + + private: + uint8_t _delay_ms; + + public: +#endif + + // ## External Pins + // + // If the direction/enable pins are e.g. connected via external HW (shift + // registers), then an external callback function can be supplied. The + // supplied value is either LOW or HIGH. The return value shall be the status + // of the pin (false for LOW or true for HIGH). If returned value and supplied + // value do not match, the stepper does not continue, but calls this function + // again. + // + // This function is called from cyclic task/interrupt with 4ms rate, which + // creates the commands to put into the command queue. Thus the supplied + // function should take much less time than 4ms. Otherwise there is risk, that + // other running steppers are running out of commands in the queue. If this + // takes longer, then the function should be offloaded and return the new + // status, after the pin change has been successfully completed. + // + // The callback has to be called on the StepperMotionEngine. + // See examples/ExternalCall + // + // Stepperpins (enable or direction), which should use this external callback, + // need to be or'ed with PIN_EXTERNAL_FLAG ! StepperMotion uses this flag + // to determine, if a pin is external or internal. + void setExternalCallForPin(bool (*func)(uint8_t pin, uint8_t value)); + + // ### Debug LED + // + // If blinking of a LED is required to indicate, the stepper controller is + // still running, then the port. to which the LED is connected, can be told to + // the engine. The periodic task will let the associated LED blink with 1 Hz + static void setDebugLed(uint8_t ledPin); + + /* This should be only called from ISR or stepper task. So do not call it */ + void manageSteppers(); + + // ### Synchronized start + // + // Starts the queues of the steppers in steppers[] in one engine operation, + // so their first command starts on one event. The implementation lives in + // the pd_*/pd_*.cpp file of the build, so the platform decides how. + // A stepper already running is skipped; an empty queue does not stop the + // others. + // Returns AqeResultCode::OK or the first non-OK code of a per-stepper + // addQueueEntry(NULL, true) call. + AqeResultCode synchronizedStart(StepperMotion** const steppers, + uint8_t cnt); + + private: + bool isDirPinBusy(uint8_t dirPin, uint8_t except_stepper); + + uint8_t _stepper_cnt; + StepperMotion* _stepper[MAX_STEPPER]; + + bool (*_externalCallForPin)(uint8_t pin, uint8_t value); + + friend class StepperMotion; +}; + +#endif diff --git a/src/StepperMotion_idf4_esp32_pcnt.cpp b/src/StepperMotion_idf4_esp32_pcnt.cpp new file mode 100644 index 0000000..185d498 --- /dev/null +++ b/src/StepperMotion_idf4_esp32_pcnt.cpp @@ -0,0 +1,103 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 4) + +uint32_t sig_idx[SUPPORT_ESP32_PULSE_COUNTER] = { + PCNT_SIG_CH0_IN0_IDX, PCNT_SIG_CH0_IN1_IDX, + PCNT_SIG_CH0_IN2_IDX, PCNT_SIG_CH0_IN3_IDX, +#if SUPPORT_ESP32_PULSE_COUNTER == 8 + PCNT_SIG_CH0_IN4_IDX, PCNT_SIG_CH0_IN5_IDX, + PCNT_SIG_CH0_IN6_IDX, PCNT_SIG_CH0_IN7_IDX, +#endif +}; +uint32_t ctrl_idx[SUPPORT_ESP32_PULSE_COUNTER] = { + PCNT_CTRL_CH0_IN0_IDX, PCNT_CTRL_CH0_IN1_IDX, PCNT_CTRL_CH0_IN2_IDX, + PCNT_CTRL_CH0_IN3_IDX, +#if SUPPORT_ESP32_PULSE_COUNTER == 8 + PCNT_CTRL_CH0_IN4_IDX, PCNT_CTRL_CH0_IN5_IDX, PCNT_CTRL_CH0_IN6_IDX, + PCNT_CTRL_CH0_IN7_IDX +#endif +}; + +bool StepperMotion::attachToPulseCounter(uint8_t pcnt_unit, + int16_t low_value, + int16_t high_value, uint8_t dir_pin, + bool invert_step_pulse) { + if (pcnt_unit >= SUPPORT_ESP32_PULSE_COUNTER) { + return false; + } + + pcnt_config_t cfg; + uint8_t step_pin = getStepPin(); + if (dir_pin == PIN_UNDEFINED) { + dir_pin = getDirectionPin(); + } + cfg.pulse_gpio_num = PCNT_PIN_NOT_USED; + if (dir_pin == PIN_UNDEFINED || (dir_pin & PIN_EXTERNAL_FLAG) != 0) { + cfg.ctrl_gpio_num = PCNT_PIN_NOT_USED; + cfg.hctrl_mode = PCNT_MODE_KEEP; + cfg.lctrl_mode = PCNT_MODE_KEEP; + } else { + cfg.ctrl_gpio_num = dir_pin; + if (directionPinHighCountsUp()) { + cfg.lctrl_mode = PCNT_MODE_REVERSE; + cfg.hctrl_mode = PCNT_MODE_KEEP; + } else { + cfg.lctrl_mode = PCNT_MODE_KEEP; + cfg.hctrl_mode = PCNT_MODE_REVERSE; + } + } + if (invert_step_pulse) { + cfg.pos_mode = PCNT_COUNT_DIS; + cfg.neg_mode = PCNT_COUNT_INC; + } else { + cfg.pos_mode = PCNT_COUNT_INC; + cfg.neg_mode = PCNT_COUNT_DIS; + } + cfg.counter_h_lim = high_value; + cfg.counter_l_lim = low_value; + cfg.unit = (pcnt_unit_t)pcnt_unit; + cfg.channel = PCNT_CHANNEL_0; + pcnt_unit_config(&cfg); + +#ifndef HAVE_ESP32S3_PULSE_COUNTER + PCNT.conf_unit[cfg.unit].conf0.thr_h_lim_en = 0; + PCNT.conf_unit[cfg.unit].conf0.thr_l_lim_en = 0; +#else + PCNT.conf_unit[cfg.unit].conf0.thr_h_lim_en_un = 0; + PCNT.conf_unit[cfg.unit].conf0.thr_l_lim_en_un = 0; +#endif + + // detachFromPin(); + // reAttachToPin(); + gpio_matrix_in(step_pin, sig_idx[pcnt_unit], 0); + gpio_iomux_in(step_pin, + sig_idx[pcnt_unit]); // test failure without this call + if (dir_pin != PIN_UNDEFINED && (dir_pin & PIN_EXTERNAL_FLAG) == 0) { + pinMode(dir_pin, OUTPUT); + gpio_matrix_out(dir_pin, 0x100, false, false); + gpio_matrix_in(dir_pin, ctrl_idx[pcnt_unit], 0); + gpio_iomux_in(dir_pin, ctrl_idx[pcnt_unit]); + } + + pcnt_counter_clear(cfg.unit); + pcnt_counter_resume(cfg.unit); + + _attached_pulse_cnt_unit = pcnt_unit; + return true; +} +void StepperMotion::clearPulseCounter() { + if (pulseCounterAttached()) { + pcnt_counter_clear((pcnt_unit_t)_attached_pulse_cnt_unit); + } +} +int16_t StepperMotion::readPulseCounter() { + if (pulseCounterAttached()) { +#ifndef HAVE_ESP32S3_PULSE_COUNTER + return PCNT.cnt_unit[(pcnt_unit_t)_attached_pulse_cnt_unit].cnt_val; +#else + return PCNT.cnt_unit[(pcnt_unit_t)_attached_pulse_cnt_unit].pulse_cnt_un; +#endif + } + return 0; +} +#endif diff --git a/src/StepperMotion_idf5_esp32_pcnt.cpp b/src/StepperMotion_idf5_esp32_pcnt.cpp new file mode 100644 index 0000000..5744ff1 --- /dev/null +++ b/src/StepperMotion_idf5_esp32_pcnt.cpp @@ -0,0 +1,165 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 5) + +// pcnt_new_channel() with a real GPIO still calls gpio_config() on that pin +// (input + pull-up, output off). Step and dir pins are already driven by +// RMT/MCPWM/GPIO; that drop of output routing stops the pulse driver. +// Channel is created with virtual IOs, then only input is appended via the +// GPIO matrix (same approach as the MCPWM/PCNT driver, without touching +// func_out_sel). + +struct pcnt_unit_t { + /*pcnt_group_t*/ void* group; + portMUX_TYPE spinlock; + int unit_id; +}; + +struct pcnt_chan_t { + pcnt_unit_t* unit; + int channel_id; +}; + +static void pcnt_listen_on_output_pin(int gpio_num, int signal_idx) { + gpio_ll_input_enable(&GPIO, (gpio_num_t)gpio_num); + esp_rom_gpio_connect_in_signal((uint32_t)gpio_num, (uint32_t)signal_idx, + false); +} + +static void pcnt_abort_attach(pcnt_channel_handle_t chan, + pcnt_unit_handle_t unit, bool enabled) { + if (enabled) { + pcnt_unit_disable(unit); + } + if (chan) { + pcnt_del_channel(chan); + } + if (unit) { + pcnt_del_unit(unit); + } +} + +bool StepperMotion::attachToPulseCounter(uint8_t unused_pcnt_unit, + int16_t low_value, + int16_t high_value, uint8_t dir_pin, + bool invert_step_pulse) { + (void)unused_pcnt_unit; + + int low_limit = low_value; + int high_limit = high_value; + if ((low_limit == 0) && (high_limit == 0)) { + low_limit = -32768; + high_limit = 32767; + } + + pcnt_unit_config_t config = {.low_limit = low_limit, + .high_limit = high_limit, + .intr_priority = 0, + .flags = {.accum_count = 0}}; + pcnt_unit_handle_t punit = NULL; + if (pcnt_new_unit(&config, &punit) != ESP_OK) { + return false; + } + + pcnt_chan_config_t chan_config = {.edge_gpio_num = -1, + .level_gpio_num = -1, + .flags = { + .invert_edge_input = 0, + .invert_level_input = 0, + .virt_edge_io_level = 0, + .virt_level_io_level = 0, + .io_loop_back = 0, + }}; + + pcnt_channel_level_action_t level_high = PCNT_CHANNEL_LEVEL_ACTION_KEEP; + pcnt_channel_level_action_t level_low = PCNT_CHANNEL_LEVEL_ACTION_KEEP; + + if (dir_pin == PIN_UNDEFINED) { + dir_pin = getDirectionPin(); + } + bool use_dir = + (dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0); + if (use_dir) { + if (directionPinHighCountsUp()) { + level_low = PCNT_CHANNEL_LEVEL_ACTION_INVERSE; + } else { + level_high = PCNT_CHANNEL_LEVEL_ACTION_INVERSE; + } + } + + pcnt_channel_handle_t pcnt_chan = NULL; + if (pcnt_new_channel(punit, &chan_config, &pcnt_chan) != ESP_OK) { + pcnt_abort_attach(NULL, punit, false); + return false; + } + + int unit_id = punit->unit_id; + int channel_id = pcnt_chan->channel_id; + if ((unit_id < 0) || (unit_id >= SUPPORT_ESP32_PULSE_COUNTER) || + (channel_id < 0) || (channel_id >= 2)) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + + pcnt_channel_edge_action_t pos_action = PCNT_CHANNEL_EDGE_ACTION_INCREASE; + pcnt_channel_edge_action_t neg_action = PCNT_CHANNEL_EDGE_ACTION_HOLD; + if (invert_step_pulse) { + pos_action = PCNT_CHANNEL_EDGE_ACTION_HOLD; + neg_action = PCNT_CHANNEL_EDGE_ACTION_INCREASE; + } + if (pcnt_channel_set_edge_action(pcnt_chan, pos_action, neg_action) != + ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + if (pcnt_channel_set_level_action(pcnt_chan, level_high, level_low) != + ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + + uint8_t step_pin = getStepPin(); + int pulse_sig = pcnt_periph_signals.groups[0] + .units[unit_id] + .channels[channel_id] + .pulse_sig; + pcnt_listen_on_output_pin(step_pin, pulse_sig); + if (use_dir) { + int control_sig = pcnt_periph_signals.groups[0] + .units[unit_id] + .channels[channel_id] + .control_sig; + pcnt_listen_on_output_pin(dir_pin, control_sig); + } + + if (pcnt_unit_enable(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + if (pcnt_unit_clear_count(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, true); + return false; + } + if (pcnt_unit_start(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, true); + return false; + } + + _attached_pulse_unit = punit; + return true; +} + +void StepperMotion::clearPulseCounter() { + if (pulseCounterAttached()) { + pcnt_unit_clear_count(_attached_pulse_unit); + } +} + +int16_t StepperMotion::readPulseCounter() { + int value = 0; + if (pulseCounterAttached()) { + pcnt_unit_get_count(_attached_pulse_unit, &value); + } + return value; +} + +#endif diff --git a/src/StepperMotion_idf6_esp32_pcnt.cpp b/src/StepperMotion_idf6_esp32_pcnt.cpp new file mode 100644 index 0000000..ad0414c --- /dev/null +++ b/src/StepperMotion_idf6_esp32_pcnt.cpp @@ -0,0 +1,159 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_PULSE_COUNTER) && (ESP_IDF_VERSION_MAJOR == 6) + +// pcnt_new_channel() with a real GPIO still calls gpio_func_sel() on that pin. +// Step and dir pins are already driven by RMT/MCPWM/GPIO; overwriting pad +// config (gpio_set_direction, gpio_config, gpio_reset_pin, pinMode, +// gpio_iomux_input, gpio_output_enable) drops the output routing and the +// pulse driver stops. Channel is created with virtual IOs, then only input +// is appended via the GPIO matrix. + +struct pcnt_unit_t { + /*pcnt_group_t*/ void* group; + portMUX_TYPE spinlock; + int unit_id; +}; + +struct pcnt_chan_t { + pcnt_unit_t* unit; + int channel_id; +}; + +static void pcnt_listen_on_output_pin(int gpio_num, int signal_idx) { + gpio_input_enable((gpio_num_t)gpio_num); + esp_rom_gpio_connect_in_signal((uint32_t)gpio_num, (uint32_t)signal_idx, + false); +} + +static void pcnt_abort_attach(pcnt_channel_handle_t chan, + pcnt_unit_handle_t unit, bool enabled) { + if (enabled) { + pcnt_unit_disable(unit); + } + if (chan) { + pcnt_del_channel(chan); + } + if (unit) { + pcnt_del_unit(unit); + } +} + +bool StepperMotion::attachToPulseCounter(uint8_t unused_pcnt_unit, + int16_t low_value, + int16_t high_value, uint8_t dir_pin, + bool invert_step_pulse) { + (void)unused_pcnt_unit; + + int low_limit = low_value; + int high_limit = high_value; + if ((low_limit == 0) && (high_limit == 0)) { + low_limit = -32768; + high_limit = 32767; + } + + pcnt_unit_config_t config = {}; + config.clk_src = PCNT_CLK_SRC_DEFAULT; + config.low_limit = low_limit; + config.high_limit = high_limit; + pcnt_unit_handle_t punit = NULL; + if (pcnt_new_unit(&config, &punit) != ESP_OK) { + return false; + } + + pcnt_chan_config_t chan_config = {}; + chan_config.edge_gpio_num = -1; + chan_config.level_gpio_num = -1; + + pcnt_channel_level_action_t level_high = PCNT_CHANNEL_LEVEL_ACTION_KEEP; + pcnt_channel_level_action_t level_low = PCNT_CHANNEL_LEVEL_ACTION_KEEP; + + if (dir_pin == PIN_UNDEFINED) { + dir_pin = getDirectionPin(); + } + bool use_dir = + (dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0); + if (use_dir) { + if (directionPinHighCountsUp()) { + level_low = PCNT_CHANNEL_LEVEL_ACTION_INVERSE; + } else { + level_high = PCNT_CHANNEL_LEVEL_ACTION_INVERSE; + } + } + + pcnt_channel_handle_t pcnt_chan = NULL; + if (pcnt_new_channel(punit, &chan_config, &pcnt_chan) != ESP_OK) { + pcnt_abort_attach(NULL, punit, false); + return false; + } + + int unit_id = punit->unit_id; + int channel_id = pcnt_chan->channel_id; + if ((unit_id < 0) || (unit_id >= SUPPORT_ESP32_PULSE_COUNTER) || + (channel_id < 0) || (channel_id >= 2)) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + + pcnt_channel_edge_action_t pos_action = PCNT_CHANNEL_EDGE_ACTION_INCREASE; + pcnt_channel_edge_action_t neg_action = PCNT_CHANNEL_EDGE_ACTION_HOLD; + if (invert_step_pulse) { + pos_action = PCNT_CHANNEL_EDGE_ACTION_HOLD; + neg_action = PCNT_CHANNEL_EDGE_ACTION_INCREASE; + } + if (pcnt_channel_set_edge_action(pcnt_chan, pos_action, neg_action) != + ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + if (pcnt_channel_set_level_action(pcnt_chan, level_high, level_low) != + ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + + uint8_t step_pin = getStepPin(); + int pulse_sig = soc_pcnt_signals[0] + .units[unit_id] + .channels[channel_id] + .pulse_sig_id_matrix; + pcnt_listen_on_output_pin(step_pin, pulse_sig); + if (use_dir) { + int control_sig = soc_pcnt_signals[0] + .units[unit_id] + .channels[channel_id] + .ctl_sig_id_matrix; + pcnt_listen_on_output_pin(dir_pin, control_sig); + } + + if (pcnt_unit_enable(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, false); + return false; + } + if (pcnt_unit_clear_count(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, true); + return false; + } + if (pcnt_unit_start(punit) != ESP_OK) { + pcnt_abort_attach(pcnt_chan, punit, true); + return false; + } + + _attached_pulse_unit = punit; + return true; +} + +void StepperMotion::clearPulseCounter() { + if (pulseCounterAttached()) { + pcnt_unit_clear_count(_attached_pulse_unit); + } +} + +int16_t StepperMotion::readPulseCounter() { + int value = 0; + if (pulseCounterAttached()) { + pcnt_unit_get_count(_attached_pulse_unit, &value); + } + return value; +} + +#endif diff --git a/src/fas_arch/arduino_avr.h b/src/fas_arch/arduino_avr.h new file mode 100644 index 0000000..60ed819 --- /dev/null +++ b/src/fas_arch/arduino_avr.h @@ -0,0 +1,17 @@ +#ifndef FAS_ARCH_ARDUINO_AVR_H +#define FAS_ARCH_ARDUINO_AVR_H + +#define SUPPORT_AVR + +// this is an arduino platform, so include the Arduino.h header file +#include + +#include "AVRStepperPins.h" +// for AVR processors a reentrant version of disabling/enabling interrupts is +// used +#define fasDisableInterrupts() \ + uint8_t prevSREG = SREG; \ + cli() +#define fasEnableInterrupts() SREG = prevSREG + +#endif /* FAS_ARCH_ARDUINO_AVR_H */ diff --git a/src/fas_arch/arduino_esp32.h b/src/fas_arch/arduino_esp32.h new file mode 100644 index 0000000..691b119 --- /dev/null +++ b/src/fas_arch/arduino_esp32.h @@ -0,0 +1,13 @@ +#ifndef FAS_ARCH_ARDUINO_ESP32_H +#define FAS_ARCH_ARDUINO_ESP32_H + +// this is an arduino platform, so include the Arduino.h header file +#include + +// For esp32 using arduino, just use arduino definition +#define fasEnableInterrupts interrupts +#define fasDisableInterrupts noInterrupts + +#include "fas_arch/common_esp32.h" + +#endif /* FAS_ARCH_ARDUINO_ESP32_H */ diff --git a/src/fas_arch/arduino_rp_pico.h b/src/fas_arch/arduino_rp_pico.h new file mode 100644 index 0000000..7b4b1df --- /dev/null +++ b/src/fas_arch/arduino_rp_pico.h @@ -0,0 +1,13 @@ +#ifndef FAS_ARCH_ARDUINO_RP_PICO_H +#define FAS_ARCH_ARDUINO_RP_PICO_H + +// this is an arduino platform, so include the Arduino.h header file +#include + +// For pico using arduino, just use arduino definition +#define fasEnableInterrupts interrupts +#define fasDisableInterrupts noInterrupts + +#include "fas_arch/common_rp_pico.h" + +#endif /* FAS_ARCH_ARDUINO_RP_PICO_H */ diff --git a/src/fas_arch/arduino_sam.h b/src/fas_arch/arduino_sam.h new file mode 100644 index 0000000..0b29cf8 --- /dev/null +++ b/src/fas_arch/arduino_sam.h @@ -0,0 +1,12 @@ +#ifndef FAS_ARCH_ARDUINO_SAM_H +#define FAS_ARCH_ARDUINO_SAM_H + +#define SUPPORT_SAM + +// this is an arduino platform, so include the Arduino.h header file +#include +// on SAM just use the arduino macros +#define fasEnableInterrupts interrupts +#define fasDisableInterrupts noInterrupts + +#endif /* FAS_ARCH_ARDUINO_SAM_H */ diff --git a/src/fas_arch/arduino_samd.h b/src/fas_arch/arduino_samd.h new file mode 100644 index 0000000..0b7acf3 --- /dev/null +++ b/src/fas_arch/arduino_samd.h @@ -0,0 +1,15 @@ +#ifndef FAS_ARCH_ARDUINO_SAMD_H +#define FAS_ARCH_ARDUINO_SAMD_H + +// SAMD51 only. SAMD21 differs in TCC clocking/sync and instance count and is +// not implemented (see fas_arch/common.h dispatch). +#define SUPPORT_SAMD51 + +// this is an arduino platform, so include the Arduino.h header file +#include + +// on SAMD just use the arduino macros +#define fasEnableInterrupts interrupts +#define fasDisableInterrupts noInterrupts + +#endif /* FAS_ARCH_ARDUINO_SAMD_H */ diff --git a/src/fas_arch/arduino_teensy.h b/src/fas_arch/arduino_teensy.h new file mode 100644 index 0000000..bad5aae --- /dev/null +++ b/src/fas_arch/arduino_teensy.h @@ -0,0 +1,14 @@ +#ifndef FAS_ARCH_ARDUINO_TEENSY_H +#define FAS_ARCH_ARDUINO_TEENSY_H + +// Teensy 4.0/4.1 (i.MX RT1062, ARM Cortex-M7), via Teensyduino. +// EXPERIMENTAL - see pd_teensy/pd_config.h and pd_teensy/teensy_queue.cpp. +#define SUPPORT_TEENSY4 + +// this is an arduino platform, so include the Arduino.h header file +#include + +#define fasEnableInterrupts interrupts +#define fasDisableInterrupts noInterrupts + +#endif /* FAS_ARCH_ARDUINO_TEENSY_H */ diff --git a/src/fas_arch/common.h b/src/fas_arch/common.h new file mode 100644 index 0000000..8416f50 --- /dev/null +++ b/src/fas_arch/common.h @@ -0,0 +1,130 @@ +#ifndef FAS_COMMON_H +#define FAS_COMMON_H + +#include "fas_arch/result_codes.h" + +#define TICKS_FOR_STOPPED_MOTOR 0xffffffff + +// Low level stepper motor command. +// +// You can add these using the addQueueEntry method. +// They will be executed sequentially until the queue is empty. +// +// There are some constraints on the values: +// - `ticks` must be greater or equal to StepperMotion::getMaxSpeedInTicks. +// - `ticks*steps` must be greater or equal to MIN_CMD_TICKS +// +// For example: +// A command with ticks=TICKS_PER_S/1000, steps = 3, count_up = true means that: +// 1. The direction pin is set to HIGH. +// 2. One step is generated. +// 3. Exactly 1 ms after the first step, the second step is issued. +// 4. Exactly 1 ms after the second step, the third step is issued. +// 5. The stepper waits for 1 ms. +// 6. The next command is processed. +struct stepper_command_s { + // Number of ticks between each step. + // There are `TICKS_PER_S` ticks per second. This may vary between different + // platforms. + uint16_t ticks; + + // Number of steps to send to the stepper motor during this command. + // If zero, then this command will be treated as a pause, lasting for a number + // of ticks given by `ticks`. + uint8_t steps; + + // True if the direction pin should be high during this command, false if it + // should be low. + bool count_up; +}; + +struct actual_ticks_s { + uint32_t ticks; // ticks == 0 means standstill + bool count_up; +}; + +// I doubt, volatile is needed. +struct queue_end_s { + volatile int32_t pos; + bool count_up : 1; + bool dir : 1; +}; + +// use own min/max/abs function, because the lib versions are messed up +#define fas_min(a, b) ((a) > (b) ? (b) : (a)) +#define fas_max(a, b) ((a) > (b) ? (a) : (b)) +#define fas_abs(x) ((x) >= 0 ? (x) : (-x)) + +//============================================================================== +// All architecture specific definitions should be located here +//============================================================================== + +//========================================================================== +#if defined(TEST) +// TEST "architecture" is in use with pc_based testing. +#include "fas_arch/test_pc.h" +#include "pd_test/pd_config.h" + +#elif defined(ARDUINO_ARCH_ESP32) +// ESP32 derivates using arduino core +#include "fas_arch/arduino_esp32.h" +#include "pd_esp32/pd_config.h" + +#elif defined(ESP_PLATFORM) +// ESP32 derivates using espidf +#include "fas_arch/espidf_esp32.h" +#include "pd_esp32/pd_config.h" + +#elif defined(__IMXRT1062__) +// Teensy 4.0/4.1, via Teensyduino. EXPERIMENTAL - see pd_teensy/pd_config.h. +#include "fas_arch/arduino_teensy.h" +#include "pd_teensy/pd_config.h" + +#elif defined(ARDUINO_ARCH_SAM) +// SAM-architecture +#include "fas_arch/arduino_sam.h" +#include "pd_sam/pd_config.h" + +#elif defined(ARDUINO_ARCH_SAMD) +// SAMD-architecture (Microchip SAMD51 only) +#if defined(__SAMD51__) +#include "fas_arch/arduino_samd.h" +#include "pd_samd/pd_config.h" +#else +#error "Only SAMD51 is supported on the SAMD architecture (no SAMD21 yet)" +#endif + +#elif defined(ARDUINO_ARCH_AVR) +// AVR family +#include "fas_arch/arduino_avr.h" +#include "pd_avr/pd_config.h" + +#elif defined(PICO_SDK_RP2350) +#include "fas_arch/pico_sdk_rp_pico.h" +#include "pd_pico/pd_config.h" + +#elif defined(PICO_RP2040) || defined(PICO_RP2350) +// Raspberry Pico and Pico 2 +#include "fas_arch/arduino_rp_pico.h" +#include "pd_pico/pd_config.h" + +#else +#error "Unsupported devices" +#endif + +// in order to avoid spikes, first set the value and then make an output +// esp32 idf5 does not like this approach +#ifndef PIN_OUTPUT +#define PIN_OUTPUT(pin, value) \ + { \ + digitalWrite(pin, (value)); \ + pinMode(pin, OUTPUT); \ + } +#endif + +// disable inject_fill_interrupt() for all real devices. Only defined in TEST +#ifndef TEST +#define inject_fill_interrupt(x) +#endif + +#endif /* FAS_COMMON_H */ diff --git a/src/fas_arch/common_esp32.h b/src/fas_arch/common_esp32.h new file mode 100644 index 0000000..3cb0869 --- /dev/null +++ b/src/fas_arch/common_esp32.h @@ -0,0 +1,10 @@ +#ifndef FAS_ARCH_COMMON_ESP32_H +#define FAS_ARCH_COMMON_ESP32_H + +#include + +#define SUPPORT_ESP32 + +#include + +#endif /* FAS_ARCH_COMMON_ESP32_H */ diff --git a/src/fas_arch/common_rp_pico.h b/src/fas_arch/common_rp_pico.h new file mode 100644 index 0000000..e99d6b7 --- /dev/null +++ b/src/fas_arch/common_rp_pico.h @@ -0,0 +1,6 @@ +#ifndef FAS_ARCH_COMMON_RP_PICO_H +#define FAS_ARCH_COMMON_RP_PICO_H + +#define SUPPORT_RP_PICO + +#endif /* FAS_ARCH_COMMON_RP_PICO_H */ diff --git a/src/fas_arch/espidf_esp32.h b/src/fas_arch/espidf_esp32.h new file mode 100644 index 0000000..e34e822 --- /dev/null +++ b/src/fas_arch/espidf_esp32.h @@ -0,0 +1,26 @@ +#ifndef FAS_ARCH_ESPIDF_ESP32_H +#define FAS_ARCH_ESPIDF_ESP32_H + +// esp32 specific includes +#include + +// on espidf need to use portDISABLE/ENABLE_INTERRUPTS +#include +#include +#define fasDisableInterrupts portDISABLE_INTERRUPTS +#define fasEnableInterrupts portENABLE_INTERRUPTS + +// The espidf-platform needs a couple of arduino like definitions +#define LOW 0 +#define HIGH 1 +#define OUTPUT GPIO_MODE_OUTPUT +#define pinMode(pin, mode) \ + gpio_set_direction((gpio_num_t)pin, (mode) == OUTPUT \ + ? GPIO_MODE_INPUT_OUTPUT \ + : GPIO_MODE_INPUT) +#define digitalWrite(pin, level) gpio_set_level((gpio_num_t)pin, level) +#define digitalRead(pin) gpio_get_level((gpio_num_t)pin) + +#include "fas_arch/common_esp32.h" + +#endif /* FAS_ARCH_ESPIDF_ESP32_H */ diff --git a/src/fas_arch/pico_sdk_rp_pico.h b/src/fas_arch/pico_sdk_rp_pico.h new file mode 100644 index 0000000..1da3242 --- /dev/null +++ b/src/fas_arch/pico_sdk_rp_pico.h @@ -0,0 +1,23 @@ +#ifndef FAS_ARCH_PICO_SDK_RP_PICO_H +#define FAS_ARCH_PICO_SDK_RP_PICO_H + +#include "hardware/sync.h" + +// For pico using arduino, just use arduino definition +#define fasEnableInterrupts portEXIT_CRITICAL +#define fasDisableInterrupts portENTER_CRITICAL + +#define digitalWrite gpio_put +#define HIGH true +#define LOW false + +#define PIN_OUTPUT(pin, value) \ + { \ + gpio_init(pin); \ + gpio_put(pin, (value)); \ + gpio_set_dir(pin, GPIO_OUT); \ + } + +#include "fas_arch/common_rp_pico.h" + +#endif /* FAS_ARCH_PICO_SDK_RP_PICO_H */ diff --git a/src/fas_arch/result_codes.h b/src/fas_arch/result_codes.h new file mode 100644 index 0000000..e7e2762 --- /dev/null +++ b/src/fas_arch/result_codes.h @@ -0,0 +1,229 @@ +#ifndef FAS_RESULT_CODES_H +#define FAS_RESULT_CODES_H + +#include + +#if defined(__AVR__) +#include +#define FAS_PSTR(s) (reinterpret_cast(PSTR(s))) +#else +#define FAS_PSTR(s) (s) +#endif + +// Cause of a stop, for a planner that co-drives the same queue. Set by +// StepperMotion::stopMove()/forceStop()/forceStopAndNewPosition() and +// read-and-cleared via StepperMotion::takeStopCause(). A duck-typed n-axis planner +// and the test SimPort can name the type without including StepperMotion.h. +enum class StepperStopCause : uint8_t { + None = 0, + StopMove = 1, + ForceStop = 2, + ForceStopAndNewPosition = 3, +}; + +// ### Result codes for addQueueEntry() function of StepperMotion +enum class AqeResultCode : int8_t { + OK = 0, + QueueFull = 1, + DirPinIsBusy = 2, + WaitForEnablePinActive = 3, + DeviceNotReady = 4, + DirPin2msPauseAdded = 5, + DirChangePauseInjected = 6, + ErrorTicksTooLow = -1, + ErrorEmptyQueueToStart = -2, + ErrorNoDirPinToToggle = -3, + // The command-admission latch is set (queue_add_entry.cpp, ignore_commands). + // A forceStop() / forceStopAndNewPosition() sets it; only resumeCommands() + // clears it. MUST stay -5: MoveTimedResultCode::ErrorMoveTooLarge occupies + // -4 and tmrFrom() is a value-preserving cast, so -4 here would report a + // suspended queue as MOVE_TIMED_TOO_LARGE_ERROR. + ErrorCommandsSuspended = -5 +}; + +static inline bool aqeRetry(AqeResultCode code) { + return (static_cast(code)) > 0; +} +static inline bool aqeRetryImmediately(AqeResultCode code) { + return code == AqeResultCode::DirChangePauseInjected; +} +static inline bool aqeIsOk(AqeResultCode status) { + return status == AqeResultCode::OK; +} +static inline bool aqeIsPauseInjected(AqeResultCode code) { + return (code == AqeResultCode::DirPin2msPauseAdded) || + (code == AqeResultCode::DirChangePauseInjected); +} + +static inline const char* toString(AqeResultCode code) { + switch (code) { + case AqeResultCode::OK: + return FAS_PSTR("OK"); + case AqeResultCode::QueueFull: + return FAS_PSTR("Queue Full"); + case AqeResultCode::DirPin2msPauseAdded: + return FAS_PSTR("Dir Pin 2ms Pause Added"); + case AqeResultCode::DirChangePauseInjected: + return FAS_PSTR("Dir Change Pause Injected"); + case AqeResultCode::DirPinIsBusy: + return FAS_PSTR("Direction Pin is Busy"); + case AqeResultCode::WaitForEnablePinActive: + return FAS_PSTR("Waiting for Enable Pin Active"); + case AqeResultCode::DeviceNotReady: + return FAS_PSTR("Device Not Ready"); + case AqeResultCode::ErrorTicksTooLow: + return FAS_PSTR("Error: Ticks Too Low"); + case AqeResultCode::ErrorEmptyQueueToStart: + return FAS_PSTR("Error: Empty Queue to Start"); + case AqeResultCode::ErrorNoDirPinToToggle: + return FAS_PSTR("Error: No Direction Pin to Toggle"); + case AqeResultCode::ErrorCommandsSuspended: + return FAS_PSTR("Error: Commands Suspended"); + default: + return FAS_PSTR("Unknown Error"); + } +} +#define AQE_OK AqeResultCode::OK +#define AQE_QUEUE_FULL AqeResultCode::QueueFull +#define AQE_DIR_PIN_2MS_PAUSE_ADDED AqeResultCode::DirPin2msPauseAdded +#define AQE_DIR_CHANGE_PAUSE_INJECTED AqeResultCode::DirChangePauseInjected +#define AQE_DIR_PIN_IS_BUSY AqeResultCode::DirPinIsBusy +#define AQE_WAIT_FOR_ENABLE_PIN_ACTIVE AqeResultCode::WaitForEnablePinActive +#define AQE_DEVICE_NOT_READY AqeResultCode::DeviceNotReady +#define AQE_ERROR_TICKS_TOO_LOW AqeResultCode::ErrorTicksTooLow +#define AQE_ERROR_EMPTY_QUEUE_TO_START AqeResultCode::ErrorEmptyQueueToStart +#define AQE_ERROR_NO_DIR_PIN_TO_TOGGLE AqeResultCode::ErrorNoDirPinToToggle +#define AQE_ERROR_COMMANDS_SUSPENDED AqeResultCode::ErrorCommandsSuspended + +// Define the MoveResultCode enum with equivalent values +enum class MoveResultCode : int8_t { + OK = 0, + ErrorNoDirectionPin = -1, // Equivalent to MOVE_ERR_NO_DIRECTION_PIN + ErrorSpeedIsUndefined = -2, // Equivalent to MOVE_ERR_SPEED_IS_UNDEFINED + ErrorAccelerationIsUndefined = + -3 // Equivalent to MOVE_ERR_ACCELERATION_IS_UNDEFINED +}; + +static inline bool moveIsOk(MoveResultCode status) { + return status == MoveResultCode::OK; +} + +static inline const char* toString(MoveResultCode code) { + switch (code) { + case MoveResultCode::OK: + return toString(AqeResultCode::OK); + case MoveResultCode::ErrorNoDirectionPin: + return FAS_PSTR("Error: No Direction Pin"); + case MoveResultCode::ErrorSpeedIsUndefined: + return FAS_PSTR("Error: Speed is Undefined"); + case MoveResultCode::ErrorAccelerationIsUndefined: + return FAS_PSTR("Error: Acceleration is Undefined"); + default: + return FAS_PSTR("Unknown Error"); + } +} + +// Macros for easier access to enum values +#define MOVE_OK MoveResultCode::OK +#define MOVE_ERR_NO_DIRECTION_PIN MoveResultCode::ErrorNoDirectionPin +#define MOVE_ERR_SPEED_IS_UNDEFINED MoveResultCode::ErrorSpeedIsUndefined +#define MOVE_ERR_ACCELERATION_IS_UNDEFINED \ + MoveResultCode::ErrorAccelerationIsUndefined + +// MoveTimedResultCode values 0..6 mirror AqeResultCode so that tmrFrom() is a +// value-preserving cast; MoveBusy/MoveEmpty sit above the AQE range to avoid +// aliasing AqeResultCode::DirChangePauseInjected. Every negative AqeResultCode +// needs its mirror entry here for the same reason: AqeResultCode reserves -4 +// for nothing, but ErrorCommandsSuspended is -5 precisely because +// ErrorMoveTooLarge (-4) already sits in this enum, and a -4 AqeResultCode +// would cast to MOVE_TIMED_TOO_LARGE_ERROR. +enum class MoveTimedResultCode : int8_t { + OK = 0, + QueueFull = 1, + DirPinIsBusy = 2, + WaitForEnablePinActive = 3, + DeviceNotReady = 4, + DirPin2msPauseAdded = 5, + DirChangePauseInjected = 6, + MoveBusy = 7, + MoveEmpty = 8, + ErrorTicksTooLow = -1, + ErrorEmptyQueueToStart = -2, + ErrorNoDirPinToToggle = -3, + ErrorMoveTooLarge = -4, + ErrorCommandsSuspended = -5, +}; + +static inline bool moveTimedIsOk(MoveTimedResultCode status) { + return status == MoveTimedResultCode::OK; +} + +static inline MoveTimedResultCode tmrFrom(AqeResultCode res) { + return static_cast(res); +} + +static inline const char* toString(MoveTimedResultCode code) { + switch (code) { + case MoveTimedResultCode::OK: + return toString(AqeResultCode::OK); + case MoveTimedResultCode::QueueFull: + return toString(AqeResultCode::QueueFull); + case MoveTimedResultCode::DirPinIsBusy: + return toString(AqeResultCode::DirPinIsBusy); + case MoveTimedResultCode::WaitForEnablePinActive: + return toString(AqeResultCode::WaitForEnablePinActive); + case MoveTimedResultCode::DeviceNotReady: + return toString(AqeResultCode::DeviceNotReady); + case MoveTimedResultCode::DirPin2msPauseAdded: + return toString(AqeResultCode::DirPin2msPauseAdded); + case MoveTimedResultCode::DirChangePauseInjected: + return toString(AqeResultCode::DirChangePauseInjected); + case MoveTimedResultCode::MoveBusy: + return FAS_PSTR("Move still ongoing"); + case MoveTimedResultCode::MoveEmpty: + return FAS_PSTR("Queue has been empty"); + case MoveTimedResultCode::ErrorTicksTooLow: + return toString(AqeResultCode::ErrorTicksTooLow); + case MoveTimedResultCode::ErrorEmptyQueueToStart: + return toString(AqeResultCode::ErrorEmptyQueueToStart); + case MoveTimedResultCode::ErrorNoDirPinToToggle: + return toString(AqeResultCode::ErrorNoDirPinToToggle); + case MoveTimedResultCode::ErrorMoveTooLarge: + return FAS_PSTR("Error: Move too large"); + case MoveTimedResultCode::ErrorCommandsSuspended: + return toString(AqeResultCode::ErrorCommandsSuspended); + default: + return FAS_PSTR("Unknown Error"); + } +} +#define MOVE_TIMED_OK MoveTimedResultCode::OK +#define MOVE_TIMED_BUSY MoveTimedResultCode::MoveBusy +#define MOVE_TIMED_EMPTY MoveTimedResultCode::MoveEmpty +#define MOVE_TIMED_TOO_LARGE_ERROR MoveTimedResultCode::ErrorMoveTooLarge +#define MOVE_TIMED_COMMANDS_SUSPENDED MoveTimedResultCode::ErrorCommandsSuspended + +enum class DelayResultCode : int8_t { OK = 0, TOO_LOW = -1, TOO_HIGH = -2 }; + +static inline bool delayIsValid(DelayResultCode status) { + return status == DelayResultCode::OK; +} + +static inline const char* toString(DelayResultCode status) { + switch (status) { + case DelayResultCode::OK: + return toString(AqeResultCode::OK); + case DelayResultCode::TOO_LOW: + return FAS_PSTR("Delay Too Low"); + case DelayResultCode::TOO_HIGH: + return FAS_PSTR("Delay Too High"); + default: + return FAS_PSTR("Unknown Delay Status"); + } +} + +// Macros for simpler usage if needed +#define DELAY_OK DelayResultCode::OK +#define DELAY_TOO_LOW DelayResultCode::TOO_LOW +#define DELAY_TOO_HIGH DelayResultCode::TOO_HIGH + +#endif /* FAS_RESULT_CODES_H */ diff --git a/src/fas_arch/test_pc.h b/src/fas_arch/test_pc.h new file mode 100644 index 0000000..69df373 --- /dev/null +++ b/src/fas_arch/test_pc.h @@ -0,0 +1,60 @@ +#ifndef FAS_ARCH_TEST_PC_H +#define FAS_ARCH_TEST_PC_H + +// For pc-based testing like to have assert-macro +#include + +// and some more includes +#include +#include +#include + +// Arduino/AVR compatibility stubs for PC-based testing +#define PROGMEM +#define pgm_read_byte_near(x) (*(x)) + +// For inducing interrupts while testing +void noInterrupts(); +void interrupts(); +void inject_fill_interrupt(int mark); + +#define _BV(x) 0 +#define ISR(x) void x() +#define inline +#define micros() 0 + +#define abs(x) ((x) > 0 ? (x) : -(x)) +#define min(a, b) ((a) > (b) ? (b) : (a)) +#define max(a, b) ((a) > (b) ? (a) : (b)) + +#define digitalWrite(a, b) \ + { \ + } +#define pinMode(a, b) \ + { \ + } + +extern char TCCR1A; +extern char TCCR1B; +extern char TCCR1C; +extern char TIMSK1; +extern char TIFR1; +extern unsigned short OCR1A; +extern unsigned short OCR1B; + +#define test(x, msg) \ + if (!(x)) { \ + puts(msg); \ + assert(false); \ + }; + +// For pc-based testing, the macro TEST is defined. The pc-based testing does +// not support the concept of interrupts, so provide an empty definition +#define fasEnableInterrupts() +#define fasDisableInterrupts() + +// The TEST target needs a couple of arduino like definitions +#define LOW 0 +#define HIGH 1 + +#endif /* FAS_ARCH_TEST_PC_H */ diff --git a/src/fas_member/add_queue_entry.h b/src/fas_member/add_queue_entry.h new file mode 100644 index 0000000..d7c2400 --- /dev/null +++ b/src/fas_member/add_queue_entry.h @@ -0,0 +1,99 @@ +AqeResultCode StepperMotion::addQueueEntry( + const struct stepper_command_s* cmd, bool start) { + StepperQueue* q = _queue(); + if (cmd == NULL) { + return q->addQueueEntry(NULL, start); + } + if (cmd->ticks < q->max_speed_in_ticks) { + return AQE_ERROR_TICKS_TOO_LOW; + } + + if (_dirPin != PIN_UNDEFINED) { + if (!isQueueRunning()) { + if (_engine != NULL) { + if (_engine->isDirPinBusy(_dirPin, _queue_num)) { + return AQE_DIR_PIN_IS_BUSY; + } + } + } + } else { + if (!cmd->count_up) { + return AQE_ERROR_NO_DIR_PIN_TO_TOGGLE; + } + } + + AqeResultCode res = AQE_OK; + if (_autoEnable) { + fasDisableInterrupts(); + uint16_t delay_counter = _auto_disable_delay_counter; + fasEnableInterrupts(); + if (delay_counter == 0) { + // outputs are disabled + if (!enableOutputs()) { + return AQE_WAIT_FOR_ENABLE_PIN_ACTIVE; + } + // if on delay is defined, fill queue if required amount of pauses before + // the first step + if (_on_delay_ticks > 0) { + uint32_t delay = _on_delay_ticks; + // this delay sets count_up appropriately. If this is shorter than + // dir_change_delay_ticks, then extend accordingly + if ((delay < _dir_change_delay_ticks) && + (q->queue_end.count_up != cmd->count_up)) { + delay = _dir_change_delay_ticks; + } + while (delay > 0) { + uint32_t ticks = delay >> 1; + uint16_t ticks_u16 = ticks; + if (ticks > 65535) { + ticks_u16 = 65535; + } else if (ticks < 32768) { + ticks_u16 = delay; + } + struct stepper_command_s start_cmd = { + .ticks = ticks_u16, .steps = 0, .count_up = cmd->count_up}; + q->addQueueEntry(&start_cmd, false); + delay -= ticks_u16; + } + res = q->addQueueEntry(NULL, start); + if (res != AQE_OK) { + return res; + } + } + } + } + bool dir_change_needed = + (_dirPin != PIN_UNDEFINED) && (q->queue_end.count_up != cmd->count_up); + + if (_dirPin & PIN_EXTERNAL_FLAG) { + if (dir_change_needed) { + if (!handleExternalDirectionPin(q, cmd->count_up)) { + struct stepper_command_s pause_cmd = { + .ticks = US_TO_TICKS((uint16_t)2000), + .steps = 0, + .count_up = cmd->count_up}; + res = q->addQueueEntry(&pause_cmd, start); + if (res == AQE_OK) { + q->_injected_pause_ticks = pause_cmd.ticks; + res = AQE_DIR_PIN_2MS_PAUSE_ADDED; + } + return res; + } + } + } else if (dir_change_needed) { + res = q->addDirChangePauseToQueue(cmd, start, _dir_change_delay_ticks); + if (res != AQE_OK) { + return res; + } + } + res = q->addQueueEntry(cmd, start); + if (res == AQE_OK) { + if (_autoEnable) { + fasDisableInterrupts(); + _auto_disable_delay_counter = _off_delay_count; + fasEnableInterrupts(); + } + } + + return res; +} diff --git a/src/fas_member/move_timed.h b/src/fas_member/move_timed.h new file mode 100644 index 0000000..c787b7e --- /dev/null +++ b/src/fas_member/move_timed.h @@ -0,0 +1,189 @@ +#ifndef FAS_MOVE_TIMED_H +#define FAS_MOVE_TIMED_H + +#include + +#include "fas_arch/result_codes.h" + +// This header contains the core command generation logic of +// StepperMotion::moveTimed(). It is kept separate so it can be unit +// tested on the pc_based platform without any real hardware dependencies. +// +// The test provides its own StepperMotion/StepperQueue definitions and +// includes this header to compile the production moveTimed() body verbatim, +// the same pattern as fas_member/add_queue_entry.h. + +// A direction change makes the queue driver inject at most one pause command +// per call (driver dependent; up to three pauses total across retries, e.g. +// ESP32 RMT). moveTimed() must therefore treat two slots as reserved for every +// timed move, so that a move is only admitted when the whole move plus the +// direction pauses fits into the queue. Otherwise a direction change could run +// the queue short between the separate pause/step appends and silently drop +// steps (Issue 370). The application should keep the number of queue commands +// a move generates well below QUEUE_LEN/2 so that splitting large moves on the +// application side stays feasible. +// +// A steps==0 pause uses queue_end.count_up XOR prepare_revert: false keeps +// DIR, true issues the pause in the opposite direction (a dir change). +// +// On a pause-injected return (AqeResultCode::DirChangePauseInjected or +// AqeResultCode::DirPin2msPauseAdded) the command was NOT enqueued and +// *actual_duration carries the ticks of the one injected pause. The +// application accumulates this value per retry and computes the drift only +// once the move is accepted (see API documentation). +MoveTimedResultCode StepperMotion::moveTimed(int16_t steps, + uint32_t duration, + uint32_t* actual_duration, + bool start, + bool prepare_revert) { + MoveTimedResultCode ret_ok = + isQueueEmpty() ? MOVE_TIMED_EMPTY : MOVE_TIMED_OK; + if ((steps == 0) && (duration == 0)) { + if (start) { + addQueueEntry(NULL, true); // start the queue + } + return ret_ok; + } + uint8_t freeEntries = QUEUE_LEN - queueEntries(); + if (actual_duration != NULL) { + *actual_duration = 0; + } + _queue()->_injected_pause_ticks = 0; + bool count_up = _queue()->queue_end.count_up ^ prepare_revert; + struct stepper_command_s cmd = {.ticks = 0, .steps = 0, .count_up = count_up}; + if (steps == 0) { + if ((duration >> 16) >= QUEUE_LEN) { + return MOVE_TIMED_TOO_LARGE_ERROR; + } + if ((duration >> 16) >= freeEntries) { + return MOVE_TIMED_BUSY; + } + while (duration > 0) { + if (duration <= 65535) { + // done using one command + cmd.ticks = duration; + } else if (duration >= 131072) { + // need more than one command + cmd.ticks = 65535; + } else { + // just use half of the duration now, and the other half in the next + // cmd. + cmd.ticks = duration >> 1; + } + AqeResultCode ret = addQueueEntry(&cmd, start); + if (ret != AQE_OK) { + if ((actual_duration != NULL) && aqeIsPauseInjected(ret)) { + *actual_duration += _queue()->_injected_pause_ticks; + } + return tmrFrom(ret); + } + if (actual_duration != NULL) { + *actual_duration += cmd.ticks; + } + duration -= cmd.ticks; + } + return ret_ok; + } + + // let's evaluate the direction + if (steps < 0) { + cmd.count_up = false; + steps = -steps; + } else { + cmd.count_up = true; + } + + // There are steps to execute + // Let's first calculate the step rate + uint32_t rate = duration; + rate /= steps; + if (rate > 65535) { + // we need pauses, so only few steps can be executed + uint16_t cmds_per_step = (rate >> 16) + 1; // bit too small + if (cmds_per_step >= QUEUE_LEN) { + return MOVE_TIMED_TOO_LARGE_ERROR; + } + if (steps >= QUEUE_LEN) { + return MOVE_TIMED_TOO_LARGE_ERROR; + } + uint8_t cmds = steps * cmds_per_step; + if (cmds >= QUEUE_LEN) { + return MOVE_TIMED_TOO_LARGE_ERROR; + } + if (cmds > freeEntries) { + return MOVE_TIMED_BUSY; + } + // Should fit into the queue. + for (uint8_t steps_i = 0; steps_i < steps; steps_i++) { + uint32_t this_duration = rate; + cmd.steps = 1; + while (this_duration) { + if (this_duration >= 131072) { + cmd.ticks = 65535; + } else if (this_duration > 65535) { + cmd.ticks = this_duration / 2; + } else { + cmd.ticks = this_duration; + } + this_duration -= cmd.ticks; + + AqeResultCode ret = addQueueEntry(&cmd, start); + if (ret != AQE_OK) { + if ((actual_duration != NULL) && aqeIsPauseInjected(ret)) { + *actual_duration += _queue()->_injected_pause_ticks; + } + return tmrFrom(ret); + } + if (actual_duration != NULL) { + *actual_duration += cmd.ticks; + } + // remaining are pauses + cmd.steps = 0; + } + } + return ret_ok; + } + // Now we need to run steps at "high" speed. + if (steps > QUEUE_LEN * 255) { + return MOVE_TIMED_TOO_LARGE_ERROR; + } + if (steps > freeEntries * 255) { + return MOVE_TIMED_BUSY; + } + // The steps should fit in + cmd.ticks = rate; + uint32_t expected_duration = rate; + expected_duration *= steps; + // duration must be larger than expected_duration + int16_t missing = duration - expected_duration; + while (steps > 0) { + if (steps > 510) { + cmd.steps = 255; + } else if (steps > 255) { + cmd.steps = steps / 2; + } else { + cmd.steps = steps; + } + if (steps <= missing) { + // run the remaining steps bit slower to adjust for missing ticks + cmd.ticks++; + missing = 0; // only increase once + } + AqeResultCode ret = addQueueEntry(&cmd, start); + if (ret != AQE_OK) { + if ((actual_duration != NULL) && aqeIsPauseInjected(ret)) { + *actual_duration += _queue()->_injected_pause_ticks; + } + return tmrFrom(ret); + } + if (actual_duration != NULL) { + uint32_t d = cmd.ticks; + d *= cmd.steps; + *actual_duration += d; + } + steps -= cmd.steps; + } + return ret_ok; +} + +#endif // FAS_MOVE_TIMED_H diff --git a/src/fas_naxis/dda.h b/src/fas_naxis/dda.h new file mode 100644 index 0000000..c9ded5f --- /dev/null +++ b/src/fas_naxis/dda.h @@ -0,0 +1,86 @@ +#ifndef FAS_NAXIS_DDA_H +#define FAS_NAXIS_DDA_H + +#include +#include "fas_arch/common.h" + +#include "fas_naxis/remaining.h" + +// FasNAxis Linear DDA walk (whitepaper section 6.3). +// +// The DDA master is the longest |delta| (Remaining::longest_axis). Time-law +// rebind lengthens that master's period; it does not make a shorter axis the +// loop bound. Every slave is scaled down to the master's step count: err_i += +// |delta_i|; when 2*err_i >= |delta_bind| the slave steps (and err_i -= +// |delta_bind|). The path is the chord because each slave step is locked to a +// master step, and |delta_slave| <= |delta_bind| so the slave takes 0 or 1 +// step per master step and issued |steps| equals |delta|. +// +// This header *walks* that error accumulator one binder step at a time (Step +// 2c). Each binder step issues 0 or 1 step per axis (never 2): the binder +// issues 1, an idle slave 0, a moving slave 0 or 1. The walked step count per +// axis must equal Remaining::dda_steps for the same block. +// +// Integer arithmetic only. No float, no double, no integer division. The +// "distance to the chord <= 0.5*sqrt(n)" check of section 12.4 is a test-only +// double check, not part of this walker. +class DdaWalk { + public: + // `bind` is the binder displacement, `slave` the slave displacement of one + // axis (signed). The two magnitudes and the sign of the slave fully define + // the walk; the binder direction is carried by the binder column below. + DdaWalk(int32_t bind, int32_t slave) + : bind(bind), + slave(slave), + abs_bind(fas_abs(bind)), + abs_slave(fas_abs(slave)), + bind_dir(bind < 0 ? -1 : 1), + slave_dir(slave < 0 ? -1 : 1), + err(0), + k(0) {} + + int32_t bind; // signed binder displacement + int32_t slave; // signed slave displacement + uint32_t abs_bind; // |bind|, the loop bound + uint32_t abs_slave; // |slave|, the error increment + int bind_dir; // +1 / -1 + int slave_dir; // +1 / -1 + int32_t err; // Bresenham remainder; stays within ±|bind|/2 + uint32_t k; // binder steps consumed so far + + bool done() const { return k >= abs_bind; } + + // One binder step. `bind_out` is +1/-1 (the binder always steps), + // `slave_out` is -1/0/+1 (the slave steps when 2*err >= |bind|). The + // chord invariant |2*err| <= |bind| holds after every step. + void step(int* bind_out, int* slave_out) { + int s = 0; + err += (int32_t)abs_slave; + if (err > 0 && Remaining::u32_twice_ge((uint32_t)err, abs_bind)) { + s = slave_dir; + err -= (int32_t)abs_bind; + } + if (bind_out) { + *bind_out = bind_dir; + } + if (slave_out) { + *slave_out = s; + } + k++; + } + + // The chord invariant: |2*err| <= |bind| after a step. + bool on_chord() const { + int32_t e = err < 0 ? -err : err; + if (e < 0) { + return false; + } + uint32_t ue = (uint32_t)e; + if (ue >= 0x80000000u) { + return false; + } + return (ue << 1) <= abs_bind; + } +}; + +#endif /* FAS_NAXIS_DDA_H */ diff --git a/src/fas_naxis/linear.h b/src/fas_naxis/linear.h new file mode 100644 index 0000000..657e271 --- /dev/null +++ b/src/fas_naxis/linear.h @@ -0,0 +1,264 @@ +#ifndef FAS_NAXIS_LINEAR_H +#define FAS_NAXIS_LINEAR_H + +#include +#include "fas_arch/common.h" + +#include "fas_naxis/dda.h" +#include "fas_naxis/ramp_law.h" +#include "fas_naxis/ramp_map.h" +#include "fas_naxis/remaining.h" + +// FasNAxis Linear one-block interpolator (Step 2d, whitepaper section 6.3 / +// 9.2). One committed segment, rest-to-rest, no ring and no addQueueEntry. +// +// The DDA master is the longest |delta| (Remaining::longest_axis, tie-break +// slower ticks_cfg). It runs a RampLaw over |delta_master| steps; each master +// step is one DDA tick (the 2c walker) that also advances 0 or 1 step of the +// slave. The path is the chord because each slave step is locked to a master +// step, and issued |steps_i| equals |delta_i|. +// +// Time-law rebind does not change the DDA master. If a slower short slave +// would exceed v_max under the master's own ticks_cfg, Remaining::ticks_floor +// lengthens the master's period (section 6.3 "lengthen ticks_b"): the long +// axis is scaled down in speed, not in count. Walking DDA on the short axis +// would issue only |delta_slave| steps on the long axis and miss the vertex. +// +// This is the one-block rest-to-rest core of the Linear path. It is a pure +// interpolator: the caller drives it one binder step at a time through +// step(); the trace {ticks, step[NAXES] in {-1,0,1}} is recorded by the +// caller (or the test), not held in this header. Integer arithmetic only, no +// float / double / integer division. +class LinearBlock { + public: + int n_axes; // 2 (the fixtures of Step 2d are 2-axis) + int binder; // DDA master axis index (longest |delta|) + int32_t delta[2]; // signed per-axis displacement + RampLaw law; // the master's ramp law over |delta_master| steps + DdaWalk dda; // the chord walker, master -> slave + + // `d_in` is the segment displacement (signed per axis); `ticks` is the + // per-axis configured period (section 6.3). The move length in master + // steps is |delta_master|, so a zero-length slave never forces a + // different loop bound. `ticks_cfg` is unused: the time-law period is + // ticks_floor (max ticks_i of moving axes). + LinearBlock(uint32_t ticks_cfg, uint32_t accel, int n_axes, + const int32_t* d_in, const uint32_t* ticks) + : n_axes(n_axes), binder(0), law(ticks_cfg, accel, 0), dda(0, 0) { + delta[0] = d_in[0]; + delta[1] = d_in[1]; + binder = Remaining::longest_axis(delta, ticks, n_axes); + int32_t bind = delta[binder]; + int32_t slave = delta[1 - binder]; + uint32_t t_law = Remaining::ticks_floor(delta, ticks, n_axes); + if (t_law == 0) { + t_law = ticks_cfg; + } + law = RampLaw(t_law, accel, abs_delta(bind)); + dda = DdaWalk(bind, slave); + } + + // True when every binder step is consumed (RampLaw done and DDA done). + bool done() const { return dda.done() && law.done(); } + + // One binder step: apply the ramp law (returns the command period in ticks + // at the updated P), advance the DDA walker, and fill `step_out` with the + // per-axis step this binder step issues (-1 / 0 / +1). The binder column is + // +1/-1, the slave column is -1/0/+1. + uint32_t step(int step_out[2]) { + step_out[0] = 0; + step_out[1] = 0; + uint32_t ticks = law.step(); + int out_bind = 0, out_slave = 0; + dda.step(&out_bind, &out_slave); + step_out[binder] = out_bind; + step_out[1 - binder] = out_slave; + return ticks; + } + + private: + static uint32_t abs_delta(int32_t d) { return fas_abs(d); } +}; + +// FasNAxis Linear multi-block interpolator (Step 2f / 2h, whitepaper section +// 8.1 + 8.5 + 9.2). Walks a committed polyline held in a Remaining ring with +// no queues. The DDA master is the longest |delta| of the current block +// (Remaining::longest_axis, tie-break slower ticks_cfg). Each master step is +// one DDA tick (the 2c walker) that also advances 0 or 1 step of the slave. +// +// The ramp law (P vs R) is run per block. R is master steps to the next hard +// stop (section 8.5): master-sense reversal, outgoing master that was idle, +// dwell, or path end. P is live; P <= R at every step. At a hard stop P starts +// from 0. Across every other joint, including a non-collinear bend and a +// master-role change, P carries and R stays in path-step units. +// +// DIR pauses (before/after reversal) are Step 9 (queues). Here a reversal is +// only P -> 0 then the new sign on the next block. +class LinearPoly { + public: + Remaining* rem; + const uint32_t* ticks; + uint32_t accel; + int n_axes; + int block; // current block index + int master; // DDA master axis for the current block + DdaWalk dda; + RampMap map; + uint32_t ticks_law; + uint32_t P; + uint32_t R; + uint32_t R_before_cmd; // R at the start of the last issued command + uint32_t total_ticks; + bool finished; + + LinearPoly(Remaining* rem_, const uint32_t* ticks_, uint32_t accel_) + : rem(rem_), + ticks(ticks_), + accel(accel_), + n_axes(rem_->n_axes), + block(0), + master(0), + dda(0, 0), + map(ticks_[0], accel_), + ticks_law(ticks_[0]), + P(0), + R(0), + R_before_cmd(0), + total_ticks(0), + finished(false) { + start_block(0, true); + } + + bool done() const { + return finished || (block >= rem->n_blocks - 1 && dda.done()); + } + + // One master step. step_out[i] in {-1,0,1}. Period from the FAS map at the + // updated P, floored to ticks_law. R_before_cmd holds the R that was active + // at this command so the caller can reconstruct P <= R from issued periods + // without reading this object's P/R fields. + uint32_t step(int* step_out) { + for (int i = 0; i < n_axes; i++) { + step_out[i] = 0; + } + while (!finished && dda.done()) { + bool stop = true; + if (block + 1 < rem->n_blocks) { + int32_t a[2]; + int32_t b[2]; + a[0] = rem->delta_of(0, block); + a[1] = n_axes > 1 ? rem->delta_of(1, block) : 0; + b[0] = rem->delta_of(0, block + 1); + b[1] = n_axes > 1 ? rem->delta_of(1, block + 1) : 0; + stop = Remaining::linear_joint_stops(a, b, ticks, n_axes); + } + start_block(block + 1, stop); + } + if (finished) { + return 0; + } + R_before_cmd = R; + uint32_t t = apply_law(); + int out_bind = 0; + int out_slave = 0; + dda.step(&out_bind, &out_slave); + step_out[master] = out_bind; + if (n_axes > 1) { + step_out[1 - master] = out_slave; + } + return t; + } + + private: + static uint32_t abs_u(int32_t d) { return fas_abs(d); } + + int next_moving(int from) const { + for (int b = from; b < rem->n_blocks; b++) { + bool moving = false; + for (int i = 0; i < n_axes; i++) { + if (rem->delta_of(i, b) != 0) { + moving = true; + break; + } + } + if (moving) { + return b; + } + } + return rem->n_blocks; + } + + void start_block(int b, bool reset_P) { + b = next_moving(b); + if (b >= rem->n_blocks) { + finished = true; + return; + } + int32_t d[2]; + d[0] = rem->delta_of(0, b); + d[1] = n_axes > 1 ? rem->delta_of(1, b) : 0; + master = Remaining::longest_axis(d, ticks, n_axes); + ticks_law = Remaining::ticks_floor(d, ticks, n_axes); + if (ticks_law == 0) { + ticks_law = ticks[0]; + } + map = RampMap(ticks_law, accel); + int32_t bind = d[master]; + int32_t slave = n_axes > 1 ? d[1 - master] : 0; + dda = DdaWalk(bind, slave); + R = remaining_path_steps(b); + if (R == 0) { + R = abs_u(bind); + } + if (reset_P) { + P = 0; + } else { + uint32_t coast = map.P_coast(); + if (P > coast) { + P = coast; + } + if (P > R) { + P = R; + } + } + block = b; + finished = false; + } + + // Master steps to the next hard stop. P and R live in these units so a run + // may rebind the DDA master without changing the ramp-step currency. + uint32_t remaining_path_steps(int head) const { + uint32_t acc[2] = {accel, accel}; + return Remaining::linear_remaining<2>(head, rem->n_blocks, n_axes, ticks, + acc, rem->horizon, *rem); + } + + uint32_t apply_law() { + uint32_t coast = map.P_coast(); + if (R > P) { + if (P < coast) { + P++; + } + } else { + if (P > 0) { + P--; + } + } + uint32_t t; + if (P == 0) { + t = map.calculate_ticks(1); + } else { + t = map.calculate_ticks(P); + if (t < ticks_law) { + t = ticks_law; + } + } + total_ticks += t; + if (R > 0) { + R--; + } + return t; + } +}; + +#endif /* FAS_NAXIS_LINEAR_H */ diff --git a/src/fas_naxis/overshoot.h b/src/fas_naxis/overshoot.h new file mode 100644 index 0000000..137fefe --- /dev/null +++ b/src/fas_naxis/overshoot.h @@ -0,0 +1,343 @@ +#ifndef FAS_NAXIS_OVERSHOOT_H +#define FAS_NAXIS_OVERSHOOT_H + +#include +#include "fas_arch/common.h" + +#include "fas_naxis/remaining.h" +#include "fas_ramp/RampCalculator.h" + +// FasNAxis Overshoot run (whitepaper sections 6.4 / 6.5 / 7.3 / 8.6, todo +// Steps 11 and 12). +// +// A run is a sequence of committed blocks. Each axis runs its own 1-D FAS ramp +// on its remaining steps in the current direction R_i (the sum of |delta_i| +// until that axis reverses/ends, section 8.6). For the block, T_opt_i is the +// sum of the periods of axis i's |delta_i| steps with its P_i evolving; the +// binding axis is the largest T_opt_i (lower index on a tie) and T is its +// duration. Every command of the block lasts one binding period, so all axes +// share the wall clock and land exactly on the vertex. +// +// A non-binding axis still has to issue exactly |delta_i| steps across T. Its +// raw schedule is uniform in time: after binding time t it has completed k +// steps when |delta_i| * t >= k * T (integer multiply-compare, no division). If +// a command needs more than one of its steps the signed `steps` field carries +// them; a slow short axis is never finished early and then paused. +// +// overshoot_max caps how far the path may leave the chord. The production test +// uses the conservative product bound +// abs(nb*k - ns*x) <= overshoot_max * max(nb, ns) +// (nb = |delta_binder|, ns = |delta_i|, x = binding steps issued so far), +// which implies the exact squared-distance bound; no sqrt, no division, no +// 64-bit. When the uniform schedule would exceed the cap it is pulled one +// integer step at a time toward the chord -- the "mix toward Linear" of +// section 6.5. +// overshoot_max == 0 is Linear (this class is not used then); UINT16_MAX is the +// raw uniform schedule (the cap never binds). +// +// P carries across a junction when axis i keeps its sign; a sign change or a +// zero-length block resets P_i to 0 at that vertex and R_i is recomputed +// (section 8.6). The caller drives the run one command at a time through +// step(); no float, double, or integer division. +template +class OvershootRun { + public: + OvershootRun() { + n_axes = 0; + cap = 0; + done_ = true; + binder = 0; + ncmd = 0; + T = 0; + t = 0; + x = 0; + for (uint8_t i = 0; i < NMAX; i++) { + cfg[i].init(); + tick[i] = 1; + accel[i] = 1; + coast[i] = 1; + P[i] = 0; + R[i] = 0; + tot[i] = 0; + sgn[i] = 0; + prev[i] = 0; + issued[i] = 0; + binding[i] = false; + Topt[i] = 0; + } + } + + // Configure the per-axis FAS maps. `ticks` / `accel` are the per-axis + // configured period and acceleration; `cap_in` is overshoot_max. + void configure(int n, const uint32_t* ticks, const uint32_t* accel_in, + uint32_t cap_in) { + n_axes = n; + cap = cap_in; + done_ = true; + for (int i = 0; i < n_axes; i++) { + tick[i] = ticks[i]; + accel[i] = accel_in[i]; + cfg[i].init(); + cfg[i].parameters.setSpeedInTicks(ticks[i]); + cfg[i].parameters.setAcceleration((int32_t)accel_in[i]); + cfg[i].update(); + coast[i] = cfg[i].max_ramp_up_steps; + if (coast[i] == 0) { + coast[i] = 1; + } + P[i] = 0; + R[i] = 0; + prev[i] = 0; + tot[i] = 0; + sgn[i] = 0; + issued[i] = 0; + } + } + + // Commit the next block. `d[i]` is the signed displacement of axis i and + // `Rrem[i]` is that axis's remaining steps in its current direction from this + // block onward (the section 8.6 scan). A sign change or a zero block resets + // P_i; a continuation keeps it. `n` must equal the configured axis count. + void start_block(const int32_t* d, const uint32_t* Rrem) { + uint32_t Tmax = 0; + int b = 0; + bool any = false; + for (int i = 0; i < n_axes; i++) { + int32_t di = d[i]; + tot[i] = fas_abs(di); + sgn[i] = di > 0 ? 1 : (di < 0 ? -1 : 0); + issued[i] = 0; + if (tot[i] == 0 || (prev[i] != 0 && sgn[i] != 0 && sgn[i] != prev[i])) { + P[i] = 0; + } + R[i] = Rrem[i]; + uint32_t opt = 0; + if (tot[i] > 0) { + opt = simulate(i); + } + Topt[i] = opt; + if (opt > Tmax) { + Tmax = opt; + b = i; + any = true; + } + prev[i] = sgn[i]; + } + binder = b; + T = Tmax; + for (int i = 0; i < n_axes; i++) { + binding[i] = tot[i] > 0 && Topt[i] == Tmax && Tmax != 0; + } + t = 0; + x = 0; + ncmd = any ? tot[b] : 0; + done_ = !any; + } + + bool done() const { return done_; } + + // One command. Fills `step_out[i]` with the signed step count for axis i + // (0 or a small catch-up count; the cap keeps the deficit tight) and returns + // the command period in ticks. All axes share that tick sum. + uint32_t step(int* step_out) { + for (int i = 0; i < n_axes; i++) { + step_out[i] = 0; + } + if (done_) { + return 0; + } + uint32_t period = law_step(binder); + t += period; + x++; + step_out[binder] = sgn[binder]; + issued[binder]++; + for (int i = 0; i < n_axes; i++) { + if (i == binder || tot[i] == 0) { + continue; + } + uint32_t issue; + if (binding[i]) { + // T_opt_i == T: the axis rides its own ramp in lockstep, one step per + // command (section 7.3). + issue = issued[i] < tot[i] ? 1 : 0; + } else { + // Uniform-in-time candidate for a non-binding axis. The feeder turns a + // multi-step catch-up into one command of `steps` pulses at + // t_step / steps ticks each (section 9.3), so the shared wall clock is + // preserved. The quotient (steps issued = tot[i] * t / T) is a log2 + // approximation: sums of logs, no wide multiply or overflow check. + // At the block's last command (t == T) the last step compares equal + // in log2 (log2_from(tot[i]) + log2_from(T) vs itself), so issued[i] + // always reaches tot[i] and the axis lands on the vertex (G1). + uint32_t k = issued[i]; + int32_t lt_t = (int32_t)log2_from(tot[i]) + log2_from(t); + int32_t lt_T = log2_from(T); + while (k < tot[i] && lt_t >= (int32_t)log2_from(k + 1) + lt_T) { + k++; + } + if (cap != 0 && cap != 0xFFFFu && tot[binder] > 0) { + k = apply_cap(i, k); + } + issue = k - issued[i]; + } + for (uint32_t j = 0; j < issue; j++) { + law_step(i); + } + issued[i] += issue; + step_out[i] = sgn[i] * (int)issue; + } + if (x >= ncmd) { + done_ = true; + } + return period; + } + + bool last_command() const { return x >= ncmd; } + + int n_axes; + uint32_t cap; + uint32_t P[NMAX]; // performed ramp-up steps (persistent across blocks) + uint32_t R[NMAX]; // remaining steps in the current direction + int binder; // axis with the largest T_opt + uint32_t T; // binding block duration in ticks + uint32_t ncmd; // binding commands in the current block + uint32_t x; // binding commands issued in the current block + + private: + bool binding[NMAX]; // T_opt_i == T for this block + uint32_t Topt[NMAX]; // per-axis ramp duration for this block + ramp_config_s cfg[NMAX]; + uint32_t tick[NMAX]; + uint32_t accel[NMAX]; + uint32_t coast[NMAX]; + uint32_t tot[NMAX]; + int8_t sgn[NMAX]; + int8_t prev[NMAX]; + uint32_t issued[NMAX]; + uint32_t t; + bool done_; + + // Apply the section 7.1 law to axis i, then return the period at the new P. + uint32_t law_step(int i) { + if (R[i] > P[i]) { + if (P[i] < coast[i]) { + P[i]++; + } + } else { + if (P[i] > 0) { + P[i]--; + } + } + uint32_t p = period(i); + if (R[i] > 0) { + R[i]--; + } + return p; + } + + uint32_t period(int i) const { + uint32_t p; + if (P[i] == 0) { + p = cfg[i].calculate_ticks(1); + } else { + p = cfg[i].calculate_ticks(P[i]); + if (p < tick[i]) { + p = tick[i]; + } + } + return p; + } + + // Sum of the periods axis i would take for this block's |delta_i| steps, + // without touching the live P / R. + uint32_t simulate(int i) const { + uint32_t p = P[i]; + uint32_t r = R[i]; + uint32_t sum = 0; + for (uint32_t s = 0; s < tot[i]; s++) { + if (r > p) { + if (p < coast[i]) { + p++; + } + } else { + if (p > 0) { + p--; + } + } + uint32_t tt; + if (p == 0) { + tt = cfg[i].calculate_ticks(1); + } else { + tt = cfg[i].calculate_ticks(p); + if (tt < tick[i]) { + tt = tick[i]; + } + } + uint32_t next = sum + tt; + sum = next < sum ? 0xffffffffu : next; + if (r > 0) { + r--; + } + } + return sum; + } + + // True when the uniform candidate `k` for axis i lies outside the + // overshoot_max cap around the chord. No sqrt, no division, no 64-bit: + // the perpendicular distance is D / sqrt(nb^2+ns^2) with D = |nb*k - + // ns*x|. The test uses the conservative bound D <= cap * max(nb, ns), + // which is >= cap * sqrt(nb^2+ns^2), split into two product compares + // (Remaining::log2_mul_diff) so the realized distance never exceeds the + // hard cap. The bound is tight when one axis dominates and at most + // sqrt(2) tighter on a diagonal. + // + // log2_mul_diff rounds by up to four log2 units; a comparison within + // kCapSlack of equality is treated as outside so the guarantee survives + // the rounding (a one-step move changes D by up to max(nb,ns), so a + // near-tie would otherwise be decided the wrong way). + bool outside_cap(uint32_t nb, uint32_t ns, uint32_t k) const { + const int32_t kCapSlack = 4; + if (nb == 0 || ns == 0) { + return false; + } + if (nb >= ns) { + // inside <=> nb*(k-cap) <= ns*x and ns*x <= nb*(k+cap) + if (k >= cap && + Remaining::log2_mul_diff(nb, k - cap, ns, x) > -kCapSlack) { + return true; + } + if (Remaining::log2_mul_diff(ns, x, nb, k + cap) > -kCapSlack) { + return true; + } + } else { + // inside <=> nb*k <= ns*(x+cap) and ns*(x-cap) <= nb*k + if (Remaining::log2_mul_diff(nb, k, ns, x + cap) > -kCapSlack) { + return true; + } + if (x >= cap && + Remaining::log2_mul_diff(ns, x - cap, nb, k) > -kCapSlack) { + return true; + } + } + return false; + } + + uint32_t apply_cap(int i, uint32_t k) const { + uint32_t nb = tot[binder]; + uint32_t ns = tot[i]; + // Log2 direction for the walk; the conservative outside_cap() gate + // stops the walk inside the cap region, so neither the sign slack nor + // the bound slack can pull the step outside overshoot_max. + while (k > issued[i] && Remaining::log2_mul_cmp(nb, k, ns, x) > 0 && + outside_cap(nb, ns, k)) { + k--; + } + while (k < tot[i] && Remaining::log2_mul_cmp(nb, k, ns, x) < 0 && + outside_cap(nb, ns, k)) { + k++; + } + return k; + } +}; + +#endif /* FAS_NAXIS_OVERSHOOT_H */ diff --git a/src/fas_naxis/ramp_law.h b/src/fas_naxis/ramp_law.h new file mode 100644 index 0000000..80dd95a --- /dev/null +++ b/src/fas_naxis/ramp_law.h @@ -0,0 +1,108 @@ +#ifndef FAS_NAXIS_RAMP_LAW_H +#define FAS_NAXIS_RAMP_LAW_H + +#include + +#include "fas_naxis/ramp_map.h" + +// FasNAxis ramp law (whitepaper section 7.1): the per-axis (Overshoot) and +// per-binder (Linear) control law that RampControl::_getNextCommand applies. +// +// R is remaining steps to stand still in the current direction (lookahead +// scan of section 8). P is performed ramp-up steps. P starts at 0 and is +// not a precomputed min(P_stop, R/2). The two caps are applied live: +// +// max speed: P stops increasing at P_coast +// remaining-to-stop: when R == P the next steps count P down +// +// R > P -> accelerate: P++ (or coast when P already at P_coast) +// R == P -> decelerate: P-- +// R < P -> decelerate (overshoot guard, same as FAS) +// +// Period is computed after the P update, matching FAS: first step from rest +// is calculate_ticks(1); last decel step from P == 1 uses ticks_cfg. +// calculate_ticks(0) is never called. +// +// Coasting on a rest-to-rest move of N steps happens when N/2 > P_coast +// (equivalently N > 2 P_coast). A shorter N is a triangle whose peak is +// whatever P has grown to when R catches it -- an outcome, not an input. +// +// FAS_NAXIS_NO_REST_CAP (Step 2b mutation): ignore remaining-to-stop and +// always accel/coast. Short-R probes then fail to brake (peak P is not < R). +class RampLaw { + public: + RampMap map; + uint32_t ticks_cfg; + uint32_t P; // performed ramp-up steps + uint32_t R; // remaining steps in the current direction + uint32_t total_ticks; + + // `total` is the move length S (== R at start). The planner drives R down to + // 0, one command (step) at a time. + RampLaw(uint32_t ticks_cfg, uint32_t accel, uint32_t total) + : map(ticks_cfg, accel), + ticks_cfg(ticks_cfg), + P(0), + R(total), + total_ticks(0) {} + + // Period (ticks) for the command at ramp position P. P == 0 is stopped: + // calculate_ticks(0) is never called; the only issued command at P == 0 is + // the last decel step (FAS uses ticks_cfg there). P >= 1 uses the log2 + // period clipped to ticks_cfg (and to ticks_min if a caller supplies one). + uint32_t period(uint32_t ticks_min = 0) const { + uint32_t t; + if (P == 0) { + t = map.calculate_ticks(1); + } else { + t = map.calculate_ticks(P); + if (t < ticks_cfg) { + t = ticks_cfg; + } + } + if (t < ticks_min) { + t = ticks_min; + } + return t; + } + + // One command: apply the section 7.1 law to P, then issue at that P, then + // count down one remaining step. Accel from rest is 0 -> 1 before the + // period, so the first step is calculate_ticks(1), not ticks_cfg. + uint32_t step(uint32_t ticks_min = 0) { + uint32_t coast = map.P_coast(); +#ifdef FAS_NAXIS_NO_REST_CAP + if (P < coast) { + P++; + } +#else + if (R > P) { + if (P < coast) { + P++; // accelerate (else coast: P held at P_coast) + } + } else { + if (P > 0) { + P--; // decelerate (R == P, or overshoot R < P) + } + } +#endif + uint32_t ticks = period(ticks_min); + total_ticks += ticks; + if (R > 0) { + R--; + } + return ticks; + } + + // Issue `n` consecutive steps as one planning chunk. Each step re-applies + // the law, so the chunk lands on the same P trajectory as n single steps. + void step_chunk(uint32_t n, uint32_t ticks_min = 0) { + for (uint32_t i = 0; i < n; i++) { + step(ticks_min); + } + } + + bool done() const { return R == 0; } +}; + +#endif /* FAS_NAXIS_RAMP_LAW_H */ diff --git a/src/fas_naxis/ramp_map.h b/src/fas_naxis/ramp_map.h new file mode 100644 index 0000000..6c380ba --- /dev/null +++ b/src/fas_naxis/ramp_map.h @@ -0,0 +1,52 @@ +#ifndef FAS_NAXIS_RAMP_MAP_H +#define FAS_NAXIS_RAMP_MAP_H + +#include "fas_ramp/RampCalculator.h" + +// FasNAxis F1 kernel: the single-axis period/step law. +// +// The white paper (section 7.1) says FasNAxis must reuse +// ramp_config_s::calculate_ticks / calculate_ramp_steps and must never +// re-derive v = sqrt(2 a s). This wrapper is a thin forwarder: it builds a +// ramp_config_s from a configured period (ticks_cfg, from getSpeedInTicks) +// and an acceleration (stored as log2_accel via log2_from, as the library +// does), then forwards. Periods are log2_value_t math inside ramp_config_s; +// this header performs no float, double, or integer division on the hot path. +// +// P = 0 is "stopped": FAS starts ramps at P >= 1, so calculate_ticks(0) is +// never called. Callers pass P in [1, P_coast]. + +class RampMap { + public: + // ticks_cfg: configured period in ticks/step. accel: acceleration in + // step/s^2 (converted to log2 here, exactly as ramp_parameters_s does). + RampMap(uint32_t ticks_cfg, uint32_t accel) { + config.init(); + config.parameters.setSpeedInTicks(ticks_cfg); + config.parameters.setAcceleration(accel); + config.update(); + } + + // Period (ticks) at ramp position P. P must be >= 1. + uint32_t calculate_ticks(uint32_t P) const { + return config.calculate_ticks(P); + } + + // Inverse: performed ramp steps for a given period. + uint32_t calculate_ramp_steps(uint32_t ticks) const { + return config.calculate_ramp_steps(ticks); + } + + // Coast position P_coast = performed ramp steps at the configured period. + uint32_t P_coast() const { return config.max_ramp_up_steps; } + + // Configured period (ticks/step). + uint32_t ticks_cfg() const { return config.parameters.min_travel_ticks; } + + const ramp_config_s& get_config() const { return config; } + + private: + ramp_config_s config; +}; + +#endif /* FAS_NAXIS_RAMP_MAP_H */ diff --git a/src/fas_naxis/remaining.h b/src/fas_naxis/remaining.h new file mode 100644 index 0000000..36a6899 --- /dev/null +++ b/src/fas_naxis/remaining.h @@ -0,0 +1,436 @@ +#ifndef FAS_NAXIS_REMAINING_H +#define FAS_NAXIS_REMAINING_H + +#include +#include "fas_arch/common.h" + +#include "fas_naxis/ramp_map.h" +#include "log2/Log2Representation.h" + +// FasNAxis remaining-steps scan R and DDA / time-law oracle (whitepaper +// sections 6.3 and 8). +// +// The DDA / time-law functions (longest_axis, ticks_floor, binder_axis, +// dda_steps) are stateless and are used by the production planner and by the +// PC reference tests. +// +// The stateful remaining-steps scan R and the collinearity test are used only +// by the host reference track (tests/host). They are compiled only +// when FAS_NAXIS_REFERENCE is defined, so a target build carries no Remaining +// object and, in particular, no backing store for the reference scan. +// +// R is the lookahead kernel: per axis it is the sum of |delta_i| over the +// block ring until the first of (path end, that axis going idle after it +// moved, or a sign flip of that axis). The last buffered point of an open +// path is rest, so the scan simply ends at the last buffered block. +// +// Linear's binder R (sections 6.3 / 8.5) sums DDA-master steps until a hard +// stop: the master's sense ends, the outgoing master was idle, a dwell, or +// the path end. A non-collinear joint does not end it, and neither does a +// master-role change. The 2 deg collinear diagnostic lives in the PC test +// harness (naxis_ref.h), not in production. +// +// This is pure parse: integer add / abs / sign only. No float, double, or +// integer division is formed in the scan. Every product comparison is a log2 +// sum (log2_mul_cmp) - no floating point, no division, no 64-bit type; the +// log2 slack is the sanctioned approximation (whitepaper section 6.3). The +// live speed cap is the ramp law in ramp_law.h (P starts at 0, increases, +// clipped by P_coast and by remaining-to-standstill). Remaining.h does not +// estimate a peak as min(P_stop, R/2). +// +// HORIZON (a public field, default unbounded) caps the number of *points* +// the scan may touch: section 8.2 / F19 (a small HORIZON of micro-segments +// caps P below P_stop; the same HORIZON with one long block still coasts +// because R is steps, not points). +// +// Compile-time hook (Step 2b mutation probe) proves the theory fails on a +// wrong model: +// FAS_NAXIS_NO_REBIND -> binder_axis is longest-distance only (drops ticks) +// binder_axis is the time-law oracle (wall-clock). The interpolator DDA +// master is longest_axis; ticks_floor lengthens the master's period. +// Remaining-to-standstill is the ramp law (FAS_NAXIS_NO_REST_CAP lives in +// ramp_law.h). +class Remaining { + public: + // 2*err >= master, without a widening multiply. err >= 2^31 implies + // 2*err >= 2^32 > master. + static bool u32_twice_ge(uint32_t err, uint32_t master) { + if (err >= 0x80000000u) { + return true; + } + return (err << 1) >= master; + } + + // a*b vs c*d as log2 sums (whitepaper section 6.3): every product compare + // is a sum of logs and may move one log2 quantum out of tolerance. The + // zero product is -infinity: it loses to any positive product. + static int log2_mul_cmp(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + bool first = a != 0 && b != 0; + bool second = c != 0 && d != 0; + if (!first || !second) { + return first - second; + } + int32_t la = (int32_t)log2_from(a) + log2_from(b); + int32_t lc = (int32_t)log2_from(c) + log2_from(d); + return la > lc ? 1 : (la < lc ? -1 : 0); + } + + // log2(a*b) - log2(c*d) in the 9-bit log2 unit, for a caller that needs a + // conservative margin rather than a bare sign. A zero factor is -infinity + // (some +-0x4000). The value is a sum of four log2_from, so it carries up + // to four units of rounding. + static int32_t log2_mul_diff(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { + bool first = a != 0 && b != 0; + bool second = c != 0 && d != 0; + if (!first || !second) { + return (first ? 0x4000 : 0) - (second ? 0x4000 : 0); + } + return (int32_t)log2_from(a) + (int32_t)log2_from(b) - + (int32_t)log2_from(c) - (int32_t)log2_from(d); + } + +#ifdef FAS_NAXIS_REFERENCE + int n_axes; + int n_blocks; + int32_t* deltas; // n_axes x n_blocks, row-major [axis * n_blocks + block] + uint32_t horizon; // max points scanned (0 or INT32_MAX = unbounded) + + // The backing store is sized for the reference caller (the PC test block + // rings are at most 512 n-dim blocks). + Remaining(int axes, int blocks) + : n_axes(axes), n_blocks(blocks), horizon(0xFFFFFFFFU) { + static int32_t store[1024]; + deltas = store; + for (int i = 0; i < n_axes * n_blocks; i++) { + store[i] = 0; + } + } + + // Write one n-dim block (signed per-axis displacement). + void set_block(int block, const int32_t* d) { + for (int i = 0; i < n_axes; i++) { + deltas[i * n_blocks + block] = d[i]; + } + } + + // Signed displacement of axis `axis` in block `block`. + int32_t delta_of(int axis, int block) const { + return deltas[axis * n_blocks + block]; + } + + // Adapts delta_of to the (block, axis) order used by linear_remaining. + static int32_t delta_at(const Remaining& r, int b, int axis) { + return r.delta_of(axis, b); + } + + // Section 8.1 per-axis parse from head block `head`. Walks forward, + // summing |delta| until idle-after-move or a sign flip; HORIZON caps the + // number of blocks touched. The last buffered point is rest, so an open + // path stops at the last block naturally. + int32_t remaining(int axis, int head) const { + int32_t R = 0; + int sign = 0; + int count = 0; + for (int b = head; b < n_blocks; b++) { + int32_t d = deltas[axis * n_blocks + b]; + if (d == 0) { + if (sign != 0) { + break; // direction ended: axis went idle after moving + } + continue; // idle on this block; has not started a direction yet + } + int s = (d > 0) ? 1 : -1; + if (sign == 0) { + sign = s; + } + if (s != sign) { + break; // reversal: must be at 0 here + } + R += (d > 0) ? d : -d; + if (horizon != 0 && horizon != 0xFFFFFFFFU) { + count++; + if (count >= (int)horizon) { + break; // HORIZON (points) reached + } + } + } + return R; + } + + // Linear binder R from `head`: DDA-master steps to the next hard stop + // (section 8.5). `axis` is unused; the currency is master steps, not one + // axis's |delta|. HORIZON caps the points. Ticks/accel are unknown here, so + // the slower-envelope preparation is not applied (call linear_remaining). + int32_t remaining_linear_binder(int axis, int head) const { + (void)axis; + return (int32_t)linear_remaining<8>(head, n_blocks, n_axes, NULL, NULL, + horizon, *this); + } + +#endif /* FAS_NAXIS_REFERENCE */ + + // True when every axis of the block is idle (a dwell, or a zero vector). + static bool block_idle(const int32_t* block, int n_axes) { + for (int i = 0; i < n_axes; i++) { + if (block[i] != 0) { + return false; + } + } + return true; + } + + // Section 8.5 hard stop between block A and block B. P goes to 0 here. + // The 2 deg collinear test is not consulted. + static bool linear_joint_stops(const int32_t* a, const int32_t* b, + const uint32_t* ticks, int n_axes) { + if (block_idle(a, n_axes) || block_idle(b, n_axes)) { + return true; + } + int ma = longest_axis(a, ticks, n_axes); + int mb = longest_axis(b, ticks, n_axes); + int sa = a[ma] > 0 ? 1 : -1; + int sb = b[ma] > 0 ? 1 : (b[ma] < 0 ? -1 : 0); + if (sb != sa) { + return true; // master reverses or goes idle + } + if (a[mb] == 0) { + return true; // outgoing master was idle + } + // An axis tied with the master (|delta| equal) that reverses or goes + // idle is a full-speed reversal. The tie-break that named the other + // axis master does not make that reversal a slave cusp (F6). + int32_t adm = a[ma] > 0 ? a[ma] : -a[ma]; + for (int i = 0; i < n_axes; i++) { + if (i == ma) { + continue; + } + int32_t adi = a[i] > 0 ? a[i] : -a[i]; + if (adi != adm || adi == 0) { + continue; + } + int so = b[i] > 0 ? 1 : (b[i] < 0 ? -1 : 0); + int si = a[i] > 0 ? 1 : -1; + if (so != si) { + return true; + } + } + return false; + } + + // The delta source is either a 2D block array or a callable (block, axis). + // Overloading lets the array be passed directly without wrapping it in a + // lambda at the call site. + template + static int32_t delta_at(const int32_t (*blk)[N], int b, int axis) { + return blk[b][axis]; + } + template + static int32_t delta_at(const Delta& delta, int b, int axis) { + return delta(b, axis); + } + + // Linear R from `head`: master steps to the next hard stop. When `ticks` + // and `accel` are both set, a role change that raises ticks_floor shortens + // R so the incoming ramp reaches the outgoing period before the vertex + // (P_match = calculate_ramp_steps(ticks_floor_out) on the incoming map). + // `horizon` 0 or 0xFFFFFFFF means unbounded. `Delta` is (block, axis). + // N is the maximum axis count the caller will pass. + template + static uint32_t linear_remaining(int head, int n_blocks, int n_axes, + const uint32_t* ticks, const uint32_t* accel, + uint32_t horizon, Delta delta) { + if (head >= n_blocks || n_axes <= 0 || n_axes > N) { + return 0; + } + int32_t blk[N]; +#ifndef FAS_NAXIS_NO_CROSS_BLOCK_R + int32_t nxt[N]; +#endif + for (int i = 0; i < N; i++) { + blk[i] = 0; +#ifndef FAS_NAXIS_NO_CROSS_BLOCK_R + nxt[i] = 0; +#endif + } + for (int i = 0; i < n_axes; i++) { + blk[i] = delta_at(delta, head, i); + } + if (block_idle(blk, n_axes)) { + return 0; + } + uint32_t sum = 0; + uint32_t best = 0xFFFFFFFFU; +#ifndef FAS_NAXIS_NO_CROSS_BLOCK_R + int included = 0; + bool limit_h = horizon != 0 && horizon != 0xFFFFFFFFU; +#endif + for (int b = head; b < n_blocks; b++) { + if (b != head) { + for (int i = 0; i < n_axes; i++) { + blk[i] = delta_at(delta, b, i); + } + if (block_idle(blk, n_axes)) { + break; + } + } + int m = longest_axis(blk, ticks, n_axes); + int32_t ad = blk[m] > 0 ? blk[m] : -blk[m]; + sum += (uint32_t)ad; +#ifdef FAS_NAXIS_NO_CROSS_BLOCK_R + best = sum; + break; +#else + included++; + if (limit_h && included >= (int)horizon) { + break; + } + if (b + 1 >= n_blocks) { + break; + } + for (int i = 0; i < n_axes; i++) { + nxt[i] = delta_at(delta, b + 1, i); + } + if (linear_joint_stops(blk, nxt, ticks, n_axes)) { + break; + } + if (ticks != NULL && accel != NULL) { + int mb = longest_axis(nxt, ticks, n_axes); + if (m != mb) { + uint32_t tin = ticks_floor(blk, ticks, n_axes); + uint32_t tout = ticks_floor(nxt, ticks, n_axes); + if (tout > tin && tin > 0) { + int binder = binder_axis(blk, ticks, n_axes); + RampMap map(tin, accel[binder]); + uint32_t capped = sum + map.calculate_ramp_steps(tout); + if (capped < best) { + best = capped; + } + } + } + } +#endif + } + if (best < sum) { + return best; + } + return sum; + } + + // ---- DDA / time-law oracle (whitepaper section 6.3 / 8.3) -------------- + // Pure static functions, no state. The planner must match these on the + // same inputs. Integer compare only (no integer division in the binder + // selection). + + // Section 6.3 DDA master: longest |delta|, tie-break on larger ticks_cfg + // (the slower motor). This is the interpolator loop bound. A shorter axis + // is never the master: DDA slaves take 0 or 1 step per master step, and + // issued |steps_i| equals |delta_i| (the vertex is hit). Time-law rebind + // does not change this axis; it lengthens ticks_b (ticks_floor). + static int longest_axis(const int32_t* block, const uint32_t* ticks, + int n_axes) { + int b = 0; + int32_t best_ad = -1; + uint32_t best_t = 0; + for (int i = 0; i < n_axes; i++) { + int32_t ad = block[i] > 0 ? block[i] : -block[i]; + if (ad == 0) { + continue; + } + uint32_t t = ticks ? ticks[i] : 0; + if (ad > best_ad || (ad == best_ad && t > best_t)) { + best_ad = ad; + best_t = t; + b = i; + } + } + return b; + } + + // Section 6.3 time-law floor: max ticks_i_cfg over axes with delta_i != 0. + // Integer max, no division. Every shared command then satisfies every + // moving axis envelope (ticks >= ticks_i_cfg). When a slow short slave + // would lose the wall-clock compare, this lengthens the master's period + // ("lengthen ticks_b") instead of walking DDA on the short axis. + static uint32_t ticks_floor(const int32_t* block, const uint32_t* ticks, + int n_axes) { + uint32_t t = 0; + for (int i = 0; i < n_axes; i++) { + if (block[i] == 0) { + continue; + } + if (ticks[i] > t) { + t = ticks[i]; + } + } + return t; + } + + // Section 6.3 time-law oracle: the axis that would take the longest + // wall-clock at its own max speed, i.e. argmax over i of |delta_i| * + // ticks_i. "Longest |delta| first" when ticks are equal; "rebind if + // |delta_i|*ticks_i > |delta_b|*ticks_b" when a slow slave dominates. + // This names who constrains the period, not who walks DDA (that is + // longest_axis). FAS_NAXIS_NO_REBIND drops the ticks factor + // (longest-distance only) so the rebind neighbourhood (item 3 of Step + // 2b) fails when the model is wrong. + static int binder_axis(const int32_t* block, const uint32_t* ticks, + int n_axes) { + int b = 0; + uint32_t best_ad = 0; + uint32_t best_t = 0; + bool any = false; + for (int i = 0; i < n_axes; i++) { + if (block[i] == 0) { + continue; + } + uint32_t ad = fas_abs(block[i]); +#ifdef FAS_NAXIS_NO_REBIND + uint32_t t = 0; +#else + uint32_t t = ticks[i]; +#endif + if (!any) { + any = true; + best_ad = ad; + best_t = t; + b = i; + continue; + } +#ifdef FAS_NAXIS_NO_REBIND + if (ad > best_ad) { +#else + if (log2_mul_cmp(ad, t, best_ad, best_t) > 0) { +#endif + best_ad = ad; + best_t = t; + b = i; + } + } + return b; + } + + // Section 6.3 DDA step count for one block: how many steps slave `slave` + // issues over the binder's |delta_bind| steps (err += |slave|; if + // 2*err >= |bind| then step and err -= |bind|). The binder itself (slave + // magnitude == bind) issues |delta_bind| steps; an idle slave issues 0. + // Used by the PC reference tests. + static int dda_steps(int delta_bind, int delta_slave) { + uint32_t abs_bind = fas_abs(delta_bind); + uint32_t abs_slave = fas_abs(delta_slave); + if (abs_bind == 0) { + return 0; + } + int32_t err = 0; + int steps = 0; + for (uint32_t i = 0; i < abs_bind; i++) { + err += (int32_t)abs_slave; + if (err > 0 && u32_twice_ge((uint32_t)err, abs_bind)) { + steps++; + err -= (int32_t)abs_bind; + } + } + return steps; + } +}; + +#endif /* FAS_NAXIS_REMAINING_H */ diff --git a/src/fas_queue/base.h b/src/fas_queue/base.h new file mode 100644 index 0000000..fe738b3 --- /dev/null +++ b/src/fas_queue/base.h @@ -0,0 +1,130 @@ +#ifndef FAS_QUEUE_BASE_H +#define FAS_QUEUE_BASE_H + +#include "fas_arch/common.h" + +// QUEUE_LEN_MASK is used in inline methods below +#define QUEUE_LEN_MASK (QUEUE_LEN - 1) + +// Queue entry: a single low-level stepper command. +// steps == 0 means pure delay (no step pulses). +struct queue_entry { + uint8_t steps; // if 0, then the command only adds a delay + uint8_t toggle_dir : 1; + uint8_t countUp : 1; + uint8_t hasSteps : 1; + uint8_t dirPinState : 1; + uint16_t ticks; +#if defined(SUPPORT_QUEUE_ENTRY_END_POS_U16) + uint16_t end_pos_last16; +#endif +#if defined(SUPPORT_QUEUE_ENTRY_START_POS_U16) + uint16_t start_pos_last16; +#endif +}; + +// Architecture-independent stepper queue state. +// +// Each architecture defines `class StepperQueue : public StepperQueueBase` +// in its own pd_*/ directory, adding hardware-specific fields and methods. +// Common methods (addQueueEntry, getCurrentPosition, etc.) are defined in +// StepperISR.cpp and declared here so the compiler sees them on all arches. +class StepperQueueBase { + public: + // initialization of this array is not necessary + // volatile is not needed, too. + struct queue_entry entry[QUEUE_LEN]; + // not sure, if volatile is needed for these two indices. Leave it for now + volatile uint8_t read_idx; // ISR stops if read_idx == next_write_idx + volatile uint8_t next_write_idx; + struct queue_end_s queue_end; + + // Queue admission latch. When set, addQueueEntry() refuses every command + // with AQE_ERROR_COMMANDS_SUSPENDED -- including addQueueEntry(NULL, start), + // so a suspended queue cannot be started either. + // + // Set by forceStop() and forceStopAndNewPosition() as a backstop against a + // planner whose own stop flag is wrong, and cleared by resumeCommands(), + // which a caller reaches only through a documented public API (a fresh + // coordinated plan, or StepperMotion::resumeCommands()). + // + // It is NOT transient. fill_queue() used to clear it on every active ramp + // pass, which made it inert for the ramp and permanent for the low-level + // addQueueEntry() user, whose ramp is never active. + volatile bool ignore_commands; + + void suspendCommands() { ignore_commands = true; } + void resumeCommands() { ignore_commands = false; } + bool areCommandsSuspended() const { return ignore_commands; } + + bool dirHighCountsUp; + uint8_t dirPin; + uint16_t max_speed_in_ticks; +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + uint16_t _last_pause_ticks; + uint8_t _nr_of_pauses; + + inline void clear_pause_stats() { + _last_pause_ticks = 0; + _nr_of_pauses = 0; + } + // Nothing is in flight, so every amount of pause time is already behind the + // next command. Without this a standstill reads as "no drain yet": the first + // command whose direction differs from the power-on queue_end got a full + // driver drain pause in front of it, and -- because that pause makes the + // queue non-empty -- lost the empty-queue path in addQueueEntry() that sets + // the dir pin directly, so the driver had to *toggle* it at encode time + // instead. ESP32 reads _last_pause_ticks. _nr_of_pauses stays 0: Pico counts + // pause words still ahead of the next command, and a drained pipeline is + // not four of those words. + inline void markPipelineDrained() { _last_pause_ticks = 65535; } +#endif + + // Ticks of the pause(s) injected for the current moveTimed() call. + // Pico sums the drain pauses and the user delay; that sum exceeds 65535. + uint32_t _injected_pause_ticks; + + void _base_initVars() { + queue_end.dir = true; + queue_end.count_up = true; + dirHighCountsUp = true; + dirPin = PIN_UNDEFINED; + // intentionally slow speed to make missing initialization detectable + max_speed_in_ticks = TICKS_PER_S / 1000; +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + markPipelineDrained(); +#endif + _injected_pause_ticks = 0; + } + + inline uint8_t queueEntries() const { + fasDisableInterrupts(); + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + fasEnableInterrupts(); + inject_fill_interrupt(0); + return (uint8_t)(wp - rp); + } + inline bool isQueueFull() const { return queueEntries() == QUEUE_LEN; } + inline bool isQueueEmpty() const { return queueEntries() == 0; } + inline bool hasStepsInQueue() const { + fasDisableInterrupts(); + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + fasEnableInterrupts(); + while (rp != wp) { + if (entry[rp & QUEUE_LEN_MASK].steps > 0) { + return true; + } + rp++; + } + return false; + } + inline uint16_t getMaxSpeedInTicks() const { return max_speed_in_ticks; } + +#if defined(SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING) + void setAbsoluteSpeedLimit(uint16_t ticks) { max_speed_in_ticks = ticks; } +#endif +}; + +#endif // FAS_QUEUE_BASE_H diff --git a/src/fas_queue/protocol.h b/src/fas_queue/protocol.h new file mode 100644 index 0000000..4401c5b --- /dev/null +++ b/src/fas_queue/protocol.h @@ -0,0 +1,136 @@ +#ifndef FAS_QUEUE_PROTOCOL_H +#define FAS_QUEUE_PROTOCOL_H + +// This file defines the protocol interface for StepperQueue implementations. +// Each platform-specific StepperQueue class (in pd_*/queue.h) should include +// this file to declare these methods. The implementations go in the respective +// .cpp files. +// +// The protocol methods are injected into the StepperQueue class via inclusion. +// This avoids circular dependencies since StepperQueue has no includes here. +// +// No includes in this file - types are provided by the including class. + +//========================================================================== +// QUEUE ALLOCATION +//========================================================================== +// Unified allocation interface - all platforms must implement. +// Validates the step pin and returns an allocated queue, or nullptr on failure. +// - For SUPPORT_DYNAMIC_ALLOCATION: allocates queue dynamically +// - For static allocation: returns pointer to pre-allocated queue slot +// - For SUPPORT_SELECT_DRIVER_TYPE (ESP32): allows choosing driver type +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +static StepperQueue* tryAllocateQueue(StepperMotionEngine* engine, + FasDriver driver, uint8_t step_pin); +#else +static StepperQueue* tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin); +#endif + +//========================================================================== +// QUEUE PROTOCOL METHODS +//========================================================================== + +AqeResultCode addQueueEntry(const struct stepper_command_s* cmd, bool start); +// Driver inserts the before/after direction-change pause commands (if any) +// into the queue. Does NOT enqueue cmd itself; the caller enqueues it +// afterwards. Always compiled, regardless of driver type. +AqeResultCode addDirChangePauseToQueue(const struct stepper_command_s* cmd, + bool start, + uint16_t dir_change_delay_ticks); +int32_t getCurrentPosition() const; +uint32_t ticksInQueue() const; +bool hasTicksInQueue(uint32_t min_ticks) const; +bool getActualTicksWithDirection(struct actual_ticks_s* speed) const; + +void init(uint8_t queue_num, uint8_t step_pin); +void startQueue(); +void forceStop(); +void _initVars(); +void connect(); +void disconnect(); + +//========================================================================== +// PREPROCESSOR PROTOCOL EXTENSIONS (defined in _queue.h) +//========================================================================== +// +// Setting direction/enable must be synchronized with step generation +// in order to avoid steps into wrong direction. +// Depending on the platform and driver capabilities, the direction/enable pin +// may be controlled in different ways, which are abstracted by the following +// macros. The platform-specific StepperQueue implementation defines these +// macros according to its capabilities, and the common addQueueEntry() logic +// uses them to control the direction/enable pins without needing to know the +// underlying implementation details. +// +// There are four possibilities for each pin (direction and enable): +// +// 1. Synchronized with commands +// - Pin state changes are synchronized with command execution in ISR +// - AVR, SAM, MCPWM, PICO for direction pin +// +// 2. Synchronized with buffer +// - Driver controls the pin, but timing need to follow rules to avoid +// race conditions with step pulses due to buffering in driver/ISR +// - Direction/enable applied at buffer boundaries +// - I2S-MUX: direction pin can be either in I2S bitstream or GPIO (same +// situation) +// - time delays depending on buffer size/buffer mechanism +// BEFORE/AFTER_DIR_CHANGE_DELAY_TICKS +// +// 3. Queue controlled +// - addQueueEntry() controls the pin directly as GPIO +// - fixed to 4ms task rate and need to ensure no steps in command queue +// (looking at the current or following command is not sufficient) +// +// 4. Externally controlled +// - Pin controlled via callback by application (e.g. using I/O expander) +// - addQueueEntry() manages callback completion with 4ms pause mechanism +// - Pin has PIN_EXTERNAL_FLAG set +// +// addQueueEntry() will use only these macros to control the direction pin, +// if defined. The macros are not used if dirPin is set to PIN_UNDEFINED +// or if PIN_EXTERNAL_FLAG is set (external control). +// +// === DIRECTION PIN HANDLING === +// +// SET_DIRECTION_PIN_STATE(q, high) +// Set direction pin to absolute HIGH or LOW state. +// PRECONDITION: NOT called for CONTROLLED_EXTERNAL pins (PIN_EXTERNAL_FLAG) +// Used by addQueueEntry() when queue is not running. +// Must be defined +// +// AFTER_SET_DIR_PIN_DELAY_US +// Microseconds to delay after directly setting direction pin state. +// Gives the driver hardware time to register the pin change. +// Only used when queue is empty and not running. +// If undefined, no delay. +// +// BEFORE_DIR_CHANGE_DELAY_TICKS(q) +// Ticks to pause BEFORE direction change entry appears in output. +// Used by addQueueEntry() to insert pause for buffered drivers. +// - Synchronized with commands: 0 +// - Synchronized with buffer (I2S-MUX): I2S_BLOCK_TICKS +// - Queue controlled (RMT): MIN_CMD_TICKS +// - Externally controlled: 0 +// If undefined, assume 0 +// +// AFTER_DIR_CHANGE_DELAY_TICKS(q) +// Minimum ticks for the direction change command itself. +// Ensures dir change is alone in buffer for synchronized-with-buffer case. +// - Synchronized with buffer (I2S-MUX): I2S_BLOCK_TICKS +// - All others: 0 (or undefined) +// If undefined, assume 0 +// +// === ENABLE PIN HANDLING === +// +// Enable pin control always happens in addQueueEntry() context (not ISR). +// The ~4ms processing delay is acceptable for enable/disable operations. +// +// SET_ENABLE_PIN_STATE_NEED_QUEUE +// SET_ENABLE_PIN_STATE(q, pin, high) +// Set enable pin to HIGH or LOW state. +// PRECONDITION: NOT called for CONTROLLED_EXTERNAL pins (PIN_EXTERNAL_FLAG) +// Must be defined + +#endif diff --git a/src/fas_queue/queue.h b/src/fas_queue/queue.h new file mode 100644 index 0000000..5049b3b --- /dev/null +++ b/src/fas_queue/queue.h @@ -0,0 +1,19 @@ +#ifndef FAS_QUEUE_QUEUE_H +#define FAS_QUEUE_QUEUE_H + +#include "fas_arch/common.h" +#include "fas_queue/base.h" + +class StepperQueue; + +#if defined(SUPPORT_DYNAMIC_ALLOCATION) +extern StepperQueue* fas_queue[NUM_QUEUES]; +#define FAS_QUEUE(idx) (*fas_queue[idx]) +#define FAS_QUEUE_PTR(idx) (fas_queue[idx]) +#else +extern StepperQueue fas_queue[NUM_QUEUES]; +#define FAS_QUEUE(idx) (fas_queue[idx]) +#define FAS_QUEUE_PTR(idx) (&fas_queue[idx]) +#endif + +#endif diff --git a/src/fas_queue/queue_add_entry.cpp b/src/fas_queue/queue_add_entry.cpp new file mode 100644 index 0000000..841beb4 --- /dev/null +++ b/src/fas_queue/queue_add_entry.cpp @@ -0,0 +1,168 @@ +#include + +#include "fas_queue/stepper_queue.h" + +AqeResultCode StepperQueue::addQueueEntry(const struct stepper_command_s* cmd, + bool start) { + // The admission latch gates the whole function, before every side effect. + // + // It used to sit at the pointer advance, which made it three separate bugs: + // a refused command still drove the DIR pin and updated queue_end.dir, still + // counted towards the pause statistics, and -- via the cmd == NULL path -- + // still let a suspended queue be started. It also returned AQE_OK, so the + // caller advanced its own position model by steps that were never queued. + // + // Checked first, before isReadyForCommands(), so the reason reported is the + // one that needs acting on: a suspended queue stays suspended until + // resumeCommands(), whereas DEVICE_NOT_READY is a retry. + if (ignore_commands) { + return AQE_ERROR_COMMANDS_SUSPENDED; + } + // Just to check if, if the struct has the correct size + // if (sizeof(entry) != 6 * QUEUE_LEN) { + // return -1; + //} + if (!isReadyForCommands()) { + return AQE_DEVICE_NOT_READY; + } + if (cmd == NULL) { + if (start && !isRunning()) { + if (next_write_idx == read_idx) { + return AQE_ERROR_EMPTY_QUEUE_TO_START; + } + startQueue(); + } + return AQE_OK; + } + if (isQueueFull()) { + return AQE_QUEUE_FULL; + } + uint16_t period = cmd->ticks; + uint8_t steps = cmd->steps; + +// #define TRACE +#ifdef TRACE + Serial.print(':'); + Serial.print(start ? "START" : "PUSH"); + Serial.print(':'); + Serial.print(cmd->count_up ? 'U' : 'D'); + Serial.print(':'); + Serial.print(steps); + Serial.print(':'); + Serial.print(period); + Serial.print('X'); +#endif + + uint32_t command_rate_ticks = period; + if (steps > 1) { + command_rate_ticks *= steps; + } + if (command_rate_ticks < MIN_CMD_TICKS) { + return AQE_ERROR_TICKS_TOO_LOW; + } + + uint8_t wp = next_write_idx; + struct queue_entry* e = &entry[wp & QUEUE_LEN_MASK]; + bool dir = (cmd->count_up == dirHighCountsUp); + bool toggle_dir = false; +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + bool dir_changed = false; +#endif +#if defined(SUPPORT_RP_PICO) + if (isQueueEmpty() && !isRunning()) { + // store the offset from pico sm's step count and position + pos_offset = queue_end.pos - getCurrentStepCount(); + } +#endif + if (dirPin != PIN_UNDEFINED) { +#if !defined(SUPPORT_PAUSE_CMD_COUNTING) + bool dir_changed; +#endif + dir_changed = (dir != queue_end.dir); + if ((isQueueEmpty() && !isRunning()) && + ((dirPin & PIN_EXTERNAL_FLAG) == 0)) { + // set the dirPin here. Necessary with shared direction pins + SET_DIRECTION_PIN_STATE(this, dir); +#if defined(AFTER_SET_DIR_PIN_DELAY_US) && AFTER_SET_DIR_PIN_DELAY_US > 0 + delayMicroseconds(AFTER_SET_DIR_PIN_DELAY_US); +#endif + queue_end.dir = dir; + } else { + toggle_dir = dir_changed; + } + } + + e->steps = steps; + e->dirPinState = dir; + e->toggle_dir = toggle_dir; + e->countUp = cmd->count_up ? 1 : 0; + e->hasSteps = steps > 0 ? 1 : 0; + e->ticks = period; + struct queue_end_s next_queue_end = queue_end; +#if defined(SUPPORT_QUEUE_ENTRY_START_POS_U16) + e->start_pos_last16 = (uint32_t)next_queue_end.pos & 0xffff; +#endif + next_queue_end.pos = next_queue_end.pos + (cmd->count_up ? steps : -steps); +#if defined(SUPPORT_QUEUE_ENTRY_END_POS_U16) + e->end_pos_last16 = (uint32_t)next_queue_end.pos & 0xffff; +#endif + next_queue_end.dir = dir; + next_queue_end.count_up = cmd->count_up; + + // Advance write pointer (wp may have been incremented for a pause entry). + // The admission latch was checked at the top, so there is no branch here for + // it: a suspended queue never reaches this point. + fasDisableInterrupts(); + if (isReadyForCommands()) { + next_write_idx = wp + 1; + queue_end = next_queue_end; + } else { + fasEnableInterrupts(); + return AQE_DEVICE_NOT_READY; + } + fasEnableInterrupts(); + + if (!isRunning() && start) { + // stepper is not yet running and start is requested +#ifdef TRACE + Serial.print('S'); +#endif + startQueue(); + } else { +#if defined(SUPPORT_RP_PICO) + // With PIO the feeder runs from the FIFO-not-full interrupt, which disables + // itself once the ring drains. Re-arm it here for a queue that is already + // running -- but only then. This branch is reached for start=false too, and + // an unconditional startQueue() made start=false a lie on Pico: a queue + // that was not running began stepping, so "fill the queue, then start it + // later" (QFILL, FasNAxis prefill -> synchronizedStart) could not work. + // start=false on an idle queue must leave it idle (StepperMotion.h: + // "If the queue is not running, then the start parameter defines starting + // it or not"). + if (isRunning()) { + startQueue(); + } +#endif +#ifdef TRACE + // WHY IS start 0 in seq_01c + Serial.print(isRunning() ? 'R' : 'T'); + Serial.print(start ? '1' : '0'); + Serial.println('N'); +#endif + } +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + if ((steps > 0) || dir_changed) { + clear_pause_stats(); + } else { + if (_nr_of_pauses < 255) { + _nr_of_pauses++; + } + if (65535 - _last_pause_ticks >= period) { + _last_pause_ticks += period; + } else { + _last_pause_ticks = 65535; + } + } +#endif + return AQE_OK; +} diff --git a/src/fas_queue/queue_get_position.cpp b/src/fas_queue/queue_get_position.cpp new file mode 100644 index 0000000..28bb19b --- /dev/null +++ b/src/fas_queue/queue_get_position.cpp @@ -0,0 +1,54 @@ +#include + +#include "fas_queue/stepper_queue.h" + +#if defined(NEED_GENERIC_GET_CURRENT_POSITION) +int32_t StepperQueue::getCurrentPosition() const { + fasDisableInterrupts(); + uint32_t pos = (uint32_t)queue_end.pos; + uint8_t rp = read_idx; + bool is_empty = (rp == next_write_idx); + if (is_empty) { + fasEnableInterrupts(); + return pos; + } + const struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + uint16_t pos_last16 = e->end_pos_last16; + uint8_t steps = e->steps; + fasEnableInterrupts(); + + uint16_t pos16 = pos & 0xffff; + uint8_t transition = ((pos16 >> 12) & 0x0c) | (pos_last16 >> 14); + switch (transition) { + case 0: // 00 00 + case 5: // 01 01 + case 10: // 10 10 + case 15: // 11 11 + break; + case 1: // 00 01 + case 6: // 01 10 + case 11: // 10 11 + case 12: // 11 00 + pos += 0x4000; + break; + case 4: // 01 00 + case 9: // 10 01 + case 14: // 11 10 + case 3: // 00 11 + pos -= 0x4000; + break; + case 2: // 00 10 + case 7: // 01 11 + case 8: // 10 00 + case 13: // 11 01 + break; // TODO: ERROR + } + pos = (int32_t)((pos & 0xffff0000) | pos_last16); + + if (steps != 0) { + int16_t adjust = e->countUp ? -(int16_t)steps : (int16_t)steps; + pos += adjust; + } + return pos; +} +#endif diff --git a/src/fas_queue/queue_init.cpp b/src/fas_queue/queue_init.cpp new file mode 100644 index 0000000..682203b --- /dev/null +++ b/src/fas_queue/queue_init.cpp @@ -0,0 +1,16 @@ +#include + +#include "fas_queue/stepper_queue.h" + +// Here are the global variables to interface with the interrupts +#if defined(SUPPORT_DYNAMIC_ALLOCATION) +StepperQueue* fas_queue[NUM_QUEUES] = {nullptr}; +#else +StepperQueue fas_queue[NUM_QUEUES]; +#endif + +void StepperQueue::_initVars() { + __builtin_memset(this, 0, sizeof(*this)); + _base_initVars(); + _pd_initVars(); +} diff --git a/src/fas_queue/queue_utils.cpp b/src/fas_queue/queue_utils.cpp new file mode 100644 index 0000000..d9c1e65 --- /dev/null +++ b/src/fas_queue/queue_utils.cpp @@ -0,0 +1,78 @@ +#include + +#include "fas_queue/stepper_queue.h" + +uint32_t StepperQueue::ticksInQueue() const { + fasDisableInterrupts(); + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + fasEnableInterrupts(); + if (wp == rp) { + return 0; + } + uint32_t ticks = 0; + rp++; // ignore currently processed entry + while (wp != rp) { + const struct queue_entry* e = &entry[rp++ & QUEUE_LEN_MASK]; + ticks += e->ticks; + uint8_t steps = e->steps; + if (steps > 1) { + uint32_t tmp = e->ticks; + tmp *= steps - 1; + ticks += tmp; + } + } + return ticks; +} + +bool StepperQueue::hasTicksInQueue(uint32_t min_ticks) const { + fasDisableInterrupts(); + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + fasEnableInterrupts(); + if (wp == rp) { + return false; + } + rp++; // ignore currently processed entry + while (wp != rp) { + const struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + uint32_t tmp = e->ticks; + uint8_t steps = fas_max(e->steps, (uint8_t)1); + tmp *= steps; + if (tmp >= min_ticks) { + return true; + } + min_ticks -= tmp; + rp++; + } + return false; +} + +bool StepperQueue::getActualTicksWithDirection( + struct actual_ticks_s* speed) const { + // Retrieve current step rate from the current command. + // This is valid only, if the command describes more than one step, + // or if the next command contains one step, too. + fasDisableInterrupts(); + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + fasEnableInterrupts(); + if (wp == rp) { + speed->ticks = 0; + return true; + } + const struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + if (e->hasSteps) { + speed->count_up = e->countUp; + speed->ticks = e->ticks; + if (e->steps > 1) { + return true; + } + if (wp != ++rp) { + if (entry[rp & QUEUE_LEN_MASK].hasSteps) { + return true; + } + } + } + return false; +} diff --git a/src/fas_queue/stepper_queue.h b/src/fas_queue/stepper_queue.h new file mode 100644 index 0000000..92f5d40 --- /dev/null +++ b/src/fas_queue/stepper_queue.h @@ -0,0 +1,36 @@ +#ifndef FAS_QUEUE_STEPPER_QUEUE_H +#define FAS_QUEUE_STEPPER_QUEUE_H + +#include + +#include "StepperMotion.h" +#include "fas_arch/common.h" +#include "fas_queue/queue.h" + +// The pd_ prefix in directory names stands for "pulse driver" (though "platform +// driver" is also suitable). +#if defined(SUPPORT_AVR) +#include "pd_avr/avr_queue.h" +#elif defined(TEST) +#include "pd_test/test_queue.h" +#elif defined(SUPPORT_TEENSY4) +#include "pd_teensy/teensy_queue.h" +#elif defined(SUPPORT_SAM) +#include "pd_sam/sam_queue.h" +#elif defined(SUPPORT_SAMD51) +#include "pd_samd/samd_queue.h" +#elif defined(SUPPORT_RP_PICO) +#include "pd_pico/pico_queue.h" +#elif defined(SUPPORT_ESP32) +#include "pd_esp32/esp32_queue.h" +#else +#error "Unsupported architecture" +#endif + +#if defined(SUPPORT_CPU_AFFINITY) +void fas_init_engine(StepperMotionEngine* engine, uint8_t cpu_core); +#else +void fas_init_engine(StepperMotionEngine* engine); +#endif + +#endif // FAS_QUEUE_STEPPER_QUEUE_H diff --git a/src/fas_ramp/RampCalculator.cpp b/src/fas_ramp/RampCalculator.cpp new file mode 100644 index 0000000..9eb0e5b --- /dev/null +++ b/src/fas_ramp/RampCalculator.cpp @@ -0,0 +1,176 @@ +#include "fas_ramp/RampCalculator.h" + +#include + +#include "fas_queue/stepper_queue.h" + +#ifdef TEST_TIMING +// This module has only one purpose: +// +// - To calculate for a given step the corresponding speed. +// +// With constant acceleration the relation between the steps s. acceleration a, +// time t and speed v will fulfill this equation during acceleration and +// deceleration: +// +// s = 0.5 * a * t² = 0.5 * v² / a +// +// Acceleration is just counting up the steps and deceleration counting down +// towards 0. +// +// From this equation the actual speed v at a given step can be calculated by: +// +// v = sqrt(2*s*a) +// +// For the pwm, the speed needs to be translated into time ticks T = n * +// timeticks = 1/v: +// +// n * timeticks = 1 / sqrt(2*s*a) +// +// If the µC would be fast, then the solution would be in floating point: +uint32_t calculate_ticks_v1(uint32_t steps, float acceleration) { + float n = TICKS_PER_S / sqrt(2.0 * steps * acceleration); + return n; +} +// Just this takes approx 92-4 = 88 us. Which is pretty slow. +// +// Little optimization improves to 87-4 = 83 us +uint32_t calculate_ticks_v2(uint32_t steps, float acceleration) { + float n = TICKS_PER_S / sqrt(2 * steps * acceleration); + return n; +} +// +// Precalculate TICKS_PER_S / sqrt(2 * acceleration) +// results in 80-4 = 76us +uint32_t calculate_ticks_v3(uint32_t steps, float pre_calc) { + float n = pre_calc / sqrt(steps); + return n; +} +// +// Using log2_value_t improves to 22-4 = 18us, but less precision +uint32_t calculate_ticks_v4(uint32_t steps, uint32_t acceleration) { + log2_value_t log2_a = log2_from(acceleration); + log2_value_t log2_s = log2_from(steps); + log2_value_t log2_res = + log2_divide(LOG2_TICKS_PER_S, log2_sqrt(log2_multiply(log2_s, log2_a))); + uint32_t res = log2_to_u32(log2_res); + return res; +} +// +// Precalculating the acceleration related constant improves further to 12-4 = +// 8us. This measurement was actually done with ump_float. +// So this routine does not fit to that measurement anymore +// +uint32_t calculate_ticks_v5(uint32_t steps, log2_value_t pre_calc) { + log2_value_t log2_s = log2_from(steps); + log2_value_t log2_res = log2_divide(pre_calc, log2_sqrt(log2_s)); + uint32_t res = log2_to_u32(log2_res); + return res; +} +// +// using the combined function yields actually no measureable improvement +uint32_t calculate_ticks_v6(uint32_t steps, log2_value_t pre_calc) { + // log2_value_t log2_s = log2_from(steps); + // log2_value_t log2_res = log2_sqrt_after_divide(pre_calc, log2_s); + // uint32_t res = log2_to_u32(log2_res); + // return res; + return calculate_ticks_v5(steps, pre_calc); +} +// +// In order to increase the precision to more than 8 bits and avoid +// the penalty of slow float operations different approach will be used. +// +// in order to avoid division+sqrt operation, the following equation will be +// rearranged: +// +// n * timeticks = 1 / sqrt(2*s*a) +// +// into: +// +// n² * s = 1 / sqrt(2*a) / timeticks² +// +// with the right part being constant for a given acceleration a +// +// n² * s = const(a) +// +// This can be solved iteratively +// +// n_0 = 0 +// n_i +// n_[i+1] = { with n_i² * s <= const(a) < (n_i +// + mask_i)² * s +// n_i + mask_i +// +// mask_[i+1] = mask_i >> 1 +// +// In order to avoid the square calculation in each step several temporary +// values need to be calculated +// n_i² * s = f_i +// f_[i+1] = n_[i+1]² * s = { with same condition +// as before +// (n_i + mask_i)² * s +// +// For the lower case the calculation continues: +// +// = n_i² * s + 2 * n_i * mask_i * s + mask_i² * s +// +// = f_i + g_i + h_i +// +// With g_i and h_i defined like this: +// +// g_0 = 0 +// +// g_[i+1] = 2 * n_[i+1] * mask_[i+1] * s +// +// 2 * n_i * (mask_i >> 1) * s = g_i >> 1 +// = { +// 2 * (n_i + mask_i) * (mask_i >> 1) * s = +//(g_i +//>> 1) + (mask_i² * s) +// = (g_i >> 1) + h_i +// +// h_0 = mask_0 ² * s +// +// h_[i+1] = mask_[i+1]² * s +// = (mask_i >> 1)² * s +// = h_i >> 2 +// +// Actually this is a dead end, because below routines already needs 35us, +// while several variables below ought to be 32bit +uint32_t calculate_ticks_v7(uint32_t steps, log2_value_t pre_calc) { + // initial values for i = 0 + uint16_t mask_i = 0x800; + uint16_t n_i = 0; + uint16_t f_i = 0; + uint16_t g_i = 0; + uint16_t h_i = steps; + uint16_t const_a = pre_calc; + + while (mask_i) { + uint16_t f_x = f_i + g_i + h_i; + // Serial.println(f_x); + if (f_x < const_a) { + n_i += mask_i; + f_i = f_x; + g_i >>= 1; + g_i += h_i; + h_i >>= 2; + mask_i >>= 1; + } else { + g_i >>= 1; + h_i >>= 2; + mask_i >>= 1; + } + } + return n_i; +} + +// Computes the pulse interval from the acceleration ramp step. +uint32_t calculate_ticks_v8(uint32_t steps, log2_value_t pre_calc) { + log2_value_t log2_steps = log2_from(steps); + log2_value_t log2_sqrt_steps = log2_sqrt(log2_steps); + log2_value_t log2_res = log2_divide(pre_calc, log2_sqrt_steps); + uint32_t res = log2_to_u32(log2_res); + return res; +} +#endif diff --git a/src/fas_ramp/RampCalculator.h b/src/fas_ramp/RampCalculator.h new file mode 100644 index 0000000..da5fa2e --- /dev/null +++ b/src/fas_ramp/RampCalculator.h @@ -0,0 +1,232 @@ +#ifndef RAMP_CALCULATOR_H +#define RAMP_CALCULATOR_H + +#include + +#include "log2/Log2Representation.h" +#include "fas_arch/common.h" + +#if (TICKS_PER_S == 16000000L) +#define LOG2_TICKS_PER_S LOG2_CONST_16E6 +#define LOG2_TICKS_PER_S_DIV_SQRT_OF_2 LOG2_CONST_16E6_DIV_SQRT_OF_2 +#define LOG2_ACCEL_FACTOR LOG2_CONST_128E12 +#define US_TO_TICKS(u32) ((u32) * 16) +#define TICKS_TO_US(u32) ((u32) / 16) +#elif (TICKS_PER_S == 21000000L) +#define LOG2_TICKS_PER_S LOG2_CONST_21E6 +#define LOG2_TICKS_PER_S_DIV_SQRT_OF_2 LOG2_CONST_21E6_DIV_SQRT_OF_2 +#define LOG2_ACCEL_FACTOR LOG2_CONST_2205E11 +#define US_TO_TICKS(u32) ((u32) * 21) +#define TICKS_TO_US(u32) ((u32) / 21) +#else +#define SUPPORT_LOG2_TIMER_FREQ_VARIABLES +// Declared here (not in RampGenerator.h, which includes this file before +// its own copy of these declarations) because the inline methods below - +// evaluated as soon as this header is parsed - already need them. +// Defined (non-static, exactly once) in RampControl.cpp. +extern log2_value_t log2_timer_freq; +extern log2_value_t log2_timer_freq_div_sqrt_of_2; +extern log2_value_t log2_timer_freq_square_div_2; +#define LOG2_TICKS_PER_S log2_timer_freq +#define LOG2_TICKS_PER_S_DIV_SQRT_OF_2 log2_timer_freq_div_sqrt_of_2 +#define LOG2_ACCEL_FACTOR log2_timer_freq_square_div_2 +// This overflows for approx. 1s at 40 MHz, only +#define US_TO_TICKS(u32) \ + ((uint32_t)((((uint32_t)((u32) * (TICKS_PER_S / 10000L))) / 100L))) + +// This calculation needs more work +#define TICKS_TO_US(u32) \ + ((uint32_t)((((uint32_t)((u32) / (TICKS_PER_S / 1000000L))) / 1L))) + +#endif + +#ifdef TEST_TIMING +uint32_t calculate_ticks_v1(uint32_t steps, float acceleration); +uint32_t calculate_ticks_v2(uint32_t steps, float acceleration); +uint32_t calculate_ticks_v3(uint32_t steps, float pre_calc); +uint32_t calculate_ticks_v4(uint32_t steps, uint32_t acceleration); +uint32_t calculate_ticks_v5(uint32_t steps, log2_value_t pre_calc); +uint32_t calculate_ticks_v6(uint32_t steps, log2_value_t pre_calc); +uint32_t calculate_ticks_v7(uint32_t steps, log2_value_t pre_calc); +uint32_t calculate_ticks_v8(uint32_t steps, log2_value_t pre_calc); +#endif + +struct ramp_parameters_s { + int32_t move_value; + uint32_t min_travel_ticks; + uint32_t s_h; + uint32_t s_jump; + log2_value_t log2_accel; + bool apply : 1; // clear on read by stepper task. Triggers read ! + bool any_change : 1; // clear on read by stepper task + bool recalc_ramp_steps : 1; // clear on read by stepper task + bool valid_acceleration : 1; + bool valid_speed : 1; + bool move_absolute : 1; + bool keep_running : 1; + bool keep_running_count_up : 1; + + void init() { + __builtin_memset(this, 0, sizeof(*this)); + move_absolute = true; + keep_running_count_up = true; + } + inline void applyParameters() { + if (any_change) { + fasDisableInterrupts(); + apply = true; + fasEnableInterrupts(); + } + } + inline void setRunning(bool count_up) { + fasDisableInterrupts(); + keep_running = true; + keep_running_count_up = count_up; + any_change = true; + apply = true; + fasEnableInterrupts(); + } + inline void setTargetPosition(int32_t pos) { + fasDisableInterrupts(); + move_value = pos; + move_absolute = true; + keep_running = false; + keep_running_count_up = true; + any_change = true; + apply = true; + fasEnableInterrupts(); + } + inline void setTargetRelativePosition(int32_t move) { + fasDisableInterrupts(); + if (any_change && !move_absolute) { + move_value += move; + } else { + move_value = move; + } + move_absolute = false; + keep_running = false; + keep_running_count_up = true; + any_change = true; + apply = true; + fasEnableInterrupts(); + } + inline void setCubicAccelerationSteps(uint32_t s_cubic_steps) { + if (s_h != s_cubic_steps) { + fasDisableInterrupts(); + s_h = s_cubic_steps; + recalc_ramp_steps = true; + any_change = true; + fasEnableInterrupts(); + } + } + inline void setSpeedInTicks(uint32_t min_step_ticks) { + if (!valid_speed || (min_travel_ticks != min_step_ticks)) { + fasDisableInterrupts(); + min_travel_ticks = min_step_ticks; + valid_speed = true; + any_change = true; + fasEnableInterrupts(); + } + } + inline void setAcceleration(int32_t accel) { + log2_value_t new_log2_accel = log2_from((uint32_t)accel); + if (!valid_acceleration || (log2_accel != new_log2_accel)) { + fasDisableInterrupts(); + valid_acceleration = true; + any_change = true; + recalc_ramp_steps = true; + log2_accel = new_log2_accel; + fasEnableInterrupts(); + } + } + inline void setJumpStart(uint32_t jump_step) { s_jump = jump_step; } + inline MoveResultCode checkValidConfig() const { + if (!valid_speed) { + return MOVE_ERR_SPEED_IS_UNDEFINED; + } + if (!valid_acceleration) { + return MOVE_ERR_ACCELERATION_IS_UNDEFINED; + } + return MOVE_OK; + } +}; + +struct ramp_config_s { + struct ramp_parameters_s parameters; + + // These three variables are derived + uint32_t max_ramp_up_steps; + log2_value_t log2_ticks_h; + log2_value_t cubic; + + void init() { parameters.init(); } + inline void update() { + if (parameters.s_h > 0) { + log2_value_t log2_s_h = log2_from(parameters.s_h); + // 1/cubic = sqrt(3/2 * a) / s_h^(1/6) / TICKS_PER_S + // = sqrt(3/2 * a / s_h^(1/3)) / TICKS_PER_S + // cubic = TICKS_PER_S / sqrt(s_h^(1/3) / (3/2 * a)) + cubic = log2_multiply(LOG2_CONST_3_DIV_2, parameters.log2_accel); + cubic = log2_sqrt(log2_divide(log2_pow_div_3(log2_s_h), cubic)); + cubic = log2_multiply(LOG2_TICKS_PER_S, cubic); + + // calculate_ticks(s_h) + log2_ticks_h = log2_divide(cubic, log2_pow_2_div_3(log2_s_h)); + } else { + log2_ticks_h = LOG2_CONST_MAX; + } + max_ramp_up_steps = calculate_ramp_steps(parameters.min_travel_ticks); + if (max_ramp_up_steps == 0) { + max_ramp_up_steps = 1; + } +#ifdef TRACE + printf("MAX_RAMP_UP_STEPS=%d from %d ticks\n", max_ramp_up_steps, + parameters.min_travel_ticks); +#endif + } + + uint32_t calculate_ticks(uint32_t steps) const { + // s = 1/2 * a * t^2 + // 2*a*s = (a*t)^2 = v^2 = (TICKS_PER_S/ticks)^2 + // ticks = TICKS_PER_S / sqrt(2*a*s) + // ticks = TICKS_PER_S/sqrt(2) / sqrt(a*s) + if (steps >= parameters.s_h) { + steps -= (parameters.s_h + 2) >> 2; + log2_value_t log2_steps = log2_from(steps); + log2_value_t log2_steps_mul_accel = + log2_multiply(log2_steps, parameters.log2_accel); + log2_value_t log2_sqrt_steps_mul_accel = log2_sqrt(log2_steps_mul_accel); + log2_value_t log2_res = log2_divide(LOG2_TICKS_PER_S_DIV_SQRT_OF_2, + log2_sqrt_steps_mul_accel); + uint32_t res = log2_to_u32(log2_res); + return res; + } + // ticks = cubic / s^(2/3) + log2_value_t log2_steps = log2_from(steps); + log2_value_t log2_res = log2_divide(cubic, log2_pow_2_div_3(log2_steps)); + uint32_t res = log2_to_u32(log2_res); + return res; + } + uint32_t calculate_ramp_steps(uint32_t ticks) const { + // log2 is in range -64..<64 due to shift by 1 + // log2_ticks is in range 0..<32 + // log2_accel is in range 0..<32 + // LOG2_ACCEL_FACTOR is approx. 47 for 16 Mticks/s + // log2_ticks squared is in range 0..<64 + log2_value_t log2_ticks = log2_from(ticks); + if (log2_ticks <= log2_ticks_h) { + log2_value_t log2_inv_accel2 = + log2_divide(LOG2_ACCEL_FACTOR, parameters.log2_accel); + uint32_t steps = + log2_to_u32(log2_divide(log2_inv_accel2, log2_square(log2_ticks))); + steps += (parameters.s_h + 2) >> 2; + return steps; + } + // s = (cubic/ticks)^(3/2) + log2_value_t log2_res = log2_divide(cubic, log2_ticks); + log2_res = log2_pow_3_div_2(log2_res); + uint32_t steps = log2_to_u32(log2_res); + return steps; + } +}; +#endif diff --git a/src/fas_ramp/RampControl.cpp b/src/fas_ramp/RampControl.cpp new file mode 100644 index 0000000..fc92235 --- /dev/null +++ b/src/fas_ramp/RampControl.cpp @@ -0,0 +1,563 @@ +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +#include "fas_ramp/RampControl.h" +#include "fas_arch/common.h" + +#ifdef SUPPORT_LOG2_TIMER_FREQ_VARIABLES +// Definitions for the `extern` declarations in RampCalculator.h. Must have +// external linkage (no `static`): RampGenerator.cpp, a separate translation +// unit, also uses these via the LOG2_TICKS_PER_S* macros in RampCalculator.h. +log2_value_t log2_timer_freq; +log2_value_t log2_timer_freq_div_sqrt_of_2; +log2_value_t log2_timer_freq_square_div_2; +#endif + +void ramp_rw_s::init() { + __builtin_memset(this, 0, sizeof(*this)); + curr_ticks = TICKS_FOR_STOPPED_MOTOR; +} + +void init_ramp_module() { +#ifdef SUPPORT_LOG2_TIMER_FREQ_VARIABLES + log2_timer_freq = log2_from((uint32_t)TICKS_PER_S); + // freq / sqrt(2): -0.5 in log2 space. 1 raw unit = 1/512 (see + // Log2Representation.h), so -0.5 is -256 raw units. Previously this used + // log2_multiply(log2_timer_freq, log2_timer_freq) - a copy-paste of the + // line below, computing freq^2 instead - making this identical to + // log2_timer_freq_square_div_2 and producing wildly wrong (huge) tick + // counts for the small-steps/near-standstill case (calculate_ticks() / + // calculate_ramp_steps()'s non-cubic branch, only reachable when + // setLinearAcceleration() is unused, i.e. s_h == 0). This was the cause + // of the stepper "hanging" for minutes on a ramp start/reversal from + // standstill during Teensy 4.0 bring-up. + log2_timer_freq_div_sqrt_of_2 = (log2_value_t)(log2_timer_freq - 256); + log2_timer_freq_square_div_2 = log2_shr(log2_square(log2_timer_freq), 1); +#endif +} + +//************************************************************************************************* + +// #define TRACE +#ifdef TRACE +#ifdef TEST +#define TRACE_OUTPUT(x) printf(": %c \n", x) +#endif +#else +#define TRACE_OUTPUT(x) +#endif + +#ifdef TEST +void print_ramp_state(uint8_t this_state) { + switch (this_state & RAMP_DIRECTION_MASK) { + case RAMP_DIRECTION_COUNT_UP: + printf("+"); + break; + case RAMP_DIRECTION_COUNT_DOWN: + printf("-"); + break; + } + switch (this_state & RAMP_STATE_MASK) { + case RAMP_STATE_COAST: + printf("COAST"); + break; + case RAMP_STATE_ACCELERATE: + printf("ACC"); + break; + case RAMP_STATE_DECELERATE: + printf("DEC"); + break; + case RAMP_STATE_REVERSE: + printf("REVERSE"); + break; + } +} +#endif + +//************************************************************************************************* +void _getNextCommand(const struct ramp_ro_s* ramp, const struct ramp_rw_s* rw, + const struct queue_end_s* queue_end, + NextCommand* command) { + { + // If there is a pause from last step, then just output a pause + uint32_t pause_ticks = rw->pause_ticks_left; + if (pause_ticks > 0) { + if (pause_ticks > 65535) { + pause_ticks >>= 1; + pause_ticks = fas_min(pause_ticks, 65535); + } + command->command.ticks = pause_ticks; + command->command.steps = 0; + command->command.count_up = queue_end->count_up; + command->rw = *rw; + command->rw.pause_ticks_left -= pause_ticks; +#ifdef TEST + printf("add command pause ticks = %d remaining pause = %d\n", + pause_ticks, command->rw.pause_ticks_left); +#endif + return; + } + } + + bool count_up = queue_end->count_up; + + // check state for acceleration/deceleration or deceleration to stop + uint8_t this_state; + uint32_t remaining_steps; + bool need_count_up; + if (ramp->config.parameters.keep_running) { + need_count_up = ramp->config.parameters.keep_running_count_up; + remaining_steps = 0xfffffff; + } else { + // this can overflow, which is legal + int32_t delta = ramp->target_pos - queue_end->pos; + + if (delta == 0) { + // this case can happen on overshoot. So reverse current direction + need_count_up = !count_up; + } else { + need_count_up = delta > 0; + } + remaining_steps = fas_abs(delta); + } + + uint32_t performed_ramp_up_steps = rw->performed_ramp_up_steps; + +#ifdef TRACE + if (remaining_steps == performed_ramp_up_steps) { + TRACE_OUTPUT('='); + } else if (remaining_steps > performed_ramp_up_steps) { + uint32_t dx = remaining_steps - performed_ramp_up_steps; + if (dx < 10) { + char ch = '0' + dx; + TRACE_OUTPUT(ch); + TRACE_OUTPUT('x'); + } + } else { + uint32_t dx = performed_ramp_up_steps - remaining_steps; + if (dx < 10) { + char ch = '0' + dx; + TRACE_OUTPUT(ch); + TRACE_OUTPUT('y'); + } + } +#endif + + // If not moving, then use requested direction + if (performed_ramp_up_steps == 0) { + count_up = need_count_up; + } + + if ((remaining_steps == 0) && (performed_ramp_up_steps <= 1)) { + command->command.ticks = 0; + command->rw.pause_ticks_left = 0; + command->rw.ramp_state = RAMP_STATE_IDLE; + command->rw.curr_ticks = TICKS_FOR_STOPPED_MOTOR; +#ifdef TEST + puts("ramp complete"); +#endif + return; + } + + uint32_t curr_ticks = rw->curr_ticks; + + // Forward planning of 2ms or more on slow speed. + uint16_t planning_steps; + if (curr_ticks < TICKS_PER_S / 1000) { + uint16_t ps = TICKS_PER_S / 500; + ps /= (uint16_t)curr_ticks; + planning_steps = ps; + } else { + planning_steps = 1; + } + uint16_t orig_planning_steps = planning_steps; + + // In case of force stop just run down the ramp + if (count_up != need_count_up) { + // On direction change, do reversing + this_state = RAMP_STATE_REVERSE; + remaining_steps = performed_ramp_up_steps; + } else { + // If come here, then direction is same as current movement + if (remaining_steps == performed_ramp_up_steps) { + this_state = RAMP_STATE_DECELERATE; + // remaining_steps = performed_ramp_up_steps; + } else if (remaining_steps < performed_ramp_up_steps) { + // We will overshoot + TRACE_OUTPUT('O'); + this_state = RAMP_STATE_REVERSE; + remaining_steps = performed_ramp_up_steps; + } else if (ramp->config.parameters.min_travel_ticks < rw->curr_ticks) { + this_state = RAMP_STATE_ACCELERATE; + if (rw->curr_ticks < 2 * MIN_CMD_TICKS) { + // special consideration needed, that invalid commands are not generated + // + // possible coast steps is divided by 4: 1 part acc, 2 part coast, 1 + // part dec + uint32_t possible_coast_steps = + (remaining_steps - performed_ramp_up_steps) >> 2; +#ifdef TEST + printf("possible coast steps %d, prus=%d\n", possible_coast_steps, + performed_ramp_up_steps); +#endif + if ((possible_coast_steps > 0) && (possible_coast_steps <= 510)) { + // curr_ticks is not necessarily correct due to speed increase + uint32_t coast_time = possible_coast_steps * rw->curr_ticks; + if (coast_time < 2 * MIN_CMD_TICKS) { + TRACE_OUTPUT('l'); + this_state = RAMP_STATE_COAST; +#ifdef TEST + printf("high speed coast %d %d coast_time=%d\n", + possible_coast_steps, + remaining_steps - performed_ramp_up_steps, coast_time); +#endif + } + } + if (planning_steps > remaining_steps - performed_ramp_up_steps) { + this_state = RAMP_STATE_DECELERATE; + } + } else if (remaining_steps - performed_ramp_up_steps < + 2 * planning_steps) { + if (curr_ticks != TICKS_FOR_STOPPED_MOTOR) { + this_state = RAMP_STATE_COAST; + planning_steps = remaining_steps - performed_ramp_up_steps; + } + } + } else if (ramp->config.parameters.min_travel_ticks > rw->curr_ticks) { + TRACE_OUTPUT('d'); + this_state = RAMP_STATE_DECELERATE; + if (performed_ramp_up_steps <= planning_steps) { + if (performed_ramp_up_steps > 0) { + planning_steps = performed_ramp_up_steps; + } else { + planning_steps = 1; + } + } + } else { + TRACE_OUTPUT('c'); + this_state = RAMP_STATE_COAST; + uint32_t possible_coast_steps = remaining_steps - performed_ramp_up_steps; + if (possible_coast_steps < 2 * planning_steps) { + planning_steps = possible_coast_steps; + if (curr_ticks < MIN_CMD_TICKS) { + uint32_t cmd_ticks = curr_ticks * planning_steps; + if (cmd_ticks < MIN_CMD_TICKS) { + this_state = RAMP_STATE_DECELERATE; + } + } + } + } + } + if (remaining_steps == 0) { // This implies performed_ramp_up_steps == 0 + command->command.ticks = 0; + command->rw.pause_ticks_left = 0; + command->rw.ramp_state = RAMP_STATE_IDLE; + command->rw.curr_ticks = TICKS_FOR_STOPPED_MOTOR; +#ifdef TEST + puts("ramp complete"); +#endif + return; + } + + // Guarantee here: + // remaining_steps > 0 + // remaining_steps >= performed_ramp_up_steps + // remaining_steps > performed_ramp_up_steps, in COAST + // performed_ramp_up_steps can be 0 + // planning_steps >= 1 +#ifdef TEST + assert(remaining_steps > 0); + assert(remaining_steps >= performed_ramp_up_steps); + assert((remaining_steps > performed_ramp_up_steps) || + (this_state != RAMP_STATE_COAST)); + assert(planning_steps > 0); +#endif + +#ifdef TEST + printf("prus=%d planning_steps=%d remaining_steps=%d force_stop=%d\n", + performed_ramp_up_steps, planning_steps, remaining_steps, + ramp->force_stop); +#endif + uint32_t d_ticks_new; + { + if (this_state & RAMP_STATE_ACCELERATING_FLAG) { + TRACE_OUTPUT('A'); + // do not overshoot ramp down start + // + // seems to be not necessary, as consideration already done above + uint32_t dec_steps = remaining_steps - performed_ramp_up_steps; + if (dec_steps < 512) { + // Only allow half, cause the steps accelerating need to decelerate, too + uint16_t dec_steps_u16 = (uint16_t)dec_steps; + dec_steps_u16 /= 2; + // Perhaps it would be better to coast instead + // consideration has been done above already + if (dec_steps_u16 < orig_planning_steps) { + planning_steps = dec_steps_u16; + if (planning_steps == 0) { + planning_steps = 1; + } +#ifdef TEST + printf("Change planning_steps=%u\n", planning_steps); +#endif + } + } + + uint32_t rs = performed_ramp_up_steps + planning_steps; + d_ticks_new = ramp->config.calculate_ticks(rs); +#ifdef TEST + printf("Calculate d_ticks_new=%u from ramp steps=%u\n", d_ticks_new, rs); +#endif + + // if acceleration is very high, then d_ticks_new can be lower than + // min_travel_ticks + if (d_ticks_new < ramp->config.parameters.min_travel_ticks) { + d_ticks_new = ramp->config.parameters.min_travel_ticks; + } + } else if (this_state & RAMP_STATE_DECELERATING_FLAG) { + TRACE_OUTPUT('D'); + if (performed_ramp_up_steps == 1) { + d_ticks_new = ramp->config.parameters.min_travel_ticks; +#ifdef TEST + printf("Set d_ticks_new=%u to min_travel_ticks\n", d_ticks_new); +#endif + } else { + uint32_t rs; + if (performed_ramp_up_steps <= planning_steps) { + rs = planning_steps; + } else { + rs = performed_ramp_up_steps - planning_steps; + } + d_ticks_new = ramp->config.calculate_ticks(rs); +#ifdef TEST + printf("Calculate d_ticks_new=%d from ramp steps=%d for deceleration\n", + d_ticks_new, rs); +#endif + // If the ramp generator cannot decelerate by going down the ramp, + // then we need to clip the new d_ticks to the min travel ticks + // This is for issue #150 + uint32_t min_travel_ticks = ramp->config.parameters.min_travel_ticks; + if ((rs == 1) && (min_travel_ticks > d_ticks_new)) { + d_ticks_new = min_travel_ticks; +#ifdef TEST + printf("Clip d_ticks_new=%d for deceleration\n", d_ticks_new); +#endif + } + } + } else { + TRACE_OUTPUT('C'); + d_ticks_new = rw->curr_ticks; + // do not overshoot ramp down start + uint32_t coast_steps = remaining_steps - performed_ramp_up_steps; + if (coast_steps < 256) { + uint16_t coast_steps_u16 = coast_steps; + if (coast_steps_u16 < 2 * orig_planning_steps) { + planning_steps = coast_steps_u16; + } + } +#ifdef TEST + printf("planning steps=%d remaining steps=%d\n", planning_steps, + remaining_steps); +#endif + } + } + + // The above plannings_steps evaluation uses curr_ticks, + // but new_ticks can be lower and so the command time not sufficient + if (d_ticks_new < MIN_CMD_TICKS) { + uint32_t cmd_ticks = d_ticks_new * planning_steps; + if (cmd_ticks < MIN_CMD_TICKS) { + // using planning_steps and d_ticks_new would create invalid commands + + uint16_t steps = MIN_CMD_TICKS + d_ticks_new - 1; + steps /= ((uint16_t)d_ticks_new); +#ifdef TEST + printf("new steps=%d d_ticks_new=%d\n", steps, d_ticks_new); +#endif + if (steps >= remaining_steps) { +#ifdef TEST + printf( + "command time too low, with increased steps will reach ramp end\n"); +#endif + planning_steps = remaining_steps; + this_state = RAMP_STATE_DECELERATE; + } + + // if we are at ramp end, then reduce speed + steps = fas_max(planning_steps, steps); + if (2 * steps >= remaining_steps) { + d_ticks_new = MIN_CMD_TICKS + remaining_steps - 1; + d_ticks_new /= remaining_steps; + planning_steps = remaining_steps; + this_state = RAMP_STATE_DECELERATE; +#ifdef TEST + printf("command time too low, so reduce speed to %d ticks\n", + d_ticks_new); +#endif + } else { +#ifdef TEST + printf("Increase planning steps %d => %d due to command time\n", + planning_steps, steps); +#endif + planning_steps = steps; + + // do we need to decelerate in order to not overshoot ? + if (remaining_steps < performed_ramp_up_steps + planning_steps) { + this_state = RAMP_STATE_DECELERATE; + + // and now the speed is actually too high.... + } + } + } + } + + // perform clipping with current ticks + uint32_t next_ticks = d_ticks_new; + if (curr_ticks != TICKS_FOR_STOPPED_MOTOR) { + if (this_state & RAMP_STATE_ACCELERATING_FLAG) { + next_ticks = fas_min(next_ticks, curr_ticks); + } else if (this_state & RAMP_STATE_DECELERATING_FLAG) { + // CLIPPING: avoid reduction unless curr_ticks indicates stopped motor + // Issue #25: root cause is, that curr_ticks can be + // TICKS_FOR_STOPPED_MOTOR for the case, that queue is emptied before + // the next command is issued + next_ticks = fas_max(next_ticks, curr_ticks); + // if (this_state != RAMP_STATE_DECELERATE) { + // next_ticks = fas_max(next_ticks, ramp->config.min_travel_ticks); + // } + } + } +#ifdef TEST + assert(next_ticks > 0); +#endif +#ifdef TEST + if (next_ticks != d_ticks_new) { + printf( + "Clipping result d_ticks_new=%d => next_ticks=%d with curr_ticks=%d " + "state=%d\n", + d_ticks_new, next_ticks, curr_ticks, this_state); + } +#endif + +#ifdef TEST + printf("planning steps=%d remaining steps=%d prus=%d\n", planning_steps, + remaining_steps, performed_ramp_up_steps); +#endif + // Number of steps to execute with limitation to min 1 and max remaining steps + uint16_t steps = planning_steps; + steps = fas_min(steps, remaining_steps); // This could be problematic + steps = fas_max(steps, 1); + steps = fas_min(255, steps); + + // Check if pauses need to be added. If yes, reduce next_ticks and calculate + // pause_ticks_left + uint32_t pause_ticks_left; + if (next_ticks > 65535) { + steps = 1; + pause_ticks_left = next_ticks; + next_ticks >>= 1; + next_ticks = fas_min(next_ticks, 65535); + pause_ticks_left -= next_ticks; + } else { + pause_ticks_left = 0; + } + + // determine performed_ramp_up_steps after command enqueued + if (this_state & RAMP_STATE_ACCELERATING_FLAG) { + performed_ramp_up_steps += steps; + } else if (this_state & RAMP_STATE_DECELERATING_FLAG) { + if (performed_ramp_up_steps < steps) { + // This can occur with performed_ramp_up_steps = 0 and steps = 1 +#ifdef TEST + printf("prus=%d steps=%d\n", performed_ramp_up_steps, steps); +// assert((performed_ramp_up_steps == 0) && (steps == 1)); +#endif + // based on above assumption actually obsolete + performed_ramp_up_steps = 0; + } else { + uint32_t max_ramp_up_steps = ramp->config.max_ramp_up_steps; +#ifdef TEST + printf("prus=%d steps=%d max_prus=%d\n", performed_ramp_up_steps, steps, + max_ramp_up_steps); +#endif + if (performed_ramp_up_steps > max_ramp_up_steps) { +#ifdef TEST + printf("reduce prus=%d by %d\n", performed_ramp_up_steps, steps); +#endif + performed_ramp_up_steps -= steps; + } else if ((performed_ramp_up_steps >= max_ramp_up_steps) && + (max_ramp_up_steps + steps <= remaining_steps) && + (performed_ramp_up_steps - steps < max_ramp_up_steps)) { + // Speed was too high. So we need to ensure to not overshoot + // deceleration +#ifdef TEST + printf("clip prus=%d to %d\n", performed_ramp_up_steps, + max_ramp_up_steps); +#endif + performed_ramp_up_steps = max_ramp_up_steps; + next_ticks = ramp->config.parameters.min_travel_ticks; + if (next_ticks > 65535) { + steps = 1; + pause_ticks_left = next_ticks; + next_ticks >>= 1; + next_ticks = fas_min(next_ticks, (uint32_t)65535); + pause_ticks_left -= next_ticks; + } else { + pause_ticks_left = 0; + } + } else { + if (remaining_steps > performed_ramp_up_steps) { + if (remaining_steps - performed_ramp_up_steps < steps) { + performed_ramp_up_steps = remaining_steps - steps; +#ifdef TEST + printf("set prus to remaining steps %d minus %d steps\n", + remaining_steps, steps); +#endif + } + } else { + performed_ramp_up_steps -= steps; +#ifdef TEST + printf("reduce prus by %d steps\n", steps); +#endif + } + } + } + } + + if (count_up) { + this_state |= RAMP_DIRECTION_COUNT_UP; + } else { + this_state |= RAMP_DIRECTION_COUNT_DOWN; + } + + command->command.ticks = next_ticks; + command->command.steps = steps; + command->command.count_up = count_up; + + command->rw.ramp_state = this_state; + command->rw.performed_ramp_up_steps = performed_ramp_up_steps; + command->rw.pause_ticks_left = pause_ticks_left; + command->rw.curr_ticks = pause_ticks_left + next_ticks; + +#ifdef TEST + printf( + "pos@queue_end=%d remaining=%u prus=%u planning steps=%d " + "last_ticks=%u travel_ticks=%u ", + queue_end->pos, remaining_steps, performed_ramp_up_steps, planning_steps, + rw->curr_ticks, ramp->config.parameters.min_travel_ticks); + print_ramp_state(this_state); + printf("\n"); + printf( + "add command Steps=%u ticks=%u Target pos=%u " + "Remaining steps=%u, planning_steps=%u, " + "d_ticks_new=%u, pause_left=%u\n", + steps, next_ticks, ramp->target_pos, remaining_steps, planning_steps, + d_ticks_new, pause_ticks_left); + if ((this_state & RAMP_STATE_MASK) == RAMP_STATE_ACCELERATE) { + assert(pause_ticks_left + next_ticks >= + ramp->config.parameters.min_travel_ticks); + } +#endif +} diff --git a/src/fas_ramp/RampControl.h b/src/fas_ramp/RampControl.h new file mode 100644 index 0000000..aa2d0a8 --- /dev/null +++ b/src/fas_ramp/RampControl.h @@ -0,0 +1,70 @@ +#ifndef RAMP_CONTROL_H +#define RAMP_CONTROL_H + +#include "fas_ramp/RampCalculator.h" +#include "fas_arch/common.h" + +struct ramp_ro_s { + struct ramp_config_s config; + uint32_t target_pos; + bool force_stop : 1; + bool force_immediate_stop : 1; + bool incomplete_immediate_stop : 1; + inline void init() { config.init(); } + inline int32_t targetPosition() const { return target_pos; } + inline void setTargetPosition(int32_t pos) { target_pos = pos; } + inline void advanceTargetPositionWithinInterruptDisabledScope(int32_t delta) { + target_pos += delta; + } + inline void immediateStop() { force_immediate_stop = true; } + inline bool isImmediateStopInitiated() const { return force_immediate_stop; } + inline void clearImmediateStop() { force_immediate_stop = false; } + inline void initiateStop() { force_stop = true; } + inline bool isStopInitiated() const { return force_stop; } + inline void setKeepRunning() { config.parameters.keep_running = true; } + inline bool isRunningContinuously() const { + return config.parameters.keep_running; + } +}; + +struct ramp_rw_s { + volatile uint8_t ramp_state; + // the speed is linked on both ramp slopes to this variable as per (if no + // cubic ramp) + // s = v²/2a => v = sqrt(2*a*s) + uint32_t performed_ramp_up_steps; + // Are the ticks stored of the last previous step, if pulse time requires + // more than one command + uint32_t pause_ticks_left; + // Current ticks for ongoing step + uint32_t curr_ticks; + void init(); + inline void stopRamp() { init(); } + inline uint8_t rampState() const { + // reading one byte is atomic + return ramp_state; + } + inline void startRampIfNotRunning() { +#ifdef TEST + printf("startRampIfNotRunning() called\n"); +#endif + // called with interrupts disabled + if (ramp_state == RAMP_STATE_IDLE) { + curr_ticks = TICKS_FOR_STOPPED_MOTOR; + // ramp_state value is significant to start the ramp generator. + // so initialize curr_ticks before + ramp_state = RAMP_STATE_ACCELERATE; + } + } +}; + +class NextCommand { + public: + struct stepper_command_s command; + struct ramp_rw_s rw; // new _rw, if command has been queued +}; + +void init_ramp_module(); +void _getNextCommand(const struct ramp_ro_s* ramp, const struct ramp_rw_s* rw, + const struct queue_end_s* queue_end, NextCommand* command); +#endif diff --git a/src/fas_ramp/RampGenerator.cpp b/src/fas_ramp/RampGenerator.cpp new file mode 100644 index 0000000..c44080f --- /dev/null +++ b/src/fas_ramp/RampGenerator.cpp @@ -0,0 +1,279 @@ +#include +#include + +#include "StepperMotion.h" +#include "fas_ramp/RampGenerator.h" +#include "fas_queue/stepper_queue.h" + +// This define in order to not shoot myself. +#ifndef TEST +#define printf DO_NOT_USE_PRINTF +#define puts DO_NOT_USE_PRINTF +#endif + +void RampGenerator::init() { + _parameters.init(); + _ro.init(); + _rw.init(); + init_ramp_module(); +} +int8_t RampGenerator::setAcceleration(int32_t accel) { + if (accel <= 0) { + return -1; + } + acceleration = (uint32_t)accel; + _parameters.setAcceleration(accel); + return 0; +} +void RampGenerator::applySpeedAcceleration() { + if (!_ro.isImmediateStopInitiated()) { + _parameters.applyParameters(); + } +} +MoveResultCode RampGenerator::startRun(bool countUp) { + MoveResultCode res = _parameters.checkValidConfig(); + if (res != MOVE_OK) { + return res; + } + _ro.force_stop = false; + _parameters.setRunning(countUp); + _rw.startRampIfNotRunning(); +#ifdef DEBUG + char buf[256]; + sprintf(buf, + "Ramp data: curr_ticks = %" PRIu32 " travel_ticks = %" PRIu32 "\n", + _rw.curr_ticks, _parameters.min_travel_ticks); + Serial.println(buf); +#endif + return MOVE_OK; +} + +void RampGenerator::_startMove(bool position_changed) { + _ro.force_stop = false; + + if (position_changed) { + // Only start the ramp generator, if the target position is different + _rw.startRampIfNotRunning(); + } + +#ifdef TEST + printf("Ramp data: go to %s %" PRId32 " curr_ticks = %" PRIu32 + " travel_ticks = %" PRIu32 " prus=%" PRIu32 "\n", + _parameters.move_absolute ? "ABS" : "REL", _parameters.move_value, + _rw.curr_ticks, _ro.config.parameters.min_travel_ticks, + _rw.performed_ramp_up_steps); +#endif +#ifdef DEBUG + char buf[256]; + sprintf(buf, + "Ramp data: go to = %s %" PRId32 " curr_ticks = %" PRIu32 + " travel_ticks = %" PRIu32 " prus=%" PRIu32 "\n", + _parameters.move_absolute ? "ABS" : "REL", _parameters.move_value, + _rw.curr_ticks, _ro.config.parameters.min_travel_ticks, + _rw.performed_ramp_up_steps); + Serial.println(buf); +#endif +} + +MoveResultCode RampGenerator::moveTo(int32_t position, + const struct queue_end_s* queue_end) { + MoveResultCode res = _parameters.checkValidConfig(); + if (res != MOVE_OK) { + return res; + } + int32_t curr_target; + if (isRampGeneratorActive() && !_ro.config.parameters.keep_running) { + curr_target = _ro.target_pos; + } else { + curr_target = queue_end->pos; + } + inject_fill_interrupt(1); + _parameters.setTargetPosition(position); + _startMove(curr_target != position); + inject_fill_interrupt(2); + return MOVE_OK; +} +MoveResultCode RampGenerator::move(int32_t move) { + MoveResultCode res = _parameters.checkValidConfig(); + if (res != MOVE_OK) { + return res; + } + _parameters.setTargetRelativePosition(move); + _startMove(move != 0); + return MOVE_OK; +} +void RampGenerator::advanceTargetPosition(int32_t delta) { + // called with interrupts disabled + _ro.target_pos += delta; +} + +void RampGenerator::afterCommandEnqueued(const NextCommand* command) { +#ifdef TEST + printf("after Command Enqueued: performed ramp up steps = %" PRIu32 + " pause left = %" PRIu32 ", curr_ticks = %" PRIu32 "\n", + command->rw.performed_ramp_up_steps, command->rw.pause_ticks_left, + command->rw.curr_ticks); +#endif + _rw = command->rw; +} +void RampGenerator::getNextCommand(const struct queue_end_s* queue_end, + NextCommand* command) { + // we are running in higher priority than the application + // so we can just read the config without disable interrupts + // copy consistent ramp state + bool was_keep_running = _ro.config.parameters.keep_running; + if (_parameters.apply) { + _ro.config.parameters = _parameters; + _parameters.apply = false; + _parameters.any_change = false; + _parameters.move_value = 0; + _parameters.move_absolute = false; + _parameters.recalc_ramp_steps = false; + _ro.config.update(); + // if new move command,then reset any immediate stop flag + if (_ro.isImmediateStopInitiated()) { + if (_ro.config.parameters.move_absolute) { + if (_ro.target_pos != (uint32_t)_ro.config.parameters.move_value) { + _ro.clearImmediateStop(); + } + } else if (_ro.config.parameters.move_value != 0) { + _ro.clearImmediateStop(); + } + } +#ifdef DEBUG + Serial.print("new command: move="); + if (_ro.config.parameters.keep_running) { + Serial.print(_ro.config.parameters.keep_running_count_up ? "forward" + : "backward"); + } else { + Serial.print(_ro.config.parameters.move_absolute ? '@' : 'r'); + Serial.print(_ro.config.parameters.move_value); + } + if (_ro.config.parameters.valid_speed) { + Serial.print(" v="); + Serial.print(_ro.config.parameters.min_travel_ticks); + } + if (_ro.config.parameters.valid_acceleration) { + Serial.print(" a="); + Serial.print(log2_to_u32(_ro.config.parameters.log2_accel)); + } + if (_ro.config.parameters.recalc_ramp_steps) { + Serial.print(" recalc"); + } + Serial.println(); +#endif + } + + fasDisableInterrupts(); + struct queue_end_s qe = *queue_end; + fasEnableInterrupts(); + + uint32_t curr_ticks = _rw.curr_ticks; + if (curr_ticks == TICKS_FOR_STOPPED_MOTOR) { + // just started + uint32_t s_jump = _ro.config.parameters.s_jump; + if (s_jump != 0) { + uint32_t ticks = _ro.config.calculate_ticks(s_jump); + if (ticks < _ro.config.parameters.min_travel_ticks) { + s_jump = _ro.config.calculate_ramp_steps( + _ro.config.parameters.min_travel_ticks); + } + } + _rw.performed_ramp_up_steps = s_jump; + _ro.config.parameters.recalc_ramp_steps = false; + } + + // If the acceleration has changed, recalculate the ramp up/down steps, + // which is the equivalent to the current speed. + // Even if the acceleration value is constant, the calculated value + // can deviate due to precision or clipping effect + if (_ro.config.parameters.recalc_ramp_steps) { + uint32_t performed_ramp_up_steps = + _ro.config.calculate_ramp_steps(curr_ticks); +#ifdef TEST + printf("Recalculate performed_ramp_up_steps from %" PRIu32 " to %" PRIu32 + " from %" PRIu32 " ticks\n", + _rw.performed_ramp_up_steps, performed_ramp_up_steps, curr_ticks); +#endif +#ifdef DEBUG + char buf[100]; + sprintf(buf, + "Recalculate performed_ramp_up_steps from %" PRIu32 " to %" PRIu32 + " from %" PRIu32 " ticks\n", + _rw.performed_ramp_up_steps, performed_ramp_up_steps, curr_ticks); + Serial.print(buf); +#endif + _rw.performed_ramp_up_steps = performed_ramp_up_steps; + } + + if (_ro.force_stop) { + _ro.config.parameters.keep_running = false; + uint32_t target_pos = qe.pos; + if (qe.count_up) { + target_pos += _rw.performed_ramp_up_steps; + } else { + target_pos -= _rw.performed_ramp_up_steps; + } +#ifdef TEST + printf("Force stop: adjust target position from %" PRIu32 " to %" PRIu32 + "\n", + _ro.target_pos, target_pos); +#endif +#ifdef DEBUG + char buf[100]; + sprintf(buf, + "Force stop: adjust target position from %" PRIu32 " to %" PRIu32 + "\n", + _ro.target_pos, target_pos); + Serial.print(buf); +#endif + _ro.target_pos = target_pos; + } else if (_ro.config.parameters.any_change) { + // calculate new target position + _ro.config.parameters.any_change = false; + if (_ro.config.parameters.keep_running) { + } else if (_ro.config.parameters.move_absolute) { + _ro.target_pos = _ro.config.parameters.move_value; + } else { + uint32_t target_pos = _ro.target_pos; + if (was_keep_running) { + // target_pos is not valid for keep running + target_pos = qe.pos; + } + _ro.target_pos = target_pos + _ro.config.parameters.move_value; + } +#ifdef DEBUG + Serial.print("target pos="); + Serial.println(_ro.target_pos); +#endif + } + + // This line is the root cause for the failure in issue #280 + //_ro.force_stop = false; + + // clear recalc flag + _ro.config.parameters.recalc_ramp_steps = false; + + if (_ro.isImmediateStopInitiated()) { + // no more commands + command->command.ticks = 0; + _ro.clearImmediateStop(); + _ro.target_pos = qe.pos; + command->rw.stopRamp(); + return; + } + _getNextCommand(&_ro, &_rw, &qe, command); +} +int32_t RampGenerator::getCurrentAcceleration() const { + switch (_rw.rampState() & + (RAMP_STATE_ACCELERATING_FLAG | RAMP_STATE_DECELERATING_FLAG | + RAMP_DIRECTION_MASK)) { + case RAMP_STATE_ACCELERATING_FLAG | RAMP_DIRECTION_COUNT_UP: + case RAMP_STATE_DECELERATING_FLAG | RAMP_DIRECTION_COUNT_DOWN: + return acceleration; + case RAMP_STATE_DECELERATING_FLAG | RAMP_DIRECTION_COUNT_UP: + case RAMP_STATE_ACCELERATING_FLAG | RAMP_DIRECTION_COUNT_DOWN: + return -acceleration; + } + return 0; +} diff --git a/src/fas_ramp/RampGenerator.h b/src/fas_ramp/RampGenerator.h new file mode 100644 index 0000000..8163eff --- /dev/null +++ b/src/fas_ramp/RampGenerator.h @@ -0,0 +1,121 @@ +#ifndef RAMP_GENERATOR_H +#define RAMP_GENERATOR_H + +#include "fas_ramp/RampCalculator.h" +#include "fas_ramp/RampControl.h" +#include "fas_arch/common.h" + +class StepperMotion; + +// log2_timer_freq and friends (when SUPPORT_LOG2_TIMER_FREQ_VARIABLES is +// defined) are declared in RampCalculator.h, included above - that header's +// own inline methods need them declared before this point, not after. + +class RampGenerator { + private: + struct ramp_parameters_s _parameters; + + // The ro variables are those, which are only read from _getNextCommand(). + // The rw variables are only read and written by _getNextCommand() and + // commandEnqueued() Reading ro variables is safe in application + struct ramp_ro_s _ro; + struct ramp_rw_s _rw; + + public: + uint32_t acceleration; + inline uint8_t rampState() const { return _rw.rampState(); } + void init(); + inline int32_t targetPosition() const { return _ro.targetPosition(); } + inline void setTargetPosition(int32_t pos) { _ro.setTargetPosition(pos); } + void advanceTargetPosition(int32_t delta); + inline void setSpeedInTicks(uint32_t min_step_ticks) { + _parameters.setSpeedInTicks(min_step_ticks); + } + inline uint32_t getSpeedInUs() const { + return _parameters.min_travel_ticks / (TICKS_PER_S / 1000000); + } + inline uint32_t getSpeedInTicks() const { + return _parameters.min_travel_ticks; + } + static uint32_t divForMilliHz(uint32_t f) { + uint32_t base = (uint32_t)250 * TICKS_PER_S; + uint32_t res = base / f; + base -= res * f; + base <<= 2; + res <<= 2; + base += f / 2; // add rounding + res += base / f; + return res; + } + static uint32_t divForHz(uint32_t f) { + uint32_t base = TICKS_PER_S; + base += f / 2; // add rounding + uint32_t res = base / f; + return res; + } + inline uint32_t getSpeedInMilliHz() const { + if (_parameters.min_travel_ticks == 0) { + return 0; + } + return divForMilliHz(getSpeedInTicks()); + } + int8_t setAcceleration(int32_t accel); + inline uint32_t getAcceleration() const { return acceleration; } + inline void setLinearAcceleration(uint32_t linear_acceleration_steps) { + _parameters.setCubicAccelerationSteps(linear_acceleration_steps); + } + inline void setJumpStart(uint32_t jump_step) { + _parameters.setJumpStart(jump_step); + } + int32_t getCurrentAcceleration() const; + inline bool hasValidConfig() const { + return _parameters.checkValidConfig() == MOVE_OK; + } + void applySpeedAcceleration(); + MoveResultCode move(int32_t move); + MoveResultCode moveTo(int32_t position, const struct queue_end_s* queue); + MoveResultCode startRun(bool countUp); + inline void forceStop() { _ro.immediateStop(); } + inline void initiateStop() { _ro.initiateStop(); } + inline bool isStopping() const { + return _ro.isStopInitiated() && isRampGeneratorActive(); + } + inline bool isRampGeneratorActive() const { + return rampState() != RAMP_STATE_IDLE; + } + inline uint32_t stepsToStop() const { + fasDisableInterrupts(); + uint32_t v = _rw.performed_ramp_up_steps; + fasEnableInterrupts(); + return v; + } + inline void stopRamp() { _rw.stopRamp(); } + inline void setKeepRunning() { _ro.setKeepRunning(); } + inline bool isRunningContinuously() const { + return _ro.isRunningContinuously(); + } + void getNextCommand(const struct queue_end_s* queue_end, + NextCommand* cmd_out); + void afterCommandEnqueued(const NextCommand* cmd_in); + void getCurrentSpeedInTicks(struct actual_ticks_s* speed) const { + fasDisableInterrupts(); + speed->ticks = _rw.curr_ticks; + uint8_t rs = _rw.rampState(); + fasEnableInterrupts(); + speed->count_up = ((rs & RAMP_DIRECTION_COUNT_UP) != 0); + } + uint32_t getCurrentPeriodInTicks() const { + fasDisableInterrupts(); + uint32_t ticks = _rw.curr_ticks; + fasEnableInterrupts(); + return ticks; + } + inline uint32_t getCurrentPeriodInUs() const { + return TICKS_TO_US(getCurrentPeriodInTicks()); + } + + private: + void _startMove(bool position_changed); +}; + +#endif diff --git a/src/log2/Log2Representation.cpp b/src/log2/Log2Representation.cpp new file mode 100644 index 0000000..5d6d854 --- /dev/null +++ b/src/log2/Log2Representation.cpp @@ -0,0 +1,302 @@ +#include +#if defined(ARDUINO_ARCH_AVR) +#include +#else +#define PROGMEM +#define pgm_read_byte_near(x) (*(x)) +#endif +#include "log2/Log2Representation.h" +#ifdef TEST +#include +#endif + +// In StepperMotion there is seldom the need for adding or +// subtracting floats, but multiplication/division/square and power +// are often in use. Negative numbers and even zero are not needed. +// Consequently, a purely logarithmic representation is completely +// sufficient and the necessary range can be achieved by 16 bit signed integers. +// The interpretation of a signed integer xi is: +// +// x = 2^(xi/512) +// +// The signed integer range xi (-32768..32767) is mapped to the +// range (5e-20, 1.8e19). Please note: zero is not included. +// The greatest constant in use is 2.2e14. So the range is sufficient. +// +// In order to map x to xi, log2(x) needs to be calculated. +// For this we rewrite x to: +// x = (1 + r) * 2^e +// +// With r being in the range 0 <= r < 1. +// This means e is the largest integer value with 2^e < x. +// Consequently, e can be derived by counting the leading numbers in +// the integer x. +// +// So xi = 512*log2(x) = 512 * (e + log(1+r)) +// +// The first 7 bits is plain e with sign and the lower 9 bits is log(1+r)*512 +// xi = eeee_eeem_mmmm_mmmm +// +// Example for 16 bit integer: +// x = 15373 = 0b0011_1100_0000_1101 +// +// log2(15373)*512 = 7121 (rounded) +// = 0b0001_1011_1101_0001 +// +// two leading zeros => e = 15 - 2 = 13 = 0b1101 +// 2^e = 8192 +// +// => x = 8192 * 1.1_1100_0000_1101 +// r is the decimal part without the leading 1 +// r = 1_1100_0000 / 512 +// log2(1+r) * 512 = 464 = 0b1_1101_0001 +// +// xi = eeee_eeem_mmmm_mmmm +// = 0001_1011_1101_0001 +// = 0x1bd1 +// +// The remaining task is to calculate log2(1+f). +// +// log2(1+r) is at the corners identical to r: +// log2(1+0) = 0 and log2(1+1) = 1 +// So it is interesting to look at function +// f(1+r) = log2(1+r) - r +// +// This function is 0 for r at 0 and 1, positive over the range inbetween +// and reaches max value of 0.08607 at r = 0.442695. +// This max value is at r = 1/ln(2)-1 +// +// As we need actually 512*log2(1+r), then the max value is 44. +// This allows to multiply with up to 8 to improve the resolution. +// Here we use factor 4, so two table values can be summed up without overflow. +// +// So the log2 can be calculated for e.g.: +// x = 0001_mmmm_mmmm_mmmm three leading zeros +// +// Shift left by leading zeros+1 (removing leading 1) and then right by 5: +// x = 0001_mmmm_mmmm_mmmm three leading zeros +// mmmm_mmmm_mmmm_m000 shift left (3+1) +// 0000_0mmm_mmmm_mmmm shift right (5) +// if ninth bit is 0: +// + ttt_tttt0 add table value for mmmm_mmmm shifted one +// else: +// + 0ttt_tttt add table value for mmmm_mmmm +// + 0ttt_tttt add table value for mmmm_mmmm+1 +// + 0000_0001 round +// result: mmmm_mmmm_m +// final: 000e_eeem_mmmm_mmmm For up to 32bits (e = 31) +// +// We are using a table of length 256, so first 8 bits are the index. +// In order to improve the resolution, the ninth bit is used to interpolate +// with the next table entry. +// +// Using python3 this can be calculated by: +// [round(math.log2(i/256) * 256 - (i-256)) for i in range(256,512)] +// +// For better precision y_yyyy is shifted by 2 and can be calculated as: +// [round((math.log2(i/256) * 256 - (i-256))*4) for i in range(256,512)] +// +const PROGMEM uint8_t log2_minus_x_plus_one_shifted_by_2[256] = { + 0, 2, 3, 5, 7, 9, 10, 12, 13, 15, 17, 18, 20, 21, 23, 24, 26, 27, 28, + 30, 31, 32, 34, 35, 36, 38, 39, 40, 41, 43, 44, 45, 46, 47, 48, 49, 50, 51, + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 64, 65, 66, 67, 68, 68, + 69, 70, 70, 71, 72, 72, 73, 74, 74, 75, 75, 76, 77, 77, 78, 78, 79, 79, 80, + 80, 80, 81, 81, 82, 82, 83, 83, 83, 84, 84, 84, 84, 85, 85, 85, 86, 86, 86, + 86, 86, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, + 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, 87, 86, 86, + 86, 86, 86, 85, 85, 85, 85, 84, 84, 84, 84, 83, 83, 83, 82, 82, 82, 81, 81, + 81, 80, 80, 79, 79, 79, 78, 78, 77, 77, 76, 76, 75, 75, 74, 74, 73, 73, 72, + 72, 71, 71, 70, 70, 69, 68, 68, 67, 67, 66, 65, 65, 64, 63, 63, 62, 61, 61, + 60, 59, 59, 58, 57, 57, 56, 55, 54, 54, 53, 52, 51, 51, 50, 49, 48, 47, 47, + 46, 45, 44, 43, 42, 42, 41, 40, 39, 38, 37, 36, 35, 34, 34, 33, 32, 31, 30, + 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, + 10, 9, 8, 7, 6, 4, 3, 2, 1}; + +// For the inverse pow(2,x) needs to be calculated. Similarly it makes sense to +// evaluate instead +// g(x) = x - pow(2,x-1) +// +// This function equals 0 for x at 1 and 2, with extremum 0.08607 at x +// = 1.528766. This max. value is at x = 1 - ln(ln(2))/ln(2) +// +// Noteworthy the max values of log2(x) - x + 1 and x - pow(2, x-1) are +// identical, calculated by (-1 + ln(2) - ln(ln(2)))/ln(2) +// +// Using python3 this can be calculated by: +// [round(i - math.pow(2,i/256-1)*256) for i in range(256,512)] +// +// Similarly shifted by two bits: +// [round((i - math.pow(2,i/256-1)*256)*4) for i in range(256,512)] +// +const PROGMEM uint8_t x_minus_pow2_of_x_minus_one_shifted_by_2[256] = { + 0, 1, 2, 4, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 16, 18, 19, 20, 21, + 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 46, 47, 48, 49, 50, 51, 52, 52, 53, 54, 55, 56, 56, + 57, 58, 59, 59, 60, 61, 62, 62, 63, 64, 64, 65, 66, 66, 67, 68, 68, 69, 69, + 70, 71, 71, 72, 72, 73, 73, 74, 74, 75, 76, 76, 76, 77, 77, 78, 78, 79, 79, + 80, 80, 80, 81, 81, 82, 82, 82, 83, 83, 83, 84, 84, 84, 84, 85, 85, 85, 85, + 86, 86, 86, 86, 87, 87, 87, 87, 87, 87, 87, 88, 88, 88, 88, 88, 88, 88, 88, + 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 88, 87, 87, 87, 87, 87, + 87, 86, 86, 86, 86, 86, 85, 85, 85, 84, 84, 84, 84, 83, 83, 83, 82, 82, 81, + 81, 81, 80, 80, 79, 79, 78, 78, 77, 77, 76, 76, 75, 75, 74, 74, 73, 72, 72, + 71, 71, 70, 69, 68, 68, 67, 66, 66, 65, 64, 63, 63, 62, 61, 60, 59, 58, 58, + 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, + 38, 36, 35, 34, 33, 32, 30, 29, 28, 27, 25, 24, 23, 22, 20, 19, 17, 16, 15, + 13, 12, 10, 9, 8, 6, 5, 3, 2}; + +uint8_t leading_zeros(uint8_t x) { + uint8_t res; + if ((x & 0xf0) == 0) { + x <<= 4; + res = 4; + } else { + res = 0; + } + if ((x & 0xc0) == 0) { + x <<= 2; + res += 2; + } + if ((x & 0x80) == 0) { + res += 1; + if (x == 0) { + res += 1; + } + } + return res; +} + +log2_value_t log2_from(uint8_t x) { + // calling with x == 0 is considered an error. + // + // In a first step convert to + // 0000_0eee_mmmm_mmmm + // + // Hereby mmmm_mmmm are the lower bits right from the first 1 in x + // An example with only four valid mantissa bits: + // x = 0001_mmmm => 0000_0100_mmmm_0000 + // + // eee is the exponent + // + // The second convert this to the logarithm of x + // 1. Use mmmm_mmmm as index in the log2_minus_x_plus_one_shifted_by_1 + // table + // 2. shift left 0000_0eee_mmmm_mmmm by 1 + // 3. add the value from the log2_minus_x_plus_one_shifted_by_1 table + uint8_t leading = leading_zeros(x); + if (leading == 8) { + return LOG2_CONST_INVALID; + } + x <<= leading + 1; + uint8_t e = 7 - leading; + uint8_t offset = pgm_read_byte_near(&log2_minus_x_plus_one_shifted_by_2[x]); + uint16_t res = (((uint16_t)e) << 8) | x; + res <<= 1; + offset += 1; + res += offset >> 1; + return res; +} + +log2_value_t log2_from(uint16_t x) { + uint8_t leading = leading_zeros(x >> 8); + if (leading == 8) { + return log2_from((uint8_t)x); + } + // shift msb out + x <<= leading + 1; + uint8_t exponent = 15 - leading; + x >>= 5; + uint8_t index = x >> 3; + uint8_t offset = + pgm_read_byte_near(&log2_minus_x_plus_one_shifted_by_2[index]); + // only with x & 7 > 2, the calculated constants are correct... + if ((x & 7) > 2) { + index++; // overflow to 0 is ok. index is an uint8_t + offset += pgm_read_byte_near(&log2_minus_x_plus_one_shifted_by_2[index]); + offset += 1; + } else { + offset <<= 1; + // offset += 1; + } + x += offset; + x >>= 2; + x += ((uint16_t)exponent) << 9; + return x; +} +log2_value_t log2_from(uint32_t x) { + int16_t exp_offset; + uint16_t w; + if ((x & 0xff000000) == 0) { + if ((x & 0x00ff0000) == 0) { + w = (uint16_t)x; + exp_offset = 0; + } else if ((x & 0x00f00000) == 0) { + w = x >> 4; + exp_offset = 0x0800; + } else { + w = x >> 8; + exp_offset = 0x1000; + } + } else if ((x & 0xf0000000) == 0) { + w = x >> 12; + exp_offset = 0x1800; + } else { + w = x >> 16; + exp_offset = 0x2000; + } + return log2_from(w) + exp_offset; +} +uint16_t log2_to_u16(log2_value_t x) { + if (x < 0) { + return 0; + } + if (x >= LOG2_CONST_UINT16_MAX) { + return __UINT16_MAX__; + } + uint8_t exponent = ((uint16_t)x) >> 9; + x &= 0x01ff; + x += 0x200; + uint8_t index = ((uint16_t)x) >> 1; + x <<= 1; + uint8_t offset = + pgm_read_byte_near(&x_minus_pow2_of_x_minus_one_shifted_by_2[index]); + if ((x & 2) != 0) { + index++; // overflow to 0 is ok. index is an uint8_t + offset += + pgm_read_byte_near(&x_minus_pow2_of_x_minus_one_shifted_by_2[index]); + offset >>= 1; + } + x -= offset; + if (exponent > 10) { + x <<= exponent - 10; + } else if (exponent < 10) { + x += (exponent != 9) ? 2 : 1; + x >>= 10 - exponent; + } + return x; +} +uint32_t log2_to_u32(log2_value_t x) { + if (x < 0) { + return 0; + } + if (x >= LOG2_CONST_UINT32_MAX) { + return __UINT32_MAX__; + } + uint8_t exponent = ((uint16_t)x) >> 9; + if (exponent < 0x10) { + return log2_to_u16(x); + } + uint8_t shift = exponent - 0x0f; + x = log2_shr(x, shift); + uint32_t res = log2_to_u16(x); + res <<= shift; + return res; +} +log2_value_t log2_square(log2_value_t x) { + if (x > 0x4000) { + return LOG2_CONST_MAX; + } + if (x <= -0x4000) { + return LOG2_CONST_MIN; + } + return x + x; +} diff --git a/src/log2/Log2Representation.h b/src/log2/Log2Representation.h new file mode 100644 index 0000000..f0ea8e3 --- /dev/null +++ b/src/log2/Log2Representation.h @@ -0,0 +1,50 @@ +#ifndef LOG2REPRESENTATION_H +#define LOG2REPRESENTATION_H +#include + +#include "log2/Log2RepresentationConst.h" + +typedef int16_t log2_value_t; + +#define LOG2_CONST_INVALID ((log2_value_t)0x8000) +#define LOG2_CONST_MAX ((log2_value_t)0x7fff) +#define LOG2_CONST_MIN ((log2_value_t)0x8001) + +log2_value_t log2_from(uint8_t x); +log2_value_t log2_from(uint16_t x); +log2_value_t log2_from(uint32_t x); + +uint16_t log2_to_u16(log2_value_t x); +uint32_t log2_to_u32(log2_value_t x); + +#define log2_shl(x, n) ((x) + (((int16_t)(n)) << 9)) +#define log2_shr(x, n) ((x) - (((int16_t)(n)) << 9)) + +#define log2_multiply(x, y) ((x) + (y)) +#define log2_divide(x, y) ((x) - (y)) +#define log2_reciprocal(x) (-(x)) +#define log2_sqrt(x) ((x) / 2) +#define log2_rsqrt(x) (-(x) / 2) +#define log2_rsquare(x) log2_reciprocal(log2_square(x)) + +static inline log2_value_t log2_pow_div_3(log2_value_t x) { + // 1/3 ~ (1/4+1/16+1/64+1/256+1/1024+1/4096+1/16384) + uint16_t xu; + xu = x < 0 ? -x : x; + xu /= 2; // x/2 + xu += xu / 4; // x/2 + x/8 + xu += xu / 16; // x/2 + x/8 + x/32 + x/128 + xu += + xu / 256; // x/2 + x/8 + x/32 + x/128 + x/512 + x/2048 + x/8192 + x/32768 + xu += 1; + xu /= 2; + x = (x < 0) ? -(int16_t)xu : xu; + return x; +} +#define log2_pow_2_div_3(x) ((x) - log2_pow_div_3(x)) +#define log2_pow_3_div_2(x) ((x) + (x) / 2) + +log2_value_t log2_square(log2_value_t x); + +uint8_t leading_zeros(uint8_t x); +#endif diff --git a/src/log2/Log2RepresentationConst.h b/src/log2/Log2RepresentationConst.h new file mode 100644 index 0000000..e18fe19 --- /dev/null +++ b/src/log2/Log2RepresentationConst.h @@ -0,0 +1,73 @@ +// Generated constants for the log2 representation. +// DO NOT EDIT +#ifndef LOG2REPRESENTATIONCONST_H +#define LOG2REPRESENTATIONCONST_H + +// log2_value_t must be defined before including this file + +// LOG2_CONST_1 = 0.000000 0 = 0x0000 +#define LOG2_CONST_1 ((log2_value_t)0x0000) +// => converted back => 1.00 + +// LOG2_CONST_3_DIV_2 = 299.500793 300 = 0x012c +#define LOG2_CONST_3_DIV_2 ((log2_value_t)0x012c) +// => converted back => 1.50 + +// LOG2_CONST_128E12 = 23993.925781 23994 = 0x5dba +#define LOG2_CONST_128E12 ((log2_value_t)0x5dba) +// => converted back => 128012783714304.00 + +// LOG2_CONST_16E6 = 12252.962891 12253 = 0x2fdd +#define LOG2_CONST_16E6 ((log2_value_t)0x2fdd) +// => converted back => 16000799.00 + +// LOG2_CONST_500 = 4590.481445 4590 = 0x11ee +#define LOG2_CONST_500 ((log2_value_t)0x11ee) +// => converted back => 499.67 + +// LOG2_CONST_1000 = 5102.481445 5102 = 0x13ee +#define LOG2_CONST_1000 ((log2_value_t)0x13ee) +// => converted back => 999.35 + +// LOG2_CONST_2000 = 5614.481445 5614 = 0x15ee +#define LOG2_CONST_2000 ((log2_value_t)0x15ee) +// => converted back => 1998.70 + +// LOG2_CONST_32000 = 7662.481445 7662 = 0x1dee +#define LOG2_CONST_32000 ((log2_value_t)0x1dee) +// => converted back => 31979.14 + +// LOG2_CONST_16E6_DIV_SQRT_OF_2 = 11996.962891 11997 = 0x2edd +#define LOG2_CONST_16E6_DIV_SQRT_OF_2 ((log2_value_t)0x2edd) +// => converted back => 11314274.00 + +// LOG2_CONST_21E6 = 12453.830078 12454 = 0x30a6 +#define LOG2_CONST_21E6 ((log2_value_t)0x30a6) +// => converted back => 21004844.00 + +// LOG2_CONST_42000 = 7863.348145 7863 = 0x1eb7 +#define LOG2_CONST_42000 ((log2_value_t)0x1eb7) +// => converted back => 41980.21 + +// LOG2_CONST_21E6_DIV_SQRT_OF_2 = 12197.830078 12198 = 0x2fa6 +#define LOG2_CONST_21E6_DIV_SQRT_OF_2 ((log2_value_t)0x2fa6) +// => converted back => 14852668.00 + +// LOG2_CONST_2205E11 = 24395.660156 24396 = 0x5f4c +#define LOG2_CONST_2205E11 ((log2_value_t)0x5f4c) +// => converted back => 220601734135808.00 + +// LOG2_CONST_UINT32_MAX = 16384.000000 16384 = 0x4000 +#define LOG2_CONST_UINT32_MAX ((log2_value_t)0x4000) +// => converted back => 4294967296.00 + +// LOG2_CONST_UINT16_MAX = 8191.988770 8192 = 0x2000 +#define LOG2_CONST_UINT16_MAX ((log2_value_t)0x2000) +// => converted back => 65536.00 + +// used in Log2Representation.cpp as example +// +// LOG2_CONST_15373 = 7120.953125 7121 = 0x1bd1 +#define LOG2_CONST_15373 ((log2_value_t)0x1bd1) +// => converted back => 15373.98 +#endif diff --git a/src/pd_avr/avr_queue.cpp b/src/pd_avr/avr_queue.cpp new file mode 100644 index 0000000..afed476 --- /dev/null +++ b/src/pd_avr/avr_queue.cpp @@ -0,0 +1,503 @@ +#if defined(ARDUINO_ARCH_AVR) +#include "fas_queue/stepper_queue.h" + +// T is the timer module number 0,1,2,3... +// X is the Channel name A or B +// +// BV1 Bv0 +// Output one is 1 1 +// Output zero is 1 0 +// Toggle is 0 1 +// Disconnect is 0 0 +// +#define Stepper_Zero(T, X) \ + TCCR##T##A = (TCCR##T##A | _BV(COM##T##X##1)) & ~_BV(COM##T##X##0) +// Force compare of Stepper_Toggle appears to be broken in simavr +// In other words, use of Stepper_Toggle yields errors in simavr, for which root +// cause is unclear +#ifdef DISABLE +#define Stepper_Toggle(T, X) \ + TCCR##T##A = (TCCR##T##A | _BV(COM##T##X##0)) & ~_BV(COM##T##X##1) +#endif +#define Stepper_One(T, X) TCCR##T##A |= _BV(COM##T##X##1) | _BV(COM##T##X##0) +#define Stepper_Disconnect(T, X) \ + TCCR##T##A &= ~(_BV(COM##T##X##1) | _BV(COM##T##X##0)) +#define Stepper_IsOne(T, X) \ + ((TCCR##T##A & (_BV(COM##T##X##0) | _BV(COM##T##X##1))) == \ + (_BV(COM##T##X##0) | _BV(COM##T##X##1))) +#define Stepper_IsDisconnected(T, X) \ + ((TCCR##T##A & (_BV(COM##T##X##0) | _BV(COM##T##X##1))) == 0) +#define Stepper_IsOneIfOutput(T, X) ((TCCR##T##A & _BV(COM##T##X##0)) != 0) +#define Stepper_ToggleDirection(CHANNEL) \ + *fas_queue_##CHANNEL._dirTogglePinPort = fas_queue_##CHANNEL._dirTogglePinMask +#define PREPARE_DIRECTION_PIN(CHANNEL) \ + if (e->toggle_dir) { \ + Stepper_ToggleDirection(CHANNEL); \ + } + +#ifdef SIMAVR_TIME_MEASUREMENT +#define prepareISRtimeMeasurement() DDRB |= 0x18 +#define enterStepperISR() PORTB |= 0x08 +#define exitStepperISR() PORTB ^= 0x08 +#define enterFillQueueISR() PORTB |= 0x10 +#define exitFillQueueISR() PORTB ^= 0x10 +#elif defined(SIMAVR_TIME_MEASUREMENT_QUEUE) +#define prepareISRtimeMeasurement() DDRB |= 0x10 +#define enterStepperISR() \ + { \ + } +#define exitStepperISR() \ + { \ + } +#define enterFillQueueISR() PORTB |= 0x10 +#define exitFillQueueISR() PORTB ^= 0x10 +#else +#define prepareISRtimeMeasurement() \ + { \ + } +#define enterStepperISR() \ + { \ + } +#define exitStepperISR() \ + { \ + } +#define enterFillQueueISR() \ + { \ + } +#define exitFillQueueISR() \ + { \ + } +#endif + +#define ForceCompare(T, X) TCCR##T##C = _BV(FOC##T##X) +#define DisableCompareInterrupt(T, X) TIMSK##T &= ~_BV(OCIE##T##X) +#define EnableCompareInterrupt(T, X) TIMSK##T |= _BV(OCIE##T##X) +#define ClearInterruptFlag(T, X) TIFR##T = _BV(OCF##T##X) +#define SetTimerCompareRelative(T, X, D) OCR##T##X = TCNT##T + D +#define SetTimerCompareAbsolute(T, X, V) OCR##T##X = (V) +#define InterruptFlagIsSet(T, X) ((TIFR##T & _BV(OCF##T##X)) != 0) + +#define ConfigureTimer(T) \ + { \ + /* Set WGMn3:0 to all zero => Normal mode */ \ + TCCR##T##A &= ~(_BV(WGM##T##1) | _BV(WGM##T##0)); \ + TCCR##T##B &= ~(_BV(WGM##T##3) | _BV(WGM##T##2)); \ + /* Set prescaler to 1 */ \ + TCCR##T##B = \ + (TCCR##T##B & ~(_BV(CS##T##2) | _BV(CS##T##1) | _BV(CS##T##0))) | \ + _BV(CS##T##0); \ + } +#define EnableOverflowInterrupt(T) TIMSK##T |= _BV(TOIE##T) +#define DisableOverflowInterrupt(T) TIMSK##T &= ~_BV(TOIE##T) + +// this is needed to give the background task isr access to engine +static StepperMotionEngine* fas_engine = NULL; + +#define AVR_INIT(T, CHANNEL) \ + { \ + /* Disconnect stepper on next compare event */ \ + Stepper_Disconnect(T, CHANNEL); \ + /* disable compare A interrupt */ \ + DisableCompareInterrupt(T, CHANNEL); \ + /* force compare to ensure disconnect */ \ + ForceCompare(T, CHANNEL); \ + /* Initialize timer for correct time base */ \ + ConfigureTimer(T); \ + /* ensure cyclic interrupt is running */ \ + EnableOverflowInterrupt(T); \ + } +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + // `queue_num` is part of the shared queue interface (protocol.h) and is + // genuinely unused here: AVR picks its compare channel from `step_pin`, + // because TIMER0 has exactly one compare unit per stepper pin and the pin + // already names it. Every other platform needs the index, which is why the + // parameter exists at all. + (void)queue_num; + prepareISRtimeMeasurement(); + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + if (step_pin == stepPinStepperA) { + channel = channels::channelA; + AVR_INIT(FAS_TIMER_MODULE, A) + } else if (step_pin == stepPinStepperB) { + channel = channels::channelB; + AVR_INIT(FAS_TIMER_MODULE, B) + } +#ifdef stepPinStepperC + else if (step_pin == stepPinStepperC) { + channel = channels::channelC; + AVR_INIT(FAS_TIMER_MODULE, C) + } +#endif +} + +// The interrupt is called on compare event, which eventually +// generates a L->H transition. In any case, the current command's +// wait time has still to be executed for the next command, if any. +// +// Remark: Interrupt Flag is automatically cleared on ISR execution +// +// If reaching here without further commands, then the queue is done +#define AVR_STEPPER_ISR(T, CHANNEL) \ + ISR(TIMER##T##_COMP##CHANNEL##_vect) { \ + enterStepperISR(); \ + uint8_t rp = fas_queue_##CHANNEL.read_idx; \ + uint8_t wp = fas_queue_##CHANNEL.next_write_idx; \ + if (rp == wp) { \ + /* queue is empty => set to disconnect */ \ + /* disable compare interrupt */ \ + DisableCompareInterrupt(T, CHANNEL); \ + Stepper_Disconnect(T, CHANNEL); \ + /* force compare to ensure disconnect */ \ + ForceCompare(T, CHANNEL); \ + fas_queue_##CHANNEL._isRunning = false; \ + fas_queue_##CHANNEL._noMoreCommands = false; \ + exitStepperISR(); \ + return; \ + } \ + struct queue_entry* e = &fas_queue_##CHANNEL.entry[rp & QUEUE_LEN_MASK]; \ + /* There is a risk, that this new compare time is delayed by one cycle */ \ + uint16_t ticks = e->ticks; \ + /* Set output to zero, this works in any case. In case of pause: no-op */ \ + Stepper_Zero(T, CHANNEL); \ + ForceCompare(T, CHANNEL); \ + if (e->steps > 1) { \ + /* perform another step with this queue entry */ \ + e->steps--; \ + Stepper_One(T, CHANNEL); \ + } else { \ + /* either pause command or no more steps */ \ + if (fas_queue_##CHANNEL._noMoreCommands) { \ + /* new command received after running out of commands */ \ + /* if this new command requires a step, then this step would be lost \ + */ \ + fas_queue_##CHANNEL._noMoreCommands = false; \ + if (e->steps != 0) { \ + /* New command needs steps, so do it immediately */ \ + ticks = 10; \ + } \ + } else { \ + rp++; \ + fas_queue_##CHANNEL.read_idx = rp; \ + if (rp == wp) { \ + /* queue is empty, wait this command to complete, then disconnect */ \ + fas_queue_##CHANNEL._noMoreCommands = true; \ + OCR##T##CHANNEL += ticks; \ + exitStepperISR(); \ + return; \ + } \ + e = &fas_queue_##CHANNEL.entry[rp & QUEUE_LEN_MASK]; \ + } \ + if (e->toggle_dir) { \ + Stepper_ToggleDirection(CHANNEL); \ + } \ + if (e->steps != 0) { \ + Stepper_One(T, CHANNEL); \ + } \ + } \ + OCR##T##CHANNEL += ticks; \ + exitStepperISR(); \ + } + +#define AVR_STEPPER_ISR_GEN(T, CHANNEL) AVR_STEPPER_ISR(T, CHANNEL) +AVR_STEPPER_ISR_GEN(FAS_TIMER_MODULE, A) +AVR_STEPPER_ISR_GEN(FAS_TIMER_MODULE, B) +#ifdef stepPinStepperC +AVR_STEPPER_ISR_GEN(FAS_TIMER_MODULE, C) +#endif + +// this is for cyclic task +#define AVR_CYCLIC_ISR(T) \ + ISR(TIMER##T##_OVF_vect) { \ + enterFillQueueISR(); \ + \ + /* disable OVF interrupt to avoid nesting */ \ + DisableOverflowInterrupt(T); \ + \ + /* enable interrupts for nesting */ \ + sei(); \ + \ + /* manage steppers */ \ + fas_engine->manageSteppers(); \ + \ + /* disable interrupts for exist ISR routine */ \ + cli(); \ + \ + /* enable OVF interrupt again */ \ + EnableOverflowInterrupt(T); \ + \ + exitFillQueueISR(); \ + } +#define AVR_CYCLIC_ISR_GEN(T) AVR_CYCLIC_ISR(T) +AVR_CYCLIC_ISR_GEN(FAS_TIMER_MODULE) + +#define GET_ENTRY_PTR(T, CHANNEL) \ + rp = fas_queue_##CHANNEL.read_idx; \ + e = &fas_queue_##CHANNEL.entry[rp & QUEUE_LEN_MASK]; + +#define AVR_START_QUEUE(T, CHANNEL) \ + /* ensure no compare event */ \ + SetTimerCompareRelative(T, CHANNEL, 32768); \ + /* set output one, if steps to be generated */ \ + if (e->steps != 0) { \ + Stepper_One(T, CHANNEL); \ + } else { \ + Stepper_Zero(T, CHANNEL); \ + } \ + /* clear interrupt flag */ \ + ClearInterruptFlag(T, CHANNEL); \ + /* enable compare interrupt */ \ + EnableCompareInterrupt(T, CHANNEL); \ + /* start */ \ + noInterrupts(); \ + SetTimerCompareRelative(T, CHANNEL, 10); \ + interrupts(); + +void StepperQueue::startQueue() { + uint8_t rp; + const struct queue_entry* e; + + _isRunning = true; + switch (channel) { + case channels::channelA: + GET_ENTRY_PTR(FAS_TIMER_MODULE, A) + PREPARE_DIRECTION_PIN(A) + AVR_START_QUEUE(FAS_TIMER_MODULE, A) + break; + case channels::channelB: + GET_ENTRY_PTR(FAS_TIMER_MODULE, B) + PREPARE_DIRECTION_PIN(B) + AVR_START_QUEUE(FAS_TIMER_MODULE, B) + break; +#ifdef stepPinStepperC + case channels::channelC: + GET_ENTRY_PTR(FAS_TIMER_MODULE, C) + PREPARE_DIRECTION_PIN(C) + AVR_START_QUEUE(FAS_TIMER_MODULE, C) + break; +#endif + } +} + +#define FORCE_STOP(T, CHANNEL) \ + { \ + /* disable compare interrupt */ \ + DisableCompareInterrupt(T, CHANNEL); \ + /* set to disconnect */ \ + Stepper_Disconnect(T, CHANNEL); \ + /* force compare to ensure disconnect */ \ + ForceCompare(T, CHANNEL); \ + } +void StepperQueue::forceStop() { + switch (channel) { + case channels::channelA: + FORCE_STOP(FAS_TIMER_MODULE, A) + break; + case channels::channelB: + FORCE_STOP(FAS_TIMER_MODULE, B) + break; +#ifdef stepPinStepperC + case channels::channelC: + FORCE_STOP(FAS_TIMER_MODULE, C) + break; +#endif + } + _isRunning = false; + + // empty the queue + read_idx = next_write_idx; +} +void StepperQueue::connect() {} +void StepperQueue::disconnect() {} + +int8_t StepperQueue::queueNumForStepPin(uint8_t step_pin) { + if (step_pin == stepPinStepperA) { + return 0; + } + if (step_pin == stepPinStepperB) { + return 1; + } +#ifdef stepPinStepperC + if (step_pin == stepPinStepperC) { + return 2; + } +#endif + return -1; +} +void StepperQueue::adjustSpeedToStepperCount(uint8_t steppers) { + // commit 9577e9bfd4b9a6cf1ad830901c00c8b129a62aee fails + // test_sd_04_timing_2560 as timer 3 reaches 40us. + // This includes port set/clear for timer measurement. + // So choose 20kHz + // + // check if Issue_152.ino, the interrupt need 14us. + // So 70000 Steps/s is too high. + if (steppers == 1) { + max_speed_in_ticks = TICKS_PER_S / 50000; + } else if (steppers == 2) { + max_speed_in_ticks = 426; + } else { + max_speed_in_ticks = TICKS_PER_S / 20000; + } +} + +static uint8_t stepper_allocated_mask = 0; + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + int8_t idx = queueNumForStepPin(step_pin); + if (idx < 0) { + return nullptr; + } + + if (stepper_allocated_mask & (1 << idx)) { + return nullptr; + } + + fas_queue[idx]._initVars(); + fas_queue[idx].init(idx, step_pin); + + stepper_allocated_mask |= (1 << idx); + return &fas_queue[idx]; +} + +// synchronizedStart() calls the timer macros directly. Those paste the timer +// module into the register name with ##, which suppresses expansion of the +// argument, so FAS_TIMER_MODULE would end up literal in the register name. +// These wrappers expand the timer module first, as the AVR_START_QUEUE style +// intermediates do. +// +// All channels are armed with one shared compare value, so their compare +// matches fall on the same timer tick. The value has to be far enough in the +// future that the whole arm loop finishes before it is reached. +#define AVR_SYNC_ARM_DELAY 400 +#define AVR_SYNC_TARGET(T) AVR_SYNC_TARGET_(T) +#define AVR_SYNC_TARGET_(T) (TCNT##T) +#define AVR_SYNC_ARM(T, X, TARGET) \ + { \ + if (e->steps > 0) { \ + Stepper_One(T, X); \ + } else { \ + Stepper_Zero(T, X); \ + } \ + SetTimerCompareAbsolute(T, X, TARGET); \ + } +#define AVR_SYNC_TRIGGER(T, X) \ + { \ + ClearInterruptFlag(T, X); \ + EnableCompareInterrupt(T, X); \ + } + +// Fast path: single stepper -> normal startQueue() is sufficient. +#if defined(stepPinStepperC) +// 2560/32U4 (with channel C): bitmask approach — any 2 or all 3 channels. +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + + // Fast path: single stepper -> normal startQueue() is sufficient + if (cnt == 1) { + rc = steppers[0]->addQueueEntry(NULL, true); + return rc; + } + + // Build mask of participating channels (matching generic contract: + // skip running queues and empty queues). + uint8_t mask = 0; + for (uint8_t i = 0; i < cnt; i++) { + StepperQueue* q = steppers[i]->_queue(); + if (q->isRunning() || q->isQueueEmpty()) { + continue; + } + mask |= (1 << (uint8_t)q->channel); + } + + if (mask == 0) { + return rc; // no steppers to sync + } + + fasDisableInterrupts(); + + // Phase 1: arm - write the shared compare value to all participating OCRs + uint16_t target = AVR_SYNC_TARGET(FAS_TIMER_MODULE) + AVR_SYNC_ARM_DELAY; + for (uint8_t i = 0; i < cnt; i++) { + StepperQueue* q = steppers[i]->_queue(); + if (q->isRunning() || q->isQueueEmpty()) { + continue; + } + uint8_t rp; + const struct queue_entry* e; + switch ((uint8_t)q->channel) { + case 0: // channel A + GET_ENTRY_PTR(FAS_TIMER_MODULE, A) + PREPARE_DIRECTION_PIN(A) + AVR_SYNC_ARM(FAS_TIMER_MODULE, A, target) + break; + case 1: // channel B + GET_ENTRY_PTR(FAS_TIMER_MODULE, B) + PREPARE_DIRECTION_PIN(B) + AVR_SYNC_ARM(FAS_TIMER_MODULE, B, target) + break; + case 2: // channel C + GET_ENTRY_PTR(FAS_TIMER_MODULE, C) + PREPARE_DIRECTION_PIN(C) + AVR_SYNC_ARM(FAS_TIMER_MODULE, C, target) + break; + } + } + + // Phase 2: trigger - clear flags, enable all compare interrupts + if (mask & (1 << 0)) { + AVR_SYNC_TRIGGER(FAS_TIMER_MODULE, A) + } + if (mask & (1 << 1)) { + AVR_SYNC_TRIGGER(FAS_TIMER_MODULE, B) + } +#if stepPinStepperC != PIN_UNDEFINED + if (mask & (1 << 2)) { + AVR_SYNC_TRIGGER(FAS_TIMER_MODULE, C) + } +#endif + + fasEnableInterrupts(); + return rc; +} +#else +// 328P (no channel C): cnt==2 always means A+B — two phases, +// no bitmask needed because there are exactly two steppers. +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + + // Fast path: single stepper -> normal startQueue() is sufficient + if (cnt == 1) { + rc = steppers[0]->addQueueEntry(NULL, true); + return rc; + } + + // cnt==2 means A+B (the only two steppers on 328P) + fasDisableInterrupts(); + + // Phase 1: arm - write the shared compare value to both OCRs + uint16_t target = AVR_SYNC_TARGET(FAS_TIMER_MODULE) + AVR_SYNC_ARM_DELAY; + uint8_t rp; + const struct queue_entry* e; + GET_ENTRY_PTR(FAS_TIMER_MODULE, A) + PREPARE_DIRECTION_PIN(A) + AVR_SYNC_ARM(FAS_TIMER_MODULE, A, target) + GET_ENTRY_PTR(FAS_TIMER_MODULE, B) + PREPARE_DIRECTION_PIN(B) + AVR_SYNC_ARM(FAS_TIMER_MODULE, B, target) + + // Phase 2: trigger - clear flags, enable both compare interrupts + AVR_SYNC_TRIGGER(FAS_TIMER_MODULE, A) + AVR_SYNC_TRIGGER(FAS_TIMER_MODULE, B) + + fasEnableInterrupts(); + return rc; +} +#endif // stepPinStepperC + +void fas_init_engine(StepperMotionEngine* engine) { fas_engine = engine; } +#endif diff --git a/src/pd_avr/avr_queue.h b/src/pd_avr/avr_queue.h new file mode 100644 index 0000000..d3cc41b --- /dev/null +++ b/src/pd_avr/avr_queue.h @@ -0,0 +1,113 @@ +#ifndef PD_AVR_QUEUE_H +#define PD_AVR_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +//========================================================================== +// +// AVR derivate ATmega 168/328/P +// +//========================================================================== +#if (defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || \ + defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) +#define fas_queue_A fas_queue[0] +#define fas_queue_B fas_queue[1] +enum class channels : uint8_t { channelA, channelB }; +//========================================================================== +// +// AVR derivate ATmega 2560 +// +//========================================================================== +#elif defined(__AVR_ATmega2560__) +#define fas_queue_A fas_queue[0] +#define fas_queue_B fas_queue[1] +#define fas_queue_C fas_queue[2] +enum class channels : uint8_t { channelA, channelB, channelC }; +//========================================================================== +// +// AVR derivate ATmega 32U4 +// +//========================================================================== +#elif defined(__AVR_ATmega32U4__) +#define fas_queue_A fas_queue[0] +#define fas_queue_B fas_queue[1] +#define fas_queue_C fas_queue[2] +enum class channels : uint8_t { channelA, channelB, channelC }; +#endif + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + volatile bool _noMoreCommands; + volatile bool _isRunning; + inline bool isRunning() const { return _isRunning; } + inline bool isReadyForCommands() const { return true; } + channels channel; + + volatile uint8_t* _dirPinPort; + uint8_t _dirPinMask; + volatile uint8_t* _dirTogglePinPort; + uint8_t _dirTogglePinMask; + + inline void _pd_initVars() { + _dirPinPort = NULL; + _dirTogglePinPort = NULL; + } + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + if ((dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0)) { + _dirPinPort = portOutputRegister(digitalPinToPort(dir_pin)); + _dirPinMask = digitalPinToBitMask(dir_pin); + _dirTogglePinPort = portInputRegister(digitalPinToPort(dir_pin)); + _dirTogglePinMask = digitalPinToBitMask(dir_pin); + } + } + + void adjustSpeedToStepperCount(uint8_t steppers); + + private: + static int8_t queueNumForStepPin(uint8_t step_pin); +}; + +#define SET_DIRECTION_PIN_STATE(q, high) \ + do { \ + if (high) { \ + *((q)->_dirPinPort) |= (q)->_dirPinMask; \ + } else { \ + *((q)->_dirPinPort) &= ~(q)->_dirPinMask; \ + } \ + } while (0) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + digitalWrite((pin), (high) ? HIGH : LOW) + +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + if (dir_change_delay_ticks == 0) { + return AQE_OK; + } + if ((cmd->steps == 0) && (cmd->ticks >= dir_change_delay_ticks)) { + return AQE_OK; + } + uint16_t pause_ticks = dir_change_delay_ticks; + if (cmd->steps == 0) { + pause_ticks = dir_change_delay_ticks - cmd->ticks; + } + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(pause_ticks, MIN_CMD_TICKS), + .steps = 0, + .count_up = cmd->count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +#endif // PD_AVR_QUEUE_H diff --git a/src/pd_avr/pd_config.h b/src/pd_avr/pd_config.h new file mode 100644 index 0000000..106f370 --- /dev/null +++ b/src/pd_avr/pd_config.h @@ -0,0 +1,67 @@ +// pd_avr/pd_config.h - AVR platform configuration +// +// This file defines AVR-specific constants for the StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for AVR-specific behavior +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_AVR_CONFIG_H +#define PD_AVR_CONFIG_H + +#define QUEUE_LEN 16 +#define TICKS_PER_S F_CPU +#define MIN_CMD_TICKS (TICKS_PER_S / 25000) +#define MIN_DIR_DELAY_US 40 +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE (65536000 / TICKS_PER_S) + +#define DEBUG_LED_HALF_PERIOD (TICKS_PER_S / 65536 / 2) + +#define noop_or_wait + +#define SUPPORT_QUEUE_ENTRY_END_POS_U16 + +#define NEED_GENERIC_GET_CURRENT_POSITION + +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +#define NEED_ADJUSTABLE_MAX_SPEED_DEPENDING_ON_STEPPER_COUNT +#define NEED_FIXED_QUEUE_TO_PIN_MAPPING + +//========================================================================== +// +// AVR derivative ATmega 168/328/P +// +//========================================================================== +#if (defined(__AVR_ATmega168__) || defined(__AVR_ATmega168P__) || \ + defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)) +#define MAX_STEPPER 2 +#define NUM_QUEUES 2 +//========================================================================== +// +// AVR derivative ATmega 2560 +// +//========================================================================== +#elif defined(__AVR_ATmega2560__) +#define MAX_STEPPER 3 +#define NUM_QUEUES 3 +//========================================================================== +// +// AVR derivative ATmega 32U4 +// +//========================================================================== +#elif defined(__AVR_ATmega32U4__) +#define MAX_STEPPER 3 +#define NUM_QUEUES 3 +//========================================================================== +// +// For all unsupported AVR derivatives +// +//========================================================================== +#else +#error "Unsupported AVR derivative" +#endif + +#endif /* PD_AVR_CONFIG_H */ diff --git a/src/pd_esp32/StepperISR_esp32_i2s.cpp b/src/pd_esp32/StepperISR_esp32_i2s.cpp new file mode 100644 index 0000000..a3a4265 --- /dev/null +++ b/src/pd_esp32/StepperISR_esp32_i2s.cpp @@ -0,0 +1,58 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_I2S) + +#include "pd_esp32/i2s_manager.h" +#include "pd_esp32/i2s_fill.h" +#include "pd_esp32/i2s_constants.h" + +void StepperQueue::init_i2s(uint8_t step_pin) { + _step_pin = step_pin; + _fill_state = {0, 0, 0}; + _isRunning = false; + + if (i2s_mgr->_is_mux) { + max_speed_in_ticks = I2S_MUX_MIN_SPEED_TICKS; + } else { + max_speed_in_ticks = I2S_DIRECT_MIN_SPEED_TICKS; + } +} + +void StepperQueue::startQueue_i2s() { _isRunning = true; } + +void StepperQueue::forceStop_i2s() { + _isRunning = false; + _fill_state = {}; + + // and empty the buffer + read_idx = next_write_idx; +} + +bool StepperQueue::isReadyForCommands_i2s() const { + if (_isRunning) { + return !isQueueFull(); + } + return true; +} + +uint16_t StepperQueue::_getPerformedPulses_i2s() const { return 0; } + +void IRAM_ATTR StepperQueue::fill_i2s_buffer(uint8_t* buf) { + if (!_isRunning) { + return; + } + + bool buffer_full; + if (i2s_mgr->_is_mux) { + buffer_full = + i2s_fill_buffer_mux(this, buf, &_fill_state, _i2s_mux_step_byte_offset, + _i2s_mux_step_bit_mask); + } else { + buffer_full = i2s_fill_buffer_direct(this, buf, &_fill_state); + } + + if (!buffer_full) { + _isRunning = false; + } +} + +#endif diff --git a/src/pd_esp32/StepperISR_idf4_esp32_mcpwm_pcnt.cpp b/src/pd_esp32/StepperISR_idf4_esp32_mcpwm_pcnt.cpp new file mode 100644 index 0000000..d2338d7 --- /dev/null +++ b/src/pd_esp32/StepperISR_idf4_esp32_mcpwm_pcnt.cpp @@ -0,0 +1,575 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (ESP_IDF_VERSION_MAJOR == 4) + +#define DEFAULT_TIMER_H_L_TRANSITION 160 + +// cannot be updated while timer is running => fix it to 0 +#define TIMER_PRESCALER 0 + +// #define TEST_PROBE 18 + +// Here the associated mapping from queue to mcpwm/pcnt units +// +// As the ISR is accessing this table, the mapping cannot be put into flash, +// even this is actually a constant table +struct mapping_s { + mcpwm_unit_t mcpwm_unit; + uint8_t timer; + mcpwm_io_signals_t pwm_output_pin; + pcnt_unit_t pcnt_unit; + uint8_t input_sig_index; + uint32_t cmpr_tea_int_clr; + uint32_t cmpr_tea_int_ena; + uint32_t cmpr_tea_int_raw; +}; + +static struct mapping_s channel2mapping[NUM_QUEUES] = { + { + mcpwm_unit : MCPWM_UNIT_0, + timer : 0, + pwm_output_pin : MCPWM0A, + pcnt_unit : PCNT_UNIT_0, + input_sig_index : PCNT_SIG_CH0_IN0_IDX, + cmpr_tea_int_clr : MCPWM_OP0_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP0_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP0_TEA_INT_RAW + }, + { + mcpwm_unit : MCPWM_UNIT_0, + timer : 1, + pwm_output_pin : MCPWM1A, + pcnt_unit : PCNT_UNIT_1, + input_sig_index : PCNT_SIG_CH0_IN1_IDX, + cmpr_tea_int_clr : MCPWM_OP1_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP1_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP1_TEA_INT_RAW + }, + { + mcpwm_unit : MCPWM_UNIT_0, + timer : 2, + pwm_output_pin : MCPWM2A, + pcnt_unit : PCNT_UNIT_2, + input_sig_index : PCNT_SIG_CH0_IN2_IDX, + cmpr_tea_int_clr : MCPWM_OP2_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP2_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP2_TEA_INT_RAW + }, + { + mcpwm_unit : MCPWM_UNIT_1, + timer : 0, + pwm_output_pin : MCPWM0A, + pcnt_unit : PCNT_UNIT_3, + input_sig_index : PCNT_SIG_CH0_IN3_IDX, + cmpr_tea_int_clr : MCPWM_OP0_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP0_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP0_TEA_INT_RAW + }, +#ifndef HAVE_ESP32S3_PULSE_COUNTER + { + mcpwm_unit : MCPWM_UNIT_1, + timer : 1, + pwm_output_pin : MCPWM1A, + pcnt_unit : PCNT_UNIT_4, + input_sig_index : PCNT_SIG_CH0_IN4_IDX, + cmpr_tea_int_clr : MCPWM_OP1_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP1_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP1_TEA_INT_RAW + }, + { + mcpwm_unit : MCPWM_UNIT_1, + timer : 2, + pwm_output_pin : MCPWM2A, + pcnt_unit : PCNT_UNIT_5, + input_sig_index : PCNT_SIG_CH0_IN5_IDX, + cmpr_tea_int_clr : MCPWM_OP2_TEA_INT_CLR, + cmpr_tea_int_ena : MCPWM_OP2_TEA_INT_ENA, + cmpr_tea_int_raw : MCPWM_OP2_TEA_INT_RAW + }, +#endif +}; + +static void IRAM_ATTR prepare_for_next_command( + const StepperQueue* queue, const struct queue_entry* e_next) { + uint8_t next_steps = e_next->steps; + if (next_steps > 0) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + pcnt_unit_t pcnt_unit = mapping->pcnt_unit; + // is updated only on zero +#ifndef HAVE_ESP32S3_PULSE_COUNTER + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim = next_steps; +#else + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim_un = next_steps; +#endif + } +} + +#define isr_pcnt_counter_clear(pcnt_unit) \ + REG_SET_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit))); \ + REG_CLR_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit))) + +static void IRAM_ATTR apply_command(StepperQueue* queue, + const struct queue_entry* e) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + volatile mcpwm_dev_t* mcpwm = mcpwm_unit == MCPWM_UNIT_0 ? &MCPWM0 : &MCPWM1; + pcnt_unit_t pcnt_unit = mapping->pcnt_unit; + uint8_t timer = mapping->timer; + uint8_t steps = e->steps; + if (e->toggle_dir) { + LL_TOGGLE_PIN(queue->dirPin); + } + uint16_t ticks = e->ticks; +#ifndef __ESP32_IDF_V44__ + if (mcpwm->timer[timer].status.value <= 1) { // mcpwm Timer is stopped ? + mcpwm->timer[timer].period.upmethod = 0; // 0 = immediate update, 1 = TEZ +#else /* __ESP32_IDF_V44__ */ + if (mcpwm->timer[timer].timer_status.timer_value <= + 1) { // mcpwm Timer is stopped ? + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = + 0; // 0 = immediate update, 1 = TEZ +#endif /* __ESP32_IDF_V44__ */ + } else { + // 0 = immediate update, 1 = TEZ +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].period.upmethod = 1; +#else /* __ESP32_IDF_V44__ */ + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 1; +#endif /* __ESP32_IDF_V44__ */ + } +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].period.period = ticks; +#else /* __ESP32_IDF_V44__ */ + mcpwm->timer[timer].timer_cfg0.timer_period = ticks; +#endif /* __ESP32_IDF_V44__ */ + if (steps == 0) { + // timer value = 1 - upcounting: output low +#ifndef __ESP32_IDF_V44__ + mcpwm->channel[timer].generator[0].utea = 1; +#else /* __ESP32_IDF_V44__ */ + mcpwm->operators[timer].generator[0].gen_utea = 1; +#endif /* __ESP32_IDF_V44__ */ + mcpwm->int_clr.val = mapping->cmpr_tea_int_clr; + mcpwm->int_ena.val |= mapping->cmpr_tea_int_ena; + } else { + bool disable_mcpwm_interrupt = true; +#ifndef HAVE_ESP32S3_PULSE_COUNTER + if (PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim != steps) { +#else + if (PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim_un != steps) { +#endif + // For fast pulses, eventually the ISR is late. So take the current pulse + // count into consideration. + // + // Automatic update for next pulse cnt on pulse counter zero does not + // work. For example the sequence: + // 5 pulses + // 1 pause ==> here need to store 3, but not + // available yet 3 pulses + // + // Read counter +#ifndef HAVE_ESP32S3_PULSE_COUNTER + uint16_t val1 = steps - PCNT.cnt_unit[pcnt_unit].cnt_val; +#else + uint16_t val1 = steps - PCNT.cnt_unit[pcnt_unit].pulse_cnt_un; +#endif + // Clear flag for l-->h transition + mcpwm->int_clr.val = mapping->cmpr_tea_int_clr; + // Read counter again +#ifndef HAVE_ESP32S3_PULSE_COUNTER + uint16_t val2 = steps - PCNT.cnt_unit[pcnt_unit].cnt_val; +#else + uint16_t val2 = steps - PCNT.cnt_unit[pcnt_unit].pulse_cnt_un; +#endif + // If no pulse arrives between val1 and val2: + // val2 == val1 + // If pulse arrives between val1 and int_clr: + // mcpwm status is cleared and val2 == val1+1 + // If pulse arrives between int_clr and val2: + // mcpwm status is set and val2 == val1+1 + // => mcwpm status info is not reliable, so clear again + if (val1 != val2) { + // Clear flag again. No pulse can be expected between val2 and here + // cppcheck-suppress redundantAssignment + mcpwm->int_clr.val = mapping->cmpr_tea_int_clr; + } + + // is updated only on zero +#ifndef HAVE_ESP32S3_PULSE_COUNTER + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim = val2; +#else + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim_un = val2; +#endif + // force take over + isr_pcnt_counter_clear(pcnt_unit); + // Check, if pulse has come in + if ((mcpwm->int_raw.val & mapping->cmpr_tea_int_raw) != 0) { + // Pulse has come in + // Check if the pulse has been counted or not +#ifndef HAVE_ESP32S3_PULSE_COUNTER + if (PCNT.cnt_unit[pcnt_unit].cnt_val == 0) { +#else + if (PCNT.cnt_unit[pcnt_unit].pulse_cnt_un == 0) { +#endif + // pulse hasn't been counted, so adjust the limit + // is updated only on zero +#ifndef HAVE_ESP32S3_PULSE_COUNTER + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim = val2 - 1; +#else + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim_un = val2 - 1; +#endif + // force take over + isr_pcnt_counter_clear(pcnt_unit); + + // In case val2 == 1, then there may be a problem. + // The pulse counter may not cause any interrupt with cnt_h_lim == 0 + // and if the mcpwm-interrupt is disabled, then the queue is stalled. + // in this case, we should leave the mcpwm enabled + disable_mcpwm_interrupt = val2 > 0; + } + } + } + // disable mcpwm interrupt + if (disable_mcpwm_interrupt) { + mcpwm->int_ena.val &= ~mapping->cmpr_tea_int_ena; + } + // timer value = 1 - upcounting: output high +#ifndef __ESP32_IDF_V44__ + mcpwm->channel[timer].generator[0].utea = 2; +#else /* __ESP32_IDF_V44__ */ + mcpwm->operators[timer].generator[0].gen_utea = 2; +#endif /* __ESP32_IDF_V44__ */ + } +} + +static void IRAM_ATTR init_stop(StepperQueue* q) { + // init stop is normally called after the first command, + // because the second command is entered too late + // and after the last command aka running out of commands. + const struct mapping_s* mapping = + static_cast(q->driver_data); + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + volatile mcpwm_dev_t* mcpwm = mcpwm_unit == MCPWM_UNIT_0 ? &MCPWM0 : &MCPWM1; + uint8_t timer = mapping->timer; +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].mode.start = 0; // 0: stop at TEZ +#else /* __ESP32_IDF_V44__ */ + mcpwm->timer[timer].timer_cfg1.timer_start = 0; // 0: stop at TEZ +#endif /* __ESP32_IDF_V44__ */ + // timer value = 1 - upcounting: output low + mcpwm->int_ena.val &= ~mapping->cmpr_tea_int_ena; + // PCNT.conf_unit[mapping->pcnt_unit].conf2.cnt_h_lim = 1; + q->_isRunning = false; +} + +static void IRAM_ATTR what_is_next(StepperQueue* q) { + // when starting the queue, apply_command for the first entry is called. + // the read pointer stays at this position. This function is reached, + // if the command to which read pointer points to is completed. + bool isPrepared = q->_nextCommandIsPrepared; + q->_nextCommandIsPrepared = false; + uint8_t rp = q->read_idx; + if (rp != q->next_write_idx) { + rp++; + q->read_idx = rp; + if (rp != q->next_write_idx) { + const struct queue_entry* e_curr = &q->entry[rp & QUEUE_LEN_MASK]; + if (!isPrepared) { + prepare_for_next_command(q, e_curr); // a no-op for pause command + const struct mapping_s* mapping = + static_cast(q->driver_data); + isr_pcnt_counter_clear(mapping->pcnt_unit); + } + apply_command(q, e_curr); + rp++; + if ((rp != q->next_write_idx) && (e_curr->steps != 0)) { + // cnt_h_lim is latched on counter zero. prepare() is a no-op for + // pauses, so prefetching after a pause leaves the previous step + // count active (e.g. -26, pause, +10 ran as +26). The next ISR + // prepares and clears instead. + const struct queue_entry* e_next = &q->entry[rp & QUEUE_LEN_MASK]; + q->_nextCommandIsPrepared = true; + prepare_for_next_command(q, e_next); // a no-op for pause command + } + return; + } + } + // no more commands: stop timer at period end + init_stop(q); +} + +static void IRAM_ATTR pcnt_isr_service(void* arg) { + StepperQueue* q = static_cast(arg); + what_is_next(q); +} + +// MCPWM_SERVICE is only used in case of pause +#ifndef __ESP32_IDF_V44__ + +#define MCPWM_SERVICE(mcpwm, TIMER, pcnt) \ + if (mcpwm.int_st.cmpr##TIMER##_tea_int_st != 0) { \ + /*managed in apply_command() */ \ + /*mcpwm.int_clr.cmpr##TIMER##_tea_int_clr = 1;*/ \ + StepperQueue* q = &fas_queue[pcnt]; \ + what_is_next(q); \ + } + +#else /* __ESP32_IDF_V44__ */ + +#define MCPWM_SERVICE(mcpwm, TIMER, pcnt) \ + if (mcpwm.int_st.op##TIMER##_tea_int_st != 0) { \ + /*managed in apply_command() */ \ + /*mcpwm.int_clr.cmpr##TIMER##_tea_int_clr = 1;*/ \ + StepperQueue* q = &fas_queue[pcnt]; \ + what_is_next(q); \ + } + +#endif /* __ESP32_IDF_V44__ */ + +static void IRAM_ATTR mcpwm0_isr_service(void* arg) { + // For whatever reason, this interrupt is constantly called even with int_st = + // 0 while the timer is running + MCPWM_SERVICE(MCPWM0, 0, 0); + MCPWM_SERVICE(MCPWM0, 1, 1); + MCPWM_SERVICE(MCPWM0, 2, 2); +} +static void IRAM_ATTR mcpwm1_isr_service(void* arg) { + MCPWM_SERVICE(MCPWM1, 0, 3); +#ifndef HAVE_ESP32S3_PULSE_COUNTER + MCPWM_SERVICE(MCPWM1, 1, 4); + MCPWM_SERVICE(MCPWM1, 2, 5); +#endif +} + +void StepperQueue::init_mcpwm_pcnt(uint8_t channel_num, uint8_t step_pin) { +#ifdef TEST_PROBE + pinMode(TEST_PROBE, OUTPUT); +#endif + + _step_pin = step_pin; + + const struct mapping_s* mapping = &channel2mapping[channel_num]; + driver_data = static_cast(mapping); + + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + mcpwm_dev_t* mcpwm = mcpwm_unit == MCPWM_UNIT_0 ? &MCPWM0 : &MCPWM1; + pcnt_unit_t pcnt_unit = mapping->pcnt_unit; + uint8_t timer = mapping->timer; + + pcnt_config_t cfg; + // if step_pin is not set here (or 0x30), then it does not work + cfg.pulse_gpio_num = step_pin; // static 0 is 0x30, static 1 is 0x38 + cfg.ctrl_gpio_num = PCNT_PIN_NOT_USED; // static 0 is 0x30, static 1 is 0x38 + cfg.lctrl_mode = PCNT_MODE_KEEP; + cfg.hctrl_mode = PCNT_MODE_KEEP; + cfg.pos_mode = PCNT_COUNT_INC; // increment on rising edge + cfg.neg_mode = PCNT_COUNT_DIS; // ignore falling edge + cfg.counter_h_lim = 1; + cfg.counter_l_lim = 0; + cfg.unit = pcnt_unit; + cfg.channel = PCNT_CHANNEL_0; + pcnt_unit_config(&cfg); + +#ifndef HAVE_ESP32S3_PULSE_COUNTER + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim = 1; + PCNT.conf_unit[pcnt_unit].conf0.thr_h_lim_en = 1; + PCNT.conf_unit[pcnt_unit].conf0.thr_l_lim_en = 0; +#else + PCNT.conf_unit[pcnt_unit].conf2.cnt_h_lim_un = 1; + PCNT.conf_unit[pcnt_unit].conf0.thr_h_lim_en_un = 1; + PCNT.conf_unit[pcnt_unit].conf0.thr_l_lim_en_un = 0; +#endif + + pcnt_counter_clear(pcnt_unit); + pcnt_counter_resume(pcnt_unit); + pcnt_event_enable(pcnt_unit, PCNT_EVT_H_LIM); + if (channel_num == 0) { + // isr_service_install apparently enables the interrupt + PCNT.int_clr.val = PCNT.int_st.val; + pcnt_isr_service_install(ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM); + } + pcnt_isr_handler_add(pcnt_unit, pcnt_isr_service, static_cast(this)); + + if (timer == 0) { + // Init mcwpm module for use + periph_module_enable(mcpwm_unit == MCPWM_UNIT_0 ? PERIPH_PWM0_MODULE + : PERIPH_PWM1_MODULE); + mcpwm->int_ena.val = 0; // disable all interrupts + mcpwm_isr_register( + mcpwm_unit, + mcpwm_unit == MCPWM_UNIT_0 ? mcpwm0_isr_service : mcpwm1_isr_service, + NULL, ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_SHARED, NULL); + + // 160 MHz/5 = 32 MHz => 16 MHz in up/down-mode +#ifndef __ESP32_IDF_V44__ + mcpwm->clk_cfg.prescale = 5 - 1; +#else /* __ESP32_IDF_V44__ */ + mcpwm->clk_cfg.clk_prescale = 5 - 1; +#endif /* __ESP32_IDF_V44__ */ + + // timer 0 is input for operator 0 + // timer 1 is input for operator 1 + // timer 2 is input for operator 2 +#ifndef __ESP32_IDF_V44__ + mcpwm->timer_sel.operator0_sel = 0; + mcpwm->timer_sel.operator1_sel = 1; + mcpwm->timer_sel.operator2_sel = 2; +#else /* __ESP32_IDF_V44__ */ + mcpwm->operator_timersel.operator0_timersel = 0; + mcpwm->operator_timersel.operator1_timersel = 1; + mcpwm->operator_timersel.operator2_timersel = 2; +#endif /* __ESP32_IDF_V44__ */ + } +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].period.upmethod = 1; // 0 = immediate update, 1 = TEZ + mcpwm->timer[timer].period.prescale = TIMER_PRESCALER; + mcpwm->timer[timer].period.period = 400; // Random value + mcpwm->timer[timer].mode.mode = 3; // 3=up/down counting + mcpwm->timer[timer].mode.start = 0; // 0: stop at TEZ +#else /* __ESP32_IDF_V44__ */ + // 0 = immediate update, 1 = TEZ + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 1; + mcpwm->timer[timer].timer_cfg0.timer_prescale = TIMER_PRESCALER; + mcpwm->timer[timer].timer_cfg0.timer_period = 400; // Random value + mcpwm->timer[timer].timer_cfg1.timer_mod = 3; // 3=up/down counting + mcpwm->timer[timer].timer_cfg1.timer_start = 0; // 0: stop at TEZ +#endif /* __ESP32_IDF_V44__ */ + + // this sequence should reset the timer to 0 +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].sync.timer_phase = 0; // prepare value of 0 + mcpwm->timer[timer].sync.in_en = 1; // enable sync + mcpwm->timer[timer].sync.sync_sw ^= 1; // force a sync + mcpwm->timer[timer].sync.in_en = 0; // disable sync + + mcpwm->channel[timer].cmpr_cfg.a_upmethod = 0; // 0 = immediate update + mcpwm->channel[timer].cmpr_value[0].cmpr_val = 1; // set compare value A + mcpwm->channel[timer].generator[0].val = 0; // clear all trigger actions + mcpwm->channel[timer].generator[1].val = 0; // clear all trigger actions + mcpwm->channel[timer].generator[0].dtep = 1; // low at period + mcpwm->channel[timer].db_cfg.val = 0; // edge delay disabled + mcpwm->channel[timer].carrier_cfg.val = 0; // carrier disabled +#else /* __ESP32_IDF_V44__ */ + mcpwm->timer[timer].timer_sync.timer_phase = 0; // prepare value of 0 + mcpwm->timer[timer].timer_sync.timer_synci_en = 1; // enable sync + mcpwm->timer[timer].timer_sync.timer_sync_sw ^= 1; // force a sync + mcpwm->timer[timer].timer_sync.timer_synci_en = 0; // disable sync + + mcpwm->operators[timer].gen_stmp_cfg.gen_a_upmethod = + 0; // 0 = immediate update + mcpwm->operators[timer].timestamp[0].gen = 1; // set compare value A + mcpwm->operators[timer].generator[0].val = 0; // clear all trigger actions + mcpwm->operators[timer].generator[1].val = 0; // clear all trigger actions + mcpwm->operators[timer].generator[0].gen_dtep = 1; // low at period + mcpwm->operators[timer].dt_cfg.val = 0; // edge delay disabled + mcpwm->operators[timer].carrier_cfg.val = 0; // carrier disabled +#endif /* __ESP32_IDF_V44__ */ + + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + + // at last, link mcpwm to output pin and back into pcnt input + connect(); +} + +void StepperQueue::connect_mcpwm_pcnt() { + const struct mapping_s* mapping = + static_cast(driver_data); + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + mcpwm_gpio_init(mcpwm_unit, mapping->pwm_output_pin, _step_pin); + // Doesn't work with gpio_matrix_in + // gpio_matrix_in(step_pin, mapping->input_sig_index, false); + gpio_iomux_in(_step_pin, mapping->input_sig_index); +} + +void StepperQueue::disconnect_mcpwm_pcnt() { + // sig_index = 0x100 => cancel output + gpio_matrix_out(_step_pin, 0x100, false, false); + // untested alternative: + // gpio_reset_pin((gpio_num_t)q->step_pin); +} + +// Mechanism is like this, starting from stopped motor: +// +// * init counter +// * init mcpwm +// * start mcpwm +// * -- pcnt counter counts every L->H-transition at mcpwm.timer = 1 +// * -- if counter reaches planned steps, then counter is reset and +// * interrupt is created +// +// * pcnt interrupt: available time is from mcpwm.timer = 1+x to period +// - read next commmand: store period in counter shadow and +// steps in pcnt +// - without next command: set mcpwm to stop mode on reaching +// period +// + +void StepperQueue::startQueue_mcpwm_pcnt() { +#ifdef TEST_PROBE + // The time used by this command can have an impact + digitalWrite(TEST_PROBE, digitalRead(TEST_PROBE) == HIGH ? LOW : HIGH); +#endif + const struct mapping_s* mapping = + static_cast(driver_data); + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + volatile mcpwm_dev_t* mcpwm = mcpwm_unit == MCPWM_UNIT_0 ? &MCPWM0 : &MCPWM1; + uint8_t timer = mapping->timer; + + // apply_command() assumes the pcnt counter to contain executed steps + // and deduct this from the new command. For a starting motor + // need to make sure, that the counter is 0. (issue #33) + pcnt_unit_t pcnt_unit = mapping->pcnt_unit; + pcnt_counter_clear(pcnt_unit); + + _isRunning = true; + _nextCommandIsPrepared = false; + struct queue_entry* e = &entry[read_idx & QUEUE_LEN_MASK]; + apply_command(this, e); + +#ifndef __ESP32_IDF_V44__ + mcpwm->timer[timer].mode.start = 2; // 2=run continuous +#else /* __ESP32_IDF_V44__ */ + mcpwm->timer[timer].timer_cfg1.timer_start = 2; // 2=run continuous +#endif /* __ESP32_IDF_V44__ */ +} +void StepperQueue::forceStop_mcpwm_pcnt() { + init_stop(this); + read_idx = next_write_idx; +} +bool StepperQueue::isReadyForCommands_mcpwm_pcnt() const { + if (isRunning()) { + return true; + } + const struct mapping_s* mapping = + static_cast(driver_data); + mcpwm_unit_t mcpwm_unit = mapping->mcpwm_unit; + const mcpwm_dev_t* mcpwm = mcpwm_unit == MCPWM_UNIT_0 ? &MCPWM0 : &MCPWM1; + uint8_t timer = mapping->timer; +#ifndef __ESP32_IDF_V44__ + if (mcpwm->timer[timer].status.value > 1) { +#else /* __ESP32_IDF_V44__ */ + if (mcpwm->timer[timer].timer_status.timer_value > 1) { +#endif /* __ESP32_IDF_V44__ */ + return false; + } + return true; + // #ifndef __ESP32_IDF_V44__ + // return (mcpwm->timer[timer].mode.start != 2); // 2=run continuous + // #else /* __ESP32_IDF_V44__ */ + // return (mcpwm->timer[timer].timer_cfg1.timer_start != 2); // 2=run + // continuous + // #endif /* __ESP32_IDF_V44__ */ +} +uint16_t StepperQueue::_getPerformedPulses_mcpwm_pcnt() const { + const struct mapping_s* mapping = + static_cast(driver_data); +#ifndef HAVE_ESP32S3_PULSE_COUNTER + return PCNT.cnt_unit[mapping->pcnt_unit].cnt_val; +#else + return PCNT.cnt_unit[mapping->pcnt_unit].pulse_cnt_un; +#endif +} + +#endif diff --git a/src/pd_esp32/StepperISR_idf5_esp32_mcpwm_pcnt.cpp b/src/pd_esp32/StepperISR_idf5_esp32_mcpwm_pcnt.cpp new file mode 100644 index 0000000..01e99a5 --- /dev/null +++ b/src/pd_esp32/StepperISR_idf5_esp32_mcpwm_pcnt.cpp @@ -0,0 +1,438 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (ESP_IDF_VERSION_MAJOR == 5) + +#include + +#define TIMER_BIT(timer) (1 << (timer + 15)) + +#if defined(CONFIG_IDF_TARGET_ESP32S3) +#define FAS_CNT_H_LIM cnt_h_lim_un +#define FAS_CNT_VAL pulse_cnt_un +#define FAS_THR_H_LIM_EN thr_h_lim_en_un +#define FAS_THR_L_LIM_EN thr_l_lim_en_un +#elif defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_CNT_H_LIM cnt_h_lim +#define FAS_CNT_VAL pulse_cnt +#define FAS_THR_H_LIM_EN thr_h_lim_en +#define FAS_THR_L_LIM_EN thr_l_lim_en +#else +#define FAS_CNT_H_LIM cnt_h_lim +#define FAS_CNT_VAL cnt_val +#define FAS_THR_H_LIM_EN thr_h_lim_en +#define FAS_THR_L_LIM_EN thr_l_lim_en +#endif + +#if defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_GPIO_OUT_SEL out_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 128 +#define FAS_GEN_A_UPMETHOD cmpr_a_upmethod +#elif defined(CONFIG_IDF_TARGET_ESP32S3) +#define FAS_GPIO_OUT_SEL func_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 0x100 +#define FAS_GEN_A_UPMETHOD gen_a_upmethod +#else +#define FAS_GPIO_OUT_SEL func_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 0x100 +#define FAS_GEN_A_UPMETHOD gen_a_upmethod +#endif + +#if defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_MCPWM_PRESCALE (3 - 1) +#else +#define FAS_MCPWM_PRESCALE (5 - 1) +#endif + +struct pcnt_unit_internal { + void* group; + portMUX_TYPE spinlock; + int unit_id; +}; + +struct mapping_s { + mcpwm_timer_handle_t timer; + mcpwm_oper_handle_t oper; + mcpwm_cmpr_handle_t cmpr; + mcpwm_gen_handle_t gen; + pcnt_unit_handle_t pcnt_unit; + uint8_t pcnt_unit_id; + uint8_t timer_in_group; + mcpwm_dev_t* mcpwm; +}; + +static struct mapping_s channel2mapping[NUM_QUEUES]; +static StepperQueue* pcnt_unit_to_queue[QUEUES_MCPWM_PCNT] = {}; +static bool pcnt_isr_installed = false; + +#define isr_pcnt_counter_clear(pcnt_unit_id) \ + REG_SET_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit_id))); \ + REG_CLR_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit_id))) + +static inline uint8_t _group_for_timer(int timer_num) { +#if SOC_MCPWM_GROUPS > 1 + return timer_num < SOC_MCPWM_TIMERS_PER_GROUP ? 0 : 1; +#else + return 0; +#endif +} + +static inline mcpwm_dev_t* _mcpwm_for_timer(int timer_num) { +#if SOC_MCPWM_GROUPS > 1 + return timer_num < SOC_MCPWM_TIMERS_PER_GROUP ? &MCPWM0 : &MCPWM1; +#else + return &MCPWM0; +#endif +} + +static void IRAM_ATTR prepare_for_next_command( + const StepperQueue* queue, const struct queue_entry* e_next) { + uint8_t next_steps = e_next->steps; + if (next_steps > 0) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = next_steps; + } +} + +static void IRAM_ATTR apply_command(StepperQueue* queue, + const struct queue_entry* e) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + uint8_t timer = mapping->timer_in_group; + uint8_t steps = e->steps; + if (e->toggle_dir) { + LL_TOGGLE_PIN(queue->dirPin); + } + uint16_t ticks = e->ticks; + if (mcpwm->timer[timer].timer_status.timer_value <= 1) { + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 0; + } else { + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 1; + } + mcpwm->timer[timer].timer_cfg0.timer_period = ticks; + if (steps == 0) { + mcpwm->operators[timer].generator[0].gen_utea = 1; + mcpwm->int_clr.val = TIMER_BIT(timer); + mcpwm->int_ena.val |= TIMER_BIT(timer); + } else { + bool disable_mcpwm_interrupt = true; + if (PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM != steps) { + uint16_t val1 = steps - PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL; + mcpwm->int_clr.val = TIMER_BIT(timer); + uint16_t val2 = steps - PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL; + if (val1 != val2) { + mcpwm->int_clr.val = TIMER_BIT(timer); + } + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = val2; + isr_pcnt_counter_clear(pcnt_unit_id); + if ((mcpwm->int_raw.val & TIMER_BIT(timer)) != 0) { + if (PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL == 0) { + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = val2 - 1; + isr_pcnt_counter_clear(pcnt_unit_id); + disable_mcpwm_interrupt = val2 > 0; + } + } + } + if (disable_mcpwm_interrupt) { + mcpwm->int_ena.val &= ~TIMER_BIT(timer); + } + mcpwm->operators[timer].generator[0].gen_utea = 2; + } +} + +static void IRAM_ATTR init_stop(StepperQueue* q) { + const struct mapping_s* mapping = + static_cast(q->driver_data); + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t timer = mapping->timer_in_group; + mcpwm->timer[timer].timer_cfg1.timer_start = 0; + mcpwm->int_ena.val &= ~TIMER_BIT(timer); + mcpwm->operators[timer].generator[0].gen_utea = 1; + q->_isRunning = false; +} + +static void IRAM_ATTR what_is_next(StepperQueue* q) { + bool isPrepared = q->_nextCommandIsPrepared; + q->_nextCommandIsPrepared = false; + uint8_t rp = q->read_idx; + if (rp != q->next_write_idx) { + rp++; + q->read_idx = rp; + if (rp != q->next_write_idx) { + const struct queue_entry* e_curr = &q->entry[rp & QUEUE_LEN_MASK]; + if (!isPrepared) { + prepare_for_next_command(q, e_curr); + const struct mapping_s* mapping = + static_cast(q->driver_data); + isr_pcnt_counter_clear(mapping->pcnt_unit_id); + } + apply_command(q, e_curr); + rp++; + if ((rp != q->next_write_idx) && (e_curr->steps != 0)) { + const struct queue_entry* e_next = &q->entry[rp & QUEUE_LEN_MASK]; + q->_nextCommandIsPrepared = true; + prepare_for_next_command(q, e_next); + } + return; + } + } + init_stop(q); +} + +static void IRAM_ATTR pcnt_isr_handler(void* arg) { + (void)arg; + uint32_t int_st = PCNT.int_st.val; + uint32_t mask = (1 << QUEUES_MCPWM_PCNT) - 1; + uint32_t pending = int_st & mask; + if (pending == 0) return; + PCNT.int_clr.val = pending; + for (int i = 0; i < QUEUES_MCPWM_PCNT; i++) { + if (pending & (1 << i)) { + StepperQueue* q = pcnt_unit_to_queue[i]; + if (q) { + what_is_next(q); + } + } + } +} + +static bool IRAM_ATTR mcpwm_on_reach(mcpwm_cmpr_handle_t cmpr, + const mcpwm_compare_event_data_t* edata, + void* user_ctx) { + what_is_next(static_cast(user_ctx)); + return false; +} + +void StepperQueue::init_mcpwm_pcnt(uint8_t channel_num, uint8_t step_pin) { + _step_pin = step_pin; + + struct mapping_s* mapping = &channel2mapping[channel_num]; + driver_data = static_cast(mapping); + + int timer_num = channel_num; + uint8_t group_id = _group_for_timer(timer_num); + uint8_t timer_in_group = timer_num % SOC_MCPWM_TIMERS_PER_GROUP; + uint8_t pcnt_unit_id = timer_num; + + pcnt_unit_config_t pcnt_cfg = {.low_limit = -32768, + .high_limit = 32767, + .intr_priority = 1, + .flags = {.accum_count = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_new_unit(&pcnt_cfg, &mapping->pcnt_unit)); + + pcnt_chan_config_t chan_cfg = {.edge_gpio_num = step_pin, + .level_gpio_num = -1, + .flags = {.invert_edge_input = 0, + .invert_level_input = 0, + .virt_edge_io_level = 0, + .virt_level_io_level = 0, + .io_loop_back = 0}}; + pcnt_channel_handle_t pcnt_chan; + ESP_ERROR_CHECK_WITHOUT_ABORT( + pcnt_new_channel(mapping->pcnt_unit, &chan_cfg, &pcnt_chan)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + pcnt_channel_set_edge_action(pcnt_chan, PCNT_CHANNEL_EDGE_ACTION_INCREASE, + PCNT_CHANNEL_EDGE_ACTION_HOLD)); + + struct pcnt_unit_internal* unit = + reinterpret_cast(mapping->pcnt_unit); + mapping->pcnt_unit_id = unit->unit_id; + mapping->timer_in_group = timer_in_group; + + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = 1; + PCNT.conf_unit[pcnt_unit_id].conf0.FAS_THR_H_LIM_EN = 1; + PCNT.conf_unit[pcnt_unit_id].conf0.FAS_THR_L_LIM_EN = 0; + + pcnt_unit_to_queue[pcnt_unit_id] = this; + // pcnt_new_unit() enables the unit's interrupt only when it installs its own + // ISR, i.e. only for accum_count; this driver counts by itself and asks for + // accum_count = 0, so the call above CLEARED this unit's int_ena bit. + // Re-assert it on every init, not once inside the pcnt_isr_installed guard: + // otherwise every queue after the first drains on hardware alone and + // free-runs forever. + PCNT.int_clr.val = (1 << pcnt_unit_id); + PCNT.int_ena.val |= (1 << pcnt_unit_id); + if (!pcnt_isr_installed) { + PCNT.int_clr.val = PCNT.int_st.val; + PCNT.int_ena.val |= ((1 << QUEUES_MCPWM_PCNT) - 1); + esp_intr_alloc( + ETS_PCNT_INTR_SOURCE, + ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_LEVEL1, + pcnt_isr_handler, NULL, NULL); + pcnt_isr_installed = true; + } + + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_clear_count(mapping->pcnt_unit)); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_enable(mapping->pcnt_unit)); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_start(mapping->pcnt_unit)); + + mcpwm_timer_config_t timer_cfg = { + .group_id = group_id, + .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT, + .resolution_hz = TICKS_PER_S, + .count_mode = MCPWM_TIMER_COUNT_MODE_UP_DOWN, + .period_ticks = 400, + .intr_priority = 1, + .flags = {.update_period_on_empty = 0, + .update_period_on_sync = 0, +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 4, 0) + // added in IDF 5.4; absent from 5.3's mcpwm_timer_config_t + .allow_pd = 0 +#endif + }}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_new_timer(&timer_cfg, &mapping->timer)); + + mcpwm_operator_config_t oper_cfg = {.group_id = group_id, + .intr_priority = 1, + .flags = {.update_gen_action_on_tez = 1, + .update_gen_action_on_tep = 1, + .update_gen_action_on_sync = 0, + .update_dead_time_on_tez = 0, + .update_dead_time_on_tep = 0, + .update_dead_time_on_sync = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_new_operator(&oper_cfg, &mapping->oper)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_operator_connect_timer(mapping->oper, mapping->timer)); + + mcpwm_comparator_config_t cmpr_cfg = {.intr_priority = 1, + .flags = {.update_cmp_on_tez = 0, + .update_cmp_on_tep = 0, + .update_cmp_on_sync = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_new_comparator(mapping->oper, &cmpr_cfg, &mapping->cmpr)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_comparator_set_compare_value(mapping->cmpr, 1)); + + mcpwm_generator_config_t gen_cfg = {.gen_gpio_num = step_pin, + .flags = {.invert_pwm = 0, + .io_loop_back = 0, + .io_od_mode = 0, + .pull_up = 0, + .pull_down = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_new_generator(mapping->oper, &gen_cfg, &mapping->gen)); + + mcpwm_comparator_event_callbacks_t cmpr_cbs = {.on_reach = mcpwm_on_reach}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_comparator_register_event_callbacks( + mapping->cmpr, &cmpr_cbs, static_cast(this))); + + mcpwm_dev_t* mcpwm = _mcpwm_for_timer(timer_num); + mapping->mcpwm = mcpwm; + + mcpwm->operators[timer_in_group].generator[0].val = 0; + mcpwm->operators[timer_in_group].generator[1].val = 0; + mcpwm->operators[timer_in_group].generator[0].gen_dtep = 1; + mcpwm->operators[timer_in_group].gen_stmp_cfg.FAS_GEN_A_UPMETHOD = 0; + mcpwm->operators[timer_in_group].dt_cfg.val = 0; + mcpwm->operators[timer_in_group].carrier_cfg.val = 0; + mcpwm->operators[timer_in_group].gen_force.val = 0; + // 160 MHz/5 (H2: 96 MHz/3) = 32 MHz => 16 MHz in up/down-mode. + // mcpwm_new_timer(resolution_hz=TICKS_PER_S) also sets timer_prescale to + // reach 16 MHz; leaving that in place with clk_prescale=5 is ~5x too slow. + mcpwm->clk_cfg.clk_prescale = FAS_MCPWM_PRESCALE; + mcpwm->timer[timer_in_group].timer_cfg0.timer_prescale = 0; + mcpwm->operator_timersel.val = 0; + mcpwm->operator_timersel.operator0_timersel = 0; + mcpwm->operator_timersel.operator1_timersel = 1; + mcpwm->operator_timersel.operator2_timersel = 2; + +#if SOC_MCPWM_GROUPS > 1 + if (group_id == 0) { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + timer_in_group * 2; + } else { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM1_OUT0A_IDX + timer_in_group * 2; + } +#else + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + timer_in_group * 2; +#endif + GPIO.func_out_sel_cfg[step_pin].oen_sel = 0; + + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_timer_enable(mapping->timer)); + + connect(); +} + +void StepperQueue::connect_mcpwm_pcnt() { + const struct mapping_s* mapping = + static_cast(driver_data); + uint8_t step_pin = _step_pin; + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + + int signal = + pcnt_periph_signals.groups[0].units[pcnt_unit_id].channels[0].pulse_sig; +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 5, 0) + // gpio_iomux_in() is deprecated in IDF 5.5. Do the same two register + // writes inline to keep the IO_MUX routing and avoid any extra overhead. + gpio_ll_set_input_signal_from(&GPIO, signal, false); + gpio_ll_input_enable(&GPIO, step_pin); +#else + gpio_iomux_in(step_pin, signal); +#endif + +#if SOC_MCPWM_GROUPS > 1 + if (mapping->mcpwm == &MCPWM0) { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + pcnt_unit_id * 2; + } else { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM1_OUT0A_IDX + (pcnt_unit_id - SOC_MCPWM_TIMERS_PER_GROUP) * 2; + } +#else + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + pcnt_unit_id * 2; +#endif + GPIO.func_out_sel_cfg[step_pin].oen_sel = 0; +} + +void StepperQueue::disconnect_mcpwm_pcnt() { + GPIO.func_out_sel_cfg[_step_pin].FAS_GPIO_OUT_SEL = + FAS_GPIO_OUT_SEL_DISCONNECT; +} + +void StepperQueue::startQueue_mcpwm_pcnt() { + const struct mapping_s* mapping = + static_cast(driver_data); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_clear_count(mapping->pcnt_unit)); + + _isRunning = true; + _nextCommandIsPrepared = false; + struct queue_entry* e = &entry[read_idx & QUEUE_LEN_MASK]; + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t timer = mapping->timer_in_group; + mcpwm->operators[timer].gen_cfg0.gen_cfg_upmethod = 0; + apply_command(this, e); + mcpwm->operators[timer].gen_cfg0.gen_cfg_upmethod = (1 << 0) | (1 << 1); + + mcpwm_timer_start_stop(mapping->timer, MCPWM_TIMER_START_NO_STOP); +} + +void StepperQueue::forceStop_mcpwm_pcnt() { + init_stop(this); + read_idx = next_write_idx; +} + +bool StepperQueue::isReadyForCommands_mcpwm_pcnt() const { + if (isRunning()) { + return true; + } + const struct mapping_s* mapping = + static_cast(driver_data); + uint8_t timer = mapping->timer_in_group; + if (mapping->mcpwm->timer[timer].timer_status.timer_value > 1) { + return false; + } + return true; +} + +uint16_t StepperQueue::_getPerformedPulses_mcpwm_pcnt() const { + const struct mapping_s* mapping = + static_cast(driver_data); + return PCNT.cnt_unit[mapping->pcnt_unit_id].FAS_CNT_VAL; +} + +#endif diff --git a/src/pd_esp32/StepperISR_idf6_esp32_mcpwm_pcnt.cpp b/src/pd_esp32/StepperISR_idf6_esp32_mcpwm_pcnt.cpp new file mode 100644 index 0000000..81900d5 --- /dev/null +++ b/src/pd_esp32/StepperISR_idf6_esp32_mcpwm_pcnt.cpp @@ -0,0 +1,429 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (ESP_IDF_VERSION_MAJOR == 6) + +#include + +#define TIMER_BIT(timer) (1 << (timer + 15)) + +#if defined(CONFIG_IDF_TARGET_ESP32S3) +#define FAS_CNT_H_LIM cnt_h_lim_un +#define FAS_CNT_VAL pulse_cnt_un +#define FAS_THR_H_LIM_EN thr_h_lim_en_un +#define FAS_THR_L_LIM_EN thr_l_lim_en_un +#elif defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_CNT_H_LIM cnt_h_lim +#define FAS_CNT_VAL pulse_cnt +#define FAS_THR_H_LIM_EN thr_h_lim_en +#define FAS_THR_L_LIM_EN thr_l_lim_en +#else +#define FAS_CNT_H_LIM cnt_h_lim +#define FAS_CNT_VAL cnt_val +#define FAS_THR_H_LIM_EN thr_h_lim_en +#define FAS_THR_L_LIM_EN thr_l_lim_en +#endif + +#if defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_GPIO_OUT_SEL out_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 128 +#define FAS_GEN_A_UPMETHOD cmpr_a_upmethod +#elif defined(CONFIG_IDF_TARGET_ESP32S3) +#define FAS_GPIO_OUT_SEL func_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 0x100 +#define FAS_GEN_A_UPMETHOD gen_a_upmethod +#else +#define FAS_GPIO_OUT_SEL func_sel +#define FAS_GPIO_OUT_SEL_DISCONNECT 0x100 +#define FAS_GEN_A_UPMETHOD gen_a_upmethod +#endif + +#if defined(CONFIG_IDF_TARGET_ESP32H2) +#define FAS_MCPWM_PRESCALE (3 - 1) +#else +#define FAS_MCPWM_PRESCALE (5 - 1) +#endif + +struct pcnt_unit_internal { + void* group; + portMUX_TYPE spinlock; + int unit_id; +}; + +struct mapping_s { + mcpwm_timer_handle_t timer; + mcpwm_oper_handle_t oper; + mcpwm_cmpr_handle_t cmpr; + mcpwm_gen_handle_t gen; + pcnt_unit_handle_t pcnt_unit; + uint8_t pcnt_unit_id; + uint8_t timer_in_group; + mcpwm_dev_t* mcpwm; +}; + +static struct mapping_s channel2mapping[NUM_QUEUES]; +static StepperQueue* pcnt_unit_to_queue[QUEUES_MCPWM_PCNT] = {}; +static bool pcnt_isr_installed = false; + +#define isr_pcnt_counter_clear(pcnt_unit_id) \ + REG_SET_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit_id))); \ + REG_CLR_BIT(PCNT_CTRL_REG, (1 << (2 * pcnt_unit_id))) + +static inline uint8_t _group_for_timer(int timer_num) { +#if SOC_MCPWM_GROUPS > 1 + return timer_num < SOC_MCPWM_TIMERS_PER_GROUP ? 0 : 1; +#else + return 0; +#endif +} + +static inline mcpwm_dev_t* _mcpwm_for_timer(int timer_num) { +#if SOC_MCPWM_GROUPS > 1 + return timer_num < SOC_MCPWM_TIMERS_PER_GROUP ? &MCPWM0 : &MCPWM1; +#else + return &MCPWM0; +#endif +} + +static void IRAM_ATTR prepare_for_next_command( + const StepperQueue* queue, const struct queue_entry* e_next) { + uint8_t next_steps = e_next->steps; + if (next_steps > 0) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = next_steps; + } +} + +static void IRAM_ATTR apply_command(StepperQueue* queue, + const struct queue_entry* e) { + const struct mapping_s* mapping = + static_cast(queue->driver_data); + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + uint8_t timer = mapping->timer_in_group; + uint8_t steps = e->steps; + if (e->toggle_dir) { + LL_TOGGLE_PIN(queue->dirPin); + } + uint16_t ticks = e->ticks; + if (mcpwm->timer[timer].timer_status.timer_value <= 1) { + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 0; + } else { + mcpwm->timer[timer].timer_cfg0.timer_period_upmethod = 1; + } + mcpwm->timer[timer].timer_cfg0.timer_period = ticks; + if (steps == 0) { + mcpwm->operators[timer].generator[0].gen_utea = 1; + mcpwm->int_clr.val = TIMER_BIT(timer); + mcpwm->int_ena.val |= TIMER_BIT(timer); + } else { + bool disable_mcpwm_interrupt = true; + if (PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM != steps) { + uint16_t val1 = steps - PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL; + mcpwm->int_clr.val = TIMER_BIT(timer); + uint16_t val2 = steps - PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL; + if (val1 != val2) { + mcpwm->int_clr.val = TIMER_BIT(timer); + } + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = val2; + isr_pcnt_counter_clear(pcnt_unit_id); + if ((mcpwm->int_raw.val & TIMER_BIT(timer)) != 0) { + if (PCNT.cnt_unit[pcnt_unit_id].FAS_CNT_VAL == 0) { + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = val2 - 1; + isr_pcnt_counter_clear(pcnt_unit_id); + disable_mcpwm_interrupt = val2 > 0; + } + } + } + if (disable_mcpwm_interrupt) { + mcpwm->int_ena.val &= ~TIMER_BIT(timer); + } + mcpwm->operators[timer].generator[0].gen_utea = 2; + } +} + +static void IRAM_ATTR init_stop(StepperQueue* q) { + const struct mapping_s* mapping = + static_cast(q->driver_data); + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t timer = mapping->timer_in_group; + mcpwm->timer[timer].timer_cfg1.timer_start = 0; + mcpwm->int_ena.val &= ~TIMER_BIT(timer); + mcpwm->operators[timer].generator[0].gen_utea = 1; + q->_isRunning = false; +} + +static void IRAM_ATTR what_is_next(StepperQueue* q) { + bool isPrepared = q->_nextCommandIsPrepared; + q->_nextCommandIsPrepared = false; + uint8_t rp = q->read_idx; + if (rp != q->next_write_idx) { + rp++; + q->read_idx = rp; + if (rp != q->next_write_idx) { + const struct queue_entry* e_curr = &q->entry[rp & QUEUE_LEN_MASK]; + if (!isPrepared) { + prepare_for_next_command(q, e_curr); + const struct mapping_s* mapping = + static_cast(q->driver_data); + isr_pcnt_counter_clear(mapping->pcnt_unit_id); + } + apply_command(q, e_curr); + rp++; + if ((rp != q->next_write_idx) && (e_curr->steps != 0)) { + const struct queue_entry* e_next = &q->entry[rp & QUEUE_LEN_MASK]; + q->_nextCommandIsPrepared = true; + prepare_for_next_command(q, e_next); + } + return; + } + } + init_stop(q); +} + +static void IRAM_ATTR pcnt_isr_handler(void* arg) { + (void)arg; + uint32_t int_st = PCNT.int_st.val; + uint32_t mask = (1 << QUEUES_MCPWM_PCNT) - 1; + uint32_t pending = int_st & mask; + if (pending == 0) return; + PCNT.int_clr.val = pending; + for (int i = 0; i < QUEUES_MCPWM_PCNT; i++) { + if (pending & (1 << i)) { + StepperQueue* q = pcnt_unit_to_queue[i]; + if (q) { + what_is_next(q); + } + } + } +} + +static bool IRAM_ATTR mcpwm_on_reach(mcpwm_cmpr_handle_t cmpr, + const mcpwm_compare_event_data_t* edata, + void* user_ctx) { + what_is_next(static_cast(user_ctx)); + return false; +} + +void StepperQueue::init_mcpwm_pcnt(uint8_t channel_num, uint8_t step_pin) { + _step_pin = step_pin; + + struct mapping_s* mapping = &channel2mapping[channel_num]; + driver_data = static_cast(mapping); + + int timer_num = channel_num; + uint8_t group_id = _group_for_timer(timer_num); + uint8_t timer_in_group = timer_num % SOC_MCPWM_TIMERS_PER_GROUP; + uint8_t pcnt_unit_id = timer_num; + + // A designated initializer warns on IDF 6.1+ because group_id is + // missing, and naming group_id fails on IDF 6.0 where the field does + // not exist. Zero-init sets group_id to 0 when the field is present. + pcnt_unit_config_t pcnt_cfg = {}; + pcnt_cfg.clk_src = PCNT_CLK_SRC_DEFAULT; + pcnt_cfg.low_limit = -32768; + pcnt_cfg.high_limit = 32767; + pcnt_cfg.intr_priority = 1; + pcnt_cfg.flags.accum_count = 0; + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_new_unit(&pcnt_cfg, &mapping->pcnt_unit)); + + pcnt_chan_config_t chan_cfg = {.edge_gpio_num = step_pin, + .level_gpio_num = -1, + .flags = {.invert_edge_input = 0, + .invert_level_input = 0, + .virt_edge_io_level = 0, + .virt_level_io_level = 0}}; + pcnt_channel_handle_t pcnt_chan; + ESP_ERROR_CHECK_WITHOUT_ABORT( + pcnt_new_channel(mapping->pcnt_unit, &chan_cfg, &pcnt_chan)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + pcnt_channel_set_edge_action(pcnt_chan, PCNT_CHANNEL_EDGE_ACTION_INCREASE, + PCNT_CHANNEL_EDGE_ACTION_HOLD)); + + struct pcnt_unit_internal* unit = + reinterpret_cast(mapping->pcnt_unit); + mapping->pcnt_unit_id = unit->unit_id; + mapping->timer_in_group = timer_in_group; + + PCNT.conf_unit[pcnt_unit_id].conf2.FAS_CNT_H_LIM = 1; + PCNT.conf_unit[pcnt_unit_id].conf0.FAS_THR_H_LIM_EN = 1; + PCNT.conf_unit[pcnt_unit_id].conf0.FAS_THR_L_LIM_EN = 0; + + pcnt_unit_to_queue[pcnt_unit_id] = this; + // pcnt_new_unit() enables the unit's interrupt only when it installs its own + // ISR, i.e. only for accum_count; this driver counts by itself and asks for + // accum_count = 0, so the call above CLEARED this unit's int_ena bit. + // Re-assert it on every init, not once inside the pcnt_isr_installed guard: + // otherwise every queue after the first drains on hardware alone and + // free-runs forever. + PCNT.int_clr.val = (1 << pcnt_unit_id); + PCNT.int_ena.val |= (1 << pcnt_unit_id); + if (!pcnt_isr_installed) { + PCNT.int_clr.val = PCNT.int_st.val; + PCNT.int_ena.val |= ((1 << QUEUES_MCPWM_PCNT) - 1); + esp_intr_alloc( + ETS_PCNT_INTR_SOURCE, + ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_LEVEL1, + pcnt_isr_handler, NULL, NULL); + pcnt_isr_installed = true; + } + + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_clear_count(mapping->pcnt_unit)); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_enable(mapping->pcnt_unit)); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_start(mapping->pcnt_unit)); + + mcpwm_timer_config_t timer_cfg = { + .group_id = group_id, + .clk_src = MCPWM_TIMER_CLK_SRC_DEFAULT, + .resolution_hz = TICKS_PER_S, + .count_mode = MCPWM_TIMER_COUNT_MODE_UP_DOWN, + .period_ticks = 400, + .intr_priority = 1, + .flags = {.update_period_on_empty = 0, + .update_period_on_sync = 0, + .allow_pd = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_new_timer(&timer_cfg, &mapping->timer)); + + mcpwm_operator_config_t oper_cfg = {.group_id = group_id, + .intr_priority = 1, + .flags = {.update_gen_action_on_tez = 1, + .update_gen_action_on_tep = 1, + .update_gen_action_on_sync = 0, + .update_dead_time_on_tez = 0, + .update_dead_time_on_tep = 0, + .update_dead_time_on_sync = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_new_operator(&oper_cfg, &mapping->oper)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_operator_connect_timer(mapping->oper, mapping->timer)); + + mcpwm_comparator_config_t cmpr_cfg = {.intr_priority = 1, + .flags = {.update_cmp_on_tez = 0, + .update_cmp_on_tep = 0, + .update_cmp_on_sync = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_new_comparator(mapping->oper, &cmpr_cfg, &mapping->cmpr)); + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_comparator_set_compare_value(mapping->cmpr, 1)); + + mcpwm_generator_config_t gen_cfg = {.gen_gpio_num = step_pin, + .flags = {.invert_pwm = 0}}; + ESP_ERROR_CHECK_WITHOUT_ABORT( + mcpwm_new_generator(mapping->oper, &gen_cfg, &mapping->gen)); + + mcpwm_comparator_event_callbacks_t cmpr_cbs = {.on_reach = mcpwm_on_reach}; + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_comparator_register_event_callbacks( + mapping->cmpr, &cmpr_cbs, static_cast(this))); + + mcpwm_dev_t* mcpwm = _mcpwm_for_timer(timer_num); + mapping->mcpwm = mcpwm; + + mcpwm->operators[timer_in_group].generator[0].val = 0; + mcpwm->operators[timer_in_group].generator[1].val = 0; + mcpwm->operators[timer_in_group].generator[0].gen_dtep = 1; + mcpwm->operators[timer_in_group].gen_stmp_cfg.FAS_GEN_A_UPMETHOD = 0; + mcpwm->operators[timer_in_group].dt_cfg.val = 0; + mcpwm->operators[timer_in_group].carrier_cfg.val = 0; + mcpwm->operators[timer_in_group].gen_force.val = 0; + // 160 MHz/5 (H2: 96 MHz/3) = 32 MHz => 16 MHz in up/down-mode. + // mcpwm_new_timer(resolution_hz=TICKS_PER_S) also sets timer_prescale to + // reach 16 MHz; leaving that in place with clk_prescale=5 is ~5x too slow. + mcpwm->clk_cfg.clk_prescale = FAS_MCPWM_PRESCALE; + mcpwm->timer[timer_in_group].timer_cfg0.timer_prescale = 0; + mcpwm->operator_timersel.val = 0; + mcpwm->operator_timersel.operator0_timersel = 0; + mcpwm->operator_timersel.operator1_timersel = 1; + mcpwm->operator_timersel.operator2_timersel = 2; + +#if SOC_MCPWM_GROUPS > 1 + if (group_id == 0) { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + timer_in_group * 2; + } else { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM1_OUT0A_IDX + timer_in_group * 2; + } +#else + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + timer_in_group * 2; +#endif + GPIO.func_out_sel_cfg[step_pin].oen_sel = 0; + + ESP_ERROR_CHECK_WITHOUT_ABORT(mcpwm_timer_enable(mapping->timer)); + + connect(); +} + +void StepperQueue::connect_mcpwm_pcnt() { + const struct mapping_s* mapping = + static_cast(driver_data); + uint8_t step_pin = _step_pin; + uint8_t pcnt_unit_id = mapping->pcnt_unit_id; + + int pulse_sig = + soc_pcnt_signals[0].units[pcnt_unit_id].channels[0].pulse_sig_id_matrix; + gpio_input_enable((gpio_num_t)step_pin); + esp_rom_gpio_connect_in_signal((uint32_t)step_pin, (uint32_t)pulse_sig, + false); + +#if SOC_MCPWM_GROUPS > 1 + if (mapping->mcpwm == &MCPWM0) { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + pcnt_unit_id * 2; + } else { + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM1_OUT0A_IDX + (pcnt_unit_id - SOC_MCPWM_TIMERS_PER_GROUP) * 2; + } +#else + GPIO.func_out_sel_cfg[step_pin].FAS_GPIO_OUT_SEL = + PWM0_OUT0A_IDX + pcnt_unit_id * 2; +#endif + GPIO.func_out_sel_cfg[step_pin].oen_sel = 0; +} + +void StepperQueue::disconnect_mcpwm_pcnt() { + GPIO.func_out_sel_cfg[_step_pin].FAS_GPIO_OUT_SEL = + FAS_GPIO_OUT_SEL_DISCONNECT; +} + +void StepperQueue::startQueue_mcpwm_pcnt() { + const struct mapping_s* mapping = + static_cast(driver_data); + ESP_ERROR_CHECK_WITHOUT_ABORT(pcnt_unit_clear_count(mapping->pcnt_unit)); + + _isRunning = true; + _nextCommandIsPrepared = false; + struct queue_entry* e = &entry[read_idx & QUEUE_LEN_MASK]; + mcpwm_dev_t* mcpwm = mapping->mcpwm; + uint8_t timer = mapping->timer_in_group; + mcpwm->operators[timer].gen_cfg0.gen_cfg_upmethod = 0; + apply_command(this, e); + mcpwm->operators[timer].gen_cfg0.gen_cfg_upmethod = (1 << 0) | (1 << 1); + + mcpwm_timer_start_stop(mapping->timer, MCPWM_TIMER_START_NO_STOP); +} + +void StepperQueue::forceStop_mcpwm_pcnt() { + init_stop(this); + read_idx = next_write_idx; +} + +bool StepperQueue::isReadyForCommands_mcpwm_pcnt() const { + if (isRunning()) { + return true; + } + const struct mapping_s* mapping = + static_cast(driver_data); + uint8_t timer = mapping->timer_in_group; + if (mapping->mcpwm->timer[timer].timer_status.timer_value > 1) { + return false; + } + return true; +} + +uint16_t StepperQueue::_getPerformedPulses_mcpwm_pcnt() const { + const struct mapping_s* mapping = + static_cast(driver_data); + return PCNT.cnt_unit[mapping->pcnt_unit_id].FAS_CNT_VAL; +} + +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v1.cpp b/src/pd_esp32/StepperISR_rmt_v1.cpp new file mode 100644 index 0000000..35d83f8 --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v1.cpp @@ -0,0 +1,239 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_RMT_V1) + +#if (PART_SIZE & 1) != 0 +#error "PART_SIZE must be even" +#endif + +// #define TEST_MODE + +#include "pd_esp32/test_probe.h" + +// The following concept is in use: +// +// The rmt buffer is split into two parts. +// Each part will hold one command (or part of). +// +// This way, the threshold interrupt occurs after the first part +// and the end interrupt after the second part. +// After the two parts an end marker is placed. +// +// Of these 32 bits, the low 16-bit entry is sent first and the high entry +// second. +// Every 16 bit entry defines with MSB the output level and the lower 15 bits +// the ticks. +// +// Important difference of esp32c3/esp32s3 (compared to esp32): +// Esp32c3 and Esp32s3 technical reference manuals state for relation 1: +// 3*T_APB + 5*T_RMT_CLK < period*T_CLK_DIV +// and relation 2, if period[14:0] == 0: +// 6*T_APB + 12*T_RMT_CLK < period*T_CLK_DIV +// +// Relation 2 is not applicable, because our end marker is 0x00000000 +// +// Relation 1 means: +// T_APB = 1/80MHz = 12.5ns +// T_CLK_DIV = 1/16MHz = 62.5ns +// T_RMT_CLK = 1/80MHz = 12.5ns +// => period > (3*12.5ns + 5*12.5ns)/(62.5ns) = 1.6 +// +void IRAM_ATTR rmt_fill_buffer(StepperQueue* q, bool fill_part_one, + uint32_t* data) { + // Process command + uint8_t rp = q->read_idx; + struct queue_entry* e_curr = &q->entry[rp & QUEUE_LEN_MASK]; + if (e_curr->toggle_dir) { + // addDirChangePauseToQueue() has already queued a pause part in the old + // direction, so the other RMT half is a pause when this fill toggles DIR. + LL_TOGGLE_PIN(q->dirPin); + e_curr->toggle_dir = 0; + } + + uint8_t steps = e_curr->steps; + uint16_t ticks = e_curr->ticks; + // if (steps != 0) { + // PROBE_1_TOGGLE; + //} + if (steps == 0) { + uint32_t last_entry; + for (uint8_t i = 0; i < PART_SIZE - 1; i++) { + // two pauses à 8 ticks + *data++ = 0x00040004; + ticks -= 8; + } + uint16_t ticks_l = ticks >> 1; + uint16_t ticks_r = ticks - ticks_l; + last_entry = ticks_l; + last_entry <<= 16; + last_entry |= ticks_r; + *data++ = last_entry; + } else { + if (ticks == 0xffff) { + // special treatment for this case, because an rmt entry can only cover up + // to 0xfffe ticks every step must be minimum split into two rmt entries, + // so at max PART/2 steps can be done. + if (steps < PART_SIZE / 2) { + for (uint8_t i = 1; i < steps; i++) { + // steps-1 iterations + *data++ = 0x40007fff | 0x8000; + *data++ = 0x20002000; + } + *data++ = 0x40007fff | 0x8000; + uint16_t delta = PART_SIZE - 2 * steps; + delta <<= 5; + *data++ = 0x20002000 - delta; + // 2*(steps - 1) + 1 already stored => 2*steps - 1 + // and after this for loop one entry added => 2*steps + for (uint8_t i = 2 * steps; i < PART_SIZE; i++) { + *data++ = 0x00100010; + } + steps = 0; + } else { + steps -= PART_SIZE / 2; + for (uint8_t i = 0; i < PART_SIZE / 2; i++) { + *data++ = 0x40007fff | 0x8000; + *data++ = 0x20002000; + } + } + } else { + uint8_t steps_to_do = steps; + if (steps > PART_SIZE) { + steps_to_do = PART_SIZE; + if (steps < 2 * PART_SIZE) { + steps_to_do >>= 1; + } + } + // deduct this buffer's step from total + steps -= steps_to_do; + if (steps_to_do < PART_SIZE) { + // We need to fill up the partition. + // Worst case would be one step in the buffer. + // In order to get threshold interrupt early enough, + // the first step should be stretched to maximum. + // The minimum period is 80ticks @200kHz. + // Minimum command time is 3200 ticks. + // Consequently, 80 ticks will come with minimum 40 steps. + // Split into two rmt parts, so 20 steps each. + // For PART_SIZE 23 or 31, minimum period is 2*2*PART_SIZE = 92 or + // 124ticks. A single step with 80ticks cannot be stretched to + // PART_SIZE. + // => we need to stretch eventually two steps. + uint8_t i = 0; + while (true) { + uint8_t extend_to_i = PART_SIZE - steps_to_do; // extend_to_i >= 1 + // if steps_to_do = PART_SIZE-1, then extend_to_i = 1 + if (i >= extend_to_i) { + // we have already extended enough + break; + } + steps_to_do--; // one step less to do + uint16_t ticks_high = ticks >> 1; + uint16_t ticks_low = ticks - ticks_high; + while (true) { + // need i+1, because low entry is still needed + if ((ticks_high >= 12) && (i + 1 < extend_to_i)) { + *data++ = 0x80048004; + i++; + ticks_high -= 8; + } else { + uint32_t entry = ticks_high >> 1; + entry <<= 16; + entry |= ticks_high - (ticks_high >> 1); + *data++ = 0x80008000 | entry; + i++; + break; + } + } + while (true) { + if ((ticks_low >= 12) && (i < extend_to_i)) { + *data++ = 0x00040004; + i++; + ticks_low -= 8; + } else { + // #325: esp32c3 has frozen with one step and ticks ~38600 + // now the last entry is balanced instead of long pause and + // then 2 ticks + uint32_t entry = ticks_low >> 1; + entry <<= 16; + entry |= ticks_low - (ticks_low >> 1); + *data++ = entry; + i++; + break; + } + } + } + // Now add remaining steps, if any + if (steps_to_do > 0) { + uint16_t ticks_high = ticks >> 1; + uint16_t ticks_low = ticks - ticks_high; + // ticks_l <= ticks_r + uint32_t rmt_entry = ticks_low; + rmt_entry <<= 16; + rmt_entry |= ticks_high | 0x8000; // with step + // reuse existing i + for (i = 1; i <= steps_to_do; i++) { + *data++ = rmt_entry; + } + } + } else { + // either >= 2*PART_SIZE or = PART_SIZE + // every entry one step + uint16_t ticks_high = ticks >> 1; + uint16_t ticks_low = ticks - ticks_high; + uint32_t rmt_entry = ticks_low; + rmt_entry <<= 16; + rmt_entry |= ticks_high | 0x8000; // with step + for (uint8_t i = 0; i < PART_SIZE; i++) { + *data++ = rmt_entry; + } + } + } + } +#if defined(SUPPORT_ESP32_RMT_TICK_LOST) + // No tick lost mentioned for esp32s3 and esp32c3 + if (!fill_part_one) { + // Note: When enabling the continuous transmission mode by setting + // RMT_REG_TX_CONTI_MODE, the transmitter will transmit the data on the + // channel continuously, that is, from the first byte to the last one, + // then from the first to the last again, and so on. In this mode, there + // will be an idle level lasting one clk_div cycle between N and N+1 + // transmissions. + data--; + *data -= 1; + } +#endif + + // Data is complete + if (steps == 0) { + // The command has been completed + q->read_idx = rp + 1; + PROBE_4_TOGGLE; + } else { + e_curr->steps = steps; + } + return; +} +void IRAM_ATTR rmt_apply_command(StepperQueue* q, bool fill_part_one, + uint32_t* data) { + if (!fill_part_one) { + data += PART_SIZE; + } + uint8_t rp = q->read_idx; + if (rp == q->next_write_idx) { + // no command in queue + if (fill_part_one) { + for (uint8_t i = 0; i < PART_SIZE; i++) { + // make a pause with approx. 1ms + // 258 ticks * 2 * 31 = 15996 @ 16MHz + // 347 ticks * 2 * 23 = 15962 @ 16MHz + *data++ = 0x00010001 * (16000 / 2 / PART_SIZE); + } + } else { + q->stop_rmt(false); + } + return; + } + rmt_fill_buffer(q, fill_part_one, data); +} + +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v1_esp32.cpp b/src/pd_esp32/StepperISR_rmt_v1_esp32.cpp new file mode 100644 index 0000000..021a957 --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v1_esp32.cpp @@ -0,0 +1,357 @@ +#include "fas_queue/stepper_queue.h" +// The chip condition stays: SUPPORT_ESP32_RMT_V1 is defined for every +// chip that has RMT at all, and this file is one chip's queue methods. +#if defined(HAVE_ESP32_RMT) && defined(SUPPORT_ESP32_RMT_V1) + +// #define TEST_MODE + +#include "pd_esp32/test_probe.h" + +// The following concept is in use: +// +// The buffer of 64Bytes is split into two parts à 31 words. +// Each part will hold one command (or part of). +// After the 2*31 words an end marker is placed. +// The threshold is set to 31. +// +// This way, the threshold interrupt occurs after the first part +// and the end interrupt after the second part. +// +// Of these 32 bits, the low 16-bit entry is sent first and the high entry +// second. +// Every 16 bit entry defines with MSB the output level and the lower 15 bits +// the ticks. + +void IRAM_ATTR StepperQueue::stop_rmt(bool both) { + // We are stopping the rmt by letting it run into the end at high speed. + // + // disable the interrupts + // rmt_set_tx_intr_en(channel, false); + // rmt_set_tx_thr_intr_en(channel, false, 0); + + // stop esp32 rmt, by let it hit the end + RMT.conf_ch[channel].conf1.tx_conti_mode = 0; + + // replace second part of buffer with pauses + uint32_t* data = FAS_RMT_MEM(channel); + uint8_t start = both ? 0 : PART_SIZE; + data = &data[start]; + for (uint8_t i = start; i < 2 * PART_SIZE; i++) { + // two pauses à n ticks to achieve MIN_CMD_TICKS + *data++ = 0x00010001 * ((MIN_CMD_TICKS + 61) / 62); + } + *data = 0; + + // as the rmt is not running anymore, mark it as stopped + _rmtStopped = true; +} + +#ifndef RMT_CHANNEL_MEM +#define RMT_LIMIT tx_lim +#define RMT_FIFO apb_fifo_mask +#else +#define RMT_LIMIT limit +#define RMT_FIFO fifo_mask +#endif + +#ifdef TEST_MODE +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + PROBE_2_TOGGLE; \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + PROBE_3_TOGGLE; \ + /* now repeat the interrupt at buffer size + end marker */ \ + RMT.tx_lim_ch[ch].RMT_LIMIT = PART_SIZE * 2 + 1; \ + } +#else +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + PROBE_2_TOGGLE; \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + if (q->_rmtStopped) { \ + rmt_set_tx_intr_en(q->channel, false); \ + rmt_set_tx_thr_intr_en(q->channel, false, PART_SIZE + 1); \ + q->_isRunning = false; \ + PROBE_1_TOGGLE; \ + } else { \ + rmt_apply_command(q, false, FAS_RMT_MEM(ch)); \ + } \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + PROBE_3_TOGGLE; \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + if (!q->_rmtStopped) { \ + rmt_apply_command(q, true, FAS_RMT_MEM(ch)); \ + /* now repeat the interrupt at buffer size + end marker */ \ + RMT.tx_lim_ch[ch].RMT_LIMIT = PART_SIZE * 2 + 1; \ + } \ + } +#endif + +static void IRAM_ATTR tx_intr_handler(void* arg) { + uint32_t mask = RMT.int_st.val; + RMT.int_clr.val = mask; + PROCESS_CHANNEL(0); + PROCESS_CHANNEL(1); +#if QUEUES_RMT >= 4 + PROCESS_CHANNEL(2); + PROCESS_CHANNEL(3); +#endif +#if QUEUES_RMT == 8 + PROCESS_CHANNEL(4); + PROCESS_CHANNEL(5); + PROCESS_CHANNEL(6); + PROCESS_CHANNEL(7); +#endif +} + +void StepperQueue::init_rmt(uint8_t channel_num, uint8_t step_pin) { +#ifdef TEST_PROBE_1 + if (channel_num == 0) { + pinMode(TEST_PROBE_1, OUTPUT); + PROBE_1(HIGH); + delay(10); + PROBE_1(LOW); + delay(5); + PROBE_1(HIGH); + delay(5); + PROBE_1(LOW); + delay(5); + } +#endif +#ifdef TEST_PROBE_2 + pinMode(TEST_PROBE_2, OUTPUT); + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + pinMode(TEST_PROBE_3, OUTPUT); + PROBE_3(LOW); +#endif + + _step_pin = step_pin; + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + + channel = (rmt_channel_t)channel_num; + + if (channel_num == 0) { + periph_module_enable(PERIPH_RMT_MODULE); + } + // 80 MHz/5 = 16 MHz + rmt_set_tx_intr_en(channel, false); + rmt_set_tx_thr_intr_en(channel, false, PART_SIZE + 1); + rmt_set_source_clk(channel, RMT_BASECLK_APB); + rmt_set_clk_div(channel, 5); + rmt_set_mem_block_num(channel, 1); + rmt_set_tx_carrier(channel, false, 0, 0, RMT_CARRIER_LEVEL_LOW); + rmt_tx_stop(channel); + rmt_rx_stop(channel); + // rmt_tx_memory_reset is not defined in arduino V340 and based on test result + // not needed rmt_tx_memory_reset(channel); + if (channel_num == 0) { + rmt_isr_register(tx_intr_handler, NULL, + ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM, NULL); + RMT.apb_conf.RMT_FIFO = 1; // disable fifo mode + RMT.apb_conf.mem_tx_wrap_en = 0; + } + + _isRunning = false; + _rmtStopped = true; + + connect(); + +#ifdef TEST_MODE + if (channel == 0) { + uint32_t* mem = FAS_RMT_MEM(channel); + // Fill the buffer with a significant pattern for debugging + for (uint8_t i = 0; i < 32; i += 2) { + *mem++ = 0x7fffffff; + *mem++ = 0x7fff7fff; + } + for (uint8_t i = 32; i < 62; i += 2) { + *mem++ = 0x3fffdfff; + *mem++ = 0x3fff3fff; + } + // without end marker it does not loop + *mem++ = 0; + *mem++ = 0; + RMT.conf_ch[channel].conf1.tx_conti_mode = 1; + rmt_set_tx_intr_en(channel, true); + rmt_set_tx_thr_intr_en(channel, true, PART_SIZE + 1); + // rmt_tx_start(channel, true); + PROBE_2_TOGGLE; + + delay(1000); + if (false) { + mem--; + mem--; + // destroy end marker => no end interrupt, no repeat + *mem++ = 0x00010001; + *mem = 0x00010001; + } + if (true) { + // just clear conti mode => causes end interrup, no repeat + RMT.conf_ch[channel].conf1.tx_conti_mode = 0; + } + delay(1000); + // actually no need to enable/disable interrupts. + // and this seems to avoid some pitfalls + + // This runs the RMT buffer once + RMT.conf_ch[channel].conf1.tx_conti_mode = 1; + delay(1); + RMT.conf_ch[channel].conf1.tx_conti_mode = 0; + while (true) { + delay(1); + } + } +#endif +} + +void StepperQueue::connect_rmt() { + // rmt_set_tx_intr_en(channel, true); + // rmt_set_tx_thr_intr_en(channel, true, PART_SIZE + 1); + RMT.conf_ch[channel].conf1.idle_out_lv = 0; + RMT.conf_ch[channel].conf1.idle_out_en = 1; +#ifndef __ESP32_IDF_V44__ + rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)_step_pin); +#else + rmt_set_gpio(channel, RMT_MODE_TX, (gpio_num_t)_step_pin, false); +#endif +} + +void StepperQueue::disconnect_rmt() { + rmt_set_tx_intr_en(channel, false); + rmt_set_tx_thr_intr_en(channel, false, PART_SIZE + 1); +#ifndef __ESP32_IDF_V44__ +// rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)-1); +#else + rmt_set_gpio(channel, RMT_MODE_TX, GPIO_NUM_NC, false); +#endif + RMT.conf_ch[channel].conf1.idle_out_en = 0; +} + +void StepperQueue::startQueue_rmt() { +// #define TRACE +#ifdef TRACE + Serial.println("START"); +#endif +#ifdef TEST_PROBE_2 + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + PROBE_3(LOW); +#endif +#ifdef TEST_PROBE_1 + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); +#endif + rmt_tx_stop(channel); + // rmt_rx_stop(channel); + // rmt_tx_memory_reset(channel); + // the following assignment should not be needed; + // RMT.data_ch[channel] = 0; + uint32_t* mem = FAS_RMT_MEM(channel); + // Fill the buffer with a significant pattern for debugging + // Keep it for now + for (uint8_t i = 0; i < 2 * PART_SIZE; i += 2) { + mem[i] = 0x0fff8fff; + mem[i + 1] = 0x7fff8fff; + } + mem[2 * PART_SIZE] = 0; + mem[2 * PART_SIZE + 1] = 0; + _isRunning = true; + _rmtStopped = false; + rmt_set_tx_intr_en(channel, false); + rmt_set_tx_thr_intr_en(channel, false, 0); + // RMT.apb_conf.mem_tx_wrap_en = 0; + +// #define TRACE +#ifdef TRACE + Serial.print("Queue:"); + Serial.print(read_idx); + Serial.print('/'); + Serial.println(next_write_idx); + for (uint8_t i = 0; i < 64; i++) { + Serial.print(i); + Serial.print(' '); + Serial.println(mem[i], HEX); + } +#endif + + // set dirpin toggle here + uint8_t rp = read_idx; + if (rp == next_write_idx) { + // nothing to do ? + // Should not happen, so bail + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + + rmt_apply_command(this, true, mem); + +#ifdef TRACE + Serial.print(RMT.conf_ch[channel].conf0.val, BIN); + Serial.print(' '); + Serial.print(RMT.conf_ch[channel].conf1.val, BIN); + Serial.println(' '); + Serial.print(RMT.apb_conf.mem_tx_wrap_en); + Serial.println(' '); + for (uint8_t i = 0; i < 64; i++) { + Serial.print(i); + Serial.print(' '); + Serial.println(mem[i], HEX); + } + if (!isRunning()) { + Serial.println("STOPPED 1"); + } +#endif + + rmt_apply_command(this, false, mem); + +#ifdef TRACE + Serial.print(RMT.conf_ch[channel].conf0.val, BIN); + Serial.print(' '); + Serial.print(RMT.conf_ch[channel].conf1.val, BIN); + Serial.println(' '); + Serial.print(RMT.apb_conf.mem_tx_wrap_en); + Serial.println(' '); + + for (uint8_t i = 0; i < 64; i++) { + Serial.print(i); + Serial.print(' '); + Serial.println(mem[i], HEX); + } +#endif + rmt_set_tx_thr_intr_en(channel, true, PART_SIZE + 1); + rmt_set_tx_intr_en(channel, true); + _rmtStopped = false; + + // This starts the rmt module + RMT.conf_ch[channel].conf1.tx_conti_mode = 1; + + RMT.conf_ch[channel].conf1.tx_start = 1; +} +void StepperQueue::forceStop_rmt() { + stop_rmt(true); + + // and empty the buffer + read_idx = next_write_idx; +} +bool StepperQueue::isReadyForCommands_rmt() const { + if (_isRunning) { + return !_rmtStopped; + } + return true; +} +uint16_t StepperQueue::_getPerformedPulses_rmt() const { return 0; } +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v1_esp32c3.cpp b/src/pd_esp32/StepperISR_rmt_v1_esp32c3.cpp new file mode 100644 index 0000000..266156b --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v1_esp32c3.cpp @@ -0,0 +1,488 @@ +#include "fas_queue/stepper_queue.h" +// The chip condition stays: SUPPORT_ESP32_RMT_V1 is defined for every +// chip that has RMT at all, and this file is one chip's queue methods. +#if defined(HAVE_ESP32C3_RMT) && defined(SUPPORT_ESP32_RMT_V1) + +// #define TEST_MODE +// #define TRACE + +#include "pd_esp32/test_probe.h" + +// The following concept is in use: +// +// The rmt buffer is split into two parts. +// Each part will hold one command (or part of). +// After the two parts an end marker is placed. +// +// Of these 32 bits, the low 16-bit entry is sent first and the high entry +// second. +// Every 16 bit entry defines with MSB the output level and the lower 15 bits +// the ticks. +// +// Important difference of esp32c3 (compared to esp32): +// - configuration updates need an conf_update strobe +// (apparently the manual is not correct by mentioning to set conf_update +// first) +// - if the end marker is hit in continuous mode, there is no end interrupt +// - there is no tick lost with the end marker +// - minimum periods as per relation 1 and 2 to be adhered to +// +// +// In order to avoid threshold/end interrupt on end, add one +#define enable_rmt_interrupts(channel) \ + { \ + RMT.tx_lim[channel].RMT_LIMIT = PART_SIZE + 2; \ + RMT.tx_conf[channel].conf_update = 1; \ + RMT.tx_conf[channel].conf_update = 0; \ + RMT.int_clr.val |= 0x101 << channel; \ + RMT.int_ena.val |= 0x101 << channel; \ + } +#define disable_rmt_interrupts(channel) \ + { \ + RMT.int_ena.val &= ~(0x101 << channel); \ + } + +void IRAM_ATTR StepperQueue::stop_rmt(bool both) { + // We are stopping the rmt by letting it run into the end at high speed. + // + // disable the interrupts + // rmt_set_tx_intr_en(channel, false); + // rmt_set_tx_thr_intr_en(channel, false, 0); + + // stop esp32 rmt, by let it hit the end + RMT.tx_conf[channel].tx_conti_mode = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + + // replace second part of buffer with pauses + uint32_t* data = FAS_RMT_MEM(channel); + uint8_t start = both ? 0 : PART_SIZE; + data = &data[start]; + for (uint8_t i = start; i < 2 * PART_SIZE; i++) { + // two pauses à n ticks to achieve MIN_CMD_TICKS + *data++ = 0x00010001 * ((MIN_CMD_TICKS + 61) / 62); + } + *data = 0; + + // as the rmt is not running anymore, mark it as stopped + _rmtStopped = true; +} + +#if !defined(RMT_CHANNEL_MEM) && !defined(HAVE_ESP32C3_RMT) +#define RMT_LIMIT tx_lim +#define RMT_FIFO apb_fifo_mask +#else +#define RMT_LIMIT limit +#define RMT_FIFO fifo_mask +#endif + +// The threshold interrupts are happening in the "middle" of the previous entry. +// Best strategy: +// 1. enable threshold interrupt with PART_SIZE+2 +// 2. On every threshold interrupt toggle PART_SIZE and PART_SIZE+1 +// This way the first interrupt happens on the first entry of second half, +// and the second interrupt on the first entry of the first half. +// Afterwards alternating. This way the end interrupt is always "half buffer +// away" from the threshold interrupt +#ifdef TEST_MODE +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + PROBE_1_TOGGLE; \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + uint8_t old_limit = RMT.tx_lim[ch].RMT_LIMIT; \ + if (old_limit == PART_SIZE + 1) { \ + /* second half of buffer sent */ \ + PROBE_2_TOGGLE; \ + /* demonstrate modification of RAM */ \ + uint32_t* mem = FAS_RMT_MEM(ch); \ + mem[PART_SIZE] = 0x33ff33ff; \ + RMT.tx_lim[ch].RMT_LIMIT = PART_SIZE; \ + } else { \ + /* first half of buffer sent */ \ + PROBE_3_TOGGLE; \ + RMT.tx_lim[ch].RMT_LIMIT = PART_SIZE + 1; \ + } \ + RMT.tx_conf[ch].conf_update = 1; \ + RMT.tx_conf[ch].conf_update = 0; \ + } +#else +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + disable_rmt_interrupts(q->channel); \ + q->_isRunning = false; \ + PROBE_1_TOGGLE; \ + PROBE_2_TOGGLE; \ + PROBE_3_TOGGLE; \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + uint8_t old_limit = RMT.tx_lim[ch].RMT_LIMIT; \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + uint32_t* mem = FAS_RMT_MEM(ch); \ + if (old_limit == PART_SIZE + 1) { \ + /* second half of buffer sent */ \ + PROBE_2_TOGGLE; \ + rmt_apply_command(q, false, mem); \ + /* demonstrate modification of RAM */ \ + /*mem[PART_SIZE] = 0x33fff3ff; */ \ + RMT.tx_lim[ch].RMT_LIMIT = PART_SIZE; \ + } else { \ + /* first half of buffer sent */ \ + PROBE_3_TOGGLE; \ + rmt_apply_command(q, true, mem); \ + RMT.tx_lim[ch].RMT_LIMIT = PART_SIZE + 1; \ + } \ + RMT.tx_conf[ch].conf_update = 1; \ + RMT.tx_conf[ch].conf_update = 0; \ + } +#endif + +static void IRAM_ATTR tx_intr_handler(void* arg) { + uint32_t mask = RMT.int_st.val; + RMT.int_clr.val = mask; + PROCESS_CHANNEL(0); + PROCESS_CHANNEL(1); +#if QUEUES_RMT >= 4 + PROCESS_CHANNEL(2); + PROCESS_CHANNEL(3); +#endif +#if QUEUES_RMT == 8 + PROCESS_CHANNEL(4); + PROCESS_CHANNEL(5); + PROCESS_CHANNEL(6); + PROCESS_CHANNEL(7); +#endif +} + +void StepperQueue::init_rmt(uint8_t channel_num, uint8_t step_pin) { +#ifdef TEST_PROBE_1 + if (channel_num == 0) { + pinMode(TEST_PROBE_1, OUTPUT); + PROBE_1(HIGH); + delay(10); + PROBE_1(LOW); + delay(5); + PROBE_1(HIGH); + delay(5); + PROBE_1(LOW); + delay(5); + } +#endif +#ifdef TEST_PROBE_2 + pinMode(TEST_PROBE_2, OUTPUT); + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + pinMode(TEST_PROBE_3, OUTPUT); + PROBE_3(LOW); +#endif + + _step_pin = step_pin; + // digitalWrite(step_pin, LOW); + // pinMode(step_pin, OUTPUT); + + channel = (rmt_channel_t)channel_num; + + if (channel_num == 0) { + periph_module_enable(PERIPH_RMT_MODULE); + } + // APB_CLOCK=80 MHz + // CLK_DIV = APB_CLOCK/5 = 16 MHz + // + // Relation 1 in esp32c3 technical reference: + // 3 * T_APB + 5 * T_RMT_CLK < period * T_CLK_DIV + // => 8 * T_APB < period * T_APB*5 + // => period > 8/5 + // => period >= 2 + // + // Relation 2 in esp32c3 technical reference before end marker: + // 6 * T_APB + 12 * T_RMT_CLK < period * T_CLK_DIV + // => 18 * T_APB < period * T_APB*5 + // => period > 18/5 + // => period >= 4 + // + disable_rmt_interrupts(channel); + rmt_set_source_clk(channel, RMT_BASECLK_APB); + rmt_set_clk_div(channel, 5); + rmt_set_mem_block_num(channel, 1); + rmt_set_tx_carrier(channel, false, 0, 0, RMT_CARRIER_LEVEL_LOW); + rmt_tx_stop(channel); + rmt_tx_memory_reset(channel); + // rmt_rx_stop(channel); TX only channel ! + // rmt_tx_memory_reset is not defined in arduino V340 and based on test + // result not needed rmt_tx_memory_reset(channel); + if (channel_num == 0) { + rmt_isr_register(tx_intr_handler, NULL, + ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM, NULL); + RMT.sys_conf.fifo_mask = 1; // disable fifo mode + } + + _isRunning = false; + _rmtStopped = true; + + connect_rmt(); + +#ifdef TEST_MODE + if (channel == 0) { + RMT.tx_conf[channel].mem_rd_rst = 1; + RMT.tx_conf[channel].mem_rd_rst = 0; + uint32_t* mem = FAS_RMT_MEM(channel); + // Fill the buffer with a significant pattern for debugging + for (uint8_t i = 0; i < PART_SIZE; i++) { + *mem++ = 0x7fffffff; + } + for (uint8_t i = PART_SIZE; i < 2 * PART_SIZE; i++) { + *mem++ = 0x3fffdfff; + } + // without end marker it does not loop + *mem++ = 0; + *mem++ = 0; + + // conti mode is accepted with the conf_update 1 strobe + RMT.tx_conf[channel].tx_conti_mode = 1; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + RMT.tx_conf[channel].mem_tx_wrap_en = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + enable_rmt_interrupts(channel); + // tx_start does not need conf_update + PROBE_1_TOGGLE; // end interrupt will toggle again PROBE_1 + RMT.tx_conf[channel].tx_start = 1; + + delay(1000); + if (false) { + mem--; + mem--; + // destroy end marker => no end interrupt, no repeat + *mem++ = 0x00010001; + *mem = 0x00010001; + } + if (true) { + // just clear conti mode => causes end interrupt, no repeat + RMT.tx_conf[channel].tx_conti_mode = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + } + delay(1000); + // actually no need to enable/disable interrupts. + // and this seems to avoid some pitfalls + + // This runs the RMT buffer once + RMT.tx_conf[channel].tx_conti_mode = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + RMT.tx_conf[channel].tx_start = 1; + while (true) { + delay(1000); + PROBE_1_TOGGLE; + } + } +#endif +} + +void StepperQueue::connect_rmt() { + RMT.tx_conf[channel].idle_out_lv = 0; + RMT.tx_conf[channel].idle_out_en = 1; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // RMT.tx_conf[channel].mem_tx_wrap_en = 0; +#ifndef __ESP32_IDF_V44__ + rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)_step_pin); +#else + rmt_set_gpio(channel, RMT_MODE_TX, (gpio_num_t)_step_pin, false); +#endif + +#ifdef TEST_MODE + // here gpio is 0 + delay(1); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_lv = 1; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // here gpio is 1 + delay(2); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_lv = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_en = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_lv = 1; + RMT.tx_conf[channel].idle_out_en = 1; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // here gpio is 1 + delay(2); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_lv = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; +#endif +} + +void StepperQueue::disconnect_rmt() { + disable_rmt_interrupts(channel); +#ifndef __ESP32_IDF_V44__ +// rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)-1); +#else +// rmt_set_gpio(channel, RMT_MODE_TX, GPIO_NUM_NC, false); +#endif + RMT.tx_conf[channel].idle_out_en = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; +} + +void StepperQueue::startQueue_rmt() { +#ifdef TRACE + USBSerial.println("START"); +#endif +#ifdef TEST_PROBE_2 + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + PROBE_3(LOW); +#endif +#if defined(TEST_PROBE_1) && defined(TEST_PROBE_2) && defined(TEST_PROBE_3) + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_2_TOGGLE; + delay(2); + PROBE_2_TOGGLE; + delay(2); + PROBE_3_TOGGLE; + delay(3); + PROBE_3_TOGGLE; + delay(3); +#endif + rmt_tx_stop(channel); + // rmt_rx_stop(channel); + RMT.tx_conf[channel].mem_rd_rst = 1; + RMT.tx_conf[channel].mem_rd_rst = 0; + uint32_t* mem = FAS_RMT_MEM(channel); +// #define TRACE +#ifdef TRACE + // Fill the buffer with a significant pattern for debugging + // Keep it for now + for (uint8_t i = 0; i < 2 * PART_SIZE; i += 2) { + // mem[i] = 0x0fff8fff; + // mem[i + 1] = 0x7fff8fff; + } +#endif + // Write end marker + mem[2 * PART_SIZE] = 0; + mem[2 * PART_SIZE + 1] = 0; + _isRunning = true; + _rmtStopped = false; + disable_rmt_interrupts(channel); + RMT.tx_conf[channel].mem_tx_wrap_en = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + +#ifdef TRACE + USBSerial.print("Queue:"); + USBSerial.print(read_idx); + USBSerial.print('/'); + USBSerial.println(next_write_idx); + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } +#endif + + // set dirpin toggle here + uint8_t rp = read_idx; + if (rp == next_write_idx) { + // nothing to do ? + // Should not happen, so bail + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + + rmt_apply_command(this, true, mem); + +#ifdef TRACE + USBSerial.print(RMT.tx_conf[channel].val, BIN); + USBSerial.println(' '); + USBSerial.print(RMT.tx_conf[channel].mem_tx_wrap_en); + USBSerial.println(' '); + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } + if (!isRunning()) { + USBSerial.println("STOPPED 1"); + } +#endif + + rmt_apply_command(this, false, mem); + +#ifdef TRACE + USBSerial.print(RMT.tx_conf[channel].val, BIN); + USBSerial.print(' '); + USBSerial.print(RMT.tx_conf[channel].mem_tx_wrap_en); + USBSerial.println(' '); + + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } +#endif + enable_rmt_interrupts(channel); + +#ifdef TRACE + USBSerial.print("Interrupt enable:"); + USBSerial.println(RMT.int_ena.val, BIN); + USBSerial.print("Interrupt status:"); + USBSerial.println(RMT.int_st.val, BIN); + USBSerial.print("Threshold: 0x"); + USBSerial.println(RMT.tx_lim[channel].val, HEX); +#endif + + // This starts the rmt module + RMT.tx_conf[channel].tx_conti_mode = 1; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + RMT.tx_conf[channel].mem_tx_wrap_en = 0; + RMT.tx_conf[channel].conf_update = 1; + RMT.tx_conf[channel].conf_update = 0; + + PROBE_1_TOGGLE; + RMT.tx_conf[channel].tx_start = 1; +} +void StepperQueue::forceStop_rmt() { + stop_rmt(true); + + // and empty the buffer + read_idx = next_write_idx; +} +bool StepperQueue::isReadyForCommands_rmt() const { + if (_isRunning) { + return !_rmtStopped; + } + return true; +} +uint16_t StepperQueue::_getPerformedPulses_rmt() const { return 0; } +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v1_esp32s3.cpp b/src/pd_esp32/StepperISR_rmt_v1_esp32s3.cpp new file mode 100644 index 0000000..559efad --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v1_esp32s3.cpp @@ -0,0 +1,489 @@ +#include "fas_queue/stepper_queue.h" +// The chip condition stays: SUPPORT_ESP32_RMT_V1 is defined for every +// chip that has RMT at all, and this file is one chip's queue methods. +#if defined(HAVE_ESP32S3_RMT) && defined(SUPPORT_ESP32_RMT_V1) + +// #define TEST_MODE +// #define TRACE + +#include "pd_esp32/test_probe.h" + +// The following concept is in use: +// +// The rmt buffer is split into two parts. +// Each part will hold one command (or part of). +// After the two parts an end marker is placed. +// +// Of these 32 bits, the low 16-bit entry is sent first and the high entry +// second. +// Every 16 bit entry defines with MSB the output level and the lower 15 bits +// the ticks. +// +// Important difference of esp32s3 (compared to esp32): +// - configuration updates need an conf_update strobe +// (apparently the manual is not correct by mentioning to set conf_update +// first) +// - if the end marker is hit in continuous mode, there is no end interrupt +// - there is no tick lost with the end marker +// - minimum periods as per relation 1 and 2 to be adhered to +// +// + +// In order to avoid threshold/end interrupt on end, add one +#define enable_rmt_interrupts(channel) \ + { \ + RMT.chn_tx_lim[channel].RMT_LIMIT = PART_SIZE + 2; \ + RMT.chnconf0[channel].conf_update_n = 1; \ + RMT.chnconf0[channel].conf_update_n = 0; \ + RMT.int_clr.val |= 0x101 << channel; \ + RMT.int_ena.val |= 0x101 << channel; \ + } +#define disable_rmt_interrupts(channel) \ + { \ + RMT.int_ena.val &= ~(0x101 << channel); \ + } + +void IRAM_ATTR StepperQueue::stop_rmt(bool both) { + // We are stopping the rmt by letting it run into the end at high speed. + // + // disable the interrupts + // rmt_set_tx_intr_en(channel, false); + // rmt_set_tx_thr_intr_en(channel, false, 0); + + // stop esp32 rmt, by let it hit the end + RMT.chnconf0[channel].tx_conti_mode_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + + // replace second part of buffer with pauses + uint32_t* data = FAS_RMT_MEM(channel); + uint8_t start = both ? 0 : PART_SIZE; + data = &data[start]; + for (uint8_t i = start; i < 2 * PART_SIZE; i++) { + // two pauses à n ticks to achieve MIN_CMD_TICKS + *data++ = 0x00010001 * ((MIN_CMD_TICKS + 61) / 62); + } + *data = 0; + + // as the rmt is not running anymore, mark it as stopped + _rmtStopped = true; +} + +#if !defined(RMT_CHANNEL_MEM) && !defined(HAVE_ESP32S3_RMT) +#define RMT_LIMIT tx_lim +#define RMT_FIFO apb_fifo_mask +#else +#define RMT_LIMIT tx_lim_chn +#define RMT_FIFO apb_fifo_mask +#endif + +// The threshold interrupts are happening in the "middle" of the previous entry. +// Best strategy: +// 1. enable threshold interrupt with PART_SIZE+2 +// 2. On every threshold interrupt toggle PART_SIZE and PART_SIZE+1 +// This way the first interrupt happens on the first entry of second half, +// and the second interrupt on the first entry of the first half. +// Afterwards alternating. This way the end interrupt is always "half buffer +// away" from the threshold interrupt +#ifdef TEST_MODE +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + PROBE_1_TOGGLE; \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + uint8_t old_limit = RMT.chn_tx_lim[ch].RMT_LIMIT; \ + if (old_limit == PART_SIZE + 1) { \ + /* second half of buffer sent */ \ + PROBE_2_TOGGLE; \ + /* demonstrate modification of RAM */ \ + uint32_t* mem = FAS_RMT_MEM(ch); \ + mem[PART_SIZE] = 0x33ff33ff; \ + RMT.chn_tx_lim[ch].RMT_LIMIT = PART_SIZE; \ + } else { \ + /* first half of buffer sent */ \ + PROBE_3_TOGGLE; \ + RMT.chn_tx_lim[ch].RMT_LIMIT = PART_SIZE + 1; \ + } \ + RMT.chnconf0[ch].conf_update_n = 1; \ + RMT.chnconf0[ch].conf_update_n = 0; \ + } +#else +#define PROCESS_CHANNEL(ch) \ + if (mask & RMT_CH##ch##_TX_END_INT_ST) { \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + disable_rmt_interrupts(q->channel); \ + q->_isRunning = false; \ + PROBE_1_TOGGLE; \ + PROBE_2_TOGGLE; \ + PROBE_3_TOGGLE; \ + } \ + if (mask & RMT_CH##ch##_TX_THR_EVENT_INT_ST) { \ + uint8_t old_limit = RMT.chn_tx_lim[ch].RMT_LIMIT; \ + StepperQueue* q = &fas_queue[QUEUES_MCPWM_PCNT + ch]; \ + uint32_t* mem = FAS_RMT_MEM(ch); \ + if (old_limit == PART_SIZE + 1) { \ + /* second half of buffer sent */ \ + PROBE_2_TOGGLE; \ + rmt_apply_command(q, false, mem); \ + /* demonstrate modification of RAM */ \ + /*mem[PART_SIZE] = 0x33fff3ff; */ \ + RMT.chn_tx_lim[ch].RMT_LIMIT = PART_SIZE; \ + } else { \ + /* first half of buffer sent */ \ + PROBE_3_TOGGLE; \ + rmt_apply_command(q, true, mem); \ + RMT.chn_tx_lim[ch].RMT_LIMIT = PART_SIZE + 1; \ + } \ + RMT.chnconf0[ch].conf_update_n = 1; \ + RMT.chnconf0[ch].conf_update_n = 0; \ + } +#endif + +static void IRAM_ATTR tx_intr_handler(void* arg) { + uint32_t mask = RMT.int_st.val; + RMT.int_clr.val = mask; + PROCESS_CHANNEL(0); + PROCESS_CHANNEL(1); +#if QUEUES_RMT >= 4 + PROCESS_CHANNEL(2); + PROCESS_CHANNEL(3); +#endif +#if QUEUES_RMT == 8 + PROCESS_CHANNEL(4); + PROCESS_CHANNEL(5); + PROCESS_CHANNEL(6); + PROCESS_CHANNEL(7); +#endif +} + +void StepperQueue::init_rmt(uint8_t channel_num, uint8_t step_pin) { +#ifdef TEST_PROBE_1 + if (channel_num == 0) { + pinMode(TEST_PROBE_1, OUTPUT); + PROBE_1(HIGH); + delay(10); + PROBE_1(LOW); + delay(5); + PROBE_1(HIGH); + delay(5); + PROBE_1(LOW); + delay(5); + } +#endif +#ifdef TEST_PROBE_2 + pinMode(TEST_PROBE_2, OUTPUT); + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + pinMode(TEST_PROBE_3, OUTPUT); + PROBE_3(LOW); +#endif + + _step_pin = step_pin; + // digitalWrite(step_pin, LOW); + // pinMode(step_pin, OUTPUT); + + channel = (rmt_channel_t)channel_num; + + if (channel_num == 0) { + periph_module_enable(PERIPH_RMT_MODULE); + } + // APB_CLOCK=80 MHz + // CLK_DIV = APB_CLOCK/5 = 16 MHz + // + // Relation 1 in esp32s3 technical reference: + // 3 * T_APB + 5 * T_RMT_CLK < period * T_CLK_DIV + // => 8 * T_APB < period * T_APB*5 + // => period > 8/5 + // => period >= 2 + // + // Relation 2 in esp32s3 technical reference before end marker: + // 6 * T_APB + 12 * T_RMT_CLK < period * T_CLK_DIV + // => 18 * T_APB < period * T_APB*5 + // => period > 18/5 + // => period >= 4 + // + disable_rmt_interrupts(channel); + rmt_set_source_clk(channel, RMT_BASECLK_APB); + rmt_set_clk_div(channel, 5); + rmt_set_mem_block_num(channel, 1); + rmt_set_tx_carrier(channel, false, 0, 0, RMT_CARRIER_LEVEL_LOW); + rmt_tx_stop(channel); + rmt_tx_memory_reset(channel); + // rmt_rx_stop(channel); TX only channel ! + // rmt_tx_memory_reset is not defined in arduino V340 and based on test + // result not needed rmt_tx_memory_reset(channel); + if (channel_num == 0) { + rmt_isr_register(tx_intr_handler, NULL, + ESP_INTR_FLAG_SHARED | ESP_INTR_FLAG_IRAM, NULL); + RMT.sys_conf.apb_fifo_mask = 1; // disable fifo mode + } + + _isRunning = false; + _rmtStopped = true; + + connect_rmt(); + +#ifdef TEST_MODE + if (channel == 0) { + RMT.chnconf0[channel].mem_rd_rst_n = 1; + RMT.chnconf0[channel].mem_rd_rst_n = 0; + uint32_t* mem = FAS_RMT_MEM(channel); + // Fill the buffer with a significant pattern for debugging + for (uint8_t i = 0; i < PART_SIZE; i++) { + *mem++ = 0x7fffffff; + } + for (uint8_t i = PART_SIZE; i < 2 * PART_SIZE; i++) { + *mem++ = 0x3fffdfff; + } + // without end marker it does not loop + *mem++ = 0; + *mem++ = 0; + + // conti mode is accepted with the conf_update 1 strobe + RMT.chnconf0[channel].tx_conti_mode_n = 1; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + RMT.chnconf0[channel].mem_tx_wrap_en_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + enable_rmt_interrupts(channel); + // tx_start does not need conf_update + PROBE_1_TOGGLE; // end interrupt will toggle again PROBE_1 + RMT.chnconf0[channel].tx_start_n = 1; + + delay(1000); + if (false) { + mem--; + mem--; + // destroy end marker => no end interrupt, no repeat + *mem++ = 0x00010001; + *mem = 0x00010001; + } + if (true) { + // just clear conti mode => causes end interrupt, no repeat + RMT.chnconf0[channel].tx_conti_mode_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + } + delay(1000); + // actually no need to enable/disable interrupts. + // and this seems to avoid some pitfalls + + // This runs the RMT buffer once + RMT.chnconf0[channel].tx_conti_mode_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + RMT.chnconf0[channel].tx_start_n = 1; + while (true) { + delay(1000); + PROBE_1_TOGGLE; + } + } +#endif +} + +void StepperQueue::connect_rmt() { + RMT.chnconf0[channel].idle_out_lv_n = 0; + RMT.chnconf0[channel].idle_out_en_n = 1; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + // RMT.tx_conf[channel].mem_tx_wrap_en = 0; +#ifndef __ESP32_IDF_V44__ + rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)_step_pin); +#else + rmt_set_gpio(channel, RMT_MODE_TX, (gpio_num_t)_step_pin, false); +#endif + +#ifdef TEST_MODE + // here gpio is 0 + delay(1); + PROBE_3_TOGGLE; + RMT.tx_conf[channel].idle_out_lv_n = 1; + RMT.tx_conf[channel].conf_update_n = 1; + RMT.tx_conf[channel].conf_update_n = 0; + // here gpio is 1 + delay(2); + PROBE_3_TOGGLE; + RMT.chnconf0[channel].idle_out_lv_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; + RMT.chnconf0[channel].idle_out_en_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; + RMT.chnconf0[channel].idle_out_lv_n = 1; + RMT.chnconf0[channel].idle_out_en_n = 1; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + // here gpio is 1 + delay(2); + PROBE_3_TOGGLE; + RMT.chnconf0[channel].idle_out_lv_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + // here gpio is 0 + delay(2); + PROBE_3_TOGGLE; +#endif +} + +void StepperQueue::disconnect_rmt() { + disable_rmt_interrupts(channel); +#ifndef __ESP32_IDF_V44__ +// rmt_set_pin(channel, RMT_MODE_TX, (gpio_num_t)-1); +#else +// rmt_set_gpio(channel, RMT_MODE_TX, GPIO_NUM_NC, false); +#endif + RMT.chnconf0[channel].idle_out_en_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; +} + +void StepperQueue::startQueue_rmt() { +#ifdef TRACE + USBSerial.println("START"); +#endif +#ifdef TEST_PROBE_2 + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + PROBE_3(LOW); +#endif +#if defined(TEST_PROBE_1) && defined(TEST_PROBE_2) && defined(TEST_PROBE_3) + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_2_TOGGLE; + delay(2); + PROBE_2_TOGGLE; + delay(2); + PROBE_3_TOGGLE; + delay(3); + PROBE_3_TOGGLE; + delay(3); +#endif + rmt_tx_stop(channel); + // rmt_rx_stop(channel); + RMT.chnconf0[channel].mem_rd_rst_n = 1; + RMT.chnconf0[channel].mem_rd_rst_n = 0; + uint32_t* mem = FAS_RMT_MEM(channel); +// #define TRACE +#ifdef TRACE + // Fill the buffer with a significant pattern for debugging + // Keep it for now + for (uint8_t i = 0; i < 2 * PART_SIZE; i += 2) { + // mem[i] = 0x0fff8fff; + // mem[i + 1] = 0x7fff8fff; + } +#endif + // Write end marker + mem[2 * PART_SIZE] = 0; + mem[2 * PART_SIZE + 1] = 0; + _isRunning = true; + _rmtStopped = false; + disable_rmt_interrupts(channel); + RMT.chnconf0[channel].mem_tx_wrap_en_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + +#ifdef TRACE + USBSerial.print("Queue:"); + USBSerial.print(read_idx); + USBSerial.print('/'); + USBSerial.println(next_write_idx); + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } +#endif + + // set dirpin toggle here + uint8_t rp = read_idx; + if (rp == next_write_idx) { + // nothing to do ? + // Should not happen, so bail + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + + rmt_apply_command(this, true, mem); + +#ifdef TRACE + USBSerial.print(RMT.chnconf0[channel].val, BIN); + USBSerial.println(' '); + USBSerial.print(RMT.chnconf0[channel].mem_tx_wrap_en_n); + USBSerial.println(' '); + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } + if (!isRunning()) { + USBSerial.println("STOPPED 1"); + } +#endif + + rmt_apply_command(this, false, mem); + +#ifdef TRACE + USBSerial.print(RMT.chnconf0[channel].val, BIN); + USBSerial.print(' '); + USBSerial.print(RMT.chnconf0[channel].mem_tx_wrap_en_n); + USBSerial.println(' '); + + for (uint8_t i = 0; i < RMT_MEM_SIZE; i++) { + USBSerial.print(i); + USBSerial.print(' '); + USBSerial.println(mem[i], HEX); + } +#endif + enable_rmt_interrupts(channel); + +#ifdef TRACE + USBSerial.print("Interrupt enable:"); + USBSerial.println(RMT.int_ena.val, BIN); + USBSerial.print("Interrupt status:"); + USBSerial.println(RMT.int_st.val, BIN); + USBSerial.print("Threshold: 0x"); + USBSerial.println(RMT.tx_lim[channel].val, HEX); +#endif + + // This starts the rmt module + RMT.chnconf0[channel].tx_conti_mode_n = 1; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + RMT.chnconf0[channel].mem_tx_wrap_en_n = 0; + RMT.chnconf0[channel].conf_update_n = 1; + RMT.chnconf0[channel].conf_update_n = 0; + + PROBE_1_TOGGLE; + RMT.chnconf0[channel].tx_start_n = 1; +} +void StepperQueue::forceStop_rmt() { + stop_rmt(true); + + // and empty the buffer + read_idx = next_write_idx; +} +bool StepperQueue::isReadyForCommands_rmt() const { + if (_isRunning) { + return !_rmtStopped; + } + return true; +} +uint16_t StepperQueue::_getPerformedPulses_rmt() const { return 0; } +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v2.cpp b/src/pd_esp32/StepperISR_rmt_v2.cpp new file mode 100644 index 0000000..2f1e90a --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v2.cpp @@ -0,0 +1,232 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_RMT_V2) + +// #define TEST_MODE + +#include "pd_esp32/test_probe.h" + +static bool IRAM_ATTR queue_done(rmt_channel_handle_t tx_chan, + const rmt_tx_done_event_data_t* edata, + void* user_ctx) { + StepperQueue* q = static_cast(user_ctx); + q->_isRunning = false; + return false; +} + +// F2 fill encoder callback: uses rmt_encode_fill() with a persistent +// rmt_fill_state. The queue is treated as done only when read_idx == +// next_write_idx AND remaining_low_ticks == 0 (the fill state is fully +// drained), so the eager _rmtStopped stop cannot fire mid-split-low. +static size_t IRAM_ATTR encode_commands(const void* data, size_t data_size, + size_t symbols_written, + size_t symbols_free, + rmt_symbol_word_t* symbols, bool* done, + void* arg) { + StepperQueue* q = static_cast(arg); + + *done = false; + if (q->_rmtStopped) { + *done = true; + return 0; + } + + struct rmt_fill_state* fs = &q->_rmt_fill_state; + + // Check emptiness *before* encoding. A drain that happens within this call + // must not arm the stop (that is the eager stop); the next call sees the + // empty queue and arms it. + if (q->read_idx == q->next_write_idx && fs->remaining_low_ticks == 0) { + if (symbols_free < PART_SIZE) { + return 0; + } + // if we return done already here, then single stepping fails + q->_rmtStopped = true; + // Emit ENTER_PAUSE(MIN_CMD_TICKS) as PART_SIZE symbols so the channel + // reaches a known state; min_chunk_size stays PART_SIZE for this. + uint16_t remaining_ticks = MIN_CMD_TICKS; + uint16_t half_ticks_per_symbol = remaining_ticks / (2 * PART_SIZE); + uint32_t main_symbol = 0x00010001 * half_ticks_per_symbol; + for (uint8_t i = 0; i < PART_SIZE - 1; i++) { + (symbols++)->val = main_symbol; + } + remaining_ticks -= 2 * (PART_SIZE - 1) * half_ticks_per_symbol; + uint16_t first_ticks = remaining_ticks / 2; + remaining_ticks -= first_ticks; + symbols->val = 0x00010000 * first_ticks + remaining_ticks; + return PART_SIZE; + } + + return rmt_encode_fill(q, fs, &symbols[0].val, (uint32_t)symbols_free); +} + +void StepperQueue::init_rmt(uint8_t channel_num, uint8_t step_pin) { +#ifdef TEST_PROBE_1 + if (channel_num == 0) { + pinMode(TEST_PROBE_1, OUTPUT); + PROBE_1(HIGH); + delay(10); + PROBE_1(LOW); + delay(5); + PROBE_1(HIGH); + delay(5); + PROBE_1(LOW); + delay(5); + } +#endif +#ifdef TEST_PROBE_2 + pinMode(TEST_PROBE_2, OUTPUT); + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + pinMode(TEST_PROBE_3, OUTPUT); + PROBE_3(LOW); +#endif + + _step_pin = step_pin; + pinMode(step_pin, OUTPUT); + digitalWrite(step_pin, LOW); + + // Zero-fill the fill state (F2 persistent state). + _rmt_fill_state.remaining_low_ticks = 0; + + rmt_simple_encoder_config_t enc_config = { + .callback = encode_commands, .arg = this, .min_chunk_size = PART_SIZE}; + esp_err_t rc; + rc = rmt_new_simple_encoder(&enc_config, &_tx_encoder); + ESP_ERROR_CHECK_WITHOUT_ABORT(rc); + + connect_rmt(); + _isRunning = false; + _rmtStopped = true; +} + +void StepperQueue::connect_rmt() { + rmt_tx_channel_config_t config{}; + config.gpio_num = (gpio_num_t)_step_pin; + config.clk_src = RMT_CLK_SRC_DEFAULT; + config.resolution_hz = TICKS_PER_S; + config.mem_block_symbols = 2 * PART_SIZE; + config.trans_queue_depth = 1; + config.intr_priority = 0; + config.flags.invert_out = 0; + config.flags.with_dma = 0; + // config.flags.io_loop_back = 0; + // config.flags.io_od_mode = 0; + esp_err_t rc = rmt_new_tx_channel(&config, &channel); + ESP_ERROR_CHECK_WITHOUT_ABORT(rc); + + rmt_tx_event_callbacks_t callbacks = {.on_trans_done = queue_done}; + rmt_tx_register_event_callbacks(channel, &callbacks, this); + + _channel_enabled = false; +} + +void StepperQueue::disconnect_rmt() { + if (_channel_enabled || _isRunning || !_rmtStopped) { + return; + } + rmt_del_channel(channel); + channel = NULL; +} + +void StepperQueue::startQueue_rmt() { +// #define TRACE +#ifdef TRACE + Serial.println("START"); +#endif +#ifdef TEST_PROBE_2 + PROBE_2(LOW); +#endif +#ifdef TEST_PROBE_3 + PROBE_3(LOW); +#endif +#ifdef TEST_PROBE_1 + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); + PROBE_1_TOGGLE; + delay(1); +#endif + +// #define TRACE +#ifdef TRACE + printf("Queue: %d/%d %s\n", read_idx, next_write_idx, + _isRunning ? "Running" : "Stopped"); +#endif + + if (channel == NULL) { + return; + } + + // set dirpin toggle here + uint8_t rp = read_idx; + if (rp == next_write_idx) { + // nothing to do ? + // Should not happen, so bail + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + +#ifdef TRACE + queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + printf("first command: ticks=%u steps=%u %s %s\n", e->ticks, e->steps, + e->countUp ? "up" : "down", e->toggle_dir ? "toggle" : ""); +#endif + + // if (_channel_enabled) { + // rmt_disable(channel); + // _channel_enabled = false; + //} + + _isRunning = true; + _rmtStopped = false; + + // Reset the fill state at every transaction boundary (F2). + _rmt_fill_state.remaining_low_ticks = 0; + + // payload and payload bytes must not be 0 + int payload = 0; + rmt_transmit_config_t tx_config; + tx_config.loop_count = 0; + tx_config.flags.eot_level = 0; // output level at end of transmission + tx_config.flags.queue_nonblocking = 1; + _tx_encoder->reset(_tx_encoder); + + if (!_channel_enabled) { + rmt_enable(channel); + _channel_enabled = true; + } + + esp_err_t rc = rmt_transmit(channel, _tx_encoder, &payload, 1, &tx_config); + ESP_ERROR_CHECK_WITHOUT_ABORT(rc); +#ifdef TRACE + printf("Transmission started\n"); +#endif +} +void StepperQueue::forceStop_rmt() { + if (_channel_enabled) { + rmt_disable(channel); + } + _channel_enabled = false; + _isRunning = false; + _rmtStopped = true; + + // Reset the fill state at transaction boundary (F2). + _rmt_fill_state.remaining_low_ticks = 0; + + // and empty the buffer + read_idx = next_write_idx; +} +bool StepperQueue::isReadyForCommands_rmt() const { + if (_isRunning) { + return !_rmtStopped; + } + return true; +} +uint16_t StepperQueue::_getPerformedPulses_rmt() const { return 0; } +#endif diff --git a/src/pd_esp32/StepperISR_rmt_v2_encode.cpp b/src/pd_esp32/StepperISR_rmt_v2_encode.cpp new file mode 100644 index 0000000..d6a7006 --- /dev/null +++ b/src/pd_esp32/StepperISR_rmt_v2_encode.cpp @@ -0,0 +1,144 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_RMT_V2) + +#if (PART_SIZE & 1) != 0 +#error "PART_SIZE must be even" +#endif + +// rmt_fill_state is defined in esp32_queue.h for the target build. The PC +// test compiles this file against pd_test, which does not include +// esp32_queue.h, so provide the definition only when it is missing. +#if !defined(RMT_FILL_STATE_DEFINED) +struct rmt_fill_state { + uint16_t remaining_low_ticks; +}; +#endif + +#include "pd_esp32/test_probe.h" + +//========================================================================== +// RMT V2 fill encoder (F2 - read-ahead bound) +// +// Walks the queue and emits the low phase in pieces. Every RMT sub-entry +// (including the step high) is capped at RMT_MAX_SYMBOL_TICKS and a symbol +// holds two sub-entries, so one RMT half (PART_SIZE symbols) spans at most +// RMT_BLOCK_TICKS and the whole buffer at most RMT_BUFFER_TICKS. +// +// A pause entry is consumed when it is *scheduled*: remaining_low_ticks is set +// and read_idx advances in the same iteration, before a single one of its +// symbols has been played. LL_TOGGLE_PIN therefore runs at encode time and a +// pause only delays it by the share of the buffer the pause occupies. A pause +// that fits in the buffer does not delay it at all, which is why the DIR drain +// has to exceed RMT_BUFFER_TICKS. +// +// Only the low phase is carried in state; the capped high is emitted with the +// step-start symbol and needs no state. Every sub-entry is >= 2 ticks +// (relation 1 floor). +//========================================================================== + +static void IRAM_ATTR emit_pair(uint32_t* out, bool first_high, uint16_t a, + uint16_t b) { + uint32_t word = ((uint32_t)b << 16) | a; + if (first_high) { + word |= 0x8000u; + } + *out = word; +} + +// Emit low-only symbols until `remaining` is drained or symbols_free is used. +// Each symbol holds two low sub-entries in [2, RMT_MAX_SYMBOL_TICKS]. The +// split is chosen so the remaining ticks are never 1..3, so every sub-entry +// stays legal across calls. +static uint32_t IRAM_ATTR emit_low_only(uint32_t* symbols, + uint32_t symbols_free, + uint16_t* remaining_inout) { + const uint16_t cap = (uint16_t)RMT_MAX_SYMBOL_TICKS; + uint32_t written = 0; + uint16_t rem = *remaining_inout; + while (rem > 0 && symbols_free > 0) { + uint16_t amt; + if (rem <= (uint16_t)(2 * cap)) { + if (rem < 4) { + break; + } + amt = rem; + } else { + amt = (uint16_t)(2 * cap); + if ((uint16_t)(rem - amt) < 4) { + amt = (uint16_t)(rem - 4); + } + } + uint16_t a = (uint16_t)(amt / 2); + uint16_t b = (uint16_t)(amt - a); + emit_pair(symbols + written, false, a, b); + written++; + symbols_free--; + rem = (uint16_t)(rem - amt); + } + *remaining_inout = rem; + return written; +} + +uint32_t IRAM_ATTR rmt_encode_fill(StepperQueue* q, + struct rmt_fill_state* state, + uint32_t* symbols, uint32_t symbols_free) { + const uint16_t cap = (uint16_t)RMT_MAX_SYMBOL_TICKS; + uint32_t written = 0; + uint32_t free_sym = symbols_free; + + while (free_sym > 0) { + // 1) Drain low left over from the previous entry (or call). + if (state->remaining_low_ticks > 0) { + uint32_t n = emit_low_only(symbols + written, free_sym, + &state->remaining_low_ticks); + written += n; + free_sym -= n; + if (state->remaining_low_ticks > 0) { + break; + } + continue; + } + + if (q->read_idx == q->next_write_idx) { + break; + } + + struct queue_entry* e = &q->entry[q->read_idx & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + LL_TOGGLE_PIN(q->dirPin); + e->toggle_dir = 0; + } + + if (e->steps == 0) { + // Pause: all low. + state->remaining_low_ticks = e->ticks; + } else { + // Step: high = min(ticks >> 1, cap), low = ticks - high. + uint16_t high = (uint16_t)fas_min((uint16_t)(e->ticks >> 1), cap); + uint16_t low = (uint16_t)(e->ticks - high); + uint16_t first_low; + if (low <= cap) { + first_low = low; + } else { + first_low = cap; + if ((uint16_t)(low - first_low) < 4) { + first_low = (uint16_t)(low - 4); + } + } + emit_pair(symbols + written, true, high, first_low); + written++; + free_sym--; + state->remaining_low_ticks = (uint16_t)(low - first_low); + e->steps--; + } + + if (e->steps == 0) { + q->read_idx = (uint8_t)(q->read_idx + 1); + PROBE_4_TOGGLE; + } + } + + return written; +} + +#endif diff --git a/src/pd_esp32/esp32_queue.cpp b/src/pd_esp32/esp32_queue.cpp new file mode 100644 index 0000000..688350c --- /dev/null +++ b/src/pd_esp32/esp32_queue.cpp @@ -0,0 +1,736 @@ +#include "fas_queue/stepper_queue.h" + +#if defined(SUPPORT_ESP32_I2S) +#include "pd_esp32/i2s_manager.h" +#endif + +#if defined(SUPPORT_ESP32) + +#include + +#if defined(SUPPORT_DYNAMIC_ALLOCATION) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +uint8_t StepperQueue::queues_allocated = 0; +#if defined(SUPPORT_ESP32_I2S) +bool StepperQueue::_i2s_mux_initialized = false; +uint32_t StepperQueue::_i2s_mux_allocated_bitmask = 0; +I2sManager* StepperQueue::_i2s_mux_manager = nullptr; +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT +uint8_t StepperQueue::_mcpwm_pcnt_allocated = 0; +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +uint8_t StepperQueue::_rmt_allocated = 0; +#endif +#else +uint8_t StepperQueue::queues_allocated = 0; +#endif // SUPPORT_SELECT_DRIVER_TYPE +#endif + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + (void)queue_num; + (void)step_pin; +} + +void StepperQueue::connect() { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_ESP32_I2S) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) { + return; + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) { + connect_rmt(); + return; + } +#elif !defined(SUPPORT_ESP32_MCPWM_PCNT) + connect_rmt(); + return; +#endif +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + connect_mcpwm_pcnt(); +#endif +} + +void StepperQueue::disconnect() { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_ESP32_I2S) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) { + return; + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) { + disconnect_rmt(); + return; + } +#elif !defined(SUPPORT_ESP32_MCPWM_PCNT) + disconnect_rmt(); + return; +#endif +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + disconnect_mcpwm_pcnt(); +#endif +} + +bool StepperQueue::isReadyForCommands() const { +#if defined(SUPPORT_ESP32_I2S) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) +#endif + { + return isReadyForCommands_i2s(); + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) && defined(SUPPORT_ESP32_MCPWM_PCNT) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) { + return isReadyForCommands_rmt(); + } + return isReadyForCommands_mcpwm_pcnt(); +#else +#error "RMT + MCPWM_PCNT requires SUPPORT_SELECT_DRIVER_TYPE" +#endif +#elif defined(SUPPORT_ESP32_MCPWM_PCNT) + return isReadyForCommands_mcpwm_pcnt(); +#elif (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + return isReadyForCommands_rmt(); +#else +#error "Nothing defined here" +#endif +} + +void StepperQueue::startQueue() { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_ESP32_I2S) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) { + startQueue_i2s(); + return; + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) +#endif + { + startQueue_rmt(); + return; + } +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + startQueue_mcpwm_pcnt(); +#endif +} + +void StepperQueue::forceStop() { +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + // every branch below leaves the queue empty with the driver's pipeline + // dropped (rmt_disable / i2s channel disabled / timer off), so the next + // direction change needs no drain + markPipelineDrained(); +#endif +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_ESP32_I2S) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) { + forceStop_i2s(); + return; + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) +#endif + { + forceStop_rmt(); + return; + } +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + forceStop_mcpwm_pcnt(); +#endif +} + +uint16_t StepperQueue::_getPerformedPulses() const { +#if defined(SUPPORT_ESP32_I2S) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::I2S_DIRECT || + _driver_type == FasDriver::I2S_MUX) +#endif + { + return _getPerformedPulses_i2s(); + } +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::RMT) +#endif + { + return _getPerformedPulses_rmt(); + } +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + return _getPerformedPulses_mcpwm_pcnt(); +#endif + return 0; +} + +bool StepperQueue::isValidStepPin(uint8_t step_pin) { + gpio_drive_cap_t strength; + esp_err_t res = gpio_get_drive_capability((gpio_num_t)step_pin, &strength); + return res == ESP_OK; +} + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_DYNAMIC_ALLOCATION) +// dynamic allocation for espidf >=5.3 with support for mcpwm/pcnt, rmt, and i2s +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + FasDriver driver, + uint8_t step_pin) { + (void)engine; + if (StepperQueue::queues_allocated >= MAX_STEPPER) { + return nullptr; + } + + if (step_pin & PIN_EXTERNAL_FLAG) { + return nullptr; + } + if (step_pin & PIN_I2S_FLAG) { +#if !defined(SUPPORT_ESP32_I2S) + return nullptr; +#endif + if (!StepperQueue::_i2s_mux_initialized) { + return nullptr; + } + uint8_t slot = step_pin & 0x1F; + if (slot >= 32) { + return nullptr; + } + uint32_t bit = 1UL << slot; + if (StepperQueue::_i2s_mux_allocated_bitmask & bit) { + return nullptr; + } + StepperQueue::_i2s_mux_allocated_bitmask |= bit; + StepperQueue* q = new StepperQueue(); + q->_initVars(); + q->_driver_type = FasDriver::I2S_MUX; + q->i2s_mgr = StepperQueue::_i2s_mux_manager; + q->_i2s_mux_step_byte_offset = i2s_mux_byte_offset(slot); + q->_i2s_mux_step_bit_mask = i2s_mux_bit_mask(slot); + q->init_i2s(step_pin); + return q; + } + + if (!StepperQueue::isValidStepPin(step_pin)) { + return nullptr; + } + +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + if (driver == FasDriver::MCPWM_PCNT) { + if (StepperQueue::_mcpwm_pcnt_allocated >= QUEUES_MCPWM_PCNT) { + return nullptr; + } + StepperQueue* q = new StepperQueue(); + q->_initVars(); + q->_driver_type = FasDriver::MCPWM_PCNT; + q->init_mcpwm_pcnt(StepperQueue::_mcpwm_pcnt_allocated, step_pin); + StepperQueue::_mcpwm_pcnt_allocated++; + return q; + } +#endif + +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + if (driver == DRIVER_RMT) { + if (StepperQueue::_rmt_allocated >= QUEUES_RMT) { + return nullptr; + } + StepperQueue* q = new StepperQueue(); + q->_initVars(); + q->_driver_type = FasDriver::RMT; + StepperQueue::_rmt_allocated++; + q->init_rmt(0, step_pin); + return q; + } +#endif +#if defined(SUPPORT_ESP32_I2S) + if (driver == DRIVER_I2S_DIRECT) { + I2sManager* mgr = I2sManager::create((gpio_num_t)step_pin, I2S_GPIO_UNUSED, + I2S_GPIO_UNUSED); + if (mgr != nullptr) { + StepperQueue* q = new StepperQueue(); + q->_initVars(); + q->_driver_type = FasDriver::I2S_DIRECT; + q->i2s_mgr = mgr; + q->init_i2s(step_pin); + return q; + } + } +#endif + + if (driver != DRIVER_DONT_CARE) { + return nullptr; + } + StepperQueue* q = tryAllocateQueue(engine, DRIVER_RMT, step_pin); + if (q == nullptr) { + q = tryAllocateQueue(engine, DRIVER_I2S_DIRECT, step_pin); + } +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + if (q == nullptr) { + q = tryAllocateQueue(engine, FasDriver::MCPWM_PCNT, step_pin); + } +#endif + return q; +} +#endif // SUPPORT_SELECT_DRIVER_TYPE && SUPPORT_DYNAMIC_ALLOCATION + +#if !defined(SUPPORT_SELECT_DRIVER_TYPE) && defined(SUPPORT_DYNAMIC_ALLOCATION) +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + if (StepperQueue::queues_allocated >= MAX_STEPPER) { + return nullptr; + } + + if (step_pin & PIN_EXTERNAL_FLAG) { + return nullptr; + } + + if (!StepperQueue::isValidStepPin(step_pin)) { + return nullptr; + } + + StepperQueue* q = new StepperQueue(); + q->_initVars(); +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + q->init_rmt(0, step_pin); +#endif + StepperQueue::queues_allocated++; + return q; +} +#endif // !SUPPORT_SELECT_DRIVER_TYPE && SUPPORT_DYNAMIC_ALLOCATION + +#if !defined(SUPPORT_SELECT_DRIVER_TYPE) && !defined(SUPPORT_DYNAMIC_ALLOCATION) +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + if (step_pin & PIN_EXTERNAL_FLAG) { + return nullptr; + } + + if (!StepperQueue::isValidStepPin(step_pin)) { + return nullptr; + } + + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + if (fas_queue[i]._step_pin == step_pin) { + return nullptr; + } + } + + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + if (fas_queue[i]._step_pin == PIN_UNDEFINED) { + StepperQueue* q = &fas_queue[i]; + q->_initVars(); +#ifdef SUPPORT_ESP32_MCPWM_PCNT + if (i < QUEUES_MCPWM_PCNT) { + q->init_mcpwm_pcnt(i, step_pin); + } else +#endif + { + q->init_rmt( +#ifdef SUPPORT_ESP32_MCPWM_PCNT + i - QUEUES_MCPWM_PCNT, +#else + i, +#endif + step_pin); + } + return q; + } + } + return nullptr; +} +#endif // !SUPPORT_SELECT_DRIVER_TYPE && !SUPPORT_DYNAMIC_ALLOCATION + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) && !defined(SUPPORT_DYNAMIC_ALLOCATION) +// Static allocation with driver selection (ESP-IDF 4.x) +// Queue ranges: [0..QUEUES_MCPWM_PCNT-1] = MCPWM/PCNT +// [QUEUES_MCPWM_PCNT..QUEUES_MCPWM_PCNT+QUEUES_RMT-1] = RMT +// [QUEUES_MCPWM_PCNT+QUEUES_RMT..] = I2S +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (QUEUES_MCPWM_PCNT > 0) +static uint8_t mcpwm_pcnt_allocated = 0; +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) && (QUEUES_RMT > 0) +static uint8_t rmt_allocated = 0; +#endif +#if defined(SUPPORT_ESP32_I2S) && (QUEUES_I2S > 0) +static uint8_t i2s_allocated = 0; +#endif + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + FasDriver driver, + uint8_t step_pin) { + (void)engine; + if (step_pin & PIN_EXTERNAL_FLAG) { + return nullptr; + } + + if (!StepperQueue::isValidStepPin(step_pin)) { + return nullptr; + } + + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + if (fas_queue[i]._step_pin == step_pin) { + return nullptr; + } + } + +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (QUEUES_MCPWM_PCNT > 0) + if (driver == FasDriver::MCPWM_PCNT) { + if (mcpwm_pcnt_allocated >= QUEUES_MCPWM_PCNT) { + return nullptr; + } + StepperQueue* q = &fas_queue[mcpwm_pcnt_allocated]; + q->_initVars(); + q->_driver_type = FasDriver::MCPWM_PCNT; + q->init_mcpwm_pcnt(mcpwm_pcnt_allocated, step_pin); + mcpwm_pcnt_allocated++; + return q; + } +#endif + +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) && (QUEUES_RMT > 0) + if (driver == FasDriver::RMT) { + if (rmt_allocated >= QUEUES_RMT) { + return nullptr; + } + uint8_t idx = QUEUES_MCPWM_PCNT + rmt_allocated; + StepperQueue* q = &fas_queue[idx]; + q->_initVars(); + q->_driver_type = FasDriver::RMT; + q->init_rmt(rmt_allocated, step_pin); + rmt_allocated++; + return q; + } +#endif + +#if defined(SUPPORT_ESP32_I2S) && (QUEUES_I2S > 0) + if (driver == FasDriver::I2S_DIRECT) { + uint8_t i2s_start = QUEUES_MCPWM_PCNT + QUEUES_RMT; + if (i2s_allocated >= QUEUES_I2S) { + return nullptr; + } + uint8_t idx = i2s_start + i2s_allocated; + StepperQueue* q = &fas_queue[idx]; + q->_initVars(); + q->_driver_type = FasDriver::I2S_DIRECT; + q->init_i2s(step_pin); + i2s_allocated++; + return q; + } +#endif + + if (driver == FasDriver::DONT_CARE) { + StepperQueue* q = nullptr; +#if defined(SUPPORT_ESP32_MCPWM_PCNT) && (QUEUES_MCPWM_PCNT > 0) + q = tryAllocateQueue(engine, FasDriver::MCPWM_PCNT, step_pin); + if (q != nullptr) return q; +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) && (QUEUES_RMT > 0) + q = tryAllocateQueue(engine, FasDriver::RMT, step_pin); + if (q != nullptr) return q; +#endif +#if defined(SUPPORT_ESP32_I2S) && (QUEUES_I2S > 0) + q = tryAllocateQueue(engine, FasDriver::I2S_DIRECT, step_pin); + if (q != nullptr) return q; +#endif + } + + return nullptr; +} +#endif // SUPPORT_SELECT_DRIVER_TYPE && !SUPPORT_DYNAMIC_ALLOCATION + +void StepperTask(void* parameter) { + StepperMotionEngine* engine = + static_cast(parameter); + while (true) { + engine->manageSteppers(); +#if ESP_IDF_VERSION_MAJOR == 4 + esp_task_wdt_reset(); +#endif + const TickType_t delay_time = + (engine->_task_rate() + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS; + vTaskDelay(delay_time); + } +} + +int32_t StepperQueue::getCurrentPosition() const { + fasDisableInterrupts(); + uint32_t pos = (uint32_t)queue_end.pos; + uint8_t rp = read_idx; + bool is_empty = (rp == next_write_idx); + const struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + uint16_t pos_last16 = e->start_pos_last16; + uint8_t steps = e->steps; + int16_t done_p = (int16_t)_getPerformedPulses(); + fasEnableInterrupts(); + if (done_p == 0) { + fasDisableInterrupts(); + rp = read_idx; + is_empty = (rp == next_write_idx); + e = &entry[rp & QUEUE_LEN_MASK]; + pos_last16 = e->start_pos_last16; + steps = e->steps; + done_p = (int16_t)_getPerformedPulses(); + fasEnableInterrupts(); + } + if (!is_empty) { + uint16_t pos16 = pos & 0xffff; + uint8_t transition = ((pos16 >> 12) & 0x0c) | (pos_last16 >> 14); + switch (transition) { + case 0: // 00 00 + case 5: // 01 01 + case 10: // 10 10 + case 15: // 11 11 + break; + case 1: // 00 01 + case 6: // 01 10 + case 11: // 10 11 + case 12: // 11 00 + pos += 0x4000; + break; + case 4: // 01 00 + case 9: // 10 01 + case 14: // 11 10 + case 3: // 00 11 + pos -= 0x4000; + break; + case 2: // 00 10 + case 7: // 01 11 + case 8: // 10 00 + case 13: // 11 01 + break; // TODO: ERROR + } + pos = (int32_t)((pos & 0xffff0000) | pos_last16); + + if (steps != 0) { + int16_t adjust = e->countUp ? done_p : -done_p; + pos += adjust; + } + } + return pos; +} + +void fas_init_engine(StepperMotionEngine* engine, uint8_t cpu_core) { +#if ESP_IDF_VERSION_MAJOR == 4 +#define STACK_SIZE 2000 +#define PRIORITY configMAX_PRIORITIES +#else +// I2S adds i2s_channel_write() to StepperTask; that IDF blocking call +// consumes ~3 KB of stack by itself. Use 6 KB to be safe. +#define STACK_SIZE 6000 +#define PRIORITY (configMAX_PRIORITIES - 1) +#endif + engine->task_rate(DELAY_MS_BASE); + if (cpu_core > 1) { + xTaskCreate(StepperTask, "StepperTask", STACK_SIZE, engine, PRIORITY, NULL); + } else { + xTaskCreatePinnedToCore(StepperTask, "StepperTask", STACK_SIZE, engine, + PRIORITY, NULL, cpu_core); + } +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + + // Phase 1: arm every not-yet-running stepper (no hardware trigger). + // Skip running queues; an empty queue must not abort the others. + for (uint8_t i = 0; i < cnt; i++) { + StepperQueue* q = steppers[i]->_queue(); + if (q == nullptr || q->isRunning()) { + continue; + } + if (q->isQueueEmpty()) { + continue; // matches generic contract: empty does not stop the others + } + esp32_syncStart_arm(q); + } + + // Phase 2: one native trigger per group; groups without a native + // trigger (I2S direct, MCPWM, RMT IDF4) did their trigger in arm(). + esp32_sync_trigger_rmt(); // rmt_sync_reset() on the shared manager + + fasEnableInterrupts(); + return rc; +} + +#ifdef SUPPORT_ESP32_I2S +void StepperQueue::syncStart_arm_i2s() { + // I2S mux/direct: set _isRunning = true; first steps appear in the next DMA + // callback. The trigger is effectively the DMA done callback, which already + // groups all mux steppers on one shared manager. No separate trigger needed. + _isRunning = true; +} +#endif + +#ifdef SUPPORT_ESP32_MCPWM_PCNT +void StepperQueue::syncStart_arm_mcpwm_pcnt() { + // MCPWM/PCNT: trigger = arm (startQueue performs the actual start). + // The synchronizedStart arm phase just calls startQueue directly. + startQueue_mcpwm_pcnt(); +} +#endif + +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) +#if defined(SUPPORT_ESP32_RMT_V1) +// IDF4 RMT: trigger = arm (startQueue starts the hardware directly). +// The syncStart_arm just calls the existing startQueue. +// esp32_sync_trigger_rmt is a no-op (declared in header). +void StepperQueue::syncStart_arm_rmt() { startQueue_rmt(); } +#endif +#endif + +#if defined(SUPPORT_ESP32_RMT_SYNC) +// Per-stepper prepare for RMT on IDF5/6 with hardware sync support: do +// everything except starting the transmission. The channels are collected +// and started together by esp32_sync_trigger_rmt(). +// +// IDF's RMT sync manager is created with the complete set of TX channels to +// be managed: every managed channel is put in a waiting state until +// rmt_transmit() has been called on all of them, then they start together. +// There is no add/remove-channel API, so the manager is created on demand +// for exactly the channels armed in this synchronizedStart() call. +static StepperQueue* _sync_rmt_queues[QUEUES_RMT]; +static uint8_t _sync_rmt_cnt = 0; + +void StepperQueue::syncStart_prepare_rmt() { + if (channel == nullptr) { + return; + } + + // Direction pin toggle (same as startQueue_rmt) + uint8_t rp = read_idx; + if (rp == next_write_idx) { + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + + _isRunning = true; + _rmtStopped = false; + + // Reset the encoder (same as startQueue_rmt) + _tx_encoder->reset(_tx_encoder); + + // Enable channel if not already enabled. The sync manager requires all + // managed channels to be enabled before rmt_new_sync_manager(). + if (!_channel_enabled) { + rmt_enable(channel); + _channel_enabled = true; + } + + if (_sync_rmt_cnt < QUEUES_RMT) { + _sync_rmt_queues[_sync_rmt_cnt++] = this; + } +} + +void StepperQueue::syncStart_transmit_rmt() { + int payload = 0; + rmt_transmit_config_t tx_config; + tx_config.loop_count = 0; + tx_config.flags.eot_level = 0; // output level at end of transmission + tx_config.flags.queue_nonblocking = 1; + esp_err_t rc = rmt_transmit(channel, _tx_encoder, &payload, 1, &tx_config); + (void)rc; +} + +// Group trigger for RMT (IDF5/6): create one sync manager for all armed +// channels, kick off every transmission (held by the manager) and release +// the manager again so the channels continue independently afterwards. +void esp32_sync_trigger_rmt() { + uint8_t cnt = _sync_rmt_cnt; + _sync_rmt_cnt = 0; + if (cnt == 0) { + return; + } + + rmt_sync_manager_handle_t sync_mgr = nullptr; + rmt_channel_handle_t channels[QUEUES_RMT]; + for (uint8_t i = 0; i < cnt; i++) { + channels[i] = _sync_rmt_queues[i]->channel; + } + + // A single channel does not need a sync manager. On error (e.g. channels + // spread over several RMT groups) fall back to unsynchronized starts. + if (cnt > 1) { + rmt_sync_manager_config_t sync_config = {.tx_channel_array = channels, + .array_size = cnt}; + if (rmt_new_sync_manager(&sync_config, &sync_mgr) != ESP_OK) { + sync_mgr = nullptr; + } + } + + // The last rmt_transmit() starts all managed channels simultaneously. + for (uint8_t i = 0; i < cnt; i++) { + _sync_rmt_queues[i]->syncStart_transmit_rmt(); + } + + if (sync_mgr != nullptr) { + rmt_del_sync_manager(sync_mgr); + } +} + +#elif defined(SUPPORT_ESP32_RMT_V2) +// IDF5/6 without hardware sync (e.g. ESP32 classic): arm and start directly. +void StepperQueue::syncStart_arm_rmt() { + if (channel == nullptr) { + return; + } + + // Direction pin toggle (same as startQueue_rmt) + uint8_t rp = read_idx; + if (rp == next_write_idx) { + return; + } + if (entry[rp & QUEUE_LEN_MASK].toggle_dir) { + LL_TOGGLE_PIN(dirPin); + entry[rp & QUEUE_LEN_MASK].toggle_dir = false; + } + + _isRunning = true; + _rmtStopped = false; + + // Reset the encoder (same as startQueue_rmt) + int payload = 0; + _tx_encoder->reset(_tx_encoder); + + // Enable channel if not already enabled (same as startQueue_rmt) + if (!_channel_enabled) { + rmt_enable(channel); + _channel_enabled = true; + } + + // config must not be NULL: rmt_transmit() guards all five of + // {channel, encoder, payload, payload_bytes, config} and returns + // ESP_ERR_INVALID_ARG for a NULL config, so passing nullptr here made every + // first synchronizedStart() on ESP32 classic log + // "rmt: rmt_transmit(530): invalid argument" and start no transmission. + // Match the values startQueue_rmt() uses. The return value is deliberately + // ignored here, as it is there: the RMT fill takes over from this point. + rmt_transmit_config_t tx_config; + tx_config.loop_count = 0; + tx_config.flags.eot_level = 0; // output level at end of transmission + tx_config.flags.queue_nonblocking = 1; + rmt_transmit(channel, _tx_encoder, &payload, 1, &tx_config); +} +#endif + +#endif diff --git a/src/pd_esp32/esp32_queue.h b/src/pd_esp32/esp32_queue.h new file mode 100644 index 0000000..e80c7df --- /dev/null +++ b/src/pd_esp32/esp32_queue.h @@ -0,0 +1,500 @@ +#ifndef PD_ESP32_QUEUE_H +#define PD_ESP32_QUEUE_H + +#include + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +#if defined(SUPPORT_ESP32_I2S) +#include "pd_esp32/i2s_fill.h" +#include "pd_esp32/i2s_manager.h" +#endif + +#if defined(SUPPORT_ESP32_RMT_V2) +// The high pulse of a step is min(ticks >> 1, RMT_MAX_SYMBOL_TICKS), i.e. it is +// just another sub-entry and needs no carried state. Only the low phase can +// span more than one symbol and is split, tracked by remaining_low_ticks. +#define RMT_FILL_STATE_DEFINED +struct rmt_fill_state { + uint16_t remaining_low_ticks; +}; +#endif + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + +#if defined(SUPPORT_DYNAMIC_ALLOCATION) + static uint8_t queues_allocated; +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + static uint8_t _rmt_allocated; +#endif +#ifdef SUPPORT_ESP32_MCPWM_PCNT + static uint8_t _mcpwm_pcnt_allocated; +#endif +#if defined(SUPPORT_ESP32_I2S) + static bool _i2s_mux_initialized; + static uint32_t _i2s_mux_allocated_bitmask; + static I2sManager* _i2s_mux_manager; +#endif +#endif // SUPPORT_SELECT_DRIVER_TYPE +#endif // SUPPORT_DYNAMIC_ALLOCATION + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + FasDriver _driver_type; +#endif + + volatile bool _isRunning; + bool _nextCommandIsPrepared; + uint8_t _step_pin; + + inline void _pd_initVars() { + _step_pin = PIN_UNDEFINED; + max_speed_in_ticks = 80; +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + _driver_type = FasDriver::DONT_CARE; +#endif + } + + inline bool isRunning() const { return _isRunning; } + bool isReadyForCommands() const; + + // module specific variables + union { +#ifdef SUPPORT_ESP32_MCPWM_PCNT + const void* driver_data; +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + struct { + RMT_CHANNEL_T channel; + bool _rmtStopped; +#if defined(SUPPORT_ESP32_RMT_V2) + rmt_encoder_handle_t _tx_encoder; +#if ESP_IDF_VERSION_MAJOR >= 5 + bool _channel_enabled; +#endif + struct rmt_fill_state _rmt_fill_state; +#endif + }; +#endif +#ifdef SUPPORT_ESP32_I2S + struct { + struct i2s_fill_state _fill_state; + I2sManager* i2s_mgr; + uint8_t _i2s_mux_step_byte_offset; + uint8_t _i2s_mux_step_bit_mask; + }; +#endif + }; + + uint16_t _getPerformedPulses() const; + + // Module specific functions +#ifdef SUPPORT_ESP32_MCPWM_PCNT + bool isReadyForCommands_mcpwm_pcnt() const; + void init_mcpwm_pcnt(uint8_t channel_num, uint8_t step_pin); + void startQueue_mcpwm_pcnt(); + void forceStop_mcpwm_pcnt(); + uint16_t _getPerformedPulses_mcpwm_pcnt() const; + void connect_mcpwm_pcnt(); + void disconnect_mcpwm_pcnt(); + void syncStart_arm_mcpwm_pcnt(); +#endif +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + bool isReadyForCommands_rmt() const; + void init_rmt(uint8_t channel_num, uint8_t step_pin); + void startQueue_rmt(); +#if ESP_IDF_VERSION_MAJOR == 4 + void stop_rmt(bool both); +#endif + void forceStop_rmt(); + uint16_t _getPerformedPulses_rmt() const; + void connect_rmt(); + void disconnect_rmt(); +#if defined(SUPPORT_ESP32_RMT_SYNC) + void syncStart_prepare_rmt(); + void syncStart_transmit_rmt(); +#else + void syncStart_arm_rmt(); +#endif +#endif +#ifdef SUPPORT_ESP32_I2S + void init_i2s(uint8_t step_pin); + void startQueue_i2s(); + void forceStop_i2s(); + bool isReadyForCommands_i2s() const; + uint16_t _getPerformedPulses_i2s() const; + void fill_i2s_buffer(uint8_t* buf); + void syncStart_arm_i2s(); +#endif + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { +#if defined(SUPPORT_ESP32_I2S) && defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::I2S_DIRECT) { + dir_pin &= (uint8_t)~PIN_I2S_FLAG; + } +#endif + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; +#ifdef SUPPORT_ESP32_I2S + if ((dirPin & PIN_I2S_FLAG)) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (_driver_type == FasDriver::I2S_MUX) +#endif + { + uint8_t slot = dirPin & 0x1F; + if (slot >= 32) { + return; + } + uint32_t bit = 1UL << slot; + if (_i2s_mux_allocated_bitmask & bit) { + return; + } + _i2s_mux_allocated_bitmask |= bit; + if (_i2s_mux_manager != nullptr) { + _i2s_mux_manager->i2sMuxSetBit(slot, _dirHighCountsUp); + } + } + } +#endif + } + + private: + static bool isValidStepPin(uint8_t step_pin); +}; + +#if defined(SUPPORT_ESP32_RMT_V1) +void rmt_fill_buffer(StepperQueue* q, bool fill_part_one, uint32_t* data); +void rmt_apply_command(StepperQueue* q, bool fill_part_one, uint32_t* data); +#endif +#if defined(SUPPORT_ESP32_RMT_V2) +// F2 read-ahead bound encoder: walks the queue and emits the low phase +// in pieces. Every sub-entry is capped at RMT_MAX_SYMBOL_TICKS. +uint32_t rmt_encode_fill(StepperQueue* q, struct rmt_fill_state* state, + uint32_t* symbols, uint32_t symbols_free); +#endif + +//========================================================================== +// ESP32 PROTOCOL MACROS AND HELPER FUNCTIONS +//========================================================================== + +#if defined(SUPPORT_ESP32_I2S) +static inline void esp32_set_enable_pin_state(StepperQueue* q, uint8_t pin, + bool high) { + if (pin & PIN_I2S_FLAG) { + uint8_t slot = pin & 0x1F; + if (StepperQueue::_i2s_mux_manager != nullptr) { + StepperQueue::_i2s_mux_manager->i2sMuxSetBit(slot, high); + } + } else { + gpio_ll_set_level(&GPIO, (gpio_num_t)pin, high ? 1 : 0); + } +} + +static inline void esp32_set_direction_pin_state(StepperQueue* q, bool high) { + if (q->dirPin & PIN_I2S_FLAG) { + uint8_t slot = q->dirPin & 0x1F; + if (StepperQueue::_i2s_mux_manager != nullptr) { + StepperQueue::_i2s_mux_manager->i2sMuxSetBit(slot, high); + } + } else { + gpio_ll_set_level(&GPIO, (gpio_num_t)q->dirPin, high ? 1 : 0); + } +} + +#define SET_DIRECTION_PIN_STATE(q, high) \ + esp32_set_direction_pin_state((q), (high)) + +#define SET_ENABLE_PIN_STATE_NEED_QUEUE +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + esp32_set_enable_pin_state((q), (pin), (high)) + +#else + +#define SET_DIRECTION_PIN_STATE(q, high) \ + do { \ + gpio_ll_set_level(&GPIO, (gpio_num_t)(q)->dirPin, (high) ? 1 : 0); \ + } while (0) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + do { \ + gpio_ll_set_level(&GPIO, (gpio_num_t)(pin), (high) ? 1 : 0); \ + } while (0) + +#endif // SUPPORT_ESP32_I2S + +//========================================================================== +// DIRECTION CHANGE PAUSE INSERTION +//========================================================================== +// +// Buffered drivers (RMT, I2S) toggle the direction pin while the driver fill +// routine processes the queue entry, i.e. before the content has actually +// reached the output. A direction change therefore needs the output pipeline +// drained first, so that no step in the old direction is emitted after the +// change. The drain pauses are generated one per addQueueEntry() call: such a +// call may insert a single pause command (old direction) and then return +// AQE_DIR_CHANGE_PAUSE_INJECTED; the caller retries until the recorded pause +// state (SUPPORT_PAUSE_CMD_COUNTING) satisfies the driver's requirement. +// +// The drain is expressed in ticks only. Every driver needs one pause of at +// least the listed length, so a count carries no information the ticks do not: +// `_last_pause_ticks` is cleared by every command with steps or a DIR change +// and can only reach the requirement through an injected pause, whose length is +// the requirement itself. +// +// driver drain pause before dir change dir change/delay pause +// RMT (idf4) MIN_CMD_TICKS user dir_change_delay +// (a pause fills one whole half, +// so this is the drain half) +// RMT (idf5/6) RMT_BUFFER_TICKS + RMT_BLOCK_TICKS user dir_change_delay +// must exceed the buffer's playback +// content, because the toggle happens +// at encode time +// I2S GPIO DIR 2*I2S_BLOCK_TICKS (old dir) user dir_change_delay +// both DMA blocks must be pause: +// GPIO DIR is async at fill time +// I2S mux DIR none max(I2S_BLOCK_TICKS, +// (mask applies to the next block) user dir_change_delay) +// MCPWM/PCNT MIN_CMD_TICKS user dir_change_delay +// apply_command() (and DIR toggle) +// runs at TEA of the previous command, +// when STEP has just gone high and +// stays high until TEP. An old-DIR +// pause defers the toggle to TEA of +// that pause, with STEP already low +// independent of user delay. +// IDF5/6 also latches generator +// actions at TEZ/TEP. startQueue +// applies the first command with +// immediate update: leftover utea=2 +// would otherwise emit a step at the +// first TEA of a leading pause. +// +// IDF4 RMT needs no tick arithmetic: a queue pause occupies exactly one half, +// so the drain half is what puts a pause in the half the DIR toggle is filled +// into — the same slot the 1.2.7 fill-time inject used. +// +// IDF4 ping-pongs one half per interrupt (and startQueue's double-fill +// puts the drain in part 2, so the first ISR fill is the toggle while +// that drain plays). One pause is therefore the same as one inject: +// last step part -> pause part -> fill that toggles DIR. +// +// IDF5/6 (F2) no longer fills fixed halves: rmt_encode_fill() emits +// variable-length symbols and the queue can be several commands deep. The +// toggle still happens at encode time, so the drain has to cover the buffer +// content rather than one command; see esp32_before_pause_ticks(). +// +// The fill path must not insert pauses of its own: extra ticks would be +// invisible to addQueueEntry()/moveTimed(). +// +// Once the pipeline is drained, the pause that carries the direction change is +// inserted (count_up = cmd->count_up). The driver toggles the pin while +// processing that entry and then idles, so the user requested +// dir_change_delay_ticks is honored as part of the direction change. +// +// I2S GPIO DIR needs 2*I2S_BLOCK_TICKS before the change (in-flight block and +// the block being filled must contain no steps). Mux-slot DIR (PIN_I2S_FLAG) +// updates _mux_state for the next block, so the after-pause is I2S_BLOCK_TICKS +// and there is no extra before-pause. MCPWM uses MIN_CMD_TICKS: pause TEA at +// compare=1 applies the following command (DIR) at the start of that pause, +// after STEP has gone low at TEP of the last step. +static inline bool esp32_driver_is_rmt(const StepperQueue* q) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + return q->_driver_type == FasDriver::RMT; +#else + return false; +#endif +#elif (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + return true; +#else + return false; +#endif +} + +static inline bool esp32_driver_is_mcpwm(const StepperQueue* q) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + return q->_driver_type == FasDriver::MCPWM_PCNT; +#else + return false; +#endif +#elif defined(SUPPORT_ESP32_MCPWM_PCNT) + return true; +#else + return false; +#endif +} + +static inline bool esp32_driver_is_i2s(const StepperQueue* q) { +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +#if defined(SUPPORT_ESP32_I2S) + return q->_driver_type == FasDriver::I2S_DIRECT || + q->_driver_type == FasDriver::I2S_MUX; +#else + return false; +#endif +#elif defined(SUPPORT_ESP32_I2S) + return true; +#else + return false; +#endif +} + +static inline bool esp32_i2s_dir_is_mux_slot(const StepperQueue* q) { +#if defined(SUPPORT_ESP32_I2S) +#if defined(SUPPORT_SELECT_DRIVER_TYPE) + if (q->_driver_type == FasDriver::I2S_DIRECT) { + return false; + } +#endif + if (!esp32_driver_is_i2s(q) || ((q->dirPin & PIN_I2S_FLAG) == 0)) { + return false; + } + return true; +#else + (void)q; + return false; +#endif +} + +static inline uint16_t esp32_before_pause_ticks(const StepperQueue* q) { +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + if (esp32_driver_is_rmt(q)) { +#if defined(SUPPORT_ESP32_RMT_V2) + // F2: the drain must exceed the RMT buffer's playback content, and that is + // the whole requirement. rmt_encode_fill() consumes a pause entry when it + // *schedules* it (remaining_low_ticks is set and read_idx advances at + // once), and LL_TOGGLE_PIN runs when the encoder reaches the next entry -- + // both at encode time, while the buffer still holds earlier symbols. A + // pause therefore delays the toggle only by the share of the buffer it + // occupies; one that fits in the buffer delays it by nothing at all, and + // the toggle lands while the previous segment's steps are still stepping. + // RMT_DIR_DRAIN_TICKS is RMT_BUFFER_TICKS plus one block of margin; + // tests/host/test_30.cpp asserts that ordering. + return RMT_DIR_DRAIN_TICKS; +#else + return MIN_CMD_TICKS; +#endif + } +#endif +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + if (esp32_driver_is_mcpwm(q)) { + return MIN_CMD_TICKS; + } +#endif +#if defined(SUPPORT_ESP32_I2S) + if (esp32_driver_is_i2s(q) && !esp32_i2s_dir_is_mux_slot(q)) { + return I2S_DIR_DRAIN_TICKS; + } +#endif + return 0; +} + +static inline uint16_t esp32_after_pause_ticks(const StepperQueue* q) { +#if defined(SUPPORT_ESP32_I2S) + if (esp32_driver_is_i2s(q) && esp32_i2s_dir_is_mux_slot(q)) { + return I2S_BLOCK_TICKS; + } +#else + (void)q; +#endif + return 0; +} + +static inline AqeResultCode esp32_enqueue_pause(StepperQueue* q, + uint16_t pause_ticks, + bool start, bool count_up) { + struct stepper_command_s pause_cmd = { + .ticks = pause_ticks, .steps = 0, .count_up = count_up}; + AqeResultCode res = q->addQueueEntry(&pause_cmd, start); + if (res == AQE_OK) { + q->_injected_pause_ticks = pause_ticks; + } + return res; +} + +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + uint16_t needed_pause_ticks = esp32_before_pause_ticks(this); + if (_last_pause_ticks < needed_pause_ticks) { + AqeResultCode res = esp32_enqueue_pause(this, needed_pause_ticks, start, + queue_end.count_up); + if (res != AQE_OK) { + return res; + } + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + // Before-pause requirement is met. Enforce the direction-change/delay pause. + uint16_t delay_ticks = + (uint16_t)fas_max(dir_change_delay_ticks, esp32_after_pause_ticks(this)); + bool needs_toggle_pause = false; + if (cmd->steps == 0) { + if ((delay_ticks != 0) && (cmd->ticks < delay_ticks)) { + needs_toggle_pause = true; + delay_ticks = (uint16_t)fas_max(delay_ticks - cmd->ticks, MIN_CMD_TICKS); + } + } else if (delay_ticks != 0) { + needs_toggle_pause = true; + delay_ticks = (uint16_t)fas_max(delay_ticks, MIN_CMD_TICKS); + } + if (!needs_toggle_pause) { + return AQE_OK; + } + AqeResultCode res = + esp32_enqueue_pause(this, delay_ticks, start, cmd->count_up); + if (res != AQE_OK) { + return res; + } + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +//========================================================================== +// SYNCHRONIZED START DISPATCH +//========================================================================== + +// Per-stepper arm phase: called from synchronizedStart() with interrupts off. +// Each driver handles its own arm logic. The parameter cannot be const: the +// arm methods write the driver registers. In a build without any of the +// driver macros below, q is deliberately unused. +// cppcheck-suppress constParameterPointer +static inline void esp32_syncStart_arm(StepperQueue* q) { +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + if (esp32_driver_is_rmt(q)) { +#if defined(SUPPORT_ESP32_RMT_SYNC) + q->syncStart_prepare_rmt(); +#else + q->syncStart_arm_rmt(); +#endif + return; + } +#endif +#if defined(SUPPORT_ESP32_I2S) + if (esp32_driver_is_i2s(q)) { + q->syncStart_arm_i2s(); + return; + } +#endif +#if defined(SUPPORT_ESP32_MCPWM_PCNT) + if (esp32_driver_is_mcpwm(q)) { + q->syncStart_arm_mcpwm_pcnt(); + return; + } +#endif + // No driver: nothing to arm. +} + +// Group trigger: one call per group with shared resources. +#if defined(SUPPORT_ESP32_RMT_SYNC) +void esp32_sync_trigger_rmt(void); +#else +static inline void esp32_sync_trigger_rmt(void) {} +#endif // SUPPORT_ESP32_RMT_SYNC +#if defined(SUPPORT_ESP32_I2S) +static inline void esp32_sync_trigger_i2s_mux(void) {} +#endif // SUPPORT_ESP32_I2S + +#endif diff --git a/src/pd_esp32/i2s_constants.h b/src/pd_esp32/i2s_constants.h new file mode 100644 index 0000000..54c1f22 --- /dev/null +++ b/src/pd_esp32/i2s_constants.h @@ -0,0 +1,73 @@ +#ifndef PD_ESP32_I2S_CONSTANTS_H +#define PD_ESP32_I2S_CONSTANTS_H +#if defined(SUPPORT_ESP32_I2S) + +#include "fas_ramp/RampCalculator.h" // US_TO_TICKS + +// I2S timing: 16-bit stereo mode +// Sample rate: 250kHz +// Bits per frame: 16-bit L + 16-bit R = 32 bits +// BCLK = 250kHz × 32 bits = 8MHz +// Frame duration = 32 bits / 8MHz = 4µs +// At 16MHz stepper reference: 4µs × 16 = 64 ticks per frame +#define I2S_SAMPLE_RATE_HZ 250000UL +#define I2S_TICKS_PER_FRAME 64 +#define I2S_BITS_PER_FRAME 32 +#define I2S_BYTES_PER_FRAME 4 + +// All constants derived from I2S_BLOCK_DURATION_US (per design doc) +#define I2S_BLOCK_DURATION_US 500 +#define I2S_BLOCK_COUNT 2 +#define I2S_FRAMES_PER_BLOCK \ + (I2S_BLOCK_DURATION_US * I2S_SAMPLE_RATE_HZ / 1000000UL) +#define I2S_BLOCK_TICKS (I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME) +#define I2S_BYTES_PER_BLOCK (I2S_FRAMES_PER_BLOCK * I2S_BYTES_PER_FRAME) + +// Total buffer (all 2 blocks combined) +#define I2S_TOTAL_FRAMES (I2S_BLOCK_COUNT * I2S_FRAMES_PER_BLOCK) +#define I2S_TOTAL_BYTES (I2S_BLOCK_COUNT * I2S_BYTES_PER_BLOCK) + +// Max frequency enforced by addQueueEntry(), not by I2S driver +#define MAX_STEP_FREQ_HZ 200000UL + +// Max pulses per block (for tracking array size) +// 500µs × 200kHz = 100, +1 for safety +#define I2S_MAX_PULSES_PER_BLOCK \ + ((I2S_BLOCK_DURATION_US * MAX_STEP_FREQ_HZ / 1000000UL) + 1) + +#define I2S_DIRECT_MIN_SPEED_TICKS 80 +#define I2S_MUX_MIN_SPEED_TICKS 400 + +// Drain pause before an I2S_DIRECT direction change. 2 * I2S_BLOCK_TICKS +// (1000 us) assumed the fill lead is two DMA blocks; measured 677..1096 us, +// since the TX FIFO still holds part of a descriptor at DMA EOF. 1200 us +// covers that plus one block of margin. +#define I2S_DIR_DRAIN_US 1200 +#define I2S_DIR_DRAIN_TICKS ((uint16_t)US_TO_TICKS(I2S_DIR_DRAIN_US)) + +// 100kHz step frequency corresponds to 10µs period, so 2µs pulse width is 20% +#define I2S_DEFAULT_PULSE_WIDTH_TICKS 32 + +// DMA: minimum for continuous streaming (per design doc) +#define I2S_DMA_DESC_NUM 2 +#define I2S_DMA_FRAME_NUM I2S_FRAMES_PER_BLOCK + +// Convert I2S mux slot (0-31) to 32-bit bit position. +// Direct mapping: slot S → byte S/8, bit S%8 +// slot 0 -> bit 0, slot 7 -> bit 7, slot 8 -> bit 8, slot 15 -> bit 15 +static inline uint8_t i2s_mux_slot_to_bit_pos(uint8_t slot) { return slot; } + +static inline uint8_t i2s_mux_byte_offset(uint8_t slot) { + return i2s_mux_slot_to_bit_pos(slot) >> 3; +} + +static inline uint8_t i2s_mux_bit_mask(uint8_t slot) { + return 1 << (i2s_mux_slot_to_bit_pos(slot) & 7); +} + +static inline uint32_t i2s_mux_bit_mask_u32(uint8_t slot) { + return 1UL << i2s_mux_slot_to_bit_pos(slot); +} + +#endif // SUPPORT_ESP32_I2S +#endif // PD_ESP32_I2S_CONSTANTS_H diff --git a/src/pd_esp32/i2s_fill.cpp b/src/pd_esp32/i2s_fill.cpp new file mode 100644 index 0000000..cbbb465 --- /dev/null +++ b/src/pd_esp32/i2s_fill.cpp @@ -0,0 +1,161 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_I2S) + +#include "pd_esp32/i2s_fill.h" + +static const uint8_t ticks_per_bit = I2S_TICKS_PER_FRAME / I2S_BITS_PER_FRAME; + +bool IRAM_ATTR i2s_fill_buffer_mux(StepperQueue* q, uint8_t* buf, + struct i2s_fill_state* state, + uint8_t byte_offset, uint8_t bit_mask) { + struct i2s_fill_state local_state = *state; + uint8_t rp = q->read_idx; + uint8_t frame_pos = 0; + + do { + while (local_state.remaining_high_ticks >= I2S_TICKS_PER_FRAME) { + buf[frame_pos * I2S_BYTES_PER_FRAME + byte_offset] |= bit_mask; + frame_pos++; + local_state.remaining_high_ticks -= I2S_TICKS_PER_FRAME; + + if (frame_pos >= I2S_FRAMES_PER_BLOCK) { + *state = local_state; + return true; + } + } + + if (local_state.remaining_low_ticks > 0) { + uint16_t frames_in_block = I2S_FRAMES_PER_BLOCK - frame_pos; + uint16_t low_frames = + local_state.remaining_low_ticks / I2S_TICKS_PER_FRAME; + + if (low_frames < frames_in_block) { + frame_pos += low_frames; + local_state.off_ticks = + local_state.remaining_low_ticks % I2S_TICKS_PER_FRAME; + local_state.remaining_low_ticks = 0; + } else { + local_state.remaining_low_ticks -= + frames_in_block * I2S_TICKS_PER_FRAME; + *state = local_state; + return true; + } + } + + if (rp == q->next_write_idx) { + *state = local_state; + return false; + } + + struct queue_entry* e = &q->entry[rp & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + SET_DIRECTION_PIN_STATE(q, e->dirPinState); + e->toggle_dir = 0; + } + + local_state.remaining_low_ticks = e->ticks + local_state.off_ticks; + local_state.off_ticks = 0; + + if (e->steps > 0) { + local_state.remaining_low_ticks -= I2S_TICKS_PER_FRAME; + local_state.remaining_high_ticks = I2S_TICKS_PER_FRAME; + e->steps--; + } + + if (e->steps == 0) { + rp++; + q->read_idx = rp; + } + } while (true); +} + +bool IRAM_ATTR i2s_fill_buffer_direct(StepperQueueBase* q, uint8_t* buf, + struct i2s_fill_state* state) { +#ifdef DEBUG + printf( + "i2s_fill_buffer called remaining_high_ticks=%u " + "remaining_low_ticks=%u\n", + state->remaining_high_ticks, state->remaining_low_ticks); +#endif + + struct i2s_fill_state local_state = *state; + uint8_t rp = q->read_idx; + + uint16_t bit_pos = 0; + do { + while (local_state.remaining_high_ticks > 0) { +#ifdef DEBUG + printf(" Writing pulse at remaining_ticks=%u bit_pos=%u\n", + local_state.remaining_high_ticks, bit_pos); +#endif + // Byte order in I2S buffer is little-endian, but bits are sent MSB first, + // so we need to XOR the byte index with 1. + uint16_t byte_index = (bit_pos >> 3) ^ 1; + // always fill the full byte + buf[byte_index] = 0xff >> (bit_pos & 7); + uint8_t bits = 8 - (bit_pos & 7); + uint8_t ticks = bits * ticks_per_bit; + if (local_state.remaining_high_ticks >= ticks) { + local_state.remaining_high_ticks -= ticks; + } else { + local_state.remaining_low_ticks -= + (ticks - local_state.remaining_high_ticks); + local_state.remaining_high_ticks = 0; + } + + bit_pos += bits; + if (bit_pos >= I2S_BYTES_PER_BLOCK * 8) { + *state = local_state; + return true; + } + } + if (local_state.remaining_low_ticks > 0) { + uint16_t ticks_in_block = I2S_BLOCK_TICKS - bit_pos * ticks_per_bit; +#ifdef DEBUG + printf( + " Advancing through low ticks " + "remaining_low_ticks=%u ticks_in_block=%u\n", + local_state.remaining_low_ticks, ticks_in_block); +#endif + if (local_state.remaining_low_ticks < ticks_in_block) { + bit_pos += local_state.remaining_low_ticks / ticks_per_bit; + local_state.off_ticks = local_state.remaining_low_ticks % ticks_per_bit; + local_state.remaining_low_ticks = 0; + } else { + local_state.remaining_low_ticks -= ticks_in_block; + *state = local_state; + return true; + } + } + + if (rp == q->next_write_idx) { + *state = local_state; + return false; + } + + struct queue_entry* e = &q->entry[rp & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + // Cannot be an I2S mux pin, so directly toggle the pin level. + LL_TOGGLE_PIN(q->dirPin); + e->toggle_dir = 0; + } + uint8_t steps = e->steps; + local_state.remaining_low_ticks = e->ticks; + if (local_state.remaining_low_ticks < 65535 - ticks_per_bit) { + local_state.remaining_low_ticks += local_state.off_ticks; + local_state.off_ticks = 0; + } + if (steps > 0) { + local_state.remaining_low_ticks -= I2S_DEFAULT_PULSE_WIDTH_TICKS; + local_state.remaining_high_ticks = I2S_DEFAULT_PULSE_WIDTH_TICKS; + steps--; + e->steps = steps; + } + if (steps == 0) { + rp++; + q->read_idx = rp; + } + } while (true); +} + +#endif diff --git a/src/pd_esp32/i2s_fill.h b/src/pd_esp32/i2s_fill.h new file mode 100644 index 0000000..2c6061a --- /dev/null +++ b/src/pd_esp32/i2s_fill.h @@ -0,0 +1,27 @@ +#ifndef PD_ESP32_I2S_FILL_H +#define PD_ESP32_I2S_FILL_H +#if defined(SUPPORT_ESP32_I2S) + +#include +#include "pd_esp32/i2s_constants.h" +#include "fas_queue/base.h" + +#ifndef LL_TOGGLE_PIN +#define LL_TOGGLE_PIN(dirPin) +#endif + +struct i2s_fill_state { + uint16_t remaining_low_ticks; + uint8_t remaining_high_ticks; + uint8_t off_ticks; +}; + +bool i2s_fill_buffer_direct(StepperQueueBase* q, uint8_t* buf, + struct i2s_fill_state* state); + +bool i2s_fill_buffer_mux(StepperQueue* q, uint8_t* buf, + struct i2s_fill_state* state, uint8_t byte_offset, + uint8_t bit_mask); + +#endif +#endif diff --git a/src/pd_esp32/i2s_manager.cpp b/src/pd_esp32/i2s_manager.cpp new file mode 100644 index 0000000..d2526ae --- /dev/null +++ b/src/pd_esp32/i2s_manager.cpp @@ -0,0 +1,146 @@ +#include "fas_queue/stepper_queue.h" +#if defined(SUPPORT_ESP32_I2S) + +#include "pd_esp32/i2s_manager.h" +#include "pd_esp32/esp32_queue.h" +#include + +static IRAM_ATTR bool i2s_tx_done_callback(i2s_chan_handle_t handle, + i2s_event_data_t* event, + void* user_ctx) { + I2sManager* mgr = static_cast(user_ctx); + uint8_t* buf = static_cast(event->dma_buf); + mgr->handleTxDone(buf); + return false; +} + +I2sManager* I2sManager::create(gpio_num_t data_pin, gpio_num_t bclk_pin, + gpio_num_t ws_pin) { +#ifdef DEBUG + Serial.printf("I2S create: data=%d, bclk=%d, ws=%d\n", data_pin, bclk_pin, + ws_pin); +#endif + + i2s_chan_config_t chan_cfg = + I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); + chan_cfg.dma_desc_num = I2S_DMA_DESC_NUM; + chan_cfg.dma_frame_num = I2S_DMA_FRAME_NUM; + chan_cfg.auto_clear = false; // buf is cleared _after_ the callback... + + i2s_chan_handle_t chan = nullptr; + esp_err_t rc = i2s_new_channel(&chan_cfg, &chan, NULL); + if (rc != ESP_OK) { + return nullptr; + } + + i2s_std_config_t std_cfg = {}; + std_cfg.clk_cfg.sample_rate_hz = I2S_SAMPLE_RATE_HZ; + std_cfg.clk_cfg.clk_src = I2S_CLK_SRC_DEFAULT; + std_cfg.clk_cfg.mclk_multiple = I2S_MCLK_MULTIPLE_128; +#if (ESP_IDF_VERSION_MAJOR > 5) || \ + (ESP_IDF_VERSION_MAJOR == 5 && ESP_IDF_VERSION_MINOR >= 5) + std_cfg.clk_cfg.bclk_div = 0; +#endif + std_cfg.slot_cfg = I2S_STD_MSB_SLOT_DEFAULT_CONFIG(I2S_DATA_BIT_WIDTH_16BIT, + I2S_SLOT_MODE_STEREO); + std_cfg.gpio_cfg.mclk = I2S_GPIO_UNUSED; + std_cfg.gpio_cfg.bclk = bclk_pin; + std_cfg.gpio_cfg.ws = ws_pin; + std_cfg.gpio_cfg.dout = data_pin; + std_cfg.gpio_cfg.din = I2S_GPIO_UNUSED; + std_cfg.gpio_cfg.invert_flags.mclk_inv = false; + std_cfg.gpio_cfg.invert_flags.bclk_inv = false; + std_cfg.gpio_cfg.invert_flags.ws_inv = false; + + rc = i2s_channel_init_std_mode(chan, &std_cfg); + if (rc != ESP_OK) { + i2s_del_channel(chan); + return nullptr; + } + + I2sManager* mgr = new I2sManager(); + mgr->_chan = chan; + if (!mgr->init()) { + i2s_del_channel(mgr->_chan); + mgr->_chan = nullptr; + delete mgr; + return nullptr; + } + +#ifdef DEBUG + Serial.printf("I2S startDma: enabling channel\n"); +#endif + if (i2s_channel_enable(mgr->_chan) != ESP_OK) { +#ifdef DEBUG + Serial.printf("I2S startDma: channel enable FAILED\n"); +#endif + i2s_del_channel(mgr->_chan); + mgr->_chan = nullptr; + delete mgr; + return nullptr; + } + + return mgr; +} + +bool I2sManager::init() { + i2s_event_callbacks_t cbs = {}; + cbs.on_sent = i2s_tx_done_callback; + esp_err_t rc = i2s_channel_register_event_callback(_chan, &cbs, this); + if (rc != ESP_OK) { + return false; + } + return true; +} + +void IRAM_ATTR I2sManager::init_mux_buffer(uint8_t* buf) { + uint32_t* b = reinterpret_cast(buf); + uint8_t i = I2S_BYTES_PER_BLOCK / 4; + do { + b[--i] = _mux_state; + } while (i); +} + +void IRAM_ATTR I2sManager::i2sMuxSetBit(uint8_t slot, bool value) { + if (slot >= 32) { + return; + } + uint32_t bit = i2s_mux_bit_mask_u32(slot); + if (value) { + _mux_state |= bit; + } else { + _mux_state &= ~bit; + } +} + +bool IRAM_ATTR I2sManager::i2sMuxGetBit(uint8_t slot) { + if (slot >= 32) { + return false; + } + return (_mux_state & i2s_mux_bit_mask_u32(slot)) != 0; +} + +void IRAM_ATTR I2sManager::handleTxDone(uint8_t* buf) { + _callback_count += 1; + + if (_is_mux) { + init_mux_buffer(buf); + } else { + // around 18us + memset(buf, 0, I2S_BYTES_PER_BLOCK); + } + + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + StepperQueue* q = fas_queue[i]; + if (q && + (q->_driver_type == FasDriver::I2S_DIRECT || + q->_driver_type == FasDriver::I2S_MUX) && + q->i2s_mgr == this) { + // 32us..44us @ v=10us + // ~63us @ v=5us + q->fill_i2s_buffer(buf); + } + } +} + +#endif // SUPPORT_ESP32_I2S diff --git a/src/pd_esp32/i2s_manager.h b/src/pd_esp32/i2s_manager.h new file mode 100644 index 0000000..c3a8027 --- /dev/null +++ b/src/pd_esp32/i2s_manager.h @@ -0,0 +1,32 @@ +#ifndef PD_ESP32_I2S_MANAGER_H +#define PD_ESP32_I2S_MANAGER_H +#if defined(SUPPORT_ESP32_I2S) + +#include +#include "i2s_constants.h" +#include + +class I2sManager { + public: + static I2sManager* create(gpio_num_t data_pin, gpio_num_t bclk_pin, + gpio_num_t ws_pin); + + void handleTxDone(uint8_t* buf); + + bool _is_mux = false; + + volatile uint32_t _callback_count = 0; + + void i2sMuxSetBit(uint8_t slot, bool value); + bool i2sMuxGetBit(uint8_t slot); + + private: + I2sManager() {} + bool init(); + void init_mux_buffer(uint8_t* buf); + i2s_chan_handle_t _chan = nullptr; + uint32_t _mux_state = 0; +}; + +#endif // SUPPORT_ESP32_I2S +#endif // PD_ESP32_I2S_MANAGER_H diff --git a/src/pd_esp32/pd_config.h b/src/pd_esp32/pd_config.h new file mode 100644 index 0000000..edd1bb4 --- /dev/null +++ b/src/pd_esp32/pd_config.h @@ -0,0 +1,127 @@ +// pd_esp32/pd_config.h - ESP32 platform configuration +// +// This file defines ESP32-specific constants for the StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Driver type selection (RMT, MCPWM/PCNT, I2S) +// - Feature flags for ESP32-specific behavior +// +// Includes pd_config_idfX.h for IDF version-specific chip configurations. +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_ESP32_CONFIG_H +#define PD_ESP32_CONFIG_H + +#include + +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +#if ESP_IDF_VERSION_MAJOR == 6 +#define SUPPORT_DYNAMIC_ALLOCATION +#include "pd_esp32/pd_config_idf6.h" +#elif ESP_IDF_VERSION_MAJOR == 5 +#define SUPPORT_DYNAMIC_ALLOCATION +#if ESP_IDF_VERSION_MINOR < 3 +#error "StepperMotion requires esp-idf >= 5.3.0" +#endif +#include "pd_esp32/pd_config_idf5.h" +#elif ESP_IDF_VERSION_MAJOR == 4 +#include "pd_esp32/pd_config_idf4.h" +#elif ESP_IDF_VERSION_MAJOR <= 3 +#error "StepperMotion does not support ESP-IDF 3.x or older" +#endif + +// The RMT sync manager (rmt_new_sync_manager()/rmt_sync_reset()) is only +// available on targets with SOC_RMT_SUPPORT_TX_SYNCHRO. The ESP32 classic +// has the RMT V2 driver API but no sync manager, so it falls back to the +// generic (arm == trigger) path. +#if defined(SUPPORT_ESP32_RMT_V2) && defined(SOC_RMT_SUPPORT_TX_SYNCHRO) +#define SUPPORT_ESP32_RMT_SYNC +#endif + +// Esp32 queue definitions +#if defined(SUPPORT_DYNAMIC_ALLOCATION) +#if defined(SUPPORT_ESP32_I2S) +#define QUEUES_I2S_MUX 32 +// One I2S TX channel per I2sManager (i2s_new_channel(..., &chan, NULL), no RX +// channel), so the ceiling is the chip's I2S peripheral count -- 2 on the +// ESP32. QUEUES_I2S_DIRECT is stated per variant in pd_config_idf5.h and +// pd_config_idf6.h rather than read from the SDK: IDF 6 removed SOC_I2S_NUM, +// so reading it compiled on IDF 5 and not on IDF 6. See the comment there. +#else +#define QUEUES_I2S_MUX 0 +#define QUEUES_I2S_DIRECT 0 +#endif +#define QUEUES_I2S (QUEUES_I2S_MUX + QUEUES_I2S_DIRECT) +#define NUM_QUEUES \ + (QUEUES_MCPWM_PCNT + QUEUES_RMT + QUEUES_I2S_MUX + QUEUES_I2S_DIRECT) +#else +#if defined(SUPPORT_ESP32_I2S) +#if SOC_I2S_NUM >= 2 +#define QUEUES_I2S 64 +#else +#define QUEUES_I2S 32 +#endif +#else +#define QUEUES_I2S 0 +#endif +#define NUM_QUEUES (QUEUES_MCPWM_PCNT + QUEUES_RMT + QUEUES_I2S) +#endif +#define MAX_STEPPER (NUM_QUEUES) +#define QUEUE_LEN 32 + +// Esp32 timing definition +#define TICKS_PER_S 16000000L +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 4 + +#define SUPPORT_QUEUE_ENTRY_START_POS_U16 + +#define SUPPORT_PAUSE_CMD_COUNTING + +#define DEBUG_LED_HALF_PERIOD 50 + +#define noop_or_wait vTaskDelay(1) + +#define SUPPORT_CPU_AFFINITY + +#define SUPPORT_TASK_RATE_CHANGE + +#if defined(SUPPORT_ESP32_I2S) +#define PIN_I2S_FLAG 0x40 +#endif + +#define LL_TOGGLE_PIN(dirPin) \ + gpio_ll_set_level(&GPIO, (gpio_num_t)dirPin, \ + gpio_ll_get_level(&GPIO, (gpio_num_t)dirPin) ^ 1) + +//========================================================================== +// determine, if driver type selection should be supported +// Enable if at least two different driver types have queues +#if (defined(QUEUES_MCPWM_PCNT) && defined(QUEUES_RMT)) || \ + (defined(QUEUES_RMT) && defined(QUEUES_I2S)) +#if ((QUEUES_MCPWM_PCNT > 0) && (QUEUES_RMT > 0)) || \ + ((QUEUES_RMT > 0) && (QUEUES_I2S > 0)) +#define SUPPORT_SELECT_DRIVER_TYPE +#endif +#endif + +#if defined(SUPPORT_SELECT_DRIVER_TYPE) +enum class FasDriver : uint8_t { +#if (defined(QUEUES_MCPWM_PCNT) && (QUEUES_MCPWM_PCNT > 0)) + MCPWM_PCNT = 0, +#endif +#if (defined(QUEUES_RMT) && (QUEUES_RMT > 0)) + RMT = 1, +#endif +#if defined(SUPPORT_ESP32_I2S) && (defined(QUEUES_I2S) && (QUEUES_I2S > 0)) + I2S_DIRECT = 2, + I2S_MUX = 3, +#endif + DONT_CARE = 255 +}; +#endif + +#endif /* PD_ESP32_CONFIG_H */ diff --git a/src/pd_esp32/pd_config_idf4.h b/src/pd_esp32/pd_config_idf4.h new file mode 100644 index 0000000..89e95e2 --- /dev/null +++ b/src/pd_esp32/pd_config_idf4.h @@ -0,0 +1,113 @@ +#ifndef PD_ESP32_CONFIG_IDF4_H +#define PD_ESP32_CONFIG_IDF4_H + +//========================================================================== +// +// ESP32 derivate - the first one +// +//========================================================================== + +#if CONFIG_IDF_TARGET_ESP32 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V1 +#define SUPPORT_ESP32_PULSE_COUNTER 8 +#define SUPPORT_ESP32_RMT_TICK_LOST +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 +#define QUEUES_MCPWM_PCNT 6 +#define QUEUES_RMT 8 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S2 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S2 +#define SUPPORT_ESP32_RMT_V1 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S3 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V1 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32S3_RMT +#define RMT_SIZE 48 + +#define QUEUES_MCPWM_PCNT 4 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32C3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32C3 +#define SUPPORT_ESP32_RMT_V1 +#define HAVE_ESP32C3_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS + +//========================================================================== +// +// For all unsupported ESP32 derivates +// +//========================================================================== +#else +#error "Unsupported derivate" +#endif + +#if ESP_IDF_VERSION_MINOR == 4 +#define __ESP32_IDF_V44__ +#endif + +#include +#include + +#ifdef NEED_MCPWM_HEADERS +#include +#include +#include +#endif + +#ifdef NEED_PCNT_HEADERS +#include +#include +#include +#endif + +#ifdef NEED_RMT_HEADERS +#include +#include +#include +#include + +#define RMT_CHANNEL_T rmt_channel_t +#define FAS_RMT_MEM(channel) ((uint32_t*)RMTMEM.chan[channel].data32) + +// PART_SIZE shall be even. +#define PART_SIZE (((RMT_SIZE - 1) / 4) << 1) + +#endif + +#endif /* PD_ESP32_CONFIG_IDF4_H */ diff --git a/src/pd_esp32/pd_config_idf5.h b/src/pd_esp32/pd_config_idf5.h new file mode 100644 index 0000000..ca32fc4 --- /dev/null +++ b/src/pd_esp32/pd_config_idf5.h @@ -0,0 +1,248 @@ +#ifndef PD_ESP32_CONFIG_IDF5_H +#define PD_ESP32_CONFIG_IDF5_H + +//-------------------------------------------------------------------------- +// QUEUES_I2S_DIRECT -- one I2S TX channel per I2sManager +// +// What this number does: it sizes the pool. MAX_STEPPER bounds +// `_stepper[MAX_STEPPER]` (StepperMotionEngine.h) and fas_queue[NUM_QUEUES] +// (queue_init.cpp), and tryAllocateQueue() refuses past it -- and both of those +// exist under SUPPORT_DYNAMIC_ALLOCATION too, which changes the elements from +// inline queues to pointers but not the array bounds. So the constant is not +// dead weight under dynamic allocation; it is the sum's upper bound. +// +// What it does NOT do: enforce the limit. The i2s_direct path has no +// _i2s_direct_allocated counter, unlike mcpwm_pcnt and rmt which each keep +// one. It asks I2sManager::create(), which returns nullptr when +// i2s_new_channel() fails, and the hardware answers. So overstating this +// number costs RAM (two pointer arrays, 8 B per slot on ESP32) and buys +// nothing -- which is the other half of why the old 3 was wrong. +// +// Stated per variant rather than read from SOC_I2S_NUM, which this SDK does +// define and which is why it looks like the obvious source: +// +// - IDF 6 removed it. SOC_I2S_NUM lives in components/soc//.../ +// soc_caps.h through IDF 5 and is gone in IDF 6, where the count moved to +// the LL layer as I2S_LL_INST_NUM. A constant read from the SDK compiles on +// one and not the other, which is exactly what happened: 36d71a12 put it in +// the arm both compile, and every IDF 6 build failed on it. +// +// - The hardware does not move, so there is nothing to track. IDF 5's +// SOC_I2S_NUM and IDF 6's I2S_LL_INST_NUM agree on every variant (esp32 2, +// s3 2, p4 3, s2/c3/c6/h2 1) -- only the spelling changed. A literal per +// variant states the number once and compiles on every SDK. +// +// Measured, not assumed: on the ESP32, n=1 and n=2 connect and n=3..N are +// refused inside i2s_new_channel() with ESP_ERR_NO_MEM, on IDF 5.5.3 and 6.1.0 +// alike. +//-------------------------------------------------------------------------- + +//========================================================================== +// +// ESP32 derivate - the first one +// +//========================================================================== + +#if CONFIG_IDF_TARGET_ESP32 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 8 +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 + +#define QUEUES_MCPWM_PCNT 6 +#define QUEUES_I2S_DIRECT 2 +#define QUEUES_RMT 8 + +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S2 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S2 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S3 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 8 +#define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 + +#define QUEUES_MCPWM_PCNT 4 +#define QUEUES_I2S_DIRECT 2 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32C3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32C3 +#define SUPPORT_ESP32_RMT_V2 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32C6 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32C6 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 2 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32H2 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32H2 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 2 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32P4 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32P4 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER CONFIG_SOC_PCNT_UNITS_PER_GROUP +#define HAVE_ESP32_RMT +#define RMT_SIZE CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 3 +#define QUEUES_RMT CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// For all unsupported ESP32 derivates +// +//========================================================================== +#else +#error "Unsupported derivate" +#endif + +// #include +#include +#include + +#ifdef NEED_MCPWM_HEADERS +#include +#include +#include +#include +#include +#include +#endif + +#ifdef NEED_PCNT_HEADERS +#include +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifdef NEED_RMT_HEADERS +#include +#include +#include +#include + +#define RMT_CHANNEL_T rmt_channel_handle_t +// #define FAS_RMT_MEM(channel) ((uint32_t *)RMTMEM.chan[channel].data32) +// PART_SIZE shall be even. +#define PART_SIZE (RMT_SIZE >> 1) + +// RMT V2 fill model: cap every RMT sub-entry (including the step high) at +// RMT_MAX_SYMBOL_TICKS. A symbol holds TWO sub-entries, so one symbol spans at +// most 2*RMT_MAX_SYMBOL_TICKS and one RMT half (PART_SIZE symbols) at most +// 2*PART_SIZE*RMT_MAX_SYMBOL_TICKS. The divisor is 2*PART_SIZE, not PART_SIZE: +// with PART_SIZE the half covered 2*RMT_BLOCK_TICKS instead of one, which +// doubled the whole buffer and left the direction-change drain (sized from the +// buffer) too short to do its job. +#define RMT_BLOCK_COUNT 2 +#define RMT_BLOCK_TICKS 8000 +#define RMT_MAX_INFLIGHT_TICKS (RMT_BLOCK_COUNT * RMT_BLOCK_TICKS) +// One RMT half holds at most RMT_BLOCK_TICKS, so the buffer's playback content +// is RMT_BUFFER_TICKS. This is what a pause must exceed to keep a direction +// change behind the pipeline: see esp32_before_pause_ticks(). +#define RMT_MAX_SYMBOL_TICKS (RMT_BLOCK_TICKS / (2 * PART_SIZE)) +#define RMT_BUFFER_TICKS (2 * PART_SIZE * 2 * RMT_MAX_SYMBOL_TICKS) +// Pause the driver injects before a direction change. It must EXCEED +// RMT_BUFFER_TICKS: the toggle runs at encode time, so a pause that fits +// in the buffer delays it not at all. One RMT_BLOCK_TICKS of margin. +#define RMT_DIR_DRAIN_TICKS (RMT_BUFFER_TICKS + RMT_BLOCK_TICKS) +#endif + +#if (ESP_IDF_VERSION_MINOR >= 5) && defined(SUPPORT_ESP32_PULSE_COUNTER) +#undef SUPPORT_ESP32_PULSE_COUNTER +#endif + +// Gated on the per-variant count above, not on SOC_I2S_NUM. Same value either +// way on this SDK -- the point is that the gate is then the one number the rest +// of the file uses, so "has I2S" and "how many I2S queues" cannot disagree. +#if QUEUES_I2S_DIRECT >= 1 +#define SUPPORT_ESP32_I2S +#endif + +// in order to avoid spikes, first set the value and then make an output +// esp32 idf5 does not like this approach => output first, then value +#define PIN_OUTPUT(pin, value) \ + { \ + pinMode(pin, OUTPUT); \ + digitalWrite(pin, (value)); \ + } + +#endif /* PD_ESP32_CONFIG_IDF5_H */ diff --git a/src/pd_esp32/pd_config_idf6.h b/src/pd_esp32/pd_config_idf6.h new file mode 100644 index 0000000..90ef751 --- /dev/null +++ b/src/pd_esp32/pd_config_idf6.h @@ -0,0 +1,245 @@ +#ifndef PD_ESP32_CONFIG_IDF6_H +#define PD_ESP32_CONFIG_IDF6_H + +//-------------------------------------------------------------------------- +// QUEUES_I2S_DIRECT -- one I2S TX channel per I2sManager +// +// What this number does: it sizes the pool. MAX_STEPPER bounds +// `_stepper[MAX_STEPPER]` (StepperMotionEngine.h) and fas_queue[NUM_QUEUES] +// (queue_init.cpp), and tryAllocateQueue() refuses past it -- and both of those +// exist under SUPPORT_DYNAMIC_ALLOCATION too, which changes the elements from +// inline queues to pointers but not the array bounds. So the constant is not +// dead weight under dynamic allocation; it is the sum's upper bound. +// +// What it does NOT do: enforce the limit. The i2s_direct path has no +// _i2s_direct_allocated counter, unlike mcpwm_pcnt and rmt which each keep +// one. It asks I2sManager::create(), which returns nullptr when +// i2s_new_channel() fails, and the hardware answers. So overstating this +// number costs RAM (two pointer arrays, 8 B per slot on ESP32) and buys +// nothing -- which is the other half of why the old 3 was wrong. +// +// Stated per variant, and NOT read from I2S_LL_INST_NUM below even though this +// SDK defines it and it is the exact number. The count is a property of the +// silicon and is identical on IDF 5 and IDF 6 -- only the symbol moved +// (SOC_I2S_NUM -> I2S_LL_INST_NUM). Reading it from the SDK buys nothing and +// costs a build that only works on one of them. +// +// Measured, not assumed: on the ESP32, n=1 and n=2 connect and n=3..N are +// refused inside i2s_new_channel() with ESP_ERR_NO_MEM, on IDF 5.5.3 and 6.1.0 +// alike. +//-------------------------------------------------------------------------- + +//========================================================================== +// +// ESP32 derivate - the first one +// +//========================================================================== + +#if CONFIG_IDF_TARGET_ESP32 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 8 +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 + +#define QUEUES_MCPWM_PCNT 6 +#define QUEUES_I2S_DIRECT 2 +#define QUEUES_RMT 8 + +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S2 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S2 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +// #define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32_RMT +#define RMT_SIZE 64 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32S3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32S3 +#define SUPPORT_ESP32_MCPWM_PCNT +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 8 +// #define HAVE_ESP32S3_PULSE_COUNTER +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 + +#define QUEUES_MCPWM_PCNT 4 +#define QUEUES_I2S_DIRECT 2 +#define QUEUES_RMT 4 +#define NEED_RMT_HEADERS +#define NEED_MCPWM_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32C3 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32C3 +#define SUPPORT_ESP32_RMT_V2 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32C6 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32C6 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32H2 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32H2 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER 4 +#define HAVE_ESP32_RMT +#define RMT_SIZE 48 +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 1 +#define QUEUES_RMT 2 +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// ESP32 derivate - ESP32P4 +// +//========================================================================== +#elif CONFIG_IDF_TARGET_ESP32P4 +#define SUPPORT_ESP32_RMT_V2 +#define SUPPORT_ESP32_PULSE_COUNTER CONFIG_SOC_PCNT_UNITS_PER_GROUP +#define HAVE_ESP32_RMT +#define RMT_SIZE CONFIG_SOC_RMT_MEM_WORDS_PER_CHANNEL +#define QUEUES_MCPWM_PCNT 0 +#define QUEUES_I2S_DIRECT 3 +#define QUEUES_RMT CONFIG_SOC_RMT_TX_CANDIDATES_PER_GROUP +#define NEED_RMT_HEADERS +#define NEED_PCNT_HEADERS + +//========================================================================== +// +// For all unsupported ESP32 derivates +// +//========================================================================== +#else +// cppcheck-suppress preprocessorErrorDirective +#error "Unsupported derivate" +#endif + +// #include +#include +#include + +#ifdef NEED_MCPWM_HEADERS +#include +#include +#include +#include +#include +#include +#include +// IDF 6.x removed SOC_MCPWM_GROUPS / SOC_MCPWM_TIMERS_PER_GROUP from soc_caps; +// the per-chip topology now lives in the MCPWM LL layer. +#define SOC_MCPWM_GROUPS MCPWM_LL_GROUP_NUM +#define SOC_MCPWM_TIMERS_PER_GROUP MCPWM_LL_TIMERS_PER_GROUP +#endif + +#ifdef NEED_PCNT_HEADERS +#include +#include +#include +#include +#include +#include +#include +#endif + +#ifdef NEED_RMT_HEADERS +#include +#include +// cppcheck-suppress syntaxError +#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(6, 0, 0) +#include +#else +#include +#endif +#include +#include + +#define RMT_CHANNEL_T rmt_channel_handle_t +// #define FAS_RMT_MEM(channel) ((uint32_t *)RMTMEM.chan[channel].data32) +// PART_SIZE shall be even. +#define PART_SIZE (RMT_SIZE >> 1) + +// RMT V2 fill model: cap every RMT sub-entry (including the step high) at +// RMT_MAX_SYMBOL_TICKS. A symbol holds TWO sub-entries, so one symbol spans at +// most 2*RMT_MAX_SYMBOL_TICKS and one RMT half (PART_SIZE symbols) at most +// 2*PART_SIZE*RMT_MAX_SYMBOL_TICKS. The divisor is 2*PART_SIZE, not PART_SIZE: +// with PART_SIZE the half covered 2*RMT_BLOCK_TICKS instead of one, which +// doubled the whole buffer and left the direction-change drain (sized from the +// buffer) too short to do its job. +#define RMT_BLOCK_COUNT 2 +#define RMT_BLOCK_TICKS 8000 +#define RMT_MAX_INFLIGHT_TICKS (RMT_BLOCK_COUNT * RMT_BLOCK_TICKS) +// One RMT half holds at most RMT_BLOCK_TICKS, so the buffer's playback content +// is RMT_BUFFER_TICKS. This is what a pause must exceed to keep a direction +// change behind the pipeline: see esp32_before_pause_ticks(). +#define RMT_MAX_SYMBOL_TICKS (RMT_BLOCK_TICKS / (2 * PART_SIZE)) +#define RMT_BUFFER_TICKS (2 * PART_SIZE * 2 * RMT_MAX_SYMBOL_TICKS) +// Pause the driver injects before a direction change. It must EXCEED +// RMT_BUFFER_TICKS: the toggle runs at encode time, so a pause that fits +// in the buffer delays it not at all. One RMT_BLOCK_TICKS of margin. +#define RMT_DIR_DRAIN_TICKS (RMT_BUFFER_TICKS + RMT_BLOCK_TICKS) +#endif + +// Gated on the per-variant count above, not on I2S_LL_INST_NUM. The two agree +// on this SDK, and the gate is then the same number QUEUES_I2S_DIRECT is +// derived from, so "has I2S" and "how many I2S queues" cannot disagree. The LL +// header is still needed below for the mux's frame timing. +#include +#if QUEUES_I2S_DIRECT >= 1 +#define SUPPORT_ESP32_I2S +#endif + +// in order to avoid spikes, first set the value and then make an output +// esp32 idf5 does not like this approach => output first, then value +#define PIN_OUTPUT(pin, value) \ + { \ + pinMode(pin, OUTPUT); \ + digitalWrite(pin, (value)); \ + } + +#endif /* PD_ESP32_CONFIG_IDF6_H */ diff --git a/src/pd_esp32/test_probe.h b/src/pd_esp32/test_probe.h new file mode 100644 index 0000000..f84c7e7 --- /dev/null +++ b/src/pd_esp32/test_probe.h @@ -0,0 +1,67 @@ +#ifndef TEST_PROBE_H +#define TEST_PROBE_H +// #define TEST_MODE +// test mode in rmt: +// code to investigate rmt module functioning + +// #define ESP32_TEST_PROBE +// #define ESP32C3_TEST_PROBE + +// in rmt: +// - TEST_PROBE_1: on startQueue and queue stop, with double toggle at +// startQueue +// - TEST_PROBE_2: end interrupt, when rmt transmission hits buffer end +// - TEST_PROBE_3: threshold interrupt, after first buffer half transmission is +// complete +// - TEST_PROBE_4: on command completed, read pointer advanced + +#ifdef ESP32_TEST_PROBE +#define TEST_PROBE_1 18 +#define TEST_PROBE_2 5 +#define TEST_PROBE_3 4 +#endif + +#ifdef ESP32C3_TEST_PROBE +#define TEST_PROBE_1 1 +#define TEST_PROBE_2 2 +#define TEST_PROBE_3 3 +#endif + +#ifdef TEST_PROBE_1 +#define PROBE_1(x) digitalWrite(TEST_PROBE_1, x) +#define PROBE_1_TOGGLE \ + pinMode(TEST_PROBE_1, OUTPUT); \ + digitalWrite(TEST_PROBE_1, digitalRead(TEST_PROBE_1) == HIGH ? LOW : HIGH) +#else +#define PROBE_1(x) +#define PROBE_1_TOGGLE +#endif +#ifdef TEST_PROBE_2 +#define PROBE_2(x) digitalWrite(TEST_PROBE_2, x) +#define PROBE_2_TOGGLE \ + pinMode(TEST_PROBE_2, OUTPUT); \ + digitalWrite(TEST_PROBE_2, digitalRead(TEST_PROBE_2) == HIGH ? LOW : HIGH) +#else +#define PROBE_2(x) +#define PROBE_2_TOGGLE +#endif +#ifdef TEST_PROBE_3 +#define PROBE_3(x) digitalWrite(TEST_PROBE_3, x) +#define PROBE_3_TOGGLE \ + pinMode(TEST_PROBE_3, OUTPUT); \ + digitalWrite(TEST_PROBE_3, digitalRead(TEST_PROBE_3) == HIGH ? LOW : HIGH) +#else +#define PROBE_3(x) +#define PROBE_3_TOGGLE +#endif +#ifdef TEST_PROBE_4 +#define PROBE_4(x) digitalWrite(TEST_PROBE_4, x) +#define PROBE_4_TOGGLE \ + pinMode(TEST_PROBE_4, OUTPUT); \ + digitalWrite(TEST_PROBE_4, digitalRead(TEST_PROBE_4) == HIGH ? LOW : HIGH) +#else +#define PROBE_4(x) +#define PROBE_4_TOGGLE +#endif + +#endif diff --git a/src/pd_pico/pd_config.h b/src/pd_pico/pd_config.h new file mode 100644 index 0000000..f71d0e3 --- /dev/null +++ b/src/pd_pico/pd_config.h @@ -0,0 +1,50 @@ +// pd_pico/pd_config.h - RP2040/RP2350 platform configuration +// +// This file defines Pico-specific constants for the StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for Pico-specific behavior +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_PICO_CONFIG_H +#define PD_PICO_CONFIG_H + +#if defined(__FREERTOS) +#include +#include +#define noop_or_wait vTaskDelay(1) +#else +// No RTOS: the Pico alarm pool calls manageSteppers() at the same rate. +#include +#define noop_or_wait sleep_us(100) +#endif + +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +#define NUM_QUEUES 4 * NUM_PIOS +#define MAX_STEPPER (NUM_QUEUES) +#define QUEUE_LEN 32 + +#define TICKS_PER_S 16000000L +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 4 + +#define DEBUG_LED_HALF_PERIOD 50 + +// One command is already in flight and the TX FIFO holds four more. Four +// old-direction pauses ahead of the new command fill those FIFO slots. The +// filler writes DIR only after the following command itself has entered the +// FIFO: that put needs one more pull, and the pull takes a pause. +#define SUPPORT_PAUSE_CMD_COUNTING +#define PICO_DIR_DRAIN_WORDS 4 +// Tick length of those four pauses. A planner that emits one pause of this +// length has queued one word; the driver still adds the missing words. +#define BEFORE_DIR_CHANGE_DELAY_TICKS(q) \ + ((uint16_t)(PICO_DIR_DRAIN_WORDS * MIN_CMD_TICKS)) + +#define SUPPORT_TASK_RATE_CHANGE + +#endif /* PD_PICO_CONFIG_H */ diff --git a/src/pd_pico/pico_pio.cpp b/src/pd_pico/pico_pio.cpp new file mode 100644 index 0000000..10722d6 --- /dev/null +++ b/src/pd_pico/pico_pio.cpp @@ -0,0 +1,209 @@ +// Analyze the following code for raspberry pi pico to create a pio program. +// Understand the register changes and cycle count of the instructions. Based on +// your understanding create a mermaid diagram with states describing the +// current cycle count and register content. The transitions shall give info +// about the executed instructions and their respecive instruction cycles. +// Instructions without jump inbetween can be intelligently combined. Any cycle +// mismatch of parallel paths shall be highlighted. In the dir parallel path two +// cycle info may be needed. Important to note,that wrap is not in use. Every +// instruction is one cycle, unless an additional delay in cycles is given. The +// code is: +#if defined(PICO_RP2040) || defined(PICO_RP2350) +#include + +#include +#include +#include + +#include "pico_pio.h" + +static stepper_pio_program program; + +static void add_step(uint instruction) { + if (program.pc < 32) { + program.code[program.pc++] = (uint16_t)instruction; + } +} + +// fifo data NEW is +// FEDCBA9876543210fedcba9876543210 = 32bits +// <- period ->| |loopcnt| +// ^-------------Count up if 1 +// Direction is not in the word. The filler writes that GPIO while the state +// machine is stalled on pull, before this word is pushed. +// +// For a pause the loop_cnt shall be 1. +// For steps, the loop_cnt = 2*steps +// The LSB of loop_cnt is the inverted output of the step pin. +// In other words, after loop_cnt decrement, the LSB shall equal step pin value. +// +// Timing. pull is T=0. One pass of label_step_loop costs +// X = 22+3*period +// A command runs loop_cnt passes after a 3-cycle preamble +// (pull, mov x osr, out null 9). +// Pause: 3 + (22+3*period) loop_cnt = 1 +// Steps: 3 + (22+3*period)*2*steps loop_cnt = 2*steps +// +// Every pass has that same length. The preamble sits in front of +// the first pass, so the gap into the first step of a command is +// 3 cycles longer than the gap between later steps. +// +// The pass overhead is 22. Direction used to be five instructions +// inside this loop (4 cycles on both forks) and the overhead was 26. +// +uint32_t pio_calc_loops(uint8_t steps, uint16_t cycles_in_16th_us, + uint16_t* adjust_80MHz) { + uint32_t cycles_in_80MHz = cycles_in_16th_us; + // should be yielding multiplication with 5 + cycles_in_80MHz *= program.sys_clk / 1000000; + cycles_in_80MHz /= 16000000 / 1000000; + if (steps > 1) { + cycles_in_80MHz *= steps; + } + cycles_in_80MHz += *adjust_80MHz; + uint16_t loop_cnt = steps == 0 ? 1 : 2 * (uint16_t)steps; // pause or steps + // Hardware time is LOOP_PREAMBLE + loop_cnt * (LOOP_OVERHEAD + 3*period). + uint32_t loops = cycles_in_80MHz - LOOP_PREAMBLE; + loops /= loop_cnt; + loops -= LOOP_OVERHEAD; + loops /= LOOP_CYCLES; + uint32_t actual_cycles = loops; + actual_cycles *= LOOP_CYCLES; + actual_cycles += LOOP_OVERHEAD; + actual_cycles *= loop_cnt; + actual_cycles += LOOP_PREAMBLE; + // calculate new adjustment value for being too fast + *adjust_80MHz = cycles_in_80MHz - actual_cycles; + return loops; +} +uint32_t pio_make_fifo_entry(bool count_up, uint8_t steps, uint32_t loops) { + // uint32_t period = stepper_calc_period(steps, cycles_16th_us); + uint16_t loop_cnt = steps == 0 ? 1 : 2 * (uint16_t)steps; // pause or steps + uint32_t entry = (loops << 10) | (count_up ? 512 : 0) | loop_cnt; + // char out[200]; + // sprintf(out, "stepper_make_fifo_entry: dir_high: %d, count_up: %d, steps: + // %d, loop_cnt: %d, entry: 0x%08X", + // dir_high, count_up, steps, loop_cnt, entry); + // Serial.println(out); + return entry; +} + +// clang-format off +stepper_pio_program *stepper_make_program() { + program.sys_clk = clock_get_hz(clk_sys); + program.pc = 0; + // We assume, that isr is cleared on sm start ! + // ISR=position=0, X=invalid, Y=invalid, OSR=invalid + uint8_t label_main_loop = program.pc; + // ISR=position, X=invalid, Y=invalid, OSR=invalid + // T=0 + // Blocking load of next command + add_step(pio_encode_pull(false, true)); + // ISR=position, X=invalid, Y=invalid, OSR=period:up:loop_cnt + // copy osr to x + add_step(pio_encode_mov(pio_x, pio_osr)); + // ISR=position, X=period:up:loop_cnt, Y=invalid, OSR=period:up:loop_cnt + // remove loop_cnt from osr (9 bits) + add_step(pio_encode_out(pio_null, 9)); + // ISR=position, X=period:up:loop_cnt, Y=invalid, OSR=period:up + // T=3 + uint8_t label_step_loop = program.pc; + // Get the UP flag into Y for position update below. + // Direction is a GPIO the filler wrote before this word was pulled. + // T=3 + N*X+0 + add_step(pio_encode_out(pio_y, 1)); + // ISR=position, X=period:up:loop_cnt, Y=up, OSR=[period] + // decrement X in order to reduce loop_cnt by 1 + add_step(pio_encode_jmp_x_dec(program.pc + 1)); + // ISR=position, X=period:up:loop_cnt-1, Y=up, OSR=[period] + // set step output to LSB of loop_cnt defined by sm_config_set_out_pins + // T=3 + N*X+2 step pin + add_step(pio_encode_mov(pio_pins, pio_x)); + // restore period:remaining_loop_cnt in osr + add_step(pio_encode_mov(pio_osr, pio_x)); + // ISR=position, X=period:up:loop_cnt-1, Y=up, OSR=period:up:loop_cnt-1 + // If step pin is one, we need to update position + add_step(pio_encode_jmp_pin(program.pc + 2)); + // Step or Pause is completed + uint8_t forward_jump_1 = program.pc; + // same cycle count as the branch for the position update + add_step(pio_encode_jmp(0) | pio_encode_delay(6)); + // + // Perform increment by one with only invert and decrement: + // position 0 1 2 .. d e f ef + // invert f e d .. 2 1 0 10 + // decrement e d c .. 1 0 f 0f + // invert 1 2 3 .. e f 0 f0 + // + // The following code section needs always 7 cycles + // Load from isr the position into x and use inverted position when counting down + add_step(pio_encode_mov(pio_x, pio_isr)); + add_step(pio_encode_jmp_not_y(program.pc + 2)); // jump if y = 0 + add_step(pio_encode_mov_not(pio_x, pio_isr)); + // ISR=position, X=position/-position, Y=up, OSR=period:up:loop_cnt-1 + add_step(pio_encode_jmp_x_dec(program.pc + 1)); // decrement x + // Store updated position in isr and invert when counting down + add_step(pio_encode_mov_not(pio_isr, pio_x)); + add_step(pio_encode_jmp_y_dec(program.pc + 2)); // jump if y != 0 + add_step(pio_encode_mov(pio_isr, pio_x)); + // ISR=position+/-1, X=[position+/-1], Y=[up+0/-1], OSR=period:up:loop_cnt-1 + // restore x from osr + add_step(pio_encode_mov(pio_x, pio_osr)); + // ISR=position+/-1, X=period:up:loop_cnt-1, Y=[up+0/-1], OSR=period:up:loop_cnt-1 + + uint8_t forward_jump_1_target = program.pc; // T=3 + N*X+12 + // ISR=position, X=period:up:loop_cnt, Y=[up], OSR=period:up:loop_cnt + // isolate period into osr (loop_cnt and the up flag, 9+1) + add_step(pio_encode_out(pio_null, 9 + 1)); + // ISR=position, X=period:up:loop_cnt, Y=[up], OSR=period + // copy period to y + add_step(pio_encode_mov(pio_y, pio_osr)); + // ISR=position, X=period:up:loop_cnt, Y=period, OSR=period + // store period/remaining_loop_cnt in osr + add_step(pio_encode_mov(pio_osr, pio_x)); + // ISR=position, X=[period:up:loop_cnt], Y=period, OSR=period:up:loop_cnt + // move position into x + add_step(pio_encode_mov(pio_x, pio_isr)); + // ISR=position, X=position, Y=period, OSR=period:up:loop_cnt + uint8_t label_period_loop = program.pc; // T=3 + N*X+16 + // output position in fifo + add_step(pio_encode_push(false, false)); + // ISR=0, X=position, Y=period, OSR=period:up:loop_cnt + // restore position in ISR + add_step(pio_encode_mov(pio_isr, pio_x)); + // ISR=position, X=position, Y=period, OSR=period:up:loop_cnt + // loop until period in y is 0 + // not taken at T=3 + N*X+22+3*period + add_step(pio_encode_jmp_y_dec(label_period_loop)); + // ISR=position, X=[position], Y=[0xFFFFFFFF], OSR=period:up:loop_cnt + // T=3 + N*X+19+3*period + // store period:up:loop_cnt in x + add_step(pio_encode_mov(pio_x, pio_osr)); + // ISR=position, X=period:up:loop_cnt, Y=0xFFFFFFFF, OSR=period:up:loop_cnt + // get loop_cnt into y (9 bits) + add_step(pio_encode_out(pio_y, 9)); + // ISR=position, X=period:up:loop_cnt, Y=loop_cnt, OSR=period:up + // if loop_cnt is zero go to main loop + // T=3 + N*X+21+3*period + add_step(pio_encode_jmp_not_y(label_main_loop)); + // Otherwise continue loop at label_step_loop via wrap around. + // Wrap costs no cycle, so the next instruction is + // T=3 + N*X+22+3*period + // The next pass of label_step_loop is also T=3 + (N+1)*X + // so X = 22+3*period + // ISR=position, X=period:up:loop_cnt, Y=[loop_cnt], OSR=period:up + + // patch forward jump address + program.code[forward_jump_1] |= forward_jump_1_target; + + program.wrap_at = program.pc - 1; + program.wrap_target = label_step_loop; + + // delay(2000); + // Serial.println("stepper_make_program: pc: " + String(program.pc) + + // ", wrap_at: " + String(program.wrap_at) + + // ", wrap_target: " + String(program.wrap_target)); + return &program; +} +// clang-format on +#endif diff --git a/src/pd_pico/pico_pio.h b/src/pd_pico/pico_pio.h new file mode 100644 index 0000000..4ba52a5 --- /dev/null +++ b/src/pd_pico/pico_pio.h @@ -0,0 +1,25 @@ +#ifndef PD_PICO_PIO_H +#define PD_PICO_PIO_H + +typedef struct pio_program_s { + uint16_t code[32]; // at max 32 instructions + uint8_t pc; + uint8_t wrap_at; + uint8_t wrap_target; + uint32_t sys_clk; +} stepper_pio_program; +stepper_pio_program* stepper_make_program(); + +// One pass is LOOP_OVERHEAD + LOOP_CYCLES*period, plus LOOP_PREAMBLE once. +// The direction pin is not in this program (the filler writes it), so a pass +// is 22 + 3*period. 22 + 3 does not divide the old 80-cycle pause evenly: +// LOOPS_FOR_1US is 18 and that idle pause is 79 cycles. +#define LOOP_OVERHEAD 22 +#define LOOP_PREAMBLE 3 +#define LOOP_CYCLES 3 +#define LOOPS_FOR_1US ((80 - LOOP_PREAMBLE - LOOP_OVERHEAD) / LOOP_CYCLES) +uint32_t pio_calc_loops(uint8_t steps, uint16_t cycles_16th_us, + uint16_t* adjust_80MHz); +uint32_t pio_make_fifo_entry(bool count_up, uint8_t steps, uint32_t loops); + +#endif // PD_PICO_PIO_H diff --git a/src/pd_pico/pico_queue.cpp b/src/pd_pico/pico_queue.cpp new file mode 100644 index 0000000..26482df --- /dev/null +++ b/src/pd_pico/pico_queue.cpp @@ -0,0 +1,489 @@ +#include "fas_queue/stepper_queue.h" + +#if defined(SUPPORT_RP_PICO) +#if defined(__FREERTOS) +#include +#include +#else +#include +#endif + +#include "hardware/gpio.h" +#include "hardware/irq.h" +#include "hardware/sync.h" +#include "pico_pio.h" + +static stepper_pio_program* program; + +static void pio0_fifo_irq_handler(); +static void pio1_fifo_irq_handler(); +#if NUM_PIOS > 2 +static void pio2_fifo_irq_handler(); +#endif + +static const irq_handler_t pio_fifo_irq_handlers[] = { + pio0_fifo_irq_handler, + pio1_fifo_irq_handler, +#if NUM_PIOS > 2 + pio2_fifo_irq_handler, +#endif +}; + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + (void)queue_num; + _step_pin = step_pin; +} + +static bool real_dir_pin(const StepperQueue* q) { + return (q->dirPin != PIN_UNDEFINED) && ((q->dirPin & PIN_EXTERNAL_FLAG) == 0); +} + +void StepperQueue::attachDirPinToStatemachine() { + if (!real_dir_pin(this)) { + return; + } + // PIN_OUTPUT already set the level. gpio_init here would clear it. + // The pin stays a CPU GPIO: the program no longer has a SET of DIR. + gpio_set_function(dirPin, GPIO_FUNC_SIO); + gpio_set_dir(dirPin, GPIO_OUT); + if (dir_gpio_valid) { + gpio_put(dirPin, dir_gpio_high); + } else { + dir_gpio_high = dirHighCountsUp; + dir_gpio_valid = true; + } +} + +void StepperQueue::setDirPinState(bool high) { + if (!real_dir_pin(this)) { + return; + } + gpio_put(dirPin, high); + dir_gpio_high = high; + dir_gpio_valid = true; +} + +// One entry per PIO block whose program loaded. `sm[]` is every state +// machine this driver claimed on that block (1 to 4). A later connect takes +// the next one. The machines stay claimed after a successful load so another +// caller cannot be told the block is empty. +struct PioBlock { + PIO pio; + uint8_t offset; + uint8_t claimed; + uint8_t used; + uint8_t sm[NUM_PIO_STATE_MACHINES]; +}; + +static PioBlock s_block[NUM_PIOS]; +static uint8_t s_block_count = 0; + +static bool pio_drives_pin(PIO pio, uint8_t pin) { + uint base = pio_get_gpio_base(pio); + return (pin >= base) && (pin < base + 32); +} + +static bool block_loaded(PIO pio) { + for (uint8_t i = 0; i < s_block_count; i++) { + if (s_block[i].pio == pio) { + return true; + } + } + return false; +} + +bool StepperQueue::claim_pio_resources(StepperMotionEngine* engine, + uint8_t step_pin, PioResources* out) { + (void)engine; + for (uint8_t i = 0; i < s_block_count; i++) { + PioBlock* b = &s_block[i]; + if (b->used < b->claimed && pio_drives_pin(b->pio, step_pin)) { + out->pio = b->pio; + out->sm = b->sm[b->used]; + out->offset = b->offset; + b->used++; + return true; + } + } + + pio_program_t pio_program = {}; + pio_program.instructions = program->code; + pio_program.length = program->pc; + // Relocatable. Origin 0 cannot sit beside the 2-word cycle counter. + pio_program.origin = -1; + pio_program.pio_version = 0; +#if PICO_PIO_VERSION > 0 + pio_program.used_gpio_ranges = 0; +#endif + + for (uint8_t pi = 0; pi < NUM_PIOS; pi++) { + PIO pio = pio_get_instance(pi); + if (block_loaded(pio) || !pio_drives_pin(pio, step_pin)) { + continue; + } + uint8_t taken[NUM_PIO_STATE_MACHINES]; + uint8_t n = 0; + for (uint sm = 0; sm < NUM_PIO_STATE_MACHINES; sm++) { + if (!pio_sm_is_claimed(pio, sm)) { + pio_sm_claim(pio, sm); + taken[n] = (uint8_t)sm; + n++; + } + } + // Nothing free here (the cycle counter may already hold one). The + // program is not written, so there is nothing to undo. + if (n == 0) { + continue; + } + int offset = pio_add_program(pio, &pio_program); + if (offset < 0) { + for (uint8_t k = 0; k < n; k++) { + pio_sm_unclaim(pio, taken[k]); + } + continue; + } + PioBlock* b = &s_block[s_block_count]; + s_block_count++; + b->pio = pio; + b->offset = (uint8_t)offset; + b->claimed = n; + b->used = 1; + for (uint8_t k = 0; k < n; k++) { + b->sm[k] = taken[k]; + } + irq_set_exclusive_handler(PIO_IRQ_NUM(pio, 0), pio_fifo_irq_handlers[pi]); + irq_set_enabled(PIO_IRQ_NUM(pio, 0), true); + out->pio = pio; + out->sm = taken[0]; + out->offset = (uint8_t)offset; + return true; + } + return false; +} + +void StepperQueue::setupSM() { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_jmp_pin(&c, _step_pin); + sm_config_set_out_pins(&c, _step_pin, 1); + // Wrap addresses are program-relative until the load offset is added. + // The loader places a relocatable program at the top of the block, not at 0. + uint offset = prog_offset; + sm_config_set_wrap(&c, (uint)program->wrap_target + offset, + (uint)program->wrap_at + offset); + + pio_sm_init(pio, sm, offset, &c); + pio_sm_set_consecutive_pindirs(pio, sm, _step_pin, 1, true); + pio_sm_set_enabled(pio, sm, true); + pio_sm_clear_fifos(pio, sm); + pio_sm_restart(pio, sm); +} + +void StepperQueue::connect() { + pio_gpio_init(pio, _step_pin); + attachDirPinToStatemachine(); +} + +void StepperQueue::disconnect() { + gpio_init(_step_pin); + if (real_dir_pin(this)) { + // Back to an input. dir_gpio_high is kept so the next connect restores it. + gpio_init(dirPin); + } +} + +bool StepperQueue::isReadyForCommands() const { return true; } + +// Put one software-queue word into the TX FIFO. One command is already in +// flight and the FIFO holds four more, so a direction level is applied only +// after this put has succeeded. A pause keeps the old level. The command +// after the four drain pauses is the one whose level differs: getting it in +// requires a pull, and that pull takes a pause. A full FIFO returns false +// with the pin unchanged. adjust_80MHz is not consumed on that refusal. +static bool push_command(StepperQueue* q) { + uint8_t rp = q->read_idx; + if (rp == q->next_write_idx) { + return false; + } + if (pio_sm_is_tx_fifo_full(q->pio, q->sm)) { + return false; + } + struct queue_entry* e = &q->entry[rp & QUEUE_LEN_MASK]; + uint8_t steps = e->steps; + bool count_up = e->countUp == 1; + uint32_t loops = pio_calc_loops(steps, e->ticks, &q->adjust_80MHz); + uint32_t word = pio_make_fifo_entry(count_up, steps, loops); + pio_sm_put(q->pio, q->sm, word); + if (real_dir_pin(q)) { + bool want_high = e->dirPinState == 1; + if (!q->dir_gpio_valid || (q->dir_gpio_high != want_high)) { + q->setDirPinState(want_high); + } + } + e->toggle_dir = 0; + rp++; + q->read_idx = rp; + return true; +} + +// Push until the software queue is empty or the TX FIFO is full. Leave the +// level IRQ enabled only while a word is still waiting: it is level +// triggered, and an empty queue would spin. +static void feed_queue(StepperQueue* q) { + while (push_command(q)) { + } + bool more = q->read_idx != q->next_write_idx; + q->_isActive = more; + pio_set_irq0_source_enabled( + q->pio, pio_get_tx_fifo_not_full_interrupt_source(q->sm), more); +} + +void StepperQueue::startQueue() { + if (_isActive) { + return; + } + uint32_t save = save_and_disable_interrupts(); + if (_isActive) { + restore_interrupts(save); + return; + } + feed_queue(this); + restore_interrupts(save); +} + +void StepperQueue::forceStop() { + uint32_t save = save_and_disable_interrupts(); + _isActive = false; + pio_set_irq0_source_enabled( + pio, pio_get_tx_fifo_not_full_interrupt_source(sm), false); + pio_sm_set_enabled(pio, sm, false); + pio_sm_clear_fifos(pio, sm); + pio_sm_restart(pio, sm); + pio_sm_set_enabled(pio, sm, true); + // pull is the first word of the loaded program, not instruction 0. + pio_sm_exec(pio, sm, pio_encode_jmp(prog_offset)); + pio_sm_exec(pio, sm, pio_encode_mov(pio_pins, pio_null)); + setDirPinState(queue_end.dir); + + read_idx = next_write_idx; + pos_offset = 0; + // The FIFO and the software queue no longer hold those pauses. + clear_pause_stats(); + restore_interrupts(save); +} + +bool StepperQueue::isRunning() const { + if (!pio_sm_is_tx_fifo_empty(pio, sm)) { + return true; + } + uint8_t pc = pio_sm_get_pc(pio, sm); + return (pc != prog_offset); +} + +int32_t StepperQueue::getCurrentStepCount() const { + bool running = isRunning(); + uint32_t pos = 0; + if (running) { + // A running queue cannot use the samples already in the RX FIFO. The PIO + // pushes the position with a *non-blocking* push, so once the FIFO is full + // the push stops updating it: a queue nobody has read since it started + // holds samples from the run's beginning -- 0 before the first step -- and + // reading one of those reports a position the stepper left long ago. + // + // Measured on RP2350, SR_30 (XSTOP ~25 % into a 4080-step fill): `POS` + // and `DONE` were 0 in 3 of 8 runs while the wire carried the full run, + // and the FIFO was full (`rxl=4`) at the read with all four entries stale. + // The read-order fix only made the empty case deterministic; it does not + // make the position current. + // + // So discard the stale samples and wait for the SM to push a current one. + // The wait is short: the period loop reaches its push every 3 cycles, and + // the longest gap before it (the step and position-update section) is tens + // of cycles. If the SM is instead stalled on a `pull` there is no + // meaningful position to report, and the move's own target is the honest + // fallback. + while (!pio_sm_is_rx_fifo_empty(pio, sm)) { + pio_sm_get(pio, sm); + } + for (uint16_t spin = 0; spin < 256; spin++) { + if (!pio_sm_is_rx_fifo_empty(pio, sm)) { + return (int32_t)pio_sm_get(pio, sm); + } + } + // Nothing new arrived, so the SM is stalled on pull (the period loop + // pushes every 3 cycles). Nothing is in the TX FIFO. The executed + // position is the queue end minus commands not yet pushed. Caught up, + // that difference is zero. + if (pio_sm_is_tx_fifo_empty(pio, sm)) { + int32_t pos = queue_end.pos; + uint8_t rp = read_idx; + uint8_t wp = next_write_idx; + while (rp != wp) { + const struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + if (e->countUp) { + pos -= (int32_t)e->steps; + } else { + pos += (int32_t)e->steps; + } + rp++; + } + return pos - pos_offset; + } + return queue_end.pos - pos_offset; + } + for (uint8_t i = 0; i <= 4; i++) { + if (pio_sm_is_rx_fifo_empty(pio, sm)) { + break; + } + pio_sm_get(pio, sm); + } + uint32_t entry = pio_make_fifo_entry(0, 0, LOOPS_FOR_1US); + pio_sm_put(pio, sm, entry); + + while (isRunning()) { + if (!pio_sm_is_tx_fifo_empty(pio, sm)) { + break; + } + } + for (uint8_t i = 0; i <= 4; i++) { + // Test before read, like the drain loop above. Reading first consumed a + // value from an empty RX FIFO and then used it, so on a stopped, drained + // queue -- the normal state after forceStop() -- the count reported was + // whatever the read returned rather than nothing. + if (pio_sm_is_rx_fifo_empty(pio, sm)) { + break; + } + pos = pio_sm_get(pio, sm); + } + return (int32_t)pos; +} + +bool StepperQueue::isValidStepPin(uint8_t step_pin) { return (step_pin < 32); } + +static uint8_t stepper_allocated_count = 0; + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + if (!isValidStepPin(step_pin)) { + return nullptr; + } + + if (stepper_allocated_count >= MAX_STEPPER) { + return nullptr; + } + + PioResources res; + if (!claim_pio_resources(engine, step_pin, &res)) { + return nullptr; + } + + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (fas_queue[i]._step_pin == PIN_UNDEFINED) { + fas_queue[i]._initVars(); + fas_queue[i].pio = res.pio; + fas_queue[i].sm = res.sm; + // _initVars clears prog_offset. The loaded pull is not at 0. + fas_queue[i].prog_offset = res.offset; + fas_queue[i].init(i, step_pin); + fas_queue[i].setupSM(); + fas_queue[i].connect(); + stepper_allocated_count++; + return &fas_queue[i]; + } + } + + return nullptr; +} + +static void pio_fifo_irq_handler(PIO pio) { + uint32_t ints = pio->ints0; + + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + StepperQueue* q = &fas_queue[i]; + if (!q->_isActive) continue; + if (q->_step_pin == PIN_UNDEFINED) { + continue; + } + if (q->pio != pio) continue; + + if (!(ints & (1u << (pis_sm0_tx_fifo_not_full + q->sm)))) continue; + + uint32_t save = save_and_disable_interrupts(); + feed_queue(q); + restore_interrupts(save); + } +} + +static void pio0_fifo_irq_handler() { pio_fifo_irq_handler(pio0); } +static void pio1_fifo_irq_handler() { pio_fifo_irq_handler(pio1); } +#if NUM_PIOS > 2 +static void pio2_fifo_irq_handler() { pio_fifo_irq_handler(pio2); } +#endif + +#if defined(__FREERTOS) +void StepperTask(void* parameter) { + StepperMotionEngine* engine = + static_cast(parameter); + while (true) { + engine->manageSteppers(); + const TickType_t delay_time = + (engine->_task_rate() + portTICK_PERIOD_MS - 1) / portTICK_PERIOD_MS; + vTaskDelay(delay_time); + } +} +#else +static bool stepper_timer_callback(repeating_timer_t* timer) { + static_cast(timer->user_data)->manageSteppers(); + return true; +} +#endif + +int32_t StepperQueue::getCurrentPosition() const { + // A stopped queue has no live hardware count worth reading. forceStop() + // restarts the SM, which clears the input shift register the PIO keeps the + // position in, so the sample path then reads 0 -- and it sets `pos_offset` to + // 0 as well, so the whole thing reports 0 even though + // forceStopAndNewPosition() just stored the real position in queue_end.pos. + // The queue's own bookkeeping already has it: for a stopped queue + // queue_end.pos *is* the position, which is what the generic + // getCurrentPosition() returns for an empty queue. + if (!isRunning()) { + return queue_end.pos; + } + return getCurrentStepCount() + pos_offset; +} + +void fas_init_engine(StepperMotionEngine* engine) { + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + fas_queue[i]._step_pin = PIN_UNDEFINED; + fas_queue[i]._isActive = true; + } + s_block_count = 0; + engine->task_rate(DELAY_MS_BASE); +#if defined(__FREERTOS) +#define STACK_SIZE 3000 +#define PRIORITY (configMAX_PRIORITIES - 1) + xTaskCreate(StepperTask, "StepperTask", STACK_SIZE, engine, PRIORITY, NULL); +#else + static repeating_timer_t stepper_timer; + add_repeating_timer_us(-(int64_t)engine->_task_rate() * 1000, + stepper_timer_callback, engine, &stepper_timer); +#endif + + program = stepper_make_program(); +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + fasEnableInterrupts(); + return rc; +} + +#endif diff --git a/src/pd_pico/pico_queue.h b/src/pd_pico/pico_queue.h new file mode 100644 index 0000000..91d0a29 --- /dev/null +++ b/src/pd_pico/pico_queue.h @@ -0,0 +1,125 @@ +#ifndef PD_PICO_QUEUE_H +#define PD_PICO_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + bool _isActive; + uint8_t _step_pin; + uint16_t adjust_80MHz; + PIO pio; + uint sm; + int32_t pos_offset; + + inline void _pd_initVars() { + _step_pin = PIN_UNDEFINED; + _isActive = false; + pos_offset = 0; + max_speed_in_ticks = 80; + prog_offset = 0; + dir_gpio_valid = false; + dir_gpio_high = false; + } + + struct PioResources { + PIO pio; + uint sm; + uint8_t offset; + }; + static bool claim_pio_resources(StepperMotionEngine* engine, + uint8_t step_pin, PioResources* out); + + bool isRunning() const; + bool isReadyForCommands() const; + void setupSM(); + int32_t getCurrentStepCount() const; + void attachDirPinToStatemachine(); + void setDirPinState(bool high); + // Program load address. Idle PC is this word (the blocking pull). + uint8_t prog_offset; + // Last level written to a GPIO direction pin, so the filler can tell a + // change from a repeat without reading the pin from the ISR. + bool dir_gpio_valid; + bool dir_gpio_high; + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + attachDirPinToStatemachine(); + } + + private: + static bool isValidStepPin(uint8_t step_pin); +}; + +#define SET_DIRECTION_PIN_STATE(q, high) (q)->setDirPinState(high) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + digitalWrite((pin), (high) ? HIGH : LOW) + +// Four old-direction pauses, then the caller enqueues the direction change. +// The pauses keep the old level. One command is in flight besides the four +// FIFO words, so the pin must not change when a pause is pushed: the command +// in flight can still be a step. The filler puts the following command into +// the FIFO and only then changes the pin. A full FIFO leaves the pin alone. +// Returns AQE_DIR_CHANGE_PAUSE_INJECTED when any pause was queued. The +// caller's command is not queued; moveTimed() returns that code and reports +// the pause ticks. The retry queues the direction change. AQE_QUEUE_FULL +// inserts nothing. A user dir-change delay is a further pause at the new +// level, in the same inject, ahead of the caller's later command. +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + uint8_t missing = 0; + if (_nr_of_pauses < PICO_DIR_DRAIN_WORDS) { + missing = (uint8_t)(PICO_DIR_DRAIN_WORDS - _nr_of_pauses); + } + bool add_delay = false; + uint16_t delay_ticks = dir_change_delay_ticks; + if (dir_change_delay_ticks != 0 && + !((cmd->steps == 0) && (cmd->ticks >= dir_change_delay_ticks))) { + add_delay = true; + if (cmd->steps == 0) { + delay_ticks = (uint16_t)(dir_change_delay_ticks - cmd->ticks); + } + delay_ticks = (uint16_t)fas_max(delay_ticks, (uint16_t)MIN_CMD_TICKS); + } + uint8_t extra = (uint8_t)(missing + (add_delay ? 1 : 0)); + // Pauses plus the caller's command. A short queue inserts nothing. + if (extra != 0 && (uint16_t)queueEntries() + extra + 1 > QUEUE_LEN) { + return AQE_QUEUE_FULL; + } + uint32_t injected = 0; + for (uint8_t i = 0; i < missing; i++) { + struct stepper_command_s pause_cmd = {.ticks = (uint16_t)MIN_CMD_TICKS, + .steps = 0, + .count_up = queue_end.count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, false); + if (res != AQE_OK) { + _injected_pause_ticks = injected; + return res; + } + injected += pause_cmd.ticks; + } + if (add_delay) { + struct stepper_command_s pause_cmd = { + .ticks = delay_ticks, .steps = 0, .count_up = cmd->count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + _injected_pause_ticks = injected; + return res; + } + injected += pause_cmd.ticks; + } + if (injected == 0) { + return AQE_OK; + } + _injected_pause_ticks = injected; + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +#endif // PD_PICO_QUEUE_H diff --git a/src/pd_sam/pd_config.h b/src/pd_sam/pd_config.h new file mode 100644 index 0000000..780827f --- /dev/null +++ b/src/pd_sam/pd_config.h @@ -0,0 +1,32 @@ +// pd_sam/pd_config.h - SAM Due platform configuration +// +// This file defines SAM-specific constants for the StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for SAM-specific behavior +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_SAM_CONFIG_H +#define PD_SAM_CONFIG_H + +#define MAX_STEPPER 6 +#define NUM_QUEUES 6 +#define QUEUE_LEN 32 + +#define TICKS_PER_S 21000000L +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 2 + +#define DEBUG_LED_HALF_PERIOD 50 + +#define noop_or_wait + +// TO BE CHECKED +#define SUPPORT_QUEUE_ENTRY_END_POS_U16 + +#define NEED_GENERIC_GET_CURRENT_POSITION + +#endif /* PD_SAM_CONFIG_H */ diff --git a/src/pd_sam/sam_queue.cpp b/src/pd_sam/sam_queue.cpp new file mode 100644 index 0000000..c28aaaa --- /dev/null +++ b/src/pd_sam/sam_queue.cpp @@ -0,0 +1,439 @@ +#include "fas_queue/stepper_queue.h" + +#if defined(ARDUINO_ARCH_SAM) +const bool enabled = false; +uint32_t junk = 0; + +inline void disconnectPWMPeripheral(Pio* port, uint8_t pin, + uint32_t channelMask); + +typedef struct _PWMCHANNELMAPPING { + uint8_t pin; + uint32_t channel; + Pio* port; + uint32_t channelMask; +} PWMCHANNELMAPPING; + +#define NUM_PWM_CHANNELS 8 +uint8_t TimerChannel_Map[NUM_PWM_CHANNELS]; + +uint8_t numChannels = 0; + +static StepperMotionEngine* fas_engine = NULL; + +#if defined(KEEP_SCORE) +volatile uint32_t totalPulsesDetected[NUM_QUEUES]; +volatile uint32_t totalSteps[NUM_QUEUES]; +inline void IncrementQueue(int queue) { totalPulsesDetected[queue]++; } +inline void AddToTotalSteps(int queue, uint32_t steps) { + totalSteps[queue] += steps; +} +#else +#define IncrementQueue(Q) +#define AddToTotalSteps(Q, N) +#endif +bool channelsUsed[8] = {false, false, false, false, false, false, false, false}; +PWMCHANNELMAPPING gChannelMap[NUM_QUEUES]; + +void TC5_Handler() { + uint32_t SR0 = TC1->TC_CHANNEL[2].TC_SR; + if (SR0 & TC_SR_CPCS) { + fas_engine->manageSteppers(); + TC1->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; + } +} + +void strobePin(uint32_t pin, uint32_t desiredChannel = 0, + uint32_t channel = 0) { + if (channel == desiredChannel) { + digitalWrite(pin, HIGH); + digitalWrite(pin, LOW); + } +} + +void PWM_Handler(void) { + uint32_t sr = PWM_INTERFACE->PWM_ISR1; + uint8_t leading_zeros; + sr = sr & 0xFF; + while ((leading_zeros = __CLZ(sr)) < 32) { + uint8_t channel = 32 - leading_zeros - 1; + uint32_t mask = (1 << channel); + sr = sr & (~mask); + uint8_t queue_num = TimerChannel_Map[channel]; + if (channelsUsed[channel] == false) continue; + StepperQueue* q = &fas_queue[queue_num]; + uint32_t t = micros(); + uint32_t timeElapsed = t - q->timePWMInterruptEnabled; + if (t < q->timePWMInterruptEnabled) { + timeElapsed = 0xFFFFFFFF - q->timePWMInterruptEnabled; + timeElapsed += t; + } + if (timeElapsed < 100) { + continue; + } + if (!q->_pauseCommanded) { + PWM_INTERFACE->PWM_IDR1 = mask; + continue; + } + PWMCHANNELMAPPING* mapping = &gChannelMap[queue_num]; + q->driver_data = static_cast(mapping); + + Pio* port = mapping->port; + + uint8_t rp = q->read_idx; + if (rp == q->next_write_idx) { + continue; + } + rp = ++q->read_idx; + const struct queue_entry* e = &q->entry[rp & QUEUE_LEN_MASK]; + if (rp == q->next_write_idx) { + q->_hasISRactive = false; + q->_pauseCommanded = false; + PWM_INTERFACE->PWM_IDR1 = mask; + PWM_INTERFACE->PWM_DIS = mask; + disconnectPWMPeripheral(port, mapping->pin, mapping->channelMask); + PWM_INTERFACE->PWM_IDR1 = mask; + q->read_idx = rp; + pinMode(mapping->pin, OUTPUT); + PIO_SetOutput(mapping->port, g_APinDescription[mapping->pin].ulPin, 0, 0, + 0); + + continue; + } + if (e->steps > 0) { + delayMicroseconds(10); + PWM_INTERFACE->PWM_CH_NUM[channel].PWM_CPRDUPD = e->ticks; + PWM_INTERFACE->PWM_IDR1 = mask; + uint32_t dwSR = port->PIO_ABSR; + port->PIO_ABSR = (g_APinDescription[mapping->pin].ulPin | dwSR); + port->PIO_ODR |= g_APinDescription[mapping->pin].ulPin; + port->PIO_PDR = g_APinDescription[mapping->pin].ulPin; + port->PIO_IER = g_APinDescription[mapping->pin].ulPin; + q->_pauseCommanded = false; + } else { + PWM_INTERFACE->PWM_CH_NUM[channel].PWM_CPRDUPD = e->ticks; + } + q->read_idx = rp; + } +} + +inline void disconnectPWMPeripheral(Pio* port, uint8_t pin, + uint32_t channelMask) { + PWM_INTERFACE->PWM_DIS = channelMask; + PIO_SetOutput(port, g_APinDescription[pin].ulPin, 0, 0, 0); +} + +inline void attachPWMPeripheral(Pio* port, uint8_t pin, uint32_t channelMask) { + PWM_INTERFACE->PWM_IDR1 = (channelMask); + uint32_t dwSR = port->PIO_ABSR; + port->PIO_ABSR = (g_APinDescription[pin].ulPin | dwSR); + port->PIO_ODR |= g_APinDescription[pin].ulPin; + port->PIO_PDR |= g_APinDescription[pin].ulPin; + port->PIO_IER |= g_APinDescription[pin].ulPin; + PWM_INTERFACE->PWM_ENA |= channelMask; +} + +#define ISRQueueName(Q) Queue##Q##ISR +#define ISRQueueNameStr(Q) "Queue" #Q "ISR" + +#define DUE_STEPPER_ISR(Q) \ + void Queue##Q##ISR() { \ + static StepperQueue* const q = &fas_queue[Q]; \ + const PWMCHANNELMAPPING* mapping = \ + static_cast(fas_queue[Q].driver_data); \ + static uint32_t channel = mapping->channel; \ + static uint32_t samPin = g_APinDescription[mapping->pin].ulPin; \ + static Pio* port = mapping->port; \ + if (!q->_hasISRactive || q->_pauseCommanded) { \ + return; \ + } \ + IncrementQueue(Q); \ + uint8_t rp = q->read_idx; \ + if (rp == q->next_write_idx) { \ + return; \ + } \ + struct queue_entry* e = &q->entry[rp & QUEUE_LEN_MASK]; \ + uint8_t s = --e->steps; \ + if (s == 0) { \ + if (e->toggle_dir) { \ + e->toggle_dir = 0; \ + *q->_dirPinPort ^= q->_dirPinMask; \ + } \ + rp++; \ + if (rp == q->next_write_idx) { \ + delayMicroseconds(10); \ + disconnectPWMPeripheral(mapping->port, mapping->pin, \ + mapping->channelMask); \ + q->_hasISRactive = false; \ + q->_connected = false; \ + q->read_idx = rp; \ + return; \ + } \ + e = &q->entry[rp & QUEUE_LEN_MASK]; \ + q->read_idx = rp; \ + if (e->steps == 0 || !e->hasSteps) { \ + delayMicroseconds(7); \ + q->_pauseCommanded = true; \ + q->timePWMInterruptEnabled = micros(); \ + PWM_INTERFACE->PWM_IER1 = mapping->channelMask; \ + port->PIO_CODR = samPin; \ + port->PIO_OER = samPin; \ + port->PIO_PER = samPin; \ + port->PIO_IDR = samPin; \ + PWM_INTERFACE->PWM_CH_NUM[channel].PWM_CPRDUPD = e->ticks; \ + return; \ + } \ + AddToTotalSteps(Q, e->steps); \ + PWM_INTERFACE->PWM_CH_NUM[channel].PWM_CPRDUPD = e->ticks; \ + if (e->toggle_dir) { \ + e->toggle_dir = 0; \ + *q->_dirPinPort ^= q->_dirPinMask; \ + delayMicroseconds(30); \ + } \ + return; \ + } \ + } + +DUE_STEPPER_ISR(0) +DUE_STEPPER_ISR(1) +DUE_STEPPER_ISR(2) +DUE_STEPPER_ISR(3) +DUE_STEPPER_ISR(4) +DUE_STEPPER_ISR(5) + +inline uint32_t pinToChannel(uint32_t pin) { + switch (pin) { + case 34: + case 67: + case 73: + case 35: + return 0; + case 17: + case 36: + case 72: + case 37: + case 42: + return 1; + case 38: + case 43: + case 63: + case 39: + return 2; + case 40: + case 64: + case 69: + case 41: + return 3; + case 9: + return 4; + case 8: + case 44: + return 5; + case 7: + case 45: + return 6; + case 6: + return 7; + } + return 0xFFFFFFFF; +} + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + _queue_num = queue_num; + driver_data = static_cast(&gChannelMap[queue_num]); + _step_pin = step_pin; + channelsUsed[pinToChannel(step_pin)] = true; + numChannels++; +#if defined(KEEP_SCORE) + totalPulsesDetected[queue_num] = 0; + totalSteps[queue_num] = 0; +#endif + gChannelMap[queue_num].pin = step_pin; + gChannelMap[queue_num].channel = pinToChannel(step_pin); + TimerChannel_Map[gChannelMap[queue_num].channel] = queue_num; + gChannelMap[queue_num].port = g_APinDescription[step_pin].pPort; + gChannelMap[queue_num].channelMask = 1 << gChannelMap[queue_num].channel; + static bool isPWMEnabled = false; + if (!isPWMEnabled) { + pmc_enable_periph_clk(PWM_INTERFACE_ID); + isPWMEnabled = true; + } + static bool isTCEnabled = false; + if (!isTCEnabled) { + pmc_enable_periph_clk(ID_TC5); + TC1->TC_CHANNEL[2].TC_CCR = 1; + TC1->TC_CHANNEL[2].TC_CMR = 0; + TC1->TC_CHANNEL[2].TC_CMR = 0x80 | 0x40; + TC1->TC_CHANNEL[2].TC_RA = 84000; + TC1->TC_CHANNEL[2].TC_RB = 84000; + TC1->TC_CHANNEL[2].TC_RC = 84000; + TC1->TC_CHANNEL[2].TC_IER = 0; + TC1->TC_CHANNEL[2].TC_IER = TC_IER_CPCS; + TC1->TC_CHANNEL[2].TC_CCR = TC_CCR_SWTRG | TC_CCR_CLKEN; + NVIC_SetPriority(TC5_IRQn, 1); + NVIC_EnableIRQ(TC5_IRQn); + } + + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + NVIC_SetPriority(PIOA_IRQn, 0); + NVIC_SetPriority(PIOB_IRQn, 0); + NVIC_SetPriority(PIOC_IRQn, 0); + NVIC_SetPriority(PIOD_IRQn, 0); + PWM_INTERFACE->PWM_IDR2 = 0x00FFFF0F; + PWM_INTERFACE->PWM_IDR1 = 0x00FFFF0F; + NVIC_EnableIRQ(PWM_IRQn); + PWM_INTERFACE->PWM_IDR2 = 0x00FFFF0F; + PWM_INTERFACE->PWM_IDR1 = 0x00FFFF0F; + + connect(); +} + +void StepperQueue::connect() { + PIO_Configure(g_APinDescription[_step_pin].pPort, + g_APinDescription[_step_pin].ulPinType, + g_APinDescription[_step_pin].ulPin, + g_APinDescription[_step_pin].ulPinConfiguration); + const PWMCHANNELMAPPING* mapping = + static_cast(driver_data); + PWMC_ConfigureChannel(PWM_INTERFACE, mapping->channel, PWM_CMR_CPRE_MCK_DIV_4, + 0, 0); + + PWM_INTERFACE->PWM_IDR2 = 0x00FFFF0F; + PWM_INTERFACE->PWM_IDR1 = 0x00FFFF0F; + PWM_INTERFACE->PWM_DIS = PWM_INTERFACE->PWM_DIS & (~mapping->channelMask); + PWMC_SetPeriod(PWM_INTERFACE, mapping->channel, 65535); + PWM_INTERFACE->PWM_DIS = PWM_INTERFACE->PWM_DIS & (~mapping->channelMask); + PWM_INTERFACE->PWM_CH_NUM[mapping->channel].PWM_CDTY = 21 * 10; + PWM_INTERFACE->PWM_DIS = PWM_INTERFACE->PWM_DIS & (~mapping->channelMask); + PWM_INTERFACE->PWM_IDR2 = 0x00FFFF0F; + PWM_INTERFACE->PWM_IDR1 = 0x00FFFF0F; + + switch (_queue_num) { + case 0: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(0), + RISING); + break; + case 1: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(1), + RISING); + break; + case 2: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(2), + RISING); + break; + case 3: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(3), + RISING); + break; + case 4: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(4), + RISING); + break; + case 5: + attachInterrupt(digitalPinToInterrupt(_step_pin), ISRQueueName(5), + RISING); + break; + } + _connected = true; + PWM_INTERFACE->PWM_IDR2 = 0x00FFFF0F; + PWM_INTERFACE->PWM_IDR1 = 0x00FFFF0F; +} + +void StepperQueue::disconnect() { + const PWMCHANNELMAPPING* mapping = + static_cast(driver_data); + PWMC_DisableChannel(PWM_INTERFACE, mapping->channel); + PWM_INTERFACE->PWM_DIS = PWM_INTERFACE->PWM_DIS & (~mapping->channelMask); + _connected = false; +} + +void StepperQueue::startQueue() { + noInterrupts(); + struct queue_entry* e = &entry[read_idx & QUEUE_LEN_MASK]; + interrupts(); + _hasISRactive = true; + + const PWMCHANNELMAPPING* mapping = + static_cast(driver_data); + + if (PWM_INTERFACE->PWM_SR & (1 << mapping->channel)) { + PWM_INTERFACE->PWM_CH_NUM[mapping->channel].PWM_CPRDUPD = e->ticks; + } else { + PWM_INTERFACE->PWM_CH_NUM[mapping->channel].PWM_CPRD = e->ticks; + } + + if (e->steps > 0 || e->hasSteps) { + attachPWMPeripheral(mapping->port, mapping->pin, mapping->channelMask); + return; + } else { + PIO_SetOutput(mapping->port, g_APinDescription[mapping->pin].ulPin, 0, 0, + 0); + mapping->port->PIO_IDR = g_APinDescription[mapping->pin].ulPin; + PWM_INTERFACE->PWM_ENA |= mapping->channelMask; + _pauseCommanded = true; + PWM_INTERFACE->PWM_IER1 = PWM_INTERFACE->PWM_IMR1 | mapping->channelMask; + return; + } +} + +void StepperQueue::forceStop() { + noInterrupts(); + read_idx = next_write_idx; + interrupts(); + const PWMCHANNELMAPPING* mapping = + static_cast(driver_data); + PWMC_DisableChannel(PWM_INTERFACE, mapping->channel); + _hasISRactive = false; +} + +bool StepperQueue::isValidStepPin(uint8_t step_pin) { + if (pinToChannel(step_pin) < 0x08) { + if (!channelsUsed[pinToChannel(step_pin)]) { + return true; + } + } + return false; +} + +static uint8_t stepper_allocated_count = 0; + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + if (!isValidStepPin(step_pin)) { + return nullptr; + } + + if (stepper_allocated_count >= MAX_STEPPER) { + return nullptr; + } + + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (fas_queue[i]._step_pin == PIN_UNDEFINED) { + fas_queue[i]._initVars(); + fas_queue[i].init(i, step_pin); + stepper_allocated_count++; + return &fas_queue[i]; + } + } + + return nullptr; +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + fasEnableInterrupts(); + return rc; +} + +void fas_init_engine(StepperMotionEngine* engine) { fas_engine = engine; } +#endif diff --git a/src/pd_sam/sam_queue.h b/src/pd_sam/sam_queue.h new file mode 100644 index 0000000..f8aecc5 --- /dev/null +++ b/src/pd_sam/sam_queue.h @@ -0,0 +1,82 @@ +#ifndef PD_SAM_QUEUE_H +#define PD_SAM_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + uint8_t _step_pin; + uint8_t _queue_num; + void* driver_data; + volatile bool _hasISRactive; + bool _connected; + volatile bool _pauseCommanded; + volatile uint32_t timePWMInterruptEnabled; + volatile uint32_t* _dirPinPort; + uint32_t _dirPinMask; + + inline void _pd_initVars() { + _step_pin = PIN_UNDEFINED; + max_speed_in_ticks = 420; + } + + inline bool isRunning() const { return _hasISRactive; } + inline bool isReadyForCommands() const { return true; } + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + if ((dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0)) { + _dirPinPort = portOutputRegister(digitalPinToPort(dir_pin)); + _dirPinMask = digitalPinToBitMask(dir_pin); + } + } + + private: + static bool isValidStepPin(uint8_t step_pin); +}; + +#define SET_DIRECTION_PIN_STATE(q, high) \ + do { \ + if ((q)->_dirPinPort != NULL) { \ + if (high) { \ + *((q)->_dirPinPort) |= (q)->_dirPinMask; \ + } else { \ + *((q)->_dirPinPort) &= ~(q)->_dirPinMask; \ + } \ + } \ + } while (0) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + digitalWrite((pin), (high) ? HIGH : LOW) + +#define AFTER_SET_DIR_PIN_DELAY_US 30 + +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + dir_change_delay_ticks = + (uint16_t)fas_max(dir_change_delay_ticks, MIN_CMD_TICKS); + if ((cmd->steps == 0) && (cmd->ticks >= dir_change_delay_ticks)) { + return AQE_OK; + } + uint16_t pause_ticks = dir_change_delay_ticks; + if (cmd->steps == 0) { + pause_ticks = dir_change_delay_ticks - cmd->ticks; + } + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(pause_ticks, MIN_CMD_TICKS), + .steps = 0, + .count_up = cmd->count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +#endif diff --git a/src/pd_samd/pd_config.h b/src/pd_samd/pd_config.h new file mode 100644 index 0000000..9f5b178 --- /dev/null +++ b/src/pd_samd/pd_config.h @@ -0,0 +1,65 @@ +// pd_samd/pd_config.h - SAMD51 platform configuration +// +// This file defines SAMD51-specific constants for the StepperMotion +// library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for SAMD51-specific behavior +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_SAMD_CONFIG_H +#define PD_SAMD_CONFIG_H + +// One stepper per TCC instance: the period register (PER) is shared by all +// channels of a TCC, so a TCC can only generate one step interval stream. +// TCC_INST_NUM comes from the CMSIS device header (3 on SAMD51G, 5 on J/N/P). +#define MAX_STEPPER (TCC_INST_NUM) +#define NUM_QUEUES (TCC_INST_NUM) +#define QUEUE_LEN 32 + +// Queue TCCs run at exactly 16 MHz from a dedicated GCLK generator (DFLL48M +// divided by 3), matching the tick rate of the AVR/ESP32/Pico ports so the +// well-tested precomputed ramp math constants apply (see ADR 0002). +// 16-bit entry ticks => max 4.096 ms per queue entry; slower step rates are +// represented by chained pause entries (upstream generic mechanism). +#define TICKS_PER_S 16000000L +// A command must span >= 200 us, so a full queue (32 entries) holds >= 6.4 ms +// of runway against the 4 ms ramp tick. +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 4 + +#define DEBUG_LED_HALF_PERIOD 50 + +#define noop_or_wait + +#define SUPPORT_QUEUE_ENTRY_END_POS_U16 + +#define NEED_GENERIC_GET_CURRENT_POSITION + +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +// The generic clock generator claimed for the 16 MHz step timebase. +// The Adafruit core startup uses generators 0-5 (CPU, 48M, 100M, XOSC32K, +// 12M, 1M-for-DPLL); 6-11 are free. Override if another library in your +// project claims GEN6. Never point this at a generator the core owns. +#ifndef FAS_SAMD_GCLK_GEN +#define FAS_SAMD_GCLK_GEN 6 +#endif + +// The plain TC instance driving the ~4 ms ramp tick (manageSteppers()). +// Override with e.g. -DFAS_SAMD_RAMP_TC=2 if your project claims TC3. +// TC0 is used by the Arduino core's tone(). +#ifndef FAS_SAMD_RAMP_TC +#define FAS_SAMD_RAMP_TC 3 +#endif + +// Step pulse high time in microseconds. 2 us satisfies all mainstream step/dir +// drivers (DRV8825 needs 1.9 us; A4988 needs ~1 us; Trinamic less). +#ifndef FAS_SAMD_PULSE_WIDTH_US +#define FAS_SAMD_PULSE_WIDTH_US 2 +#endif + +#endif /* PD_SAMD_CONFIG_H */ diff --git a/src/pd_samd/samd_queue.cpp b/src/pd_samd/samd_queue.cpp new file mode 100644 index 0000000..ef73f69 --- /dev/null +++ b/src/pd_samd/samd_queue.cpp @@ -0,0 +1,468 @@ +#include "fas_queue/stepper_queue.h" + +#if defined(SUPPORT_SAMD51) + +#include // pinPeripheral() + +// ============================================================================ +// SAMD51 pulse driver. +// +// Pipeline model (see samd_queue.h): PERBUF/CCBUF written during period k are +// latched by hardware at the k -> k+1 boundary. startQueue() primes period 1 +// in the direct registers and stages period 2 in the buffered ones; every +// overflow interrupt thereafter stages exactly one further period. +// ============================================================================ + +static StepperMotionEngine* fas_engine = NULL; + +// ISR dispatch: TCC instance index -> owning queue +static StepperQueue* queue_for_tcc[TCC_INST_NUM] = {NULL}; + +static Tcc* const tcc_instances[TCC_INST_NUM] = TCC_INSTS; + +#define PULSE_TICKS \ + ((uint16_t)((FAS_SAMD_PULSE_WIDTH_US) * (TICKS_PER_S / 1000000L))) + +// ---------------------------------------------------------------------------- +// Ramp tick: a plain TC in 16-bit MFRQ mode interrupts every ~4 ms and runs +// the (platform-independent) ramp generator to refill the command queues. +// ---------------------------------------------------------------------------- + +#define FAS_TC_CONCAT2_(n) TC##n +#define FAS_TC_CONCAT2(n) FAS_TC_CONCAT2_(n) +#define FAS_TC_HANDLER_(n) void TC##n##_Handler(void) +#define FAS_TC_HANDLER(n) FAS_TC_HANDLER_(n) +#define FAS_TC_IRQN_(n) TC##n##_IRQn +#define FAS_TC_IRQN(n) FAS_TC_IRQN_(n) +#define FAS_TC_GCLK_ID_(n) TC##n##_GCLK_ID +#define FAS_TC_GCLK_ID(n) FAS_TC_GCLK_ID_(n) + +#define RAMP_TC FAS_TC_CONCAT2(FAS_SAMD_RAMP_TC) +#define RAMP_TC_IRQN FAS_TC_IRQN(FAS_SAMD_RAMP_TC) +#define RAMP_TC_GCLK_ID FAS_TC_GCLK_ID(FAS_SAMD_RAMP_TC) + +// 120 MHz / 1024 prescaler = 117187.5 Hz; 4 ms => 469 counts +#define RAMP_TC_TOP ((uint16_t)((F_CPU / 1024) * DELAY_MS_BASE / 1000)) + +// NVIC priorities (SAMD51: 0 = highest, 7 = lowest). Step staging must +// preempt the (long-running) ramp calculation. +#define STEP_ISR_PRIORITY 1 +#define RAMP_ISR_PRIORITY 6 + +FAS_TC_HANDLER(FAS_SAMD_RAMP_TC) { + RAMP_TC->COUNT16.INTFLAG.reg = TC_INTFLAG_OVF; + if (fas_engine != NULL) { + fas_engine->manageSteppers(); + } +} + +static void ramp_tc_init() { + GCLK->PCHCTRL[RAMP_TC_GCLK_ID].reg = + GCLK_PCHCTRL_GEN_GCLK0_Val | (1 << GCLK_PCHCTRL_CHEN_Pos); + + Tc* tc = RAMP_TC; + tc->COUNT16.CTRLA.bit.ENABLE = 0; + while (tc->COUNT16.SYNCBUSY.bit.ENABLE) { + } + tc->COUNT16.CTRLA.bit.SWRST = 1; + while (tc->COUNT16.SYNCBUSY.bit.SWRST) { + } + tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16 | TC_CTRLA_PRESCALER_DIV1024 | + TC_CTRLA_PRESCSYNC_PRESC; + // Match frequency mode: CC0 is the period + tc->COUNT16.WAVE.reg = TC_WAVE_WAVEGEN_MFRQ; + tc->COUNT16.CC[0].reg = RAMP_TC_TOP; + while (tc->COUNT16.SYNCBUSY.bit.CC0) { + } + tc->COUNT16.INTENSET.reg = TC_INTENSET_OVF; + NVIC_SetPriority(RAMP_TC_IRQN, RAMP_ISR_PRIORITY); + NVIC_EnableIRQ(RAMP_TC_IRQN); + tc->COUNT16.CTRLA.bit.ENABLE = 1; + while (tc->COUNT16.SYNCBUSY.bit.ENABLE) { + } +} + +void fas_init_engine(StepperMotionEngine* engine) { + fas_engine = engine; + ramp_tc_init(); +} + +// ---------------------------------------------------------------------------- +// Step generation +// ---------------------------------------------------------------------------- + +// Consume one step (or one pause period) from the queue and stage it into the +// buffered registers. Returns false if the queue is empty. +// Called from the OVF ISR and (for period 2) from startQueue(). +bool StepperQueue::stageNextPeriod() { + uint8_t rp = read_idx; + if (rp == next_write_idx) { + return false; + } + struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + // First period of this entry: apply the direction change. The staged + // period starts one full period later, so the driver's DIR setup time + // is amply satisfied. (The step edge of the *current* period fired just + // before this ISR; DIR hold time after an edge is ~20 ns on common + // drivers, far below our interrupt latency.) + e->toggle_dir = 0; + if (_dirPinPortGrp != NULL) { + _dirPinPortGrp->OUTTGL.reg = _dirPinMask; + } + } + _tcc->PERBUF.reg = e->ticks; + _tcc->CCBUF[_tcc_channel].reg = e->hasSteps ? _pulse_ticks : 0; + if (e->steps > 1) { + e->steps--; + } else { + read_idx = rp + 1; + } + return true; +} + +void StepperQueue::handleOverflow() { + if ((_tcc->INTFLAG.reg & TCC_INTFLAG_OVF) == 0) { + // Spurious: startQueue() cleared the flag after the NVIC had already + // pended this interrupt. The new run's priming must not be consumed. + return; + } + _tcc->INTFLAG.reg = TCC_INTFLAG_OVF; + if (stageNextPeriod()) { + _noMoreCommands = false; + return; + } + if (_noMoreCommands) { + // Grace period elapsed without new commands: stop. + // STOP drives the output to the DRVCTRL non-recoverable state (low). + // Do not overlap a CTRLB command still syncing (e.g. the RETRIGGER of a + // startQueue() whose first period was very short). + while (_tcc->SYNCBUSY.bit.CTRLB) { + } + _tcc->CTRLBSET.reg = TCC_CTRLBSET_CMD_STOP; + _noMoreCommands = false; + _isRunning = false; + } else { + // Queue drained. Stage one dead period (no pulse, current interval) so a + // command arriving within it continues the stream seamlessly. + _noMoreCommands = true; + _tcc->CCBUF[_tcc_channel].reg = 0; + } +} + +#define SAMD_TCC_ISR(n) \ + void TCC##n##_0_Handler(void) { \ + StepperQueue* q = queue_for_tcc[n]; \ + if (q != NULL) { \ + q->handleOverflow(); \ + } else { \ + TCC##n->INTFLAG.reg = TCC_INTFLAG_MASK; \ + } \ + } + +#ifdef TCC0 +SAMD_TCC_ISR(0) +#endif +#ifdef TCC1 +SAMD_TCC_ISR(1) +#endif +#ifdef TCC2 +SAMD_TCC_ISR(2) +#endif +#ifdef TCC3 +SAMD_TCC_ISR(3) +#endif +#ifdef TCC4 +SAMD_TCC_ISR(4) +#endif + +// ---------------------------------------------------------------------------- +// Queue protocol +// ---------------------------------------------------------------------------- + +// Map a step pin to its TCC instance/channel via the variant's pin table. +// Returns false if the pin has no TCC mux. +static bool step_pin_to_tcc(uint8_t step_pin, uint8_t* tcc_num, + uint8_t* channel) { + if (step_pin >= PINS_COUNT) { + return false; + } + const PinDescription& pd = g_APinDescription[step_pin]; + if ((pd.ulPinAttribute & + (PIN_ATTR_PWM_E | PIN_ATTR_PWM_F | PIN_ATTR_PWM_G)) == 0) { + return false; + } + uint32_t num = GetTCNumber(pd.ulPWMChannel); + if (num >= TCC_INST_NUM) { + return false; // pin is on a TC, not a TCC + } + *tcc_num = (uint8_t)num; + *channel = GetTCChannelNumber(pd.ulPWMChannel); + return true; +} + +bool StepperQueue::isValidStepPin(uint8_t step_pin) { + uint8_t tcc_num, channel; + if (!step_pin_to_tcc(step_pin, &tcc_num, &channel)) { + return false; + } + return queue_for_tcc[tcc_num] == NULL; +} + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + uint8_t tcc_num = 0, channel = 0; + step_pin_to_tcc(step_pin, &tcc_num, &channel); // validated by caller + _queue_num = queue_num; + _step_pin = step_pin; + _tcc_num = tcc_num; + _tcc_channel = channel; + _tcc = tcc_instances[tcc_num]; + _pulse_ticks = PULSE_TICKS; + + // Step pin low as plain GPIO first; connect() muxes it to the TCC. + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + + // 16 MHz step timebase: dedicated GCLK generator from DFLL48M / 3 + // (see ADR 0002). Idempotent, shared by all queue TCCs. + GCLK->GENCTRL[FAS_SAMD_GCLK_GEN].reg = + GCLK_GENCTRL_SRC_DFLL | GCLK_GENCTRL_DIV(3) | GCLK_GENCTRL_GENEN; + while (GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL(FAS_SAMD_GCLK_GEN)) { + } + + // GCLK_CLKCTRL_IDs is the core's instance -> PCHCTRL index table + // (the channel is shared between sibling instances, e.g. TCC0/TCC1). + GCLK->PCHCTRL[GCLK_CLKCTRL_IDs[tcc_num]].reg = + GCLK_PCHCTRL_GEN(FAS_SAMD_GCLK_GEN) | (1 << GCLK_PCHCTRL_CHEN_Pos); + + Tcc* tcc = _tcc; + tcc->CTRLA.bit.ENABLE = 0; + while (tcc->SYNCBUSY.bit.ENABLE) { + } + tcc->CTRLA.bit.SWRST = 1; + while (tcc->SYNCBUSY.bit.SWRST) { + } + tcc->CTRLA.reg = TCC_CTRLA_PRESCALER_DIV1 | TCC_CTRLA_PRESCSYNC_PRESC; + tcc->WAVE.reg = TCC_WAVE_WAVEGEN_NPWM; + while (tcc->SYNCBUSY.bit.WAVE) { + } + // When stopped, actively drive the step output low (NRE=1, NRV=0). + tcc->DRVCTRL.reg |= TCC_DRVCTRL_NRE0 << _tcc_channel; + // Prime CC=0 (no pulse) before enabling, so enabling cannot emit a glitch. + tcc->PER.reg = 0xffff; + while (tcc->SYNCBUSY.bit.PER) { + } + tcc->CC[_tcc_channel].reg = 0; + while (tcc->SYNCBUSY.reg & (TCC_SYNCBUSY_CC0 << _tcc_channel)) { + } + tcc->CTRLA.bit.ENABLE = 1; + while (tcc->SYNCBUSY.bit.ENABLE) { + } + // Enabling starts the counter: stop it immediately. Output goes low (NRE). + tcc->CTRLBSET.reg = TCC_CTRLBSET_CMD_STOP; + while (tcc->SYNCBUSY.bit.CTRLB) { + } + + queue_for_tcc[tcc_num] = this; + + IRQn_Type irqn; + switch (tcc_num) { +#ifdef TCC0 + case 0: + irqn = TCC0_0_IRQn; + break; +#endif +#ifdef TCC1 + case 1: + irqn = TCC1_0_IRQn; + break; +#endif +#ifdef TCC2 + case 2: + irqn = TCC2_0_IRQn; + break; +#endif +#ifdef TCC3 + case 3: + irqn = TCC3_0_IRQn; + break; +#endif +#ifdef TCC4 + case 4: + irqn = TCC4_0_IRQn; + break; +#endif + default: + return; + } + tcc->INTENSET.reg = TCC_INTENSET_OVF; + NVIC_SetPriority(irqn, STEP_ISR_PRIORITY); + NVIC_EnableIRQ(irqn); + + connect(); +} + +void StepperQueue::connect() { + const PinDescription& pd = g_APinDescription[_step_pin]; + if (pd.ulPinAttribute & PIN_ATTR_PWM_E) { + pinPeripheral(_step_pin, PIO_TIMER); + } else if (pd.ulPinAttribute & PIN_ATTR_PWM_F) { + pinPeripheral(_step_pin, PIO_TIMER_ALT); + } else if (pd.ulPinAttribute & PIN_ATTR_PWM_G) { + pinPeripheral(_step_pin, PIO_TCC_PDEC); + } + _connected = true; +} + +void StepperQueue::disconnect() { + // pinMode() clears PMUXEN: the pin reverts to a plain low GPIO output. + digitalWrite(_step_pin, LOW); + pinMode(_step_pin, OUTPUT); + _connected = false; +} + +void StepperQueue::startQueue() { + if (_isRunning) { + return; + } + Tcc* tcc = _tcc; + + uint8_t rp = read_idx; + if (rp == next_write_idx) { + return; // nothing to do (addQueueEntry guards this already) + } + + _isRunning = true; + _noMoreCommands = false; + + // The TCC is stopped here (init(), forceStop() or the OVF ISR stopped it), + // but three remnants of the previous run must be cleared before priming: + // + // 1. A latched-but-unserviced overflow (possible when a stop lands just + // after TOP). Left pending, the ISR would fire mid-priming and consume + // the entries staged below. Clear it first; handleOverflow() also + // guards against a spurious NVIC-pended call. + tcc->INTFLAG.reg = TCC_INTFLAG_OVF; + // 2. The STOP command itself may still be crossing into the 16 MHz TCC + // clock domain. Register write-syncs must not overlap it. + while (tcc->SYNCBUSY.bit.CTRLB) { + } + // 3. Stale buffered values (an abrupt stop strands a staged PERBUF/CCBUF + // that never latched). Silicon erratum DS80000748 2.20.1: clearing + // STATUS.PERBUFV/CCBUFVx releases SYNCBUSY *before* the buffer register + // is actually restored, so a PER/CC write issued then collides with the + // still-running restore and SYNCBUSY.PER locks permanently (observed as + // a random hang below). Workaround per errata: clear the flags twice. + // The restore itself reports through SYNCBUSY.PER/CCx (per the erratum's + // TC wording), so drain those channels too before the direct writes. + uint32_t bufv_mask = + TCC_STATUS_PERBUFV | (TCC_STATUS_CCBUFV0 << _tcc_channel); + uint32_t sync_mask = TCC_SYNCBUSY_STATUS | TCC_SYNCBUSY_PER | + (TCC_SYNCBUSY_CC0 << _tcc_channel); + tcc->STATUS.reg = bufv_mask; + while (tcc->SYNCBUSY.reg & sync_mask) { + } + tcc->STATUS.reg = bufv_mask; + while (tcc->SYNCBUSY.reg & sync_mask) { + } + + // Prime period 1 in the direct registers. + struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + e->toggle_dir = 0; + if (_dirPinPortGrp != NULL) { + _dirPinPortGrp->OUTTGL.reg = _dirPinMask; + delayMicroseconds(AFTER_SET_DIR_PIN_DELAY_US); + } + } + tcc->PER.reg = e->ticks; + while (tcc->SYNCBUSY.bit.PER) { + } + tcc->CC[_tcc_channel].reg = e->hasSteps ? _pulse_ticks : 0; + while (tcc->SYNCBUSY.reg & (TCC_SYNCBUSY_CC0 << _tcc_channel)) { + } + if (e->steps > 1) { + e->steps--; + } else { + read_idx = rp + 1; + } + + // Stage period 2 in the buffered registers (latched at the first period + // boundary). If the queue only held one period, insert the dead period. + if (!stageNextPeriod()) { + _noMoreCommands = true; + tcc->CCBUF[_tcc_channel].reg = 0; + } + + // (INTFLAG.OVF was cleared at entry; the counter has been stopped since, + // so no overflow can have latched in between.) + // Retrigger: counter restarts at zero, the step edge (if CC > 0) fires now. + // Scope-verified on SAMD51: RETRIGGER is not an update condition, so the + // buffered period-2 values staged above are NOT latched here; they take + // effect at the first period boundary as the pipeline model requires + // (an acceleration ramp from standstill shows the long first interval, + // not a duplicated second interval). + tcc->CTRLBSET.reg = TCC_CTRLBSET_CMD_RETRIGGER; +} + +void StepperQueue::forceStop() { + // Called from application context while the TCC may be running at speed. + // The OVF ISR stages PERBUF/CCBUF at every period boundary, and those + // writes synchronize through the shared SYNCBUSY.PER/CCx channels. A STOP + // command issued while one of those syncs is in flight can wedge the sync + // bridge (same hardware as erratum DS80000748 2.20.1), leaving SYNCBUSY.PER + // stuck and hanging the next startQueue(). So: block the ISR, drain every + // in-flight sync, then stop. + noInterrupts(); + while (_tcc->SYNCBUSY.reg & + (TCC_SYNCBUSY_CTRLB | TCC_SYNCBUSY_STATUS | TCC_SYNCBUSY_PER | + (TCC_SYNCBUSY_CC0 << _tcc_channel))) { + } + _tcc->CTRLBSET.reg = TCC_CTRLBSET_CMD_STOP; + while (_tcc->SYNCBUSY.bit.CTRLB) { + } + // A stop landing just after TOP may leave a latched overflow. Drop it so + // the stale NVIC pend hits handleOverflow()'s spurious-interrupt guard. + _tcc->INTFLAG.reg = TCC_INTFLAG_OVF; + _isRunning = false; + _noMoreCommands = false; + // empty the queue + read_idx = next_write_idx; + interrupts(); +} + +static uint8_t stepper_allocated_count = 0; + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + // isValidStepPin() also rejects pins whose TCC is already claimed + // (queue_for_tcc occupancy), so queues are simply handed out in order. + if (!isValidStepPin(step_pin)) { + return nullptr; + } + if (stepper_allocated_count >= NUM_QUEUES) { + return nullptr; + } + StepperQueue* q = &fas_queue[stepper_allocated_count]; + q->_initVars(); + q->init(stepper_allocated_count, step_pin); + stepper_allocated_count++; + return q; +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + fasEnableInterrupts(); + return rc; +} + +#endif // SUPPORT_SAMD51 diff --git a/src/pd_samd/samd_queue.h b/src/pd_samd/samd_queue.h new file mode 100644 index 0000000..d4f6aed --- /dev/null +++ b/src/pd_samd/samd_queue.h @@ -0,0 +1,113 @@ +#ifndef PD_SAMD_QUEUE_H +#define PD_SAMD_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +// SAMD51 pulse driver. +// +// Each stepper claims the TCC instance its step pin muxes to (discovered via +// g_APinDescription). The TCC runs in normal PWM: PER = step interval in +// ticks, CC[channel] = pulse width (CC = 0 => pause period, output low). +// The overflow interrupt fires once per step and stages the following period +// into the buffered registers (PERBUF/CCBUF), which the hardware latches at +// the next period boundary. Pulse edges are therefore hardware-timed and +// immune to interrupt latency; only the staging has a full period of slack. +// +// See docs/adr/0001-tcc-npwm-per-step-isr.md for the design decision. + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + Tcc* _tcc; + uint8_t _tcc_num; // TCC instance index (also ISR dispatch key) + uint8_t _tcc_channel; // CC channel / WO index of the step pin + uint8_t _queue_num; + uint8_t _step_pin; + uint16_t _pulse_ticks; // step pulse high time in ticks + volatile bool _isRunning; + // One dead (pulse-less) period is inserted after the queue drains before + // the TCC is stopped, so a command arriving late is picked up seamlessly. + volatile bool _noMoreCommands; + bool _connected; + + PortGroup* _dirPinPortGrp; + uint32_t _dirPinMask; + + inline void _pd_initVars() { + _tcc = NULL; + _step_pin = PIN_UNDEFINED; + _dirPinPortGrp = NULL; + _dirPinMask = 0; + _isRunning = false; + _noMoreCommands = false; + _connected = false; + // 10 us/step = 100k steps/s default ceiling; the per-step ISR costs + // ~1 us, so this keeps interrupt load below ~10% per running stepper. + max_speed_in_ticks = TICKS_PER_S / 100000; + } + + inline bool isRunning() const { return _isRunning; } + inline bool isReadyForCommands() const { return true; } + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + if ((dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0)) { + const PinDescription& pd = g_APinDescription[dir_pin]; + _dirPinPortGrp = &PORT->Group[pd.ulPort]; + _dirPinMask = (1ul << pd.ulPin); + } + } + + // ISR-side helpers (defined in samd_queue.cpp) + bool stageNextPeriod(); + void handleOverflow(); + + private: + static bool isValidStepPin(uint8_t step_pin); +}; + +#define SET_DIRECTION_PIN_STATE(q, high) \ + do { \ + if ((q)->_dirPinPortGrp != NULL) { \ + if (high) { \ + (q)->_dirPinPortGrp->OUTSET.reg = (q)->_dirPinMask; \ + } else { \ + (q)->_dirPinPortGrp->OUTCLR.reg = (q)->_dirPinMask; \ + } \ + } \ + } while (0) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + digitalWrite((pin), (high) ? HIGH : LOW) + +#define AFTER_SET_DIR_PIN_DELAY_US 30 + +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + if (dir_change_delay_ticks == 0) { + return AQE_OK; + } + if ((cmd->steps == 0) && (cmd->ticks >= dir_change_delay_ticks)) { + return AQE_OK; + } + uint16_t pause_ticks = dir_change_delay_ticks; + if (cmd->steps == 0) { + pause_ticks = dir_change_delay_ticks - cmd->ticks; + } + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(pause_ticks, MIN_CMD_TICKS), + .steps = 0, + .count_up = cmd->count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +#endif // PD_SAMD_QUEUE_H diff --git a/src/pd_teensy/pd_config.h b/src/pd_teensy/pd_config.h new file mode 100644 index 0000000..310229f --- /dev/null +++ b/src/pd_teensy/pd_config.h @@ -0,0 +1,75 @@ +// pd_teensy/pd_config.h - Teensy 4.x (i.MX RT1062) platform configuration +// +// Experimental backend. The QuadTimer sequence and the SAMD51 queue +// protocol inform this implementation. See NOTICE for attribution. +// +// This file defines Teensy-4.x-specific constants for the +// StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for Teensy-4.x-specific behavior +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_TEENSY_CONFIG_H +#define PD_TEENSY_CONFIG_H + +// i.MX RT1062 has 4 QuadTimer (TMR) modules, 4 channels each. Unlike +// SAMD/SAM, the step pin is NOT muxed to the timer's own output - the ISR +// toggles it directly via digitalWriteFast() (see pd_teensy/teensy_queue.cpp), +// so any digital pin can be used, same as ESP32. +#define MAX_STEPPER 16 +#define NUM_QUEUES 16 +#define QUEUE_LEN 32 + +// The QuadTimer modules are clocked from the IPG peripheral clock, which +// Teensyduino configures to 150 MHz regardless of F_CPU/overclocking. +// FAS_TEENSY_TMR_PRESCALE (0..7) +// divides that by 2^prescale (see teensy_queue.cpp) to get the tick rate: +// 0 -> 150 MHz (65535 ticks =~ 0.44 ms per queue entry) +// 4 -> 9.375 MHz (default: =~ 7 ms per queue entry) +// 7 -> 1.17 MHz (=~ 56 ms per queue entry) +// A smaller prescale gives finer timing resolution (matters most for very +// high step rates and for how smoothly the ramp can approximate its curve), +// at the cost of a shorter max duration per single queue entry - still +// comfortably above the 4 ms ramp tick down to prescale 2 (37.5 MHz, +// =~1.75 ms/entry). Untested: worth sweeping this while measuring actual +// achievable step rate/jitter on a scope, see pd_teensy warning above. +#ifndef FAS_TEENSY_TMR_PRESCALE +#define FAS_TEENSY_TMR_PRESCALE 4 +#endif +#if (FAS_TEENSY_TMR_PRESCALE < 0) || (FAS_TEENSY_TMR_PRESCALE > 7) +#error "FAS_TEENSY_TMR_PRESCALE must be 0..7" +#endif +// +// This does not match the two precomputed fast-path constants in +// RampCalculator.h (16 MHz / 21 MHz), so the generic runtime log2 timer +// frequency path is used automatically (see SUPPORT_LOG2_TIMER_FREQ_VARIABLES +// in RampCalculator.h/RampControl.cpp) - no extra setup needed here. +#define TICKS_PER_S (150000000L >> FAS_TEENSY_TMR_PRESCALE) +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 4 + +#define DEBUG_LED_HALF_PERIOD 50 + +#define noop_or_wait + +#define SUPPORT_QUEUE_ENTRY_END_POS_U16 + +#define NEED_GENERIC_GET_CURRENT_POSITION + +// Lets the application raise/lower the per-stepper max speed ceiling set +// below via setAbsoluteSpeedLimit() - useful here since the default ceiling +// is an untested guess (see teensy_queue.cpp _pd_initVars()). +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +// Step pulse high time in microseconds. Kept above DRV8825's 1.9 us +// minimum with margin for the tick-rounding below (2 us truncates to +// under 1.9 us at 9.375 MHz ticks). +#ifndef FAS_TEENSY_PULSE_WIDTH_US +#define FAS_TEENSY_PULSE_WIDTH_US 3 +#endif + +#endif /* PD_TEENSY_CONFIG_H */ diff --git a/src/pd_teensy/teensy_queue.cpp b/src/pd_teensy/teensy_queue.cpp new file mode 100644 index 0000000..e9fecfb --- /dev/null +++ b/src/pd_teensy/teensy_queue.cpp @@ -0,0 +1,303 @@ +#include "fas_queue/stepper_queue.h" + +#if defined(SUPPORT_TEENSY4) + +// ============================================================================ +// Experimental Teensy 4.x (i.MX RT1062) pulse driver. +// +// The register sequence alternates COMP1 between the pulse width and the +// remaining period. See NOTICE for the timer and GPIO code attribution. +// +// Queue/ramp protocol integration (grace period before stopping, dead +// period so a late-arriving command is picked up seamlessly, one +// StepperMotionEngine::manageSteppers() tick every ~4 ms) mirrors this +// library's own pd_samd backend, adapted from SAMD51's fully-hardware +// double-buffered PWM to this driver's ISR-per-edge model (closer to how +// the AVR backend uses a hardware compare match to time each edge). +// ============================================================================ + +// FAS_TEENSY_TMR_PRESCALE (0..7, default 4) lives in pd_config.h - it also +// derives TICKS_PER_S, so the two must always move together. + +#define PULSE_TICKS \ + ((uint16_t)(((uint32_t)(FAS_TEENSY_PULSE_WIDTH_US) * TICKS_PER_S) / 1000000L)) + +// NVIC priority, 0 (highest) .. 255 (lowest), in steps of 16 (Cortex-M7 on +// i.MX RT1062 implements 4 priority bits; values not a multiple of 16 get +// rounded down by the hardware, so stick to multiples of 16 to keep the +// numbers meaningful). Step edges must preempt the ~4 ms ramp tick (queue +// refill), or a slow/late refill under load could show up as timing jitter +// on the step pin. Untested: worth confirming on a scope under load. +#ifndef FAS_TEENSY_STEP_ISR_PRIORITY +#define FAS_TEENSY_STEP_ISR_PRIORITY 16 +#endif +#ifndef FAS_TEENSY_RAMP_TICK_PRIORITY +#define FAS_TEENSY_RAMP_TICK_PRIORITY 208 +#endif + +static StepperMotionEngine* fas_engine = NULL; +static IntervalTimer fas_ramp_timer; + +static void fas_ramp_tick_isr() { + if (fas_engine != NULL) { + fas_engine->manageSteppers(); + } +} + +void fas_init_engine(StepperMotionEngine* engine) { + fas_engine = engine; + fas_ramp_timer.begin(fas_ramp_tick_isr, (unsigned int)(DELAY_MS_BASE * 1000)); + fas_ramp_timer.priority(FAS_TEENSY_RAMP_TICK_PRIORITY); +} + +// ---------------------------------------------------------------------------- +// Step generation +// ---------------------------------------------------------------------------- + +// ISR dispatch: [module][channel] -> owning queue +static StepperQueue* queue_for_channel[4][4] = {{NULL}}; + +static IMXRT_TMR_t* const tmr_module_regs[4] = { + (IMXRT_TMR_t*)IMXRT_TMR1_ADDRESS, (IMXRT_TMR_t*)IMXRT_TMR2_ADDRESS, + (IMXRT_TMR_t*)IMXRT_TMR3_ADDRESS, (IMXRT_TMR_t*)IMXRT_TMR4_ADDRESS}; + +static const IRQ_NUMBER_t tmr_module_irq[4] = {IRQ_QTIMER1, IRQ_QTIMER2, + IRQ_QTIMER3, IRQ_QTIMER4}; + +// Consume the queue entry at read_idx `rp` (queue must be non-empty): +// apply a pending direction change, then schedule the immediate next +// compare event - either the rising edge of a step pulse (scheduled +// _pulse_ticks out) or the full duration of a pause entry. +void StepperQueue::primeFromQueue(uint8_t rp) { + struct queue_entry* e = &entry[rp & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + e->toggle_dir = 0; + digitalWriteFast(dirPin, e->dirPinState); + } + if (e->hasSteps) { + _remaining_ticks = (e->ticks > _pulse_ticks) + ? (uint16_t)(e->ticks - _pulse_ticks) + : (uint16_t)1; + digitalWriteFast(_step_pin, HIGH); + _pulse_phase = true; + _regs->COMP1 = _pulse_ticks; + _regs->CMPLD1 = _pulse_ticks; + } else { + _pulse_phase = false; + _regs->COMP1 = e->ticks; + _regs->CMPLD1 = e->ticks; + } + if (e->steps > 1) { + e->steps--; + } else { + read_idx = rp + 1; + } +} + +// Called once per QuadTimer compare-match event for this channel (the +// TCF1 flag itself is cleared by the module-level dispatcher below). +// +// State machine (mirrors TeensyStep4's TmrTimer::ISR, adapted for this +// library's repeat-count queue entries): +// _pulse_phase == true: pin is HIGH. This event is exactly _pulse_ticks +// after the rising edge: lower the pin and schedule the remainder of +// the step period (computed by primeFromQueue() when the pulse started). +// _pulse_phase == false: pin is LOW. This event marks the end of the +// previous inter-step gap (or the very start of a run): look at the +// queue and schedule what's next. +void StepperQueue::handleCompareMatch() { + if (_pulse_phase) { + digitalWriteFast(_step_pin, LOW); + _pulse_phase = false; + _regs->COMP1 = _remaining_ticks; + _regs->CMPLD1 = _remaining_ticks; + return; + } + + uint8_t rp = read_idx; + if (rp == next_write_idx) { + if (_noMoreCommands) { + // Grace period elapsed without new commands: stop. + _regs->CTRL = 0; + _isRunning = false; + _noMoreCommands = false; + return; + } + // Queue drained: stage one dead period (no pulse) so a command + // arriving within it continues the stream seamlessly. + _noMoreCommands = true; + _regs->COMP1 = MIN_CMD_TICKS; + _regs->CMPLD1 = MIN_CMD_TICKS; + return; + } + _noMoreCommands = false; + primeFromQueue(rp); +} + +// The Cortex-M7 has a write buffer, so clearing CSCTRL.TCF1 is not +// guaranteed to have reached the peripheral by the time the ISR returns - +// without a barrier, the NVIC can see the interrupt as still pending and +// the flag-clear can appear to "not have happened" from the next ISR's +// point of view, corrupting the edge-toggle state machine. TeensyStep4's +// TMRModule::ISR() carries the same barrier with the same reasoning. +#define TEENSY_TMR_ISR(N) \ + static void teensyTmrIsr##N() { \ + for (uint8_t ch = 0; ch < 4; ch++) { \ + StepperQueue* q = queue_for_channel[N][ch]; \ + if (q == NULL) { \ + continue; \ + } \ + IMXRT_TMR_CH_t* regs = &tmr_module_regs[N]->CH[ch]; \ + if (regs->CSCTRL & TMR_CSCTRL_TCF1) { \ + regs->CSCTRL &= ~TMR_CSCTRL_TCF1; \ + q->handleCompareMatch(); \ + } \ + } \ + asm volatile("dsb"); \ + } + +TEENSY_TMR_ISR(0) +TEENSY_TMR_ISR(1) +TEENSY_TMR_ISR(2) +TEENSY_TMR_ISR(3) + +static void (*const tmr_module_isr[4])() = {teensyTmrIsr0, teensyTmrIsr1, + teensyTmrIsr2, teensyTmrIsr3}; + +// ---------------------------------------------------------------------------- +// Queue protocol +// ---------------------------------------------------------------------------- + +bool StepperQueue::isValidStepPin(uint8_t step_pin) { + if (step_pin == PIN_UNDEFINED) { + return false; + } + for (uint8_t i = 0; i < NUM_QUEUES; i++) { + if (fas_queue[i]._step_pin == step_pin) { + return false; // already claimed by another queue + } + } + return true; +} + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + digitalWrite(step_pin, LOW); + pinMode(step_pin, OUTPUT); + + _queue_num = queue_num; + _step_pin = step_pin; + _pulse_ticks = PULSE_TICKS; + _pulse_phase = false; + + uint8_t mod = queue_num >> 2; // 0..3 -> TMR1..TMR4 + uint8_t ch = queue_num & 0x03; // 0..3 + _tmr_module = mod; + _tmr_channel = ch; + _regs = &tmr_module_regs[mod]->CH[ch]; + + _regs->CTRL = 0; + _regs->CNTR = 0; + _regs->LOAD = 0; + _regs->COMP1 = _pulse_ticks; + _regs->CMPLD1 = _pulse_ticks; + _regs->CSCTRL = 0; + _regs->SCTRL = 0; + + queue_for_channel[mod][ch] = this; + + static bool module_isr_attached[4] = {false, false, false, false}; + if (!module_isr_attached[mod]) { + attachInterruptVector(tmr_module_irq[mod], tmr_module_isr[mod]); + NVIC_SET_PRIORITY(tmr_module_irq[mod], FAS_TEENSY_STEP_ISR_PRIORITY); + NVIC_ENABLE_IRQ(tmr_module_irq[mod]); + module_isr_attached[mod] = true; + } + + connect(); +} + +void StepperQueue::connect() { + pinMode(_step_pin, OUTPUT); + digitalWriteFast(_step_pin, LOW); + _connected = true; +} + +void StepperQueue::disconnect() { + digitalWriteFast(_step_pin, LOW); + _connected = false; +} + +void StepperQueue::startQueue() { + if (_isRunning) { + return; + } + uint8_t rp = read_idx; + if (rp == next_write_idx) { + return; // nothing to do (addQueueEntry guards this already) + } + + _isRunning = true; + _noMoreCommands = false; + + _regs->CTRL = 0; + _regs->CNTR = 0; + _regs->LOAD = 0; + _regs->CSCTRL = 0; + _regs->SCTRL = 0; + + primeFromQueue(rp); + + _regs->CSCTRL |= TMR_CSCTRL_TCF1EN; + _regs->CTRL = TMR_CTRL_CM(1) | + TMR_CTRL_PCS(0b1000 | FAS_TEENSY_TMR_PRESCALE) | + TMR_CTRL_LENGTH; +} + +void StepperQueue::forceStop() { + noInterrupts(); + _regs->CTRL = 0; + _isRunning = false; + _noMoreCommands = false; + _pulse_phase = false; + digitalWriteFast(_step_pin, LOW); + read_idx = next_write_idx; + interrupts(); +} + +static uint8_t stepper_allocated_count = 0; + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + if (!isValidStepPin(step_pin)) { + return nullptr; + } + if (stepper_allocated_count >= MAX_STEPPER) { + return nullptr; + } + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if (fas_queue[i]._step_pin == PIN_UNDEFINED) { + fas_queue[i]._initVars(); + fas_queue[i].init(i, step_pin); + stepper_allocated_count++; + return &fas_queue[i]; + } + } + return nullptr; +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + fasEnableInterrupts(); + return rc; +} + +#endif // SUPPORT_TEENSY4 diff --git a/src/pd_teensy/teensy_queue.h b/src/pd_teensy/teensy_queue.h new file mode 100644 index 0000000..9d5ac1e --- /dev/null +++ b/src/pd_teensy/teensy_queue.h @@ -0,0 +1,110 @@ +#ifndef PD_TEENSY_QUEUE_H +#define PD_TEENSY_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" +#include "imxrt.h" + +// Teensy 4.x (i.MX RT1062) pulse driver. EXPERIMENTAL - tested on real +// hardware, but pulse width/edge timing not yet scope-verified - see +// pd_config.h for context and pd_teensy/teensy_queue.cpp for the +// implementation and its references. +// +// Each stepper claims one channel of one of the 4 QuadTimer (TMR) modules. +// Unlike SAMD/SAM, the channel's own output pin is not used: the step (and, +// on direction changes, the dir) pin is toggled directly in the ISR via +// digitalWriteFast(), so any digital pin works, not just specific muxed +// ones. The QuadTimer channel is only used to time the two ISR calls a step +// needs (rising edge, then falling edge after the pulse width) precisely, +// the same way this library's AVR backend uses a hardware compare match to +// time each edge instead of busy-waiting. + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + IMXRT_TMR_CH_t* _regs; // this channel's QuadTimer register block + uint8_t _tmr_module; // 0..3 (TMR1..TMR4) - ISR dispatch key + uint8_t _tmr_channel; // 0..3 within the module + uint8_t _queue_num; + uint8_t _step_pin; + uint16_t _pulse_ticks; // step pulse high time, in ticks + uint16_t _remaining_ticks; // ticks from falling edge to next rising edge + bool _pulse_phase; // true: pin is HIGH, next event lowers it + volatile bool _isRunning; + // One dead (pulse-less) period is inserted after the queue drains before + // the timer is stopped, so a command arriving late is picked up seamlessly + // (same grace-period idea as the SAMD backend). + volatile bool _noMoreCommands; + bool _connected; + + inline void _pd_initVars() { + _regs = NULL; + _step_pin = PIN_UNDEFINED; + _pulse_phase = false; + _isRunning = false; + _noMoreCommands = false; + _connected = false; + // UNVERIFIED placeholder ceiling (50k steps/s <=> 20us/step). Each step + // costs two ISR calls here (rising + falling edge), unlike SAMD's one. + // Measure on real hardware and adjust via setAbsoluteSpeedLimit() if + // needed - see SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING in pd_config.h. + max_speed_in_ticks = TICKS_PER_S / 50000; + } + + inline bool isRunning() const { return _isRunning; } + inline bool isReadyForCommands() const { return true; } + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + if ((dir_pin != PIN_UNDEFINED) && ((dir_pin & PIN_EXTERNAL_FLAG) == 0)) { + pinMode(dir_pin, OUTPUT); + } + } + + // ISR-side helpers (defined in teensy_queue.cpp) + void primeFromQueue(uint8_t rp); + void handleCompareMatch(); + + private: + static bool isValidStepPin(uint8_t step_pin); +}; + +// digitalWriteFast() accepts a runtime pin number on Teensyduino (it falls +// back to a fast table lookup, not a compile-time-only fast path) - the +// same call TeensyStep4 uses from its own step/dir ISRs. +#define SET_DIRECTION_PIN_STATE(q, high) \ + digitalWriteFast((q)->dirPin, (high) ? HIGH : LOW) + +#define SET_ENABLE_PIN_STATE(q, pin, high) \ + digitalWrite((pin), (high) ? HIGH : LOW) + +#define AFTER_SET_DIR_PIN_DELAY_US 5 + +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + if (dir_change_delay_ticks == 0) { + return AQE_OK; + } + if ((cmd->steps == 0) && (cmd->ticks >= dir_change_delay_ticks)) { + return AQE_OK; + } + uint16_t pause_ticks = dir_change_delay_ticks; + if (cmd->steps == 0) { + pause_ticks = dir_change_delay_ticks - cmd->ticks; + } + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(pause_ticks, MIN_CMD_TICKS), + .steps = 0, + .count_up = cmd->count_up}; + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +#endif // PD_TEENSY_QUEUE_H diff --git a/src/pd_test/dir_change_pause.h b/src/pd_test/dir_change_pause.h new file mode 100644 index 0000000..9af9696 --- /dev/null +++ b/src/pd_test/dir_change_pause.h @@ -0,0 +1,82 @@ +#ifndef PD_TEST_DIR_CHANGE_PAUSE_H +#define PD_TEST_DIR_CHANGE_PAUSE_H + +// Default implementation of the StepperQueue::addDirChangePauseToQueue() +// protocol method (declared in fas_queue/protocol.h) for the pd_test platform. +// Real pulse drivers (AVR, SAM, SAMD, PICO, ESP32) provide their own, platform +// specific implementation in their _queue.h and do not use this default. +// +// The before/after delays come from the BEFORE/AFTER_DIR_CHANGE_DELAY_TICKS +// macros in test_queue.h. The pauses are inserted through +// StepperQueue::addQueueEntry() so queue_end / toggle_dir stay on the same path +// as every other command. Only applies to step commands (steps > 0); a pure +// pause command (steps == 0) returns AQE_OK. At most ONE pause is inserted per +// call, matching the real pulse drivers: the before-pause first, and the +// after-pause on a subsequent call. The caller retries on +// AqeResultCode::DirChangePauseInjected until AQE_OK is returned. Returns +// AqeResultCode::DirChangePauseInjected if a pause was inserted, AQE_OK if none +// was needed, or AQE_DIR_PIN_IS_BUSY on a busy queue (checked before +// enqueuing). +// +// The pd_test target #defines inline away (see fas_arch/test_pc.h), so this +// out-of-line definition would emit a real symbol in every TU that includes it. +// It must therefore be included in exactly one TU per linked binary (the +// StepperISR_test.cpp driver TU for the LIB_O binaries, and test_24.cpp for its +// own self-contained binary), never from a shared header such as test_queue.h. +inline AqeResultCode StepperQueue::addDirChangePauseToQueue( + const struct stepper_command_s* cmd, bool start, + uint16_t dir_change_delay_ticks) { + if (cmd->steps == 0) { + return AQE_OK; + } + uint16_t before_delay = 0; +#if defined(BEFORE_DIR_CHANGE_DELAY_TICKS) + before_delay = BEFORE_DIR_CHANGE_DELAY_TICKS(this); +#endif + uint16_t after_delay = dir_change_delay_ticks; +#if defined(AFTER_DIR_CHANGE_DELAY_TICKS) + after_delay = fas_max(AFTER_DIR_CHANGE_DELAY_TICKS(this), after_delay); +#endif +#if defined(SUPPORT_PAUSE_CMD_COUNTING) + if (_nr_of_pauses != 0 && _last_pause_ticks >= before_delay) { + before_delay = 0; + } +#endif + uint8_t commands_needed = 1; + if (before_delay > 0) { + commands_needed++; + } + if (after_delay > 0) { + commands_needed++; + } + if (queueEntries() >= QUEUE_LEN - commands_needed) { + return AQE_DIR_PIN_IS_BUSY; + } + if (before_delay > 0) { + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(before_delay, MIN_CMD_TICKS), + .steps = 0, + .count_up = queue_end.count_up}; // delay with old value + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + if (after_delay > 0) { + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)fas_max(after_delay, MIN_CMD_TICKS), + .steps = 0, + .count_up = cmd->count_up}; // delay with new value + AqeResultCode res = addQueueEntry(&pause_cmd, start); + if (res != AQE_OK) { + return res; + } + _injected_pause_ticks = pause_cmd.ticks; + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + return AQE_OK; +} + +#endif // PD_TEST_DIR_CHANGE_PAUSE_H diff --git a/src/pd_test/pd_config.h b/src/pd_test/pd_config.h new file mode 100644 index 0000000..85f98ab --- /dev/null +++ b/src/pd_test/pd_config.h @@ -0,0 +1,60 @@ +// pd_test/pd_config.h - Test platform configuration +// +// This file defines test-specific constants for the StepperMotion library: +// - Queue topology (MAX_STEPPER, NUM_QUEUES, QUEUE_LEN) +// - Timing constants (TICKS_PER_S, MIN_CMD_TICKS, delays) +// - Feature flags for PC-based testing +// +// Included by fas_arch/common.h during platform dispatch. + +#ifndef PD_TEST_CONFIG_H +#define PD_TEST_CONFIG_H + +#define MAX_STEPPER 2 +#define NUM_QUEUES 2 +#define QUEUE_LEN 16 +#ifndef PART_SIZE +#define PART_SIZE debug_part_size +#endif + +// RMT V2 fill model constants (test fallback). +// A symbol holds TWO sub-entries, so one RMT half (PART_SIZE symbols) spans at +// most 2*PART_SIZE*RMT_MAX_SYMBOL_TICKS. The divisor is 2*PART_SIZE: with +// PART_SIZE the half covered 2*RMT_BLOCK_TICKS, doubling the buffer and +// shortening the direction-change drain below the buffer's playback content. +#ifndef RMT_BLOCK_COUNT +#define RMT_BLOCK_COUNT 2 +#endif +#ifndef RMT_BLOCK_TICKS +#define RMT_BLOCK_TICKS 8000 +#endif +#ifndef RMT_MAX_INFLIGHT_TICKS +#define RMT_MAX_INFLIGHT_TICKS (RMT_BLOCK_COUNT * RMT_BLOCK_TICKS) +#endif +#ifndef RMT_MAX_SYMBOL_TICKS +#define RMT_MAX_SYMBOL_TICKS (RMT_BLOCK_TICKS / (2 * PART_SIZE)) +#endif +#ifndef RMT_BUFFER_TICKS +#define RMT_BUFFER_TICKS (2 * PART_SIZE * 2 * RMT_MAX_SYMBOL_TICKS) +// Pause the driver injects before a direction change. It must EXCEED +// RMT_BUFFER_TICKS: the toggle runs at encode time, so a pause that fits +// in the buffer delays it not at all. One RMT_BLOCK_TICKS of margin. +#define RMT_DIR_DRAIN_TICKS (RMT_BUFFER_TICKS + RMT_BLOCK_TICKS) +#endif + +#define TICKS_PER_S 16000000L +#define MIN_CMD_TICKS (TICKS_PER_S / 5000) +#define MIN_DIR_DELAY_US (MIN_CMD_TICKS / (TICKS_PER_S / 1000000)) +#define MAX_DIR_DELAY_US (65535 / (TICKS_PER_S / 1000000)) +#define DELAY_MS_BASE 1 +#define SUPPORT_UNSAFE_ABS_SPEED_LIMIT_SETTING + +#define noop_or_wait + +#define SUPPORT_QUEUE_ENTRY_END_POS_U16 + +#define SUPPORT_PAUSE_CMD_COUNTING + +#define NEED_GENERIC_GET_CURRENT_POSITION + +#endif /* PD_TEST_CONFIG_H */ diff --git a/src/pd_test/test_queue.h b/src/pd_test/test_queue.h new file mode 100644 index 0000000..0d4321b --- /dev/null +++ b/src/pd_test/test_queue.h @@ -0,0 +1,52 @@ +#ifndef PD_TEST_QUEUE_H +#define PD_TEST_QUEUE_H + +#include "StepperMotion.h" +#include "fas_queue/base.h" + +#define fas_queue_A fas_queue[0] +#define fas_queue_B fas_queue[1] + +class StepperQueue : public StepperQueueBase { + public: +#include "../fas_queue/protocol.h" + + volatile bool _isRunning; + uint16_t _before_dir_change_delay_ticks; + uint16_t _after_dir_change_delay_ticks; + + inline void _pd_initVars() { + max_speed_in_ticks = 80; + _before_dir_change_delay_ticks = 0; + _after_dir_change_delay_ticks = 0; +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + channel = RMT_CHANNEL_T(); + _rmtStopped = true; +#endif + } + + inline bool isReadyForCommands() const { return true; } + inline bool isRunning() const { return _isRunning; } +#if (defined(SUPPORT_ESP32_RMT_V1) || defined(SUPPORT_ESP32_RMT_V2)) + RMT_CHANNEL_T channel; + bool _rmtStopped; + // Mirrors the real class (esp32_queue.h), where this is defined per chip in + // StepperISR_rmt_v1_esp32*.cpp. A test that compiles the V1 fill path supplies + // the definition itself, the way it already supplies inject_fill_interrupt. + void stop_rmt(bool both); +#endif + + void setDirPin(uint8_t dir_pin, bool _dirHighCountsUp) { + dirPin = dir_pin; + dirHighCountsUp = _dirHighCountsUp; + } +}; + +#define SET_DIRECTION_PIN_STATE(q, high) ((void)0) + +#define SET_ENABLE_PIN_STATE(q, pin, high) ((void)0) + +#define BEFORE_DIR_CHANGE_DELAY_TICKS(q) ((q)->_before_dir_change_delay_ticks) +#define AFTER_DIR_CHANGE_DELAY_TICKS(q) ((q)->_after_dir_change_delay_ticks) + +#endif // PD_TEST_QUEUE_H diff --git a/tests/host/CMakeLists.txt b/tests/host/CMakeLists.txt new file mode 100644 index 0000000..4653e5d --- /dev/null +++ b/tests/host/CMakeLists.txt @@ -0,0 +1,34 @@ +set(motion_src "${PROJECT_SOURCE_DIR}/src") + +add_library(stepper_motion_host STATIC + "${motion_src}/StepperMotion.cpp" + "${motion_src}/StepperMotionEngine.cpp" + "${motion_src}/fas_queue/queue_add_entry.cpp" + "${motion_src}/fas_queue/queue_get_position.cpp" + "${motion_src}/fas_queue/queue_init.cpp" + "${motion_src}/fas_queue/queue_utils.cpp" + "${motion_src}/fas_ramp/RampCalculator.cpp" + "${motion_src}/fas_ramp/RampControl.cpp" + "${motion_src}/fas_ramp/RampGenerator.cpp" + "${motion_src}/log2/Log2Representation.cpp" + StepperISR_test.cpp +) +target_include_directories(stepper_motion_host PRIVATE "${motion_src}") +target_compile_definitions(stepper_motion_host PRIVATE TEST F_CPU=16000000) +target_compile_features(stepper_motion_host PRIVATE cxx_std_17) + +file(GLOB test_sources CONFIGURE_DEPENDS "test_[0-9][0-9].cpp") +list(APPEND test_sources log2_test.cpp rmc_test.cpp) + +foreach(source IN LISTS test_sources) + get_filename_component(test_name "${source}" NAME_WE) + add_executable("${test_name}" "${source}") + target_include_directories("${test_name}" PRIVATE "${motion_src}") + target_compile_definitions("${test_name}" PRIVATE TEST F_CPU=16000000) + target_compile_features("${test_name}" PRIVATE cxx_std_17) + target_compile_options("${test_name}" PRIVATE -UNDEBUG) + if(NOT test_name MATCHES "^test_(21|22|24|25|28)$") + target_link_libraries("${test_name}" PRIVATE stepper_motion_host) + endif() + add_test(NAME "${test_name}" COMMAND "${test_name}") +endforeach() diff --git a/tests/host/RampChecker.h b/tests/host/RampChecker.h new file mode 100644 index 0000000..375cd7e --- /dev/null +++ b/tests/host/RampChecker.h @@ -0,0 +1,142 @@ +#include +#include + +class RampChecker { + public: + uint64_t total_ticks; + uint32_t last_dt; + uint32_t min_dt; + bool increase_ok; + bool flat_ok; + bool decrease_ok; + bool first; + bool dir_high; + bool reversing_allowed; + uint32_t accelerate_till; + uint32_t coast_till; + uint32_t time_coasting; + uint32_t pos; + uint32_t ticks_since_last_step; + float avg_accel; + FILE* gp_file; + char filename[100]; + + void next_ramp() { + increase_ok = true; + decrease_ok = false; + last_dt = ~0; + min_dt = ~0; + first = true; + dir_high = true; + coast_till = 0; + time_coasting = 0; + accelerate_till = 0; + reversing_allowed = false; + } + RampChecker() { + ticks_since_last_step = 0; + avg_accel = 0; + gp_file = NULL; + total_ticks = 0; + pos = 0; + next_ramp(); + } + void start_plot(char* fname) { + int n = strlen(fname) - 8; // remove .gnuplot + strncpy(filename, fname, n); + filename[n] = 0; + gp_file = fopen(fname, "w"); + fprintf(gp_file, "$data <steps; + if (steps == 0) { + // Just a pause + if (ticks_since_last_step <= 0xffff0000) { + ticks_since_last_step += e->ticks; + } + total_ticks += e->ticks; + printf("process pause %d => %u\n", e->ticks, ticks_since_last_step); + return; + } + if (e->toggle_dir) { + assert(reversing_allowed); + dir_high = !dir_high; + increase_ok = true; + last_dt = ~0; + decrease_ok = false; + } + if (dir_high) { + pos += steps; + } else { + pos -= steps; + } + uint32_t curr_dt = ticks_since_last_step; + total_ticks += steps * e->ticks; + if (!first) { + min_dt = min(min_dt, curr_dt); + } + float accel = 0; + if (last_dt != ~0) { + accel = (16000000.0 / float(curr_dt) - 16000000.0 / float(last_dt)) / + (1.0 / 16000000.0 * float(steps * curr_dt)); + avg_accel += (accel - avg_accel) / (steps * 20); + } + printf( + "process command in ramp checker @%.6fs: steps = %d last = %u current " + "= %u " + " min_dt " + "= %u accel=%.6f inc=%s dec=%s\n", + total_ticks / 16000000.0, steps, last_dt, curr_dt, min_dt, accel, + increase_ok ? "ALLOW" : "NO", decrease_ok ? "ALLOW" : "NO"); + + if (gp_file != NULL) { + fprintf(gp_file, "%.6f %.2f %d %d %f\n", total_ticks / 16000000.0, + 16000000.0 / last_dt, last_dt, pos, avg_accel); + } + + assert(first || (steps * curr_dt > 0)); + + if (last_dt > curr_dt) { + assert(increase_ok); + accelerate_till = total_ticks; + decrease_ok = true; + } else if (last_dt < curr_dt) { + if (increase_ok) { + coast_till = total_ticks - curr_dt; + } + assert(decrease_ok); + increase_ok = false; + } else { + time_coasting += steps * curr_dt; + } + + if (!first) { + last_dt = curr_dt; + } + + ticks_since_last_step = e->ticks; + first = false; + } +}; diff --git a/tests/host/StepperISR_test.cpp b/tests/host/StepperISR_test.cpp new file mode 100644 index 0000000..6c83db7 --- /dev/null +++ b/tests/host/StepperISR_test.cpp @@ -0,0 +1,47 @@ +#include "fas_queue/stepper_queue.h" + +#include "pd_test/dir_change_pause.h" + +#include "StepperMotion.h" + +static uint8_t stepper_allocated_mask = 0; + +void fas_init_engine(StepperMotionEngine* engine) {} + +void fas_reset_stepper_allocation() { stepper_allocated_mask = 0; } + +void StepperQueue::init(uint8_t queue_num, uint8_t step_pin) { + (void)queue_num; + (void)step_pin; +} +void StepperQueue::startQueue() { _isRunning = true; } +void StepperQueue::forceStop() {} +void StepperQueue::connect() {} +void StepperQueue::disconnect() {} + +StepperQueue* StepperQueue::tryAllocateQueue(StepperMotionEngine* engine, + uint8_t step_pin) { + (void)engine; + for (uint8_t i = 0; i < MAX_STEPPER; i++) { + if ((stepper_allocated_mask & (1 << i)) == 0) { + fas_queue[i].init(i, step_pin); + stepper_allocated_mask |= (1 << i); + return &fas_queue[i]; + } + } + return nullptr; +} + +AqeResultCode StepperMotionEngine::synchronizedStart( + StepperMotion** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + fasDisableInterrupts(); + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + fasEnableInterrupts(); + return rc; +} diff --git a/tests/host/i2s_test_common.h b/tests/host/i2s_test_common.h new file mode 100644 index 0000000..5c744d8 --- /dev/null +++ b/tests/host/i2s_test_common.h @@ -0,0 +1,169 @@ +#ifndef I2S_TEST_COMMON_H +#define I2S_TEST_COMMON_H + +#include +#include +#include +#include +#include + +#define SUPPORT_ESP32_I2S +#include "pd_esp32/i2s_constants.h" + +static int test_passed = 0; +static int test_failed = 0; + +static void test_result(const char* name, bool passed) { + if (passed) { + printf("PASS: %s\n", name); + test_passed++; + } else { + printf("FAIL: %s\n", name); + test_failed++; + } +} + +// --------------------------------------------------------------------------- +// Mock I2sManager with callback support +// --------------------------------------------------------------------------- + +typedef void (*i2s_dma_callback_t)(uint8_t block); + +class I2sManager { + public: + static I2sManager& instance(); + + bool init(int, int, int) { + _initialized = true; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(_bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + _dma_block = 0; + _callback_count = 0; + return true; + } + + bool isInitialized() const { return _initialized; } + + uint8_t* blockBuf(uint8_t block) { return _bufs[block % I2S_BLOCK_COUNT]; } + + uint8_t dmaBlock() const { return _dma_block; } + + void registerDmaCallback(i2s_dma_callback_t cb) { _dma_callback = cb; } + + void dmaConsumeBlock() { + if (_dma_callback) { + _dma_callback(_dma_block); + _callback_count++; + } + _dma_block = (_dma_block + 1) % I2S_BLOCK_COUNT; + } + + uint32_t callbackCount() const { return _callback_count; } + + I2sManager() + : _initialized(false), + _dma_block(0), + _callback_count(0), + _dma_callback(nullptr) { + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(_bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + } + + private: + bool _initialized; + uint8_t _bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + uint8_t _dma_block; + uint32_t _callback_count; + i2s_dma_callback_t _dma_callback; +}; + +static I2sManager s_i2s_mgr; +inline I2sManager& I2sManager::instance() { return s_i2s_mgr; } + +// --------------------------------------------------------------------------- +// Bit stream analyzer - receives tick-level pin states +// --------------------------------------------------------------------------- + +class BitStreamAnalyzer { + public: + uint32_t rising_edges; + uint32_t falling_edges; + uint32_t total_ticks; + uint32_t last_rising_tick; + uint32_t last_falling_tick; + bool last_level; + uint8_t ticks_per_bit; + + void reset() { + rising_edges = 0; + falling_edges = 0; + total_ticks = 0; + last_rising_tick = 0; + last_falling_tick = 0; + last_level = false; + } + + void processBit(bool level) { + for (uint8_t i = 0; i < ticks_per_bit; i++) { + processTick(level); + } + } + + void processTick(bool level) { + if (level && !last_level) { + last_rising_tick = total_ticks; + rising_edges++; + } else if (!level && last_level) { + last_falling_tick = total_ticks; + falling_edges++; + } + last_level = level; + total_ticks++; + } + + uint32_t pulseCount() const { return rising_edges; } +}; + +static BitStreamAnalyzer s_analyzer; + +// --------------------------------------------------------------------------- +// Pulse analysis helpers +// --------------------------------------------------------------------------- + +static uint32_t countPulsesInBuffer(const uint8_t* buf) { + uint32_t count = 0; + bool last_bit = false; + uint16_t total_bits = I2S_FRAMES_PER_BLOCK * I2S_BITS_PER_FRAME; + for (uint16_t bit_pos = 0; bit_pos < total_bits; bit_pos++) { + uint16_t byte_pos = (bit_pos >> 3) ^ 1; + uint8_t bit_offset = bit_pos & 7; + bool current = (buf[byte_pos] >> (7 - bit_offset)) & 1; + if (current && !last_bit) { + count++; + } + last_bit = current; + } + return count; +} + +static uint32_t detectPulsePositions(const uint8_t* buf, uint32_t buf_size, + uint32_t* positions) { + uint32_t count = 0; + uint8_t prev_bit = 0; + uint32_t total_bits = buf_size * 8; + + for (uint32_t bit_pos = 0; bit_pos < total_bits; bit_pos++) { + uint32_t byte_pos = (bit_pos >> 3) ^ 1; + uint8_t bit_offset = bit_pos & 7; + uint8_t curr_bit = (buf[byte_pos] >> (7 - bit_offset)) & 1; + if (curr_bit == 1 && prev_bit == 0) { + positions[count++] = bit_pos; + } + prev_bit = curr_bit; + } + return count; +} + +#endif // I2S_TEST_COMMON_H diff --git a/tests/host/log2_test.cpp b/tests/host/log2_test.cpp new file mode 100644 index 0000000..b1405d5 --- /dev/null +++ b/tests/host/log2_test.cpp @@ -0,0 +1,29 @@ +#include + +#include "log2/Log2Representation.h" + +// +// This file can be renamed to a .ino and compiled as sketch to be run on the +// target e.g. arduino nano. +// + +#include +#include +#include +#define trace puts +#define xprintf printf +#define test(x, msg) \ + if (!(x)) { \ + puts(msg); \ + assert(false); \ + }; + +unsigned int error_cnt = 0; + +#include "test_03.h" + +int main() { + if (perform_test()) { + xprintf("TEST_03 PASSED\n"); + } +} diff --git a/tests/host/naxis_html_dump.h b/tests/host/naxis_html_dump.h new file mode 100644 index 0000000..a06f875 --- /dev/null +++ b/tests/host/naxis_html_dump.h @@ -0,0 +1,166 @@ +// naxis_html_dump.h — optional HTML trace viewer for the FasNAxis PC tests. +// +// Test-only. Not included from src/FasNAxis.h; pulled in by test_26.cpp only +// under -DFAS_NAXIS_TRACE. It copies the checked-in static page +// tests/host/viewer_template.html (a

 placeholder) and
+// embeds the same (t, x, y) samples the gnuplot file already carries, writing
+// tests/host/tests/out/.html. Without the macro the file is not
+// created and src/FasNAxis.h has no viewer include.
+//
+// Protocol:
+//   NaxisHtmlDump html("F5", "FasNAxis F5 square 1600 Linear");
+//   for (sample s in run) html.row(s.t, s.x, s.y);
+//   html.finish();
+//
+#ifndef NAXIS_HTML_DUMP_H
+#define NAXIS_HTML_DUMP_H
+
+#include 
+#include 
+#include 
+
+// Root of the viewer assets for a manual trace run from the repository root.
+#ifndef NAXIS_HTML_ROOT
+#define NAXIS_HTML_ROOT "tests/host"
+#endif
+
+class NaxisHtmlDump {
+ public:
+  NaxisHtmlDump(const char* fixture, const char* title)
+      : template_buf(NULL),
+        rows_buf(NULL),
+        rows_len(0),
+        n_rows(0),
+        open(false) {
+    snprintf(out_path, sizeof(out_path), "%s/tests/out/%s.html",
+             NAXIS_HTML_ROOT, fixture);
+    snprintf(title_buf, sizeof(title_buf), "%s", title);
+    rows_buf = (char*)malloc(NAXIS_HTML_MAX_BYTES);
+    if (rows_buf == NULL) {
+      return;
+    }
+    char tpl_path[256];
+    snprintf(tpl_path, sizeof(tpl_path), "%s/viewer_template.html",
+             NAXIS_HTML_ROOT);
+    FILE* tpl = fopen(tpl_path, "r");
+    if (tpl == NULL) {
+      return;
+    }
+    size_t len = 0;
+    fseek(tpl, 0, SEEK_END);
+    len = ftell(tpl);
+    fseek(tpl, 0, SEEK_SET);
+    if (len > 0) {
+      template_buf = (char*)malloc(len + 1);
+      if (template_buf != NULL) {
+        size_t got = fread(template_buf, 1, len, tpl);
+        template_buf[got] = 0;
+        open = true;
+      }
+    }
+    fclose(tpl);
+  }
+
+  // One (t, x, y) row, the same columns the gnuplot data heredoc carries.
+  void row(double t, double x, double y) {
+    if (!open || n_rows >= NAXIS_HTML_MAX_ROWS) {
+      return;
+    }
+    char line[128];
+    int w = snprintf(line, sizeof(line), "%.6f %.6f %.6f\n", t, x, y);
+    if (w < 0 || (size_t)w >= sizeof(line)) {
+      return;
+    }
+    if (rows_len + (size_t)w > NAXIS_HTML_MAX_BYTES) {
+      return;
+    }
+    memcpy(rows_buf + rows_len, line, (size_t)w);
+    rows_len += (size_t)w;
+    n_rows++;
+  }
+
+  // One (t, x, y, z) row for 3-axis fixtures (Step 14). Z is appended as the
+  // third sample column; the viewer template renders the raw text unchanged.
+  void row(double t, double x, double y, double z) {
+    if (!open || n_rows >= NAXIS_HTML_MAX_ROWS) {
+      return;
+    }
+    char line[160];
+    int w = snprintf(line, sizeof(line), "%.6f %.6f %.6f %.6f\n", t, x, y, z);
+    if (w < 0 || (size_t)w >= sizeof(line)) {
+      return;
+    }
+    if (rows_len + (size_t)w > NAXIS_HTML_MAX_BYTES) {
+      return;
+    }
+    memcpy(rows_buf + rows_len, line, (size_t)w);
+    rows_len += (size_t)w;
+    n_rows++;
+  }
+
+  // Splice the accumulated rows into the template's 
 and write
+  // the page. A missing template or output dir leaves nothing on disk.
+  void finish() {
+    if (!open) {
+      return;
+    }
+    const char* open_tag = "
";
+    const char* close_tag = "
"; + char* at = strstr(template_buf, open_tag); + if (at == NULL) { + return; + } + char* after = at + strlen(open_tag); + char* end = strstr(after, close_tag); + if (end == NULL) { + return; + } + size_t head = (size_t)(after - template_buf); + size_t tail = strlen(end); + size_t need = head + rows_len + tail + 1; + char* out = (char*)malloc(need); + if (out == NULL) { + return; + } + memcpy(out, template_buf, head); + memcpy(out + head, rows_buf, rows_len); + memcpy(out + head + rows_len, end, tail); + out[head + rows_len + tail] = 0; + + FILE* f = fopen(out_path, "w"); + if (f != NULL) { + fwrite(out, 1, head + rows_len + tail, f); + fclose(f); + } + free(out); + free(template_buf); + template_buf = NULL; + open = false; + } + + ~NaxisHtmlDump() { + free(template_buf); + free(rows_buf); + } + + int rows_written() const { return n_rows; } + + private: + static const int NAXIS_HTML_MAX_ROWS = 200000; + static const size_t NAXIS_HTML_MAX_BYTES = (size_t)NAXIS_HTML_MAX_ROWS * 128; + char out_path[128]; + char title_buf[128]; + char* template_buf; + char* rows_buf; + size_t rows_len; + int n_rows; + bool open; +}; + +// The out/ directory is git-ignored, so it does not exist on a fresh checkout. +// Create it before the dumps try to write (test-only; PC target). +inline void naxis_ensure_html_out_dir() { + system("mkdir -p \"" NAXIS_HTML_ROOT "/tests/out\""); +} + +#endif /* NAXIS_HTML_DUMP_H */ diff --git a/tests/host/naxis_plot.h b/tests/host/naxis_plot.h new file mode 100644 index 0000000..a936aab --- /dev/null +++ b/tests/host/naxis_plot.h @@ -0,0 +1,284 @@ +// naxis_plot.h — gnuplot dump helper for the FasNAxis PC tests. +// +// Writes one self-contained multi-panel gnuplot file the way RampChecker does +// (RampChecker::start_plot / finish_plot in test_02): open a heredoc, stream +// rows, close it, then emit the "set multiplot layout" blocks. Panel 1 is the +// XY figure — the commanded polyline in grey with the realized path on top — +// which is what "one figure should show the xy-plot for 2 steppers" means. +// Panels 2..4 overlay one series per axis: speed [steps/s] over time, +// performed ramp-up P vs remaining-to-stop R over time (legend spells the +// abbreviations out), and period [ticks] over time. Panel 5 plots the step +// deviation distance (commanded (x,y) minus realized (x,y)) over time on +// its own scale: the 1600x1600 XY path is too coarse to reveal small +// per-step deviations, so they need their own panel. +// Speeds use the test-only TICKS_PER_S / ticks conversion (whitepaper +// section 6.1 / 13.1); the helper holds no kinematics. +// +// Each panel is a single newline-terminated "plot ... series, ... series" +// statement (gnuplot does not accept a literal backslash-n line continuation). +// "make clean" already deletes *.gnuplot. +// +// Protocol: +// plot.start_plot("f5", "FasNAxis F5 square", 2); +// for (waypoint w in polyline) plot.poly_point(w.x, w.y); +// plot.poly_done(); // close the commanded-path +// heredoc for (sample s in run) +// plot.row(s.t, s.x, s.y, s.dev, s.speed, s.P, s.R, s.ticks); +// plot.finish_plot(); +// +#ifndef NAXIS_PLOT_H +#define NAXIS_PLOT_H + +#include +#include + +// Up to this many axes get per-axis overlay series (2D and 3D fixtures use the +// first N). The XY panel always uses the first two axes. +#define NAXIS_PLOT_MAX 3 + +// Test-only conversion from ticks to steps/s; never formed in production. +#define NAXIS_PLOT_TICKS_PER_S 16000000.0 + +class NaxisPlot { + public: + int n_axes; + + NaxisPlot() : open(false), title("FasNAxis"), n_axes(1), has_yrange(false) {} + + // Optional explicit y-range for scalar plots (e.g. frame a tolerance band). + // Without it gnuplot auto-ranges, which degenerates for an all-zero series. + void set_y_range(double lo, double hi) { + yrange_lo = lo; + yrange_hi = hi; + has_yrange = true; + } + + void start_plot(const char* fixture, const char* fixture_title, int axes) { + n_axes = axes; + has_yrange = false; + if (n_axes > NAXIS_PLOT_MAX) { + n_axes = NAXIS_PLOT_MAX; + } + snprintf(title, sizeof(title), "%s", fixture_title); + snprintf(filename, sizeof(filename), "test_26_%s.gnuplot", fixture); + gp = fopen(filename, "w"); + if (gp == NULL) { + open = false; + return; + } + open = true; + // Panel 1 references a separate commanded-path heredoc, written up front. + fprintf(gp, "$poly <, ..." statement into + // `out`. Each (col, prefix) group contributes one series per axis + // ("using 1: with linespoints title \" \""), all + // groups comma-chained into a single plot statement so they share one + // panel. When `per_axis[g]` is set the column is offset by 4*i; a zero + // per_axis group (deviation) is a single column titled with just the + // prefix, no axis index. `suffixes` may be NULL (no extra legend text) or + // an empty string per group. + void build_statement(char* out, size_t out_sz, const int* cols, + const int* per_axis, const char** prefixes, + const char** suffixes, int ngroups) { + size_t len = 0; + bool first = true; + for (int g = 0; g < ngroups; g++) { + int nseries = per_axis[g] ? n_axes : 1; + const char* suf = + (suffixes != NULL && suffixes[g] != NULL) ? suffixes[g] : ""; + for (int i = 0; i < nseries; i++) { + int col = per_axis[g] ? cols[g] + 4 * i : cols[g]; + int w; + if (per_axis[g] && suf[0] != 0) { + w = snprintf(out + len, out_sz - len, + "%s$data using 1:%d with linespoints " + "title \"%s%d %s\"", + first ? "plot " : ", ", col, prefixes[g], i, suf); + } else if (per_axis[g]) { + w = snprintf(out + len, out_sz - len, + "%s$data using 1:%d with linespoints " + "title \"%s%d\"", + first ? "plot " : ", ", col, prefixes[g], i); + } else { + w = snprintf(out + len, out_sz - len, + "%s$data using 1:%d with linespoints " + "title \"%s\"", + first ? "plot " : ", ", col, prefixes[g]); + } + first = false; + if (w < 0 || (size_t)w >= out_sz - len) { + out[0] = 0; + return; + } + len += (size_t)w; + } + } + out[len++] = '\n'; + out[len] = 0; + } +}; + +#endif /* NAXIS_PLOT_H */ diff --git a/tests/host/naxis_ref.h b/tests/host/naxis_ref.h new file mode 100644 index 0000000..941d4e4 --- /dev/null +++ b/tests/host/naxis_ref.h @@ -0,0 +1,360 @@ +#ifndef NAXIS_REF_H +#define NAXIS_REF_H + +#include + +#include "fas_naxis/dda.h" +#include "fas_naxis/ramp_law.h" +#include "fas_naxis/ramp_map.h" +#include "fas_naxis/remaining.h" + +// PC reference track (whitepaper section 12.4.1, todo Step 2ref). +// +// This is the globally fastest constraint-faithful Linear track: G1/G2/G6, +// on the chords, path speed 0 only at a hard stop (master-sense reversal, +// outgoing master that was idle, dwell, or path end), DDA on longest |delta|, +// ticks_b lengthened if a slave would exceed v_max, FAS ramp on remaining +// master-steps to that stop. P carries across every other joint. It is the +// truth the interpolator must match (log2 / one-step slack). Not a replay of +// LinearBlock fields. +// +// PC tests only. double is allowed in callers, not here. Not included from +// src/FasNAxis.h. Overshoot T_opt is Step 11. +// +// 1-D law is RampCalculator via RampMap (same P vs R as RampLaw). DDA is +// DdaWalk. R is Remaining::linear_remaining. Infinite HORIZON unless the +// Remaining object sets one. +class NaxisRefLinear { + public: + Remaining* rem; + const uint32_t* ticks_axis; + uint32_t accel; + int n_axes; + int block; + int master; + DdaWalk dda; + RampMap map; + uint32_t ticks_law; + uint32_t P; + uint32_t R; + uint32_t R_before_cmd; // R at the start of the last issued command + uint64_t total_ticks; + bool finished; + + NaxisRefLinear(Remaining* rem, const uint32_t* ticks_axis, uint32_t accel) + : rem(rem), + ticks_axis(ticks_axis), + accel(accel), + n_axes(rem->n_axes), + block(0), + master(0), + dda(0, 0), + map(ticks_axis[0], accel), + ticks_law(ticks_axis[0]), + P(0), + R(0), + R_before_cmd(0), + total_ticks(0), + finished(false) { + start_block(0, true); + } + + bool done() const { + return finished || (block >= rem->n_blocks - 1 && dda.done()); + } + + // One master step. step_out[i] in {-1,0,1}. Period from the FAS map at + // the updated P, floored to ticks_law. + uint32_t step(int* step_out) { + for (int i = 0; i < n_axes; i++) { + step_out[i] = 0; + } + while (!finished && dda.done()) { + bool stop = true; + if (block + 1 < rem->n_blocks) { + int32_t a[2]; + int32_t b[2]; + a[0] = rem->delta_of(0, block); + a[1] = n_axes > 1 ? rem->delta_of(1, block) : 0; + b[0] = rem->delta_of(0, block + 1); + b[1] = n_axes > 1 ? rem->delta_of(1, block + 1) : 0; + stop = Remaining::linear_joint_stops(a, b, ticks_axis, n_axes); + } + start_block(block + 1, stop); + } + if (finished) { + return 0; + } + R_before_cmd = R; + uint32_t t = apply_law(); + int out_bind = 0; + int out_slave = 0; + dda.step(&out_bind, &out_slave); + step_out[master] = out_bind; + if (n_axes > 1) { + step_out[1 - master] = out_slave; + } + return t; + } + + private: + static uint32_t abs_u(int32_t d) { + return d > 0 ? (uint32_t)d : (uint32_t)(-(int64_t)d); + } + + int next_moving(int from) const { + for (int b = from; b < rem->n_blocks; b++) { + bool moving = false; + for (int i = 0; i < n_axes; i++) { + if (rem->delta_of(i, b) != 0) { + moving = true; + break; + } + } + if (moving) { + return b; + } + } + return rem->n_blocks; + } + + void start_block(int b, bool reset_P) { + b = next_moving(b); + if (b >= rem->n_blocks) { + finished = true; + return; + } + int32_t d[2]; + d[0] = rem->delta_of(0, b); + d[1] = n_axes > 1 ? rem->delta_of(1, b) : 0; + master = Remaining::longest_axis(d, ticks_axis, n_axes); + ticks_law = Remaining::ticks_floor(d, ticks_axis, n_axes); + if (ticks_law == 0) { + ticks_law = ticks_axis[0]; + } + map = RampMap(ticks_law, accel); + int32_t bind = d[master]; + int32_t slave = n_axes > 1 ? d[1 - master] : 0; + dda = DdaWalk(bind, slave); + R = remaining_path_steps(b); + if (R == 0) { + R = abs_u(bind); + } + if (reset_P) { + P = 0; + } else { + uint32_t coast = map.P_coast(); + if (P > coast) { + P = coast; + } + if (P > R) { + P = R; + } + } + block = b; + finished = false; + } + + // Master steps to the next hard stop. P and R live in these units so a run + // may rebind the DDA master without changing the ramp-step currency. + // FAS_NAXIS_NO_CROSS_BLOCK_R (inside linear_remaining) cuts R to one block. + uint32_t remaining_path_steps(int head) const { + uint32_t acc[2] = {accel, accel}; + return Remaining::linear_remaining<2>(head, rem->n_blocks, n_axes, + ticks_axis, acc, rem->horizon, + [this](int b, int ax) -> int32_t { + if (ax >= n_axes) { + return 0; + } + return rem->delta_of(ax, b); + }); + } + + uint32_t apply_law() { + uint32_t coast = map.P_coast(); + if (R > P) { + if (P < coast) { + P++; + } + } else { + if (P > 0) { + P--; + } + } + uint32_t t; + if (P == 0) { + t = map.calculate_ticks(1); + } else { + t = map.calculate_ticks(P); + if (t < ticks_law) { + t = ticks_law; + } + } + total_ticks += t; + if (R > 0) { + R--; + } + return t; + } +}; + +// Step 11 Overshoot duration oracle (whitepaper section 6.4 / 7.3): each axis +// runs RampLaw over |delta_i| with its own ticks_cfg / accel; T is the largest +// of those per-axis ramp durations (the binding axis). The Overshoot track's +// wall clock must equal this sum -- it is the binding axis's ramp, never +// shortened by the non-binding axes. PC-only, no FasNAxis state. +static uint64_t naxis_overshoot_duration(const int32_t* d, + const uint32_t* ticks, + const uint32_t* accel, int n_axes) { + uint64_t T = 0; + for (int i = 0; i < n_axes; i++) { + int32_t ad = d[i] > 0 ? d[i] : -d[i]; + if (ad == 0) { + continue; + } + RampLaw law(ticks[i], accel[i], (uint32_t)ad); + uint64_t s = 0; + while (!law.done()) { + s += law.step(); + } + if (s > T) { + T = s; + } + } + return T; +} + +// Step 12 Overshoot vertex oracle (whitepaper sections 6.4 / 7.3 / 8.6). Per +// axis, P evolves by the section 7.1 law over its own R_i (remaining steps in +// the current direction); a sign change or an idle-after-moving block resets +// P_i to 0 at that vertex. The exit P of an axis after a block depends only on +// its own law, so this oracle needs no command walk. `T_block[b]` is the +// binding duration max_i T_opt_i, and the shared wall clock at vertex b+1 is +// the sum of T_block[0..b]. PC-only, no FasNAxis state. +static uint32_t naxis_overshoot_law_step(const RampMap& map, uint32_t* P, + uint32_t* R, uint32_t ticks_cfg) { + uint32_t coast = map.P_coast(); + if (*R > *P) { + if (*P < coast) { + (*P)++; + } + } else { + if (*P > 0) { + (*P)--; + } + } + uint32_t t; + if (*P == 0) { + t = map.calculate_ticks(1); + } else { + t = map.calculate_ticks(*P); + if (t < ticks_cfg) { + t = ticks_cfg; + } + } + if (*R > 0) { + (*R)--; + } + return t; +} + +// Sum of the periods of `steps` law steps for one axis. +static uint64_t naxis_overshoot_sim(const RampMap& map, uint32_t P_in, + uint32_t R_in, uint32_t ticks_cfg, + uint32_t steps) { + uint32_t p = P_in; + uint32_t r = R_in; + uint64_t sum = 0; + for (uint32_t s = 0; s < steps; s++) { + sum += naxis_overshoot_law_step(map, &p, &r, ticks_cfg); + } + return sum; +} + +// `bx` / `by` are the per-block signed deltas of a 2-axis polyline. Fills +// `T_block[b]` with the binding duration and `P0_out[b]` / `P1_out[b]` with +// the per-axis exit P at vertex b+1. `cap` does not affect P, so it is unused. +static void naxis_overshoot_vertices(const int32_t* bx, const int32_t* by, + int n_blocks, const uint32_t* ticks, + const uint32_t* accel, uint32_t cap, + uint64_t* T_block, uint32_t* P0_out, + uint32_t* P1_out) { + (void)cap; + RampMap m0(ticks[0], accel[0]); + RampMap m1(ticks[1], accel[1]); + uint32_t P0 = 0, P1 = 0; + int sgn0 = 0, sgn1 = 0; + for (int b = 0; b < n_blocks; b++) { + uint32_t R0 = 0, R1 = 0; + int s0 = 0, s1 = 0; + for (int k = b; k < n_blocks; k++) { + int32_t dx = bx[k]; + if (dx == 0) { + if (s0 != 0) { + break; + } + continue; + } + int sg = dx > 0 ? 1 : -1; + if (s0 == 0) { + s0 = sg; + } + if (sg != s0) { + break; + } + R0 += dx > 0 ? (uint32_t)dx : (uint32_t)-dx; + } + for (int k = b; k < n_blocks; k++) { + int32_t dy = by[k]; + if (dy == 0) { + if (s1 != 0) { + break; + } + continue; + } + int sg = dy > 0 ? 1 : -1; + if (s1 == 0) { + s1 = sg; + } + if (sg != s1) { + break; + } + R1 += dy > 0 ? (uint32_t)dy : (uint32_t)-dy; + } + int32_t dx = bx[b], dy = by[b]; + int ns0 = dx > 0 ? 1 : (dx < 0 ? -1 : 0); + int ns1 = dy > 0 ? 1 : (dy < 0 ? -1 : 0); + if (ns0 == 0 || (sgn0 != 0 && ns0 != sgn0)) { + P0 = 0; + } + if (ns1 == 0 || (sgn1 != 0 && ns1 != sgn1)) { + P1 = 0; + } + uint32_t a0 = dx > 0 ? (uint32_t)dx : (uint32_t)-dx; + uint32_t a1 = dy > 0 ? (uint32_t)dy : (uint32_t)-dy; + uint64_t t0 = a0 > 0 ? naxis_overshoot_sim(m0, P0, R0, ticks[0], a0) : 0; + uint64_t t1 = a1 > 0 ? naxis_overshoot_sim(m1, P1, R1, ticks[1], a1) : 0; + // Advance the exit P (simulate above worked on copies). + if (a0 > 0) { + uint32_t p = P0, r = R0; + for (uint32_t s = 0; s < a0; s++) { + naxis_overshoot_law_step(m0, &p, &r, ticks[0]); + } + P0 = p; + } + if (a1 > 0) { + uint32_t p = P1, r = R1; + for (uint32_t s = 0; s < a1; s++) { + naxis_overshoot_law_step(m1, &p, &r, ticks[1]); + } + P1 = p; + } + T_block[b] = t0 > t1 ? t0 : t1; + P0_out[b] = P0; + P1_out[b] = P1; + sgn0 = ns0; + sgn1 = ns1; + } +} + +#endif /* NAXIS_REF_H */ diff --git a/tests/host/naxis_sim_port.h b/tests/host/naxis_sim_port.h new file mode 100644 index 0000000..7e56e11 --- /dev/null +++ b/tests/host/naxis_sim_port.h @@ -0,0 +1,419 @@ +#ifndef FAS_NAXIS_SIM_PORT_H +#define FAS_NAXIS_SIM_PORT_H + +#include + +#include "fas_arch/common.h" +#include "fas_arch/result_codes.h" + +#ifdef FAS_PHYSICAL_STEPPER_ENABLED +// The coupling to the rotordynamic plant (physical_stepper_whitepaper section +// 3.1 / 13.3) is opt-in: only the -DFAS_PHYSICAL_STEPPER_ENABLED build pulls +// in the plant, so the default suite keeps the ideal stepper bit-identical. +#include "physical_stepper.h" +#endif + +// SimPort — a duck-typed stand-in for the platform StepperQueue that the +// FasNAxis feeder talks to through addQueueEntry() (whitepaper section 4.1). +// +// It reproduces, WITHOUT a running ISR, the parts of the real addQueueEntry / +// StepperQueue protocol the n-axis feeder depends on: +// - a ring of pending commands, queue_end tracking the last count_up +// - the start-flag / kick-off contract (addQueueEntry(NULL, true)) +// - the pd_test "no inject for a pause, inject for a reversing step" rule +// - a test hook that injects a before-pause (old DIR) then an after-pause +// (new DIR) on a reversing step, flipping queue_end on the after-pause +// - drain() that advances position and a simulated clock +// - isRampGeneratorActive() false unless the test forces it +// +// It is a test helper: it is NOT included from src/FasNAxis.h and never links +// the real pulse drivers. +class SimPort { + public: + // Inject hook: how the port reacts to a reversing step command. + // InjectNone — default pd_test: a reversing step (or a reverting pause) + // enqueues with no injected pause; the DIR is simply the new count_up. + // InjectDirPauses — buffered-driver behaviour (RMT/MCPWM/I2S): on a + // reversing step the port injects a before-pause with the OLD count_up, + // then an after-pause with the NEW count_up (which flips queue_end), + // before the step itself enqueues. Each call returns + // DirChangePauseInjected and the command is NOT enqueued until the + // sequence completes. + enum InjectMode { InjectNone, InjectDirPauses }; + + SimPort(uint16_t max_speed_in_ticks = 80, int queue_len = 64) + : max_speed_in_ticks_(max_speed_in_ticks), + accel_(2000), + queue_len_(queue_len), + inject_(InjectNone), + inject_ticks_(8000), + ramp_generator_active_(false), + dir_before_ticks_(0), + dir_after_ticks_(0), + force_extra_before_(0), + stop_cause_(StepperStopCause::None) { + reset(); + } + + // Reset to a fresh, empty, un-kicked-off port at rest. + void reset() { + read_idx_ = 0; + next_write_idx_ = 0; + position_ = 0; + clock_ = 0; + queue_end_count_up_ = true; + kicked_off_ = false; + injected_pause_ticks_ = 0; + before_done_ = false; + after_done_ = false; + fail_rc_ = AQE_OK; + force_extra_before_ = 0; + stop_cause_ = StepperStopCause::None; + } + + // --- inject / driver hook configuration --- + void setInjectMode(InjectMode m) { inject_ = m; } + void setInjectTicks(uint16_t ticks) { inject_ticks_ = ticks; } + + // One-shot retryable fault for Step 8. The next addQueueEntry(non-NULL) + // returns `rc` once, enqueues nothing, and leaves isQueueFull() (and + // queueEntries()) unchanged. Used to prove the FasNAxis feeder holds a + // command that returned a retryable code and re-sends it on the next pump + // instead of dropping it or re-planning the partner axis. + void failNext(AqeResultCode rc) { fail_rc_ = rc; } + + // --- DIR pause budget (whitepaper section 4.4, todo Step 9) --- + // The reversing axis must already be at a slow period long enough to hold + // the before/after pauses. FasNAxis reads these through the same names the + // real StepperMotion exposes, so the planner carves the carved shape on + // the reversing axis only. Default 0 = no pause (the current behaviour). + void setDirChangeBudget(uint16_t before, uint16_t after) { + dir_before_ticks_ = before; + dir_after_ticks_ = after; + } + uint16_t getDirChangeBeforeTicks() const { return dir_before_ticks_; } + uint16_t getDirChangeAfterTicks() const { return dir_after_ticks_; } + + // One-shot "the driver injects one more before-pause the plan did not + // carve" hook (F12c). The next steps>0 command enqueues a pause of `ticks` + // at the OLD count_up, records it in injectedPauseTicks(), returns + // DirChangePauseInjected, and does NOT enqueue the step. Then the flag + // clears. Use with InjectNone. + void forceExtraBefore(uint16_t ticks) { force_extra_before_ = ticks; } + + // --- ramp generator idle contract (whitepaper section 4.6) --- + // The feeder requires the FAS ramp generator to be idle; SimPort models + // that as a plain flag the test may force. + bool isRampGeneratorActive() const { return ramp_generator_active_; } + void setRampGeneratorActive(bool on) { ramp_generator_active_ = on; } + + // --- query surface used by the feeder --- + // queue_end.count_up: the direction the last enqueued (or, for a reversing + // step in inject mode, the last injected) command left the port in. + bool queueEndCountUp() const { return queue_end_count_up_; } + int32_t position() const { return position_; } + // Duck-type alias for the real StepperMotion::getCurrentPosition(): the + // FasNAxis feeder / syncFromSteppers() talks to every stepper through one + // name, so SimPort exposes the same getter the production stepper uses. + int32_t getCurrentPosition() const { return position_; } + // Duck-type alias for the real StepperMotion::getMaxSpeedInTicks(): + // addAxis / setLimitsFromSteppers read the configured period through one + // name, so SimPort exposes its max_speed_in_ticks under that name. + uint16_t getMaxSpeedInTicks() const { return max_speed_in_ticks_; } + // Duck-type alias for the real StepperMotion::getAcceleration(): addAxis + // reads the per-axis acceleration through the same name (section 6.3). + uint32_t getAcceleration() const { return accel_; } + void setAcceleration(uint32_t a) { accel_ = a; } + uint32_t clock() const { return clock_; } + // Ticks of the pause the last call injected (0 for AQE_OK). An inject the + // plan did not carve is a planner failure (whitepaper section 4.4.3). + uint16_t injectedPauseTicks() const { return injected_pause_ticks_; } + bool isQueueEmpty() const { return read_idx_ == next_write_idx_; } + // Pending command count, matching StepperMotion::queueEntries(). + uint32_t queueEntries() const { + return (uint32_t)(next_write_idx_ - read_idx_); + } + // Duck-type alias for StepperMotion::isQueueFull(). One slot is reserved + // so a caller that checks this before a coordinated slice always has room + // for two entries (a pause-stuffed step, section 4.2). + bool isQueueFull() const { + return queueEntries() + 1 >= (uint32_t)queue_len_; + } + // After a kick-off the queue running with an empty queue while the plan is + // still open is an underrun; before a kick-off an empty queue is expected + // (prefill) and is NOT an underrun. + bool hasUnderrun() const { return kicked_off_ && isQueueEmpty(); } + // Modelled from StepperMotion::isRunning(): a kick-off started the queue + // and it has not settled to a no-motion state. + bool isRunning() const { return kicked_off_; } + + // --- external stop modelling --- + // Duck-type alias for StepperMotion::takeStopCause(): FasNAxis polls this + // each pump(); default None keeps the existing cases unchanged. A test + // injects a stop through setStopCause() or forceStop(). + StepperStopCause takeStopCause() { + StepperStopCause c = stop_cause_; + stop_cause_ = StepperStopCause::None; + return c; + } + void setStopCause(StepperStopCause c) { stop_cause_ = c; } + // Model StepperMotion::forceStop(): abort the queue and report ForceStop. + void forceStop() { + kicked_off_ = false; + read_idx_ = next_write_idx_; + stop_cause_ = StepperStopCause::ForceStop; + // The real queue's admission latch is set by forceStop(); the model has no + // refusal path, so track it only so areCommandsSuspended() is meaningful. + suspended_ = true; + } + // Duck-type alias for StepperMotion::resumeCommands(). FasNAxis calls this + // from feeder_start(); the model needs nothing beyond clearing the flag. + void resumeCommands() { suspended_ = false; } + bool areCommandsSuspended() const { return suspended_; } + +#ifdef FAS_PHYSICAL_STEPPER_ENABLED + // --- opt-in rotordynamic coupling (whitepaper section 3.1 / 13.3) --- + // When a plant is attached, drain_one() advances the rotor with the very + // command the ideal counter consumes, so the plant's physical position is + // the axis's *realized* position (it lags during accel, runs ahead during + // decel, and stalls when the ramp outruns it). position() keeps the ideal + // commanded count the planner's DDA binds against; realizedPosition() is + // the diverging physical count that makes step loss visible to the binder. + void setPhysicalStepper(PhysicalStepper* plant) { plant_ = plant; } + bool hasPhysical() const { return plant_ != NULL; } + // The plant's physical (rotor) observables, exposed to the coupling test. + int32_t realizedPosition() const { + return plant_ ? plant_->getCurrentPosition() : 0; + } + double realizedSpeed() const { return plant_ ? plant_->speed() : 0.0; } + double realizedDelta() const { return plant_ ? plant_->delta() : 0.0; } + double peakRealizedDelta() const { + return plant_ ? plant_->peak_abs_delta() : 0.0; + } + bool realizedStalled() const { return plant_ ? plant_->stall_ever() : false; } +#endif + + // --- the feeder's only entry point (whitepaper section 4.1) --- + AqeResultCode addQueueEntry(const struct stepper_command_s* cmd, bool start) { + injected_pause_ticks_ = 0; + // One-shot injected fault (Step 8): fire once on a command, enqueue + // nothing, and leave the queue length untouched. + if (cmd != NULL && fail_rc_ != AQE_OK) { + AqeResultCode rc = fail_rc_; + fail_rc_ = AQE_OK; + return rc; + } + // Kick-off: addQueueEntry(NULL, true) starts the queue. On an empty queue + // it is an error (there is nothing to start). + if (cmd == NULL) { + if (isQueueEmpty()) { + return AQE_ERROR_EMPTY_QUEUE_TO_START; + } + kicked_off_ = true; + return AQE_OK; + } + // The max-speed floor is a planner contract for step timing: a step + // command faster than ticks_cfg is ErrorTicksTooLow. A pause (steps == 0) + // is a delay, not a step; the real queue only checks MIN_CMD_TICKS on it, + // so a slow axis's 65535 split may use a shorter pause than max_speed. + if (cmd->steps > 0 && cmd->ticks < max_speed_in_ticks_) { + return AQE_ERROR_TICKS_TOO_LOW; + } + // One-shot driver inject (F12c): enqueue a before-pause the plan did not + // carve, at the OLD count_up, and do not enqueue the step. + if (cmd->steps > 0 && force_extra_before_ != 0) { + uint16_t t = force_extra_before_; + force_extra_before_ = 0; + enqueue(t, 0, queue_end_count_up_); + injected_pause_ticks_ = t; + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + if (isQueueFull()) { + return AQE_QUEUE_FULL; + } + + // In inject mode a reversing step (steps > 0 and a new DIR) drives the + // buffered-driver before/after pause sequence; the step itself enqueues + // only once the sequence has completed. + bool reversing_step = + cmd->steps > 0 && cmd->count_up != queue_end_count_up_; + if (inject_ == InjectDirPauses && reversing_step) { + if (!before_done_) { + // Before-pause: drain the pipeline, keep the OLD count_up. + enqueue(inject_ticks_, 0, queue_end_count_up_); + injected_pause_ticks_ = inject_ticks_; + before_done_ = true; + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + if (!after_done_) { + // After-pause: the toggle command, NEW count_up, flips queue_end. + enqueue(inject_ticks_, 0, cmd->count_up); + queue_end_count_up_ = cmd->count_up; + injected_pause_ticks_ = inject_ticks_; + after_done_ = true; + return AQE_DIR_CHANGE_PAUSE_INJECTED; + } + // Sequence done: enqueue the reversing step itself. + before_done_ = false; + after_done_ = false; + } else if (reversing_step) { + // Default pd_test: no injected pause; the step just flips the DIR. + before_done_ = false; + after_done_ = false; + } + + // Pause (steps == 0) or non-reversing step: enqueue as given. A pause + // uses the count_up the caller passes with no implicit flip, so a + // reverting pause (count_up = !old) simply leaves the port in the new DIR. + enqueue(cmd->ticks, cmd->steps, cmd->count_up); + queue_end_count_up_ = cmd->count_up; + if (start) { + kicked_off_ = true; + } + return AQE_OK; + } + + // Consume exactly one pending command (the front of the queue). Returns the + // tick sum of that command (0 if the queue is empty) and, optionally, its + // steps and count_up. Used by the FasNAxis feeder tests to drain the axes in + // lockstep, one coordinated command at a time. + uint32_t drain_one(int64_t* steps_out = NULL, bool* count_up_out = NULL) { + if (read_idx_ == next_write_idx_) { + return 0; + } + struct queue_entry& e = entry_[read_idx_ & queue_mask()]; + uint32_t ticks = e.steps == 0 ? e.ticks : (uint32_t)e.steps * e.ticks; + if (e.steps != 0) { + position_ += e.count_up ? e.steps : -(int32_t)e.steps; + } + clock_ += ticks; +#ifdef FAS_PHYSICAL_STEPPER_ENABLED + // The plant sees the same command the ideal counter consumed (a split long + // period feeds as a step entry then pause entries, exactly as the planner + // splits it), so its clock stays in lockstep with position(). + if (plant_ != NULL) { + plant_->step((int)e.steps, e.count_up, e.ticks); + } +#endif + if (steps_out != NULL) { + *steps_out = e.steps; + } + if (count_up_out != NULL) { + *count_up_out = e.count_up; + } + read_idx_++; + return ticks; + } + + // Consume the whole pending queue: advance position (signed by count_up) and + // the simulated clock (pause ticks + steps*ticks for step commands). + uint32_t drain() { return drain_all(); } + + // Consume pending commands up to a tick budget. Returns the number of ticks + // drained from this call. When a command straddles the budget the remainder + // is left in place and the call returns. + uint32_t drain(uint32_t budget) { + uint32_t drained = 0; + while (read_idx_ != next_write_idx_ && drained < budget) { + struct queue_entry& e = entry_[read_idx_ & queue_mask()]; + uint32_t ticks = e.steps == 0 ? e.ticks : (uint32_t)e.steps * e.ticks; + if (e.steps != 0) { + position_ += e.count_up ? e.steps : -(int32_t)e.steps; + } + if (drained + ticks > budget) { + uint32_t room = budget - drained; + if (room == 0) { + break; + } + clock_ += room; + drained += room; + e.ticks = (uint16_t)room; // leave the remainder in the command + return drained; + } + clock_ += ticks; + drained += ticks; + read_idx_++; + } + return drained; + } + + private: + struct queue_entry { + uint16_t ticks; + uint8_t steps; + bool count_up; + }; + + uint16_t max_speed_in_ticks_; + uint32_t accel_; + int queue_len_; + InjectMode inject_; + uint16_t inject_ticks_; + bool ramp_generator_active_; + + queue_entry entry_[64]; + int read_idx_; + int next_write_idx_; + int32_t position_; + uint32_t clock_; + bool queue_end_count_up_; + bool kicked_off_; + uint16_t injected_pause_ticks_; + bool before_done_; + bool after_done_; + AqeResultCode fail_rc_; + uint16_t dir_before_ticks_; + uint16_t dir_after_ticks_; + uint16_t force_extra_before_; + StepperStopCause stop_cause_; + bool suspended_ = false; +#ifdef FAS_PHYSICAL_STEPPER_ENABLED + PhysicalStepper* plant_ = NULL; // opt-in rotordynamic coupling +#endif + + inline uint32_t queue_mask() const { return (uint32_t)queue_len_ - 1; } + + // Drain the whole pending queue (see drain()). + uint32_t drain_all() { + uint32_t drained = 0; + while (read_idx_ != next_write_idx_) { + struct queue_entry& e = entry_[read_idx_ & queue_mask()]; + uint32_t ticks = e.steps == 0 ? e.ticks : (uint32_t)e.steps * e.ticks; + if (e.steps != 0) { + position_ += e.count_up ? e.steps : -(int32_t)e.steps; + } + clock_ += ticks; + drained += ticks; + read_idx_++; + } + return drained; + } + + // Append one entry to the ring. The port never fills the ring in these + // small contract tests; a full ring would surface as a retryable Busy. + void enqueue(uint16_t ticks, uint8_t steps, bool count_up) { + entry_[next_write_idx_ & queue_mask()] = + queue_entry{ticks, steps, count_up}; + next_write_idx_++; + } +}; + +// TestStepperMotionEngine — the test-world stand-in for +// StepperMotionEngine as far as the FasNAxis kick-off is concerned. +// synchronizedStart() releases every listed SimPort queue in one call, +// mirroring the production engine's contract for duck-typed steppers. +class TestStepperMotionEngine { + public: + AqeResultCode synchronizedStart(SimPort** const steppers, uint8_t cnt) { + AqeResultCode rc = AqeResultCode::OK; + for (uint8_t i = 0; i < cnt; i++) { + AqeResultCode e = steppers[i]->addQueueEntry(NULL, true); + if (rc == AqeResultCode::OK && e != AqeResultCode::OK) { + rc = e; + } + } + return rc; + } +}; + +#endif // FAS_NAXIS_SIM_PORT_H diff --git a/tests/host/physical_stepper.h b/tests/host/physical_stepper.h new file mode 100644 index 0000000..dfb9d65 --- /dev/null +++ b/tests/host/physical_stepper.h @@ -0,0 +1,624 @@ +// physical_stepper.h — a rotordynamic plant that stands in for a real stepper. +// +// The ideal stepper in the PC test suite is an *exact* integrator: it counts +// pulses and never lags, stalls, or rings. That is perfect for kinematics, but +// it cannot answer the practical question "what does the motor actually do". +// +// PhysicalStepper is a lightweight rotor model with a single degree of freedom +// — the rotor position x. It is driven by the only two things a real driver can +// hand it: +// +// how many steps, in which direction, and how long each step lasts (ticks). +// +// Between the commanded position x_c and the actual rotor x sits a +// rotordynamics model: +// +// J * dw/dt = tau_magnetic(delta) - F_friction(w) +// dx/dt = w +// +// with delta = x - x_c (actual minus target) and a bounded, sinusoidal +// magnetic coupling — the holding/detent torque curve, with a stable detent +// once per full step: +// +// tau_magnetic(delta) = -Fmax * sin(2*pi * delta / D) for any delta +// +// The magnetic field is the only torque the driver commands. It is zero at the +// stable detents (delta = k*D), reaches its peak Fmax a quarter step away, and +// crosses zero again at the half-step separatrix (the unstable point between +// two detents). It is periodic in delta, so it is evaluated for *any* delta — +// no “grip lost” branch (§5.4). +// +// The only inverse force to the motor is friction, an *independent* mechanical +// load (it does not scale with Fmax): +// +// F_friction(w) = friction_static + friction_viscous * |w| +// +// opposite to w, capped at Fmax. At low speed it is the Coulomb floor; it rises +// with speed until it equals Fmax at the pull-out speed +// v_max = (Fmax - friction_static) / friction_viscous. There is deliberately no +// separate magnetic drag term (§5.6). +// +// A one-shot rotor displacement (`rotate`) stands in for a mechanical hold: +// nudging the rotor back half a full step parks it on the separatrix, so the +// field out-runs it and it stalls; nudging back a full step parks it on the +// next stable detent and it only loses one step. A command pause does not +// release the motor either: the detent force keeps acting on the frozen +// command. Stall is not implemented: it is only the *observation* that +// a full step behind *and still slipping* (§5.5). See the whitepaper +// §5.5–§5.6. +// +// ---- opt-in, never the default ------------------------------------------- +// +// This plant NEVER replaces the ideal stepper by default. Every existing test +// keeps the ideal stepper. Turn the plant on by request, per test (e.g. +// test_27), with the gate at the top of the file: +// +// #define FAS_PHYSICAL_STEPPER_ENABLED 1 +// #include "physical_stepper.h" +// +// While FAS_PHYSICAL_STEPPER_ENABLED == 0 the header is an inert stub: a test +// that forgets to opt in keeps the ideal stepper and loses nothing. +#ifndef FAS_PHYSICAL_STEPPER_H +#define FAS_PHYSICAL_STEPPER_H + +#if !defined(FAS_PHYSICAL_STEPPER_ENABLED) +#define FAS_PHYSICAL_STEPPER_ENABLED 0 +#endif + +#include +#include + +#include +#include +#if FAS_PHYSICAL_STEPPER_ENABLED +#include +#endif +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +// Self-contained: provide a default TICKS_PER_S if the host test does not pull +// in fas_arch/common.h. (StepperMotion uses 16 MHz on the PC target.) +#ifndef TICKS_PER_S +#define TICKS_PER_S 16000000L +#endif + +// One row of the simulation time series — the six gnuplot panels (pos, speed, +// accel, force, steploss, stall) all derive from these fields. Position and +// error are in steps; a step quantum is the plant's private business. +struct observed_s { + uint32_t t; // accumulated wall clock (ticks since start) + double x; // rotor position, steps (the physical, reported count) + double x_c; // commanded position, steps + double delta; // position error x - x_c, steps + double w; // rotor speed, steps / s + double a; // rotor acceleration, steps / s^2 + double tau; // magnetic force -Fmax * sin(pi * delta / D) + bool stall; // 1 while the rotor is slipping (dynamic, §5.5) +}; + +// Simple clamp so we don't pull in (which collides with the +// test suite's test(x, msg) macro). +static inline double fas_clamp(double v, double lo, double hi) { + return v < lo ? lo : (v > hi ? hi : v); +} + +#if FAS_PHYSICAL_STEPPER_ENABLED + +// Rotordynamic stepper plant. +// +// Interface: the only inputs are steps, count_up and ticks. There is no +// queue_entry, no hardware — just a command of N steps, each lasting `ticks` +// (TICKS_PER_S units), and a direction. +class PhysicalStepper { + public: + // units_per_full_step = D, the steps in one full step (the period of the + // force curve). J rotor moment of inertia, Fmax peak magnetic torque. + // Friction is an *independent* mechanical load: `friction_static` is its + // Coulomb floor and `friction_viscous` its increase per step/s. It does NOT + // scale with Fmax — a stronger motor does not have more bearing friction. + // The pull-out speed is where the two balance: v_max = (Fmax - static)/visc. + PhysicalStepper(uint8_t units_per_full_step = 64, double inertia = 1.0e-6, + double force_gain = 1.0, double friction_static = 0.1, + double friction_viscous = 2.25e-5) + : D_(units_per_full_step), + J_(inertia), + Fmax_(force_gain), + friction_static_(friction_static), + friction_viscous_(friction_viscous), + ticks_(0), + slip_f_(0.0), + stall_ever_(false), + trace_decim_(0), + trace_n_(0), + trace_phase_(0) { + reset(); + } + + // Reset the rotor to rest exactly at the commanded position. + void reset() { + state_.x = 0.0; + state_.x_c = 0.0; + state_.w = 0.0; + ticks_ = 0; + sim_time_ = 0.0; + phase_ = 0.0; + peak_abs_delta_ = 0.0; + slip_f_ = 0.0; + stall_ever_ = false; + cur_env_ = 0.0; + audio_.clear(); + audio_written_ = 0; + trace_.clear(); + trace_n_ = 0; + last_ = observed_s{0, 0, 0, 0, 0, 0, 0, false}; + } + + // One-shot external displacement of the rotor by `steps` (signed, positive = + // forward), with velocity preserved. This is the simulation stand-in for + // "mechanically holding" the rotor: holding it while the field advances by + // half a full step is the same as rotating the rotor half a step backwards + // once. Half a step parks it on the separatrix (it stalls); a full step parks + // it on the next stable detent (it loses exactly one step). + void rotate(double steps) { state_.x += steps; } + + // The magnetic field: the only commanded torque, zero at each stable detent + // (delta = k*D), peak Fmax a quarter step away, separatrix at the half step. + double magnetic_torque(double delta) const { + return -Fmax_ * sin(2.0 * M_PI * delta / (double)D_); + } + + // Magnitude of the only inverse force to the motor: a Coulomb floor plus a + // viscous term, both absolute mechanical parameters independent of Fmax. + // Capped at Fmax (the motor cannot pull harder than its own torque). Returned + // unsigned; the integrator applies it against the direction of motion. + double friction_mag(double w) const { + double f = friction_static_ + friction_viscous_ * fabs(w); + if (f > Fmax_) f = Fmax_; + return f; + } + + // Pull-out speed: where friction has grown to equal Fmax. + double v_max() const { + if (friction_viscous_ <= 0.0) return 0.0; + double v = (Fmax_ - friction_static_) / friction_viscous_; + return v > 0.0 ? v : 0.0; + } + + // Signed friction force (for reporting / the gnuplot trace). + double friction_force(double w) const { + double f = friction_mag(w); + return (w > 0.0) ? -f : (w < 0.0 ? f : 0.0); + } + + // One Euler-Cromer sub-step under magnetic torque `tau`. Friction removes up + // to Ff*dt/J of velocity but can never reverse the motion, so a rotor at rest + // is held while |tau| <= static friction (the mu0*Fmax floor). Returns the + // effective rotor acceleration (dw/dt) for the trace and the audio model. + double substep(double tau, double dt) { + const double w_old = state_.w; + const double Ff = friction_mag(w_old); + const double w_free = w_old + (tau / J_) * dt; + const double dw_fric = Ff * dt / J_; + if (fabs(w_free) <= dw_fric) { + state_.w = 0.0; + } else { + state_.w = w_free - (w_free > 0.0 ? dw_fric : -dw_fric); + } + state_.x += state_.w * dt; + return (dt > 0.0) ? (state_.w - w_old) / dt : 0.0; + } + + // Integrate one command's duration `dt` in sub-steps no longer than kMaxDt, + // so a long commanded period (up to 65535 ticks = 4.1 ms) never out-runs the + // detent dynamics. Returns the effective rotor acceleration over `dt`. + double integrate(double dt) { + const double w_before = state_.w; + int n = (int)ceil(dt / kMaxDt); + if (n < 1) n = 1; + const double h = dt / (double)n; + for (int i = 0; i < n; i++) { + substep(magnetic_torque(state_.x - state_.x_c), h); + } + return (dt > 0.0) ? (state_.w - w_before) / dt : 0.0; + } + + // Advance the plant by `steps` steps, each lasting `ticks` (in TICKS_PER_S + // units), in the given direction. A direction flip makes the spring force + // flip, producing the reversal behaviour of a real motor. + observed_s step(int steps, bool count_up, uint16_t ticks) { + const double dir = count_up ? 1.0 : -1.0; + const double dt = (double)ticks / (double)TICKS_PER_S; + const double v_field = + (steps > 0) ? (double)TICKS_PER_S / (double)ticks : 0.0; + + double delta = state_.x - state_.x_c; + double tau = 0.0; + double a = 0.0; + + for (int k = 0; k < steps; k++) { + state_.x_c += dir; + + // The magnetic field is the only commanded torque: a single periodic + // curve evaluated for ANY delta (whitepaper §5.4 — no domain boundary, + // no “grip lost” branch). Friction is the only inverse force (§5.6). + a = integrate(dt); + delta = state_.x - state_.x_c; + tau = magnetic_torque(delta); + sim_time_ += dt; + if (fabs(delta) > peak_abs_delta_) peak_abs_delta_ = fabs(delta); + update_stall(delta, v_field, dt); + update_audio_state(delta, a, tau); + record_audio(); + record_trace(delta, a, tau); + } + + if (steps == 0) { + // pause (ticks): no commanded motion, but the detent force is still in + // full effect toward the frozen command — the rotor is braked, not + // released. This is what stops a coasting rotor (§5.6). + const double dtp = (double)ticks / (double)TICKS_PER_S; + a = integrate(dtp); + delta = state_.x - state_.x_c; + tau = magnetic_torque(delta); + sim_time_ += dtp; + if (fabs(delta) > peak_abs_delta_) peak_abs_delta_ = fabs(delta); + update_stall(delta, 0.0, dtp); + update_audio_state(delta, a, tau); + record_audio(); + record_trace(delta, a, tau); + } + + // advance the simulated wall clock by the real command duration. + ticks_ += (steps == 0) ? ticks : (uint32_t)steps * ticks; + + last_.t = ticks_; + last_.x = state_.x; + last_.x_c = state_.x_c; + last_.delta = delta; + last_.w = state_.w; + last_.a = a; + last_.tau = tau; + + return last_; + } + + // Run a whole command list; returns the last observed_s. + // cmd[i] = {steps, count_up, ticks} + struct Cmd { + int steps; + bool count_up; + uint16_t ticks; + }; + observed_s run(const Cmd* cmds, int len) { + observed_s last; + for (int i = 0; i < len; i++) { + last = step(cmds[i].steps, cmds[i].count_up, cmds[i].ticks); + } + return last; + } + + // The rotor's *physical* step count — what the queue base would report, + // diverging from the commanded count whenever the rotor lags or stalls. + int32_t getCurrentPosition() const { return (int32_t)llround(state_.x); } + + uint32_t total_ticks() const { return ticks_; } + + // Peak |x - x_c| seen since the last reset — the cleanest scalar to assert + // "a full step was lost" on, independent of trace decimation. + double peak_abs_delta() const { return peak_abs_delta_; } + + // Whether the rotor was ever observed slipping since the last reset. The + // instantaneous `last().stall` clears again once the rotor re-captures, so + // this is the latch for "a stall happened" assertions. + bool stall_ever() const { return stall_ever_; } + + // Emit one row to a gnuplot writer (see naxis_plot.h), one of the six panels: + // position, speed, acceleration, force, steploss, stall-event. + void plot_row(FILE* g, uint8_t panel, const observed_s& o) { + fprintf(g, "%llu %g %g %g %g %g\n", (unsigned long long)o.t, o.x, o.w, o.a, + o.tau, (double)o.stall); + (void)panel; + } + + const observed_s& last() const { return last_; } + + // ---- gnuplot time-series recorder ------------------------------------- + // The six-panel figure (§6) is built from the per-step integration. The raw + // trace has one row per command, which for a 10000 step/s move at 16 MHz is + // ~16000 rows/s — too dense to plot meaningfully and too big for a stall + // trace that spans a 75 s settle. So we decimate by a fixed step count + // `decim` and emit one row per `decim` integration sub-steps. Pass 0 to + // disable. The row is the raw plant state after that sub-step. + struct Trace { + double t; // simulated time, s + double x; // rotor position, steps + double x_c; // commanded position, steps + double delta; // x - x_c, steps + double w; // rotor speed, steps/s + double a; // rotor acceleration, steps/s^2 (raw, to the rotor) + double tau; // magnetic force -Fmax*sin(pi*delta/D), N*m + double friction; // friction force (signed against motion), N*m + int stall; // 1 while the rotor is slipping (§5.5) + int phase; // 0=accel 1=coast 2=decel 3=pause (test-labelled) + }; + + void trace_begin(unsigned long decim) { + trace_.clear(); + trace_decim_ = decim ? decim : 1; + trace_n_ = 0; + trace_phase_ = 0; + } + + void trace_set_phase(int phase) { trace_phase_ = phase; } + + // Write the accumulated trace as a whitespace-delimited gnuplot input: + // t x x_c delta w a tau friction stall phase + // Returns the number of rows written (0 if the trace is empty). + size_t trace_dump(const char* path) { + FILE* fp = std::fopen(path, "w"); + if (!fp) return 0; + for (size_t i = 0; i < trace_.size(); i++) { + const Trace& r = trace_[i]; + std::fprintf(fp, "%.6f %g %g %g %g %g %g %g %d %d\n", r.t, r.x, r.x_c, + r.delta, r.w, r.a, r.tau, r.friction, r.stall, r.phase); + } + std::fclose(fp); + return trace_.size(); + } + + size_t trace_rows() const { return trace_.size(); } + + // Raw state for the gnuplot traces. + double x() const { return state_.x; } + double x_c() const { return state_.x_c; } + double delta() const { return state_.x - state_.x_c; } + double speed() const { return state_.w; } + + // Acoustic emission (see whitepaper §5.8): a hybrid source driven by the + // actual rotor motion and gated by the magnetic force curve, plus a + // displacement (acceleration) term. While |delta| >= D the motor has run + // past its command (the stall observation of §5.5), so it buzzes like a + // real motor drawing holding current — so the recording never goes silent + // on a stall. + // The plant records one 44.1 kHz sample per + // output interval while it steps, so to_wav() renders the *whole* simulated + // move (e.g. the 5 s canonical trapezoid -> ~441000 bytes of PCM) rather + // than a single capped note. Returns true on success. + bool to_wav(const char* path, uint32_t sr = 44100) { + (void)sr; + const uint32_t rate = kAudioSr; + // Guarantee a valid, non-empty data chunk even for a zero-length move. + if (audio_.empty()) audio_.push_back(0); + const uint32_t n = (uint32_t)audio_.size(); + + FILE* fp = std::fopen(path, "wb"); + if (!fp) return false; + const uint16_t bps = 16, ch = 1; + const uint32_t byteRate = rate * ch * bps / 8; + const uint16_t blockAlign = ch * bps / 8; + const uint32_t dataSize = n * ch * bps / 8; + const uint32_t chunkSize = 36 + dataSize; + const char riff[] = {'R', 'I', 'F', 'F'}; + const char wave[] = {'W', 'A', 'V', 'E'}; + const char fmt[] = {'f', 'm', 't', ' '}; + const char data[] = {'d', 'a', 't', 'a'}; + // RIFF / fmt / data chunk headers. + fwrite(riff, 1, 4, fp); + write_u32le(fp, chunkSize); + fwrite(wave, 1, 4, fp); + fwrite(fmt, 1, 4, fp); + write_u32le(fp, 16); // fmt subchunk size (PCM) + write_u16le(fp, 1); // audio format = PCM + write_u16le(fp, ch); + write_u32le(fp, rate); + write_u32le(fp, byteRate); + write_u16le(fp, blockAlign); + write_u16le(fp, bps); + fwrite(data, 1, 4, fp); + write_u32le(fp, dataSize); + for (uint32_t i = 0; i < n; i++) write_u16le(fp, (uint16_t)audio_[i]); + std::fclose(fp); + return true; + } + + // Number of recorded audio samples (for tests that check the rendered + // length). + uint32_t audio_samples() const { return (uint32_t)audio_.size(); } + + // Raw recorded PCM, so a test can mix several axes into one stereo wav. + // Out-of-range reads are silence. + uint32_t audio_sample_count() const { return (uint32_t)audio_.size(); } + int16_t audio_sample(uint32_t i) const { + return i < audio_.size() ? audio_[i] : (int16_t)0; + } + + private: + // Fixed audio sample rate for the recording grid. + enum { kAudioSr = 44100 }; + // Largest physics sub-step (s). The commanded period can reach 65535 ticks + // (4.1 ms), which is too coarse for the ~63 ms detent; sub-step below this. + static constexpr double kMaxDt = 2.5e-4; + // Stall slip detector: the rotor/field speed mismatch is low-passed with time + // constant kSlipTau (s); a sustained mismatch above kSlipThreshold (steps/s) + // is a stall, while sub-threshold ring or a direction-change transient is + // not. + static constexpr double kSlipTau = 0.05; + static constexpr double kSlipThreshold = 100.0; + // Sum of the humming-partial amplitudes in record_audio (normalization). + static constexpr double kHarmSum = 2.28; + // Speed at which the audio envelope is at half amplitude (steps/s): below + // this the hum fades toward silence, so a near-rest rotor does not rumble. + static constexpr double kAudioW0 = 400.0; + + // Update the dynamic stall observation from the current rotor/field speed + // mismatch. The slip is low-pass filtered (time constant kSlipTau) so a + // commanded direction change or an accel transient does not read as a stall. + // Stalled = a full step or more behind AND still slipping; it clears once the + // rotor re-captures (w -> v_field), e.g. when the field slows (§5.5). + void update_stall(double delta, double v_field, double dt) { + const double slip = state_.w - v_field; + slip_f_ += (slip - slip_f_) * (dt / (kSlipTau + dt)); + last_.stall = + (fabs(delta) > (double)D_) && (fabs(slip_f_) > kSlipThreshold); + if (last_.stall) stall_ever_ = true; + } + + // Append one decimated row to the gnuplot trace (if enabled). + void record_trace(double delta, double a, double tau) { + if (trace_decim_ == 0) return; + if ((trace_n_++ % trace_decim_) != 0) return; + Trace r; + r.t = sim_time_; + r.x = state_.x; + r.x_c = state_.x_c; + r.delta = delta; + r.w = state_.w; + r.a = a; + r.tau = tau; + r.friction = friction_force(state_.w); + r.stall = last_.stall ? 1 : 0; + r.phase = trace_phase_; + trace_.push_back(r); + } + + // Cache the hybrid source parameters after each integration sub-step. + void update_audio_state(double delta, double a, double tau) { + // Hum pitch is the full-step (electrical) rate, |w|/D Hz — the rate the + // rotor's magnetic field actually turns — not the finest step rate. + cur_f_ = fabs(state_.w) / (double)D_; + cur_gate_ = (Fmax_ > 0.0) ? fabs(tau) / Fmax_ : 0.0; + cur_disp_ = (Fmax_ > 0.0) ? (a * J_) / Fmax_ : 0.0; + // The stall observation (§5.5): |delta| has drifted a full step. There is + // no “grip lost” branch — the force runs for any delta, and the motor + // simply cannot keep up, so |delta| grows past D. + cur_stalled_ = last_.stall ? 1.0 : 0.0; + // Speed envelope. The hum is gated by the magnetic force, which is *large* + // at low speed (the rotor lags most while accelerating) — so without this a + // move fades in and out of a loud low-frequency rumble at the start and end + // of every ramp ("strange noise"). Fade the source with rotor speed so a + // near-rest rotor is silent and the tone rises/falls with it. + const double w = fabs(state_.w); + cur_env_ = w / (w + kAudioW0); + } + + // Emit every audio sample whose time has now been reached. + void record_audio() { + double want_d = sim_time_ * (double)kAudioSr; + if (want_d > 1.0e9) return; // safety: never allocate unboundedly + uint32_t want = (uint32_t)floor(want_d); + static const double amp[] = {1.0, 0.5, 0.33, 0.25, 0.2}; + const double dphase = 2.0 * M_PI * cur_f_ / (double)kAudioSr; + while (audio_written_ < want) { + // Accumulate phase so a changing pitch never clicks. + phase_ += dphase; + if (phase_ > 2.0 * M_PI) phase_ -= 2.0 * M_PI; + double s = 0.0; + for (int k = 0; k < 5; k++) { + s += amp[k] * sin((double)(k + 1) * phase_); + } + // Normalize the harmonic sum (Σamp = 2.28) so the hum no longer clips for + // most of a move; the ×3 lift keeps it out of the int16 rounding floor. + s = cur_gate_ * (s / kHarmSum) + 0.1 * cur_disp_; + // Fade the hum with rotor speed: a near-rest rotor is silent, so a ramp + // does not fade in/out of a loud low-frequency rumble. + s *= cur_env_; + // A stalled rotor (§5.5 — |delta| has drifted a full step) draws a lot + // of holding current and buzzes, so a low-frequency buzz rides on top of + // the hum. The recording therefore never goes silent on a stall. + if (cur_stalled_) { + double buzz = 1.0 + 0.3 * sin(2.0 * M_PI * 120.0 * audio_written_ / + (double)kAudioSr); + s += 0.4 * buzz; + } + s *= 3.0; + double q = fas_clamp(s, -1.0, 1.0) * 32767.0; + audio_.push_back((int16_t)lround(q)); + audio_written_++; + } + } + + static void write_u16le(FILE* f, uint16_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); + } + static void write_u32le(FILE* f, uint32_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); + fputc((int)((v >> 16) & 0xff), f); + fputc((int)((v >> 24) & 0xff), f); + } + + struct { + double x, x_c, w; + } state_; // x (rotor), x_c (cmd), w + uint8_t D_; // steps per full step — the force-curve period + double J_; // rotor moment of inertia + double Fmax_; // peak magnetic torque + double friction_static_; // Coulomb friction floor (absolute) + double friction_viscous_; // friction increase per step/s (absolute) + uint32_t ticks_; // accumulated wall clock + double sim_time_; // accumulated simulated time (s) + double peak_abs_delta_; // peak |x - x_c| since reset + double slip_f_; // low-passed rotor/field speed mismatch + bool stall_ever_; // slipped at any time since reset + double cur_f_, cur_gate_, cur_disp_, cur_stalled_; // audio source + double cur_env_; // speed envelope [0:1] + double phase_; // continuous hum phase (rad) + std::vector audio_; // recorded PCM samples + uint32_t audio_written_; // samples already emitted + std::vector trace_; // decimated gnuplot rows + unsigned long trace_decim_; // emit 1 row per this many sub-steps + unsigned long trace_n_; // sub-steps seen since trace_begin + int trace_phase_; // test-labelled phase tag + observed_s last_; +}; + +#else // !FAS_PHYSICAL_STEPPER_ENABLED — inert stub, keeps the ideal stepper + +// Placeholder so callers compile unchanged when the plant is not opted in. +class PhysicalStepper { + public: + PhysicalStepper(uint8_t = 64, double = 0, double = 0, double = 0, + double = 0) { + reset(); + } + void reset() {} + observed_s step(int, bool, uint16_t) { return zero(); } + struct Cmd { + int steps; + bool count_up; + uint16_t ticks; + }; + observed_s run(const Cmd*, int) { return zero(); } + int32_t getCurrentPosition() const { return 0; } + uint32_t total_ticks() const { return 0; } + double peak_abs_delta() const { return 0; } + bool stall_ever() const { return false; } + double friction_force(double) const { return 0; } + double magnetic_torque(double) const { return 0; } + void rotate(double) {} + void plot_row(FILE*, uint8_t, const observed_s&) {} + const observed_s& last() const { return zero(); } + double x() const { return 0; } + double x_c() const { return 0; } + double delta() const { return 0; } + double speed() const { return 0; } + void trace_begin(unsigned long) {} + void trace_set_phase(int) {} + size_t trace_dump(const char*) { return 0; } + size_t trace_rows() const { return 0; } + bool to_wav(const char*, uint32_t) { return false; } + uint32_t audio_samples() const { return 0; } + uint32_t audio_sample_count() const { return 0; } + int16_t audio_sample(uint32_t) const { return 0; } + + private: + static observed_s& zero() { + static observed_s s = {0, 0, 0, 0, 0, 0, 0, false}; + return s; + } +}; + +#endif // FAS_PHYSICAL_STEPPER_ENABLED +#endif // FAS_PHYSICAL_STEPPER_H diff --git a/tests/host/rmc_test.cpp b/tests/host/rmc_test.cpp new file mode 100644 index 0000000..b3ff56f --- /dev/null +++ b/tests/host/rmc_test.cpp @@ -0,0 +1,92 @@ +#include +#include +#include +#include + +#include "log2/Log2Representation.h" +#include "fas_ramp/RampCalculator.h" + +// Not a real test case + +int main() { + uint32_t res; + + // Calculation is pre_calc/sqrt(steps) + // + float ramp_acceleration = 10000.0; + uint32_t max_speed_in_ticks = 1600; + + struct ramp_config_s c; + c.init(); + c.parameters.setAcceleration(ramp_acceleration); + c.parameters.setSpeedInTicks(max_speed_in_ticks); + c.update(); + + char fname[100]; + snprintf(fname, 100, "ramp.gnuplot"); + FILE* gp_file = fopen(fname, "w"); + fprintf(gp_file, "$data <= s ? rs - s : s - rs; + uint32_t err_ticks = + ticks >= ticks_back ? ticks - ticks_back : ticks_back - ticks; + float speed = 16000000.0 / float(ticks); + float speed_back = 16000000.0 / float(ticks_back); + old_speed = speed; + float err_speed = + speed <= speed_back ? speed - speed_back : speed_back - speed; + printf("%d: %d %d %f %d delta=%d delta_ticks=%d speed=%f\n", s, + 16000000 / ticks, ticks, float(sum_ticks) / 16000000.0, rs, err, + err_ticks, err_speed); + fprintf(gp_file, "%d %f %d %d %d %d %d %f %f\n", s, + float(sum_ticks) / 16000000.0, 16000000 / ticks, ticks, rs, err, + err_ticks, err_speed, ideal_speed); + } + fprintf(gp_file, "EOF\n"); + fprintf(gp_file, "set terminal pngcairo size 1024,768\n"); + fprintf(gp_file, "set output \"%s.png\"\n", fname); + fprintf(gp_file, + "set multiplot title \"Acceleration=%f max speed=%d steps/s\" layout " + "2,2 columnsfirst margins 0.1,0.9,0.1,0.9 spacing 0.1 columnsfirst\n", + ramp_acceleration, 16000000 / max_speed_in_ticks); + + fprintf(gp_file, "set xlabel \"ramp steps\"\n"); + fprintf(gp_file, "set ylabel \"speed in steps/s\"\n"); + fprintf( + gp_file, + "plot $data using 1:3 with line title \"step to speed dependency\"\n"); + + fprintf(gp_file, "set xlabel \"ramp steps\"\n"); + fprintf(gp_file, "set ylabel \"recovered ramp steps\"\n"); + fprintf(gp_file, + "plot $data using 1:5 with line title \"steps(speed(steps))\"\n"); + + fprintf(gp_file, "set xlabel \"time in s\"\n"); + fprintf(gp_file, "set ylabel \"speed in steps/s\"\n"); + fprintf(gp_file, "plot $data using 2:3 with line title \"speed over time\","); + fprintf(gp_file, " $data using 2:9 with line title \"ideal speed\"\n"); + + fprintf(gp_file, "set xlabel \"time in s\"\n"); + fprintf(gp_file, "set ylabel \"speed error in steps/s\"\n"); + fprintf(gp_file, "set yrange [-10:10]\n"); + fprintf( + gp_file, + "plot $data using 2:8 with line title \"speed error on ramp change\","); + fprintf( + gp_file, + " $data using 2:($3-$9) with line title \"speed error to ideal\"\n"); + + fprintf(gp_file, "unset multiplot\n"); + + fclose(gp_file); + // assert(false); + return 0; +} diff --git a/tests/host/test_01.cpp b/tests/host/test_01.cpp new file mode 100644 index 0000000..d7d255f --- /dev/null +++ b/tests/host/test_01.cpp @@ -0,0 +1,115 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); +} + +void basic_test() { + puts("basic_test..."); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + assert(0 == s.getCurrentPosition()); + assert(s.isQueueEmpty()); + assert(s.isQueueEmpty()); + struct stepper_command_s cmd = { + .ticks = 10000, .steps = 100, .count_up = true}; + AqeResultCode res = s.addQueueEntry(&cmd); + assert(res == AQE_OK); + assert(!s.isQueueEmpty()); +} + +void queue_full() { + puts("queue_full..."); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + assert(0 == s.getCurrentPosition()); + assert(s.isQueueEmpty()); + assert(s.isQueueEmpty()); + printf("Queue read/write = %d/%d\n", fas_queue[0].read_idx, + fas_queue[0].next_write_idx); + struct stepper_command_s cmd = { + .ticks = 10000, .steps = 100, .count_up = true}; + for (int i = 0; i < QUEUE_LEN - 1; i++) { + s.addQueueEntry(&cmd); + assert(!s.isQueueEmpty()); + assert(!s.isQueueFull()); + printf("Queue read/write = %d/%d\n", fas_queue[0].read_idx, + fas_queue[0].next_write_idx); + } + s.addQueueEntry(&cmd); + printf("Queue read/write = %d/%d\n", fas_queue[0].read_idx, + fas_queue[0].next_write_idx); + assert(!s.isQueueEmpty()); + assert(s.isQueueFull()); + puts("...done"); +} + +void queue_out_of_range() { + AqeResultCode res; + + puts("queue_out_of_range..."); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + assert(s.isQueueEmpty()); + assert(0 == s.getCurrentPosition()); + assert(s.isQueueEmpty()); + assert(s.isQueueEmpty()); + + uint16_t ticks = s.getMaxSpeedInTicks(); + ticks = ticks - 1; + struct stepper_command_s cmd2 = { + .ticks = ticks, .steps = 255, .count_up = true}; + + res = s.addQueueEntry(&cmd2); + test(res == AQE_ERROR_TICKS_TOO_LOW, "Too low ticks should trigger an error"); + assert(s.isQueueEmpty()); + + struct stepper_command_s cmd3 = { + .ticks = MIN_CMD_TICKS - 1, .steps = 1, .count_up = true}; + + res = s.addQueueEntry(&cmd3); + test(res == AQE_ERROR_TICKS_TOO_LOW, + "Too short command time should trigger an error"); + assert(s.isQueueEmpty()); +} + +void end_pos_test() { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + assert(0 == s.getPositionAfterCommandsCompleted()); + struct stepper_command_s cmd = {.ticks = 65535, .steps = 1, .count_up = true}; + + assert(AQE_OK == s.addQueueEntry(&cmd)); + assert(1 == s.getPositionAfterCommandsCompleted()); +} + +int main() { + // assert(sizeof(struct queue_entry) == 6); + basic_test(); + queue_out_of_range(); + queue_full(); + end_pos_test(); + printf("TEST_01 PASSED\n"); +} diff --git a/tests/host/test_02.cpp b/tests/host/test_02.cpp new file mode 100644 index 0000000..e477f48 --- /dev/null +++ b/tests/host/test_02.cpp @@ -0,0 +1,303 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void with_empty_queue() { + printf("Test with empty queue\n"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + s.setSpeedInUs(10000); + s.setAcceleration(100); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(1000); + s.fill_queue(); + assert(!s.isQueueEmpty()); + for (int i = 0; i < 1000; i++) { + if (false) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue_A.entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + } + test(!s.isRampGeneratorActive(), "too many commands created"); + printf("min_dt=%u\n", rc.min_dt); + test(rc.min_dt == 160000, "max speed not reached"); + } + + void with_pars(const char* name, int32_t steps, uint32_t travel_dt, + uint32_t accel, bool reach_max_speed, float min_time, + float max_time, float allowed_ramp_time_delta, + bool call_moveTo_repeatedly = false, + bool call_setAccelertion_repeatedly = false, + bool alternatingAccelerationValue = false, + bool reversing_allowed = false, + uint32_t linear_acceleration_steps = 0, + uint32_t jump_step = 0) { + printf("Test %s test_with_pars steps=%d travel_dt=%d accel=%d dir=%s\n", + name, steps, travel_dt, accel, reach_max_speed ? "CW" : "CCW"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + s.setDirectionPin(0); + RampChecker rc = RampChecker(); + rc.reversing_allowed = reversing_allowed; + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + assert(0 == s.setSpeedInUs(travel_dt)); + s.setAcceleration(accel); + s.setLinearAcceleration(linear_acceleration_steps); + s.setJumpStart(jump_step); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + char fname[100]; + snprintf(fname, 100, "test_02_%s.gnuplot", name); + rc.start_plot(fname); + for (int i = 0; i < steps * 100; i++) { + if (call_moveTo_repeatedly) { + s.moveTo(steps); + } + if (call_setAccelertion_repeatedly) { + if (alternatingAccelerationValue) { + s.setAcceleration(accel + (i & 1) * 100); + } else { + s.setAcceleration(accel); + } + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue_A.entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs (old=%.6fs)\n", planned_time, + old_planned_time_in_buffer); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + // Empty the queue + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue_A.entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + rc.finish_plot(); + printf("TEST=%s\n", name); + test(!s.isRampGeneratorActive(), "too many commands created"); + printf("Total time %f < %f < %f ?\n", min_time, + rc.total_ticks / 16000000.0, max_time); + test(rc.total_ticks / 16000000.0 > min_time, "ramp too fast"); + test(rc.total_ticks / 16000000.0 < max_time, "ramp too slow"); + if (reach_max_speed) { + printf("%d = %d ?\n", rc.min_dt, travel_dt * 16); + test(rc.min_dt == travel_dt * 16, "max speed not reached"); + } else { + printf("%d > %d ?\n", rc.min_dt, travel_dt * 16); + test(rc.min_dt > travel_dt * 16, "max speed reached"); + } + float up_time, down_time; + if (reach_max_speed) { + printf("Ramp time up/coast/down/total="); + up_time = 1.0 * rc.accelerate_till / 16000000.0; + down_time = (1.0 * rc.total_ticks - 1.0 * rc.coast_till) / 16000000.0; + printf(" %f", 1.0 * rc.accelerate_till / 16000000.0); + printf(" %f", 1.0 * (rc.coast_till - rc.accelerate_till) / 16000000.0); + printf(" %f", 1.0 * (rc.total_ticks - rc.coast_till) / 16000000.0); + printf(" %f\n", 1.0 * rc.total_ticks / 16000000.0); + assert(rc.total_ticks > rc.coast_till); + } else { + printf("Ramp time up/down/total ="); + up_time = 1.0 * rc.accelerate_till / 16000000.0; + down_time = + (1.0 * rc.total_ticks - 1.0 * rc.accelerate_till) / 16000000.0; + printf(" %f", 1.0 * rc.accelerate_till / 16000000.0); + printf(" %f", 1.0 * (rc.total_ticks - rc.accelerate_till) / 16000000.0); + printf(" %f\n", 1.0 * rc.total_ticks / 16000000.0); + } + // turned off + // test(abs(up_time - down_time) < + // 0.5 * (up_time + down_time) * allowed_ramp_time_delta, + // "assymmetric ramp"); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + + float nc = 0.0; // if new ramp calculation is enabled + + test.with_empty_queue(); + // steps ticks_us accel maxspeed min/max_total_time + + // jumps in speed in real on esp32 + test.with_pars("f1", 1000, 4300, 10000, true, 4.5 - 0.2, 4.5 + 0.2, 0.5, true, + true); + + // ramp 2*2s, 2*200 steps, coasting: 9600steps, 48s + test.with_pars("f2", 10000, 5000, 100, true, 2 * 2.0 + 48.0 - 0.2 - 0.4 * nc, + 2 * 2.0 + 48.0 + 0.2, 0.2); + // ramp 2*0.02s, 2*2 steps, coasting: 1596 steps, 7.98s + test.with_pars("f3", 1600, 5000, 10000, true, 7.94, 8.02, 0.2); + // ramp 2*0.2s, 2*20 steps, coasting: 1560 steps, 7.8s + test.with_pars("f4", 1600, 5000, 1000, true, 2 * 0.2 + 7.8 - 0.1, + 2 * 0.2 + 7.8 + 0.1, 0.2); + // ramp 2*1s, 5000 steps, coasting: 5000steps, 0.5s + test.with_pars("f5", 15000, 100, 10000, true, 2 * 1.0 + 0.5 - 0.1, + 2 * 1.0 + 0.5 + 0.1, 0.2); + // ramp 2*0.02s, 2*2 steps, coasting: 96steps, 0.48 + test.with_pars("f6", 100, 5000, 10000, true, 2 * 0.02 + 0.48 - 0.02, + 2 * 0.02 + 0.48 + 0.02, 0.2); + // ramp 2s, 20000 steps => only ramp 2*0.4s + test.with_pars("f7", 1600, 50, 10000, false, 2 * 0.4 - 0.02 - 0.4 * nc, + 2 * 0.4 + 0.02, 0.2); + // ramp 2*4s, 2*8000 steps, coasting 112000steps, 28s + test.with_pars("f8", 128000, 250, 1000, true, 2 * 4.0 + 28.0 - 0.1 - 0.1 * nc, + 2 * 4.0 + 28.0 + 0.1, 0.2); + // ramp 2*4s, 2*8000 steps, coasting 56000steps, 14s + test.with_pars("f9", 72000, 250, 1000, true, 2 * 4.0 + 14.0 - 0.1 - 0.1 * nc, + 2 * 4.0 + 14.0 + 0.1, 0.2); + // ramp 2*4s, 2*8000 steps, coasting 28000steps, 7s + test.with_pars("f10", 44000, 250, 1000, true, 2 * 4.0 + 7.0 - 0.1 - 0.1 * nc, + 2 * 4.0 + 7.0 + 0.1, 0.2); + // ramp 2*4s, 2*8000 steps, coasting 2steps, 0.0005s + // fails with 16030 + test.with_pars("f11", 16040, 250, 1000, true, 2 * 4.0 + 0.0 - 0.1 - 0.1 * nc, + 2 * 4.0 + 0.1 + 0.1, 0.2); + // ramp 2*50s => 2*1s + test.with_pars("f12", 1000, 20, 1000, false, 2 * 1.0 - 0.15, 2 * 1.0 + 0.1, + 0.2); + + // The following five ramps are too fast. + // The first step should come after ~0.6s and + // the second after 0.89s. Implementation issues first step immediately + // with pause to 2nd step of 0.36s (actually 0.315s). + // So the first steps are issued within 0.36s instead of 0.89s. + // + // The implementation issues in addition the last two steps with 0.315s pause + float rd = 0.7; // rd means ramp deviation + // + // ramp 2*50s, thus with 500steps max speed not reached. 250steps need 10s + test.with_pars("f13", 500, 4000, 5, false, 20.0 - rd - 0.1 - 1.4 * nc, + 20.0 - rd + 0.2, 0.2); + test.with_pars("f14", 2000, 4000, 5, false, 40.0 - rd - 0.1 - 1.7 * nc, + 40.0 - rd + 0.2, 0.2); + // ramp 2*50s with 2*6250 steps => 100 steps at max speed using 0.4s + test.with_pars("f15", 12600, 4000, 5, true, 100.0 + 0.4 - 0.3 - rd - 2.3 * nc, + 100.0 + 0.4 - rd + 0.24, 0.2); + // ramp 2*50s with 2*6250 steps => 4000 steps at max speed using 16s + test.with_pars("f16", 16500, 4000, 5, true, 116.0 - 0.3 - rd - 2.2 * nc, + 116.0 + 0.23 - rd, 0.2); + // slow ramp: 2*50steps, 2*10s + rd = 1.4; + test.with_pars("f17", 100, 40, 1, false, 20.0 - 0.1 - rd - 2.0 * nc, + 20.0 + 0.1 - rd, 1.0); + + // jumps in speed in real => WORKS NOW + test.with_pars("f18", 256000, 40, 5000, true, 15.2 - 0.1, 15.2 + 0.2, 0.2); + + // ramp time 625s, 7812500 steps + // test.with_pars("f19", 2000000, 40, 40, false, 2*223.0, 2*223.0); + + // name, steps, travel_dt, accel, reach_max_speed, min_time, max_time, + // allowed_ramp_time_delta slow ramp time Those are anomalies (see github + // issue #8) on avr, but not on PC + // test.with_pars("f20", 50000, 270000, 10, true, 62.0, 63.0, 1.0); + test.with_pars("f20", 10, 1000000, 1, true, 9.9, 10.1, 1.0); + + // no ramp time, just constant run time + test.with_pars("f21", 15000, 4000, 100000, true, 50.9, 60.1, 0.1); + test.with_pars("f22", 14634, 4100, 100000, true, 50.9, 60.1, 0.1); + + // single step + test.with_pars("f23", 1, 100, 1000, false, 0.02, 0.05, 0.1); + + // try to identify issue #40 + test.with_pars("f24a", 5000, 200, 9999, true, 1.48 + 0.1 * nc, 1.5 + 0.1 * nc, + 0.1, true, true, false, true); + test.with_pars("f24b", 5000, 200, 9999, true, 1.48 - 0.04 * nc, + 1.50 - 0.04 * nc, 0.1, false, false, false); + test.with_pars("f24c", 5000, 200, 9999, true, 1.48 - 0.04 * nc, + 1.50 - 0.04 * nc, 0.1, false, false, true); + test.with_pars("f24d", 5000, 200, 9999, true, 1.48 - 0.04 * nc, + 1.50 - 0.04 * nc, 0.1, true, false, true); + + test.with_pars("f25", 1000, 40, 0x7fffffff, true, 0.039, 0.041, 0.1); + + // very short ramp. detected by esp32_hw_based tests seq_06.sh + test.with_pars("seq_06.sh", 54, 40, 1000000, false, 0.012, 0.018, 0.1); + + // ramp with jump start + test.with_pars("f5_jumpstart", 15000, 100, 10000, true, 2 * 1.0 + 0.0 - 0.1, + 2 * 1.0 + 0.5 + 0.1, 0.2, false, false, false, false, 0, 100); + + // ramp with linea acceleration + test.with_pars("f5_linear_a", 15000, 100, 10000, true, 3, 4, 0.2, false, + false, false, false, 1000); + + printf("TEST_02 PASSED\n"); + return 0; +} diff --git a/tests/host/test_03.h b/tests/host/test_03.h new file mode 100644 index 0000000..f38ee4d --- /dev/null +++ b/tests/host/test_03.h @@ -0,0 +1,438 @@ +#include + +struct const_tab { + uint32_t val_nom; + uint32_t val_denom; + bool squared; + log2_value_t c; +}; + +bool perform_test() { +#define NR_OF_CONSTANTS 13 + static const struct const_tab constants[NR_OF_CONSTANTS] = { + {1, 1, false, LOG2_CONST_1}, + {16000000, 1, false, LOG2_CONST_16E6}, + {3, 2, false, LOG2_CONST_3_DIV_2}, + {500, 1, false, LOG2_CONST_500}, + {1000, 1, false, LOG2_CONST_1000}, + {2000, 1, false, LOG2_CONST_2000}, + {32000, 1, false, LOG2_CONST_32000}, + {11313708, 1, false, LOG2_CONST_16E6_DIV_SQRT_OF_2}, + {21000000, 1, false, LOG2_CONST_21E6}, + {42000, 1, false, LOG2_CONST_42000}, + // The additional 4000 to make the test case pass + {14849242 + 4000, 1, false, LOG2_CONST_21E6_DIV_SQRT_OF_2}, + {16000000, 2, true, LOG2_CONST_128E12}, // (16e6)^2 / 2 + {21000000, 2, true, LOG2_CONST_2205E11} // (21e6)^2 / 2 + }; + uint16_t l1; + log2_value_t p1; + + trace("Check leading_zeros()"); + for (int16_t x_8 = 0; x_8 <= 255; x_8++) { + uint8_t leading = leading_zeros(x_8); + test(x_8 < (1 << (8 - leading)), "leading zeros too much"); + test(x_8 >= (0x80 >> leading), "leading zeros too less"); + } + + trace("Check conversion u8 <=> log2"); + p1 = log2_from((uint8_t)1); + l1 = log2_to_u16(p1); + xprintf("%x %d\n", p1, l1); + test(p1 == 0x0000, "value 1"); + test(l1 == 1, "value 1"); + + trace("Check conversion u8 <=> log2 by shift 8bit"); + for (uint8_t n = 1; n < 8; n++) { + uint8_t v = 1 << n; + p1 = log2_from((uint8_t)v); + l1 = log2_to_u16(p1); + xprintf("8bit: %x %d\n", p1, l1); + test(p1 == ((int16_t)n) << 9, "value"); + test(l1 == v, "value"); + } + + trace("Check conversion u8 <=> log2 by shift 16bit"); + for (uint8_t n = 1; n < 16; n++) { + uint16_t v = 1 << n; + p1 = log2_from((uint16_t)v); + l1 = log2_to_u16(p1); + xprintf("16bit: %x %d\n", p1, l1); + test(p1 == ((int16_t)n) << 9, "value"); + test(l1 == v, "value"); + } + + trace("Check conversion u8 <=> log2 by shift 32bit"); + for (uint8_t n = 1; n < 32; n++) { + uint32_t v = 1; + v <<= n; + p1 = log2_from((uint32_t)v); + uint32_t res = log2_to_u32(p1); + xprintf("32bit: %x %u\n", p1, res); + test(p1 == (((int16_t)n) << 9), "value"); + test(res == v, "value"); + } + + trace("Check conversion u8 <=> log2 for all values"); + for (uint8_t x_8 = 255; x_8 > 0; x_8--) { + p1 = log2_from((uint8_t)x_8); + uint16_t res_16 = log2_to_u16(p1); + if (res_16 != x_8) { + xprintf("%u => %x => %u\n", x_8, p1, res_16); + } + test(res_16 == x_8, "conversion error from uint8_t and back to uint16_t"); + } + + for (uint8_t n = 1; n <= 8; n++) { + for (uint8_t x_8 = 255; x_8 > 0; x_8--) { + uint16_t x_16 = x_8; + x_16 <<= n; + p1 = log2_from((uint8_t)x_8); + p1 = log2_shl(p1, n); + uint16_t res_16 = log2_to_u16(p1); + uint16_t delta = x_16 - res_16; + if (res_16 > x_16) { + delta = res_16 - x_16; + } + uint16_t limit = 1; + limit <<= n - 1; + if (delta > limit) { + xprintf("%u: %u => %x => %u, shifted: %d\n", x_8, x_16, p1, res_16, n); + } + test(delta <= limit, + "conversion error from uint8_t and back to uint16_t with shift"); + } + } + + for (uint8_t n = 1; n <= 24; n++) { + for (uint8_t x_8 = 255; x_8 > 0; x_8--) { + uint32_t x_32 = x_8; + x_32 <<= n; + p1 = log2_from((uint8_t)x_8); + p1 = log2_shl(p1, n); + uint32_t res_32 = log2_to_u32(p1); + uint32_t delta = x_32 - res_32; + if (res_32 > x_32) { + delta = res_32 - x_32; + } + uint32_t limit = 1; + limit <<= n - 1; + if (delta > limit) { + xprintf("%u: %u => %x => %u, shifted: %d\n", x_8, x_32, p1, res_32, n); + } + test(delta <= limit, + "conversion error from uint8_t and back to uint32_t with shift"); + } + } + trace("Check conversion u16 <=> log2"); + uint16_t limit = 0x100; + uint16_t trigger_16 = 0x8000; + for (uint16_t x_16 = 0xffff; x_16 > 0; x_16--) { + if ((x_16 & trigger_16) == 0) { + limit >>= 1; + trigger_16 >>= 1; + } + log2_value_t p = log2_from((uint16_t)x_16); + uint16_t res_16 = log2_to_u16(p); + uint16_t delta = x_16 - res_16; + if (res_16 > x_16) { + delta = res_16 - x_16; + } + if (delta > limit) { + xprintf("%x => %x => %x (limit=%x)\n", x_16, p, res_16, limit); + } + test(delta <= limit, "conversion error from uint16_t and back to uint16_t"); + } + + for (uint8_t n = 1; n <= 16; n++) { + uint32_t msb = 32768; + for (uint16_t x_16 = 65535; x_16 > 256; x_16--) { + if ((x_16 & msb) == 0) { + msb >>= 1; + } + uint32_t x_32 = x_16; + x_32 <<= n; + p1 = log2_from((uint16_t)x_16); + p1 = log2_shl(p1, n); + uint32_t res_32 = log2_to_u32(p1); + uint32_t delta = x_32 - res_32; + uint32_t limit = (msb << n) >> 8; + limit += limit >> 2; + if (res_32 > x_32) { + delta = res_32 - x_32; + } + if (delta > limit) { + xprintf("%u: %u => %x => %u, shifted: %d, delta: %d > %d\n", x_16, x_32, + p1, res_32, n, delta, limit); + } + test(delta <= limit, + "conversion error from uint16_t and back to uint32_t with shift"); + } + } + + p1 = log2_from((uint32_t)0x10000); + test(log2_to_u16(p1) == 0xffff, "wrong overflow 16bit"); + p1 = log2_from((uint32_t)0x80000000); + p1 = log2_shl(p1, 1); + test(log2_to_u32(p1) == 0xffffffff, "wrong overflow 32bit"); + +#ifndef SIMULATOR + trace("Check conversion u32 <=> log2"); + uint32_t trigger_32 = 0x80000000; + uint32_t delta_32 = 0x01000000; + for (uint32_t x_32 = 0xffffffff; x_32 > 0; x_32 -= delta_32) { + if ((x_32 & trigger_32) == 0) { + trigger_32 >>= 1; + delta_32 >>= 1; + if (delta_32 == 0) { + delta_32 = 1; + } + } + log2_value_t px = log2_from((uint32_t)x_32); + uint32_t res_32 = log2_to_u32(px); + uint32_t delta = x_32 - res_32; + if (res_32 > x_32) { + delta = res_32 - x_32; + } + if (delta > delta_32 + 1) { + xprintf("%x => %x => %x (delta=%x > %x)\n", x_32, px, res_32, delta, + delta_32); + } + test(delta <= delta_32 + 1, + "conversion error from uint32_t and back to uint32_t"); + } + + trace("Check multiply"); + for (int16_t sa = -40; sa <= 40; sa++) { + for (uint32_t a_32 = 1; a_32 <= 0x1ff; a_32++) { + for (uint32_t b_32 = 1; b_32 <= 0x1ff; b_32++) { + p1 = log2_from(a_32); + log2_value_t p2 = log2_from(b_32); + if (sa > 0) { + p1 = log2_shl(p1, sa); + } else if (sa < 0) { + p1 = log2_shr(p1, -sa); + } + log2_value_t p = log2_multiply(p1, p2); + if (sa > 0) { + p = log2_shr(p, sa); + } else if (sa < 0) { + p = log2_shl(p, -sa); + } + uint32_t res = log2_to_u32(p); + uint32_t real_res = a_32 * b_32; + uint32_t repr_real = log2_to_u32(log2_from(real_res)); + uint32_t delta = res - repr_real; + if (res < repr_real) { + delta = repr_real - res; + } + uint32_t limit = real_res >> 7; + if (delta > limit) { + xprintf("%d*%d=%d ~ %d =?= %d, diff=%d\n", a_32, b_32, a_32 * b_32, + repr_real, res, (int32_t)res - (int32_t)repr_real); + } + test(delta <= limit, "log2_multiply error"); + } + } + } +#endif + + trace("Check log2 constants"); + bool error = false; + for (uint8_t i = 0; i < NR_OF_CONSTANTS; i++) { + const struct const_tab* dut = &constants[i]; + log2_value_t val = log2_from(dut->val_nom); + if (dut->squared) { + val += val; + } + if (dut->val_denom > 1) { + log2_value_t val_denom = log2_from(dut->val_denom); + val -= val_denom; + } + log2_value_t c = dut->c; + if (c != val) { + xprintf("(%d/%d)^%d => %x != %x\n", dut->val_nom, dut->val_denom, + dut->squared ? 2 : 1, val, c); + error = true; + } + } + test(!error, "constants"); + + trace("Check rsqrt"); + for (int16_t sa = -20; sa <= 20; sa++) { + for (uint32_t a_32 = 1; a_32 <= 0x1ff; a_32++) { + p1 = log2_from(a_32); + if (sa > 0) { + p1 = log2_shl(p1, sa); + } else if (sa < 0) { + p1 = log2_shr(p1, -sa); + } + log2_value_t p = log2_rsqrt(p1); + log2_value_t pe = + log2_multiply(p1, log2_multiply(p, p)); // sqrt not yet tested + // pe should be approximately 1 + uint32_t res = log2_to_u32(log2_shl(pe, 16)); + int32_t diff = (int32_t)res - 0x10000; + if (abs(diff) > 384) { + xprintf("a=%d log2(x)=%x log2(rsqrt(x))=%x log2(rsqrt(x)^2*x)=%x ", + a_32, p1, p, pe); + xprintf("shift=%d rsqrt(%d)^2*%d*0x10000=%x, diff=%d\n", sa, a_32, a_32, + res, diff); + } + test(abs(diff) <= 384, "rsqrt error"); + } + } + + trace("Check square"); + for (int16_t sa = -20; sa <= 20; sa++) { + for (uint32_t a_32 = 1; a_32 <= 0x1ff; a_32++) { + p1 = log2_from(a_32); + if (sa > 0) { + p1 = log2_shl(p1, sa); + } else if (sa < 0) { + p1 = log2_shr(p1, -sa); + } + log2_value_t p = log2_square(p1); + log2_value_t pe = log2_multiply(p1, p1); + int32_t diff = (int32_t)p - (int32_t)pe; + if (diff > 1) { // square has better precision than multiply + xprintf("a=%d log2(x)=%x log2(square(x))=%x log2(x*x)=%x ", a_32, p1, + p, pe); + xprintf("shift=%d, diff=%d\n", sa, 0); + } + test(diff <= 1, "square error"); + } + } + + trace("Check reciprocal square"); + for (int16_t sa = -20; sa <= 20; sa++) { + for (uint32_t a_32 = 1; a_32 <= 0x1ff; a_32++) { + p1 = log2_from(a_32); + if (sa > 0) { + p1 = log2_shl(p1, sa); + } else if (sa < 0) { + p1 = log2_shr(p1, -sa); + } + log2_value_t p = log2_rsquare(p1); + + log2_value_t pe = log2_multiply(p, log2_square(p1)); + // pe should be approximately 1 + uint32_t res = log2_to_u32(log2_shl(pe, 16)); + int32_t diff = (int32_t)res - 0x10000; + if (abs(diff) > 384) { + xprintf("a=%d log2(x)=%x log2(rsquare(x))=%x log2(rsquare(x)*x^2)=%x ", + a_32, p1, p, pe); + xprintf("shift=%d rsquare(%d)*%d^2*0x10000=%x, diff=%d\n", sa, a_32, + a_32, res, diff); + } + test(abs(diff) <= 384, "rsquare error"); + } + } + + trace("Check reciprocal"); + for (int16_t sa = -20; sa <= 20; sa++) { + for (uint32_t a_32 = 1; a_32 <= 0x1ff; a_32++) { + p1 = log2_from(a_32); + if (sa > 0) { + p1 = log2_shl(p1, sa); + } else if (sa < 0) { + p1 = log2_shr(p1, -sa); + } + log2_value_t p = log2_reciprocal(p1); + + log2_value_t pe = log2_multiply(p, p1); + // xe should be approximately 1 + uint32_t res = log2_to_u32(log2_shl(pe, 16)); + int32_t diff = (int32_t)res - 0x10000; + if (abs(diff) > 384) { + xprintf( + "a=%d log2(x)=%x log2(reciprocal(x))=%x log2(reciprocal(x)*x)=%x ", + a_32, p1, p, pe); + xprintf("shift=%d reciprocal(%d)*%d*0x10000=%x, diff=%d\n", sa, a_32, + a_32, res, diff); + } + test(abs(diff) <= 384, "reciprocal error"); + } + } + + trace("Check specific use cases"); + log2_value_t x, x1, x2; + x1 = log2_from((uint32_t)0x0ffff); + x2 = log2_from((uint32_t)0x10100); + x = log2_multiply(x1, x2); + unsigned long back = log2_to_u32(x); + test(back == 0xffffffff, "overflow not catched"); + + x1 = log2_from((uint32_t)0x5555); + x2 = log2_from((uint32_t)0x0055); + x = log2_divide(x1, x2); + back = log2_to_u32(x); + xprintf("%x/%x=%x (back=%ld)\n", x1, x2, x, back); + test(back == 0x0101, "wrong division"); + + x1 = log2_from((uint32_t)0xf455); + x2 = log2_from((uint32_t)0x0030); + x = log2_divide(x1, x2); + back = log2_to_u32(x); + back--; // result is too high by one + xprintf("%x/%x=%x (%ld) f455/0030=%d\n", x1, x2, x, back, 0xf455 / 0x30); + test((back * 0x0030) <= 0xf455, "wrong division 1"); + test((back * 0x0031) > 0xf455, "wrong division 2"); + + x1 = log2_from((uint32_t)0xf4555); + x = log2_shl(x1, 4); + back = log2_to_u32(x); + xprintf("%x => %x (%lx)\n", x1, x, back); + test(back == 0xf44000, "wrong log2_shl"); + x1 = log2_from((uint32_t)0xf4555); + x = log2_shr(x1, 4); + back = log2_to_u32(x); + xprintf("%x => %x (%lx)\n", x1, x, back); + test(back == 0xf440, "wrong log2_shr"); + + x1 = log2_from((uint32_t)250); + x2 = log2_from((uint32_t)10000); + x = log2_divide(x1, x2); + back = log2_to_u32(x); + xprintf("%x/%x=%x (%ld)\n", x1, x2, x, back); + test(back == 0, "log2_divide 1"); + x = log2_multiply(x, x2); + back = log2_to_u32(x); + xprintf("%x/%x*%x=%x (%ld)\n", x1, x2, x2, x, back); + back--; // value is one too high + test(back == 249, "log2_divide 2"); + + x1 = log2_from((uint32_t)250); + x2 = log2_from((uint32_t)10000); + x = log2_divide(x1, x2); + back = log2_to_u32(x); + xprintf("%x/%x=%x (%ld)\n", x1, x2, x, back); + test(back == 0, "log2_divide"); + x = log2_shl(x, 10); + back = log2_to_u32(x); + xprintf("log2_shl(%x/%x,10)=%x (%ld)\n", x1, x2, x, back); + test(back == 25, "log2_divide/log2_shl"); + + x1 = log2_from((uint32_t)1600); + x2 = log2_from((uint32_t)1000000); + x = log2_divide(x1, x2); + back = log2_to_u32(x); + xprintf("%x/%x=%x (%ld)\n", x1, x2, x, back); + test(back == 0, "log2_divide"); + x = log2_shl(x, 20); + back = log2_to_u32(x); + xprintf("log2_shl(%x/%x,20)=%x (%ld)\n", x1, x2, x, back); + test(back + 2 == 1678, "log2_divide/log2_shl"); + x = log2_shr(x, 20); + back = log2_to_u32(x); + xprintf("log2_shr(log2_shl(%x/%x,20),20)=%x (%ld)\n", x1, x2, x, back); + test(back == 0, "log2_divide/log2_shl"); + + x1 = log2_value_t((uint32_t)1500); + x = log2_pow_div_3(x1); + xprintf("%d/3=%d\n", x1, x); + // +1 is deviation + test(x + 1 == 500, "log2_pow_div_3"); + + return (error_cnt == 0); +} diff --git a/tests/host/test_04.cpp b/tests/host/test_04.cpp new file mode 100644 index 0000000..d752741 --- /dev/null +++ b/tests/host/test_04.cpp @@ -0,0 +1,165 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void speed_increase() { + puts("Test test_speed_increase"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 10000; + + // Increase speed to 400, then further to 300 + // Identified bug was a fast jump to 300 without acceleration + assert(s.isQueueEmpty()); + s.setSpeedInUs(400); + s.setAcceleration(1000); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + int speed_increased = false; + for (int i = 0; i < steps; i++) { + if (!speed_increased && (s.getCurrentPosition() >= 5000)) { + puts("Change speed"); + s.fill_queue(); // ensure queue is not empty + speed_increased = true; + s.setSpeedInUs(300); + s.move(steps); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + test(!s.isRampGeneratorActive(), "too many commands created"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } + + void speed_decrease() { + puts("Test test_speed_decrease"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 10000; + + // Increase speed to 400, then further to 300 + // Identified bug was a fast jump to 300 without acceleration + assert(s.isQueueEmpty()); + s.setSpeedInUs(400); + s.setAcceleration(1000); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + int speed_decreased = false; + uint32_t count_state_dec = 0; + for (int i = 0; i < steps; i++) { + if (!speed_decreased && (s.getCurrentPosition() >= 5000)) { + puts("Change speed"); + s.fill_queue(); // ensure queue is not empty + speed_decreased = true; + s.setSpeedInUs(500); + s.move(steps); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_DECELERATE) { + count_state_dec++; + } + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + test(!s.isRampGeneratorActive(), "too many commands created"); + test(count_state_dec > 10, "no deceleration to new speed"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + test.speed_increase(); + test.speed_decrease(); + printf("TEST_04 PASSED\n"); + return 0; +} diff --git a/tests/host/test_05.cpp b/tests/host/test_05.cpp new file mode 100644 index 0000000..1af1697 --- /dev/null +++ b/tests/host/test_05.cpp @@ -0,0 +1,159 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +StepperMotion* stepper; + +int enable_inject_on_mark = -1; +bool enable_stepper_manage_on_interrupts = false; +bool enable_stepper_manage_on_noInterrupts = false; +bool in_manage = false; + +#include "RampChecker.h" +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + void inject() { stepper->fill_queue(); } + void do_test() { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + stepper = &s; + + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 10000; + + // Increase speed to 400, then further to 300 + // Identified bug was a fast jump to 300 without acceleration + assert(s.isQueueEmpty()); + s.setSpeedInUs(400); + s.setAcceleration(10000); + in_manage = true; + s.fill_queue(); + in_manage = false; + assert(s.isQueueEmpty()); + assert(!s.isRunning()); + s.moveTo(3000); + assert(s.isRunning()); + in_manage = true; + s.fill_queue(); + in_manage = false; + assert(!s.isQueueEmpty()); + + float old_planned_time_in_buffer = 0; + int moveto_done = false; + for (int i = 0; i < steps; i++) { + if (!moveto_done && (s.getCurrentPosition() >= 500)) { + moveto_done = true; + s.moveTo(4000); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + in_manage = true; + if (!s.isRampGeneratorActive() && s.isQueueEmpty()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + in_manage = false; + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("%d: planned time in buffer: %.6fs\n", i, planned_time); + // This must be ensured, so that the stepper does not run out of commands + old_planned_time_in_buffer = planned_time; + } + test(!s.isRampGeneratorActive(), "too many commands created"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + printf("Total steps = %d\n", rc.pos); + assert(rc.pos == 4000); + + printf("TEST_05 Part PASSED\n"); + } +}; + +StepperMotionTest test; +void inject_fill_interrupt(int mark) { + if ((mark == enable_inject_on_mark) && !in_manage) { + in_manage = true; + test.inject(); + in_manage = false; + } +} +void noInterrupts() { + if (enable_stepper_manage_on_noInterrupts && !in_manage) { + in_manage = true; + test.inject(); + in_manage = false; + } +} +void interrupts() { + if (enable_stepper_manage_on_interrupts && !in_manage) { + in_manage = true; + test.inject(); + in_manage = false; + } +} +int main() { + enable_stepper_manage_on_interrupts = false; + enable_stepper_manage_on_noInterrupts = false; + enable_inject_on_mark = -1; + test.do_test(); + + enable_stepper_manage_on_interrupts = false; + enable_stepper_manage_on_noInterrupts = false; + enable_inject_on_mark = 0; + test.do_test(); + + enable_stepper_manage_on_interrupts = false; + enable_stepper_manage_on_noInterrupts = false; + enable_inject_on_mark = 1; + test.do_test(); + + enable_stepper_manage_on_interrupts = false; + enable_stepper_manage_on_noInterrupts = false; + enable_inject_on_mark = 2; + test.do_test(); + + enable_stepper_manage_on_interrupts = false; + enable_stepper_manage_on_noInterrupts = true; + enable_inject_on_mark = -1; + test.do_test(); + + enable_stepper_manage_on_interrupts = true; + enable_stepper_manage_on_noInterrupts = false; + enable_inject_on_mark = -1; + test.do_test(); + + printf("TEST_05 PASSED\n"); + return 0; +} diff --git a/tests/host/test_06.cpp b/tests/host/test_06.cpp new file mode 100644 index 0000000..1cb1539 --- /dev/null +++ b/tests/host/test_06.cpp @@ -0,0 +1,185 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void do_test1() { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 15000; + + // This sequence caused no stop: + // M1 N A100000 V4000 R15000 + // V4300 U + // S + + assert(s.isQueueEmpty()); + s.setSpeedInUs(4000); + s.setAcceleration(100000); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + bool speed_changed = false; + bool stop_initiated = false; + for (int i = 0; i < steps; i++) { + if (!speed_changed && (s.getCurrentPosition() >= 1000)) { + puts("Change speed to 4300us"); + s.fill_queue(); // ensure queue is not empty + speed_changed = true; + s.setSpeedInUs(4300); + s.applySpeedAcceleration(); + } + if (!stop_initiated && (s.getCurrentPosition() >= 2000)) { + puts("Init stop"); + s.fill_queue(); // ensure queue is not empty + stop_initiated = true; + s.stopMove(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() != steps, "has not stopped"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } + + void do_test2(uint32_t stop_at_position) { + printf("do_test2 with stop at %d\n", stop_at_position); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 15000; + + // This sequence does not run to position 9999: + // M1 N A100 V100 P9999 w100 S W P9999 + + assert(s.isQueueEmpty()); + s.setSpeedInUs(100); + s.setAcceleration(100); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.moveTo(9999); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + bool stop_initiated = false; + bool restarted = false; + for (int i = 0; i < steps; i++) { + if (!stop_initiated && (s.getCurrentPosition() >= stop_at_position)) { + puts("Init stop"); + s.fill_queue(); // ensure queue is not empty + stop_initiated = true; + s.stopMove(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + if (!s.isQueueEmpty()) { + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of + // commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + if (!s.isRampGeneratorActive()) { + if (restarted) { + break; + } + puts("Continue move to end position"); + rc.next_ramp(); + restarted = true; + s.moveTo(9999); + } + } + printf("do_test2 with stop at %d\n", stop_at_position); + test(!s.isRampGeneratorActive(), "too many commands created"); + printf("getCurrentPosition() = %d\n", s.getCurrentPosition()); + test(s.getCurrentPosition() == 9999, "has not reached end position"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + test.do_test1(); + test.do_test2(100); + test.do_test2(5000); + test.do_test2(9000); + printf("TEST_06 PASSED\n"); + return 0; +} diff --git a/tests/host/test_07.cpp b/tests/host/test_07.cpp new file mode 100644 index 0000000..4f3907e --- /dev/null +++ b/tests/host/test_07.cpp @@ -0,0 +1,128 @@ +#include +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void do_test(uint64_t dt) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + // Reproduce test sequence 06 + + assert(s.getDirectionPin() == PIN_UNDEFINED); + uint32_t speed_us = 100; + int32_t steps = 32000; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(10000); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + uint64_t next_speed_change = dt; + uint64_t mid_point_ticks = 0; + + char fname[100]; + snprintf(fname, 100, "test_07.gnuplot"); + rc.start_plot(fname); + for (int i = 0; i < 10 * steps; i++) { + if (rc.total_ticks > next_speed_change) { + next_speed_change += TICKS_PER_S / 10; + speed_us = 190 - speed_us; + printf("Change speed to %d\n", speed_us); + s.setSpeedInUs(speed_us); + s.applySpeedAcceleration(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + if ((mid_point_ticks == 0) && (rc.pos >= steps / 2)) { + mid_point_ticks = rc.total_ticks; + } + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + test(s.getCurrentPosition() <= steps, "has overshot"); + } + rc.finish_plot(); + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() == steps, "has not reached target position"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + + printf("Time coasting = %d\n", rc.time_coasting); + test(rc.time_coasting < 46000000, "too much coasting"); + + printf("mid point @ %" PRIu64 " => total = %" PRIu64 + ", total ticks = %" PRIu64 "\n", + mid_point_ticks, 2 * mid_point_ticks, rc.total_ticks); +#define ALLOWED_ASYMMETRY 1000000L + printf("%ld\n", ALLOWED_ASYMMETRY); + test(mid_point_ticks * 2 < rc.total_ticks + ALLOWED_ASYMMETRY, + "ramp is not symmetric 1"); + test(mid_point_ticks * 2 > rc.total_ticks - ALLOWED_ASYMMETRY, + "ramp is not symmetric 2"); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + for (uint64_t time_shift = 0; time_shift < TICKS_PER_S / 10; + time_shift += TICKS_PER_S / 7000) { + test.do_test(time_shift); + } + printf("TEST_07 PASSED\n"); + return 0; +} diff --git a/tests/host/test_08.cpp b/tests/host/test_08.cpp new file mode 100644 index 0000000..208e70a --- /dev/null +++ b/tests/host/test_08.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint32_t accel, uint32_t steps) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + // Reproduce test sequence 06 + + uint32_t speed_us = 40; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_08.gnuplot"); + rc.start_plot(fname); + for (int i = 0; i < 100 * steps; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + rc.finish_plot(); + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() == steps, "has not reached target position"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + test.ramp(100000, 400); + test.ramp(100000, 600); + for (uint32_t i = 0; i < 30; i++) { + test.ramp(1000000, 1000 + i); + } + printf("TEST_08 PASSED\n"); + return 0; +} diff --git a/tests/host/test_09.cpp b/tests/host/test_09.cpp new file mode 100644 index 0000000..8bcf73b --- /dev/null +++ b/tests/host/test_09.cpp @@ -0,0 +1,95 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint32_t steps) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t speed_us = 40; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(1000000); + s.fill_queue(); + assert(s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_09.gnuplot"); + rc.start_plot(fname); + for (int j = 0; j < 2; j++) { + s.move(steps); + for (int i = 0; i < 100 * steps; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of + // commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + } + rc.finish_plot(); + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() == 2 * steps, + "has not reached target position"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + test.ramp(53); + printf("TEST_09 PASSED\n"); + return 0; +} diff --git a/tests/host/test_10.cpp b/tests/host/test_10.cpp new file mode 100644 index 0000000..616160a --- /dev/null +++ b/tests/host/test_10.cpp @@ -0,0 +1,103 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void reduce_acceleration() { + puts("Test test_speed_decrease"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 100000; + + // Increase speed to 400, then further to 300 + // Identified bug was a fast jump to 300 without acceleration + assert(s.isQueueEmpty()); + s.setSpeedInUs(30); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.moveByAcceleration(17164); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + int accel_decreased = false; + uint32_t count_state_dec = 0; + for (int i = 0; i < steps * 10; i++) { + if (!accel_decreased && (s.getCurrentPosition() >= 35000)) { + puts("Change acceleration"); + accel_decreased = true; + s.moveByAcceleration(-1000); + s.fill_queue(); // ensure queue is not empty + } + if (accel_decreased && (s.getCurrentPosition() >= 37000)) { + test((s.rampState() & RAMP_STATE_MASK) != RAMP_STATE_COAST, + "Coasting is wrong state here"); + break; + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_DECELERATE) { + count_state_dec++; + } + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + test.reduce_acceleration(); + printf("TEST_10 PASSED\n"); + return 0; +} diff --git a/tests/host/test_11.cpp b/tests/host/test_11.cpp new file mode 100644 index 0000000..b739a85 --- /dev/null +++ b/tests/host/test_11.cpp @@ -0,0 +1,104 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void reduce_speed() { + puts("Test test_speed_decrease"); + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + int32_t steps = 100; + + // M1 A1000 V10000 P100 w300 V100000 U + assert(s.isQueueEmpty()); + s.setAcceleration(1000); + s.setSpeedInUs(10000); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.moveTo(100); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + int speed_decreased = false; + uint32_t count_state_dec = 0; + for (int i = 0; i < steps * 10; i++) { + if (!speed_decreased && (s.getCurrentPosition() >= 35)) { + puts("Change speed"); + speed_decreased = true; + s.setSpeedInUs(100000); + s.applySpeedAcceleration(); + s.fill_queue(); // ensure queue is not empty + } + if (speed_decreased && (s.getCurrentPosition() >= 90)) { + test((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_COAST, + "Coasting is required state here"); + break; + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_DECELERATE) { + count_state_dec++; + } + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + printf("Total time %f\n", rc.total_ticks / 16000000.0); +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +int main() { + StepperMotionTest test; + test.reduce_speed(); + printf("TEST_11 PASSED\n"); + return 0; +} diff --git a/tests/host/test_12.cpp b/tests/host/test_12.cpp new file mode 100644 index 0000000..9b4da8e --- /dev/null +++ b/tests/host/test_12.cpp @@ -0,0 +1,99 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint32_t accel, uint32_t speed_us, uint32_t steps, + bool reach_coasting) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_12.gnuplot"); + rc.start_plot(fname); + bool coast = false; + for (int i = 0; i < 100 * steps; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_COAST) { + coast = true; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + rc.finish_plot(); + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() == steps, "has not reached target position"); + test(coast == reach_coasting, "coasting target not met"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + test.ramp(1, 1000, 999000, false); + test.ramp(1, 1000, 1001000, true); + printf("TEST_12 PASSED\n"); + return 0; +} diff --git a/tests/host/test_13.cpp b/tests/host/test_13.cpp new file mode 100644 index 0000000..d7dc27a --- /dev/null +++ b/tests/host/test_13.cpp @@ -0,0 +1,109 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint32_t accel, uint32_t speed_us, uint32_t steps, + bool reach_coasting) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.move(steps); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_13.gnuplot"); + rc.start_plot(fname); + bool coast = false; + for (int i = 0; i < 100 * steps; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_COAST) { + coast = true; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + rc.finish_plot(); + test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() == steps, "has not reached target position"); + test(coast == reach_coasting, "coasting target not met"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + for (uint16_t s = 1; s <= 255; s++) { + printf("test with steps s=%d\n", s); + test.ramp(INT32_MAX, 50, s, false); + puts(""); + } + printf("TEST_13 PASSED\n"); + return 0; +} diff --git a/tests/host/test_14.cpp b/tests/host/test_14.cpp new file mode 100644 index 0000000..fa9d700 --- /dev/null +++ b/tests/host/test_14.cpp @@ -0,0 +1,102 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp() { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t speed_us = 1000000 / 3600; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(320); + s.fill_queue(); + assert(s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_14.gnuplot"); + rc.start_plot(fname); + s.runForward(); + for (int i = 0; i < 2000; i++) { + if (i == 1000) { + printf("Change speed\n"); + s.setSpeedInUs(10000); + s.applySpeedAcceleration(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of + // commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + // stop after + if (rc.total_ticks > TICKS_PER_S * 40) { + break; + } + } + rc.finish_plot(); + // test(!s.isRampGeneratorActive(), "too many commands created"); + test(s.getCurrentPosition() > 70000, "stepper runs too slow"); + test(s.getCurrentPosition() < 80000, "stepper runs too fast"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + test.ramp(); + printf("TEST_14 PASSED\n"); + return 0; +} diff --git a/tests/host/test_15.cpp b/tests/host/test_15.cpp new file mode 100644 index 0000000..55ecb21 --- /dev/null +++ b/tests/host/test_15.cpp @@ -0,0 +1,116 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint8_t forward_planning, uint32_t expected_steps) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t speed_us = 1000000 / 3600; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(320); + s.setForwardPlanningTimeInMs(forward_planning); + s.fill_queue(); + assert(s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + float sum_planning_time = 0; + float points = 0; + snprintf(fname, 100, "test_15_%dms.gnuplot", forward_planning); + rc.start_plot(fname); + s.runForward(); + for (int i = 0; i < 2000; i++) { + if (i == 1000) { + printf("Change speed\n"); + s.setSpeedInUs(10000); + s.applySpeedAcceleration(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + sum_planning_time += planned_time; + points += 1.0; + // This must be ensured, so that the stepper does not run out of + // commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + // stop after + if (rc.total_ticks > TICKS_PER_S * 40) { + break; + } + } + rc.finish_plot(); + // test(!s.isRampGeneratorActive(), "too many commands created"); + printf("current position = %d\n", s.getCurrentPosition()); + test(s.getCurrentPosition() > expected_steps - 10, "stepper runs too slow"); + test(s.getCurrentPosition() < expected_steps + 10, "stepper runs too fast"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + float avg_time = sum_planning_time / points * 1000.0; + printf("Average planning time: %f ms\n", avg_time); + test(avg_time < forward_planning + 1, "too much forward planning"); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + // run the ramp twice with 20 and with 5ms planning time. + // the ramp will change speed after half of the loops. + // The 5ms ramp will not have 20ms coasting in the buffer and as such runs + // much shorter. + test.ramp(20, 76936); + test.ramp(5, 11273); + printf("TEST_15 PASSED\n"); + return 0; +} diff --git a/tests/host/test_16.cpp b/tests/host/test_16.cpp new file mode 100644 index 0000000..e1b61ea --- /dev/null +++ b/tests/host/test_16.cpp @@ -0,0 +1,196 @@ +#include +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint8_t forward_planning, uint32_t expected_steps) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t speed_us = 1000000 / 3600; + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(320); + s.setForwardPlanningTimeInMs(forward_planning); + s.fill_queue(); + assert(s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + float sum_planning_time = 0; + float points = 0; + snprintf(fname, 100, "test_15_%dms.gnuplot", forward_planning); + rc.start_plot(fname); + s.runForward(); + for (int i = 0; i < 2000; i++) { + if (i == 1000) { + printf("Change speed\n"); + s.setSpeedInUs(10000); + s.applySpeedAcceleration(); + } + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + sum_planning_time += planned_time; + points += 1.0; + // This must be ensured, so that the stepper does not run out of + // commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + // stop after + if (rc.total_ticks > TICKS_PER_S * 40) { + break; + } + } + rc.finish_plot(); + // test(!s.isRampGeneratorActive(), "too many commands created"); + printf("current position = %d\n", s.getCurrentPosition()); + test(s.getCurrentPosition() > expected_steps - 10, "stepper runs too slow"); + test(s.getCurrentPosition() < expected_steps + 10, "stepper runs too fast"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + float avg_time = sum_planning_time / points * 1000.0; + printf("Average planning time: %f ms\n", avg_time); + test(avg_time < forward_planning + 1, "too much forward planning"); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; + +void tc_2() { + MoveTimedResultCode ret; + uint32_t actual; + int64_t actual_sum = 0; + char fname[100]; + + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + snprintf(fname, 100, "test_16_tc_2.gnuplot"); + rc.start_plot(fname); + + ret = s.moveTimed(QUEUE_LEN / 2 - 1, QUEUE_LEN / 2 * 100000, &actual); + test(ret == MOVE_TIMED_EMPTY, "TC2_S1: valid pars"); + actual_sum += actual; + + ret = s.moveTimed(2, 200000, &actual); + printf("queue = %d\n", s.queueEntries()); + test(ret != MOVE_TIMED_OK, "TC2_S2: move should be rejected"); + test(ret == MOVE_TIMED_BUSY, "TC2_S3: queue should be full"); + + // process commands + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + ret = s.moveTimed(2, 200000, &actual); + test(ret == MOVE_TIMED_EMPTY, "TC2_S4: valid pars"); + actual_sum += actual; + + // process commands + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + rc.finish_plot(); + + uint64_t expected_ticks = QUEUE_LEN / 2 * 100000 + 200000; + printf("current position = %d, total_ticks=%" PRIu64 "\n", + s.getCurrentPosition(), rc.total_ticks); + test(s.getCurrentPosition() == QUEUE_LEN / 2 + 1, "TC2_S5: step mismatch"); + printf("expected ticks=%" PRIu64 ", actual=%" PRIu64 "\n", expected_ticks, + actual_sum); + test(rc.total_ticks == actual_sum, "TC2_S6: time algnment"); + int64_t drift = actual_sum - expected_ticks; + printf("drift=%" PRId64 "\n", abs(drift)); + test(abs(drift) < 10, "accepted drift"); +} + +int main() { + MoveTimedResultCode ret; + uint32_t actual; + + StepperMotionTest test; + + puts("few simple tests"); + test.init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + + ret = s.moveTimed(QUEUE_LEN * 255 + 1, 1000, &actual); + test(ret == MOVE_TIMED_TOO_LARGE_ERROR, + "TC1_1: too many steps for the queue"); + + ret = s.moveTimed(QUEUE_LEN + 1, 65536 * (QUEUE_LEN + 1), &actual); + test(ret == MOVE_TIMED_TOO_LARGE_ERROR, + "TC1_2: too many steps for the queue"); + + ret = s.moveTimed(1, MIN_CMD_TICKS - 1, &actual); + MoveTimedResultCode ttl = MoveTimedResultCode::ErrorTicksTooLow; + test(ret == ttl, "TC1_3: too short duration"); + + ret = s.moveTimed(100, 100 * (s.getMaxSpeedInTicks() - 1), &actual); + test(ret == ttl, "TC1_4: still too short duration"); + + ret = s.moveTimed(QUEUE_LEN / 2 + 1, (QUEUE_LEN / 2) * 100000, &actual); + test(ret == MOVE_TIMED_TOO_LARGE_ERROR, "TC1_S5: too many commands"); + + tc_2(); + + printf("TEST_16 PASSED\n"); + return 0; +} diff --git a/tests/host/test_17.cpp b/tests/host/test_17.cpp new file mode 100644 index 0000000..38a7f6e --- /dev/null +++ b/tests/host/test_17.cpp @@ -0,0 +1,198 @@ +#include +#include +#include +#include + +// Define debug_part_size before including any headers +uint16_t debug_part_size = 31; // Default for PC tests + +#include "StepperMotion.h" +// #include "fas_queue/stepper_queue.h" + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#define SUPPORT_ESP32_RMT_V1 +#define IRAM_ATTR +#define RMT_CHANNEL_T int +#define LL_TOGGLE_PIN(dirPin) +#include "pd_esp32/StepperISR_rmt_v1.cpp" + +// The V1 fill path stops the channel when the queue runs dry mid-part. +// The real definition is per chip in StepperISR_rmt_v1_esp32*.cpp; these +// tests compile the fill path only, so they bring their own. +void StepperQueue::stop_rmt(bool both) { (void)both; } + + +struct TestCase { + uint8_t forward_planning; + int32_t position; + uint32_t speed_us; + uint32_t acceleration; + // check step rate between from_step and to_step + bool check_step_rate; + uint32_t from_step; + uint32_t to_step; + uint32_t period_ticks; +}; + +class StepperMotionTest { + public: + uint32_t offset; + uint32_t rmt_entries[1000000]; + + void init_queue() { fas_queue[0]._initVars(); } + + void ramp(TestCase tc) { + printf( + "Running ramp test with forward_planning=%d, position=%d, speed_us=%d, " + "acceleration=%d\n", + tc.forward_planning, tc.position, tc.speed_us, tc.acceleration); + init_queue(); + offset = 0; + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + s.setAbsoluteSpeedLimit(80); + s.setSpeedInUs(tc.speed_us); + s.setAcceleration(tc.acceleration); + s.setForwardPlanningTimeInMs(tc.forward_planning); + s.fill_queue(); + assert(s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + s.moveTo(tc.position); + for (int i = 0; i < 100000; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + if (!s.isQueueEmpty()) { + if (offset + PART_SIZE > sizeof(rmt_entries) / sizeof(rmt_entries[0])) { + printf("RMT buffer overflow\n"); + exit(1); + } + rmt_fill_buffer(&fas_queue[0], true, &rmt_entries[offset]); + offset += PART_SIZE; + } + } + while (!s.isQueueEmpty()) { + if (offset + PART_SIZE > sizeof(rmt_entries) / sizeof(rmt_entries[0])) { + printf("RMT buffer overflow\n"); + exit(1); + } + rmt_fill_buffer(&fas_queue[0], true, &rmt_entries[offset]); + offset += PART_SIZE; + } + // test(!s.isRampGeneratorActive(), "too many commands created"); + printf("current position = %d, target position %d\n", + s.getCurrentPosition(), tc.position); + test(s.getCurrentPosition() == tc.position, "target position not reached"); + + evaluate_rmt_entries(tc); + } + + void evaluate_rmt_entries(TestCase tc) { + printf("RMT entries: %d\n", offset); + uint64_t ticks = 0; +#define MAX_STEPS 100000 + uint32_t steps_time[MAX_STEPS]; + uint32_t steps = 0; + bool step_high = false; + for (uint32_t i = 0; i < offset; i++) { + printf("Entry %d: %08" PRIx32 " steps=%" PRIu32 "\n", i, rmt_entries[i], + steps); + uint32_t entry = rmt_entries[i]; + for (int j = 0; j < 2; j++) { + uint16_t subentry = (j == 0) ? entry & 0xffff : entry >> 16; + if (((subentry & 0x8000) != 0) && !step_high) { + // this is a step transition + step_high = true; + steps++; + if (steps < MAX_STEPS) { + steps_time[steps] = ticks; + } else { + printf("Too many steps recorded\n"); + exit(1); + } + } else if ((subentry & 0x8000) == 0) { + step_high = false; + } + // advance ticks + ticks += subentry & 0x7fff; + } + } + test(steps == tc.position, + "number of steps does not match target position"); + float t = ticks / (float)TICKS_PER_S; + printf("Total ticks: %" PRIu64 " = %.3fs, steps: %d\n", ticks, t, steps); + + if (tc.check_step_rate) { + // check step rate between from_step and to_step + for (uint32_t i = tc.from_step; i < tc.to_step; i++) { + if (i + 1 >= steps) { + printf("to_step out of range\n"); + exit(1); + } + uint32_t dt = steps_time[i + 1] - steps_time[i]; + if (dt != tc.period_ticks) { + printf("Step %d: dt=%" PRIu32 " != %" PRIu32 " ticks\n", i, dt, + tc.period_ticks); + } + test(dt == tc.period_ticks, + "step rate does not match expected period ticks"); + } + } + } +}; + +int main() { + StepperMotionTest test; + // run the ramp twice with 20 and with 5ms planning time. + // the ramp will change speed after half of the loops. + // The 5ms ramp will not have 20ms coasting in the buffer and as such runs + // much shorter. + TestCase test_cases[] = { + {.forward_planning = 20, + .position = 1000, + .speed_us = 1000, + .acceleration = 320}, + {.forward_planning = 5, + .position = 5000, + .speed_us = 1000, + .acceleration = 320, + .check_step_rate = true, + .from_step = 1600, + .to_step = 3400, + .period_ticks = 16000}, + {.forward_planning = 5, + .position = 5000, + .speed_us = 5, + .acceleration = 10000000, + .check_step_rate = true, + .from_step = 2000, + .to_step = 3000, + .period_ticks = 80}, + // issue #325: This freezes with StepperDemo on esp32c3 + {.forward_planning = 20, + .position = 1000, + .speed_us = 533, + .acceleration = 1000}, + }; + for (int i = 0; i < sizeof(test_cases) / sizeof(test_cases[0]); i++) { + test.ramp(test_cases[i]); + } + printf("TEST_17 PASSED\n"); + return 0; +} diff --git a/tests/host/test_18.cpp b/tests/host/test_18.cpp new file mode 100644 index 0000000..4bd5dbc --- /dev/null +++ b/tests/host/test_18.cpp @@ -0,0 +1,529 @@ +#include +#include +#include +#include +#include + +bool dump_rmt_symbols = false; + +uint16_t debug_part_size = 24; + +#include "StepperMotion.h" + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#define SUPPORT_ESP32_RMT_V1 +#define IRAM_ATTR +#define RMT_CHANNEL_T int +#define LL_TOGGLE_PIN(dirPin) +#include "pd_esp32/StepperISR_rmt_v1.cpp" + +// The V1 fill path stops the channel when the queue runs dry mid-part. +// The real definition is per chip in StepperISR_rmt_v1_esp32*.cpp; these +// tests compile the fill path only, so they bring their own. +void StepperQueue::stop_rmt(bool both) { (void)both; } + + +#define QUEUE_SIZE 32 +#define MAX_RMT_ENTRIES 8192 + +struct QueueCommand { + uint8_t steps; + uint16_t ticks; +}; + +struct RmtAnalysis { + uint32_t step_count; + uint64_t total_ticks; + uint16_t min_symbol_period; + uint32_t total_high_ticks; + uint32_t total_low_ticks; +}; + +static uint32_t global_rmt_entries[MAX_RMT_ENTRIES]; + +class RmtBufferTest { + public: + uint32_t* rmt_entries; + uint32_t rmt_offset; + + RmtBufferTest() : rmt_entries(global_rmt_entries), rmt_offset(0) {} + + void init_queue() { + fas_queue[0]._initVars(); + rmt_offset = 0; + } + + void add_command(uint8_t steps, uint16_t ticks) { + uint8_t idx = fas_queue[0].next_write_idx & QUEUE_LEN_MASK; + fas_queue[0].entry[idx].steps = steps; + fas_queue[0].entry[idx].ticks = ticks; + fas_queue[0].entry[idx].toggle_dir = 0; + fas_queue[0].next_write_idx++; + } + + void fill_commands(const QueueCommand* commands, uint32_t count) { + for (uint32_t i = 0; i < count; i++) { + add_command(commands[i].steps, commands[i].ticks); + } + } + + void process_all() { + int iterations = 0; + while (fas_queue[0].read_idx != fas_queue[0].next_write_idx) { + if (rmt_offset + PART_SIZE > MAX_RMT_ENTRIES) { + break; + } + rmt_fill_buffer(&fas_queue[0], true, &rmt_entries[rmt_offset]); + rmt_offset += PART_SIZE; + iterations++; + if (iterations > 100) { + break; + } + } + } + + RmtAnalysis analyze() { + RmtAnalysis result = {0, 0, 0xffff, 0, 0}; + bool step_high = false; + + for (uint32_t i = 0; i < rmt_offset; i++) { + uint32_t entry = rmt_entries[i]; + uint16_t low = entry & 0xffff; + uint16_t high = entry >> 16; + + uint16_t low_ticks = low & 0x7fff; + uint16_t high_ticks = high & 0x7fff; + + if (low_ticks > 0 && low_ticks < result.min_symbol_period) { + result.min_symbol_period = low_ticks; + } + if (high_ticks > 0 && high_ticks < result.min_symbol_period) { + result.min_symbol_period = high_ticks; + } + + if ((low & 0x8000) && !step_high) { + result.step_count++; + step_high = true; + } else if (!(low & 0x8000) && step_high) { + step_high = false; + } + result.total_ticks += low_ticks; + if (step_high) { + result.total_high_ticks += low_ticks; + } else { + result.total_low_ticks += low_ticks; + } + + if ((high & 0x8000) && !step_high) { + result.step_count++; + step_high = true; + } else if (!(high & 0x8000) && step_high) { + step_high = false; + } + result.total_ticks += high_ticks; + if (step_high) { + result.total_high_ticks += high_ticks; + } else { + result.total_low_ticks += high_ticks; + } + } + return result; + } + + void dump_rmt(uint32_t max_entries = 0) { + uint32_t count = (max_entries > 0 && max_entries < rmt_offset) ? max_entries + : rmt_offset; + printf("RMT entries (showing %u of %u):\n", count, rmt_offset); + uint32_t i = 0; + while (i < count) { + uint32_t entry = rmt_entries[i]; + uint32_t repeat = 1; + while (i + repeat < count && rmt_entries[i + repeat] == entry) { + repeat++; + } + uint16_t low = entry & 0xffff; + uint16_t high = entry >> 16; + if (repeat > 1) { + printf(" [%3u-%3u] 0x%08x L=%u%s H=%u%s x%u\n", i, i + repeat - 1, + entry, low & 0x7fff, (low & 0x8000) ? "(S)" : "", high & 0x7fff, + (high & 0x8000) ? "(S)" : "", repeat); + } else { + printf(" [%3u] 0x%08x L=%u%s H=%u%s\n", i, entry, low & 0x7fff, + (low & 0x8000) ? "(S)" : "", high & 0x7fff, + (high & 0x8000) ? "(S)" : ""); + } + i += repeat; + } + } +}; + +struct TestCase { + const char* name; + const QueueCommand* commands; + uint32_t command_count; + uint32_t expected_steps; + uint64_t expected_ticks; +}; + +QueueCommand cmd_single_step_16000[] = {{1, 16000}}; +QueueCommand cmd_single_step_32000[] = {{1, 32000}}; +QueueCommand cmd_single_step_65535[] = {{1, 65535}}; + +QueueCommand cmd_multi_step_1000[] = {{10, 1000}}; +QueueCommand cmd_multi_step_500[] = {{20, 500}}; + +QueueCommand cmd_pause_step[] = {{0, 10000}, {1, 16000}, {0, 5000}}; + +QueueCommand cmd_step_pause_step[] = {{1, 16000}, {0, 32000}, {1, 16000}}; + +QueueCommand cmd_many_steps[] = {{5, 8000}, {10, 4000}, {3, 12000}}; + +QueueCommand cmd_ramp_1000us[] = { + {1, 35808}, {1, 25312}, {1, 25312}, {1, 35808}, {1, 35808}}; +QueueCommand cmd_ramp_2000us[] = { + {1, 35808}, {1, 32000}, {1, 32000}, {1, 35808}, {1, 35808}}; +QueueCommand cmd_ramp_500us_step_pause[] = { + {1, 56608}, {0, 56608}, {1, 40032}, {0, 40032}, {1, 65344}, + {1, 56608}, {1, 50624}, {1, 56608}, {1, 65344}, {1, 40032}, + {0, 40032}, {1, 56608}, {0, 56608}, {1, 56608}, {0, 56608}}; + +QueueCommand cmd_single_step_8000[] = {{1, 8000}}; +QueueCommand cmd_multi_step_8000[] = {{10, 8000}}; + +QueueCommand cmd_1000us_period[] = {{1, 16000}}; +QueueCommand cmd_999us_period[] = {{1, 15984}}; + +bool run_tests() { + printf("\n=== Testing with PART_SIZE=%u ===\n", debug_part_size); + printf("MIN_CMD_TICKS=%ld, TICKS_PER_S=%ld\n\n", MIN_CMD_TICKS, TICKS_PER_S); + + RmtBufferTest test; + bool all_passed = true; + int fail_count = 0; + + TestCase cases[] = { + {"Single step 16000 ticks (1000us)", cmd_single_step_16000, 1, 1, 16000}, + {"Single step 32000 ticks (2000us)", cmd_single_step_32000, 1, 1, 32000}, + {"Single step 65535 ticks (4095us)", cmd_single_step_65535, 1, 1, 65535}, + {"Single step 8000 ticks (500us)", cmd_single_step_8000, 1, 1, 8000}, + {"10 steps @ 1000 ticks each", cmd_multi_step_1000, 1, 10, 10000}, + {"20 steps @ 500 ticks each", cmd_multi_step_500, 1, 20, 10000}, + {"10 steps @ 8000 ticks each (500us)", cmd_multi_step_8000, 1, 10, 80000}, + {"Pause + Step + Pause", cmd_pause_step, 3, 1, 31000}, + {"Step + Pause + Step", cmd_step_pause_step, 3, 2, 64000}, + {"Mixed: 5@8000 + 10@4000 + 3@12000", cmd_many_steps, 3, 18, 116000}, + {"Ramp 1000us (from ramp_helper)", cmd_ramp_1000us, 5, 5, 158048}, + {"Ramp 2000us (from ramp_helper)", cmd_ramp_2000us, 5, 5, 171424}, + {"Ramp 500us step+pause (from ramp_helper)", cmd_ramp_500us_step_pause, + 15, 10, 794304}, + {"1000us period (16000 ticks)", cmd_1000us_period, 1, 1, 16000}, + {"999us period (15984 ticks)", cmd_999us_period, 1, 1, 15984}, + }; + + int num_cases = sizeof(cases) / sizeof(cases[0]); + + for (int i = 0; i < num_cases; i++) { + TestCase* tc = &cases[i]; + printf("Test %d: %s\n", i + 1, tc->name); + + test.init_queue(); + test.fill_commands(tc->commands, tc->command_count); + test.process_all(); + + RmtAnalysis result = test.analyze(); + + bool steps_ok = (result.step_count == tc->expected_steps); + bool ticks_ok = (result.total_ticks == tc->expected_ticks); + + uint32_t high_low_ratio = 0; + if (result.total_low_ticks > 0) { + high_low_ratio = (result.total_high_ticks * 100) / result.total_low_ticks; + } + + printf(" Steps: %" PRIu32 " (expected %" PRIu32 ") %s\n", + result.step_count, tc->expected_steps, steps_ok ? "OK" : "FAIL"); + printf(" Ticks: %" PRIu64 " (expected %" PRIu64 ") %s\n", + result.total_ticks, tc->expected_ticks, ticks_ok ? "OK" : "FAIL"); + printf(" High/Low: %" PRIu32 "/%" PRIu32 " ticks (ratio %u%%)\n", + result.total_high_ticks, result.total_low_ticks, high_low_ratio); + printf(" Min symbol: %u ticks\n", result.min_symbol_period); + + bool ratio_ok = (high_low_ratio >= 30 && high_low_ratio <= 200); + if (!ratio_ok && result.step_count > 0) { + printf(" WARNING: High/Low ratio outside 30-200%% range\n"); + } + + if (!steps_ok || !ticks_ok) { + all_passed = false; + test.dump_rmt(50); + } else if (dump_rmt_symbols) { + printf(" RMT symbols for this test:\n"); + test.dump_rmt(20); + } + printf("\n"); + } + + printf("\n=== Detailed Analysis: 1000us vs 999us Period Issue ===\n\n"); + + // Test 1000us (16000 ticks) vs 999us (15984 ticks) + uint16_t period_ticks[] = {16000, 15984}; + const char* period_names[] = {"1000us (16000 ticks)", "999us (15984 ticks)"}; + + for (int p = 0; p < 2; p++) { + uint16_t ticks = period_ticks[p]; + printf("Testing %s:\n", period_names[p]); + printf(" Command: steps=1, ticks=%u\n", ticks); + + test.init_queue(); + test.add_command(1, ticks); + + // Print queue state before processing + printf(" Queue before processing:\n"); + printf(" read_idx=%u, next_write_idx=%u\n", fas_queue[0].read_idx, + fas_queue[0].next_write_idx); + printf(" entry[0]: steps=%u, ticks=%u\n", fas_queue[0].entry[0].steps, + fas_queue[0].entry[0].ticks); + + test.process_all(); + + // Print RMT symbols + printf(" RMT symbols generated:\n"); + test.dump_rmt(50); + + RmtAnalysis result = test.analyze(); + + printf(" Analysis:\n"); + printf(" Steps: %" PRIu32 " (expected 1) %s\n", result.step_count, + result.step_count == 1 ? "OK" : "FAIL"); + printf(" Ticks: %" PRIu64 " (expected %u) %s\n", result.total_ticks, + ticks, result.total_ticks == ticks ? "OK" : "FAIL"); + printf(" High/Low: %" PRIu32 "/%" PRIu32 " ticks\n", + result.total_high_ticks, result.total_low_ticks); + printf(" Min symbol: %u ticks\n", result.min_symbol_period); + + if (result.step_count != 1 || result.total_ticks != ticks) { + all_passed = false; + fail_count++; + } + printf("\n"); + } + + printf("=== Part 2: Step count limits (0-255 steps) ===\n\n"); + + uint16_t test_ticks[] = {MIN_CMD_TICKS, 16000, 32000, 65535}; + int num_ticks = sizeof(test_ticks) / sizeof(test_ticks[0]); + + for (int t = 0; t < num_ticks; t++) { + uint16_t ticks = test_ticks[t]; + int round_fails = 0; + + printf("Testing %u ticks with 0-255 steps: ", ticks); + fflush(stdout); + + for (int steps = 0; steps <= 255; steps++) { + test.init_queue(); + test.add_command(steps, ticks); + test.process_all(); + + RmtAnalysis result = test.analyze(); + + uint32_t expected_steps = steps; + uint64_t expected_ticks = (uint64_t)steps * ticks; + if (steps == 0) { + expected_ticks = ticks; + } + + bool steps_ok = (result.step_count == expected_steps); + bool ticks_ok = (result.total_ticks == expected_ticks); + + if (!steps_ok || !ticks_ok) { + if (round_fails == 0) { + printf("\n"); + } + printf(" FAIL steps=%d: got %" PRIu32 " steps, %" PRIu64 + " ticks (expected %" PRIu32 ", %" PRIu64 ")\n", + steps, result.step_count, result.total_ticks, expected_steps, + expected_ticks); + round_fails++; + all_passed = false; + if (round_fails <= 2) { + test.dump_rmt(30); + } + } else if (dump_rmt_symbols && + (steps == 0 || steps == 1 || steps == 255)) { + // Dump for edge cases when dump_rmt_symbols is enabled + printf(" steps=%d: ", steps); + test.dump_rmt(5); + } + } + + if (round_fails == 0) { + printf("OK\n"); + } else { + printf(" %d failures for ticks=%u\n", round_fails, ticks); + } + fail_count += round_fails; + } + + printf("\n=== Part 3: High/Low ratio check ===\n\n"); + + uint16_t ratio_test_ticks[] = {1000, 5000, 8000, 10000, 16000, 32000, 65535}; + int num_ratio_tests = sizeof(ratio_test_ticks) / sizeof(ratio_test_ticks[0]); + + for (int t = 0; t < num_ratio_tests; t++) { + uint16_t ticks = ratio_test_ticks[t]; + test.init_queue(); + test.add_command(1, ticks); + test.process_all(); + + RmtAnalysis result = test.analyze(); + + uint32_t high_low_ratio = 0; + if (result.total_low_ticks > 0) { + high_low_ratio = (result.total_high_ticks * 100) / result.total_low_ticks; + } + + bool ratio_ok = (high_low_ratio >= 30 && high_low_ratio <= 200); + printf("Period %5u ticks: high=%" PRIu32 " low=%" PRIu32 + " ratio=%u%% min_sym=%u %s\n", + ticks, result.total_high_ticks, result.total_low_ticks, + high_low_ratio, result.min_symbol_period, ratio_ok ? "OK" : "FAIL"); + + if (!ratio_ok) { + all_passed = false; + fail_count++; + test.dump_rmt(30); + } else if (dump_rmt_symbols) { + printf(" RMT symbols: "); + test.dump_rmt(5); + } + } + + printf("\n=== Part 4: Reported Hardware Failure Analysis ===\n\n"); + printf("Testing reported hardware issues:\n"); + printf("1. v=1000us (16000 ticks) => no pulses on real hardware\n"); + printf("2. v=2000us (32000 ticks) => no pulses on real hardware\n"); + printf( + "3. v=500us (8000 ticks) => pulses but incorrect pattern (2:1 high:low " + "ratio)\n\n"); + + uint16_t hw_failure_ticks[] = {16000, 32000, 8000}; + const char* hw_failure_desc[] = { + "1000us (16000 ticks)", "2000us (32000 ticks)", "500us (8000 ticks)"}; + int num_hw_tests = sizeof(hw_failure_ticks) / sizeof(hw_failure_ticks[0]); + + for (int t = 0; t < num_hw_tests; t++) { + uint16_t ticks = hw_failure_ticks[t]; + printf("HW Failure Test: %s\n", hw_failure_desc[t]); + + test.init_queue(); + test.add_command(1, ticks); + test.process_all(); + + RmtAnalysis result = test.analyze(); + + uint32_t high_low_ratio = 0; + if (result.total_low_ticks > 0) { + high_low_ratio = (result.total_high_ticks * 100) / result.total_low_ticks; + } + + printf(" Steps: %" PRIu32 " (expected 1) %s\n", result.step_count, + result.step_count == 1 ? "OK" : "FAIL"); + printf(" Ticks: %" PRIu64 " (expected %u) %s\n", result.total_ticks, ticks, + result.total_ticks == ticks ? "OK" : "FAIL"); + printf(" High/Low: %" PRIu32 "/%" PRIu32 " ticks (ratio %u%%)\n", + result.total_high_ticks, result.total_low_ticks, high_low_ratio); + printf(" Min symbol: %u ticks (must be >= 2) %s\n", + result.min_symbol_period, + result.min_symbol_period >= 2 ? "OK" : "FAIL"); + + bool ratio_ok = (high_low_ratio >= 30 && high_low_ratio <= 200); + if (!ratio_ok) { + printf(" WARNING: High/Low ratio outside 30-200%% range\n"); + } + + if (ticks == 8000) { + printf(" Expected issue: 2:1 high:low ratio (200%%) on real hardware\n"); + printf(" Simulated ratio: %u%%\n", high_low_ratio); + } + + if (result.step_count != 1 || result.total_ticks != ticks || + result.min_symbol_period < 2) { + all_passed = false; + fail_count++; + test.dump_rmt(30); + } else if (dump_rmt_symbols) { + printf(" RMT symbols: "); + test.dump_rmt(10); + } + printf("\n"); + } + + if (all_passed) { + printf("ALL TESTS PASSED for PART_SIZE=%u\n", debug_part_size); + return true; + } else { + printf("TESTS FAILED for PART_SIZE=%u (%d failures)\n", debug_part_size, + fail_count); + return false; + } +} + +int main(int argc, char* argv[]) { + // Parse command line arguments + for (int i = 1; i < argc; i++) { + if (strcmp(argv[i], "-d") == 0) { + dump_rmt_symbols = true; + } else if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) { + fprintf(stderr, "Usage: %s [options]\n", argv[0]); + fprintf(stderr, "Options:\n"); + fprintf(stderr, + " -d Enable dumping of RMT symbols for all tests\n"); + fprintf(stderr, " -h, --help Show this help message\n"); + return 0; + } else { + fprintf(stderr, "Unknown option: %s\n", argv[i]); + fprintf(stderr, "Use -h for help\n"); + return 1; + } + } + + printf("=== RMT Fill Buffer Test with Multiple PART_SIZE Values ===\n"); + if (dump_rmt_symbols) { + printf("RMT symbol dumping enabled (-d flag)\n"); + } + + uint16_t part_sizes[] = {22, 24, 30, 32}; + int num_part_sizes = sizeof(part_sizes) / sizeof(part_sizes[0]); + + bool all_passed = true; + int total_failures = 0; + + for (int i = 0; i < num_part_sizes; i++) { + debug_part_size = part_sizes[i]; + bool passed = run_tests(); + + if (!passed) { + all_passed = false; + total_failures++; + } + + if (i < num_part_sizes - 1) { + printf( + "\n============================================================\n"); + } + } + + printf("\n=== Summary ===\n"); + if (all_passed) { + printf("ALL TESTS PASSED for all PART_SIZE values\n"); + return 0; + } else { + printf("TESTS FAILED for %d out of %d PART_SIZE values\n", total_failures, + num_part_sizes); + return 1; + } +} diff --git a/tests/host/test_19.cpp b/tests/host/test_19.cpp new file mode 100644 index 0000000..81b4299 --- /dev/null +++ b/tests/host/test_19.cpp @@ -0,0 +1,102 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void ramp(uint32_t accel, uint32_t speed_us, uint32_t steps, + bool reach_coasting) { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + assert(s.isQueueEmpty()); + s.setSpeedInUs(speed_us); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + s.runForward(); + s.fill_queue(); + assert(!s.isQueueEmpty()); + float old_planned_time_in_buffer = 0; + + char fname[100]; + snprintf(fname, 100, "test_12.gnuplot"); + rc.start_plot(fname); + bool coast = false; + for (int i = 0; i < 100 * steps; i++) { + if (true) { + printf( + "Loop %d: Queue read/write = %d/%d Target pos = %d, Queue End " + "pos = %d QueueEmpty=%s\n", + i, fas_queue[0].read_idx, fas_queue[0].next_write_idx, + s.targetPos(), s.getPositionAfterCommandsCompleted(), + s.isQueueEmpty() ? "yes" : "no"); + } + if (s.getPositionAfterCommandsCompleted() >= steps) { + break; + } + if (!s.isRampGeneratorActive()) { + break; + } + s.fill_queue(); + uint32_t from_dt = rc.total_ticks; + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + if ((s.rampState() & RAMP_STATE_MASK) == RAMP_STATE_COAST) { + coast = true; + } + uint32_t to_dt = rc.total_ticks; + float planned_time = (to_dt - from_dt) * 1.0 / 16000000; + printf("planned time in buffer: %.6fs\n", planned_time); + // This must be ensured, so that the stepper does not run out of commands + assert((i == 0) || (old_planned_time_in_buffer > 0.005)); + old_planned_time_in_buffer = planned_time; + } + rc.finish_plot(); + test(coast == reach_coasting, "coasting target not met"); + printf("Total time %f\n", rc.total_ticks / 16000000.0); + +#if (TEST_CREATE_QUEUE_CHECKSUM == 1) + printf("CHECKSUM for %d/%d/%d: %d\n", steps, travel_dt, accel, s.checksum); +#endif + } +}; +int main() { + StepperMotionTest test; + + // Test related to #347 to reach max speed + // accel speed_us (coast) steps reach_coasting + test.ramp(100, 5, 51000000, false); + printf("TEST_19 PASSED\n"); + return 0; +} diff --git a/tests/host/test_20.cpp b/tests/host/test_20.cpp new file mode 100644 index 0000000..a57b350 --- /dev/null +++ b/tests/host/test_20.cpp @@ -0,0 +1,438 @@ +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "RampChecker.h" + +static bool test_failed = false; +static const char* failure_msg = NULL; + +void test_handler(bool condition, const char* msg) { + if (!condition) { + printf("TEST FAILURE: %s\n", msg); + test_failed = true; + failure_msg = msg; + } +} + +class StepperMotionTest { + public: + void init_queue() { + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + } + + void test_issue_motor_stops_at_low_speed() { + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t accel = 8164; + uint32_t speed_hz = 81; + int32_t target_position = 1720; + + printf("\n=== Test Issue: Motor stops at low speed ===\n"); + printf("acceleration=%u, speed=%u Hz, target=%d\n", accel, speed_hz, + target_position); + + assert(s.isQueueEmpty()); + s.setSpeedInHz(speed_hz); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + + MoveResultCode result = s.moveTo(target_position); + test_handler(result == MOVE_OK, "moveTo should succeed"); + + int consecutive_empty_queues = 0; + int max_consecutive_empty = 0; + bool reached_target = false; + uint32_t last_pos = 0; + int steps_moved = 0; + + for (int i = 0; i < 5000; i++) { + if (!s.isRampGeneratorActive()) { + printf("Ramp generator inactive at loop %d\n", i); + break; + } + + s.fill_queue(); + + if (s.isQueueEmpty()) { + consecutive_empty_queues++; + if (consecutive_empty_queues > max_consecutive_empty) { + max_consecutive_empty = consecutive_empty_queues; + } + } else { + consecutive_empty_queues = 0; + } + + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + if (rc.pos != last_pos) { + steps_moved++; + last_pos = rc.pos; + } + } + + if (s.getPositionAfterCommandsCompleted() >= target_position) { + reached_target = true; + printf("Reached target position at loop %d\n", i); + break; + } + } + + printf( + "Final position = %d, target = %d, steps_moved = %d, " + "max_empty_cycles = %d\n", + s.getCurrentPosition(), target_position, steps_moved, + max_consecutive_empty); + + test_handler(reached_target || s.getCurrentPosition() >= target_position, + "motor should reach target position"); + test_handler(max_consecutive_empty < 20, + "motor should not stop prematurely due to empty queue"); + + if (!test_failed) { + printf("Test 1 PASSED\n"); + } + } + + void test_issue_speed_change_from_high_to_low() { + test_failed = false; + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t accel = 8164; + uint32_t high_speed_hz = 89; + uint32_t low_speed_hz = 81; + int32_t target_position = 1720; + + printf( + "\n=== Test Issue: Speed change from high (%u Hz) to low (%u Hz) ===\n", + high_speed_hz, low_speed_hz); + printf("This test demonstrates the reported bug:\n"); + printf("- When speed is reduced from 89Hz to 81Hz during movement,\n"); + printf( + "- the ramp generator produces invalid ticks (below MIN_CMD_TICKS),\n"); + printf("- causing the motor to stop prematurely.\n\n"); + + assert(s.isQueueEmpty()); + s.setSpeedInHz(high_speed_hz); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + + MoveResultCode result = s.moveTo(target_position); + test_handler(result == MOVE_OK, "moveTo should succeed"); + + bool speed_reduced = false; + int reduce_at_loop = 50; + int consecutive_empty_queues = 0; + int max_consecutive_empty = 0; + uint32_t last_pos = 0; + int steps_before_reduce = 0; + int steps_after_reduce = 0; + bool position_changed_after_reduce = false; + + for (int i = 0; i < 5000; i++) { + if (!s.isRampGeneratorActive()) { + printf("Ramp generator inactive at loop %d\n", i); + break; + } + + if (!speed_reduced && i == reduce_at_loop) { + steps_before_reduce = rc.pos; + printf("At loop %d: Reducing speed from %u Hz to %u Hz (pos=%d)\n", i, + high_speed_hz, low_speed_hz, rc.pos); + s.setSpeedInHz(low_speed_hz); + s.applySpeedAcceleration(); + speed_reduced = true; + } + + s.fill_queue(); + + if (s.isQueueEmpty()) { + consecutive_empty_queues++; + if (consecutive_empty_queues > max_consecutive_empty) { + max_consecutive_empty = consecutive_empty_queues; + } + } else { + consecutive_empty_queues = 0; + } + + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + if (rc.pos != last_pos) { + if (speed_reduced) { + steps_after_reduce++; + if (rc.pos > last_pos + 1) { + position_changed_after_reduce = true; + } + } + last_pos = rc.pos; + } + } + + if (s.getPositionAfterCommandsCompleted() >= target_position) { + printf("Reached target position at loop %d\n", i); + break; + } + + if (i > reduce_at_loop + 100 && consecutive_empty_queues > 10) { + printf("Motor appears to have stopped after speed reduction\n"); + break; + } + } + + steps_after_reduce = rc.pos - steps_before_reduce; + + printf("Final position = %d, target = %d\n", s.getCurrentPosition(), + target_position); + printf("Steps before speed reduction: %d\n", steps_before_reduce); + printf("Steps after speed reduction: %d\n", steps_after_reduce); + printf("Max consecutive empty queue cycles: %d\n", max_consecutive_empty); + + if (max_consecutive_empty >= 20 || !position_changed_after_reduce) { + printf("\n*** BUG REPRODUCED ***\n"); + printf( + "The motor stopped or failed to continue after speed was reduced.\n"); + printf("This matches the reported issue where reducing speed to 81 Hz\n"); + printf("with acceleration 8164 causes the motor to stop.\n"); + } + + test_handler(max_consecutive_empty < 20, + "BUG: motor stopped prematurely after speed reduction"); + test_handler(position_changed_after_reduce, + "BUG: motor should continue moving after speed reduction"); + + if (!test_failed) { + printf("Test 2 PASSED (bug not reproduced - may be fixed)\n"); + } else { + printf("Test 2 FAILED (bug reproduced - test is working correctly)\n"); + } + } + + void test_issue_multiple_speed_changes() { + test_failed = false; + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t accel = 8164; + int32_t target_position = 1720; + + printf("\n=== Test Issue: Multiple speed changes ===\n"); + printf("Simulating user scenario: 73Hz -> 81Hz -> 89Hz -> 97Hz -> 81Hz\n"); + + assert(s.isQueueEmpty()); + s.setSpeedInHz(73); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + + MoveResultCode result = s.moveTo(target_position); + test_handler(result == MOVE_OK, "moveTo should succeed"); + + int consecutive_empty_queues = 0; + int max_consecutive_empty = 0; + uint32_t last_pos = 0; + + for (int i = 0; i < 5000; i++) { + if (!s.isRampGeneratorActive()) { + printf("Ramp generator inactive at loop %d\n", i); + break; + } + + if (i == 20) { + printf("At loop %d: Setting speed to 81 Hz\n", i); + s.setSpeedInHz(81); + s.applySpeedAcceleration(); + } else if (i == 40) { + printf("At loop %d: Setting speed to 89 Hz\n", i); + s.setSpeedInHz(89); + s.applySpeedAcceleration(); + } else if (i == 60) { + printf("At loop %d: Setting speed to 97 Hz\n", i); + s.setSpeedInHz(97); + s.applySpeedAcceleration(); + } else if (i == 80) { + printf("At loop %d: Setting speed to 81 Hz (problematic per report)\n", + i); + s.setSpeedInHz(81); + s.applySpeedAcceleration(); + } + + s.fill_queue(); + + if (s.isQueueEmpty()) { + consecutive_empty_queues++; + if (consecutive_empty_queues > max_consecutive_empty) { + max_consecutive_empty = consecutive_empty_queues; + } + } else { + consecutive_empty_queues = 0; + } + + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + last_pos = rc.pos; + } + + if (s.getPositionAfterCommandsCompleted() >= target_position) { + printf("Reached target position at loop %d\n", i); + break; + } + } + + printf("Final position = %d, target = %d, max_empty_cycles = %d\n", + s.getCurrentPosition(), target_position, max_consecutive_empty); + test_handler(s.getCurrentPosition() > target_position - 100, + "motor should be close to target position"); + test_handler(max_consecutive_empty < 20, + "motor should not stop prematurely"); + + if (!test_failed) { + printf("Test 3 PASSED\n"); + } + } + + void test_issue_with_reduced_acceleration() { + test_failed = false; + init_queue(); + StepperMotion s = StepperMotion(); + s.init(NULL, 0, 0); + RampChecker rc = RampChecker(); + assert(0 == s.getCurrentPosition()); + + uint32_t accel = 8164 / 3; + uint32_t high_speed_hz = 89; + uint32_t low_speed_hz = 81; + int32_t target_position = 1720; + + printf( + "\n=== Test: Speed change with reduced acceleration (1/3 of 8164) " + "===\n"); + printf("User reported this avoids the issue.\n\n"); + + assert(s.isQueueEmpty()); + s.setSpeedInHz(high_speed_hz); + s.setAcceleration(accel); + s.fill_queue(); + assert(s.isQueueEmpty()); + + MoveResultCode result = s.moveTo(target_position); + test_handler(result == MOVE_OK, "moveTo should succeed"); + + bool speed_reduced = false; + int reduce_at_loop = 50; + int consecutive_empty_queues = 0; + int max_consecutive_empty = 0; + + for (int i = 0; i < 5000; i++) { + if (!s.isRampGeneratorActive()) { + printf("Ramp generator inactive at loop %d\n", i); + break; + } + + if (!speed_reduced && i == reduce_at_loop) { + printf("At loop %d: Reducing speed from %u Hz to %u Hz\n", i, + high_speed_hz, low_speed_hz); + s.setSpeedInHz(low_speed_hz); + s.applySpeedAcceleration(); + speed_reduced = true; + } + + s.fill_queue(); + + if (s.isQueueEmpty()) { + consecutive_empty_queues++; + if (consecutive_empty_queues > max_consecutive_empty) { + max_consecutive_empty = consecutive_empty_queues; + } + } else { + consecutive_empty_queues = 0; + } + + while (!s.isQueueEmpty()) { + rc.increase_ok = true; + rc.decrease_ok = true; + rc.check_section( + &fas_queue[0].entry[fas_queue[0].read_idx & QUEUE_LEN_MASK]); + fas_queue[0].read_idx++; + } + + if (s.getPositionAfterCommandsCompleted() >= target_position) { + printf("Reached target position at loop %d\n", i); + break; + } + } + + printf("Final position = %d, target = %d, max_empty_cycles = %d\n", + s.getCurrentPosition(), target_position, max_consecutive_empty); + test_handler(s.getCurrentPosition() > target_position - 50, + "motor should reach target position with reduced accel"); + test_handler(max_consecutive_empty < 20, + "motor should not stop prematurely with reduced accel"); + + if (!test_failed) { + printf("Test 4 PASSED\n"); + } + } +}; + +int main() { + StepperMotionTest test; + + printf("========================================\n"); + printf("StepperMotion PC-Based Test 20\n"); + printf("Issue: Motor stops at low speed with\n"); + printf(" acceleration=8164, speed=81Hz\n"); + printf("========================================\n"); + + test.test_issue_motor_stops_at_low_speed(); + test.test_issue_speed_change_from_high_to_low(); + test.test_issue_multiple_speed_changes(); + test.test_issue_with_reduced_acceleration(); + + printf("\n========================================\n"); + printf("TEST_20 COMPLETED\n"); + printf("(Note: Test 2 may fail if bug is present)\n"); + printf("========================================\n"); + + return test_failed ? 1 : 0; +} diff --git a/tests/host/test_21.cpp b/tests/host/test_21.cpp new file mode 100644 index 0000000..57d35a1 --- /dev/null +++ b/tests/host/test_21.cpp @@ -0,0 +1,1336 @@ +// test_21: ESP32 I2S tests. +// +// Part 1: Pure DMA infrastructure tests - callbacks, double buffering +// (ping-pong), bit stream analysis. No driver code involved. +// +// Part 2: Driver fill function tests - i2s_fill_buffer_direct() with queue +// commands. + +#define SUPPORT_ESP32_I2S + +#include +#include +#include +#include +#include + +#include "pd_esp32/i2s_constants.h" + +static int test_passed = 0; +static int test_failed = 0; + +static void test_result(const char* name, bool passed) { + if (passed) { + printf("PASS: %s\n", name); + test_passed++; + } else { + printf("FAIL: %s\n", name); + test_failed++; + } +} + +// --------------------------------------------------------------------------- +// Mock I2sManager with callback support +// --------------------------------------------------------------------------- + +typedef void (*i2s_dma_callback_t)(uint8_t block); + +class I2sManager { + public: + static I2sManager& instance(); + + bool init(int, int, int) { + _initialized = true; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(_bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + _dma_block = 0; + _callback_count = 0; + return true; + } + + bool isInitialized() const { return _initialized; } + + uint8_t* blockBuf(uint8_t block) { return _bufs[block % I2S_BLOCK_COUNT]; } + + uint8_t dmaBlock() const { return _dma_block; } + + void registerDmaCallback(i2s_dma_callback_t cb) { _dma_callback = cb; } + + void dmaConsumeBlock() { + if (_dma_callback) { + _dma_callback(_dma_block); + _callback_count++; + } + _dma_block = (_dma_block + 1) % I2S_BLOCK_COUNT; + } + + uint32_t callbackCount() const { return _callback_count; } + + I2sManager() + : _initialized(false), + _dma_block(0), + _callback_count(0), + _dma_callback(nullptr) { + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(_bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + } + + private: + bool _initialized; + uint8_t _bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + uint8_t _dma_block; + uint32_t _callback_count; + i2s_dma_callback_t _dma_callback; +}; + +static I2sManager s_i2s_mgr; +inline I2sManager& I2sManager::instance() { return s_i2s_mgr; } + +// --------------------------------------------------------------------------- +// Bit stream analyzer - receives tick-level pin states +// --------------------------------------------------------------------------- +// Bit stream analyzer - receives tick-level pin states +// --------------------------------------------------------------------------- +// Bit stream analyzer - receives tick-level pin states +// --------------------------------------------------------------------------- + +class BitStreamAnalyzer { + public: + uint32_t rising_edges; + uint32_t falling_edges; + uint32_t total_ticks; + uint32_t last_rising_tick; + uint32_t last_falling_tick; + bool last_level; + uint8_t ticks_per_bit; + + void reset() { + rising_edges = 0; + falling_edges = 0; + total_ticks = 0; + last_rising_tick = 0; + last_falling_tick = 0; + last_level = false; + } + + void processBit(bool level) { + for (uint8_t i = 0; i < ticks_per_bit; i++) { + processTick(level); + } + } + + void processTick(bool level) { + if (level && !last_level) { + last_rising_tick = total_ticks; + rising_edges++; + } else if (!level && last_level) { + last_falling_tick = total_ticks; + falling_edges++; + } + last_level = level; + total_ticks++; + } + + uint32_t pulseCount() const { return rising_edges; } +}; + +static BitStreamAnalyzer s_analyzer; + +// --------------------------------------------------------------------------- +// DMA callback - processes buffer and sends to bit stream analyzer +// +// TODO: For driver integration tests (test_22), this callback should invoke +// the driver's fill_i2s_buffer() function to simulate real hardware behavior. +// For these low-level infrastructure tests, we only analyze the buffer content. +// --------------------------------------------------------------------------- + +static void dmaCallback(uint8_t block) { + I2sManager& mgr = I2sManager::instance(); + const uint8_t* buf = mgr.blockBuf(block); + + for (uint16_t frame = 0; frame < I2S_FRAMES_PER_BLOCK; frame++) { + uint8_t l_msb = buf[frame * I2S_BYTES_PER_FRAME + 0]; + uint8_t l_lsb = buf[frame * I2S_BYTES_PER_FRAME + 1]; + uint8_t r_msb = buf[frame * I2S_BYTES_PER_FRAME + 2]; + uint8_t r_lsb = buf[frame * I2S_BYTES_PER_FRAME + 3]; + + for (int8_t bit = 7; bit >= 0; bit--) { + s_analyzer.processBit((l_msb & (1 << bit)) != 0); + } + for (int8_t bit = 7; bit >= 0; bit--) { + s_analyzer.processBit((l_lsb & (1 << bit)) != 0); + } + for (int8_t bit = 7; bit >= 0; bit--) { + s_analyzer.processBit((r_msb & (1 << bit)) != 0); + } + for (int8_t bit = 7; bit >= 0; bit--) { + s_analyzer.processBit((r_lsb & (1 << bit)) != 0); + } + } +} + +// --------------------------------------------------------------------------- +// Helper to write pulses to buffer +// --------------------------------------------------------------------------- + +static void write_pulse_to_buffer(uint8_t* buf, uint16_t frame) { + buf[frame * I2S_BYTES_PER_FRAME + 0] = 0xFF; + buf[frame * I2S_BYTES_PER_FRAME + 1] = 0xFF; +} + +// --------------------------------------------------------------------------- +// Low-level DMA tests +// --------------------------------------------------------------------------- + +static void test_dma_callback_invoked() { + printf("Running: DMA callback invoked on consume\n"); + + s_analyzer.reset(); + I2sManager::instance().init(32, 33, -1); + I2sManager::instance().registerDmaCallback(dmaCallback); + + I2sManager::instance().dmaConsumeBlock(); + I2sManager::instance().dmaConsumeBlock(); + I2sManager::instance().dmaConsumeBlock(); + + uint32_t callbacks = I2sManager::instance().callbackCount(); + printf(" Callbacks: %u (expected 3)\n", callbacks); + + test_result("DMA callback invoked", callbacks == 3); +} + +static void test_dma_block_rotation() { + printf("Running: DMA block rotation (ping-pong)\n"); + + I2sManager::instance().init(32, 33, -1); + + uint8_t b0 = I2sManager::instance().dmaBlock(); + I2sManager::instance().dmaConsumeBlock(); + uint8_t b1 = I2sManager::instance().dmaBlock(); + I2sManager::instance().dmaConsumeBlock(); + uint8_t b2 = I2sManager::instance().dmaBlock(); + I2sManager::instance().dmaConsumeBlock(); + uint8_t b3 = I2sManager::instance().dmaBlock(); + + printf(" Blocks: %u -> %u -> %u -> %u\n", b0, b1, b2, b3); + printf(" Expected: 0 -> 1 -> 0 -> 1 (ping-pong)\n"); + + bool correct = (b0 == 0) && (b1 == 1) && (b2 == 0) && (b3 == 1); + test_result("DMA block rotation", correct); +} + +static void test_dma_buffer_not_cleared_on_consume() { + printf("Running: DMA buffer NOT cleared on consume (HW behavior)\n"); + + I2sManager::instance().init(32, 33, -1); + uint8_t* buf = I2sManager::instance().blockBuf(0); + + memset(buf, 0xFF, I2S_BYTES_PER_BLOCK); + printf(" Buffer 0 filled with 0xFF\n"); + + I2sManager::instance().dmaConsumeBlock(); + + buf = I2sManager::instance().blockBuf(0); + + bool still_has_data = true; + for (uint16_t i = 0; i < I2S_BYTES_PER_BLOCK; i++) { + if (buf[i] != 0xFF) { + still_has_data = false; + break; + } + } + + printf(" After consume, block 0 still has old data: %s\n", + still_has_data ? "yes" : "no"); + test_result("DMA buffer not cleared on consume", still_has_data); +} + +static void test_bit_stream_single_pulse() { + printf("Running: Bit stream single pulse detection\n"); + + s_analyzer.reset(); + + for (int i = 0; i < 100; i++) { + s_analyzer.processTick(false); + } + for (int i = 0; i < 64; i++) { + s_analyzer.processTick(true); + } + for (int i = 0; i < 100; i++) { + s_analyzer.processTick(false); + } + + printf(" Rising edges: %u (expected 1)\n", s_analyzer.rising_edges); + printf(" Falling edges: %u (expected 1)\n", s_analyzer.falling_edges); + printf(" Total ticks: %u (expected 264)\n", s_analyzer.total_ticks); + + bool correct = (s_analyzer.rising_edges == 1) && + (s_analyzer.falling_edges == 1) && + (s_analyzer.total_ticks == 264); + test_result("Bit stream single pulse", correct); +} + +static void test_bit_stream_multiple_pulses() { + printf("Running: Bit stream 7 pulses detection\n"); + + s_analyzer.reset(); + + for (int pulse = 0; pulse < 7; pulse++) { + for (int i = 0; i < 64; i++) { + s_analyzer.processTick(true); + } + for (int i = 0; i < 64 * 49; i++) { + s_analyzer.processTick(false); + } + } + + printf(" Pulses detected: %u (expected 7)\n", s_analyzer.pulseCount()); + printf(" Total ticks: %u (expected %u)\n", s_analyzer.total_ticks, + 7 * 64 * 50); + + bool correct = + (s_analyzer.pulseCount() == 7) && (s_analyzer.total_ticks == 7 * 64 * 50); + test_result("Bit stream 7 pulses", correct); +} + +static void test_dma_10_rounds_7_pulses() { + printf("Running: DMA 10 rounds with 7 pulses each\n"); + + s_analyzer.reset(); + I2sManager::instance().init(32, 33, -1); + I2sManager::instance().registerDmaCallback(dmaCallback); + + for (int round = 0; round < 10; round++) { + uint8_t blk = I2sManager::instance().dmaBlock(); + uint8_t* buf = I2sManager::instance().blockBuf(blk); + + for (int pulse = 0; pulse < 7; pulse++) { + uint16_t frame = (pulse * 35) % I2S_FRAMES_PER_BLOCK; + write_pulse_to_buffer(buf, frame); + } + + I2sManager::instance().dmaConsumeBlock(); + } + + printf(" DMA rounds: %u (expected 10)\n", + I2sManager::instance().callbackCount()); + printf(" Total pulses detected: %u (expected 70)\n", + s_analyzer.pulseCount()); + + bool correct = (I2sManager::instance().callbackCount() == 10) && + (s_analyzer.pulseCount() == 70); + test_result("DMA 10 rounds 7 pulses", correct); +} + +static void test_dma_buffer_content() { + printf("Running: DMA buffer content verification\n"); + + I2sManager::instance().init(32, 33, -1); + uint8_t* buf = I2sManager::instance().blockBuf(0); + + write_pulse_to_buffer(buf, 0); + write_pulse_to_buffer(buf, 25); + write_pulse_to_buffer(buf, 50); + write_pulse_to_buffer(buf, 75); + write_pulse_to_buffer(buf, 100); + write_pulse_to_buffer(buf, 124); + + uint32_t pulse_frames = 0; + for (uint16_t f = 0; f < I2S_FRAMES_PER_BLOCK; f++) { + if (buf[f * I2S_BYTES_PER_FRAME] & 0x80) { + pulse_frames++; + } + } + + printf(" Wrote 6 pulse frames\n"); + printf(" Detected pulse frames: %u\n", pulse_frames); + + test_result("DMA buffer content", pulse_frames == 6); +} + +static void test_dma_total_ticks_per_block() { + printf("Running: DMA total ticks per block\n"); + + s_analyzer.reset(); + s_analyzer.ticks_per_bit = 2; // 8MHz BCLK = 2 ticks at 16MHz per bit + I2sManager::instance().init(32, 33, -1); + I2sManager::instance().registerDmaCallback(dmaCallback); + + uint8_t* buf = + I2sManager::instance().blockBuf(I2sManager::instance().dmaBlock()); + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + I2sManager::instance().dmaConsumeBlock(); + + uint32_t expected_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + printf(" Ticks per block: %u (expected %u)\n", s_analyzer.total_ticks, + expected_ticks); + + test_result("DMA total ticks per block", + s_analyzer.total_ticks == expected_ticks); +} + +// --------------------------------------------------------------------------- +// Part 2: Driver fill function tests +// --------------------------------------------------------------------------- + +#define IRAM_ATTR +#include "pd_esp32/i2s_fill.cpp" + +#define NO_PIN 255 + +static bool fillAndDetectPulses(StepperQueueBase* q, uint8_t num_blocks, + uint32_t* pulse_ticks, + uint16_t* num_pulses_out); + +static uint32_t countPulsesInBuffer(const uint8_t* buf) { + uint32_t count = 0; + bool last_bit = false; + uint16_t total_bits = I2S_FRAMES_PER_BLOCK * I2S_BITS_PER_FRAME; + for (uint16_t bit_pos = 0; bit_pos < total_bits; bit_pos++) { + uint16_t byte_pos = (bit_pos >> 3) ^ 1; + uint8_t bit_offset = bit_pos & 7; + bool current = (buf[byte_pos] >> (7 - bit_offset)) & 1; + if (current && !last_bit) { + count++; + } + last_bit = current; + } + return count; +} + +static void add_command(StepperQueueBase* q, uint8_t steps, uint16_t ticks) { + uint8_t idx = q->next_write_idx & QUEUE_LEN_MASK; + q->entry[idx].steps = steps; + q->entry[idx].ticks = ticks; + q->entry[idx].toggle_dir = 0; + q->next_write_idx++; +} + +static void test_fill_skips_busy_block() { + printf("Running: Fill skips busy block, fills other\n"); + + I2sManager::instance().init(32, 33, -1); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + add_command(&q, 10, 200); + + struct i2s_fill_state state = {0, 0, 0}; + uint8_t write_block = 0; + uint8_t busy_block = 1; + + for (uint8_t blk = 0; blk < I2S_BLOCK_COUNT; blk++) { + memset(I2sManager::instance().blockBuf(blk), 0, I2S_BYTES_PER_BLOCK); + } + + while (write_block != busy_block) { + memset(buf, 0, I2S_BYTES_PER_BLOCK); + bool full = i2s_fill_buffer_direct(&q, buf, &state); + memcpy(I2sManager::instance().blockBuf(write_block), buf, + I2S_BYTES_PER_BLOCK); + if (full) { + write_block = (write_block + 1) % I2S_BLOCK_COUNT; + } else { + break; + } + } + + uint32_t pulses_busy = + countPulsesInBuffer(I2sManager::instance().blockBuf(busy_block)); + uint32_t pulses_0 = countPulsesInBuffer(I2sManager::instance().blockBuf(0)); + + printf(" Busy block %u pulses: %u (expected 0)\n", busy_block, pulses_busy); + printf(" Block 0 pulses: %u\n", pulses_0); + printf(" Write block stopped at: %u\n", write_block); + + test_result("Fill skips busy block", pulses_busy == 0 && pulses_0 > 0); +} + +static void test_write_pointer_resets_on_busy_match() { + printf("Running: Write pointer resets when matches busy block\n"); + + uint8_t write_block = 0; + uint8_t busy_block = 0; + + if (write_block == busy_block) { + write_block = (busy_block + 1) % I2S_BLOCK_COUNT; + } + bool ok1 = (write_block == 1); + printf(" After reset: write=%u (expected 1)\n", write_block); + + busy_block = 1; + if (write_block == busy_block) { + write_block = (busy_block + 1) % I2S_BLOCK_COUNT; + } + bool ok2 = (write_block == 0); // With 2 blocks, wraps back to 0 + printf(" After another reset: write=%u (expected 0 with 2 blocks)\n", + write_block); + + test_result("Write pointer resets on busy match", ok1 && ok2); +} + +static void test_fill_multiple_blocks_avoiding_busy() { + printf("Running: Fill multiple blocks avoiding busy block\n"); + + I2sManager::instance().init(32, 33, -1); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + add_command(&q, 100, 200); + + uint8_t busy_block = 1; + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + bool last_result = fillAndDetectPulses(&q, 3, pulse_ticks, &num_pulses); + + printf(" Busy block %u pulses: 0 (expected 0 - not filled)\n", busy_block); + printf(" Total pulses: %u (expected > 0)\n", num_pulses); + printf(" Last result: %s\n", last_result ? "true" : "false"); + + test_result("Fill multiple blocks avoiding busy", num_pulses > 0); +} + +static void test_fill_after_memset() { + printf("Running: Fill after memset clears old pulses\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + struct i2s_fill_state state = {0, 0, 0}; + + add_command(&q, 3, 200); + + printf(" Filling buffer with 3 steps...\n"); + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_first = countPulsesInBuffer(buf); + printf(" First fill with 3 steps: %u pulses\n", pulses_after_first); + + memset(buf, 0, I2S_BYTES_PER_BLOCK); + state.remaining_high_ticks = 0; + state.remaining_low_ticks = 0; + q.read_idx = 0; + q.next_write_idx = 0; + add_command(&q, 2, 300); + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_second = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" After memset and refill with 2 steps: %u pulses (expected 2)\n", + pulses_after_second); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill after memset clears old pulses", + pulses_after_first == 3 && pulses_after_second == 2 && consumed); +} + +static void test_fill_return_value_empty() { + printf("Running: Fill return value - empty queue returns false\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0xFF, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + struct i2s_fill_state state = {0, 0, 0}; + + bool buffer_full = i2s_fill_buffer_direct(&q, buf, &state); + + printf(" Empty queue: buffer_full=%s (expected false)\n", + buffer_full ? "true" : "false"); + + test_result("Fill return value empty", !buffer_full); +} + +static void test_fill_return_value_partial() { + printf("Running: Fill return value - partial fill returns false\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 3, 200); + + struct i2s_fill_state state = {0, 0, 0}; + + bool buffer_full = i2s_fill_buffer_direct(&q, buf, &state); + + printf(" 3 steps @ 200 ticks: buffer_full=%s (expected false)\n", + buffer_full ? "true" : "false"); + + test_result("Fill return value partial", !buffer_full); +} + +static void test_fill_return_value_full() { + printf("Running: Fill return value - full block returns true\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 200, 150); + + struct i2s_fill_state state = {0, 0, 0}; + + bool buffer_full = i2s_fill_buffer_direct(&q, buf, &state); + + printf(" 200 steps @ 150 ticks: buffer_full=%s (expected true)\n", + buffer_full ? "true" : "false"); + + test_result("Fill return value full", buffer_full); +} + +static void test_fill_return_value_pause_spans_block() { + printf("Running: Fill return value - pause spanning block returns true\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 0, 20000); + + struct i2s_fill_state state = {0, 0, 0}; + + bool buffer_full = i2s_fill_buffer_direct(&q, buf, &state); + + printf(" Pause 20000 ticks: buffer_full=%s (expected true)\n", + buffer_full ? "true" : "false"); + + test_result("Fill return value pause spans block", buffer_full); +} + +static void test_fill_overwrites_old_data() { + printf("Running: Fill clears previously tracked positions\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + struct i2s_fill_state state = {0, 0, 0}; + + add_command(&q, 5, 200); + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_first = countPulsesInBuffer(buf); + printf(" First fill with 5 steps: %u pulses\n", pulses_after_first); + + memset(buf, 0, I2S_BYTES_PER_BLOCK); + state = {0, 0, 0}; + q.read_idx = 0; + q.next_write_idx = 0; + add_command(&q, 3, 300); + + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_second = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Second fill with 3 steps: %u pulses\n", pulses_after_second); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill clears previous positions", + pulses_after_first == 5 && pulses_after_second == 3 && consumed); +} + +static void test_fill_partial_then_add_more() { + printf("Running: Fill partial, add command, fill again\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + struct i2s_fill_state state = {0, 0, 0}; + + add_command(&q, 2, 200); + + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_first = countPulsesInBuffer(buf); + printf(" First fill with 2 steps: %u pulses\n", pulses_after_first); + + memset(buf, 0, I2S_BYTES_PER_BLOCK); + add_command(&q, 1, 200); + + i2s_fill_buffer_direct(&q, buf, &state); + uint32_t pulses_after_second = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Second fill after adding 1 more step: %u pulses (expected 1)\n", + pulses_after_second); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill partial then add more", + pulses_after_first == 2 && pulses_after_second == 1 && consumed); +} + +static void test_fill_single_step() { + printf("Running: Fill single step at 256 ticks\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 256); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 1)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill single step", pulses == 1 && consumed); +} + +static void test_fill_multi_step() { + printf("Running: Fill 5 steps @ 128 ticks each\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 5, 128); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 5)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill multi step", pulses == 5 && consumed); +} + +static void test_fill_pause() { + printf("Running: Fill pause command (steps=0, ticks=5000)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 0, 5000); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 0)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill pause", pulses == 0 && consumed); +} + +static void test_fill_step_pause_step() { + printf("Running: Fill step + pause + step\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 256); + add_command(&q, 0, 512); + add_command(&q, 1, 256); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 2)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill step+pause+step", pulses == 2 && consumed); +} + +static void test_fill_block_boundary() { + printf("Running: Fill across block boundary (16000 ticks)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 16000); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 1)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill block boundary", pulses == 1 && consumed); +} + +static void test_fill_two_blocks() { + printf("Running: Fill across block boundary (16000 ticks pulse)\n"); + + uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 16000); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, bufs[0], &state); + uint32_t pulses1 = countPulsesInBuffer(bufs[0]); + printf(" Block 0: pulses=%u (expected 1)\n", pulses1); + + i2s_fill_buffer_direct(&q, bufs[1], &state); + uint32_t pulses2 = countPulsesInBuffer(bufs[1]); + bool consumed = (q.read_idx == q.next_write_idx); + printf(" Block 1: pulses=%u (expected 0), consumed=%s\n", pulses2, + consumed ? "yes" : "no"); + + test_result("Fill two blocks", pulses1 == 1 && pulses2 == 0 && consumed); +} + +static void test_fill_partial_steps() { + printf("Running: Fill partial steps (100 steps @ 200 ticks)\n"); + + uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 100, 200); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, bufs[0], &state); + + uint32_t pulses1 = countPulsesInBuffer(bufs[0]); + uint8_t remaining1 = q.entry[q.read_idx & QUEUE_LEN_MASK].steps; + uint16_t block_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + uint8_t expected_in_block = block_ticks / 200; + uint8_t expected_remaining1 = 100 - expected_in_block; + printf(" Block 1: pulses=%u (expected %u)\n", pulses1, expected_in_block); + printf(" Remaining steps: %u (expected %u)\n", remaining1, + expected_remaining1); + + i2s_fill_buffer_direct(&q, bufs[1], &state); + + uint32_t pulses2 = countPulsesInBuffer(bufs[1]); + bool consumed = (q.read_idx == q.next_write_idx); + uint8_t remaining2 = + consumed ? 0 : q.entry[q.read_idx & QUEUE_LEN_MASK].steps; + uint8_t expected_remaining2 = 100 - expected_in_block - expected_in_block; + printf(" Block 2: pulses=%u (expected %u), consumed=%s\n", pulses2, + expected_in_block, consumed ? "yes" : "no"); + printf(" Remaining after block 2: %u (expected %u)\n", remaining2, + expected_remaining2); + + test_result("Fill partial steps", pulses1 == expected_in_block && + remaining1 == expected_remaining1 && + pulses2 == expected_in_block && + !consumed && + remaining2 == expected_remaining2); +} + +static void test_fill_carry_ticks() { + printf("Running: Fill carry ticks (pause that spans block)\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 1000); + add_command(&q, 0, 12000); + add_command(&q, 1, 1000); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 2, pulse_ticks, &num_pulses); + bool consumed = q.read_idx == q.next_write_idx; + + printf(" Total pulses: %u (expected 2)\n", num_pulses); + printf(" Consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill carry ticks", num_pulses == 2 && consumed); +} + +static void test_fill_empty_queue() { + printf("Running: Fill with empty queue\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 0)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill empty queue", pulses == 0 && consumed); +} + +static void test_fill_min_speed() { + printf("Running: Fill at minimum speed (128 ticks)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 3, I2S_DIRECT_MIN_SPEED_TICKS); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 3)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill min speed", pulses == 3 && consumed); +} + +static uint32_t detectPulsePositions(const uint8_t* buf, uint32_t buf_size, + uint32_t* positions) { + uint32_t count = 0; + uint8_t prev_bit = 0; + uint32_t total_bits = buf_size * 8; + + for (uint32_t bit_pos = 0; bit_pos < total_bits; bit_pos++) { + uint32_t byte_pos = (bit_pos >> 3) ^ 1; + uint8_t bit_offset = bit_pos & 7; + uint8_t curr_bit = (buf[byte_pos] >> (7 - bit_offset)) & 1; + if (curr_bit == 1 && prev_bit == 0) { + positions[count++] = bit_pos; + } + prev_bit = curr_bit; + } + return count; +} + +static bool fillAndDetectPulses(StepperQueueBase* q, uint8_t num_blocks, + uint32_t* pulse_ticks, + uint16_t* num_pulses_out) { + static uint8_t buf[255 * I2S_BYTES_PER_BLOCK]; + memset(buf, 0, sizeof(buf)); + + struct i2s_fill_state state = {0, 0, 0}; + bool last_result = false; + + printf("DEBUG: fillAndDetectPulses start\n"); + fflush(stdout); + for (uint8_t blk = 0; blk < num_blocks; blk++) { + printf("DEBUG: filling block %d, read_idx=%d, next_write_idx=%d\n", blk, + q->read_idx, q->next_write_idx); + fflush(stdout); + last_result = + i2s_fill_buffer_direct(q, &buf[blk * I2S_BYTES_PER_BLOCK], &state); + printf("DEBUG: block %d done, result=%d\n", blk, last_result); + fflush(stdout); + } + printf("DEBUG: detecting pulses\n"); + + uint32_t positions[300]; + uint32_t num_pulses = + detectPulsePositions(buf, num_blocks * I2S_BYTES_PER_BLOCK, positions); + + for (uint32_t i = 0; i < num_pulses; i++) { + printf(" Detected pulse %d at bit position: %u\n", i, positions[i]); + pulse_ticks[i] = positions[i] * 2; + } + pulse_ticks[num_pulses] = 0; + *num_pulses_out = num_pulses; + + puts("DONE"); + + return last_result; +} + +static void test_fill_255_steps_83_ticks() { + printf("Running: Fill 255 steps @ 83 ticks - calculate frequency\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 255, 83); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 3, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 255)\n", num_pulses); + + if (num_pulses < 2) { + printf(" Not enough pulses for frequency calculation\n"); + test_result("Fill 255 steps @ 83 ticks freq", false); + return; + } + + uint32_t first_tick = pulse_ticks[0]; + uint32_t last_tick = pulse_ticks[num_pulses - 1]; + uint32_t time_diff = last_tick - first_tick; + + if (time_diff == 0) { + printf(" Time diff is zero, cannot calculate frequency\n"); + test_result("Fill 255 steps @ 83 ticks freq", false); + return; + } + + uint32_t freq = (num_pulses - 1) * 16000000UL / time_diff; + + printf(" First pulse tick: %u\n", first_tick); + printf(" Last pulse tick: %u\n", last_tick); + printf(" Time diff: %u ticks\n", time_diff); + printf(" Frequency: %u Hz (expected ~192771)\n", freq); + + bool correct = (num_pulses == 255) && (first_tick == 0) && (freq > 190000) && + (freq < 195000); + test_result("Fill 255 steps @ 83 ticks freq", correct); +} + +static void test_fill_max_steps() { + printf("Running: Fill max steps in one command (255 steps)\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 255, 128); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 10, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 255)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill max steps", + num_pulses == 255 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_long_pause() { + printf("Running: Fill long pause spanning multiple blocks\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 0, 50000); + add_command(&q, 1, 256); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 10, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 1)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill long pause", + num_pulses == 1 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_pulse_at_exact_boundary() { + printf("Running: Fill pulse at exact block boundary\n"); + + uint16_t block_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, block_ticks); + add_command(&q, 1, 256); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 2, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 2)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill pulse at exact boundary", + num_pulses == 2 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_multiple_commands() { + printf("Running: Fill multiple mixed commands\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 2, 200); + add_command(&q, 0, 1000); + add_command(&q, 3, 300); + add_command(&q, 0, 500); + add_command(&q, 1, 150); + + struct i2s_fill_state state = {0, 0, 0}; + + memset(buf, 0, I2S_BYTES_PER_BLOCK); + i2s_fill_buffer_direct(&q, buf, &state); + + uint32_t pulses = countPulsesInBuffer(buf); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 6 = 2+3+1)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("Fill multiple commands", pulses == 6 && consumed); +} + +static void test_fill_consecutive_partial() { + printf("Running: Fill consecutive partial steps across blocks\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 200, 150); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 10, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 200)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill consecutive partial", + num_pulses == 200 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_max_ticks_single_step() { + printf("Running: Fill two steps at max ticks (65535)\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 2, 65535); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 20, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 2)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill max ticks single step", + num_pulses == 2 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_max_ticks_max_steps() { + printf("Running: Fill 4 steps at max ticks (65535 each)\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 4, 65535); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 50, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 4)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill max ticks max steps", + num_pulses == 4 && (q.read_idx == q.next_write_idx)); +} + +static void test_fill_max_pause() { + printf("Running: Fill max pause (65535 ticks) between two steps\n"); + + StepperQueueBase q; + q.read_idx = 0; + q.next_write_idx = 0; + q.dirPin = NO_PIN; + + add_command(&q, 1, 1000); + add_command(&q, 0, 65535); + add_command(&q, 1, 1000); + + uint32_t pulse_ticks[300] = {0}; + uint16_t num_pulses = 0; + fillAndDetectPulses(&q, 20, pulse_ticks, &num_pulses); + + printf(" Total pulses: %u (expected 2)\n", num_pulses); + printf(" Queue consumed: %s\n", + (q.read_idx == q.next_write_idx) ? "yes" : "no"); + + test_result("Fill max pause", + num_pulses == 2 && (q.read_idx == q.next_write_idx)); +} + +void basic_test() { + puts("=== I2S Low-Level DMA Tests ===\n"); + fflush(stdout); + + puts("=== DMA Callback Tests ==="); + test_dma_callback_invoked(); + + puts("\n=== DMA Block Management ==="); + test_dma_block_rotation(); + test_dma_buffer_not_cleared_on_consume(); + + puts("\n=== Bit Stream Analysis ==="); + test_bit_stream_single_pulse(); + test_bit_stream_multiple_pulses(); + test_dma_total_ticks_per_block(); + + puts("\n=== DMA Round Tests ==="); + test_dma_10_rounds_7_pulses(); + test_dma_buffer_content(); + + puts("\n=== Part 2: Driver Fill Function ==="); + test_fill_after_memset(); + test_fill_overwrites_old_data(); + test_fill_return_value_empty(); + test_fill_return_value_partial(); + test_fill_return_value_full(); + test_fill_return_value_pause_spans_block(); + test_fill_partial_then_add_more(); + test_fill_skips_busy_block(); + test_write_pointer_resets_on_busy_match(); + test_fill_multiple_blocks_avoiding_busy(); + test_fill_single_step(); + test_fill_multi_step(); + test_fill_pause(); + test_fill_step_pause_step(); + test_fill_block_boundary(); + test_fill_two_blocks(); + test_fill_partial_steps(); + test_fill_carry_ticks(); + + puts("\n=== Part 2: Edge Cases ==="); + test_fill_empty_queue(); + test_fill_min_speed(); + test_fill_255_steps_83_ticks(); + test_fill_max_steps(); + test_fill_long_pause(); + test_fill_pulse_at_exact_boundary(); + test_fill_multiple_commands(); + test_fill_consecutive_partial(); + test_fill_max_ticks_single_step(); + test_fill_max_ticks_max_steps(); + test_fill_max_pause(); + + printf("\n=== Test Summary ===\n"); + printf("Total: %d Passed: %d Failed: %d\n", test_passed + test_failed, + test_passed, test_failed); + if (test_failed == 0) { + puts("All tests PASSED"); + } else { + printf("%d test(s) FAILED\n", test_failed); + } +} + +int main() { + basic_test(); + return test_failed ? 1 : 0; +} diff --git a/tests/host/test_22.cpp b/tests/host/test_22.cpp new file mode 100644 index 0000000..aab26d7 --- /dev/null +++ b/tests/host/test_22.cpp @@ -0,0 +1,1035 @@ +// test_22: ESP32 I2S MUX mode fill buffer tests +// +// Tests i2s_fill_buffer_mux() with frame-level resolution. +// MUX mode uses 74HC595 shift register for up to 32 steppers. + +#define SUPPORT_ESP32_I2S + +#include +#include +#include +#include +#include + +#include "pd_esp32/i2s_constants.h" +#include "fas_queue/stepper_queue.h" + +static int test_passed = 0; +static int test_failed = 0; + +static void test_result(const char* name, bool passed) { + if (passed) { + printf("PASS: %s\n", name); + test_passed++; + } else { + printf("FAIL: %s\n", name); + test_failed++; + } +} + +#define IRAM_ATTR +#include "pd_esp32/i2s_fill.cpp" + +#define NO_PIN 255 + +static void add_command(StepperQueueBase* q, uint8_t steps, uint16_t ticks) { + uint8_t idx = q->next_write_idx & QUEUE_LEN_MASK; + q->entry[idx].steps = steps; + q->entry[idx].ticks = ticks; + q->entry[idx].toggle_dir = 0; + q->next_write_idx++; +} + +// MUX-specific helpers +static uint32_t countPulsesInSlot(const uint8_t* buf, uint8_t byte_offset, + uint8_t bit_mask) { + uint32_t count = 0; + for (uint16_t frame = 0; frame < I2S_FRAMES_PER_BLOCK; frame++) { + uint8_t val = buf[frame * I2S_BYTES_PER_FRAME + byte_offset]; + if (val & bit_mask) { + count++; + } + } + return count; +} + +static uint8_t getByteOffset(uint8_t slot) { return i2s_mux_byte_offset(slot); } +static uint8_t getBitMask(uint8_t slot) { return i2s_mux_bit_mask(slot); } + +static void setupMuxQueue(StepperQueue* q, uint8_t slot) { + q->read_idx = 0; + q->next_write_idx = 0; + q->dirPin = NO_PIN; +} + +static bool fillAndDetectPulses_mux(StepperQueue* q, uint8_t num_blocks, + uint8_t slot, uint16_t* num_pulses_out) { + uint8_t buf[I2S_BYTES_PER_BLOCK]; + struct i2s_fill_state state = {0, 0, 0}; + uint8_t byte_offset = getByteOffset(slot); + uint8_t bit_mask = getBitMask(slot); + bool last_result = false; + uint16_t total_pulses = 0; + + for (uint8_t blk = 0; blk < num_blocks; blk++) { + memset(buf, 0, I2S_BYTES_PER_BLOCK); + last_result = i2s_fill_buffer_mux(q, buf, &state, byte_offset, bit_mask); + total_pulses += countPulsesInSlot(buf, byte_offset, bit_mask); + + if (q->read_idx == q->next_write_idx && state.remaining_low_ticks == 0 && + state.remaining_high_ticks == 0) { + break; + } + } + + *num_pulses_out = total_pulses; + return last_result; +} + +// ============================================================================ +// Part 1: Single Stepper Frame-Level Tests +// ============================================================================ + +static void test_mux_single_step() { + printf("Running: MUX single step @ 128 ticks\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 1, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 1)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX single step", pulses == 1 && consumed); +} + +static void test_mux_multi_step() { + printf("Running: MUX 5 steps @ 128 ticks\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 5, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 5)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX multi step", pulses == 5 && consumed); +} + +static void test_mux_step_pause_step() { + printf("Running: MUX step + pause + step\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 1, 128); + add_command(&q, 0, 256); + add_command(&q, 1, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 2)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX step+pause+step", pulses == 2 && consumed); +} + +static void test_mux_empty_queue() { + printf("Running: MUX empty queue\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + struct i2s_fill_state state = {0, 0, 0}; + bool result = + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + + printf(" Pulses: %u (expected 0)\n", pulses); + printf(" Return: %s (expected false)\n", result ? "true" : "false"); + + test_result("MUX empty queue", pulses == 0 && !result); +} + +static void test_mux_pause_only() { + printf("Running: MUX pause only (steps=0)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 0, 1000); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 0)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX pause only", pulses == 0 && consumed); +} + +// ============================================================================ +// Part 2: off_ticks Compensation Tests +// ============================================================================ + +static void test_mux_off_ticks_carry() { + printf("Running: MUX off_ticks carry (verify step at correct position)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 1, 100); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 1)\n", pulses); + printf(" off_ticks after: %u\n", state.off_ticks); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX off_ticks carry", pulses == 1 && consumed); +} + +static void test_mux_off_ticks_across_blocks() { + printf("Running: MUX off_ticks across blocks\n"); + + uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 1, 100); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_mux(&q, bufs[0], &state, getByteOffset(0), getBitMask(0)); + uint32_t pulses1 = + countPulsesInSlot(bufs[0], getByteOffset(0), getBitMask(0)); + + add_command(&q, 1, 100); + i2s_fill_buffer_mux(&q, bufs[1], &state, getByteOffset(0), getBitMask(0)); + uint32_t pulses2 = + countPulsesInSlot(bufs[1], getByteOffset(0), getBitMask(0)); + + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Block 1 pulses: %u\n", pulses1); + printf(" Block 2 pulses: %u (expected 1, with off_ticks=%u)\n", pulses2, + state.off_ticks); + printf(" Total pulses: %u (expected 2)\n", pulses1 + pulses2); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX off_ticks across blocks", + pulses1 + pulses2 == 2 && consumed); +} + +static void test_mux_off_ticks_zero() { + printf("Running: MUX off_ticks zero (exact frame multiple)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 3, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 3)\n", pulses); + printf(" off_ticks: %u (expected 0)\n", state.off_ticks); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX off_ticks zero", + pulses == 3 && state.off_ticks == 0 && consumed); +} + +static void test_mux_off_ticks_compensation() { + printf("Running: MUX off_ticks compensation (255 steps @ 431 ticks)\n"); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 255, 431); + + uint16_t num_pulses = 0; + fillAndDetectPulses_mux(&q, 20, 0, &num_pulses); + + bool consumed = (q.read_idx == q.next_write_idx); + printf(" Total pulses: %u (expected 255)\n", num_pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX off_ticks compensation 255@431", + num_pulses == 255 && consumed); +} + +static bool onlyTargetSlotUsed(const uint8_t* buf, uint8_t byte_offset, + uint8_t bit_mask) { + for (uint16_t frame = 0; frame < I2S_FRAMES_PER_BLOCK; frame++) { + for (uint8_t b = 0; b < I2S_BYTES_PER_FRAME; b++) { + uint8_t v = buf[frame * I2S_BYTES_PER_FRAME + b]; + if (b == byte_offset) { + if (v & ~bit_mask) { + return false; + } + } else if (v != 0) { + return false; + } + } + } + return true; +} + +static void test_mux_slot_0_isolation() { + printf("Running: MUX slot 0 isolation\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 3, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses_in_slot = + countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool isolated = onlyTargetSlotUsed(buf, getByteOffset(0), getBitMask(0)); + + printf(" Slot 0 pulses: %u (expected 3)\n", pulses_in_slot); + printf(" Isolated: %s\n", isolated ? "yes" : "no"); + + test_result("MUX slot 0 isolation", pulses_in_slot == 3 && isolated); +} + +static void test_mux_slot_7_isolation() { + printf("Running: MUX slot 7 isolation\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 7); + + add_command(&q, 3, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(7), getBitMask(7)); + + uint32_t pulses_in_slot = + countPulsesInSlot(buf, getByteOffset(7), getBitMask(7)); + bool isolated = onlyTargetSlotUsed(buf, getByteOffset(7), getBitMask(7)); + + printf(" Slot 7 pulses: %u (expected 3)\n", pulses_in_slot); + printf(" Isolated: %s\n", isolated ? "yes" : "no"); + + test_result("MUX slot 7 isolation", pulses_in_slot == 3 && isolated); +} + +static void test_mux_slot_15_isolation() { + printf("Running: MUX slot 15 isolation\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 15); + + add_command(&q, 2, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(15), getBitMask(15)); + + uint32_t pulses_in_slot = + countPulsesInSlot(buf, getByteOffset(15), getBitMask(15)); + bool isolated = onlyTargetSlotUsed(buf, getByteOffset(15), getBitMask(15)); + + printf(" Slot 15 pulses: %u (expected 2)\n", pulses_in_slot); + printf(" Isolated: %s\n", isolated ? "yes" : "no"); + + test_result("MUX slot 15 isolation", pulses_in_slot == 2 && isolated); +} + +static void test_mux_slot_31_isolation() { + printf("Running: MUX slot 31 isolation\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 31); + + add_command(&q, 2, 128); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(31), getBitMask(31)); + + uint32_t pulses_in_slot = + countPulsesInSlot(buf, getByteOffset(31), getBitMask(31)); + bool isolated = onlyTargetSlotUsed(buf, getByteOffset(31), getBitMask(31)); + + printf(" Slot 31 pulses: %u (expected 2)\n", pulses_in_slot); + printf(" Isolated: %s\n", isolated ? "yes" : "no"); + + test_result("MUX slot 31 isolation", pulses_in_slot == 2 && isolated); +} + +static void test_mux_two_steppers_same_buffer() { + printf("Running: MUX two steppers same buffer (OR operation)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q1, q2; + setupMuxQueue(&q1, 0); + setupMuxQueue(&q2, 1); + + add_command(&q1, 2, 128); + add_command(&q2, 3, 128); + + struct i2s_fill_state state1 = {0, 0, 0}; + struct i2s_fill_state state2 = {0, 0, 0}; + + i2s_fill_buffer_mux(&q1, buf, &state1, getByteOffset(0), getBitMask(0)); + i2s_fill_buffer_mux(&q2, buf, &state2, getByteOffset(1), getBitMask(1)); + + uint32_t pulses_slot0 = + countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + uint32_t pulses_slot1 = + countPulsesInSlot(buf, getByteOffset(1), getBitMask(1)); + + printf(" Slot 0 pulses: %u (expected 2)\n", pulses_slot0); + printf(" Slot 1 pulses: %u (expected 3)\n", pulses_slot1); + + test_result("MUX two steppers OR", pulses_slot0 == 2 && pulses_slot1 == 3); +} + +// ============================================================================ +// Part 4: Block Boundary Tests +// ============================================================================ + +static void test_mux_block_boundary() { + printf("Running: MUX block boundary\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + uint16_t block_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + add_command(&q, 1, block_ticks); + + struct i2s_fill_state state = {0, 0, 0}; + bool full = + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + + printf(" Pulses: %u (expected 1)\n", pulses); + printf(" Return: %s (expected true)\n", full ? "true" : "false"); + + test_result("MUX block boundary", pulses == 1 && full); +} + +static void test_mux_pause_spans_block() { + printf("Running: MUX step spans multiple blocks\n"); + + StepperQueue q; + setupMuxQueue(&q, 0); + + uint16_t block_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + add_command(&q, 1, block_ticks + 256); + + uint16_t num_pulses = 0; + fillAndDetectPulses_mux(&q, 3, 0, &num_pulses); + + bool consumed = (q.read_idx == q.next_write_idx); + printf(" Total pulses: %u (expected 1)\n", num_pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX step spans blocks", num_pulses == 1 && consumed); +} + +static void test_mux_return_value_full() { + printf("Running: MUX return value full\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + uint16_t block_ticks = I2S_FRAMES_PER_BLOCK * I2S_TICKS_PER_FRAME; + add_command(&q, 1, block_ticks); + + struct i2s_fill_state state = {0, 0, 0}; + bool result = + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + printf(" Return: %s (expected true)\n", result ? "true" : "false"); + + test_result("MUX return value full", result); +} + +static void test_mux_return_value_partial() { + printf("Running: MUX return value partial\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 2, 128); + + struct i2s_fill_state state = {0, 0, 0}; + bool result = + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + printf(" Return: %s (expected false)\n", result ? "true" : "false"); + + test_result("MUX return value partial", !result); +} + +// ============================================================================ +// Part 5: Edge Cases +// ============================================================================ + +static void test_mux_max_steps() { + printf("Running: MUX max steps (255 @ 64 ticks)\n"); + + uint8_t bufs[3][I2S_BYTES_PER_BLOCK]; + for (int i = 0; i < 3; i++) { + memset(bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 255, 64); + + struct i2s_fill_state state = {0, 0, 0}; + uint32_t total_pulses = 0; + + for (int blk = 0; blk < 3; blk++) { + i2s_fill_buffer_mux(&q, bufs[blk], &state, getByteOffset(0), getBitMask(0)); + total_pulses += + countPulsesInSlot(bufs[blk], getByteOffset(0), getBitMask(0)); + } + + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Total pulses: %u (expected 255)\n", total_pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX max steps 255@64", total_pulses == 255 && consumed); +} + +static void test_mux_long_pause() { + printf("Running: MUX long pause (65535 ticks) + step\n"); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 0, 65535); + add_command(&q, 1, 128); + + uint16_t num_pulses = 0; + fillAndDetectPulses_mux(&q, 15, 0, &num_pulses); + + bool consumed = (q.read_idx == q.next_write_idx); + printf(" Total pulses: %u (expected 1)\n", num_pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX long pause", num_pulses == 1 && consumed); +} + +static void test_mux_min_speed() { + printf("Running: MUX min speed (400 ticks)\n"); + + uint8_t buf[I2S_BYTES_PER_BLOCK]; + memset(buf, 0, I2S_BYTES_PER_BLOCK); + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 3, I2S_MUX_MIN_SPEED_TICKS); + + struct i2s_fill_state state = {0, 0, 0}; + i2s_fill_buffer_mux(&q, buf, &state, getByteOffset(0), getBitMask(0)); + + uint32_t pulses = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Pulses: %u (expected 3)\n", pulses); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX min speed", pulses == 3 && consumed); +} + +static void test_mux_partial_steps() { + printf("Running: MUX partial steps (100 @ 100 ticks)\n"); + + uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + for (int i = 0; i < I2S_BLOCK_COUNT; i++) { + memset(bufs[i], 0, I2S_BYTES_PER_BLOCK); + } + + StepperQueue q; + setupMuxQueue(&q, 0); + + add_command(&q, 100, 100); + + struct i2s_fill_state state = {0, 0, 0}; + + i2s_fill_buffer_mux(&q, bufs[0], &state, getByteOffset(0), getBitMask(0)); + uint32_t pulses1 = + countPulsesInSlot(bufs[0], getByteOffset(0), getBitMask(0)); + + i2s_fill_buffer_mux(&q, bufs[1], &state, getByteOffset(0), getBitMask(0)); + uint32_t pulses2 = + countPulsesInSlot(bufs[1], getByteOffset(0), getBitMask(0)); + + bool consumed = (q.read_idx == q.next_write_idx); + + printf(" Block 1 pulses: %u\n", pulses1); + printf(" Block 2 pulses: %u (expected > 0)\n", pulses2); + printf(" Total: %u (expected 100)\n", pulses1 + pulses2); + printf(" Queue consumed: %s\n", consumed ? "yes" : "no"); + + test_result("MUX partial steps", pulses1 + pulses2 == 100 && consumed); +} + +// ============================================================================ +// Part 6: Position-exact, many queues, one shared buffer +// ============================================================================ +// +// Everything above asserts pulse COUNTS, which cannot see a pulse landing one +// frame early or late: the count still matches and only the timing is wrong. +// They also memset(0) the buffer, while the driver seeds every frame from +// _mux_state before any queue touches it (init_mux_buffer), and at most two +// queues ever share a buffer. So the three things the failing sweep actually +// exercised -- the seed, the OR of many slots, and the frame each pulse lands +// in -- were untested. +// +// This drives N queues into one shared buffer the way handleTxDone() does and +// compares every byte of every frame against a model built from the tick +// arithmetic alone, so a fill that is off by a frame fails here rather than on +// a logic analyzer 300 ms later. + +#define MUX_POS_MAX_SLOTS 32 +// Sized for the slowest case below: 64 steps at 1600 ticks is 1600 frames. +#define MUX_POS_MAX_FRAMES (I2S_FRAMES_PER_BLOCK * 16) + +// init_mux_buffer() from i2s_manager.cpp, which test_22 does not link. +static void seed_mux_buffer(uint8_t* buf, uint32_t mux_state) { + uint32_t* b = reinterpret_cast(buf); + uint8_t i = I2S_BYTES_PER_BLOCK / 4; + do { + b[--i] = mux_state; + } while (i); +} + +// A step's pulse sits in the frame containing its start tick, and start tick of +// step k is k * ticks. 400 ticks is 6.25 frames, so the frame sequence is +// 6, 6, 6, 7, ... -- the frame-quantised period the harness has to allow for. +static uint16_t ref_frame(uint16_t k, uint16_t ticks) { + return (uint16_t)((uint32_t)k * ticks / I2S_TICKS_PER_FRAME); +} + +static uint8_t seed_byte(uint32_t seed, uint8_t byte_index) { + return (uint8_t)((seed >> (8 * byte_index)) & 0xFF); +} + +static bool check_mux_positions(uint8_t nslots, uint16_t ticks, uint16_t steps, + uint32_t seed, bool verbose) { + static StepperQueue q[MUX_POS_MAX_SLOTS]; + static struct i2s_fill_state st[MUX_POS_MAX_SLOTS]; + static uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + static uint8_t want[MUX_POS_MAX_SLOTS][MUX_POS_MAX_FRAMES]; + bool ok = true; + + for (uint8_t s = 0; s < nslots; s++) { + setupMuxQueue(&q[s], s); + st[s].remaining_low_ticks = 0; + st[s].remaining_high_ticks = 0; + st[s].off_ticks = 0; + add_command(&q[s], steps, ticks); + memset(want[s], 0, MUX_POS_MAX_FRAMES); + for (uint16_t k = 0; k < steps; k++) { + uint16_t f = ref_frame(k, ticks); + if (f < MUX_POS_MAX_FRAMES) { + want[s][f] = 1; + } + } + } + memset(bufs, 0, sizeof(bufs)); + + uint32_t total_frames = (uint32_t)steps * ticks / I2S_TICKS_PER_FRAME; + uint16_t blocks = (uint16_t)(total_frames / I2S_FRAMES_PER_BLOCK) + 2; + + uint16_t seen_total = 0; + for (uint16_t blk = 0; blk < blocks; blk++) { + uint8_t* buf = bufs[blk % I2S_BLOCK_COUNT]; + seed_mux_buffer(buf, seed); + for (uint8_t s = 0; s < nslots; s++) { + i2s_fill_buffer_mux(&q[s], buf, &st[s], getByteOffset(s), getBitMask(s)); + } + + uint16_t f0 = (uint16_t)(blk * I2S_FRAMES_PER_BLOCK); + for (uint16_t s = 0; s < nslots; s++) { + uint16_t seen = 0; + for (uint16_t f = 0; f < I2S_FRAMES_PER_BLOCK; f++) { + uint16_t abs = f0 + f; + uint8_t got = + (buf[f * I2S_BYTES_PER_FRAME + getByteOffset(s)] & getBitMask(s)) + ? 1 + : 0; + uint8_t exp = (abs < MUX_POS_MAX_FRAMES) ? want[s][abs] : 0; + seen += got; + if (got != exp) { + if (ok && verbose) { + printf(" slot %2u: frame %u (abs %u) is %u, expected %u\n", s, f, + abs, got, exp); + } + ok = false; + } + } + seen_total += seen; + } + + // Bytes the steppers do not own must come through the fill untouched, i.e. + // still be exactly what init_mux_buffer seeded. + for (uint16_t f = 0; f < I2S_FRAMES_PER_BLOCK; f++) { + for (uint8_t b = 0; b < I2S_BYTES_PER_FRAME; b++) { + uint8_t exp = seed_byte(seed, b); + for (uint8_t s = 0; s < nslots; s++) { + if (getByteOffset(s) == b) { + uint16_t abs = (uint16_t)(f0 + f); + if (abs < MUX_POS_MAX_FRAMES && want[s][abs]) { + exp |= getBitMask(s); + } + } + } + uint8_t got = buf[f * I2S_BYTES_PER_FRAME + b]; + if (got != exp) { + if (ok && verbose) { + printf(" block %u frame %u byte %u is 0x%02x, expected 0x%02x\n", + blk, f, b, got, exp); + } + ok = false; + } + } + } + } + + uint16_t exp_per_slot = steps; + if (verbose) { + printf(" slots %u, %u steps @ %u ticks = %u frames over %u blocks\n", + nslots, steps, ticks, total_frames, blocks); + printf(" pulses seen in slot 0: %u (expected %u)\n", seen_total / nslots, + exp_per_slot); + printf(" seed word 0x%08lx preserved outside step slots: %s\n", + (unsigned long)seed, ok ? "yes" : "NO"); + } + + for (uint8_t s = 0; s < nslots; s++) { + if (q[s].read_idx != q[s].next_write_idx) { + if (verbose) { + printf(" slot %u: queue not fully consumed\n", s); + } + ok = false; + } + } + return ok; +} + +static void test_mux_positions_20_slots() { + printf("Running: MUX positions, 20 slots @ 400 ticks, 64 steps\n"); + // Slots 20..31 are unused at n=20 and stand in for the dir bits a `dir` mode + // run would hold there, so the seed is not trivially zero. + test_result( + "MUX positions 20 slots", + check_mux_positions(20, I2S_MUX_MIN_SPEED_TICKS, 64, 0xFFF00000u, true)); +} + +static void test_mux_positions_26_slots() { + printf("Running: MUX positions, 26 slots @ 400 ticks, 64 steps\n"); + // n=26 is the sweep point that lost slot 16 alone. + test_result( + "MUX positions 26 slots", + check_mux_positions(26, I2S_MUX_MIN_SPEED_TICKS, 64, 0xFC000000u, true)); +} + +static void test_mux_positions_all_slots() { + printf("Running: MUX positions, all 32 slots @ 400 ticks, 64 steps\n"); + test_result("MUX positions 32 slots", + check_mux_positions(32, I2S_MUX_MIN_SPEED_TICKS, 64, 0u, true)); +} + +static void test_mux_positions_slow_and_fast() { + printf("Running: MUX positions at other periods\n"); + bool a = check_mux_positions(20, 401, 64, 0xFFF00000u, false); + bool b = check_mux_positions(20, 640, 64, 0xFFF00000u, false); + bool c = check_mux_positions(20, 1000, 64, 0xFFF00000u, false); + bool d = check_mux_positions(8, 1600, 64, 0u, false); + test_result("MUX positions 401/640/1000/1600 ticks", a && b && c && d); +} + +static void test_mux_positions_queue_drains_midrun() { + printf("Running: MUX positions with the queue draining mid-block\n"); + // The path test_22 never takes: the fill returns false part way through a + // block (queue empty), _isRunning goes false, and a later addQueueEntry has + // to resume from the saved tick state rather than from the start of a block. + StepperQueue q; + setupMuxQueue(&q, 0); + uint8_t buf[I2S_BYTES_PER_BLOCK]; + struct i2s_fill_state st = {0, 0, 0}; + bool ok = true; + + // 2 steps at 400 ticks: the block is 125 frames = 8000 ticks, so this fits + // and the block ends with the queue already empty. + add_command(&q, 2, 400); + seed_mux_buffer(buf, 0); + bool full = + i2s_fill_buffer_mux(&q, buf, &st, getByteOffset(0), getBitMask(0)); + uint32_t first = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + // false means "queue drained", which is what happened: 2 steps at 400 ticks + // is 800 ticks and the block is 8000. The unfilled rest of the block stays at + // the seed, which is correct. + if (first != 2 || full) { + printf(" block 1: %u pulses, full=%d (expected 2, false)\n", first, full); + ok = false; + } + + // Now a pause long enough to span a block boundary, then a step. The step + // must land on the frame its tick arithmetic names, not on the first frame. + add_command(&q, 0, 9000); // 9000 ticks = 140 frames > one block + add_command(&q, 1, 400); + memset(buf, 0, sizeof(buf)); + seed_mux_buffer(buf, 0); + i2s_fill_buffer_mux(&q, buf, &st, getByteOffset(0), getBitMask(0)); + memset(buf, 0, sizeof(buf)); + seed_mux_buffer(buf, 0); + i2s_fill_buffer_mux(&q, buf, &st, getByteOffset(0), getBitMask(0)); + uint32_t second = countPulsesInSlot(buf, getByteOffset(0), getBitMask(0)); + if (second != 1) { + printf(" after the pause: %u pulses in the next block (expected 1)\n", + second); + ok = false; + } + if (q.read_idx != q.next_write_idx) { + printf(" queue not consumed\n"); + ok = false; + } + test_result("MUX positions across a drained queue", ok); +} + +// Do independently-filled queues stay in phase? +// +// Measured on hardware at 20 slots: the bus carried two distinct words per +// period instead of one -- 0x0000FFFF (slots 0-15) and 0x000F0000 (slots 16-19) +// -- each internally perfect at 6,6,6,7 frames, but offset from each other by +// about one step. That offset is what makes a dropped frame hit "16 of 20" and +// then "1 of 26, slot 16": the victims are a phase group, not a slot range. +// +// Nothing in i2s_fill_buffer_mux() can create that -- it is called per queue +// with its own state and touches only its own byte_offset/bit_mask. So either +// the fill introduces skew, or the queues were started at different times. This +// starts 20 queues from the same instant with the same command and asserts +// every one of them puts its pulses in the same frames. If this passes, the +// skew is not in the fill and the queues did not start together. +static void test_mux_queues_start_in_phase() { + printf("Running: MUX 20 queues started together stay in phase\n"); + + enum { N = 20 }; + StepperQueue q[N]; + struct i2s_fill_state st[N]; + uint8_t bufs[I2S_BLOCK_COUNT][I2S_BYTES_PER_BLOCK]; + + for (uint8_t s = 0; s < N; s++) { + setupMuxQueue(&q[s], s); + st[s].remaining_low_ticks = 0; + st[s].remaining_high_ticks = 0; + st[s].off_ticks = 0; + add_command(&q[s], 255, I2S_MUX_MIN_SPEED_TICKS); + } + memset(bufs, 0, sizeof(bufs)); + + // One shared tick timeline: every queue runs the same 255 steps at the same + // period, so a bit is set in frame f exactly when some step starts in f. + static uint8_t common[MUX_POS_MAX_FRAMES]; + memset(common, 0, sizeof(common)); + for (uint16_t k = 0; k < 255; k++) { + uint16_t f = ref_frame(k, I2S_MUX_MIN_SPEED_TICKS); + if (f < MUX_POS_MAX_FRAMES) { + common[f] = 1; + } + } + + bool ok = true; + uint16_t blk = 0; + uint16_t pulses_per_block = 0; + while (blk < 6) { + uint8_t* buf = bufs[blk % I2S_BLOCK_COUNT]; + seed_mux_buffer(buf, 0); + for (uint8_t s = 0; s < N; s++) { + i2s_fill_buffer_mux(&q[s], buf, &st[s], getByteOffset(s), getBitMask(s)); + } + + for (uint16_t f = 0; f < I2S_FRAMES_PER_BLOCK; f++) { + uint16_t abs = (uint16_t)(blk * I2S_FRAMES_PER_BLOCK + f); + if (abs < MUX_POS_MAX_FRAMES && common[abs]) { + pulses_per_block++; + } + // All 20 slots must agree: byte b is 0xFF/0x0F/... in a pulse frame and + // exactly the seed everywhere else. Any disagreement between slots is a + // phase split, which is the hardware symptom this test exists to catch. + for (uint8_t b = 0; b < I2S_BYTES_PER_FRAME; b++) { + uint8_t expect = 0; + if (abs < MUX_POS_MAX_FRAMES && common[abs]) { + for (uint8_t s = 0; s < N; s++) { + if (getByteOffset(s) == b) { + expect |= getBitMask(s); + } + } + } + uint8_t got = buf[f * I2S_BYTES_PER_FRAME + b]; + if (got != expect) { + if (ok) { + printf( + " block %u frame %u (abs %u) byte %u is 0x%02x, " + "expected 0x%02x\n", + blk, f, abs, b, got, expect); + } + ok = false; + } + } + } + blk++; + } + + if (ok) { + printf( + " all %u slots agree on every frame of %u blocks " + "(%u pulse frames per block, 6.25-frame period)\n", + N, blk, pulses_per_block / blk); + } + test_result("MUX 20 queues start in phase", ok); +} + +// ============================================================================ +// Main +// ============================================================================ + +void basic_test() { + puts("=== I2S MUX Fill Buffer Tests ===\n"); + fflush(stdout); + + puts("=== Part 1: Single Stepper Frame-Level ==="); + test_mux_single_step(); + test_mux_multi_step(); + test_mux_step_pause_step(); + test_mux_empty_queue(); + test_mux_pause_only(); + + puts("\n=== Part 2: off_ticks Compensation ==="); + test_mux_off_ticks_carry(); + test_mux_off_ticks_across_blocks(); + test_mux_off_ticks_zero(); + test_mux_off_ticks_compensation(); + + puts("\n=== Part 3: Slot Isolation (Representative: 0, 7, 15, 31) ==="); + test_mux_slot_0_isolation(); + test_mux_slot_7_isolation(); + test_mux_slot_15_isolation(); + test_mux_slot_31_isolation(); + test_mux_two_steppers_same_buffer(); + + puts("\n=== Part 4: Block Boundary ==="); + test_mux_block_boundary(); + test_mux_pause_spans_block(); + test_mux_return_value_full(); + test_mux_return_value_partial(); + + puts("\n=== Part 5: Edge Cases ==="); + test_mux_max_steps(); + test_mux_long_pause(); + test_mux_min_speed(); + test_mux_partial_steps(); + + puts("\n=== Part 6: Position-exact, Many Queues, One Buffer ==="); + test_mux_positions_20_slots(); + test_mux_positions_26_slots(); + test_mux_positions_all_slots(); + test_mux_positions_slow_and_fast(); + test_mux_positions_queue_drains_midrun(); + test_mux_queues_start_in_phase(); + + printf("\n=== Test Summary ===\n"); + printf("Total: %d Passed: %d Failed: %d\n", test_passed + test_failed, + test_passed, test_failed); + if (test_failed == 0) { + puts("All tests PASSED"); + } else { + printf("%d test(s) FAILED\n", test_failed); + } +} + +int main() { + basic_test(); + return test_failed ? 1 : 0; +} diff --git a/tests/host/test_23.cpp b/tests/host/test_23.cpp new file mode 100644 index 0000000..541ce19 --- /dev/null +++ b/tests/host/test_23.cpp @@ -0,0 +1,658 @@ +// test_23: Direction pin and external pin handling tests +// +// Part 1: MIN_DIR_DELAY_US / MAX_DIR_DELAY_US tests +// Part 2: dir_change_delay_us tests for regular direction pins +// Part 3: External direction pin behavior tests (FAILS with current impl) +// Part 4: External enable pin behavior tests +// Part 5: Integration tests + +#include +#include +#include +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +#define TASK_CYCLE_TICKS (TICKS_PER_S / 250) +#define EXTERNAL_DIR_PIN 128 +#define EXTERNAL_ENABLE_PIN 129 + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void noInterrupts() {} +void interrupts() {} +void inject_fill_interrupt(int mark) {} + +extern void fas_reset_stepper_allocation(); + +static int test_passed = 0; +static int test_failed = 0; + +static void test_result(const char* name, bool passed) { + if (passed) { + printf("PASS: %s\n", name); + test_passed++; + } else { + printf("FAIL: %s\n", name); + test_failed++; + } +} + +static void process_queue_ticks(uint32_t ticks_to_process) { + StepperQueue* q = &fas_queue[0]; + while (ticks_to_process > 0 && q->read_idx != q->next_write_idx) { + struct queue_entry* e = &q->entry[q->read_idx & QUEUE_LEN_MASK]; + uint32_t entry_ticks = e->ticks; + if (e->steps > 0) { + entry_ticks *= e->steps; + } + if (entry_ticks <= ticks_to_process) { + ticks_to_process -= entry_ticks; + q->read_idx++; + } else { + break; + } + } +} + +// AQE_DIR_CHANGE_PAUSE_INJECTED is a positive/informational result: the +// direction-change pause is in the queue, but the actual command was not +// yet enqueued. At most one pause is injected per call, so the caller must +// invoke addQueueEntry() again (cf. aqeRetry()) until AQE_OK is returned. +static AqeResultCode addQueueEntryWithDirChange(StepperMotion* s, + struct stepper_command_s* cmd, + bool start) { + AqeResultCode res = AQE_OK; + for (int i = 0; i < 10; i++) { + res = s->addQueueEntry(cmd, start); + if (res != AQE_DIR_CHANGE_PAUSE_INJECTED) { + break; + } + } + return res; +} + +static bool external_dir_callback_called = false; +static uint8_t last_callback_pin = 0; +static uint8_t last_callback_value = 0; + +static bool mock_external_callback(uint8_t pin, uint8_t value) { + external_dir_callback_called = true; + last_callback_pin = pin; + last_callback_value = value; + return value; +} + +static bool external_enable_callback_called = false; + +static bool mock_external_enable_callback(uint8_t pin, uint8_t value) { + external_enable_callback_called = true; + return value; +} + +void init_queue() { + fas_reset_stepper_allocation(); + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); +} + +static void test_min_dir_delay_value() { + printf("Running: MIN_DIR_DELAY_US value check\n"); + printf(" MIN_DIR_DELAY_US = %ld us\n", (long)MIN_DIR_DELAY_US); + printf(" MIN_CMD_TICKS = %ld ticks\n", (long)MIN_CMD_TICKS); + printf(" Expected: MIN_DIR_DELAY_US = MIN_CMD_TICKS in us = %ld\n", + (long)(MIN_CMD_TICKS / (TICKS_PER_S / 1000000))); + test_result("MIN_DIR_DELAY_US value check", + MIN_DIR_DELAY_US == MIN_CMD_TICKS / (TICKS_PER_S / 1000000)); +} + +static void test_max_dir_delay_value() { + printf("Running: MAX_DIR_DELAY_US value check\n"); + printf(" MAX_DIR_DELAY_US = %ld us\n", (long)MAX_DIR_DELAY_US); + printf(" Expected: 65535 / (TICKS_PER_S / 1000000) = %ld\n", + (long)(65535 / (TICKS_PER_S / 1000000))); + test_result("MAX_DIR_DELAY_US value check", + MAX_DIR_DELAY_US == 65535 / (TICKS_PER_S / 1000000)); +} + +static void test_dir_delay_below_min_clamped() { + printf("Running: dir_change_delay_us below MIN_DIR_DELAY_US clamped\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 1); + + printf(" Requested: 1 us\n"); + printf(" MIN_DIR_DELAY_US: %ld us\n", (long)MIN_DIR_DELAY_US); + printf(" Expected: clamped to MIN_DIR_DELAY_US\n"); + + test_result("dir_change_delay below min clamped", true); +} + +static void test_dir_delay_above_max_clamped() { + printf("Running: dir_change_delay_us above MAX_DIR_DELAY_US clamped\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 10000); + + printf(" Requested: 10000 us\n"); + printf(" MAX_DIR_DELAY_US: %ld us\n", (long)MAX_DIR_DELAY_US); + printf(" Expected: clamped to MAX_DIR_DELAY_US\n"); + + test_result("dir_change_delay above max clamped", true); +} + +static void test_dir_change_delay_inserted_on_dir_change() { + printf("Running: dir_change_delay_us pause inserted on direction change\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 1000); + s.setSpeedInUs(100); + s.setAcceleration(10000); + + struct stepper_command_s cmd1 = { + .ticks = 1600, .steps = 10, .count_up = true}; + s.addQueueEntry(&cmd1, true); + + uint8_t entries_forward = fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after forward cmd: %d\n", entries_forward); + + struct stepper_command_s cmd2 = { + .ticks = 1600, .steps = 10, .count_up = false}; + AqeResultCode res = addQueueEntryWithDirChange(&s, &cmd2, false); + printf(" Backward cmd result: %s\n", toString(res)); + + uint8_t entries_total = fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after backward cmd: %d\n", entries_total); + + bool pause_inserted = (entries_total > entries_forward + 1); + printf(" Pause entry inserted: %s\n", pause_inserted ? "yes" : "no"); + + test_result("dir_change_delay pause inserted", pause_inserted); +} + +static void test_dir_change_delay_not_on_pause_command() { + printf("Running: dir_change_delay NOT inserted for pause commands\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 1000); + + struct stepper_command_s pause_cmd = { + .ticks = 10000, .steps = 0, .count_up = true}; + AqeResultCode res = s.addQueueEntry(&pause_cmd, true); + + printf(" Pause command result: %s (expected %s)\n", toString(res), + toString(AQE_OK)); + + test_result("dir_change_delay not on pause", res == AQE_OK); +} + +static void test_before_after_dir_change_delay_defined() { + printf("Running: BEFORE/AFTER_DIR_CHANGE_DELAY_TICKS defined check\n"); + init_queue(); + + uint16_t before_delay = 0; + uint16_t after_delay = 0; + +#if defined(BEFORE_DIR_CHANGE_DELAY_TICKS) + before_delay = BEFORE_DIR_CHANGE_DELAY_TICKS(&fas_queue[0]); +#endif +#if defined(AFTER_DIR_CHANGE_DELAY_TICKS) + after_delay = AFTER_DIR_CHANGE_DELAY_TICKS(&fas_queue[0]); +#endif + + printf(" BEFORE_DIR_CHANGE_DELAY_TICKS: %u ticks\n", before_delay); + printf(" AFTER_DIR_CHANGE_DELAY_TICKS: %u ticks\n", after_delay); + + if (before_delay == 0 && after_delay == 0) { + printf(" Neither defined - using default behavior\n"); + } + + test_result("BEFORE/AFTER_DIR_CHANGE_DELAY_TICKS check", true); +} + +static void test_dir_change_before_after_getters() { + printf("Running: getDirChangeBeforeTicks / AfterTicks\n"); + init_queue(); + StepperMotionEngine engine; + engine.init(); + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + test_result( + "before/after 0 without dir pin", + s->getDirChangeBeforeTicks() == 0 && s->getDirChangeAfterTicks() == 0); + + s->setDirectionPin(5, true, 0); + fas_queue[0]._before_dir_change_delay_ticks = 0; + fas_queue[0]._after_dir_change_delay_ticks = 0; + test_result( + "before/after 0 with dir pin delay 0", + s->getDirChangeBeforeTicks() == 0 && s->getDirChangeAfterTicks() == 0); + + uint16_t before = US_TO_TICKS(500); + fas_queue[0]._before_dir_change_delay_ticks = before; + test_result( + "before ticks from driver", + s->getDirChangeBeforeTicks() == fas_max(before, (uint16_t)MIN_CMD_TICKS)); + + s->setDirectionPin(5, true, 1000); + uint16_t user_after = US_TO_TICKS(1000); + test_result("after ticks from user delay", + s->getDirChangeAfterTicks() == + fas_max(user_after, (uint16_t)MIN_CMD_TICKS)); + + uint16_t driver_after = US_TO_TICKS(2000); + fas_queue[0]._after_dir_change_delay_ticks = driver_after; + test_result("after ticks max(user, driver)", + s->getDirChangeAfterTicks() == + fas_max(driver_after, (uint16_t)MIN_CMD_TICKS)); + + engine.setExternalCallForPin(mock_external_callback); + s->setDirectionPin(EXTERNAL_DIR_PIN, true, 1000); + test_result("external dir after is 2ms", + s->getDirChangeAfterTicks() == US_TO_TICKS((uint16_t)2000)); +} + +static void test_no_delay_if_prior_pause_sufficient() { + printf("Running: No delay if prior pause has sufficient ticks\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 0); + s.setSpeedInUs(100); + s.setAcceleration(10000); + + uint16_t before_delay_ticks = US_TO_TICKS(1000); + fas_queue[0]._before_dir_change_delay_ticks = before_delay_ticks; + printf(" before_delay: %u ticks\n", before_delay_ticks); + + struct stepper_command_s pause_cmd = { + .ticks = (uint16_t)(before_delay_ticks + 1000), + .steps = 0, + .count_up = true}; + AqeResultCode res = s.addQueueEntry(&pause_cmd, true); + printf(" Pause command result: %s\n", toString(res)); + + uint8_t entries_after_pause = + fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after pause: %d\n", entries_after_pause); + + struct stepper_command_s cmd2 = { + .ticks = 1600, .steps = 10, .count_up = false}; + res = s.addQueueEntry(&cmd2, false); + + uint8_t entries_total = fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after backward cmd: %d\n", entries_total); + + bool no_extra_pause = (entries_total == entries_after_pause + 1); + printf(" Extra pause inserted: %s (expected: no)\n", + no_extra_pause ? "no" : "yes"); + + test_result("No delay if prior pause sufficient", no_extra_pause); +} + +static void test_delay_if_prior_step_sufficient() { + printf("Running: Delay IS inserted if prior step has sufficient ticks\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 0); + s.setSpeedInUs(100); + s.setAcceleration(10000); + + uint16_t before_delay_ticks = US_TO_TICKS(1000); + fas_queue[0]._before_dir_change_delay_ticks = before_delay_ticks; + printf(" before_delay: %u ticks\n", before_delay_ticks); + + struct stepper_command_s step_cmd = { + .ticks = (uint16_t)(before_delay_ticks + 1000), + .steps = 1, + .count_up = true}; + AqeResultCode res = s.addQueueEntry(&step_cmd, true); + printf(" Step command result: %s\n", toString(res)); + + uint8_t entries_after_step = + fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after step: %d\n", entries_after_step); + + struct stepper_command_s cmd2 = { + .ticks = 1600, .steps = 10, .count_up = false}; + res = addQueueEntryWithDirChange(&s, &cmd2, false); + + uint8_t entries_total = fas_queue[0].next_write_idx - fas_queue[0].read_idx; + printf(" Entries after backward cmd: %d\n", entries_total); + + // Even though the prior step's period is long enough, it still had steps + // of the old direction in flight. The before-pause must be inserted so + // those steps finish before the direction change. + bool extra_pause = (entries_total == entries_after_step + 2); + printf(" Extra pause inserted: %s (expected: yes)\n", + extra_pause ? "yes" : "no"); + + test_result("Delay if prior step sufficient", extra_pause); +} + +static void test_external_dir_pin_with_empty_queue() { + printf("Running: External dir pin with empty queue\n"); + init_queue(); + external_dir_callback_called = false; + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setDirectionPin(EXTERNAL_DIR_PIN, true, 0); + s->setSpeedInUs(100); + s->setAcceleration(10000); + + struct stepper_command_s cmd = { + .ticks = 16000, .steps = 10, .count_up = true}; + AqeResultCode res = s->addQueueEntry(&cmd, true); + + printf(" Result: %s (expected %s)\n", toString(res), toString(AQE_OK)); + printf(" Queue entries: %d\n", + fas_queue[0].next_write_idx - fas_queue[0].read_idx); + + test_result("External dir pin empty queue", res == AQE_OK); +} + +static void test_external_dir_pin_with_steps_in_queue() { + printf("Running: External dir pin with steps in queue (EXPECT FAIL)\n"); + init_queue(); + external_dir_callback_called = false; + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setDirectionPin(EXTERNAL_DIR_PIN, true, 0); + s->setSpeedInUs(100); + s->setAcceleration(10000); + + for (int i = 0; i < 10; i++) { + struct stepper_command_s cmd = { + .ticks = 1600, .steps = 25, .count_up = true}; + s->addQueueEntry(&cmd, false); + } + + uint32_t ticks_in_queue = fas_queue[0].ticksInQueue(); + printf(" Ticks in queue before dir change: %u (~%.2fms)\n", ticks_in_queue, + ticks_in_queue * 1000.0 / TICKS_PER_S); + + struct stepper_command_s cmd = { + .ticks = 16000, .steps = 10, .count_up = false}; + AqeResultCode res = s->addQueueEntry(&cmd, true); + + printf(" Result: %s (expected %s = AQE_DIR_PIN_2MS_PAUSE_ADDED)\n", + toString(res), toString(AQE_DIR_PIN_2MS_PAUSE_ADDED)); + + if (res != AQE_DIR_PIN_2MS_PAUSE_ADDED) { + printf(" BUG DETECTED: Current impl returns %s, should return %s\n", + toString(res), toString(AQE_DIR_PIN_2MS_PAUSE_ADDED)); + printf(" Two 500us pauses = 1ms is insufficient for %.2fms queue\n", + ticks_in_queue * 1000.0 / TICKS_PER_S); + } + + test_result("External dir pin with steps in queue", + res == AQE_DIR_PIN_2MS_PAUSE_ADDED); +} + +static void test_external_dir_pin_queue_drain_and_retry() { + printf("Running: External dir pin queue drain and retry\n"); + init_queue(); + external_dir_callback_called = false; + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setDirectionPin(EXTERNAL_DIR_PIN, true, 0); + s->setSpeedInUs(100); + s->setAcceleration(10000); + + for (int i = 0; i < 5; i++) { + struct stepper_command_s fwd_cmd = { + .ticks = 1600, .steps = 20, .count_up = true}; + s->addQueueEntry(&fwd_cmd, false); + } + + uint32_t ticks_remaining = fas_queue[0].ticksInQueue(); + printf(" Initial ticks in queue: %u\n", ticks_remaining); + + int retry_count = 0; + AqeResultCode res; + + struct stepper_command_s cmd = { + .ticks = 16000, .steps = 10, .count_up = false}; + + while (retry_count < 20) { + res = s->addQueueEntry(&cmd, true); + + if (res == AQE_DIR_PIN_2MS_PAUSE_ADDED) { + printf(" Retry %d: PAUSE_ADDED (queue draining)\n", retry_count); + + process_queue_ticks(TASK_CYCLE_TICKS); + + retry_count++; + ticks_remaining = fas_queue[0].ticksInQueue(); + printf(" Ticks remaining after drain: %u\n", ticks_remaining); + + if (ticks_remaining == 0) { + break; + } + } else { + break; + } + } + + printf(" Final result after %d retries: %s\n", retry_count, toString(res)); + + test_result("External dir pin queue drain retry", + retry_count > 0 && res == AQE_OK); +} + +static void test_external_enable_pin_callback() { + printf("Running: External enable pin callback\n"); + init_queue(); + external_enable_callback_called = false; + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_enable_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setEnablePin(EXTERNAL_ENABLE_PIN, true); + + bool enabled = s->enableOutputs(); + + printf(" Callback called: %s\n", + external_enable_callback_called ? "yes" : "no"); + printf(" enableOutputs returned: %s\n", enabled ? "true" : "false"); + + test_result("External enable pin callback", external_enable_callback_called); +} + +static void test_external_enable_pin_disable() { + printf("Running: External enable pin disable\n"); + init_queue(); + external_enable_callback_called = false; + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_enable_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setEnablePin(EXTERNAL_ENABLE_PIN, true); + s->enableOutputs(); + + external_enable_callback_called = false; + bool disabled = s->disableOutputs(); + + printf(" Callback called: %s\n", + external_enable_callback_called ? "yes" : "no"); + printf(" disableOutputs returned: %s\n", disabled ? "true" : "false"); + + test_result("External enable pin disable", external_enable_callback_called); +} + +static void test_queue_ticks_tracking() { + printf("Running: Queue ticks tracking\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setSpeedInUs(100); + s.setAcceleration(10000); + + struct stepper_command_s cmd = {.ticks = 1600, .steps = 10, .count_up = true}; + s.addQueueEntry(&cmd, true); + + uint32_t ticks = fas_queue[0].ticksInQueue(); + printf(" Ticks for 10 steps: %u\n", ticks); + + process_queue_ticks(ticks); + ticks = fas_queue[0].ticksInQueue(); + printf(" Ticks after processing all: %u (expected 0)\n", ticks); + + test_result("Queue ticks tracking", ticks == 0); +} + +static void test_has_steps_detection() { + printf("Running: hasStepsInQueue detection\n"); + init_queue(); + + StepperMotion s; + s.init(NULL, 0, 0); + s.setDirectionPin(5, true, 0); + s.setSpeedInUs(100); + s.setAcceleration(10000); + + struct stepper_command_s cmd = {.ticks = 1600, .steps = 50, .count_up = true}; + s.addQueueEntry(&cmd, true); + + bool has_steps = false; + StepperQueue* q = &fas_queue[0]; + uint8_t rp = q->read_idx; + while (rp != q->next_write_idx) { + if (q->entry[rp & QUEUE_LEN_MASK].steps > 0) { + has_steps = true; + break; + } + rp++; + } + + printf(" Steps in queue: %s\n", has_steps ? "yes" : "no"); + test_result("hasStepsInQueue detection", has_steps); +} + +static void test_realistic_direction_change_scenario() { + printf("Running: Realistic direction change scenario\n"); + init_queue(); + + StepperMotionEngine engine; + engine.init(); + engine.setExternalCallForPin(mock_external_callback); + + StepperMotion* s = engine.stepperConnectToPin(0); + assert(s != NULL); + s->setDirectionPin(EXTERNAL_DIR_PIN, true, 0); + s->setSpeedInUs(50); + s->setAcceleration(50000); + + for (int i = 0; i < 8; i++) { + struct stepper_command_s cmd = { + .ticks = 800, .steps = 30, .count_up = true}; + s->addQueueEntry(&cmd, false); + } + + for (int i = 0; i < 3; i++) { + process_queue_ticks(TASK_CYCLE_TICKS); + } + + uint32_t ticks_before = fas_queue[0].ticksInQueue(); + printf(" Ticks in queue before reversal: %u (~%.2fms)\n", ticks_before, + ticks_before * 1000.0 / TICKS_PER_S); + + struct stepper_command_s rev_cmd = { + .ticks = 16000, .steps = 10, .count_up = false}; + AqeResultCode res = s->addQueueEntry(&rev_cmd, true); + + printf(" addQueueEntry result: %s\n", toString(res)); + + bool correct = (ticks_before > TASK_CYCLE_TICKS) + ? (res == AQE_DIR_PIN_2MS_PAUSE_ADDED) + : true; + test_result("Realistic direction change scenario", correct); +} + +int main() { + puts("=== Direction Pin and External Pin Tests ===\n"); + fflush(stdout); + + puts("=== Part 1: MIN/MAX_DIR_DELAY_US ==="); + test_min_dir_delay_value(); + test_max_dir_delay_value(); + test_dir_delay_below_min_clamped(); + test_dir_delay_above_max_clamped(); + + puts("\n=== Part 2: dir_change_delay_us ==="); + test_dir_change_delay_inserted_on_dir_change(); + test_dir_change_delay_not_on_pause_command(); + test_before_after_dir_change_delay_defined(); + test_dir_change_before_after_getters(); + test_no_delay_if_prior_pause_sufficient(); + test_delay_if_prior_step_sufficient(); + + puts("\n=== Part 3: External Direction Pin (MAY FAIL) ==="); + test_external_dir_pin_with_empty_queue(); + test_external_dir_pin_with_steps_in_queue(); + test_external_dir_pin_queue_drain_and_retry(); + + puts("\n=== Part 4: External Enable Pin ==="); + test_external_enable_pin_callback(); + test_external_enable_pin_disable(); + + puts("\n=== Part 5: Integration ==="); + test_queue_ticks_tracking(); + test_has_steps_detection(); + test_realistic_direction_change_scenario(); + + printf("\n=== Test Summary ===\n"); + printf("Total: %d Passed: %d Failed: %d\n", test_passed + test_failed, + test_passed, test_failed); + + if (test_failed == 0) { + puts("All tests PASSED"); + return 0; + } else { + printf("%d test(s) FAILED\n", test_failed); + puts( + "Note: Some failures are expected before the external dir pin fix is " + "implemented"); + return 1; + } +} diff --git a/tests/host/test_24.cpp b/tests/host/test_24.cpp new file mode 100644 index 0000000..5fe47a3 --- /dev/null +++ b/tests/host/test_24.cpp @@ -0,0 +1,673 @@ +#include +#include +#include +#include +#include + +// Issue 370: a moveTimed() driven direction-change profile produces a +// library-position drift of -2 while the commanded step sum is 0. The -2 +// appears only from the second cycle on (-2 * (cycles - 1)). +// +// Phase 1 replays the Issue370 runCycles() feed on a real 16-entry queue: +// prefill until queue-full, start, then feed with drift compensation. When a +// command cannot be enqueued (BUSY), the RMT ISR is simulated by draining a +// chunk with the real rmt_fill_buffer(). Checks: +// - every cycle nets to the commanded sum (= 0) +// - all cycles produce identical command streams (steps + count_up) +// - the queued position (queue_end.pos) returns to zero +// +// Phase 2 feeds the SAME captured command stream through the real ESP32 RMT +// translation and validates that the encoded symbols reproduce the exact +// step count and total ticks, that the direction-change pause insertion is +// consistent, and that the queue_end position still nets to zero. +// +// If both phases pass, command generation and RMT translation are faithful: +// the -2 per cycle must live in the wire-level DIR-toggle alignment (RMT +// one-symbol prefetch racing the external driver), not in the library. + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +static struct captured { + uint16_t ticks; + uint8_t steps; + bool count_up; +} log_cmd[2048]; +static int log_idx; + +#include "fas_arch/common.h" + +// Phase 2: feed the captured command stream through the real ESP32 RMT fill +// buffer translation (the code that produces the RMT symbols on hardware). +uint16_t debug_part_size = 24; +#define SUPPORT_ESP32_RMT_V1 +#define IRAM_ATTR +#define RMT_CHANNEL_T int +#define LL_TOGGLE_PIN(dirPin) +#include "pd_esp32/StepperISR_rmt_v1.cpp" + +// The V1 fill path stops the channel when the queue runs dry mid-part. +// The real definition is per chip in StepperISR_rmt_v1_esp32*.cpp; these +// tests compile the fill path only, so they bring their own. +void StepperQueue::stop_rmt(bool both) { (void)both; } + + +#include "StepperMotion.h" + +// Direction-change pause insertion is provided by the pd_test default in +// pd_test/dir_change_pause.h; this standalone test does not link the library .o +// files, so it includes that default itself. It must be included after +// StepperQueue and its BEFORE/AFTER macros are known. The pd_test target +// #defines inline away, so this must be included in exactly one TU per binary. +#include "pd_test/dir_change_pause.h" + +// Production bodies of addQueueEntry() and moveTimed(), compiled against this +// test's StepperQueue/StepperMotion instead of the hardware queues. +#include "fas_member/add_queue_entry.h" +#include "fas_member/move_timed.h" + +static StepperQueue feed_q; +static StepperQueue rmt_q; + +#define MAX_RMT_ENTRIES 32768 +static uint32_t rmt_entries[MAX_RMT_ENTRIES]; +static uint32_t drain_syms[64]; + +static int failures = 0; +static void check(int cond, const char* msg) { + if (!cond) { + printf("FAIL: %s\n", msg); + failures++; + } +} + +// The test is not linked against StepperMotion.o, so provide the +// StepperMotion members that addQueueEntry()/moveTimed() reference. Their +// production bodies come from fas_member/add_queue_entry.h and +// fas_member/move_timed.h above. +StepperQueue* StepperMotion::_queue() const { + return (_queue_num == 0) ? &feed_q : &rmt_q; +} +bool StepperMotion::enableOutputs() { return true; } +bool StepperMotion::isQueueRunning() const { return _queue()->isRunning(); } +bool StepperMotion::handleExternalDirectionPin(StepperQueue* q, + bool count_up) { + (void)q; + (void)count_up; + return true; +} +uint8_t StepperMotion::queueEntries() const { + return _queue()->queueEntries(); +} +bool StepperMotion::isQueueEmpty() const { return _queue()->isQueueEmpty(); } + +// Test-only init: TEST makes init() public. Configure the stepper for the test +// (no engine auto-enable, dir pin active). +void StepperMotion::init(StepperMotionEngine* engine, uint8_t num, + uint8_t step_pin) { + (void)step_pin; + _engine = engine; + _queue_num = num; + _dirPin = 1; + _dirHighCountsUp = true; + _autoEnable = false; + _on_delay_ticks = 0; + _dir_change_delay_ticks = 0; + _auto_disable_delay_counter = 0; + _off_delay_count = 1; +} + +// Test has no real engine, so the dir-pin is never busy. +bool StepperMotionEngine::isDirPinBusy(uint8_t dirPin, + uint8_t except_stepper) { + (void)dirPin; + (void)except_stepper; + return false; +} + +// StepperQueue::addQueueEntry() (queue_add_entry.cpp) for the standalone +// test: maintains queue_end position, toggle flags and the write index. +// startQueue() is emulated by setting _isRunning. Writes to feed_q are +// additionally captured into log_cmd[]. +AqeResultCode StepperQueue::addQueueEntry(const struct stepper_command_s* cmd, + bool start) { + if (cmd == NULL) { + if (start && !isRunning()) { + if (next_write_idx == read_idx) { + return AQE_ERROR_EMPTY_QUEUE_TO_START; + } + _isRunning = true; + } + return AQE_OK; + } + if (isQueueFull()) { + return AQE_QUEUE_FULL; + } + uint16_t period = cmd->ticks; + uint8_t steps = cmd->steps; + uint32_t command_rate_ticks = period; + if (steps > 1) { + command_rate_ticks *= steps; + } + if (command_rate_ticks < MIN_CMD_TICKS) { + return AQE_ERROR_TICKS_TOO_LOW; + } + uint8_t wp = next_write_idx; + struct queue_entry* e = &entry[wp & QUEUE_LEN_MASK]; + bool dir = (cmd->count_up == dirHighCountsUp); + bool toggle_dir = false; + bool dir_changed = false; + if (dirPin != PIN_UNDEFINED) { + dir_changed = (dir != queue_end.dir); + if ((isQueueEmpty() && !isRunning()) && + ((dirPin & PIN_EXTERNAL_FLAG) == 0)) { + queue_end.dir = dir; + } else { + toggle_dir = dir_changed; + } + } + e->steps = steps; + e->dirPinState = dir; + e->toggle_dir = toggle_dir; + e->countUp = cmd->count_up ? 1 : 0; + e->hasSteps = steps > 0 ? 1 : 0; + e->ticks = period; + struct queue_end_s next_queue_end = queue_end; +#if defined(SUPPORT_QUEUE_ENTRY_END_POS_U16) + e->end_pos_last16 = (uint32_t)next_queue_end.pos & 0xffff; +#endif + next_queue_end.pos = next_queue_end.pos + (cmd->count_up ? steps : -steps); + next_queue_end.dir = dir; + next_queue_end.count_up = cmd->count_up; + next_write_idx = wp + 1; + queue_end = next_queue_end; + + if (this == &feed_q && + (uint32_t)log_idx < sizeof(log_cmd) / sizeof(log_cmd[0])) { + log_cmd[log_idx].ticks = period; + log_cmd[log_idx].steps = steps; + log_cmd[log_idx].count_up = cmd->count_up; + log_idx++; + } + + if (!isRunning() && start) { + _isRunning = true; + } + if ((steps > 0) || dir_changed) { + clear_pause_stats(); + } else { + if (_nr_of_pauses < 255) { + _nr_of_pauses++; + } + if (65535 - _last_pause_ticks >= period) { + _last_pause_ticks += period; + } else { + _last_pause_ticks = 65535; + } + } + return AQE_OK; +} + +// Test stepper: points addQueueEntry()/moveTimed() at feed_q (num 0) or +// rmt_q (num 1) and disables the auto-enable / external-dir-pin paths. +static StepperMotion test_stepper; +static void setup_step(uint8_t num) { test_stepper.init(NULL, num, 0); } + +static void reset() { + log_idx = 0; + __builtin_memset(&feed_q, 0, sizeof(feed_q)); + feed_q._base_initVars(); + feed_q._pd_initVars(); + feed_q.setDirPin(1, true); + setup_step(0); +} + +// ---- Phase 2: RMT translation of the captured command stream -------------- + +struct RmtResult { + uint32_t step_count; + uint64_t total_ticks; +}; + +static uint32_t rmt_pause_symbol() { + return 0x00010001 * ((MIN_CMD_TICKS + 2 * PART_SIZE - 1) / (2 * PART_SIZE)); +} + +static RmtResult analyze_rmt(uint32_t count) { + RmtResult result = {0, 0}; + bool step_high = false; + for (uint32_t i = 0; i < count; i++) { + uint16_t low = rmt_entries[i] & 0xffff; + uint16_t high = rmt_entries[i] >> 16; + uint16_t low_ticks = low & 0x7fff; + uint16_t high_ticks = high & 0x7fff; + if ((low & 0x8000) && !step_high) { + result.step_count++; + step_high = true; + } else if (!(low & 0x8000) && step_high) { + step_high = false; + } + result.total_ticks += low_ticks; + if ((high & 0x8000) && !step_high) { + result.step_count++; + step_high = true; + } else if (!(high & 0x8000) && step_high) { + step_high = false; + } + result.total_ticks += high_ticks; + } + return result; +} + +static void feed_rmt() { + __builtin_memset(&rmt_q, 0, sizeof(rmt_q)); + rmt_q._base_initVars(); + rmt_q._pd_initVars(); + rmt_q.setDirPin(1, true); + + uint32_t rmt_offset = 0; + uint32_t fed = 0; + uint32_t toggle_entries = 0; + uint64_t base_ticks = 0; + + while (fed < (uint32_t)log_idx || rmt_q.read_idx != rmt_q.next_write_idx) { + while (fed < (uint32_t)log_idx) { + uint8_t queued = rmt_q.next_write_idx - rmt_q.read_idx; + if (queued >= QUEUE_LEN) { + break; + } + struct stepper_command_s cmd = {.ticks = log_cmd[fed].ticks, + .steps = log_cmd[fed].steps, + .count_up = log_cmd[fed].count_up}; + AqeResultCode rc = rmt_q.addQueueEntry(&cmd, false); + check(rc == AQE_OK, "phase2: addQueueEntry rejected a generated command"); + if (rc != AQE_OK) { + return; + } + const struct queue_entry* e = + &rmt_q.entry[(uint8_t)(rmt_q.next_write_idx - 1) & QUEUE_LEN_MASK]; + if (e->toggle_dir) { + toggle_entries++; + } + if (e->steps > 0) { + base_ticks += (uint64_t)e->steps * e->ticks; + } else { + base_ticks += e->ticks; + } + fed++; + } + if (rmt_q.read_idx == rmt_q.next_write_idx) { + break; + } + if (rmt_offset + PART_SIZE > MAX_RMT_ENTRIES) { + check(false, "phase2: RMT entry buffer overflow"); + break; + } + rmt_fill_buffer(&rmt_q, true, &rmt_entries[rmt_offset]); + rmt_offset += PART_SIZE; + } + + // Direction-change pauses are now inserted by addQueueEntry() + // (BEFORE_DIR_CHANGE_DELAY_TICKS), NOT by the RMT fill buffer. So the RMT + // translation must not add any pause symbols of its own: every toggle_dir + // entry is emitted as-is and the total ticks must equal the base command + // ticks (no injected pause ticks). + uint32_t pause_sym = rmt_pause_symbol(); + uint32_t pauses = 0; + for (uint32_t i = 0; i + PART_SIZE <= rmt_offset; i++) { + if (rmt_entries[i] == pause_sym) { + pauses++; + i += PART_SIZE - 1; + } + } + + RmtResult rmt = analyze_rmt(rmt_offset); + uint32_t steps_expected = 0; + for (int i = 0; i < log_idx; i++) { + steps_expected += log_cmd[i].steps; + } + + printf("phase2 feed = %u cmds -> %u rmt entries\n", fed, rmt_offset); + printf("toggle cmds = %u (pause symbols injected: %u)\n", toggle_entries, + pauses); + printf("base ticks = %" PRIu64 "\n", (int64_t)base_ticks); + printf("RMT steps = %u (expected %u)\n", rmt.step_count, steps_expected); + printf("RMT ticks = %" PRIu64 " (expected %" PRIu64 ")\n", + (int64_t)rmt.total_ticks, (int64_t)base_ticks); + printf("queue_end.pos= %" PRId32 "\n", (int32_t)rmt_q.queue_end.pos); + + check(fed == (uint32_t)log_idx, "phase2: not all commands were fed"); + check(pauses == 0, "phase2: RMT fill buffer must not inject pause symbols"); + check(rmt.step_count == steps_expected, + "phase2: step pulses were lost or added by rmt_fill_buffer"); + check(rmt.total_ticks == base_ticks, + "phase2: total ticks changed by rmt_fill_buffer"); + check(rmt_q.queue_end.pos == 0, + "phase2: queue_end position drifted from commanded sum"); +} + +struct Cmd { + int16_t steps; + uint32_t ticks; +}; + +// The 87-command profile from Issue370 (net = 0 per cycle) +static const Cmd pattern[] = { + {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, + {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, + {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, + {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, {+26, 105960}, + {-2, 105960}, {-7, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, + {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, + {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, + {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, {-26, 105960}, + {-17, 105960}, {-10, 105960}, {-7, 105960}, {-5, 105960}, {-2, 105960}, + {-1, 105960}, {-1, 105960}, {+1, 105960}, {+2, 105960}, {+5, 105960}, + {+10, 105960}, {+17, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, {-1, 105960}, + {-1, 105960}, {-1, 105960}, +}; + +// Feed one pattern command like Issue370::feedCommand(): retry on queue-full, +// with the real RMT ISR drain (one chunk per retry). track drift. +static bool feedCommand(int16_t steps, uint32_t ticks, int32_t& drift, + int64_t& commanded_sum) { + uint32_t duration = (uint32_t)((int64_t)ticks + drift); + uint32_t actual = 0; + for (;;) { + MoveTimedResultCode rc = + test_stepper.moveTimed(steps, duration, &actual, false); + switch (rc) { + case MOVE_TIMED_OK: + case MOVE_TIMED_EMPTY: + drift = (int32_t)(duration - actual); + commanded_sum += steps; + return true; + case MOVE_TIMED_BUSY: + case MoveTimedResultCode::QueueFull: + case MoveTimedResultCode::DirPinIsBusy: + case MoveTimedResultCode::WaitForEnablePinActive: + // Simulate the RMT ISR consuming one chunk from the queue + rmt_fill_buffer(&feed_q, true, drain_syms); + break; + case MoveTimedResultCode::DeviceNotReady: + break; + default: + printf("feedCommand error: rc=%d steps=%d dur=%lu\n", (int)rc, + (int)steps, (unsigned long)duration); + return false; + } + } +} + +// Feed one captured command into rmt_q via the StepperMotion wrapper, the +// same way the issue370 firmware does. A direction change may return +// AQE_DIR_CHANGE_PAUSE_INJECTED (pause queued, command not yet): retry until +// the command itself is enqueued. +static AqeResultCode feedViaStepper(struct stepper_command_s* cmd) { + for (int i = 0; i < 10; i++) { + AqeResultCode rc = test_stepper.addQueueEntry(cmd, false); + if (rc != AQE_DIR_CHANGE_PAUSE_INJECTED) { + return rc; + } + } + return AQE_DIR_CHANGE_PAUSE_INJECTED; +} + +// Minimal reproduction of the Issue370_minimal dangerous reversal on the PC +// wire-level pipeline. Per cycle: +2 fast UP at full rate, then a reversal to +// -2 DOWN. Despite +2 ... -2 netting to zero in the library bookkeeping, the +// RMT DIR toggle (software LL_TOGGLE_PIN at buffer-fill time) fires before the +// two fast UP steps are emitted, so those steps go out in the wrong direction. +// +// We dump the exact queue entries as they pass through the real +// rmt_fill_buffer(), so the toggle position relative to the preceding steps is +// visible. +// +// Note on the ticks printed below: for a k-step command moveTimed() is given +// the TOTAL duration (here 105960 for 2 steps), and each queue_entry.ticks is +// the period BETWEEN steps, i.e. duration / steps = 52980. There is no timing +// drift; RMT ticks sum to 2 * 105960 for the 4 steps of +2 ... -2. +static void minimal_repro() { + reset(); + check(feed_q.queueEntries() == 0, "min: queue must start empty"); + + // Issue370_minimal buildPattern() with FAST_STEPS=2, FAST_CMDS=1: + // A: +2 fast UP (dangerous run-up) + // B: -2 (dangerous reversal UP -> DOWN) + // net = 0 per cycle + static const Cmd min_cmd[] = {{+2, 105960}, {-2, 105960}}; + const int n_min = (int)(sizeof(min_cmd) / sizeof(min_cmd[0])); + const int cycles = 1; + + int64_t cmd_sum = 0; + int32_t drift = 0; + bool started = false; + int prefilled = 0; + + for (int c = 0; c < cycles; c++) { + for (int i = 0; i < n_min; i++) { + if (!started) { + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed( + min_cmd[i].steps, min_cmd[i].ticks, &actual, false); + if (rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY) { + drift = (int32_t)(min_cmd[i].ticks - actual); + cmd_sum += min_cmd[i].steps; + prefilled++; + continue; + } + if (rc != MOVE_TIMED_BUSY) { + printf("min: prefill error rc=%d at %d\n", (int)rc, i); + return; + } + test_stepper.moveTimed(0, 0, NULL, true); + started = true; + } + if (!feedCommand(min_cmd[i].steps, min_cmd[i].ticks, drift, cmd_sum)) { + return; + } + } + } + if (!started) { + test_stepper.moveTimed(0, 0, NULL, true); + started = true; + } + + // Feed the SAME captured command stream through the real RMT fill buffer and + // dump the queue entries in pipeline order, marking toggle_dir. + // A BEFORE-direction-change pause is configured: the +2 run just before the + // reversal still has steps in flight, so production must KEEP the pause even + // though the prior period (52980 ticks) exceeds it. + __builtin_memset(&rmt_q, 0, sizeof(rmt_q)); + rmt_q._base_initVars(); + rmt_q._pd_initVars(); + rmt_q.setDirPin(1, true); + rmt_q._before_dir_change_delay_ticks = MIN_CMD_TICKS; + setup_step(1); + + printf( + "\n=== Issue370_minimal pipeline dump (FAST_STEPS=2, FAST_CMDS=1) ===\n"); + printf( + "idx entry: steps ticks count_up toggle_dir (in-pipeline " + "order)\n"); + uint32_t fed = 0; + uint32_t rmt_offset = 0; + uint32_t part = 0; + while (fed < (uint32_t)log_idx || rmt_q.read_idx != rmt_q.next_write_idx) { + while (fed < (uint32_t)log_idx) { + uint8_t queued = rmt_q.next_write_idx - rmt_q.read_idx; + if (queued >= QUEUE_LEN) { + break; + } + struct stepper_command_s cmd = {.ticks = log_cmd[fed].ticks, + .steps = log_cmd[fed].steps, + .count_up = log_cmd[fed].count_up}; + AqeResultCode rc = feedViaStepper(&cmd); + if (rc == AQE_QUEUE_FULL) { + break; // drain below, then retry this command + } + if (rc != AQE_OK) { + printf("min: feed-phase addQueueEntry rejected: %d\n", (int)rc); + check(false, "min: feed-phase addQueueEntry failed"); + return; + } + const struct queue_entry* e = + &rmt_q.entry[(uint8_t)(rmt_q.next_write_idx - 1) & QUEUE_LEN_MASK]; + printf("%3u queue: %4u %-10u %-7s %s\n", fed, e->steps, e->ticks, + e->countUp ? "UP" : "DOWN", e->toggle_dir ? "TOGGLE" : ""); + fed++; + } + if (rmt_q.read_idx == rmt_q.next_write_idx) { + break; + } + if (rmt_offset + PART_SIZE > MAX_RMT_ENTRIES) { + printf("min: RMT entry buffer overflow\n"); + return; + } + uint8_t rp_before = rmt_q.read_idx; + const struct queue_entry* ec = &rmt_q.entry[rp_before & QUEUE_LEN_MASK]; + bool this_is_toggle = ec->toggle_dir != 0; + if (this_is_toggle) { + printf( + "%3u fill : part %u consuming entry rp=%u (%s) " + "DIR toggled NOW\n", + part, part % 2, rp_before, "TOGGLE"); + } else { + printf("%3u fill : part %u consuming entry rp=%u (%s %s)\n", part, + part % 2, rp_before, ec->steps > 0 ? "steps" : "pause", + ec->countUp ? "UP" : "DOWN"); + } + rmt_fill_buffer(&rmt_q, (part % 2) == 0, &rmt_entries[rmt_offset]); + rmt_offset += PART_SIZE; + part++; + } + + RmtResult rmt = analyze_rmt(rmt_offset); + printf("captured cmds = %u, rmt offset = %u\n", fed, rmt_offset); + printf("RMT steps = %u\n", rmt.step_count); + printf("queue_end.pos = %" PRId32 "\n", (int32_t)rmt_q.queue_end.pos); + printf("RMT ticks = %" PRIu64 " (incl. injected before-pause)\n", + (int64_t)rmt.total_ticks); + + // Wire-level reading: the production fix keeps a BEFORE-direction-change + // pause before the TOGGLE entry. That pause is transmitted before the toggle + // reaches the fill position, letting the in-flight UP steps finish in the UP + // direction before DIR changes -- so no steps leak into the DOWN direction. + printf("=== end dump ===\n"); + + // The two fast UP steps are now separated from the direction toggle by the + // injected before-pause, mirroring the Issue370_minimal drift fix. + check(cmd_sum == 0, "min: commanded pattern must net to zero"); + check(rmt_q.queue_end.pos == 0, + "min: library queue_end position must return to zero"); +} + +int main() { + minimal_repro(); + // keep print buffer flush ordering deterministic + printf("\n"); + const int cycles = 3; + int64_t commanded_sum = 0; + int pattern_len = (int)(sizeof(pattern) / sizeof(pattern[0])); + int cycle_start[4]; + + reset(); + check(feed_q.queueEntries() == 0, "queue must start empty"); + + // Replay Issue370::runCycles(): prefill without starting until the 16-entry + // queue is full, then start and keep feeding with drift compensation. + int32_t drift = 0; + bool started = false; + int prefilled = 0; + for (int c = 0; c < cycles; c++) { + cycle_start[c] = log_idx; + for (int i = 0; i < pattern_len; i++) { + if (!started) { + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed( + pattern[i].steps, pattern[i].ticks, &actual, false); + if (rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY) { + drift = (int32_t)(pattern[i].ticks - actual); + commanded_sum += pattern[i].steps; + prefilled++; + continue; + } + if (rc != MOVE_TIMED_BUSY) { + printf("prefill error: rc=%d at cmd %d\n", (int)rc, i); + return 1; + } + test_stepper.moveTimed(0, 0, NULL, true); // start the queue + started = true; + } + if (!feedCommand(pattern[i].steps, pattern[i].ticks, drift, + commanded_sum)) { + return 1; + } + } + } + cycle_start[cycles] = log_idx; + + // Wait for physical completion: drain the queue via the real ISR fill code + while (feed_q.read_idx != feed_q.next_write_idx) { + rmt_fill_buffer(&feed_q, true, drain_syms); + } + + int64_t generated_sum = 0; + for (int i = 0; i < log_idx; i++) { + generated_sum += + log_cmd[i].count_up ? log_cmd[i].steps : -(int)log_cmd[i].steps; + } + + printf("pattern_len = %d (x%d cycles)\n", pattern_len, cycles); + printf("prefilled = %d cmds, then queue started\n", prefilled); + printf("queue cmds = %d\n", log_idx); + printf("commanded = %" PRId64 "\n", (int64_t)commanded_sum); + printf("generated = %" PRId64 "\n", (int64_t)generated_sum); + printf("queue_end.pos= %" PRId32 "\n", (int32_t)feed_q.queue_end.pos); + + check(commanded_sum == 0, "pattern itself must net to zero"); + check(generated_sum == commanded_sum, + "moveTimed must preserve the commanded step sum"); + check(feed_q.queue_end.pos == 0, + "queue_end position must return to zero after a full run"); + + for (int c = 0; c < cycles; c++) { + int64_t sum = 0; + int n = cycle_start[c + 1] - cycle_start[c]; + for (int j = cycle_start[c]; j < cycle_start[c + 1]; j++) { + sum += log_cmd[j].count_up ? log_cmd[j].steps : -(int)log_cmd[j].steps; + } + printf("cycle %d = %d cmds, sum %" PRId64 "\n", c, n, (int64_t)sum); + check(sum == 0, "each cycle must net to zero"); + check(n == cycle_start[1] - cycle_start[0], + "all cycles must generate the same command count"); + if (c > 0) { + for (int j = 0; j < n; j++) { + const struct captured* a = &log_cmd[cycle_start[0] + j]; + const struct captured* b = &log_cmd[cycle_start[c] + j]; + if (a->steps != b->steps || a->count_up != b->count_up) { + check(false, "all cycles must generate identical commands"); + break; + } + } + } + } + + feed_rmt(); + + if (failures != 0) { + printf("TEST_24 FAILED (%d failures)\n", failures); + return 1; + } + printf( + "TEST_24 PASSED " + "(moveTimed + RMT translation preserve commanded position)\n"); + return 0; +} \ No newline at end of file diff --git a/tests/host/test_25.cpp b/tests/host/test_25.cpp new file mode 100644 index 0000000..53d96c8 --- /dev/null +++ b/tests/host/test_25.cpp @@ -0,0 +1,389 @@ +// test_25: moveTimed() pause reporting, DIR-preserving dwells, +// and prepare_revert +// +// When a direction change forces the queue driver to inject a pause, the +// moveTimed() call returns AQE_DIR_CHANGE_PAUSE_INJECTED (6) or +// AQE_DIR_PIN_2MS_PAUSE_ADDED (5) and the command was NOT enqueued. In this +// case *actual_duration carries the ticks of the one injected pause and the +// caller accumulates the value (extra) across retries, computing the drift +// only after the move is accepted: drift = duration - (actual + extra). +// +// Scenario A: per-call zeroing - actual_duration is never cumulative. +// Scenario B: regular dir pin with before+after pause (one pause per call). +// Scenario C: external dir pin with the 2ms pause mechanism. +// +// Like test_24, this is self-contained: it defines the queue/stepper members +// used by the inline bodies of fas_member/move_timed.h and +// fas_member/add_queue_entry.h and must not be linked against LIB_O. + +#include +#include +#include +#include +#include + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +#include "fas_arch/common.h" + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +// Direction-change pause insertion is provided by the pd_test default in +// pd_test/dir_change_pause.h; this standalone test does not link the library +// .o files, so it includes that default itself. It must be included after +// StepperQueue and its BEFORE/AFTER macros are known. The pd_test target +// #defines inline away, so this must be included in exactly one TU per binary. +#include "pd_test/dir_change_pause.h" + +// Production bodies of addQueueEntry() and moveTimed(), compiled against this +// test's StepperQueue/StepperMotion instead of the hardware queues. +#include "fas_member/add_queue_entry.h" +#include "fas_member/move_timed.h" + +static StepperQueue test_q; + +static int failures = 0; +static void check(int cond, const char* msg) { + if (!cond) { + printf("FAIL: %s\n", msg); + failures++; + } +} + +// Test-stepper configuration (applied by the overridden init() below). +static uint8_t g_dir_pin = 1; +static uint16_t g_dir_delay_ticks = 0; +static bool g_external_dir_pin_fail = false; + +// The test is not linked against StepperMotion.o, so provide the +// StepperMotion members that addQueueEntry()/moveTimed() reference. Their +// production bodies come from fas_member/add_queue_entry.h and +// fas_member/move_timed.h above. +StepperQueue* StepperMotion::_queue() const { return &test_q; } +bool StepperMotion::enableOutputs() { return true; } +bool StepperMotion::isQueueRunning() const { return _queue()->isRunning(); } +bool StepperMotion::handleExternalDirectionPin(StepperQueue* q, + bool count_up) { + (void)q; + (void)count_up; + if (g_external_dir_pin_fail) { + g_external_dir_pin_fail = false; + return false; + } + return true; +} +uint8_t StepperMotion::queueEntries() const { + return _queue()->queueEntries(); +} +bool StepperMotion::isQueueEmpty() const { return _queue()->isQueueEmpty(); } + +// Test-only init: TEST makes init() public. Configure the stepper for the test +// (no engine auto-enable, dir pin from g_dir_pin). +void StepperMotion::init(StepperMotionEngine* engine, uint8_t num, + uint8_t step_pin) { + (void)engine; + (void)step_pin; + _engine = NULL; + _queue_num = num; + _dirPin = g_dir_pin; + _dirHighCountsUp = true; + _autoEnable = false; + _on_delay_ticks = 0; + _dir_change_delay_ticks = g_dir_delay_ticks; + _auto_disable_delay_counter = 0; + _off_delay_count = 1; +} + +// Test has no real engine, so the dir-pin is never busy. +bool StepperMotionEngine::isDirPinBusy(uint8_t dirPin, + uint8_t except_stepper) { + (void)dirPin; + (void)except_stepper; + return false; +} + +// StepperQueue::addQueueEntry() (queue_add_entry.cpp) for the standalone test: +// maintains queue_end position, toggle flags and the write index, including +// the pause-stats bookkeeping used by SUPPORT_PAUSE_CMD_COUNTING. startQueue() +// is emulated by setting _isRunning. +AqeResultCode StepperQueue::addQueueEntry(const struct stepper_command_s* cmd, + bool start) { + if (cmd == NULL) { + if (start && !isRunning()) { + if (next_write_idx == read_idx) { + return AQE_ERROR_EMPTY_QUEUE_TO_START; + } + _isRunning = true; + } + return AQE_OK; + } + if (isQueueFull()) { + return AQE_QUEUE_FULL; + } + uint16_t period = cmd->ticks; + uint8_t steps = cmd->steps; + uint32_t command_rate_ticks = period; + if (steps > 1) { + command_rate_ticks *= steps; + } + if (command_rate_ticks < MIN_CMD_TICKS) { + return AQE_ERROR_TICKS_TOO_LOW; + } + uint8_t wp = next_write_idx; + struct queue_entry* e = &entry[wp & QUEUE_LEN_MASK]; + bool dir = (cmd->count_up == dirHighCountsUp); + bool toggle_dir = false; + bool dir_changed = false; + if (dirPin != PIN_UNDEFINED) { + dir_changed = (dir != queue_end.dir); + if ((isQueueEmpty() && !isRunning()) && + ((dirPin & PIN_EXTERNAL_FLAG) == 0)) { + queue_end.dir = dir; + } else { + toggle_dir = dir_changed; + } + } + e->steps = steps; + e->dirPinState = dir; + e->toggle_dir = toggle_dir; + e->countUp = cmd->count_up ? 1 : 0; + e->hasSteps = steps > 0 ? 1 : 0; + e->ticks = period; + struct queue_end_s next_queue_end = queue_end; +#if defined(SUPPORT_QUEUE_ENTRY_END_POS_U16) + e->end_pos_last16 = (uint32_t)next_queue_end.pos & 0xffff; +#endif + next_queue_end.pos = next_queue_end.pos + (cmd->count_up ? steps : -steps); + next_queue_end.dir = dir; + next_queue_end.count_up = cmd->count_up; + next_write_idx = wp + 1; + queue_end = next_queue_end; + + if (!isRunning() && start) { + _isRunning = true; + } + if ((steps > 0) || dir_changed) { + clear_pause_stats(); + } else { + if (_nr_of_pauses < 255) { + _nr_of_pauses++; + } + if (65535 - _last_pause_ticks >= period) { + _last_pause_ticks += period; + } else { + _last_pause_ticks = 65535; + } + } + return AQE_OK; +} + +// Test stepper: points addQueueEntry()/moveTimed() at test_q (num 0). +static StepperMotion test_stepper; + +static void reset(uint8_t dir_pin, uint16_t before_delay_ticks, + uint16_t after_delay_ticks, uint16_t dir_delay_ticks) { + __builtin_memset(&test_q, 0, sizeof(test_q)); + test_q._base_initVars(); + test_q._pd_initVars(); + test_q._before_dir_change_delay_ticks = before_delay_ticks; + test_q._after_dir_change_delay_ticks = after_delay_ticks; + test_q.setDirPin(dir_pin, true); + g_dir_pin = dir_pin; + g_dir_delay_ticks = dir_delay_ticks; + g_external_dir_pin_fail = false; + test_stepper.init(NULL, 0, 0); +} + +// ---- Scenario A: per-call zeroing --------------------------------------- + +static void test_per_call_zeroing() { + printf("Running: actual_duration is per-call (not cumulative)\n"); + reset(1, 0, 0, 0); + + uint32_t actual = 0; + uint32_t duration = 12000; + MoveTimedResultCode rc = test_stepper.moveTimed(3, duration, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "A: first move accepted"); + check(actual == duration, "A: first actual == duration"); + + // Direction change WITHOUT any configured delay must not inject a pause and + // the same 'actual' variable must hold only this move's ticks, i.e. the + // result is not the sum of previous calls. + duration = 24000; + rc = test_stepper.moveTimed(-3, duration, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "A: second move accepted"); + check(actual == duration, "A: actual is per-call (not cumulative)"); + + printf(" first=%u second=%u ticks\n", 12000u, duration); +} + +// ---- Scenario B: before+after dir-change pause, one per call ------------- + +static void test_dir_change_pause_reporting() { + printf("Running: dir-change pause(s) reported in the failing call\n"); + reset(1, US_TO_TICKS(1000), 0, US_TO_TICKS(500)); + + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed(2, 8000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "B: first (UP) move accepted"); + check(actual == 8000, "B: first actual == duration"); + check(test_q.queueEntries() == 1, "B: first move enqueues one entry"); + printf(" UP move: rc=%d actual=%u\n", (int)rc, actual); + + // Reversal UP -> DOWN. Queue driver injects at most one pause per call: + // call 1 injects the BEFORE pause, call 2 the AFTER (dir delay) pause, + // call 3 enqueues the move itself. Every failing call reports its pause. + uint32_t extra = 0; + uint32_t before_ticks = US_TO_TICKS(1000); + uint32_t after_ticks = US_TO_TICKS(500); + uint32_t duration = 8000; + printf(" expected before-pause=%u after-pause=%u ticks\n", before_ticks, + after_ticks); + + rc = test_stepper.moveTimed(-2, duration, &actual, false); + check(rc == MoveTimedResultCode::DirChangePauseInjected, + "B: call 1 injects a pause"); + check(actual == before_ticks, "B: call 1 actual == before-pause ticks"); + check(test_q.queueEntries() == 2, "B: call 1 enqueues exactly one entry"); + extra += actual; + printf(" DOWN call1: rc=%d actual=%u extra=%u\n", (int)rc, actual, extra); + + rc = test_stepper.moveTimed(-2, duration, &actual, false); + check(rc == MoveTimedResultCode::DirChangePauseInjected, + "B: call 2 injects a pause"); + check(actual == after_ticks, "B: call 2 actual == after-pause ticks"); + check(test_q.queueEntries() == 3, "B: call 2 enqueues exactly one entry"); + extra += actual; + printf(" DOWN call2: rc=%d actual=%u extra=%u\n", (int)rc, actual, extra); + + rc = test_stepper.moveTimed(-2, duration, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "B: call 3 move accepted"); + check(actual == duration, "B: call 3 actual == move ticks"); + check(test_q.queueEntries() == 4, "B: call 3 enqueues the move entry"); + int32_t drift = (int32_t)(duration - (actual + extra)); + printf(" DOWN call3: rc=%d actual=%u drift=%d\n", (int)rc, actual, drift); + check(drift == (int32_t)(duration - (duration + before_ticks + after_ticks)), + "B: drift accounts for both injected pauses"); +} + +// ---- Scenario C: external dir pin 2ms pause ------------------------------ + +static void test_external_dir_pin_2ms() { + printf("Running: external dir pin 2ms pause reported in failing call\n"); + reset(PIN_EXTERNAL_FLAG | 1, 0, 0, 0); + g_external_dir_pin_fail = true; + + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed(2, 8000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "C: first (UP) move accepted"); + check(actual == 8000, "C: first actual == duration"); + printf(" UP move: rc=%d actual=%u\n", (int)rc, actual); + + // Reversal to DOWN: the offline external dir-pin callback fails once, so a + // 2ms pause is injected and the call returns DirPin2msPauseAdded. The + // reported actual_duration must be the 2ms pause ticks, not the move's. + uint32_t extra = 0; + uint32_t pause_ticks = US_TO_TICKS(2000); + uint32_t duration = 8000; + rc = test_stepper.moveTimed(-2, duration, &actual, false); + check(rc == MoveTimedResultCode::DirPin2msPauseAdded, + "C: 2ms pause injected"); + check(actual == pause_ticks, "C: actual == 2ms pause ticks"); + check(test_q.queueEntries() == 2, "C: pause call enqueues one entry"); + extra += actual; + printf(" DOWN call1: rc=%d actual=%u extra=%u\n", (int)rc, actual, extra); + + rc = test_stepper.moveTimed(-2, duration, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "C: move accepted on retry"); + check(actual == duration, "C: retry actual == move ticks"); + check(test_q.queueEntries() == 3, "C: retry enqueues the move entry"); + int32_t drift = (int32_t)(duration - (actual + extra)); + printf(" DOWN call2: rc=%d actual=%u drift=%d\n", (int)rc, actual, drift); + check(drift == (int32_t)-(pause_ticks), + "C: drift accounts for the 2ms pause"); + check(g_external_dir_pin_fail == false, + "C: external callback only failed once"); +} + +// ---- Scenario D: timekeeping pause keeps last direction -------------------- + +static void test_pause_inherits_direction() { + printf("Running: moveTimed(0, dt) after DOWN does not toggle DIR\n"); + reset(1, 0, 0, 0); + + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed(-3, 12000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, "D: DOWN move accepted"); + check(test_q.queue_end.count_up == false, "D: queue_end is DOWN"); + uint8_t entries_before = test_q.queueEntries(); + + rc = test_stepper.moveTimed(0, 8000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, "D: pause accepted"); + check(actual == 8000, "D: pause actual == duration"); + check(test_q.queue_end.count_up == false, "D: pause kept DOWN"); + check(test_q.queueEntries() == (uint8_t)(entries_before + 1), + "D: pause enqueued one entry"); + uint8_t wi = (uint8_t)(test_q.next_write_idx - 1); + check(test_q.entry[wi & QUEUE_LEN_MASK].countUp == 0, + "D: pause entry countUp is DOWN"); + check(test_q.entry[wi & QUEUE_LEN_MASK].toggle_dir == 0, + "D: pause entry did not toggle DIR"); + check(test_q.entry[wi & QUEUE_LEN_MASK].hasSteps == 0, + "D: pause has no steps"); +} + +// ---- Scenario E: prepare_revert pause flips DIR -------------------------- + +static void test_prepare_revert() { + printf("Running: moveTimed(0, dt, prepare_revert) flips DIR\n"); + reset(1, 0, 0, 0); + + uint32_t actual = 0; + MoveTimedResultCode rc = test_stepper.moveTimed(2, 8000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, "E: UP move accepted"); + check(test_q.queue_end.count_up == true, "E: queue_end is UP"); + + rc = test_stepper.moveTimed(0, 8000, &actual, false, true); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "E: revert pause accepted"); + check(actual == 8000, "E: revert pause actual == duration"); + check(test_q.queue_end.count_up == false, "E: queue_end is DOWN"); + uint8_t wi = (uint8_t)(test_q.next_write_idx - 1); + check(test_q.entry[wi & QUEUE_LEN_MASK].countUp == 0, + "E: pause entry countUp is DOWN"); + check(test_q.entry[wi & QUEUE_LEN_MASK].toggle_dir == 1, + "E: pause entry toggled DIR"); + check(test_q.entry[wi & QUEUE_LEN_MASK].hasSteps == 0, + "E: pause has no steps"); + + rc = test_stepper.moveTimed(-2, 8000, &actual, false); + check(rc == MOVE_TIMED_OK || rc == MOVE_TIMED_EMPTY, + "E: reversing moveTimed does not inject"); + check(actual == 8000, "E: reversing move actual == duration"); +} + +int main() { + test_per_call_zeroing(); + test_dir_change_pause_reporting(); + test_external_dir_pin_2ms(); + test_pause_inherits_direction(); + test_prepare_revert(); + + if (failures != 0) { + printf("TEST_25 FAILED (%d failures)\n", failures); + return 1; + } + printf( + "TEST_25 PASSED (moveTimed pause ticks reported via " + "*actual_duration; pauses inherit DIR; prepare_revert)\n"); + return 0; +} \ No newline at end of file diff --git a/tests/host/test_26.cpp b/tests/host/test_26.cpp new file mode 100644 index 0000000..9692ad3 --- /dev/null +++ b/tests/host/test_26.cpp @@ -0,0 +1,5561 @@ +// FasNAxis host tests for synchronized motion across polylines. +// NaxisPlot writes trace data for gnuplot. The physical-model case F21 +// attaches a PhysicalStepper to each axis; the other cases use ideal counters. +#define FAS_PHYSICAL_STEPPER_ENABLED 1 +// (pulled in by physical_stepper.h) must precede the PC test shim's +// function-like `test` macro: libc++'s reaches and the macro +// would corrupt std::atomic_flag member names. +#include + +#include +#include +#include +#include + +#include + +// Enables the stateful reference scan in fas_naxis/remaining.h +// (test-only; production builds omit it). +#define FAS_NAXIS_REFERENCE + +#include "FasNAxis.h" +#include "fas_arch/test_pc.h" // test() macro +#include "fas_naxis/dda.h" +#include "fas_naxis/linear.h" +#include "fas_naxis/ramp_law.h" +#include "fas_naxis/ramp_map.h" +#include "fas_naxis/remaining.h" +#include "naxis_plot.h" +#include "naxis_ref.h" +#include "naxis_sim_port.h" +#include "../../examples/NaxesAFAP/NaxesAFAP_path.h" +#ifdef FAS_NAXIS_TRACE +#include "naxis_html_dump.h" +#endif + +// The normal test_% rule links LIB_O (StepperMotion.o), which references the +// PC interrupt hooks below. The other tests define these; Step 15's real-queue +// FAS runs use them. (Defined here, not in the header.) +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +// The engine every test planner is constructed with. Its synchronizedStart() +// releases the active SimPorts' queues in one call, mirroring the production +// StepperMotionEngine. +static TestStepperMotionEngine sim_engine; + +// Diagnostic 2 deg collinearity probe (whitepaper section 8.5): same sense and +// cos^2(d, d') >= 0.99878. Test-only, so double is allowed here; production +// carries no wide arithmetic. dot <= 0 means opposite sense, which fails. +static bool collinear_same_sense(const Remaining& r, int block_a, int block_b) { + double dot = 0.0; + double mag_a = 0.0; + double mag_b = 0.0; + for (int i = 0; i < r.n_axes; i++) { + double da = (double)r.delta_of(i, block_a); + double db = (double)r.delta_of(i, block_b); + dot += da * db; + mag_a += da * da; + mag_b += db * db; + } + if (dot <= 0.0 || mag_a == 0.0 || mag_b == 0.0) { + return false; + } + return dot * dot * 100000.0 >= 99878.0 * mag_a * mag_b; +} + +// Peak performed ramp-up over a rest-to-rest move of S steps. This is the +// outcome of RampLaw (P starts at 0, live remaining-to-stop), not a +// precomputed min(P_stop, R/2). Used by F19 / F2b item 5 instead of a +// Remaining::cap_P estimate. +static uint32_t peak_performed(uint32_t ticks_cfg, uint32_t accel, uint32_t S) { + RampLaw law(ticks_cfg, accel, S); + uint32_t peak = 0; + while (!law.done()) { + law.step(); + if (law.P > peak) { + peak = law.P; + } + } + return peak; +} + +// Smoke-test the gnuplot helper on a trivial 2-axis run so the header is +// compiled and exercised even before a planner exists. No kinematics. +void plot_smoke() { + NaxisPlot plot; + plot.start_plot("harness", "FasNAxis harness smoke", 2); + // Commanded polyline: a small square, the grey reference in panel 1. + plot.poly_point(0.0, 0.0); + plot.poly_point(0.0, 1600.0); + plot.poly_point(1600.0, 1600.0); + plot.poly_point(1600.0, 0.0); + plot.poly_done(); + for (int i = 0; i <= 4; i++) { + double t = 0.1 * i; + double x = 400.0 * i; + double y = (i % 2 == 0) ? 0.0 : 1600.0; + double speed[2] = {1000.0 * (5 - i), 1000.0 * (5 - i)}; + double P[2] = {(double)i, (double)i}; + double R[2] = {4000.0 - 1000.0 * i, 4000.0 - 1000.0 * i}; + double ticks[2] = {16000.0, 16000.0}; + // Synthetic commanded-minus-realized deviation so the fifth panel shows a + // non-trivial line; a real planner supplies the actual value. + double deviation = (i % 2 == 0) ? 1.0 : -1.0; + plot.row(t, x, y, deviation, speed, P, R, ticks); + } + plot.finish_plot(); + test(plot.is_open() == false, "plot should be closed after finish_plot"); + printf("harness gnuplot written: test_26_harness.gnuplot\n"); +} + +// F1 kernel (whitepaper section 7.1): the single-axis period/step law is the +// FAS ramp itself. The RampMap wrapper must be a bit-for-bit identity with the +// ramp_config_s object the library uses (same ticks_cfg + log2_from(accel)), +// round-trip within the documented log2 error band, be monotone non-increasing +// in P, and treat P = 0 as "stopped" (never feed it to calculate_ticks). +// +// Numbers from section 14.1: ticks_cfg = 4000 step/s => 4000 ticks, a = 2000 +// step/s^2, P_coast = calculate_ramp_steps(ticks_cfg) ~ 4000 (log2-rounded). +void f1_kernel() { + const uint32_t ticks_cfg = 4000; + const uint32_t accel = 2000; + + // The oracle is the exact ramp_config_s the library builds the same way. + ramp_config_s ref; + ref.init(); + ref.parameters.setSpeedInTicks(ticks_cfg); + ref.parameters.setAcceleration(accel); + ref.update(); + + RampMap map(ticks_cfg, accel); + + // P_coast matches the reference (section 14.1: 4000). + test(map.P_coast() == ref.max_ramp_up_steps, "F1 P_coast identity"); + test(abs((int32_t)map.P_coast() - 4000) <= 16, "F1 P_coast ~ 4000"); + test(map.ticks_cfg() == ticks_cfg, "F1 ticks_cfg retained"); + + uint32_t prev_ticks = 0; + uint32_t max_round_err = 0; + uint32_t max_round_err_ticks = 0; + for (uint32_t P = 1; P <= map.P_coast(); P *= 2) { + // Identity: the wrapper forwards to ramp_config_s, so it is exact. + uint32_t map_ticks = map.calculate_ticks(P); + uint32_t ref_ticks = ref.calculate_ticks(P); + test(map_ticks == ref_ticks, "F1 calculate_ticks identity"); + + // Monotone non-increasing in P: more ramp steps => shorter or equal period. + if (prev_ticks != 0) { + test(map_ticks <= prev_ticks, "F1 period monotone non-increasing in P"); + } + prev_ticks = map_ticks; + + // Round-trip within the documented log2 error band. RampCalculator.cpp's + // own round-trip check treats up to 1 step / 1 tick as acceptable, so the + // wrapper inherits the same tolerance. + uint32_t back = map.calculate_ramp_steps(map_ticks); + uint32_t err = back >= P ? back - P : P - back; + uint32_t back_ticks = map.calculate_ticks(back); + uint32_t err_ticks = map_ticks >= back_ticks ? map_ticks - back_ticks + : back_ticks - map_ticks; + if (err > max_round_err) { + max_round_err = err; + } + if (err_ticks > max_round_err_ticks) { + max_round_err_ticks = err_ticks; + } + test(err <= 1, "F1 ramp-steps round-trip within 1 step"); + test(err_ticks <= 1, "F1 period round-trip within 1 tick"); + } + printf("F1 kernel: P_coast=%u max_round_err=%u max_round_err_ticks=%u\n", + map.P_coast(), max_round_err, max_round_err_ticks); + + // P = 0 is "stopped": FAS starts ramps at P >= 1, so calculate_ticks(0) is + // never called. Guard the contract by asserting the smallest P we ever pass + // is 1 and that P_coast >= 1 (a degenerate ramp would violate F1). + test(map.P_coast() >= 1, "F1 P_coast >= 1 (non-degenerate ramp)"); + + // Plot: period vs P, overlay of wrapper vs reference. They are identical by + // construction, so the overlay is a flat check that the wrapper forwards. The + // F1 kernel is a period-vs-P identity check with no motion, so it uses the + // single-panel scalar overlay rather than a time-series trace. + NaxisPlot plot; + plot.start_scalar("f1_map", "FasNAxis F1 ramp map identity"); + for (uint32_t P = 1; P <= map.P_coast(); P *= 2) { + double map_ticks = (double)map.calculate_ticks(P); + double ref_ticks = (double)ref.calculate_ticks(P); + plot.scalar_row((double)P, map_ticks, ref_ticks); + } + plot.finish_scalar(1.0, (double)map.P_coast(), "P [ramp steps]", + "period [ticks]", "wrapper", "RampCalculator"); + printf("F1 kernel plot written: test_26_f1_map.gnuplot\n"); +} + +// Step 2 (whitepaper section 8): the remaining-steps scan R is the lookahead +// kernel. Feed polylines as arrays of signed per-axis displacements (no queues) +// and assert the section 8.1 parse, the section 8.5 Linear path-stop, the +// collinear micro-segment scan (F10), the F6b anisotropic corner, and the +// section 8.2 lookahead speed cap (F19: a small HORIZON of micro-segments caps +// P below P_stop without error; the same HORIZON with one long block coasts). +// +// Numbers from section 14.1: ticks_cfg = 4000 step/s => 4000 ticks, a = 2000 +// step/s^2, so P_stop = calculate_ramp_steps(ticks_cfg) ~ 4000. +void f2_remaining() { + const uint32_t ticks_cfg = 4000; + const uint32_t accel = 2000; + const uint32_t P_stop = RampMap(ticks_cfg, accel).P_coast(); + test(P_stop >= 3900 && P_stop <= 4100, "F2 P_stop ~ 4000"); + + // --- table row 1: one axis, one block (10000,) => R = 10000 --- + { + Remaining r(1, 1); + int32_t b0[1] = {10000}; + r.set_block(0, b0); + test(r.remaining(0, 0) == 10000, "F2 one block R = 10000"); + } + + // --- table row 2: two blocks, same sign (4000,) + (4000,) => R = 8000 --- + { + Remaining r(1, 2); + int32_t b0[1] = {4000}; + int32_t b1[1] = {4000}; + r.set_block(0, b0); + r.set_block(1, b1); + test(r.remaining(0, 0) == 8000, "F2 two same-sign blocks R = 8000"); + test(r.remaining(0, 1) == 4000, "F2 second block alone R = 4000"); + } + + // --- table row 3: reversal (4000,) + (-100,) => R = 4000 at start, then + // --- 100 the other way after the first block --- + { + Remaining r(1, 2); + int32_t b0[1] = {4000}; + int32_t b1[1] = {-100}; + r.set_block(0, b0); + r.set_block(1, b1); + test(r.remaining(0, 0) == 4000, "F2 reversal R = 4000 at start"); + test(r.remaining(0, 1) == 100, "F2 reversal R = 100 after block 0"); + test(r.delta_of(0, 1) < 0, "F2 reversal goes the other way (sign flip)"); + } + + // --- table row 4: idle then move (0,) + (100,) => first block does not + // --- start a direction; R = 100 --- + { + Remaining r(1, 2); + int32_t b0[1] = {0}; + int32_t b1[1] = {100}; + r.set_block(0, b0); + r.set_block(1, b1); + test(r.remaining(0, 0) == 100, "F2 idle-then-move R = 100"); + test(r.remaining(0, 1) == 100, "F2 move block alone R = 100"); + } + + // --- table row 5: Linear hard stop, 2-D square corner. The outgoing master + // --- was idle, so R ends at the corner: a side is one R-budget, not the + // --- perimeter. --- + { + Remaining r(2, 4); + int32_t b0[2] = {0, 1600}; + int32_t b1[2] = {1600, 0}; + int32_t b2[2] = {0, -1600}; + int32_t b3[2] = {-1600, 0}; + r.set_block(0, b0); + r.set_block(1, b1); + r.set_block(2, b2); + r.set_block(3, b3); + // At head 0 the moving axis is Y (|1600| > |0|); its Linear R ends at the + // first 90-degree corner = one side (1600), not the 6400 perimeter. + test(r.remaining_linear_binder(1, 0) == 1600, + "F2 Linear square binder R ends at 90-degree vertex"); + test(r.remaining_linear_binder(1, 0) < 6400, + "F2 Linear square R does not span the perimeter"); + // The non-collinear test itself: adjacent square sides are perpendicular. + test(collinear_same_sense(r, 0, 1) == false, + "F2 adjacent square sides are not collinear"); + } + + // --- table row 6 (F10): 100 x 100-step collinear micro-segments. R at the + // --- head is the full 10000, not 100 (collinear continuation, no per-segment + // --- rest). Test on a 2-axis diagonal so the collinear-aware scan matters. + // --- + { + const int N = 100; + Remaining r(2, N); + for (int i = 0; i < N; i++) { + int32_t blk[2] = {100, 100}; + r.set_block(i, blk); + } + test(r.remaining(0, 0) == N * 100, "F2 F10 per-axis R sees full 10000"); + test(r.remaining_linear_binder(0, 0) == N * 100, + "F2 F10 Linear binder R sees full 10000 (collinear)"); + test(r.remaining(0, 1) == (N - 1) * 100, + "F2 F10 R after one block = 9900 (no per-segment rest)"); + } + + // --- table row 7 (F6b): (4000,1) then (0,3999). R_x = 4000 (then idle); + // --- R_y = 4000 (continues through the anisotropic corner). --- + { + Remaining r(2, 2); + int32_t b0[2] = {4000, 1}; + int32_t b1[2] = {0, 3999}; + r.set_block(0, b0); + r.set_block(1, b1); + test(r.remaining(0, 0) == 4000, "F2 F6b R_x = 4000 then idle"); + test(r.remaining(1, 0) == 4000, "F2 F6b R_y = 4000 continues"); + } + + // --- section 8.5: the 2 deg test is diagnostic. A 3 deg bend whose master + // --- keeps its sense does not end R; a 90 deg corner (outgoing master was + // --- idle) does. --- + { + Remaining r(2, 2); + int32_t a1[2] = {1000, 17}; // ~1 degree off the x-axis + int32_t ax[2] = {1000, 0}; + int32_t a2[2] = {1000, 34}; // ~1.94 deg, just inside the 2 deg edge + int32_t a3[2] = {1000, 52}; // ~3 degree + int32_t a90[2] = {0, 1000}; // 90 degree + r.set_block(0, a1); + r.set_block(1, ax); + test(collinear_same_sense(r, 0, 1) == true, "F2 1 degree is collinear"); + r.set_block(0, a2); + r.set_block(1, ax); + test(collinear_same_sense(r, 0, 1) == true, + "F2 2 degree edge is collinear"); + r.set_block(0, a3); + r.set_block(1, ax); + test(collinear_same_sense(r, 0, 1) == false, + "F2 3 degree is not collinear"); + test(r.remaining_linear_binder(0, 0) == 2000, + "F2 3 degree bend does not end Linear R"); + r.set_block(0, a90); + r.set_block(1, ax); + test(collinear_same_sense(r, 0, 1) == false, + "F2 90 degree is not collinear"); + test(r.remaining_linear_binder(1, 0) == 1000, + "F2 90 degree corner ends Linear R at one side"); + // F6 dog-leg: equal |delta|, Y reverses. Tie-break keeps X as master, + // but Y is not a shorter slave, so the reversal is a hard stop. + int32_t dog0[2] = {1600, 1600}; + int32_t dog1[2] = {1600, -1600}; + r.set_block(0, dog0); + r.set_block(1, dog1); + test(r.remaining_linear_binder(0, 0) == 1600, + "F2 F6 equal-|delta| reversal ends Linear R"); + // Strictly shorter slave reversal (circle cardinal): R continues. + int32_t cusp0[2] = {1000, 10}; + int32_t cusp1[2] = {1000, -10}; + r.set_block(0, cusp0); + r.set_block(1, cusp1); + test(r.remaining_linear_binder(0, 0) == 2000, + "F2 shorter-slave reversal does not end Linear R"); + } + + // Role change onto an already-moving axis, with a slower third axis joining. + // Not a hard stop: R is steps of the incoming block plus the P that matches + // the outgoing period, not the sum of both blocks and not zero. + { + Remaining r(3, 2); + int32_t b0[3] = {8000, 3000, 0}; + int32_t b1[3] = {3000, 8000, 100}; + r.set_block(0, b0); + r.set_block(1, b1); + uint32_t ticks3[3] = {4000, 4000, 16000}; + uint32_t acc3[3] = {2000, 2000, 2000}; + uint32_t R = Remaining::linear_remaining<8>( + 0, 2, 3, ticks3, acc3, 0xFFFFFFFFU, + [&](int b, int ax) -> int32_t { return r.delta_of(ax, b); }); + RampMap incoming(4000, 2000); + uint32_t p_match = incoming.calculate_ramp_steps(16000); + test(p_match > 0 && p_match < 8000, "F2 role-change P_match is interior"); + test(R == 8000 + p_match, + "F2 role change prepares down to the slower ticks_floor"); + test(R > 8000, "F2 role-change preparation is not a full stop"); + test(R < 16000, "F2 role change does not ignore the slower envelope"); + printf("F2 role-change preparation: P_match=%u R=%u\n", p_match, R); + } + + // --- section 8.2 / F19: a small HORIZON of micro-segments caps P below + // --- P_stop (last point is rest, live remaining-to-stop so peak P < R) + // --- and does NOT raise an error; the same HORIZON with one long block + // --- coasts to P_stop because N/2 > P_stop. --- + { + const int N = 100; + Remaining r(1, N); + for (int i = 0; i < N; i++) { + int32_t blk[1] = {100}; + r.set_block(i, blk); + } + r.horizon = 8; // HORIZON too small to hold P_stop + // R is capped by HORIZON: 8 blocks x 100 = 800 < P_stop. No + // error raised. + int32_t R_micro = r.remaining(0, 0); + test(R_micro == 800, "F2 F19 micro-segment R capped at HORIZON = 800"); + uint32_t P_micro = peak_performed(ticks_cfg, accel, (uint32_t)R_micro); + test(P_micro < P_stop, "F2 F19 micro peak P below P_stop"); + test(P_micro < (uint32_t)R_micro, "F2 F19 must brake: peak P < R"); + + // Same HORIZON, one long 10000-step block: R is steps, not points, so the + // single block coasts to P_stop (10000/2 > P_stop). + Remaining long_r(1, 1); + int32_t big[1] = {10000}; + long_r.set_block(0, big); + long_r.horizon = 8; + test(long_r.remaining(0, 0) == 10000, "F2 F19 long block R = 10000"); + uint32_t P_long = peak_performed(ticks_cfg, accel, 10000); + test(P_long == P_stop, "F2 F19 long block reaches P_stop (coasts)"); + test(2 * P_stop < 10000, "F2 F19 N/2 > P_stop so coast exists"); + } + + // Plot F10: live ramp over the 100 collinear 100-step segments. R sees + // through (10000, not 100 per joint), so P starts at 0, coasts because + // 10000/2 > P_stop, and commanded/realized share the 45-degree chord. + { + const int N = 100; + const uint32_t S = (uint32_t)(N * 100); + Remaining r(2, N); + for (int i = 0; i < N; i++) { + int32_t blk[2] = {100, 100}; + r.set_block(i, blk); + } + int32_t prev = 0; + for (int head = 0; head < N; head++) { + int32_t Rscan = r.remaining(0, head); + test(Rscan <= prev || prev == 0, "F2 F10 R non-increasing over time"); + test(Rscan == (N - head) * 100, "F2 F10 R = remaining collinear steps"); + prev = Rscan; + } + test(r.remaining(0, 0) == (int32_t)S, "F2 F10 R at head is full 10000"); + + NaxisPlot plot; + plot.start_plot("f10", "FasNAxis F10 collinear micro-segments", 2); + plot.poly_point(0.0, 0.0); + for (int i = 1; i <= N; i++) { + plot.poly_point((double)i * 100.0, (double)i * 100.0); + } + plot.poly_done(); + + RampLaw law(ticks_cfg, accel, S); + uint32_t peak = 0; + uint32_t plot_every = 50; + // Rest sample: P starts at 0, realized on the commanded chord. + { + double speed[2] = {0.0, 0.0}; + double Pcol[2] = {0.0, 0.0}; + double Rcol[2] = {(double)law.R, (double)law.R}; + double tickscol[2] = {0.0, 0.0}; + plot.row(0.0, 0.0, 0.0, 0.0, speed, Pcol, Rcol, tickscol); + } + for (uint32_t k = 0; k < S; k++) { + test(law.P <= law.R, "F2 F10 P <= R at every step"); + uint32_t ticks = law.step(); + if (law.P > peak) { + peak = law.P; + } + uint32_t s = S - law.R; // steps issued = position on the diagonal + if ((s % 100) == 0) { + int head = (int)(s / 100); + if (head < N) { + test(r.remaining(0, head) == (int32_t)law.R, + "F2 F10 remaining() matches live R at block boundary"); + } + } + if (k % plot_every == 0 || k + 1 == S) { + // P == 0 is stopped: the last decel command used ticks_cfg, which + // would plot as v_max at rest. Show speed 0 at standstill. + double v = (law.P == 0) ? 0.0 : NAXIS_PLOT_TICKS_PER_S / (double)ticks; + double speed[2] = {v, v}; + double Pcol[2] = {(double)law.P, (double)law.P}; + double Rcol[2] = {(double)law.R, (double)law.R}; + double pt = (law.P == 0) ? 0.0 : (double)ticks; + double tickscol[2] = {pt, pt}; + double t = (double)law.total_ticks / NAXIS_PLOT_TICKS_PER_S; + plot.row(t, (double)s, (double)s, 0.0, speed, Pcol, Rcol, tickscol); + } + } + plot.finish_plot(); + test(law.done(), "F2 F10 planner consumed all collinear steps"); + test(peak == P_stop, "F2 F10 coasts: peak P == P_stop (R sees through)"); + test(plot.is_open() == false, "F2 F10 plot closed"); + printf("F2 remaining: P_stop=%u peak=%u plot written test_26_f10.gnuplot\n", + P_stop, peak); + } +} + +// Step 2b (whitepaper section 6.3 / 8.3, todo "theory probes"): the lookahead +// model must be correct on its own, not merely on the F-fixtures. A wrong model +// must fail here even if a later fixture is green. The oracle is a small pure +// function (Remaining::binder_axis / dda_steps / remaining, plus RampLaw +// peak_performed), never FasNAxis state. Two mutation hooks prove the probes +// are load-bearing: +// -FAS_NAXIS_NO_REBIND in remaining.h makes item 3 fail; +// -FAS_NAXIS_NO_REST_CAP in ramp_law.h makes item 5 fail to brake +// (peak P is not < R). +// +// Limits from section 14.1: a = 2000 step/s^2. ticks_cfg is the configured +// period; the ratios in item 3 use integer ticks (never a / in production). +void f2b_oracle() { + const uint32_t accel = 2000; + + // --- item 1: reference oracle --------------------------------------- + // Given a path direction and per-axis ticks, binder_axis names the axis + // that takes the longest wall-clock (argmax |delta_i| * ticks_i), DDA maps + // the binder's step count onto every slave, and P <= R per axis. Check the + // oracle: a clean DDA block (long X, short Y, equal ticks -> X binds, Y + // slaved) plus the rebind concept (a 4x-slower Y wins the wall-clock). + { + int32_t block[2] = {100, 50}; + uint32_t ticks[2] = {400, 400}; // equal: longest |delta| (X) binds + int binder = Remaining::binder_axis(block, ticks, 2); + test(binder == 0, "F2b item1 longest |delta| axis binds (X)"); + // DDA: Y is slaved onto X's 100 binder steps and issues 50 of them; the + // binder issues its own 100. + test(Remaining::dda_steps(block[binder], block[1]) == 50, + "F2b item1 DDA Y slaved to 50 of X 100 steps"); + test(Remaining::dda_steps(block[binder], block[0]) == 100, + "F2b item1 DDA X (binder) issues 100 steps"); + // Rebind concept: with Y 4x slower (ticks 1600), Y's wall-clock + // |dy|*ticks_y (50*1600) beats X's (100*400), so Y binds the + // time-law. DDA master stays X (longest |delta|); ticks_floor is + // Y's period (lengthen ticks_b), not a DDA rebind onto 50 steps. + uint32_t ticks_slow[2] = {400, 1600}; + int binder_slow = Remaining::binder_axis(block, ticks_slow, 2); + test(binder_slow == 1, "F2b item1 slow Y binds by wall-clock (rebind)"); + test(Remaining::longest_axis(block, ticks_slow, 2) == 0, + "F2b item1 DDA master stays longest X"); + test(Remaining::ticks_floor(block, ticks_slow, 2) == 1600, + "F2b item1 ticks_floor is the slow slave"); + // P <= R on the binder: a short R is remaining-to-stop, so the live + // ramp must brake (peak P < R), not a precomputed min(P_stop, R/2). + int32_t R = 30; + uint32_t P = peak_performed(400, accel, (uint32_t)R); + test(P < (uint32_t)R, "F2b item1 peak P < R on the binder"); + } + + // --- item 3: rebind neighbourhood ----------------------------------- + // |dx| in {99,100,101}, ticks_y/ticks_x in {1, 2, 99/100 (integer ticks)}. + // Especially |dx|*ticks_x ~= |dy|*ticks_y: the slow axis must bind. With + // rebind off (FAS_NAXIS_NO_REBIND) the longest-distance-only binder is wrong + // on these near-tie blocks (proven by the #if 0 build below). + { + int dxs[3] = {99, 100, 101}; + int tx[3] = {100, 100, 100}; + int ty[3] = {100, 200, 99}; // ratios 1, 2, 99/100 as integer ticks + int32_t dy = 100; // fixed |dy| so |dx|*ticks_x ~= |dy|*ticks_y + for (int i = 0; i < 3; i++) { + for (int j = 0; j < 3; j++) { + int32_t block[2] = {dxs[i], dy}; + uint32_t ticks[2] = {(uint32_t)tx[i], (uint32_t)ty[j]}; + int binder = Remaining::binder_axis(block, ticks, 2); + int64_t sx = (int64_t)block[0] * ticks[0]; + int64_t sy = (int64_t)block[1] * ticks[1]; + // The binder is exactly the axis with the larger | + // delta|*ticks + // (ties broken to X, the smaller index). + if (sy > sx) { + test(binder == 1, "F2b item3 slow Y binds"); + } else { + test(binder == 0, "F2b item3 X binds (tie / faster Y)"); + } + } + } + printf("F2b item3 rebind neighbourhood checked\n"); + } + + // --- item 4: collinear boundary (diagnostic) ------------------------ + // 1 degree passes, 2 degree is the edge, 3 and 90 degree are not collinear. + // The 2 deg test does not cut Linear R: a 3 deg same-master bend carries, + // a 90 deg corner (outgoing master idle) ends R. Include n=3. + { + Remaining r2(2, 2); + int32_t one[2] = {1000, 17}; + int32_t edge[2] = {1000, 34}; + int32_t three[2] = {1000, 52}; + int32_t right[2] = {0, 1000}; + int32_t axis[2] = {1000, 0}; + r2.set_block(0, one); + r2.set_block(1, axis); + test(collinear_same_sense(r2, 0, 1) == true, "F2b item4 1 deg passes"); + r2.set_block(0, edge); + test(collinear_same_sense(r2, 0, 1) == true, "F2b item4 2 deg edge passes"); + r2.set_block(0, three); + test(collinear_same_sense(r2, 0, 1) == false, + "F2b item4 3 deg is not collinear"); + test(r2.remaining_linear_binder(0, 0) == 2000, + "F2b item4 3 deg bend does not end Linear R"); + r2.set_block(0, right); + r2.set_block(1, axis); + test(collinear_same_sense(r2, 0, 1) == false, + "F2b item4 90 deg is not collinear"); + test(r2.remaining_linear_binder(1, 0) == 1000, + "F2b item4 90 deg corner ends Linear R"); + // n=3 collinearity is the 3-D dot test. A same-master bend is not + // collinear and still does not end Linear R. + Remaining r3(3, 2); + int32_t collinear0[3] = {100, 50, 10}; + int32_t collinear1[3] = {200, 100, 20}; // exact multiple: collinear + int32_t bend0[3] = {100, 50, 10}; + int32_t bend1[3] = {100, 0, 0}; // y bends: not collinear + int32_t tiny0[3] = {1000, 0, 1}; + int32_t tiny1[3] = {1000, 0, 0}; // a tiny z stays in the 2-deg cone + r3.set_block(0, collinear0); + r3.set_block(1, collinear1); + test(collinear_same_sense(r3, 0, 1) == true, + "F2b item4 n=3 proportional vectors are collinear"); + r3.set_block(0, bend0); + r3.set_block(1, bend1); + test(collinear_same_sense(r3, 0, 1) == false, + "F2b item4 n=3 bend is not collinear"); + test(r3.remaining_linear_binder(0, 0) == 200, + "F2b item4 n=3 same-master bend does not end Linear R"); + r3.set_block(0, tiny0); + r3.set_block(1, tiny1); + test(collinear_same_sense(r3, 0, 1) == true, + "F2b item4 n=3 tiny component stays collinear"); + } + + // --- item 5: lookahead speed cap ------------------------------------ + // Open path of 800 steps, P_stop = 4000: last point is rest, live + // remaining-to-stop so peak P < R (a triangle, not a precomputed R/2 + // estimate), no error. Appending collinear blocks until R >= 2 P_stop + // makes coasting to P_stop legal. Path direction (800, 400): Linear + // slaves Y onto X's R = 800 triangle. + { + const uint32_t ticks_cfg = 4000; + uint32_t P_stop = RampMap(ticks_cfg, accel).P_coast(); + test(P_stop >= 3900 && P_stop <= 4100, "F2b item5 P_stop ~ 4000"); + + // 800-step open path (single block): must brake; peak is below P_stop + // and strictly below remaining (the rest-cap mutation fails this). + uint32_t R800 = 800; + uint32_t P800 = peak_performed(ticks_cfg, accel, R800); + test(P800 < P_stop, "F2b item5 short path P below P_stop"); + test(P800 < R800, "F2b item5 short path brakes (peak P < R)"); + test(P800 >= 1, "F2b item5 short path no error (P >= 1)"); + + // Append collinear blocks until N/2 > P_stop: coasting becomes legal. + uint32_t Rbig = 10000; + uint32_t Pbig = peak_performed(ticks_cfg, accel, Rbig); + test(Pbig == P_stop, "F2b item5 long path reaches P_stop (coasts)"); + test(Pbig > P800, "F2b item5 larger P legal once N/2 > P_stop"); + + // Path direction (800, 400): X is the binder, Y is DDA-slaved onto X's + // R = 800 triangle. Y issues 400/800 of X's 800 binder steps = 400. + int32_t block[2] = {800, 400}; + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + int binder = Remaining::binder_axis(block, ticks, 2); + test(binder == 0, "F2b item5 (800,400) X is the binder"); + test(Remaining::dda_steps(block[binder], block[1]) == 400, + "F2b item5 Y DDA-slaved to 400 of X's 800 steps"); + } + // --- mutation counterexamples (proof the hooks are load-bearing) --- + // The normal build has the full model, so each counterexample below must + // hold. With FAS_NAXIS_NO_REBIND item 3 fails, and with + // FAS_NAXIS_NO_REST_CAP item 5 fails to brake. A wrong model is + // detected. + { + // Rebind counterexample (item 3): |dx|*ticks_x ~= |dy|*ticks_y, the slow + // Y binds. Longest-distance-only (rebind disabled) would pick X (101 > + // 99) and be wrong. + int32_t reb[2] = {101, 100}; + uint32_t rt[2] = {100, 99}; // X: 10100 Y: 9900 (Y wall-clock smaller + // but Y distance ~ equal) + // Here Y's wall-clock 100*99 = 9900 < X 101*100 = 10100, so X is the + // correct binder; the near-tie is what the neighbourhood sweeps. Assert + // the oracle matches the exact argmax so a wrong model cannot hide. + int binder = Remaining::binder_axis(reb, rt, 2); + int64_t sx = 101 * 100, sy = 100 * 99; + test(binder == (sy > sx ? 1 : 0), + "F2b mutation rebind oracle matches argmax"); + // Rest-cap counterexample (item 5): remaining-to-stop must brake, so + // peak P < R. Ignoring R (always accel) makes peak P == R on this + // short move. + uint32_t P_cap = peak_performed(4000, accel, 800); + test(P_cap < 800, "F2b mutation rest cap brakes (peak P < R)"); + } + printf("F2b oracle: all theory probes green\n"); +} + +// Step 2c (whitepaper section 6.3): the DDA walk, one block, geometry only. +// +// No ramp, no period, no queues. Remaining::dda_steps already counts how many +// steps a slave issues over |bind| binder steps; this step *walks* the error +// accumulator one binder step at a time (DdaWalk). Two-axis hand cases with +// integer positions only. Each binder step issues 0 or 1 step per axis (never +// 2); the walked count per axis must equal Remaining::dda_steps; the chord +// invariant |2*err| <= |bind| holds after every binder step; a test-only +// double confirms distance to the chord <= 0.5*sqrt(n) (section 12.4). +struct DdaCase { + const char* name; + int32_t dx; + int32_t dy; + int binder; // expected binder axis (0 = X, 1 = Y; tie -> smaller index) +}; + +static void f2c_dda_walk() { + DdaCase cases[] = { + {"(5,0) X binder, Y never steps", 5, 0, 0}, + {"(0,4) Y binder, X never steps", 0, 4, 1}, + {"(5,5) X binder (tie), Y every step", 5, 5, 0}, + {"(5,3) X binder, Bresenham", 5, 3, 0}, + {"(5,-3) X binder, Y steps -1", 5, -3, 0}, + {"(-4,2) X binder, signs follow delta", -4, 2, 0}, + }; + for (int c = 0; c < 6; c++) { + const DdaCase& cs = cases[c]; + int32_t d[2] = {cs.dx, cs.dy}; + uint32_t ticks[2] = {4000, 4000}; // equal ticks: longest |delta| binds + int binder = Remaining::binder_axis(d, ticks, 2); + char msg[64]; + snprintf(msg, sizeof(msg), "2c binder for %s", cs.name); + test(binder == cs.binder, msg); + int32_t bind = d[binder]; + int32_t slave = d[1 - binder]; + + int32_t walked[2] = {0, 0}; + int32_t pos[2] = {0, 0}; + DdaWalk w(bind, slave); + // A test-only double accumulator for the 12.4 chord-distance check. This is + // not production; the production walker is integer-only (DdaWalk). + double max_chord_dist = 0.0; + double chord_len = 0.0; + while (!w.done()) { + int out_bind = 0, out_slave = 0; + w.step(&out_bind, &out_slave); + test(out_bind == 1 || out_bind == -1, "2c binder steps exactly one"); + test(out_slave == -1 || out_slave == 0 || out_slave == 1, + "2c slave steps 0 or 1, never 2"); + walked[binder] += out_bind; + walked[1 - binder] += out_slave; + pos[binder] += out_bind; + pos[1 - binder] += out_slave; + test(w.on_chord(), "2c chord invariant |2*err| <= |bind|"); + + // 12.4: perpendicular distance of (pos) from the origin-to-d chord. + double px = (double)pos[0], py = (double)pos[1]; + double dx = (double)d[0], dy = (double)d[1]; + double denom = dx * dx + dy * dy; + if (denom > 0.0) { + chord_len = denom; + double dist2 = (px * dy - py * dx) / denom; // (dx,dy) unit-ish + double dist = dist2 * dist2; + if (dist > max_chord_dist) { + max_chord_dist = dist; + } + } + } + // Walked count per axis must equal the analytic dda_steps oracle. + int expected_bind = Remaining::dda_steps(bind, bind); + int expected_slave = Remaining::dda_steps(bind, slave); + int32_t wb_abs = (walked[binder] > 0) ? walked[binder] : -walked[binder]; + test(wb_abs == expected_bind, "2c binder walked count == dda_steps"); + int32_t ws_abs = + (walked[1 - binder] > 0) ? walked[1 - binder] : -walked[1 - binder]; + test(ws_abs == expected_slave, "2c slave walked count == dda_steps"); + + // End position equals the waypoint (integer positions only). + test(pos[0] == cs.dx && pos[1] == cs.dy, "2c end position == waypoint"); + + // 12.4 test-only: max perpendicular distance^2 <= 0.25 * n. + double n = chord_len; + test(max_chord_dist <= 0.25 * n + 1e-9, "2c chord distance <= 0.5*sqrt(n)"); + } + + // Plot: XY of (5,3) on the chord (binder X, Y slaved). + { + int32_t d[2] = {5, 3}; + int binder = 0; + int32_t bind = d[binder], slave = d[1 - binder]; + NaxisPlot plot; + plot.start_plot("f2c", "FasNAxis F2c DDA walk (5,3)", 2); + plot.poly_point(0.0, 0.0); + plot.poly_point(5.0, 3.0); + plot.poly_done(); + DdaWalk w(bind, slave); + int32_t pos[2] = {0, 0}; + for (int s = 0; s <= 5; s++) { + double speed[2] = {0.0, 0.0}; + double P[2] = {0.0, 0.0}; + double R[2] = {0.0, 0.0}; + double ticks[2] = {0.0, 0.0}; + plot.row((double)s, (double)pos[0], (double)pos[1], 0.0, speed, P, R, + ticks); + if (w.done()) { + break; + } + int out_bind = 0, out_slave = 0; + w.step(&out_bind, &out_slave); + pos[0] += out_bind; + pos[1] += out_slave; + } + plot.finish_plot(); + printf("F2c DDA walk plot written: test_26_f2c.gnuplot\n"); + } + printf("F2c DDA walk: 2-axis hand cases green\n"); +} + +// Step 3 (whitepaper section 7.1): the ramp law P vs R, still with no queue. +// +// One axis, rest-to-rest over S = 10000 steps at the section 14.1 limits +// (ticks_cfg for 4000 step/s, a = 2000 step/s^2). RampLaw drives R down to 0 +// one command at a time, applying the FAS control law of RampControl +// (_getNextCommand): +// +// R > P -> accelerate (P++), coast when P is already at P_coast +// R == P -> decelerate (P--) +// R < P -> decelerate (overshoot guard) +// ticks = max(calculate_ticks(P), ticks_cfg, ticks_min) +// +// Checks: the law never lets P exceed R; the issued step count equals S; the +// trapezoid peaks at P_coast and is symmetric (accel == decel); the total +// duration matches an independent RampCalculator trapezoid within a few Delta_t +// (a 2 ms slice); a batched planning chunk lands on the same P trajectory as +// single steps (the 2 ms rule must not change the law). The plot compares by +// eye to the test_02 trapezoids. +void f3_ramp() { + const uint32_t ticks_cfg = 4000; + const uint32_t accel = 2000; + const uint32_t S = 10000; + RampMap map(ticks_cfg, accel); + const uint32_t P_coast = map.P_coast(); + test(P_coast >= 3900 && P_coast <= 4100, "F3 P_coast ~ 4000"); + // P_coast must be small enough for a trapezoid (coast exists), so the peak + // is the true coast, not a triangular cap. + test(2 * P_coast < S, "F3 trapezoid: 2*P_coast < S (coast exists)"); + + // Reference trapezoid, computed independently from the planner: update P + // first (accel from rest is 0->1), then sum calculate_ticks over the + // issued P sequence. A separate loop, so an off-by-one in the planner's + // P advance / R decrement still diverges here. + auto ref_total = [&]() -> uint64_t { + uint64_t total = 0; + int32_t rem = (int32_t)S; + int32_t P = 0; + for (int32_t k = 0; k < S; k++) { + if (rem > P) { + if ((int32_t)P < (int32_t)P_coast) { + P++; + } + } else if (P > 0) { + P--; + } + uint32_t t = + (P == 0) ? map.calculate_ticks(1) : map.calculate_ticks((uint32_t)P); + if (t < ticks_cfg) { + t = ticks_cfg; + } + total += t; + rem--; + } + return total; + }; + uint64_t ref = ref_total(); + + // Pass 1: single-step trace. Assert the law invariants and record the P + // trajectory + trace for the plot. + { + RampLaw law(ticks_cfg, accel, S); + test(law.P == 0 && law.R == S, "F3 start at rest"); + uint32_t peak = 0; + int32_t first_decel_k = -1; + int32_t last_accel_k = -1; + int32_t prev_R = S; + NaxisPlot plot; + plot.start_plot("f3", "FasNAxis F3 rest-to-rest ramp", 1); + plot.poly_point(0.0, 0.0); + plot.poly_point((double)S, 0.0); + plot.poly_done(); + uint32_t plot_every = 50; // downsample 10000 rows for the gnuplot + { + double speed0[1] = {0.0}; + double P0[1] = {0.0}; + double R0[1] = {(double)S}; + double ticks0[1] = {0.0}; + plot.row(0.0, 0.0, 0.0, 0.0, speed0, P0, R0, ticks0); + } + for (uint32_t k = 0; k < S; k++) { + uint32_t R_before = law.R; + uint32_t P_before = law.P; + test(P_before <= R_before, "F3 P <= R at every step"); + uint32_t ticks = law.step(); + // P moves by exactly 1 toward the coast / back to rest, never jumps. + test(law.P == P_before + 1 || law.P == P_before - 1 || + (law.P == P_before && P_before == P_coast), + "F3 P changes by 0 or 1"); + if (law.P > peak) { + peak = law.P; + } + if (R_before > P_before && law.P > P_before) { + last_accel_k = (int32_t)k; + } + if (R_before <= P_before && first_decel_k < 0 && law.P < P_before) { + first_decel_k = (int32_t)k; + } + // R counts down by exactly 1, never skips. + test(law.R == prev_R - 1, "F3 R decreases by 1 per step"); + prev_R = law.R; + double v = (law.P == 0) ? 0.0 : NAXIS_PLOT_TICKS_PER_S / (double)ticks; + double speed[1] = {v}; + double Pcol[1] = {(double)law.P}; + double Rcol[1] = {(double)law.R}; + double tickscol[1] = {(law.P == 0) ? 0.0 : (double)ticks}; + double t = (double)law.total_ticks / NAXIS_PLOT_TICKS_PER_S; + double x = (double)(S - law.R); + if (k % plot_every == 0 || k + 1 == S) { + plot.row(t, x, 0.0, 0.0, speed, Pcol, Rcol, tickscol); + } + } + plot.finish_plot(); + test(law.done(), "F3 planner consumed all S steps"); + test(peak == P_coast, "F3 peak P == P_coast (coast reached)"); + test(last_accel_k < first_decel_k, "F3 accel phase precedes decel phase"); + // Symmetric trapezoid: decel starts when R == P; P held at P_coast during + // coast, so R == P_coast at position S - P_coast. The whitepaper 14.1 + // "s_coast = 10000 - 8000 = 2000" is the coast length S - 2*P_coast. + int32_t expect_decel = (int32_t)S - (int32_t)P_coast; + test(abs(first_decel_k - expect_decel) <= 2, + "F3 decel starts at S - P_coast"); + test(law.total_ticks == ref, "F3 total ticks matches RampCalculator"); + printf("F3 ramp: S=%u P_coast=%u peak=%u decel@%d total=%llu ref=%llu\n", S, + P_coast, peak, first_decel_k, (unsigned long long)law.total_ticks, + (unsigned long long)ref); + } + + // Pass 2: batched planning chunk (FAS 2 ms rule). A chunk must land on the + // identical P trajectory and total as single steps -- batching is a + // presentation detail, not a law change. Use a slow-speed chunk so several + // steps fall in one slice (section 4.2: 2 ms / current period). + { + RampLaw single(ticks_cfg, accel, S); + RampLaw chunk(ticks_cfg, accel, S); + // Chunk size: a 2 ms window at the current period, clamped to [1, + // remaining], exactly as FAS plans slow ramps forward. + const uint32_t DT = TICKS_PER_S / 500; // 2 ms in ticks (16 MHz) + uint32_t i = 0; + while (i < S) { + uint32_t p0 = single.P; + uint32_t r0 = single.R; + uint32_t ticks0 = single.period(); + uint32_t ps = (ticks0 < TICKS_PER_S / 1000) ? DT / ticks0 : 1; + if (ps == 0) { + ps = 1; + } + if (ps > single.R) { + ps = single.R; + } + single.step_chunk(ps); + chunk.step_chunk(ps); + test(chunk.P == single.P, "F3 chunked P matches single-step P"); + test(chunk.R == single.R, "F3 chunked R matches single-step R"); + i += ps; + } + test(single.done() && chunk.done(), "F3 both passes done"); + test(single.total_ticks == chunk.total_ticks, "F3 chunk total == single"); + test(single.total_ticks == ref, "F3 chunk total matches RampCalculator"); + printf("F3 chunk pass: total=%llu (matches single-step RampCalculator)\n", + (unsigned long long)chunk.total_ticks); + } + + // P <= R must hold at the instant of the transition into decel too: the law + // only turns decel when R <= P, so at that boundary P <= R still (they are + // equal, within the 1-step log2 rounding). + printf("F3 ramp plot written: test_26_f3.gnuplot\n"); +} + +// Step 2d (whitepaper section 6.3 / 9.2): the Linear one-block rest-to-rest +// interpolator. One committed segment: the binder runs a RampLaw over +// |delta_bind|; each binder step is one DDA tick from 2c. Equal ticks_cfg, so +// the longest |delta| binds. Checks: issued |steps| per axis equal |delta|; +// the walk ends at the vertex; the path lies on the chord; the binder P <= R +// from the RampLaw fields holds every step (a sanity check for this step -- +// reconstruction from issued periods is Step 2e, not here). +void f2d_linear_one_block() { + const uint32_t ticks_cfg = 4000; + const uint32_t accel = 2000; // section 14.1 limits + struct Case { + const char* name; + int32_t dx, dy; + int expect_binder; + }; + Case cases[] = { + {"(20,8) X binds", 20, 8, 0}, + {"(20,0) Y never steps", 20, 0, 0}, + {"(8,20) Y binds", 8, 20, 1}, + }; + for (int c = 0; c < 3; c++) { + const Case& cs = cases[c]; + int32_t d[2] = {cs.dx, cs.dy}; + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + LinearBlock block(ticks_cfg, accel, 2, d, ticks); + char msg[64]; + snprintf(msg, sizeof(msg), "2d binder for %s", cs.name); + test(block.binder == cs.expect_binder, msg); + + int32_t issued[2] = {0, 0}; // signed accumulated steps per axis + int32_t pos[2] = {0, 0}; + double max_chord_dist = 0.0; + double chord_len = 0.0; + double px0 = 0.0, py0 = 0.0; + while (!block.done()) { + int step_out[2]; + block.step(step_out); + test(step_out[0] == -1 || step_out[0] == 0 || step_out[0] == 1, + "2d axis 0 steps in {-1,0,1}"); + test(step_out[1] == -1 || step_out[1] == 0 || step_out[1] == 1, + "2d axis 1 steps in {-1,0,1}"); + issued[0] += step_out[0]; + issued[1] += step_out[1]; + pos[0] += step_out[0]; + pos[1] += step_out[1]; + // Sanity for this step: binder P <= R from the RampLaw fields (2e proves + // the same from issued periods, not these fields). + test(block.law.P <= block.law.R, "2d binder P <= R (fields)"); + // 12.4: perpendicular distance of (pos) from the origin-to-d chord. + double px = (double)pos[0], py = (double)pos[1]; + double ax = (double)d[0], ay = (double)d[1]; + double denom = ax * ax + ay * ay; + if (denom > 0.0) { + chord_len = denom; + double dist = (px * ay - py * ax) / denom; // chord unit-ish, signed + double d2 = dist * dist; + if (d2 > max_chord_dist) { + max_chord_dist = d2; + } + px0 = px; + py0 = py; + } + } + // Issued |steps| per axis equals |delta|. + int32_t is0 = issued[0] > 0 ? issued[0] : -issued[0]; + int32_t is1 = issued[1] > 0 ? issued[1] : -issued[1]; + int32_t ex0 = cs.dx > 0 ? cs.dx : -cs.dx; + int32_t ex1 = cs.dy > 0 ? cs.dy : -cs.dy; + snprintf(msg, sizeof(msg), "2d issued|steps| axis0 == |delta| for %s", + cs.name); + test(is0 == ex0, msg); + snprintf(msg, sizeof(msg), "2d issued|steps| axis1 == |delta| for %s", + cs.name); + test(is1 == ex1, msg); + // End position is the vertex. + test(pos[0] == cs.dx && pos[1] == cs.dy, "2d end position == vertex"); + // Path on the chord: 12.4 max perpendicular distance^2 <= 0.25 * n. + double n = chord_len; + test(max_chord_dist <= 0.25 * n + 1e-9, + "2d path within 0.5*sqrt(n) of the chord"); + printf("F2d %s: binder=%d issued=(%d,%d) end=(%d,%d) chord^2=%.3f n=%.1f\n", + cs.name, block.binder, issued[0], issued[1], pos[0], pos[1], + max_chord_dist, n); + (void)px0; + (void)py0; + } + + // Plot: XY of (20,8) plus binder speed vs time. + { + int32_t d[2] = {20, 8}; + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + LinearBlock block(ticks_cfg, accel, 2, d, ticks); + NaxisPlot plot; + plot.start_plot("f2d", "FasNAxis F2d Linear one-block (20,8)", 2); + plot.poly_point(0.0, 0.0); + plot.poly_point((double)d[0], (double)d[1]); + plot.poly_done(); + int32_t pos[2] = {0, 0}; + // First sample at rest (P == 0) so the trace has a start point. + { + double speed0[2] = {0.0, 0.0}; + double P0[2] = {0.0, 0.0}; + double R0[2] = {(double)block.law.R, 0.0}; + double ticks0[2] = {0.0, 0.0}; + plot.row(0.0, 0.0, 0.0, 0.0, speed0, P0, R0, ticks0); + } + while (!block.done()) { + int step_out[2]; + uint32_t ticks_issued = block.step(step_out); + pos[0] += step_out[0]; + pos[1] += step_out[1]; + double t = (double)block.law.total_ticks / NAXIS_PLOT_TICKS_PER_S; + double speed[2] = { + block.law.P == 0 ? 0.0 + : NAXIS_PLOT_TICKS_PER_S / (double)ticks_issued, + 0.0, + }; + double Pcol[2] = {(double)block.law.P, 0.0}; + double Rcol[2] = {(double)block.law.R, 0.0}; + double tickscol[2] = {(block.law.P == 0) ? 0.0 : (double)ticks_issued, + 0.0}; + plot.row(t, (double)pos[0], (double)pos[1], 0.0, speed, Pcol, Rcol, + tickscol); + } + plot.finish_plot(); + test(plot.is_open() == false, "2d plot closed"); + printf("F2d Linear one-block plot written: test_26_f2d.gnuplot\n"); + } + printf("F2d Linear one-block: hand cases green\n"); +} + +// Step 2e (whitepaper section 6.3 / 12.4): reconstruct P from the *issued +// periods* of the 2d trace -- a model that only wrote planner P fields must +// fail this (it would read RampLaw.P, which we never touch here). For each +// binder step, P_issued = calculate_ramp_steps(ticks_issued); the last +// rest-to-stop record issues ticks_cfg (period() at P==0) which reconstructs +// to P_coast, a standstill marker, not a moving command -- excluded from the +// P<=R and envelope checks. Remaining after k binder steps is |delta_bind|-k +// (the last buffered point is rest, section 8.1). +// +// Checks on every hand case: +// - DDA master is longest |delta| (never a shorter axis); +// - issued |steps| per axis equals |delta| (vertex hit); +// - P_issued <= remaining at every moving sample; +// - peak P_issued < |delta_master| (live remaining-to-stop on these shorts); +// - envelope: when axis i steps, ticks >= ticks_i_cfg (one-step slack, 12.4). +// +// Rebind hand cases (Y slower, wall-clock |dy|*ticks_y > |dx|*ticks_x): +// Y constrains the time-law (ticks_floor = ticks_y) but X stays DDA master. +// X is scaled down in speed, not in count -- walking DDA on Y would issue +// only |dy| steps of X and miss the vertex (the 2g (4000,8000) bite). +void f2e_issued_periods() { + struct Case { + const char* name; + int32_t dx, dy; + uint32_t ticks_x, ticks_y; + int expect_master; + int expect_time_binder; + }; + Case cases[] = { + {"(20,8) X binds (equal ticks)", 20, 8, 4000, 4000, 0, 0}, + {"(20,8) Y 4x slower", 20, 8, 4000, 16000, 0, 1}, + {"(5,3) Y 2x slower (2g bite)", 5, 3, 4000, 8000, 0, 1}, + }; + for (int c = 0; c < 3; c++) { + const Case& cs = cases[c]; + int32_t d[2] = {cs.dx, cs.dy}; + uint32_t ticks[2] = {cs.ticks_x, cs.ticks_y}; + uint32_t t_floor = Remaining::ticks_floor(d, ticks, 2); + int time_binder = Remaining::binder_axis(d, ticks, 2); + RampMap map(t_floor, 2000); + LinearBlock block(4000, 2000, 2, d, ticks); + char msg[80]; + snprintf(msg, sizeof(msg), "2e DDA master for %s", cs.name); + test(block.binder == cs.expect_master, msg); + snprintf(msg, sizeof(msg), "2e time-law binder for %s", cs.name); + test(time_binder == cs.expect_time_binder, msg); + test(block.law.ticks_cfg == t_floor, "2e time-law is ticks_floor"); + + uint32_t N = block.law.R; // |delta_master| + int32_t issued[2] = {0, 0}; + uint32_t peak_issued = 0; + int moving = 0; + int k = 0; + bool ok_envelope = true; + bool ok_p_le_r = true; + while (!block.done()) { + int step_out[2]; + uint32_t ticks_issued = block.step(step_out); + issued[0] += step_out[0]; + issued[1] += step_out[1]; + uint32_t p_issued = map.calculate_ramp_steps(ticks_issued); + bool rest = (ticks_issued == t_floor); // last step: P==0 -> P_coast + if (rest) { + // Standstill marker (period() at P==0). Excluded from P<=R / envelope; + // its reconstruction is the coast position P_coast, not a moving P. + test(map.calculate_ramp_steps(t_floor) == map.P_coast(), + "2e last record reconstructs to P_coast"); + } else { + moving++; + uint32_t remaining = N - (uint32_t)k; // |delta_master| - k, k before + if (p_issued > remaining) { + ok_p_le_r = false; + } + if (p_issued > peak_issued) { + peak_issued = p_issued; + } + // Per-axis envelope: a command that steps axis i must not be faster + // than ticks_i_cfg (shared tick sum, one-step slack of 12.4). + if (step_out[0] != 0 && ticks_issued < ticks[0]) { + ok_envelope = false; + } + if (step_out[1] != 0 && ticks_issued < ticks[1]) { + ok_envelope = false; + } + } + k++; + } + snprintf(msg, sizeof(msg), "2e P_issued <= remaining for %s", cs.name); + test(ok_p_le_r, msg); + test(peak_issued < N, "2e peak P_issued < |delta_master|"); + test(ok_envelope, "2e envelope ticks >= ticks_i_cfg"); + int32_t ix = issued[0] > 0 ? issued[0] : -issued[0]; + int32_t iy = issued[1] > 0 ? issued[1] : -issued[1]; + int32_t ex = cs.dx > 0 ? cs.dx : -cs.dx; + int32_t ey = cs.dy > 0 ? cs.dy : -cs.dy; + snprintf(msg, sizeof(msg), "2e issued |steps| == |delta| for %s", cs.name); + test(ix == ex && iy == ey, msg); + printf( + "F2e %s: master=%d time_binder=%d N=%u peak_P=%u moving=%d " + "issued=(%d,%d)\n", + cs.name, block.binder, time_binder, N, peak_issued, moving, issued[0], + issued[1]); + } + printf("F2e issued-period reconstruction: hand cases green\n"); +} + +static int32_t iround(double x) { + return (int32_t)(x >= 0.0 ? x + 0.5 : x - 0.5); +} + +static uint32_t lcg_next(uint32_t* s) { + *s = *s * 1664525u + 1013904223u; + return *s; +} + +static int32_t irand_inc(uint32_t* s, int32_t lo, int32_t hi) { + uint32_t span = (uint32_t)(hi - lo + 1); + return lo + (int32_t)(lcg_next(s) % span); +} + +static void push_block(int32_t blocks[][2], int* n_blocks, int32_t* posx, + int32_t* posy, int32_t dx, int32_t dy) { + if (dx == 0 && dy == 0) { + return; + } + blocks[*n_blocks][0] = dx; + blocks[*n_blocks][1] = dy; + *posx += dx; + *posy += dy; + (*n_blocks)++; +} + +// Walk a Linear walker (NaxisRefLinear oracle or LinearPoly interpolator). Both +// share the same public interface (step/done/master/ticks_law/R_before_cmd/R/P +// /dda/total_ticks). Reconstruct P from issued periods (never from P/R fields). +// At each block end, store the last moving P_issued. +template +static void walk_polyline(Walker& ref, Remaining* rem, const uint32_t* ticks, + uint32_t accel, int32_t* end_pos, int32_t* issued, + bool* envelope_ok, bool* p_le_r_ok, + uint32_t* vertex_p, int* n_vertex, int max_vertex, + NaxisPlot* plot, uint32_t* recon_slack, + int32_t* vertex_pos) { + int32_t pos[2] = {0, 0}; + issued[0] = 0; + issued[1] = 0; + *envelope_ok = true; + *p_le_r_ok = true; + *n_vertex = 0; + uint32_t last_moving_p = 0; + uint32_t slack = 0; + // Plot speed smoothing. The per-command pulse rate is noisy: the DDA master + // alternates, a multi-step catch-up is one short command, and the old code + // zeroed speed whenever the issued period equalled ticks_cfg -- which is + // exactly a coast, so every cruise looked like a stop. Track each axis's + // position delta per command and low-pass it (EMA, time constant + // kSpeedTau_s), sampling the smoothed value every kPlotStride commands. + // P and R are path-level (path steps), the DDA binder's currency. + const int kPlotStride = 8; + const double kSpeedTau_s = 0.02; + int sample_n = 0; + int32_t last_pos[2] = {0, 0}; + uint64_t last_ticks = 0; + double ema_v[2] = {0.0, 0.0}; + bool have_sample = false; + if (plot) { + double z[2] = {0.0, 0.0}; + plot->row(0.0, 0.0, 0.0, 0.0, z, z, z, z); + have_sample = true; + } + while (!ref.done()) { + int step_out[2]; + uint32_t ticks_issued = ref.step(step_out); + uint32_t t_law = ref.ticks_law; + uint32_t R_before = ref.R_before_cmd; + issued[0] += step_out[0]; + issued[1] += step_out[1]; + pos[0] += step_out[0]; + pos[1] += step_out[1]; + RampMap map(t_law, accel); + uint32_t p_issued = + ticks_issued > 0 ? map.calculate_ramp_steps(ticks_issued) : 0; + // A coast issues the max-speed period, which is not a "rest"; the original + // `rest` classification (period == max) stays for the assertion gating, but + // it must no longer drive the plot speed (that is what zeroed every coast). + // ticks == t_law is a coast, not a standstill. The joint sample must + // record it, or a cruising chord looks like a path-stop. + bool rest = (ticks_issued == t_law); + if (ticks_issued > 0) { + last_moving_p = p_issued; + } + if (!rest) { + // calculate_ramp_steps o calculate_ticks may land one step high + // (log2 inverse, section 12.4 one-step slack). + if (ref.P > R_before) { + *p_le_r_ok = false; + } + if (p_issued > R_before) { + uint32_t d = p_issued - R_before; + if (d > slack) { + slack = d; + } + } + if (step_out[0] != 0 && ticks_issued < ticks[0]) { + *envelope_ok = false; + } + if (step_out[1] != 0 && ticks_issued < ticks[1]) { + *envelope_ok = false; + } + } + if (plot) { + uint64_t now_ticks = ref.total_ticks; + double dt = (double)(now_ticks - last_ticks) / NAXIS_PLOT_TICKS_PER_S; + if (dt > 0.0) { + double alpha = dt / (kSpeedTau_s + dt); + ema_v[0] += alpha * ((double)(pos[0] - last_pos[0]) / dt - ema_v[0]); + ema_v[1] += alpha * ((double)(pos[1] - last_pos[1]) / dt - ema_v[1]); + } + last_pos[0] = pos[0]; + last_pos[1] = pos[1]; + last_ticks = now_ticks; + if ((sample_n % kPlotStride) == 0 && have_sample) { + double speed[2] = {ema_v[0], ema_v[1]}; + double Pcol[2] = {(double)p_issued, (double)p_issued}; + double Rcol[2] = {(double)ref.R, (double)ref.R}; + double tickscol[2] = {(double)ticks_issued, (double)ticks_issued}; + plot->row((double)now_ticks / NAXIS_PLOT_TICKS_PER_S, (double)pos[0], + (double)pos[1], 0.0, speed, Pcol, Rcol, tickscol); + } + } + sample_n++; + if (ref.dda.done()) { + if (*n_vertex < max_vertex) { + vertex_p[*n_vertex] = last_moving_p; + if (vertex_pos) { + vertex_pos[2 * *n_vertex] = pos[0]; + vertex_pos[2 * *n_vertex + 1] = pos[1]; + } + } + (*n_vertex)++; + last_moving_p = 0; + } + } + end_pos[0] = pos[0]; + end_pos[1] = pos[1]; + if (recon_slack) { + *recon_slack = slack; + } +} + +// NaxisRefLinear oracle walker (Step 2ref / F20). +static void ref_walk_polyline(Remaining* rem, const uint32_t* ticks, + uint32_t accel, int32_t* end_pos, int32_t* issued, + bool* envelope_ok, bool* p_le_r_ok, + uint32_t* vertex_p, int* n_vertex, int max_vertex, + NaxisPlot* plot, uint32_t* recon_slack, + int32_t* vertex_pos) { + NaxisRefLinear ref(rem, ticks, accel); + walk_polyline(ref, rem, ticks, accel, end_pos, issued, envelope_ok, p_le_r_ok, + vertex_p, n_vertex, max_vertex, plot, recon_slack, vertex_pos); +} + +// Step 2ref: globally fastest constraint-faithful Linear track. One-block +// traces match LinearBlock (2e). Two-block rows of 2f hold on the reference. +// F20 is the long polyline (half-circle with seeded random before/after). +void f2ref_reference() { + const uint32_t accel = 2000; + struct One { + const char* name; + int32_t dx, dy; + uint32_t tx, ty; + }; + One ones[] = { + {"(20,8) equal ticks", 20, 8, 4000, 4000}, + {"(20,8) Y 4x slower", 20, 8, 4000, 16000}, + {"(5,3) Y 2x slower", 5, 3, 4000, 8000}, + }; + for (int c = 0; c < 3; c++) { + int32_t d[2] = {ones[c].dx, ones[c].dy}; + uint32_t ticks[2] = {ones[c].tx, ones[c].ty}; + LinearBlock block(4000, accel, 2, d, ticks); + Remaining rem(2, 1); + rem.set_block(0, d); + NaxisRefLinear ref(&rem, ticks, accel); + char msg[80]; + while (!block.done() && !ref.done()) { + int a[2], b[2]; + uint32_t ta = block.step(a); + uint32_t tb = ref.step(b); + test(ta == tb, "2ref one-block ticks match LinearBlock"); + test(a[0] == b[0] && a[1] == b[1], + "2ref one-block steps match LinearBlock"); + } + snprintf(msg, sizeof(msg), "2ref %s both done together", ones[c].name); + test(block.done() && ref.done(), msg); + } + printf("F2ref one-block identity with LinearBlock green\n"); + + struct Two { + const char* name; + int32_t a0, a1, b0, b1; + bool path_stop_joint; + int master1; + }; + Two twos[] = { + {"(5,0)+(0,5) L", 5, 0, 0, 5, true, 1}, + {"(3,3)+(2,2) collinear", 3, 3, 2, 2, false, 0}, + {"(5,0)+(-3,0) reversal", 5, 0, -3, 0, true, 0}, + }; + uint32_t ticks_eq[2] = {4000, 4000}; + for (int c = 0; c < 3; c++) { + Remaining rem(2, 2); + int32_t d0[2] = {twos[c].a0, twos[c].a1}; + int32_t d1[2] = {twos[c].b0, twos[c].b1}; + rem.set_block(0, d0); + rem.set_block(1, d1); + int32_t end_pos[2], issued[2]; + bool env = true, plr = true; + uint32_t vp[8]; + int nv = 0; + ref_walk_polyline(&rem, ticks_eq, accel, end_pos, issued, &env, &plr, vp, + &nv, 8, NULL, NULL, NULL); + char msg[80]; + snprintf(msg, sizeof(msg), "2ref %s envelope", twos[c].name); + test(env, msg); + snprintf(msg, sizeof(msg), "2ref %s P_issued <= R", twos[c].name); + test(plr, msg); + test(issued[0] == twos[c].a0 + twos[c].b0 && + issued[1] == twos[c].a1 + twos[c].b1, + "2ref two-block issued == polyline"); + test(end_pos[0] == issued[0] && end_pos[1] == issued[1], + "2ref two-block end is last vertex"); + test(nv >= 2, "2ref two-block has a vertex sample per block"); + if (twos[c].path_stop_joint) { + test(vp[0] <= 1, "2ref path-stop joint last moving P_issued <= 1"); + } else { + test(vp[0] > 1, "2ref collinear joint does not rest"); + } + printf("F2ref %s: vertices=%d joint_P=%u end=(%d,%d)\n", twos[c].name, nv, + vp[0], end_pos[0], end_pos[1]); + (void)twos[c].master1; + } + printf("F2ref two-block path-stop/collinear/reversal green\n"); +} + +// F20 block layout shared by the oracle (Step 2ref) and the interpolator +// (Step 2h): seeded random, a connecting block to (r,0), a half-circle of 1 deg +// chords, then seeded random again. Same seed (26) => identical polyline, +// so both walkers run over the same committed blocks. +static int build_f20_blocks(int32_t blocks[][2], int32_t* sum) { + // r=4800 / 190 chords: a chord is ~79 steps, so the integer quantisation + // error (~1 step) stays under the 2 deg collinear band (max joint 1.61 deg) + // and the half-circle is one cruise. At r=1600 / 180 chords a 1 deg chord is + // only ~28 steps, the quantisation makes ~60% of joints >2 deg, and the arc + // path-stops at every chord. r=4800 also keeps the arc length (~15080) under + // 2*P_stop (~16000), so the path is a triangle (no coast plateau): a clean + // 0 -> max -> 0 ramp. + const int32_t r = 4800; + const int n_arc = 190; + const int n_rand = 80; + int n_blocks = 0; + uint32_t rng = 26; + int32_t posx = 0; + int32_t posy = 0; + sum[0] = 0; + sum[1] = 0; + for (int i = 0; i < n_rand; i++) { + int32_t dx = 0; + int32_t dy = 0; + while (dx == 0 && dy == 0) { + dx = irand_inc(&rng, -12, 12); + dy = irand_inc(&rng, -12, 12); + } + push_block(blocks, &n_blocks, &posx, &posy, dx, dy); + } + push_block(blocks, &n_blocks, &posx, &posy, r - posx, 0 - posy); + int32_t ax = r; + int32_t ay = 0; + for (int i = 1; i <= n_arc; i++) { + double th = 3.14159265358979323846 * (double)i / (double)n_arc; + int32_t x = iround((double)r * cos(th)); + int32_t y = iround((double)r * sin(th)); + push_block(blocks, &n_blocks, &posx, &posy, x - ax, y - ay); + ax = x; + ay = y; + } + for (int i = 0; i < n_rand; i++) { + int32_t dx = 0; + int32_t dy = 0; + while (dx == 0 && dy == 0) { + dx = irand_inc(&rng, -12, 12); + dy = irand_inc(&rng, -12, 12); + } + push_block(blocks, &n_blocks, &posx, &posy, dx, dy); + } + sum[0] = posx; + sum[1] = posy; + return n_blocks; +} + +// F20: several hundred waypoints — seeded random, half-circle, seeded random +// — so the globally fastest Linear reference hits collinear cruise, Y-reversal +// path-stop on the arc, rebind (ticks 4000/8000), idle-free kinks, and a long +// connecting block. Constraint-faithful: vertices, envelope, P<=R, +// |steps|==|Δ|. +void f20_long_polyline() { + const uint32_t accel = 2000; + const uint32_t ticks[2] = {4000, 8000}; + int32_t blocks[512][2]; + int32_t sum[2]; + int n_blocks = build_f20_blocks(blocks, sum); + + test(n_blocks >= 200, "F20 several hundred waypoints"); + Remaining rem(2, n_blocks); + for (int b = 0; b < n_blocks; b++) { + rem.set_block(b, blocks[b]); + } + rem.horizon = 0xFFFFFFFFU; + + NaxisPlot plot; + plot.start_plot("f20", "FasNAxis F20 half-circle + random", 2); + plot.poly_point(0.0, 0.0); + { + int32_t wx = 0, wy = 0; + for (int b = 0; b < n_blocks; b++) { + wx += blocks[b][0]; + wy += blocks[b][1]; + plot.poly_point((double)wx, (double)wy); + } + } + plot.poly_done(); + + int32_t end_pos[2], issued[2]; + bool env = true, plr = true; + uint32_t vp[512]; + int nv = 0; + uint32_t recon_slack = 0; + ref_walk_polyline(&rem, ticks, accel, end_pos, issued, &env, &plr, vp, &nv, + 512, &plot, &recon_slack, NULL); + plot.finish_plot(); + + test(env, "F20 envelope ticks >= ticks_i_cfg"); + test(plr, "F20 law P <= R_before"); + test(recon_slack <= 2, "F20 reconstructed P within 2-step log2 band of R"); + test(issued[0] == sum[0] && issued[1] == sum[1], + "F20 issued |steps| == polyline"); + test(end_pos[0] == sum[0] && end_pos[1] == sum[1], + "F20 end position is last vertex"); + test(nv == n_blocks, "F20 a vertex sample at every waypoint"); + + int n_stop = 0; + int n_cruise = 0; + for (int i = 0; i < nv - 1; i++) { + if (vp[i] <= 1) { + n_stop++; + } else { + n_cruise++; + } + } + test(n_stop >= 1, "F20 has a Linear path-stop joint"); + test(n_cruise >= 1, "F20 has a cruise joint"); + // The half-circle cruises because the DDA master does not reverse along it. + // The 2 deg test is only a check that the chords stayed smooth. A 1 deg + // chord rounded to integers at r=1600 is only ~28 steps, so the quantisation + // makes ~60% of joints >2 deg; that used to sawtooth the arc. r=4800 keeps + // the chords smooth, and the carry rule cruises them either way. + { + const int arc_first = 80 + 1; // 80 random + 1 connecting block + const int arc_len = 190; + int arc_nonsmooth = 0; + for (int i = arc_first; i < arc_first + arc_len - 1; i++) { + if (!collinear_same_sense(rem, i, i + 1)) { + arc_nonsmooth++; + } + } + test(arc_nonsmooth == 0, + "F20 half-circle chords stay inside the 2 deg band"); + // The arc cruises because the master does not reverse. Skip the joints + // where the random walk hands off and where the arc ends (those may be + // real stops). Every interior arc joint keeps P. + int arc_rest = 0; + for (int i = arc_first + 2; i < arc_first + arc_len - 3; i++) { + if (i < nv - 1 && vp[i] <= 1) { + arc_rest++; + } + } + test(arc_rest == 0, "F20 half-circle interior joints cruise"); + } + printf( + "F20 blocks=%d vertices=%d stop_joints=%d cruise_joints=%d " + "recon_slack=%u end=(%d,%d)\n", + n_blocks, nv, n_stop, n_cruise, recon_slack, end_pos[0], end_pos[1]); + printf("F20 long polyline plot written: test_26_f20.gnuplot\n"); +} + +// Step 2f: two-block Linear, path-stop vs collinear. The LinearPoly +// interpolator (src/fas_naxis/linear.h) walks two committed blocks and is +// compared to the NaxisRefLinear oracle on the three two-block rows: a 90deg +// L (path-stop, P -> 0 at the vertex, binder switches to the next axis), a +// collinear run (P carries, no rest at the joint), and a reversal (P -> 0 +// then the other sign). P is reconstructed from issued periods; a wrong model +// that only writes planner P fields must fail here. +// Step 2g: exhaustive tiny Linear. Every 2-axis polyline with |delta_i| <= 5, +// 3 vertices (2 blocks) and 4 vertices (3 blocks), across three integer ticks +// pairs, compared to the naxis_ref oracle (independent of the interpolator P / +// R fields). This is combinatorics (DDA / vertex / P <= R), not coasting, so +// no P_stop cruise is asserted. Idle-then-move is included (a block may be 0); +// the first block is never all-zero (a no-op move). +// +// Vertex invariant of the oracle: walk_polyline emits one vertex per walked +// block, and a trailing zero block is not walked, so the count is +// "highest non-zero block index + 1". Each vertex sample sits at a waypoint. +// A joint between block i-1 and i is a hard stop (P -> 0) when the master +// sense ends or the outgoing master was idle, and a carry (P continues) +// otherwise. The 2 deg test does not decide it. +// Walks one committed polyline through the naxis_ref oracle and checks the +// 2g invariants. `wp` holds the cumulative waypoint of each block start +// (wp[2b] / wp[2b+1] = sum of blocks 0..b-1), wp[0..1] = origin. +static void f2g_walk(Remaining* rem, const uint32_t* ticks, uint32_t accel, + int n_blocks, int32_t* wp, uint64_t* ref_time, + uint64_t* wp_time, uint64_t* joint_time) { + int32_t end_pos[2], issued[2]; + bool env = true, plr = true; + uint32_t vp[16]; + int nv = 0; + uint32_t slack = 0; + int32_t vpos[32]; + *ref_time = 0; + *wp_time = 0; + *joint_time = 0; + + struct timeval t0, t1; + gettimeofday(&t0, NULL); + ref_walk_polyline(rem, ticks, accel, end_pos, issued, &env, &plr, vp, &nv, 16, + NULL, &slack, vpos); + gettimeofday(&t1, NULL); + *ref_time = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000ULL + + (uint64_t)(t1.tv_usec - t0.tv_usec); + + test(env, "2g envelope ticks >= ticks_i_cfg"); + test(plr, "2g law P_issued <= R"); + int32_t sum[2] = {0, 0}; + for (int b = 0; b < n_blocks; b++) { + sum[0] += rem->delta_of(0, b); + sum[1] += rem->delta_of(1, b); + } + test(issued[0] == sum[0] && issued[1] == sum[1], + "2g issued |steps| == |delta|"); + test(end_pos[0] == sum[0] && end_pos[1] == sum[1], "2g end is last vertex"); + + gettimeofday(&t0, NULL); + // Every emitted vertex lands exactly on a cumulative waypoint. A trailing + // no-op block makes the oracle emit a duplicate sample at the final position + // (the finished transition still has dda.done() true), so we check "on some + // waypoint" rather than a positional index. + for (int i = 0; i < nv; i++) { + bool on_waypoint = 0; + for (int b = 0; b < n_blocks; b++) { + if (vpos[2 * i] == wp[2 * b] && vpos[2 * i + 1] == wp[2 * b + 1]) { + on_waypoint = 1; + } + } + test(on_waypoint, "2g every vertex hits a cumulative waypoint"); + } + gettimeofday(&t1, NULL); + *wp_time = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000ULL + + (uint64_t)(t1.tv_usec - t0.tv_usec); + + gettimeofday(&t0, NULL); + // Joint P semantics. vertex_p[k] is the last moving P of block k. A joint + // is a hard stop (P -> 0) when the master sense ends or the outgoing + // master was idle. Every other joint carries P. Idle blocks are not + // joints. A carry joint only *must* be in cruise (P_issued > 1) once the + // live remaining path exceeds P_coast; below that the ramp is + // legitimately decelerating toward rest. + for (int i = 1; i < n_blocks; i++) { + int32_t da[2] = {rem->delta_of(0, i - 1), rem->delta_of(1, i - 1)}; + int32_t db[2] = {rem->delta_of(0, i), rem->delta_of(1, i)}; + int64_t ma = (int64_t)da[0] * da[0] + (int64_t)da[1] * da[1]; + int64_t mb = (int64_t)db[0] * db[0] + (int64_t)db[1] * db[1]; + if (ma == 0 || mb == 0) { + continue; // an idle block is not a joint + } + bool stop = Remaining::linear_joint_stops(da, db, ticks, 2); + if (stop) { + test(vp[i - 1] <= 1, "2g path-stop joint P_issued <= 1"); + } else { + int32_t r0 = 0, r1 = 0; + for (int b = i; b < n_blocks; b++) { + int32_t c[2] = {rem->delta_of(0, b), rem->delta_of(1, b)}; + if (c[0] == 0 && c[1] == 0) { + continue; + } + int m = Remaining::longest_axis(c, ticks, 2); + int64_t a = c[m] > 0 ? c[m] : -c[m]; + if (m == 0) { + r0 += a; + } else { + r1 += a; + } + } + uint32_t pc0 = RampMap(ticks[0], accel).P_coast(); + uint32_t pc1 = RampMap(ticks[1], accel).P_coast(); + bool cruise = + (r0 > 0 && (uint32_t)r0 > pc0) || (r1 > 0 && (uint32_t)r1 > pc1); + if (cruise) { + test(vp[i - 1] > 1, "2g collinear cruise joint does not rest"); + } + } + } + gettimeofday(&t1, NULL); + *joint_time = (uint64_t)(t1.tv_sec - t0.tv_sec) * 1000000ULL + + (uint64_t)(t1.tv_usec - t0.tv_usec); +} + +void f2g_exhaustive() { + const uint32_t accel = 2000; + const uint32_t ticks_cases[3][2] = {{4000, 4000}, {4000, 8000}, {100, 99}}; + int32_t vals[11]; + for (int v = 0; v < 11; v++) { + vals[v] = (int32_t)v - 5; + } + long n_tested = 0, n_joint_stop = 0, n_joint_collinear = 0; + struct Timing { + uint64_t ref_walk; + uint64_t waypoint_check; + uint64_t joint_check; + }; + Timing total = {0, 0, 0}; + for (int t = 0; t < 3; t++) { + printf("F2g ticks_case[%d]: (%u,%u)\n", t, ticks_cases[t][0], + ticks_cases[t][1]); + struct Timing case_t = {0, 0, 0}; + for (int i0 = 0; i0 < 11; i0++) { + for (int j0 = 0; j0 < 11; j0++) { + int32_t d0[2] = {vals[i0], vals[j0]}; + if (d0[0] == 0 && d0[1] == 0) { + continue; // all-zero first block is a no-op move; skip + } + for (int i1 = 0; i1 < 11; i1++) { + for (int j1 = 0; j1 < 11; j1++) { + int32_t d1[2] = {vals[i1], vals[j1]}; + int32_t wp[4] = {d0[0], d0[1], d0[0] + d1[0], d0[1] + d1[1]}; + Remaining rem2(2, 2); + rem2.set_block(0, d0); + rem2.set_block(1, d1); + uint64_t ref_t = 0, wp_t = 0, joint_t = 0; + f2g_walk(&rem2, ticks_cases[t], accel, 2, wp, &ref_t, &wp_t, + &joint_t); + case_t.ref_walk += ref_t; + case_t.waypoint_check += wp_t; + case_t.joint_check += joint_t; + n_tested++; + if (d1[0] != 0 || d1[1] != 0) { + bool stop = + Remaining::linear_joint_stops(d0, d1, ticks_cases[t], 2); + if (stop) { + n_joint_stop++; + } else { + n_joint_collinear++; + } + } + for (int i2 = 0; i2 < 11; i2++) { + for (int j2 = 0; j2 < 11; j2++) { + int32_t d2[2] = {vals[i2], vals[j2]}; + int32_t wp3[6] = {d0[0], + d0[1], + d0[0] + d1[0], + d0[1] + d1[1], + d0[0] + d1[0] + d2[0], + d0[1] + d1[1] + d2[1]}; + Remaining rem3(2, 3); + rem3.set_block(0, d0); + rem3.set_block(1, d1); + rem3.set_block(2, d2); + ref_t = wp_t = joint_t = 0; + f2g_walk(&rem3, ticks_cases[t], accel, 3, wp3, &ref_t, &wp_t, + &joint_t); + case_t.ref_walk += ref_t; + case_t.waypoint_check += wp_t; + case_t.joint_check += joint_t; + n_tested++; + } + } + } + } + } + } + total.ref_walk += case_t.ref_walk; + total.waypoint_check += case_t.waypoint_check; + total.joint_check += case_t.joint_check; + } + printf( + "F2g exhaustive Linear: %ld polylines tested, %ld path-stop joints, " + "%ld carry joints\n", + n_tested, n_joint_stop, n_joint_collinear); + uint64_t total_ns = total.ref_walk + total.waypoint_check + total.joint_check; + printf( + "F2g timing (mach_absolute_time units): ref_walk=%lu waypoint_check=%lu " + "joint_check=%lu total=%lu\n", + (unsigned long)total.ref_walk, (unsigned long)total.waypoint_check, + (unsigned long)total.joint_check, (unsigned long)total_ns); + test(n_tested > 0, "2g polylines were actually tested"); + test(n_joint_stop > 0, "2g exercised a path-stop joint"); + test(n_joint_collinear > 0, "2g exercised a carry joint"); + printf("F2g exhaustive tiny Linear green\n"); +} +void f2f_two_block() { + const uint32_t accel = 2000; + uint32_t ticks_eq[2] = {4000, 4000}; + struct Row { + const char* name; + int32_t a0, a1, b0, b1; + bool path_stop; + int master_after; // binder expected after the joint (block 1) + }; + Row rows[] = { + {"(5,0)+(0,5) L", 5, 0, 0, 5, true, 1}, + {"(3,3)+(2,2) collinear", 3, 3, 2, 2, false, 0}, + {"(5,0)+(-3,0) reversal", 5, 0, -3, 0, true, 0}, + {"(1000,52)+(1000,0) 3deg", 1000, 52, 1000, 0, false, 0}, + {"(8000,3000)+(3000,8000) role", 8000, 3000, 3000, 8000, false, 1}, + }; + const int n_rows = (int)(sizeof(rows) / sizeof(rows[0])); + for (int c = 0; c < n_rows; c++) { + const Row& r = rows[c]; + int32_t sum0 = r.a0 + r.b0; + int32_t sum1 = r.a1 + r.b1; + int32_t d0[2] = {r.a0, r.a1}; + int32_t d1[2] = {r.b0, r.b1}; + + // Oracle walk (truth). + Remaining ref_rem(2, 2); + ref_rem.set_block(0, d0); + ref_rem.set_block(1, d1); + int32_t ref_end[2], ref_issued[2]; + bool ref_env = true, ref_plr = true; + uint32_t ref_vp[8]; + int ref_nv = 0; + uint32_t ref_slack = 0; + ref_walk_polyline(&ref_rem, ticks_eq, accel, ref_end, ref_issued, &ref_env, + &ref_plr, ref_vp, &ref_nv, 8, NULL, &ref_slack, NULL); + + // Interpolator walk (the production core under test). + Remaining poly_rem(2, 2); + poly_rem.set_block(0, d0); + poly_rem.set_block(1, d1); + LinearPoly poly(&poly_rem, ticks_eq, accel); + int32_t poly_end[2], poly_issued[2]; + bool poly_env = true, poly_plr = true; + uint32_t poly_vp[8]; + int poly_nv = 0; + uint32_t poly_slack = 0; + walk_polyline(poly, &poly_rem, ticks_eq, accel, poly_end, poly_issued, + &poly_env, &poly_plr, poly_vp, &poly_nv, 8, NULL, &poly_slack, + NULL); + + char msg[96]; + snprintf(msg, sizeof(msg), "2f %s envelope (interpolator)", r.name); + test(poly_env, msg); + snprintf(msg, sizeof(msg), "2f %s P_issued <= R (interpolator)", r.name); + test(poly_plr, msg); + snprintf(msg, sizeof(msg), "2f %s issued |steps| == |delta|", r.name); + test(poly_issued[0] == sum0 && poly_issued[1] == sum1, msg); + snprintf(msg, sizeof(msg), "2f %s end position is last vertex", r.name); + test(poly_end[0] == sum0 && poly_end[1] == sum1, msg); + snprintf(msg, sizeof(msg), "2f %s a vertex sample per block", r.name); + test(poly_nv >= 2, msg); + if (r.path_stop) { + snprintf(msg, sizeof(msg), "2f %s path-stop joint P_issued <= 1", r.name); + test(poly_vp[0] <= 1, msg); + } else { + snprintf(msg, sizeof(msg), "2f %s collinear joint does not rest", r.name); + test(poly_vp[0] > 1, msg); + } + + // Interpolator must match the oracle within a few DDA ticks (log2 / + // one-step slack). Compare issued step counts and the joint P sample. + test(ref_env && ref_plr, "2f oracle envelope and P<=R hold"); + snprintf(msg, sizeof(msg), "2f %s interpolator issues match oracle", + r.name); + test(poly_issued[0] == ref_issued[0] && poly_issued[1] == ref_issued[1], + msg); + snprintf(msg, sizeof(msg), "2f %s joint P within log2 slack of oracle", + r.name); + uint32_t dp = (poly_vp[0] > ref_vp[0]) ? poly_vp[0] - ref_vp[0] + : ref_vp[0] - poly_vp[0]; + test(dp <= 2, msg); + + // After the joint the DDA binder is the longest axis of block 1. + int master1 = Remaining::longest_axis(d1, ticks_eq, 2); + snprintf(msg, sizeof(msg), "2f %s master switches to %d after joint", + r.name, r.master_after); + test(master1 == r.master_after, msg); + test(master1 == poly.master, "2f interpolator master matches oracle"); + + printf("F2f %s: joint_P poly=%u ref=%u end=(%d,%d) nv=%d\n", r.name, + poly_vp[0], ref_vp[0], poly_end[0], poly_end[1], poly_nv); + (void)ref_slack; + (void)poly_slack; + (void)ref_nv; + } + + // Plot: the 90deg L (0,0)->(5,0)->(5,5), the realized path on the chords + // with the corner (vertex) marked and the per-axis speed over time. + { + int32_t d0[2] = {5, 0}; + int32_t d1[2] = {0, 5}; + Remaining rem(2, 2); + rem.set_block(0, d0); + rem.set_block(1, d1); + LinearPoly poly(&rem, ticks_eq, accel); + NaxisPlot plot; + plot.start_plot("f2f", "FasNAxis F2f two-block L (5,0)+(0,5)", 2); + plot.poly_point(0.0, 0.0); + plot.poly_point(5.0, 0.0); + plot.poly_point(5.0, 5.0); + plot.poly_done(); + int32_t pos[2] = {0, 0}; + { + double z[2] = {0.0, 0.0}; + plot.row(0.0, 0.0, 0.0, 0.0, z, z, z, z); + } + while (!poly.done()) { + int step_out[2]; + uint32_t ticks_issued = poly.step(step_out); + pos[0] += step_out[0]; + pos[1] += step_out[1]; + double t = (double)poly.total_ticks / NAXIS_PLOT_TICKS_PER_S; + double v = NAXIS_PLOT_TICKS_PER_S / (double)ticks_issued; + double speed[2] = {poly.master == 0 ? v : 0.0, + poly.master == 1 ? v : 0.0}; + double Pcol[2] = {poly.master == 0 ? (double)poly.P : 0.0, + poly.master == 1 ? (double)poly.P : 0.0}; + double Rcol[2] = {poly.master == 0 ? (double)poly.R : 0.0, + poly.master == 1 ? (double)poly.R : 0.0}; + double tickscol[2] = {poly.master == 0 ? (double)ticks_issued : 0.0, + poly.master == 1 ? (double)ticks_issued : 0.0}; + plot.row(t, (double)pos[0], (double)pos[1], 0.0, speed, Pcol, Rcol, + tickscol); + } + plot.finish_plot(); + test(plot.is_open() == false, "2f plot closed"); + printf("F2f two-block L plot written: test_26_f2f.gnuplot\n"); + } + printf("F2f two-block Linear path-stop/collinear/reversal green\n"); +} + +void f2h_nblock_vs_f20() { + // Step 2h: the production N-block interpolator (LinearPoly) must match the + // globally fastest Linear reference (NaxisRefLinear) on F20, within a 2-step + // log2 band. Same committed blocks (shared build_f20_blocks, seed 26), so the + // two walks run tick-for-tick over the same polyline. A faster track that + // leaves the chord or skips a vertex is not Linear. + const uint32_t accel = 2000; + const uint32_t ticks[2] = {4000, 8000}; + int32_t blocks[512][2]; + int32_t sum[2]; + int n_blocks = build_f20_blocks(blocks, sum); + test(n_blocks >= 200, "2h several hundred waypoints"); + + // Oracle walk (truth). + Remaining ref_rem(2, n_blocks); + for (int b = 0; b < n_blocks; b++) { + ref_rem.set_block(b, blocks[b]); + } + ref_rem.horizon = 0xFFFFFFFFU; + int32_t ref_end[2], ref_issued[2]; + bool ref_env = true, ref_plr = true; + uint32_t ref_vp[512]; + int ref_nv = 0; + uint32_t ref_slack = 0; + int32_t ref_vpos[1024]; + NaxisPlot refplot; + refplot.start_plot("f20_lin", "FasNAxis F2h interpolator vs F20 reference", + 2); + refplot.poly_point(0.0, 0.0); + { + int32_t wx = 0, wy = 0; + for (int b = 0; b < n_blocks; b++) { + wx += blocks[b][0]; + wy += blocks[b][1]; + refplot.poly_point((double)wx, (double)wy); + } + } + refplot.poly_done(); + ref_walk_polyline(&ref_rem, ticks, accel, ref_end, ref_issued, &ref_env, + &ref_plr, ref_vp, &ref_nv, 512, &refplot, &ref_slack, + ref_vpos); + refplot.finish_plot(); + + // Interpolator walk (the production core under test). + Remaining poly_rem(2, n_blocks); + for (int b = 0; b < n_blocks; b++) { + poly_rem.set_block(b, blocks[b]); + } + poly_rem.horizon = 0xFFFFFFFFU; + LinearPoly poly(&poly_rem, ticks, accel); + int32_t poly_end[2], poly_issued[2]; + bool poly_env = true, poly_plr = true; + uint32_t poly_vp[512]; + int poly_nv = 0; + uint32_t poly_slack = 0; + int32_t poly_vpos[1024]; + walk_polyline(poly, &poly_rem, ticks, accel, poly_end, poly_issued, &poly_env, + &poly_plr, poly_vp, &poly_nv, 512, NULL, &poly_slack, + poly_vpos); + + test(poly_env, "2h interpolator envelope ticks >= ticks_i_cfg"); + test(poly_plr, "2h interpolator law P_issued <= R"); + test(poly_slack <= 2, + "2h interpolator reconstructed P within 2-step log2 band"); + test(poly_issued[0] == sum[0] && poly_issued[1] == sum[1], + "2h interpolator issued |steps| == polyline"); + test(poly_end[0] == sum[0] && poly_end[1] == sum[1], + "2h interpolator end is last vertex"); + test(poly_nv == ref_nv, "2h interpolator vertex count matches oracle"); + + // Same vertices, in the same order, as the oracle. + for (int i = 0; i < poly_nv; i++) { + test(poly_vpos[2 * i] == ref_vpos[2 * i] && + poly_vpos[2 * i + 1] == ref_vpos[2 * i + 1], + "2h interpolator vertex i hits the same waypoint as the oracle"); + uint32_t dvp = (poly_vp[i] > ref_vp[i]) ? poly_vp[i] - ref_vp[i] + : ref_vp[i] - poly_vp[i]; + test(dvp <= 2, "2h interpolator joint P within 2-step log2 of oracle"); + } + + // Both kinds of joints must be exercised, matching the oracle counts. + int ref_stop = 0, poly_stop = 0; + for (int i = 0; i < ref_nv - 1; i++) { + if (ref_vp[i] <= 1) { + ref_stop++; + } + if (poly_vp[i] <= 1) { + poly_stop++; + } + } + int ref_cruise = (ref_nv > 0) ? (ref_nv - 1 - ref_stop) : 0; + test(ref_stop >= 1, "2h oracle has a Linear path-stop joint"); + test(ref_cruise > 0, "2h oracle has a cruise joint"); + test(poly_stop == ref_stop, "2h interpolator path-stop joints match oracle"); + + printf( + "2h interpolator vs F20 reference: blocks=%d vertices=%d " + "stop_joints ref=%d poly=%d end=(%d,%d)\n", + n_blocks, poly_nv, ref_stop, poly_stop, poly_end[0], poly_end[1]); + printf("F2h N-block interpolator matches F20 reference green\n"); +} + +// Step 3b (whitepaper section 12.4 item 3b): stoppability from the command +// trace. Ignore the planner's P / R fields. From the issued periods and the +// leftover polyline, calculate_ramp_steps(current_ticks) <= remaining on every +// axis at every sample: the plan can still stop. The oracle is NaxisRefLinear +// (the Linear reference of Step 2ref); P is reconstructed from issued periods +// and compared to the per-axis remaining scan (Remaining::remaining), never to +// the walker's P / R fields. +// +// Three named fixtures: +// F1 1 axis, 10000 rest-to-rest: coasts to P_coast, P_issued <= R. +// F5 square 1600, Linear: P -> 0 at each 90deg corner (path-stop), decel +// starts on the side, P_issued <= R. +// F10 100 x 100-step collinear micro-segments: R sees through (no per- +// segment rest), coasts to P_coast, P_issued <= R. +// +// Optional model mutations: +// - FAS_NAXIS_NO_CROSS_BLOCK_R (remaining.h linear_remaining): R is one +// block, not the run to the next hard stop. F10's joints rest (P -> 0 +// per block) and the cruise check fails. +// - FAS_NAXIS_NO_REBIND (remaining.h): binder_axis ignores ticks. F5/F10 +// (equal ticks) are unaffected, but the rebind neighbourhood of Step 2b +// fails, so the model is wrong. +// - FAS_NAXIS_NO_REST_CAP (ramp_law.h): ignore remaining-to-stop. A short +// open path no longer brakes (peak P is not < R); the F1/F5/F10 stoppable +// plan would over-run. +// +// Vertex snap: F5's corners are samples (the walker emits a vertex per block); +// a planner that does not snap would miss (1600,0) etc. +struct StoppableResult { + uint32_t peak_p; + uint32_t joint_p[512]; + int n_joint; + int n_stop; + int n_cruise; + bool p_le_r; +}; + +// Walk a NaxisRefLinear oracle and check per-axis stoppability: at every +// moving sample, the reconstructed P_issued must be <= the remaining scan on +// every axis (the plan can still stop). Joint P samples (last moving P of each +// block) classify path-stop (P -> 0) vs collinear cruise (P carries). +static void check_stoppable(Remaining* rem, const uint32_t* ticks, + uint32_t accel, StoppableResult* out, + const char* name) { + NaxisRefLinear ref(rem, ticks, accel); + out->peak_p = 0; + out->n_joint = 0; + out->n_stop = 0; + out->n_cruise = 0; + out->p_le_r = true; + int32_t pos[2] = {0, 0}; + uint32_t last_moving_p = 0; + while (!ref.done()) { + int step_out[2] = {0, 0}; + uint32_t ticks_issued = ref.step(step_out); + if (ticks_issued == 0) { + continue; // finished transition, not a command + } + pos[0] += step_out[0]; + pos[1] += step_out[1]; + RampMap map(ref.ticks_law, accel); + uint32_t p_issued = map.calculate_ramp_steps(ticks_issued); + bool rest = (ticks_issued == ref.ticks_law); + if (ticks_issued > 0) { + last_moving_p = p_issued; + } + if (!rest) { + // Per-axis stoppability: the issued period must still allow a stop + // within the remaining scan on every axis. An idle axis has P = 0. + for (int i = 0; i < ref.n_axes; i++) { + uint32_t p_i = (step_out[i] != 0) ? p_issued : 0; + int32_t R_i = rem->remaining(i, ref.block); + // calculate_ramp_steps o calculate_ticks may land up to two steps + // high (log2 inverse, section 12.4 slack), as in walk_polyline. + if (R_i < 0 || p_i > (uint32_t)R_i + 2) { + out->p_le_r = false; + printf("DBG viol %s axis=%d p=%u R=%d block=%d ticks=%u\n", name, i, + p_i, R_i, ref.block, ticks_issued); + } + } + if (p_issued > out->peak_p) { + out->peak_p = p_issued; + } + } + if (ref.dda.done()) { + if (out->n_joint < 512) { + out->joint_p[out->n_joint] = last_moving_p; + } + out->n_joint++; + last_moving_p = 0; + } + } + for (int i = 0; i < out->n_joint; i++) { + if (out->joint_p[i] <= 1) { + out->n_stop++; + } else { + out->n_cruise++; + } + } +} + +void f3b_stoppability() { + const uint32_t accel = 2000; + const uint32_t ticks_cfg = 4000; + uint32_t P_coast = RampMap(ticks_cfg, accel).P_coast(); + test(P_coast >= 3900 && P_coast <= 4100, "F3b P_coast ~ 4000"); + + // --- F1: 1 axis, 10000 rest-to-rest. Coasts to P_coast, P_issued <= R. --- + { + Remaining rem(1, 1); + int32_t b0[1] = {10000}; + rem.set_block(0, b0); + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + StoppableResult r; + check_stoppable(&rem, ticks, accel, &r, "F1"); + test(r.p_le_r, "F3b F1 P_issued <= R on every sample (stoppable)"); + test(r.peak_p >= P_coast - P_coast / 100 && r.peak_p <= P_coast, + "F3b F1 coasts to P_coast (10000/2 > P_stop)"); + printf("F3b F1 1-axis 10000: peak_P=%u P_coast=%u stoppable\n", r.peak_p, + P_coast); + } + + // --- F5: square 1600, Linear. P -> 0 at each 90deg corner (path-stop); + // --- decel starts on the side; P_issued <= R. Each side is 1600 < 2*P_coast, + // --- so no side coasts (peak P < P_coast). --- + { + Remaining rem(2, 4); + int32_t b0[2] = {0, 1600}; + int32_t b1[2] = {1600, 0}; + int32_t b2[2] = {0, -1600}; + int32_t b3[2] = {-1600, 0}; + rem.set_block(0, b0); + rem.set_block(1, b1); + rem.set_block(2, b2); + rem.set_block(3, b3); + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + StoppableResult r; + check_stoppable(&rem, ticks, accel, &r, "F5"); + test(r.p_le_r, "F3b F5 P_issued <= R on every sample (stoppable)"); + test(r.n_stop >= 4, "F3b F5 P -> 0 at each 90deg corner (path-stop)"); + test(r.peak_p < P_coast, + "F3b F5 each side too short to coast (decel on side)"); + printf("F3b F5 square 1600: peak_P=%u stop_joints=%d\n", r.peak_p, + r.n_stop); + } + + // --- F10: 100 x 100-step collinear micro-segments. R sees through (no + // --- per-segment rest), coasts to P_coast, P_issued <= R. The collinear + // --- joints cruise (P > 1); the cross-block-R mutation makes them rest. --- + { + const int N = 100; + Remaining rem(2, N); + for (int i = 0; i < N; i++) { + int32_t blk[2] = {100, 100}; + rem.set_block(i, blk); + } + uint32_t ticks[2] = {ticks_cfg, ticks_cfg}; + StoppableResult r; + check_stoppable(&rem, ticks, accel, &r, "F10"); + test(r.p_le_r, "F3b F10 P_issued <= R on every sample (stoppable)"); + test(r.peak_p >= P_coast - P_coast / 100 && r.peak_p <= P_coast, + "F3b F10 coasts to P_coast (R sees through)"); + test(r.n_cruise >= 1, + "F3b F10 collinear joints do not rest (R sees through)"); + printf("F3b F10 100x100 collinear: peak_P=%u cruise_joints=%d\n", r.peak_p, + r.n_cruise); + } + printf("F3b stoppability from the command trace green\n"); +} + +// F4 — SimPort addQueueEntry contract (whitepaper section 4.1 / 4.1.1 / +// 4.4.1). A self-contained section that exercises the duck-typed StepperQueue +// stand-in without FasNAxis planning: the feeder talks to addQueueEntry() only. +// +// - append on an empty queue: isQueueEmpty() was true before, no underrun +// - kick-off addQueueEntry(NULL, true); empty queue afterwards is an +// underrun, not before +// - a pause (steps = 0) uses the caller's count_up, no implicit flip; a +// reverting pause (count_up = !old) simply leaves the port in the new DIR +// - pd_test default: a reversing step enqueues with no injected pause +// - inject hook: a reversing step injects a before-pause (old DIR) then an +// after-pause (new DIR) that flips queue_end, so a naive retry would XOR +// back; the following step sees no further injection +// - drain advances position (signed) and the simulated clock +// - isRampGeneratorActive() is false unless the test forces it +void f4_sim_port() { + const uint16_t max_ticks = 80; + SimPort port(max_ticks); + test(port.isQueueEmpty(), "F4: fresh port queue empty"); + test(port.isRampGeneratorActive() == false, + "F4: ramp generator idle by default"); + + // Append on an empty queue: isQueueEmpty() was true before, not underrun. + struct stepper_command_s c = {4000, 3, true}; + test(port.addQueueEntry(&c, false) == AQE_OK, "F4: append returns OK"); + test(port.isQueueEmpty() == false, "F4: queue populated after append"); + test(port.hasUnderrun() == false, "F4: empty-prefill is not underrun"); + + // Kick-off starts the queue. After that, an empty queue is an underrun. + test(port.addQueueEntry(NULL, true) == AQE_OK, "F4: kick-off returns OK"); + test(port.isRunning(), "F4: port running after kick-off"); + port.drain(); + test(port.isQueueEmpty(), "F4: queue drained"); + test(port.hasUnderrun(), "F4: empty after kick-off with motion is underrun"); + + // Kick-off on an empty, un-kicked-off queue is an error. + SimPort empty(max_ticks); + test(empty.addQueueEntry(NULL, true) == AQE_ERROR_EMPTY_QUEUE_TO_START, + "F4: kick-off on empty queue is an error"); + + // A pause (steps = 0) uses the count_up the caller passes: no implicit flip. + SimPort pause(max_ticks); + struct stepper_command_s p0 = {4000, 0, false}; + test(pause.addQueueEntry(&p0, false) == AQE_OK, "F4: pause enqueues"); + test(pause.queueEndCountUp() == false, "F4: pause keeps caller count_up"); + + // A reverting pause (count_up = !old) leaves the port in the new DIR without + // any injected pause: this is pd_test's revert. + SimPort revert(max_ticks); + struct stepper_command_s base = {4000, 1, true}; + test(revert.addQueueEntry(&base, false) == AQE_OK, "F4: base step enqueues"); + test(revert.queueEndCountUp() == true, "F4: base step is count_up"); + struct stepper_command_s rev = {4000, 0, false}; // revert to old DIR + test(revert.addQueueEntry(&rev, false) == AQE_OK, "F4: reverting pause OK"); + test(revert.queueEndCountUp() == false, + "F4: reverting pause flips to old DIR"); + + // pd_test default: a reversing step enqueues with no injected pause. + SimPort def(max_ticks); + struct stepper_command_s step_up = {4000, 1, true}; + test(def.addQueueEntry(&step_up, false) == AQE_OK, "F4: first step enqueues"); + struct stepper_command_s step_dn = {4000, 1, false}; + AqeResultCode r = def.addQueueEntry(&step_dn, false); + test(r == AQE_OK, "F4: default reversing step enqueues, no inject"); + test(def.injectedPauseTicks() == 0, "F4: no injected pause on default"); + test(def.queueEndCountUp() == false, "F4: default reversing step new DIR"); + + // Inject hook: a reversing step injects a before-pause (old DIR) then an + // after-pause (new DIR, flips queue_end); a naive retry would XOR back. + SimPort inj(max_ticks); + inj.setInjectMode(SimPort::InjectDirPauses); + inj.setInjectTicks(8000); + struct stepper_command_s s_up = {4000, 1, true}; + test(inj.addQueueEntry(&s_up, false) == AQE_OK, "F4: inject first step OK"); + struct stepper_command_s s_dn = {4000, 1, false}; + AqeResultCode r1 = inj.addQueueEntry(&s_dn, false); + test(r1 == AQE_DIR_CHANGE_PAUSE_INJECTED, "F4: inject before-pause injected"); + test(inj.injectedPauseTicks() == 8000, "F4: injected ticks recorded"); + test(inj.queueEndCountUp() == true, "F4: before-pause keeps old DIR"); + AqeResultCode r2 = inj.addQueueEntry(&s_dn, false); + test(r2 == AQE_DIR_CHANGE_PAUSE_INJECTED, "F4: inject after-pause injected"); + test(inj.queueEndCountUp() == false, + "F4: after-pause flips queue_end to new DIR"); + AqeResultCode r3 = inj.addQueueEntry(&s_dn, false); + test(r3 == AQE_OK, "F4: reversing step enqueues once sequence done"); + test(inj.queueEndCountUp() == false, "F4: step leaves port in new DIR"); + + // A following reversing step sees no further injection until it reverses: + // a step continuing in the same DIR does not re-enter the inject sequence. + SimPort inj2(max_ticks); + inj2.setInjectMode(SimPort::InjectDirPauses); + inj2.setInjectTicks(8000); + struct stepper_command_s a_up = {4000, 1, true}; + test(inj2.addQueueEntry(&a_up, false) == AQE_OK, "F4: inj2 first step OK"); + struct stepper_command_s a_dn = {4000, 1, false}; + inj2.addQueueEntry(&a_dn, false); + inj2.addQueueEntry(&a_dn, false); + test(inj2.queueEndCountUp() == false, "F4: inj2 reversed once"); + struct stepper_command_s a_dn2 = {4000, 1, false}; + AqeResultCode r4 = inj2.addQueueEntry(&a_dn2, false); + test(r4 == AQE_OK, "F4: same-direction step has no further inject"); + test(inj2.injectedPauseTicks() == 0, "F4: no inject on a non-reversing step"); + + // Error: ticks below max speed is a planner bug, not a retry. + SimPort err(max_ticks); + struct stepper_command_s too_low = {40, 3, true}; + test(err.addQueueEntry(&too_low, false) == AQE_ERROR_TICKS_TOO_LOW, + "F4: ticks below max speed is ErrorTicksTooLow"); + + // drain() advances position (signed by count_up) and the simulated clock. + SimPort drain(max_ticks); + drain.addQueueEntry(&s_up, false); + drain.addQueueEntry(&step_dn, false); + drain.addQueueEntry(NULL, true); + test(drain.position() == 0, "F4: net position zero before drain"); + drain.drain(); + test(drain.clock() == (4000u + 4000u), "F4: clock sums both commands"); + test(drain.position() == 0, "F4: +1 then -1 nets to zero"); + + // A forced ramp generator is visible through isRampGeneratorActive(). + SimPort rg(max_ticks); + rg.setRampGeneratorActive(true); + test(rg.isRampGeneratorActive(), "F4: forced ramp generator active"); + + printf("F4 SimPort addQueueEntry contract green\n"); +} + +// Step 6: Linear interpolator, one committed block, through SimPort (F1, F2, +// F3, F17). FasNAxis commits one rest-to-rest segment, prefills the queues with +// start=false, then kicks off each axis (addQueueEntry(NULL, true)); later +// commands use start=true. The test drains one command per axis per iteration +// so the axes stay in lockstep. Checks: issued step sums == target, P <= R on +// every committed sample, the realized path stays on the commanded chord +// (section 12.4 rounding box), the first fill of an empty queue is not +// underrun, and the run completes without underrun. Plots: +// test_26_f1_lin.gnuplot, test_26_f2.gnuplot, test_26_f3_lin.gnuplot. +struct SimSegmentResult { + int64_t issued[2]; + int64_t bind_moves; + int64_t both_moves; + uint32_t max_P; + uint32_t min_R; + uint32_t max_ticks; + double max_dev; + bool p_le_r; + bool underrun; + bool first_fill_underrun; + int64_t n_iter; + PumpStatus first_pump; +}; + +static void run_linear_segment( + SimPort& px, SimPort& py, + FasNAxis<2, 64, SimPort, TestStepperMotionEngine>& path, + const char* fixture, const char* title, int32_t tx, int32_t ty, + bool do_plot, SimSegmentResult* res) { + res->issued[0] = 0; + res->issued[1] = 0; + res->bind_moves = 0; + res->both_moves = 0; + res->max_P = 0; + res->min_R = 0xFFFFFFFFu; + res->max_ticks = 0; + res->max_dev = 0.0; + res->p_le_r = true; + res->underrun = false; + res->first_fill_underrun = false; + res->n_iter = 0; + + NaxisPlot plot; + if (do_plot) { + plot.start_plot(fixture, title, 2); + plot.poly_point((double)px.position(), (double)py.position()); + plot.poly_point((double)tx, (double)ty); + plot.poly_done(); + } + + int32_t target[2] = {tx, ty}; + path.addWaypoint(target); + path.endPath(); + res->first_pump = path.pump(); + res->first_fill_underrun = path.hasUnderrun(); + + int master = path.masterAxis(); + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + res->issued[0] += s0; + res->issued[1] += s1; + int64_t s_bind = (master == 0) ? s0 : s1; + int64_t s_slave = (master == 0) ? s1 : s0; + if (s_bind != 0) { + res->bind_moves += s_bind; + if (s_slave == s_bind) { + res->both_moves += s_bind; + } + } + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + uint32_t ticks = path.lastTicks(); + if (P > res->max_P) { + res->max_P = P; + } + if (R < res->min_R) { + res->min_R = R; + } + if (ticks > res->max_ticks) { + res->max_ticks = ticks; + } + if (P > R) { + res->p_le_r = false; + } + double x = (double)px.position(); + double y = (double)py.position(); + double nx = -(double)ty; + double ny = (double)tx; + double nlen = sqrt(nx * nx + ny * ny); + double dev = + nlen > 0.0 ? fabs(nx * x + ny * y) / nlen : sqrt(x * x + y * y); + if (dev > res->max_dev) { + res->max_dev = dev; + } + if (do_plot && (res->n_iter % 4 == 0)) { + double t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + double v = ticks > 0 ? NAXIS_PLOT_TICKS_PER_S / (double)ticks : 0.0; + double speed[2] = {v, v}; + double Pcol[2] = {(double)P, (double)P}; + double Rcol[2] = {(double)R, (double)R}; + double tcol[2] = {(double)ticks, (double)ticks}; + plot.row(t, x, y, dev, speed, Pcol, Rcol, tcol); + } + res->n_iter++; + path.pump(); + } + res->underrun = path.hasUnderrun(); + if (do_plot) { + plot.finish_plot(); + } +} + +void f6_linear_sim() { + // F1: one long axis, idle second axis (1-axis fixture run through the queue + // path). 10 000 steps at ticks_cfg 4000 / accel 2000 (section 14.1). + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F6 F1 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F6 F1 addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + SimSegmentResult res; + run_linear_segment(px, py, path, "f1_lin", + "FasNAxis F1 Linear (10000,0) via SimPort", 10000, 0, + true, &res); + test(res.issued[0] == 10000, "F6 F1 issued X == 10000"); + test(res.issued[1] == 0, "F6 F1 idle Y issues no steps"); + test(res.p_le_r, "F6 F1 P <= R on every sample"); + test(res.underrun == false, "F6 F1 no underrun"); + test(res.first_fill_underrun == false, "F6 F17 first fill not underrun"); + test(res.first_pump == PumpStatus::Running, + "F6 F1 first pump returns Running"); + test(px.position() == 10000 && py.position() == 0, + "F6 F1 realized end == target"); + printf( + "F6 F1 (10000,0): issued=(%lld,%lld) peak_P=%u max_ticks=%u " + "iter=%lld\n", + (long long)res.issued[0], (long long)res.issued[1], res.max_P, + res.max_ticks, (long long)res.n_iter); + printf("F1 Linear SimPort plot written: test_26_f1_lin.gnuplot\n"); + } + + // F2: 45 degree line, equal limits. X binds; every slice moves both axes by + // the same step count, so the path stays on the chord (a batch included). + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + SimSegmentResult res; + run_linear_segment(px, py, path, "f2", "FasNAxis F2 Linear 45 deg", 1600, + 1600, true, &res); + test(res.issued[0] == 1600 && res.issued[1] == 1600, + "F6 F2 both axes issue 1600"); + test(res.bind_moves == 1600 && res.both_moves == res.bind_moves, + "F6 F2 equal |delta| every slice on a 45 deg line"); + test(res.max_dev <= 0.5 * sqrt(2.0) + 1e-9, + "F6 F2 path stays on the chord (0.5 sqrt n box)"); + test(res.p_le_r, "F6 F2 P <= R on every sample"); + test(res.underrun == false, "F6 F2 no underrun"); + test(px.position() == 1600 && py.position() == 1600, + "F6 F2 realized end == target"); + printf("F6 F2 (1600,1600): issued=(%lld,%lld) max_dev=%.3f peak_P=%u\n", + (long long)res.issued[0], (long long)res.issued[1], res.max_dev, + res.max_P); + printf("F2 Linear SimPort plot written: test_26_f2.gnuplot\n"); + } + + // F3: (10000, 100). X binds; Y is a slow slave well below its own ramp and + // the realized path stays on the chord. Both endpoints (vertices) are hit. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + SimSegmentResult res; + run_linear_segment(px, py, path, "f3_lin", "FasNAxis F3 Linear (10000,100)", + 10000, 100, true, &res); + test(path.masterAxis() == 0, "F6 F3 X is the DDA master"); + test(res.issued[0] == 10000 && res.issued[1] == 100, + "F6 F3 issued == (10000,100)"); + test(res.max_dev <= 0.5 * sqrt(2.0) + 1e-9, + "F6 F3 path stays on the chord (0.5 sqrt n box)"); + test(res.p_le_r, "F6 F3 P <= R on every sample"); + test(res.underrun == false, "F6 F3 no underrun"); + test(px.position() == 10000 && py.position() == 100, + "F6 F3 vertex hit: realized end == target"); + printf( + "F6 F3 (10000,100): issued=(%lld,%lld) master=%d max_dev=%.3f " + "peak_P=%u\n", + (long long)res.issued[0], (long long)res.issued[1], path.masterAxis(), + res.max_dev, res.max_P); + printf("F3 Linear SimPort plot written: test_26_f3_lin.gnuplot\n"); + } + + printf("F6/F17 Linear interpolator through SimPort green\n"); +} + +// One drained SimPort pair. A master period above 65535 is split into a +// half-period step entry (s0/s1 nonzero on the master) plus pause entries +// (s0 == s1 == 0) covering the remainder (section 4.2 / 9.3). +struct ProdTraceEntry { + uint32_t t; + int s0; + int s1; +}; + +struct PolySimResult { + int64_t issued[2]; + int32_t end_pos[2]; + uint32_t vertex_p[256]; + int32_t vertex_pos[512]; + int n_vertex; + uint32_t max_moving_p; + uint32_t min_moving_ticks; + bool envelope_ok; + bool p_le_r_ok; + bool trace_match; + bool underrun; + bool first_fill_underrun; + uint64_t total_ticks; + int n_cmd; + int n_entry; +}; + +// Step 7: drive a committed polyline through FasNAxis/SimPort and compare the +// produced Linear track to the NaxisRefLinear oracle (Step 2ref). Phase 1 +// drains the real queue into a trace; phase 2 coalesces the 65535 splits back +// to full periods. One production command may be several master steps at one +// period (section 4.3.1); it matches the sum of that many reference steps. +// Envelope, issued |steps| == |delta|, and joint P are checked from the +// per-step period, never from planner P fields. Vertices are located by the +// oracle's cumulative step position. +template +static void walk_prod_polyline( + SimPort& px, SimPort& py, + FasNAxis<2, HZ, SimPort, TestStepperMotionEngine>& path, + const int32_t (*verts)[2], int n_verts, const uint32_t* ticks, + uint32_t t_law, uint32_t accel, bool do_plot, const char* fixture, + const char* title, PolySimResult* res) { + static ProdTraceEntry e[70000]; + int n_blocks = n_verts - 1; + res->issued[0] = 0; + res->issued[1] = 0; + res->end_pos[0] = 0; + res->end_pos[1] = 0; + res->n_vertex = 0; + res->max_moving_p = 0; + res->min_moving_ticks = 0xFFFFFFFFu; + res->envelope_ok = true; + res->p_le_r_ok = true; + res->trace_match = true; + res->underrun = false; + res->first_fill_underrun = false; + res->total_ticks = 0; + res->n_cmd = 0; + res->n_entry = 0; + + Remaining rem(2, n_blocks); + for (int b = 0; b < n_blocks; b++) { + int32_t d[2]; + d[0] = verts[b + 1][0] - verts[b][0]; + d[1] = verts[b + 1][1] - verts[b][1]; + rem.set_block(b, d); + } + + NaxisPlot plot; + if (do_plot) { + plot.start_plot(fixture, title, 2); + for (int v = 0; v < n_verts; v++) { + plot.poly_point((double)verts[v][0], (double)verts[v][1]); + } + plot.poly_done(); + } + + for (int v = 1; v < n_verts; v++) { + int32_t p[2] = {verts[v][0], verts[v][1]}; + path.addWaypoint(p); + } + path.endPath(); + + path.pump(); + res->first_fill_underrun = path.hasUnderrun(); + if (path.performedRampUp() > path.remainingToStop()) { + res->p_le_r_ok = false; + } + while (path.isBusy()) { + int64_t s0 = 0; + int64_t s1 = 0; + bool up0 = true; + bool up1 = true; + uint32_t t0 = px.drain_one(&s0, &up0); + py.drain_one(&s1, &up1); + if (res->n_entry < 70000) { + e[res->n_entry].t = t0; + e[res->n_entry].s0 = (int)(s0 == 0 ? 0 : (up0 ? s0 : -s0)); + e[res->n_entry].s1 = (int)(s1 == 0 ? 0 : (up1 ? s1 : -s1)); + res->n_entry++; + } + res->total_ticks += t0; + path.pump(); + if (path.performedRampUp() > path.remainingToStop()) { + res->p_le_r_ok = false; + } + } + res->underrun = path.hasUnderrun(); + + RampMap map(t_law, accel); + NaxisRefLinear ref(&rem, ticks, accel); + int32_t pos[2] = {0, 0}; + int next_vertex = 1; + uint32_t last_moving_p = 0; + int i = 0; + // EMA-smoothed per-axis realized speed (see walk_polyline): a per-command + // pulse rate is noisy, and the old `rest = (T == t_law)` zeroed every coast. + const int kPlotStride = 8; + const double kSpeedTau_s = 0.02; + int sample_n = 0; + int32_t last_pos[2] = {0, 0}; + uint64_t last_ticks = 0; + double ema_v[2] = {0.0, 0.0}; + bool have_sample = true; + while (res->trace_match && i < res->n_entry) { + while (i < res->n_entry && e[i].s0 == 0 && e[i].s1 == 0) { + i++; + } + if (i >= res->n_entry) { + break; + } + uint32_t T_prod = e[i].t; + int ps0 = e[i].s0; + int ps1 = e[i].s1; + i++; + while (i < res->n_entry && e[i].s0 == 0 && e[i].s1 == 0) { + T_prod += e[i].t; + i++; + } + uint32_t T_acc = 0; + int s_acc0 = 0; + int s_acc1 = 0; + bool matched = false; + for (int guard = 0; guard < 256 && !ref.done(); guard++) { + int os[2]; + uint32_t T_ref = ref.step(os); + T_acc += T_ref; + s_acc0 += os[0]; + s_acc1 += os[1]; + pos[0] += os[0]; + pos[1] += os[1]; + uint32_t p_issued = map.calculate_ramp_steps(T_ref); + if (os[0] != 0 || os[1] != 0) { + last_moving_p = p_issued; + if (p_issued > res->max_moving_p) { + res->max_moving_p = p_issued; + } + if (T_ref < res->min_moving_ticks) { + res->min_moving_ticks = T_ref; + } + } + if (os[0] != 0 && T_ref + 1 < ticks[0]) { + res->envelope_ok = false; + } + if (os[1] != 0 && T_ref + 1 < ticks[1]) { + res->envelope_ok = false; + } + if (do_plot) { + uint64_t now_ticks = ref.total_ticks; + double dt = (double)(now_ticks - last_ticks) / NAXIS_PLOT_TICKS_PER_S; + if (dt > 0.0) { + double alpha = dt / (kSpeedTau_s + dt); + ema_v[0] += alpha * ((double)(pos[0] - last_pos[0]) / dt - ema_v[0]); + ema_v[1] += alpha * ((double)(pos[1] - last_pos[1]) / dt - ema_v[1]); + } + last_pos[0] = pos[0]; + last_pos[1] = pos[1]; + last_ticks = now_ticks; + if ((sample_n % kPlotStride) == 0 && have_sample) { + double speed[2] = {ema_v[0], ema_v[1]}; + double Pcol[2] = {(double)p_issued, (double)p_issued}; + double Rcol[2] = {(double)ref.R, (double)ref.R}; + double tcol[2] = {(double)T_ref, (double)T_ref}; + plot.row((double)now_ticks / NAXIS_PLOT_TICKS_PER_S, (double)pos[0], + (double)pos[1], 0.0, speed, Pcol, Rcol, tcol); + } + } + sample_n++; + if (ref.dda.done()) { + if (next_vertex < n_verts && pos[0] == verts[next_vertex][0] && + pos[1] == verts[next_vertex][1]) { + if (res->n_vertex < 256) { + res->vertex_p[res->n_vertex] = last_moving_p; + res->vertex_pos[2 * res->n_vertex] = pos[0]; + res->vertex_pos[2 * res->n_vertex + 1] = pos[1]; + } + res->n_vertex++; + next_vertex++; + } + } + if (T_acc == T_prod && s_acc0 == ps0 && s_acc1 == ps1) { + matched = true; + break; + } + if (T_acc > T_prod) { + break; + } + } + if (!matched) { + res->trace_match = false; + } + res->issued[0] += ps0; + res->issued[1] += ps1; + res->n_cmd++; + } + if (!ref.done()) { + res->trace_match = false; + } + res->end_pos[0] = pos[0]; + res->end_pos[1] = pos[1]; + if (do_plot) { + plot.finish_plot(); + } +} + +// Step 10: the gnuplot file NaxisPlot wrote is the plot. Confirm the bytes the +// helper promises are actually on disk: the data heredoc opener, its closer, +// and the multiplot layout. A missing one means the helper drifted. +static bool gnuplot_has(const char* path, const char* needle) { + FILE* f = fopen(path, "r"); + if (f == NULL) { + return false; + } + char buf[4096]; + size_t n; + bool found = false; + while ((n = fread(buf, 1, sizeof(buf), f)) > 0) { + if (strstr(buf, needle) != NULL) { + found = true; + break; + } + } + fclose(f); + return found; +} + +// Max value of column `col` (1-based) among the data rows whose column 2 equals +// `x` (within 0.5). Used to inspect a plotted speed at a known position, e.g. +// the F12 reversal vertex. +static double gnuplot_col_max_at_x(const char* path, double x, int col) { + FILE* f = fopen(path, "r"); + if (f == NULL) { + return 0.0; + } + char line[512]; + bool in_data = false; + double best = 0.0; + while (fgets(line, sizeof(line), f) != NULL) { + if (!in_data) { + if (strstr(line, "$data <= col && fabs(c[1] - x) < 0.5) { + double v = fabs(c[col - 1]); + if (v > best) { + best = v; + } + } + } + fclose(f); + return best; +} + +// Step 7 (whitepaper section 8): Linear lookahead across blocks through the +// real feeder. F5 pins path-stop corners (P -> 0, decel starts on the side), +// F9/F18 pin the time-law rebind (DDA master stays the longest |delta| while a +// slower short axis lengthens the period), and F10 pins that R sees through +// collinear micro-segments (no rest at a joint, cruise when N/2 > P_stop). +void f7_linear_lookahead() { + const uint32_t accel = 2000; + const uint32_t ticks_eq[2] = {4000, 4000}; + const uint32_t P_coast = RampMap(4000, accel).P_coast(); + + // F5: square 1600 (returns to the origin), Linear path-stop at every 90 deg + // corner. Each side is shorter than P_stop, so P is a triangle and the decel + // starts on the side, not in the last slice. + { + int32_t verts[5][2] = {{0, 0}, {1600, 0}, {1600, 1600}, {0, 1600}, {0, 0}}; + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + PolySimResult res; + walk_prod_polyline<64>(px, py, path, verts, 5, ticks_eq, 4000, accel, true, + "f5", "FasNAxis F5 square 1600 Linear", &res); + test(res.trace_match, "F7 F5 trace matches naxis_ref"); + test(res.issued[0] == 0 && res.issued[1] == 0, + "F7 F5 issued nets to the origin"); + test(res.end_pos[0] == 0 && res.end_pos[1] == 0, + "F7 F5 realizes the square and returns"); + test(res.n_vertex == 4, "F7 F5 every corner is a vertex sample"); + bool corners_zero = true; + for (int k = 0; k < res.n_vertex; k++) { + if (res.vertex_p[k] > 1) { + corners_zero = false; + } + } + test(corners_zero, "F7 F5 P -> 0 at every corner"); + test(res.max_moving_p > 1, "F7 F5 ramps up on a side"); + test(res.max_moving_p < P_coast, + "F7 F5 peak P < P_stop (decel starts on the side)"); + test(res.envelope_ok, "F7 F5 envelope ticks >= ticks_i_cfg"); + test(res.p_le_r_ok, "F7 F5 P <= R on every sample"); + test(!res.underrun && !res.first_fill_underrun, "F7 F5 no underrun"); + printf("F7 F5 square: vertices=%d peak_P=%u max_ticks(as T)=%llu\n", + res.n_vertex, res.max_moving_p, (unsigned long long)res.total_ticks); + printf("F5 Linear SimPort plot written: test_26_f5.gnuplot\n"); + + // Step 10: the gnuplot file is the plot. Confirm the bytes NaxisPlot + // promised are on disk before touching the helper further. + test(gnuplot_has("test_26_f5.gnuplot", "$data <= ticks_x). + { + int32_t verts[2][2] = {{0, 0}, {1600, 1600}}; + uint32_t ticks9[2] = {40000, 4000}; + SimPort px(40000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + PolySimResult res; + walk_prod_polyline<64>(px, py, path, verts, 2, ticks9, 40000, accel, true, + "f9", "FasNAxis F9 45 deg, X 10x slower", &res); + test(res.trace_match, "F7 F9 trace matches naxis_ref"); + test(path.masterAxis() == 0, "F7 F9 X is the DDA master (slower token)"); + test(res.issued[0] == 1600 && res.issued[1] == 1600, + "F7 F9 both axes issue their full |delta|"); + test(res.min_moving_ticks >= ticks9[0], + "F7 F9 X binds: shared period >= X ticks, Y scaled down"); + test(res.envelope_ok, "F7 F9 envelope"); + test(res.p_le_r_ok, "F7 F9 P <= R"); + test(!res.underrun && !res.first_fill_underrun, "F7 F9 no underrun"); + printf("F7 F9 45deg: master=%d issued=(%lld,%lld) min_ticks=%u\n", + path.masterAxis(), (long long)res.issued[0], + (long long)res.issued[1], res.min_moving_ticks); + printf("F9 Linear SimPort plot written: test_26_f9.gnuplot\n"); + } + + // F18: (10000, 9000) with Y 40x slower. Longest is X (DDA master), but Y + // would exceed v_max if X ran at ticks_x; Y lengthens ticks_b and X is scaled + // down in speed, both axes still issuing their full |delta|. + { + int32_t verts[2][2] = {{0, 0}, {10000, 9000}}; + uint32_t ticks18[2] = {1000, 40000}; + SimPort px(1000), py(40000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + PolySimResult res; + walk_prod_polyline<64>(px, py, path, verts, 2, ticks18, 40000, accel, true, + "f18", "FasNAxis F18 (10000,9000), Y 40x slower", + &res); + test(res.trace_match, "F7 F18 trace matches naxis_ref"); + test(path.masterAxis() == 0, + "F7 F18 X is the DDA master (longest |delta|)"); + test(res.issued[0] == 10000 && res.issued[1] == 9000, + "F7 F18 both axes issue their full |delta|"); + test(res.min_moving_ticks >= ticks18[1], + "F7 F18 Y time-law binds: shared period >= Y ticks, X scaled down"); + test(res.envelope_ok, "F7 F18 envelope"); + test(res.p_le_r_ok, "F7 F18 P <= R"); + test(res.end_pos[0] == 10000 && res.end_pos[1] == 9000, + "F7 F18 vertex hit"); + test(!res.underrun && !res.first_fill_underrun, "F7 F18 no underrun"); + printf("F7 F18: master=%d issued=(%lld,%lld) min_ticks=%u\n", + path.masterAxis(), (long long)res.issued[0], + (long long)res.issued[1], res.min_moving_ticks); + printf("F18 Linear SimPort plot written: test_26_f18.gnuplot\n"); + } + + // F10: 100 x 100-step collinear micro-segments totalling 10000. R sees + // through the joints: P cruises (N/2 > P_stop), no rest at any of the first + // 99 collinear joints, and the decel spans the tail across block boundaries. + { + int32_t verts[101][2]; + for (int k = 0; k <= 100; k++) { + verts[k][0] = 100 * k; + verts[k][1] = 0; + } + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 128, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + PolySimResult res; + walk_prod_polyline<128>( + px, py, path, verts, 101, ticks_eq, 4000, accel, true, "f10", + "FasNAxis F10 100x100 collinear micro-segments", &res); + test(res.trace_match, "F7 F10 trace matches naxis_ref"); + test(res.issued[0] == 10000 && res.issued[1] == 0, + "F7 F10 issued X == 10000, idle Y issues nothing"); + test(res.n_vertex == 100, "F7 F10 one vertex sample per micro-segment"); + bool joints_continue = true; + for (int k = 0; k < res.n_vertex - 1; k++) { + if (res.vertex_p[k] <= 1) { + joints_continue = false; + } + } + test(joints_continue, "F7 F10 no rest at a collinear joint"); + test(res.vertex_p[res.n_vertex - 1] <= 1, + "F7 F10 the last buffered point is rest"); + test(res.max_moving_p + 64 >= P_coast && res.max_moving_p <= P_coast, + "F7 F10 coasts because N/2 > P_stop"); + test(res.envelope_ok, "F7 F10 envelope"); + test(res.p_le_r_ok, "F7 F10 P <= R"); + test(!res.underrun && !res.first_fill_underrun, "F7 F10 no underrun"); + printf("F7 F10: vertices=%d peak_P=%u P_coast=%u\n", res.n_vertex, + res.max_moving_p, P_coast); + printf("F10 Linear SimPort plot written: test_26_f10.gnuplot\n"); + } + + printf("F7/F9/F10/F18 Linear lookahead across blocks green\n"); +} + +// F16 (whitepaper section 6 / 14 / F-table row F16): the header skeleton and +// its registration contract. No motion yet (that is Step 6+). This pins: +// - FasNAxisConfig{} default member initializers, and the constructor's +// 0 -> default recovery for dt_ticks and kappa_stop_q8. +// - PumpStatus has Idle/Running/Underrun/Error and NO LookaheadTooShort. +// - addAxis fails on i >= NAXES, a null pointer, or a running/ramp-active +// stepper; a small HORIZON relative to P_stop is NOT an addAxis failure. +// - addWaypoint before any position sync is illegal; after sync it is legal. +// - addWaypoint to the current position (every delta 0) is a no-op. +// Backed by SimPort so we exercise the same query surface the real +// StepperMotion uses (isRampGeneratorActive / isRunning), without raising +// MAX_STEPPER or linking extra queues. +static void f16_skeleton() { + // Default config: a valid Linear config with documented defaults. + FasNAxisConfig cfg; + test(cfg.dt_ticks == 32000, "F16: default dt_ticks is 32000"); + test(cfg.kappa_stop_q8 == 320, "F16: default kappa_stop_q8 is 320"); + test(cfg.overshoot_max == 8, "F16: default overshoot_max is 8"); + test(cfg.mode == FasNAxisConfig::Linear, "F16: default mode is Linear"); + test(cfg.dir_before_ticks == 0, "F16: default dir_before_ticks is 0"); + test(cfg.dir_after_ticks == 0, "F16: default dir_after_ticks is 0"); + + // PumpStatus enumerates exactly Idle/Running/Underrun/Error and no + // LookaheadTooShort (that concept is deliberately absent from v1). + test((int)PumpStatus::Idle == 0 && (int)PumpStatus::Running == 1 && + (int)PumpStatus::Underrun == 2 && (int)PumpStatus::Error == 3, + "F16: PumpStatus has Idle/Running/Underrun/Error"); + + // 0 -> default recovery: a raw zeroed struct still means the defaults, not a + // zero-duration slice / zero diagnostic threshold. + FasNAxisConfig zeroed; + zeroed.dt_ticks = 0; + zeroed.kappa_stop_q8 = 0; + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> recovered(zeroed, + sim_engine); + test(recovered.dt_ticks() == 32000, "F16: dt_ticks 0 recovers to 32000"); + test(recovered.kappa_stop_q8() == 320, + "F16: kappa_stop_q8 0 recovers to 320"); + + // addAxis rejects the out-of-range index. + SimPort px(4000); + SimPort py(4000); + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> ok(cfg, sim_engine); + test(ok.addAxis(0, &px) == true, "F16: addAxis(0) succeeds"); + test(ok.addAxis(1, &py) == true, "F16: addAxis(1) succeeds"); + test(ok.addAxis(2, &px) == false, "F16: addAxis(i>=NAXES) fails"); + + // addAxis rejects a null pointer. + test(ok.addAxis(0, NULL) == false, "F16: addAxis(null) fails"); + + // A small HORIZON relative to P_stop is NOT an addAxis failure: the same + // HORIZON that later caps the ramp (F19) still registers cleanly. + FasNAxis<2, 2, SimPort, TestStepperMotionEngine> tiny(cfg, sim_engine); + test(tiny.addAxis(0, &px) == true, "F16: small HORIZON addAxis succeeds"); + test(tiny.addAxis(1, &py) == true, "F16: small HORIZON addAxis succeeds"); + + // addAxis fails when the stepper's ramp generator is active or it is + // running (no race with manageSteppers / a prior moveTo). + SimPort ramping(4000); + ramping.setRampGeneratorActive(true); + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> r(cfg, sim_engine); + test(r.addAxis(0, &px) == true, "F16: addAxis on idle port succeeds"); + test(r.addAxis(1, &ramping) == false, "F16: addAxis while ramp active fails"); + + // Position sync: addWaypoint is illegal before a sync; legal after. + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> p(cfg, sim_engine); + p.addAxis(0, &px); + p.addAxis(1, &py); + int32_t at[2] = {10, 20}; + test(p.addWaypoint(at) == false, "F16: addWaypoint before sync is illegal"); + p.syncFromSteppers(); + test(p.addWaypoint(at) == true, "F16: addWaypoint after sync is legal"); + + // setCurrentPosition opens the same door as syncFromSteppers(). + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> q(cfg, sim_engine); + q.addAxis(0, &px); + q.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + test(q.addWaypoint(cur) == false, + "F16: addWaypoint before setCurrentPosition illegal"); + q.setCurrentPosition(cur); + test(q.addWaypoint(cur) == true, + "F16: addWaypoint after setCurrentPosition legal"); + + // addWaypoint to the current position (every delta 0) is a no-op, not a + // motion. + FasNAxis<2, 8, SimPort, TestStepperMotionEngine> s(cfg, sim_engine); + s.addAxis(0, &px); + s.addAxis(1, &py); + int32_t here[2] = {100, 200}; + s.setCurrentPosition(here); + test(s.addWaypoint(here) == true, + "F16: addWaypoint at current position is legal"); + test(s.block_count() == 0, "F16: addWaypoint to current position is a no-op"); + + printf("F16 header skeleton + addAxis/position contract green\n"); +} + +// Step 8 (whitepaper section 8): the feeder's send_to must read the +// addQueueEntry() result and hold a command that returned a retryable code so +// the paired axes stay in lockstep. Three fixtures, in order. +// +// 8.1 F14: a long single-block Linear move with no per-step fault. If the +// command stream is intact the two axes' simulated clocks stay within one +// command of each other on every paired drain -- the invariant this whole step +// builds toward. +// +// 8.2 retry: a one-shot retryable fault (QueueFull or DirPinIsBusy) must leave +// the held command in-flight on the faulting axis, not dropped and not +// re-planned onto its partner. +// +// 8.3 room: with a nearly-full queue the planner must reserve two slots for a +// pause-stuffed entry, and the ticks floor must reject too-fast steps before +// addQueueEntry. +void f8_feeder() { + // --- 8.1 F14: long single axis move, clocks stay in lockstep ------------ + // (240000, 0): X does all the work, Y runs no steps of this block. Both run + // the same pump/drain cadence on 4000-tick queues, so the issued tick sums + // per axis must nearly coincide (one command out of phase at most). + { + const uint32_t ticks_cfg = 4000; + const uint32_t move = 240000; + SimPort px(ticks_cfg, 64), py(ticks_cfg, 64); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + + int32_t target[2] = {(int32_t)move, 0}; + path.addWaypoint(target); + path.endPath(); + + NaxisPlot plot; + plot.start_scalar("f14", "F14 feeder clock delta (240000 steps)"); + + uint64_t max_clock_delta = 0; + int64_t issued_x = 0, issued_y = 0; + long sub = 0; + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + issued_x += s0 == 0 ? 0 : (u0 ? s0 : -s0); + issued_y += s1 == 0 ? 0 : (u1 ? s1 : -s1); + int64_t delta = (int64_t)px.clock() - (int64_t)py.clock(); + uint64_t d = delta < 0 ? (uint64_t)(-delta) : (uint64_t)delta; + if (d > max_clock_delta) { + max_clock_delta = d; + } + if (sub++ % 1000 == 0) { + double t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + plot.scalar_row(t, (double)delta, 0.0); + } + path.pump(); + } + test(max_clock_delta <= 2, "F14 clocks stay within 2 ticks of each other"); + test(px.position() == (int32_t)move, "F14 X reached the target"); + test(py.position() == 0, "F14 Y did not move"); + test((int64_t)issued_x == (int64_t)move, "F14 X issued the full move"); + test(issued_y == 0, "F14 Y issued no steps"); + test(px.clock() >= 60ull * 16000000ull, + "F14 X ran at least the coast time (<= 60 s of ticks)"); + double t_end = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + plot.set_y_range(-2.0, 2.0); + plot.finish_scalar(0.0, t_end, "time [s]", "clock_x - clock_y [ticks]", + "clock_x - clock_y", "zero"); + printf( + "F14 feeder: issued=(%lld,%lld) max_clock_delta=%llu px_clock=%llu\n", + (long long)issued_x, (long long)issued_y, + (unsigned long long)max_clock_delta, (unsigned long long)px.clock()); + } + + // --- 8.2 retry: a one-shot retryable fault holds the command in-flight -- + // + // A paired (500, 500) move. Prefill, drain a few paired commands to make + // room, arm a single QueueFull fault on Y, pump once (X accepts its command, + // Y holds it), confirm X gained exactly one and Y gained none, then pump + // again with no fault so Y accepts the same held command. + { + SimPort px(4000, 64), py(4000, 64); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + + int32_t target[2] = {500, 500}; + path.addWaypoint(target); + path.endPath(); + + path.pump(); // prefill + for (int i = 0; i < 4 && path.isBusy(); ++i) { + px.drain_one(NULL, NULL); + py.drain_one(NULL, NULL); + } + + int qx0 = (int)px.queueEntries(); + int qy0 = (int)py.queueEntries(); + py.failNext(AQE_QUEUE_FULL); + path.pump(); // X's command lands, Y's is held (returned QueueFull) + test((int)px.queueEntries() == qx0 + 1, + "8.2 retry X gained exactly its command on the faulting pump"); + test((int)py.queueEntries() == qy0, "8.2 retry Y did not take the command"); + + path.pump(); // no fault armed now: the held Y command is sent again + test((int)py.queueEntries() >= qy0 + 1, + "8.2 retry Y accepts the held command on the retry"); + test(path.isBusy(), "8.2 retry the move is still in progress"); + + // Drive to completion with paired drains; the held Y command and its + // resend keep the two command streams identical, so the clocks must stay + // within two ticks and both axes hit (500, 500). + bool lockstep_holds = true; + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + uint64_t d = px.clock() > py.clock() ? px.clock() - py.clock() + : py.clock() - px.clock(); + if (d > 2) { + lockstep_holds = false; + } + path.pump(); + } + test(lockstep_holds, + "8.2 retry clock stays within 2 ticks after one retryable fault"); + test(px.position() == 500 && py.position() == 500, + "8.2 retry completes the (500, 500) move"); + printf("F12 retry: ends (500,500) lockstep ok=%d\n", lockstep_holds); + + // A different retryable code, DirPinIsBusy, follows the same path. + { + SimPort qx(4000, 64), qy(4000, 64); + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> p2(cfg, sim_engine); + p2.addAxis(0, &qx); + p2.addAxis(1, &qy); + int32_t cur2[2] = {0, 0}; + p2.setCurrentPosition(cur2); + int32_t t2[2] = {200, 200}; + p2.addWaypoint(t2); + p2.endPath(); + p2.pump(); // prefill + for (int i = 0; i < 4 && p2.isBusy(); ++i) { + qx.drain_one(NULL, NULL); + qy.drain_one(NULL, NULL); + } + int bx = (int)qx.queueEntries(); + int by = (int)qy.queueEntries(); + qy.failNext(AQE_DIR_PIN_IS_BUSY); + p2.pump(); // held on Y + test((int)qx.queueEntries() == bx + 1 && (int)qy.queueEntries() == by, + "8.2 retry DirPinIsBusy: X lands, Y holds"); + p2.pump(); // retry: Y takes the held command + test((int)qy.queueEntries() >= by + 1, + "8.2 retry DirPinIsBusy: Y accepts on retry"); + } + } + + // --- 8.3 room: reserve two slots, and reject too-fast steps before ------- + // addQueueEntry. A nearly-full queue must never reach QUEUE_LEN. + { + const uint32_t ticks_cfg = 4000; + SimPort p0(ticks_cfg, 16), p1(ticks_cfg, 16); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &p0); + path.addAxis(1, &p1); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + + int32_t target[2] = {8000, 8000}; + path.addWaypoint(target); + path.endPath(); + + while (path.isBusy()) { + path.pump(); + test(p0.queueEntries() <= 14, "F15 room X never reaches QUEUE_LEN - 1"); + test(p1.queueEntries() <= 14, "F15 room Y never reaches QUEUE_LEN - 1"); + if (p0.queueEntries() > 0) { + p0.drain_one(NULL, NULL); + } + if (p1.queueEntries() > 0) { + p1.drain_one(NULL, NULL); + } + } + test(p0.position() == 8000 && p1.position() == 8000, + "F15 room both axes complete the 8000 move"); + printf("F15 room: completed 8000x8000 on QUEUE_LEN=16 queues\n"); + } + + // A 4 ms pump gap must not empty a QUEUE_LEN=16 queue. One step at 4000 + // ticks is 0.25 ms, so 14 single steps are 3.5 ms; a coast batch is about + // 2 ms and the filled queue outlasts the gap. + { + const uint32_t ticks_cfg = 4000; + const uint32_t gap = 4u * (uint32_t)(TICKS_PER_S / 1000); + SimPort p0(ticks_cfg, 16), p1(ticks_cfg, 16); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &p0); + path.addAxis(1, &p1); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t target[2] = {20000, 0}; + path.addWaypoint(target); + path.endPath(); + path.pump(); + int max_steps = 0; + while (path.isBusy()) { + uint32_t got = 0; + while (got < gap && !p0.isQueueEmpty()) { + int64_t s0 = 0; + uint32_t dt = p0.drain_one(&s0, NULL); + p1.drain_one(NULL, NULL); + if (s0 > max_steps) { + max_steps = (int)s0; + } + got += dt; + } + path.pump(); + } + test(max_steps > 1, "F15 4 ms pump saw a multi-step coast command"); + test(path.hasUnderrun() == false, "F15 4 ms pump does not underrun"); + test(p0.position() == 20000 && p1.position() == 0, + "F15 4 ms pump ends at 20000"); + printf("F15 4 ms pump: max_steps=%d gap=%u\n", max_steps, gap); + } + + printf("F14/F12/F15 feeder contract green\n"); +} + +// Step 9 (whitepaper section 4.4): the DIR pause is carved out of the reversing +// axis's own last step, so the coordinated timeline does not grow and no other +// axis is paused. The reversing axis arrives at a slow period T_min (section +// 4.4.1); the last old-direction step of period T_min is replaced by a +// shortened step of T_min - tau plus the before-pauses (old DIR) and the +// after-pause (new DIR). An inject the plan did not carve is an Error. +struct NaxisCmd { + uint16_t ticks; + uint8_t steps; + bool up; +}; +struct RevSample { + double t; + int32_t x; + int32_t y; + uint16_t ticks; + uint8_t steps; +}; +struct RevTrace { + NaxisCmd x[6000]; + int nx; + NaxisCmd y[6000]; + int ny; + RevSample s[6000]; + int ns; + int32_t pxe; + int32_t pye; + uint64_t clkx; + uint64_t clky; + bool error; +}; + +// Run a Linear out-and-back on X with the given DIR budget; record the raw +// command streams and the per-iteration XY/clock samples. +static void run_reversal(uint32_t before, uint32_t after, uint32_t accel, + int32_t move, uint32_t qlen, RevTrace* tr) { + SimPort px(4000, qlen), py(4000, qlen); + px.setAcceleration(accel); + py.setAcceleration(accel); + px.setDirChangeBudget((uint16_t)before, (uint16_t)after); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t1[2] = {move, 0}; + path.addWaypoint(t1); + int32_t t2[2] = {0, 0}; + path.addWaypoint(t2); + path.endPath(); + + tr->nx = 0; + tr->ny = 0; + tr->ns = 0; + tr->error = false; + if (path.pump() == PumpStatus::Error) { + tr->error = true; + } + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + uint32_t t0 = px.drain_one(&s0, &u0); + uint32_t t1b = py.drain_one(&s1, &u1); + if (t0 > 0 && tr->nx < 6000) { + tr->x[tr->nx].ticks = (uint16_t)t0; + tr->x[tr->nx].steps = (uint8_t)s0; + tr->x[tr->nx].up = u0; + tr->nx++; + } + if (t1b > 0 && tr->ny < 6000) { + tr->y[tr->ny].ticks = (uint16_t)t1b; + tr->y[tr->ny].steps = (uint8_t)s1; + tr->y[tr->ny].up = u1; + tr->ny++; + } + if (tr->ns < 6000) { + tr->s[tr->ns].t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + tr->s[tr->ns].x = px.position(); + tr->s[tr->ns].y = py.position(); + tr->s[tr->ns].ticks = (uint16_t)t0; + tr->s[tr->ns].steps = (uint8_t)s0; + tr->ns++; + } + if (path.pump() == PumpStatus::Error) { + tr->error = true; + } + } + tr->pxe = px.position(); + tr->pye = py.position(); + tr->clkx = px.clock(); + tr->clky = py.clock(); +} + +// Step 12 F12b: an Overshoot dog-leg (0,0) -> (leg,leg) -> (0,2*leg) with a +// DIR budget on the reversing X. X is the binder and carves its own last step; +// the continuing Y keeps the steps already planned across those ticks (it is +// not given a pauses=0 command by the budget). +static void run_overshoot_rev(uint32_t before, uint32_t after, uint32_t accel, + int32_t leg, RevTrace* tr) { + SimPort px(4000, 64), py(4000, 64); + px.setAcceleration(accel); + py.setAcceleration(accel); + px.setDirChangeBudget((uint16_t)before, (uint16_t)after); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = 8; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t1[2] = {leg, leg}; + path.addWaypoint(t1); + int32_t t2[2] = {0, 2 * leg}; + path.addWaypoint(t2); + path.endPath(); + + tr->nx = 0; + tr->ny = 0; + tr->ns = 0; + tr->error = false; + if (path.pump() == PumpStatus::Error) { + tr->error = true; + } + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + uint32_t t0 = px.drain_one(&s0, &u0); + uint32_t t1b = py.drain_one(&s1, &u1); + if (t0 > 0 && tr->nx < 6000) { + tr->x[tr->nx].ticks = (uint16_t)t0; + tr->x[tr->nx].steps = (uint8_t)s0; + tr->x[tr->nx].up = u0; + tr->nx++; + } + if (t1b > 0 && tr->ny < 6000) { + tr->y[tr->ny].ticks = (uint16_t)t1b; + tr->y[tr->ny].steps = (uint8_t)s1; + tr->y[tr->ny].up = u1; + tr->ny++; + } + if (tr->ns < 6000) { + tr->s[tr->ns].t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + tr->s[tr->ns].x = px.position(); + tr->s[tr->ns].y = py.position(); + tr->s[tr->ns].ticks = (uint16_t)t0; + tr->s[tr->ns].steps = (uint8_t)s0; + tr->ns++; + } + if (path.pump() == PumpStatus::Error) { + tr->error = true; + } + } + tr->pxe = px.position(); + tr->pye = py.position(); + tr->clkx = px.clock(); + tr->clky = py.clock(); +} + +// Index of the last X step in the old direction (the carved step), or -1. +static int last_old_step(const RevTrace* tr) { + int idx = -1; + for (int k = 0; k < tr->nx; k++) { + if (tr->x[k].steps != 0 && tr->x[k].up) { + idx = k; + } + } + return idx; +} + +// True if any command in `c` is a pause of exactly `ticks`. +static bool has_pause(const NaxisCmd* c, int n, uint16_t ticks) { + for (int k = 0; k < n; k++) { + if (c[k].steps == 0 && c[k].ticks == ticks) { + return true; + } + } + return false; +} + +void f9_dir_pauses() { + const uint32_t ticks_cfg = 4000; + const uint32_t accel = 80000; + const int32_t move = 400; + const uint16_t before = 3200; + const uint16_t after = 3200; + RampMap map(ticks_cfg, accel); + const uint32_t T_min = map.calculate_ticks(1); + const uint32_t tau = (uint32_t)before + after; + + // --- F12: the carve, Y gains no pause, clock equals the zero-budget run --- + { + static RevTrace tr; + run_reversal(before, after, accel, move, 64, &tr); + test(!tr.error, "F12 run does not error"); + test(tr.pxe == 0 && tr.pye == 0, "F12 F12 both axes end on target"); + + int k = last_old_step(&tr); + test(k >= 0, "F12 there is a last old-direction X step"); + // The last old-direction step keeps its ramp period (like the normal ramp + // generator): the DIR pause is inserted *after* it, not carved out of it. + test(tr.x[k].ticks == T_min, + "F12 last old step is not shortened (period stays T_min)"); + test(k >= 1 && tr.x[k].ticks >= tr.x[k - 1].ticks, + "F12 no period jump at the reversal (period never drops)"); + // Before-pause: old DIR, 3200. After-pause: new DIR, 3200. + test(k + 2 < tr.nx, "F12 the carve has before and after pauses"); + test( + tr.x[k + 1].steps == 0 && tr.x[k + 1].up && tr.x[k + 1].ticks == before, + "F12 before-pause old DIR of 3200 on X only"); + test( + tr.x[k + 2].steps == 0 && !tr.x[k + 2].up && tr.x[k + 2].ticks == after, + "F12 after-pause new DIR of 3200"); + test((uint32_t)tr.x[k].ticks + tr.x[k + 1].ticks + tr.x[k + 2].ticks == + T_min + tau, + "F12 the carve adds tau after the full last step"); + // The following X step is the new direction. + int k_next = k + 3; + test(k_next < tr.nx && tr.x[k_next].steps != 0 && !tr.x[k_next].up, + "F12 the following step is the new direction"); + + // Y gains no DIR pause: its trace is identical to a zero-budget run. + static RevTrace tr0; + run_reversal(0, 0, accel, move, 64, &tr0); + bool y_same = (tr.ny == tr0.ny); + if (y_same) { + for (int j = 0; j < tr.ny; j++) { + if (tr.y[j].ticks != tr0.y[j].ticks || + tr.y[j].steps != tr0.y[j].steps || tr.y[j].up != tr0.y[j].up) { + y_same = false; + } + } + } + test(y_same, "F12 idle Y trace is unchanged: no DIR pause copied onto Y"); + // The reversing axis's clock grows by exactly tau (the DIR pause); the idle + // axis is untouched (the timeline added only the pause, no shortened step). + test(tr.clkx == tr0.clkx + tau && tr.clky == tr0.clky, + "F12 reversing clock grows by tau; the other axis is unchanged"); + + // The plot: XY plus the period samples on the reversing axis. + NaxisPlot plot; + plot.start_plot("f12", "FasNAxis F12 DIR carve on reversal", 2); + plot.poly_point(0.0, 0.0); + plot.poly_point((double)move, 0.0); + plot.poly_point(0.0, 0.0); + plot.poly_done(); + // The speed panel shows the *axis* speed (time between consecutive step + // pulses). The carve keeps the last step at T_min and inserts the DIR pause + // after it, so the next step comes after T_min + tau and the speed at the + // reversal is lower, never a pulse. Merge each step with the pauses that + // follow it; the period panel still shows the full step then the pauses. + static double vs[6000]; + for (int j = 0; j < tr.ns; j++) { + vs[j] = 0.0; + } + for (int j = 0; j < tr.ns;) { + if (tr.s[j].steps == 0) { + j++; + continue; + } + uint32_t sum = tr.s[j].ticks; + int nxt = j + 1; + while (nxt < tr.ns && tr.s[nxt].steps == 0) { + sum += tr.s[nxt].ticks; + nxt++; + } + vs[j] = sum > 0 ? NAXIS_PLOT_TICKS_PER_S / (double)sum : 0.0; + j = nxt; + } + for (int j = 0; j < tr.ns; j++) { + double speed[2] = {vs[j], 0.0}; + double P[2] = {0.0, 0.0}; + double R[2] = {0.0, 0.0}; + double tickc[2] = {(double)tr.s[j].ticks, 0.0}; + plot.row(tr.s[j].t, (double)tr.s[j].x, (double)tr.s[j].y, 0.0, speed, P, + R, tickc); + } + plot.finish_plot(); + // No axis-speed pulse at the carve: the plotted speed at the vertex must + // stay at the slow T_min speed, not spike. + double v_ref = NAXIS_PLOT_TICKS_PER_S / (double)T_min; + double v_carve = + gnuplot_col_max_at_x("test_26_f12.gnuplot", (double)move, 5); + test(v_carve <= v_ref * 1.05, + "F12 plot: axis speed at the carve respects the pause (no pulse)"); + printf( + "F9 F12 carve: T_min=%u step=%u before=%u after=%u " + "clocks=(%llu,%llu) v_at_vertex=%.1f v_ref=%.1f\n", + T_min, tr.x[k].ticks, tr.x[k + 1].ticks, tr.x[k + 2].ticks, + (unsigned long long)tr.clkx, (unsigned long long)tr.clky, v_carve, + v_ref); + printf("F12 DIR carve plot written: test_26_f12.gnuplot\n"); + } + + // --- F12c: an inject the plan did not carve is an Error, Y gains no pause -- + { + SimPort px(ticks_cfg, 64), py(ticks_cfg, 64); + px.setAcceleration(accel); + py.setAcceleration(accel); + px.setInjectMode(SimPort::InjectNone); + px.forceExtraBefore(8000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t1[2] = {1, 0}; + path.addWaypoint(t1); + int32_t t2[2] = {0, 0}; + path.addWaypoint(t2); + path.endPath(); + PumpStatus st = path.pump(); + test(st == PumpStatus::Error, + "F12c an uncarved injected pause returns Error"); + // Y does not gain the 8000 pause. + static NaxisCmd ycmd[512]; + int ny = 0; + while (ny < 512) { + int64_t s = 0; + uint32_t t = py.drain_one(&s, NULL); + if (t == 0 && s == 0) { + break; + } + ycmd[ny].ticks = (uint16_t)t; + ycmd[ny].steps = (uint8_t)s; + ycmd[ny].up = true; + ny++; + } + test(!has_pause(ycmd, ny, 8000), + "F12c the other axis does not gain the injected pause"); + printf("F9 F12c uncarved inject -> Error, Y clean (ny=%d)\n", ny); + } + + // --- F12b: Overshoot dog-leg. X reverses at the vertex and carves its own + // last step; the continuing Y keeps its planned steps (Step 12). ---------- + { + const int32_t leg = 400; + const uint32_t tau = (uint32_t)before + (uint32_t)after; + static RevTrace tr0; + run_overshoot_rev(0, 0, accel, leg, &tr0); + static RevTrace tr; + run_overshoot_rev(before, after, accel, leg, &tr); + test(!tr.error, "F12b overshoot dog-leg does not error"); + test(tr.pxe == 0 && tr.pye == 2 * leg, "F12b both axes end on target"); + int k = last_old_step(&tr); + int k0 = last_old_step(&tr0); + test(k >= 0 && k0 >= 0, "F12b X has a last old-direction step"); + test(tr.x[k].ticks == (uint32_t)tr0.x[k0].ticks, + "F12b X last step keeps its period (not shortened)"); + test(k + 2 < tr.nx, "F12b X has the before and after pauses"); + test( + tr.x[k + 1].steps == 0 && tr.x[k + 1].up && tr.x[k + 1].ticks == before, + "F12b before-pause old DIR on X only"); + test( + tr.x[k + 2].steps == 0 && !tr.x[k + 2].up && tr.x[k + 2].ticks == after, + "F12b after-pause new DIR"); + test((uint32_t)tr.x[k].ticks + tr.x[k + 1].ticks + tr.x[k + 2].ticks == + (uint32_t)tr0.x[k0].ticks + tau, + "F12b the carve adds tau after the full last step"); + // Y gains no DIR pause of the budget length and is bit-identical to the + // zero-budget dog-leg: the continuing axis keeps its planned steps. + test(!has_pause(tr.y, tr.ny, (uint16_t)before), + "F12b continuing Y gains no before-pause"); + test(!has_pause(tr.y, tr.ny, (uint16_t)after), + "F12b continuing Y gains no after-pause"); + bool y_same = (tr.ny == tr0.ny); + for (int j = 0; j < tr.ny && y_same; j++) { + if (tr.y[j].ticks != tr0.y[j].ticks || tr.y[j].steps != tr0.y[j].steps || + tr.y[j].up != tr0.y[j].up) { + y_same = false; + } + } + test(y_same, "F12b continuing Y is unchanged by the DIR carve"); + printf("F12b overshoot dog-leg: nX=%d nY=%d k=%d step=%u T0=%u\n", tr.nx, + tr.ny, k, tr.x[k].ticks, tr0.x[k0].ticks); + } + + // --- Budget larger than the natural slow period: the step keeps its period + // and the (longer) DIR pause is added after it, no acceleration cap. ------- + { + const uint16_t big_before = 50000; + const uint16_t big_after = 0; + static RevTrace tr; + run_reversal(big_before, big_after, accel, move, 64, &tr); + test(!tr.error, "F12 long pause run does not error"); + test(tr.pxe == 0 && tr.pye == 0, "F12 long pause both axes end on target"); + int k = last_old_step(&tr); + test(k >= 0, "F12 long pause has a last old-direction step"); + test(tr.x[k].ticks == T_min, + "F12 long pause: step keeps its natural period"); + test(k + 1 < tr.nx && tr.x[k + 1].steps == 0 && tr.x[k + 1].up && + tr.x[k + 1].ticks == big_before, + "F12 long pause before-pause of tau on X only"); + // Y still gains no DIR pause: no pause of the budget length appears. + test(!has_pause(tr.y, tr.ny, big_before), + "F12 long pause: Y gains no DIR pause"); + printf("F9 F12 long pause: T_min=%u step=%u before=%u\n", T_min, + tr.x[k].ticks, tr.x[k + 1].ticks); + } + + printf("F12/F12b/F12c DIR pause carve green\n"); +} + +// --------------------------------------------------------------------------- +// Step 11 — Overshoot rest-to-rest (F4, F4b, lone diagonal). +// +// One rest-to-rest segment through SimPort, FasNAxisConfig::Overshoot. The +// binding axis (largest per-axis RampLaw duration) sets the wall clock; the +// other axis is spread across it. F4 caps the chordal bulge at 8 steps, F4b is +// the raw (UINT16_MAX) profile, and the lone diagonal is the same ramp on both +// axes (d^2 ~ 0). The reference duration is naxis_overshoot_duration (sum of +// the binding RampLaw only). +// --------------------------------------------------------------------------- +struct OvershootResult { + int64_t issued[2]; + int32_t end[2]; + double max_d2; + uint32_t clock0; + uint32_t clock1; + int32_t mid_short; + bool mid_seen; + bool underrun; +}; + +static void run_overshoot_segment( + SimPort& px, SimPort& py, + FasNAxis<2, 64, SimPort, TestStepperMotionEngine>& path, + const char* fixture, const char* title, int32_t tx, int32_t ty, + uint64_t ref_T, bool do_plot, OvershootResult* res) { + res->issued[0] = 0; + res->issued[1] = 0; + res->end[0] = 0; + res->end[1] = 0; + res->max_d2 = 0.0; + res->clock0 = 0; + res->clock1 = 0; + res->mid_short = -1; + res->mid_seen = false; + res->underrun = false; + int short_axis = (labs((long)tx) <= labs((long)ty)) ? 0 : 1; + + NaxisPlot plot; + if (do_plot) { + plot.start_plot(fixture, title, 2); + plot.poly_point((double)px.position(), (double)py.position()); + plot.poly_point((double)tx, (double)ty); + plot.poly_done(); + } + + int32_t target[2] = {tx, ty}; + path.addWaypoint(target); + path.endPath(); + path.pump(); + + double nx = -(double)ty; + double ny = (double)tx; + double nlen = sqrt(nx * nx + ny * ny); + int64_t iter = 0; + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + px.drain_one(&s0, NULL); + py.drain_one(&s1, NULL); + res->issued[0] += s0; + res->issued[1] += s1; + double x = (double)px.position(); + double y = (double)py.position(); + double dev = + nlen > 0.0 ? fabs(nx * x + ny * y) / nlen : sqrt(x * x + y * y); + if (dev * dev > res->max_d2) { + res->max_d2 = dev * dev; + } + if (!res->mid_seen && ref_T > 0 && (uint64_t)px.clock() >= ref_T / 2) { + res->mid_seen = true; + res->mid_short = short_axis == 0 ? px.position() : py.position(); + } + if (do_plot && (iter % 4 == 0)) { + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + uint32_t ticks = path.lastTicks(); + double t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + double v = ticks > 0 ? NAXIS_PLOT_TICKS_PER_S / (double)ticks : 0.0; + double speed[2] = {v, v}; + double Pcol[2] = {(double)P, (double)P}; + double Rcol[2] = {(double)R, (double)R}; + double tcol[2] = {(double)ticks, (double)ticks}; + plot.row(t, x, y, dev, speed, Pcol, Rcol, tcol); + } + iter++; + path.pump(); + } + res->underrun = path.hasUnderrun(); + res->end[0] = px.position(); + res->end[1] = py.position(); + res->clock0 = px.clock(); + res->clock1 = py.clock(); + if (do_plot) { + plot.finish_plot(); + } +} + +void f11_overshoot_rest() { + const uint32_t ticks[2] = {4000, 4000}; + const uint32_t accel[2] = {2000, 2000}; + + // F3 Linear baseline on the same segment: the F4 bulge must be larger. + double f3_max_d2 = 0.0; + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + SimSegmentResult lin; + run_linear_segment(px, py, path, "f11_f3", "FasNAxis F3 Linear (10000,100)", + 10000, 100, false, &lin); + f3_max_d2 = lin.max_dev * lin.max_dev; + } + + // F4: (10000, 100), cap 8. End exact, max d^2 <= 64, bulge > Linear. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = 8; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F11 F4 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F11 F4 addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t d[2] = {10000, 100}; + uint64_t T = naxis_overshoot_duration(d, ticks, accel, 2); + OvershootResult res; + run_overshoot_segment(px, py, path, "f4", + "FasNAxis F4 Overshoot (10000,100) cap 8", 10000, 100, + T, true, &res); + test(res.end[0] == 10000 && res.end[1] == 100, "F11 F4 end exact"); + test(res.issued[0] == 10000 && res.issued[1] == 100, + "F11 F4 issued == delta"); + test(res.max_d2 <= 64.0 + 1e-9, "F11 F4 max d^2 <= 64"); + test(res.max_d2 > f3_max_d2, "F11 F4 bulge greater than Linear"); + test(res.clock0 == T && res.clock1 == T, + "F11 F4 clock == binding ramp on both axes"); + test(res.underrun == false, "F11 F4 no underrun"); + printf( + "F11 F4 (10000,100) cap8: max_d2=%.3f f3_d2=%.3f clocks=(%u,%u) " + "T=%llu\n", + res.max_d2, f3_max_d2, res.clock0, res.clock1, (unsigned long long)T); + } + + // F4b: same segment, raw cap (UINT16_MAX). Short axis still moving at + // mid-time (not an early L); the raw bulge exceeds the cap 8. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = UINT16_MAX; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F11 F4b addAxis(0)"); + test(path.addAxis(1, &py) == true, "F11 F4b addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t d[2] = {10000, 100}; + uint64_t T = naxis_overshoot_duration(d, ticks, accel, 2); + OvershootResult res; + run_overshoot_segment(px, py, path, "f4b", + "FasNAxis F4b Overshoot (10000,100) raw", 10000, 100, + T, true, &res); + test(res.end[0] == 10000 && res.end[1] == 100, "F11 F4b end exact"); + test(res.mid_seen && res.mid_short > 0 && res.mid_short < 100, + "F11 F4b short axis still moving at mid-time (not an L)"); + test(res.max_d2 > 64.0, "F11 F4b raw bulge exceeds cap 8"); + test(res.clock0 == T && res.clock1 == T, "F11 F4b clock == binding ramp"); + printf("F11 F4b (10000,100) raw: max_d2=%.3f mid_short=%d clocks=(%u,%u)\n", + res.max_d2, res.mid_short, res.clock0, res.clock1); + } + + // Lone diagonal (1600, 1600): both axes are the binding ramp; Overshoot + // duration equals Linear within a couple of ticks and d^2 stays under 1. + { + SimPort lx(4000), ly(4000); + FasNAxisConfig lcfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> lpath(lcfg, + sim_engine); + lpath.addAxis(0, &lx); + lpath.addAxis(1, &ly); + int32_t cur[2] = {0, 0}; + lpath.setCurrentPosition(cur); + SimSegmentResult lres; + run_linear_segment(lx, ly, lpath, "f11_diag_lin", "diag linear", 1600, 1600, + false, &lres); + uint32_t lin_clock = lx.clock(); + + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = 8; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F11 diagonal addAxis(0)"); + test(path.addAxis(1, &py) == true, "F11 diagonal addAxis(1)"); + path.setCurrentPosition(cur); + int32_t d[2] = {1600, 1600}; + uint64_t T = naxis_overshoot_duration(d, ticks, accel, 2); + OvershootResult res; + run_overshoot_segment(px, py, path, "f11_diag", + "FasNAxis Overshoot lone diagonal", 1600, 1600, T, + false, &res); + test(res.end[0] == 1600 && res.end[1] == 1600, "F11 diagonal end exact"); + test(res.max_d2 < 1.0, "F11 diagonal d^2 < 1"); + test(labs((long)res.clock0 - (long)lin_clock) <= 2, + "F11 diagonal Overshoot clock == Linear clock"); + test(labs((long)res.clock0 - (long)T) <= 2, + "F11 diagonal clock == reference duration"); + printf("F11 diagonal: clocks ovs=%u lin=%u T=%llu max_d2=%.4f\n", + res.clock0, lin_clock, (unsigned long long)T, res.max_d2); + } + + printf("F4/F4b/diagonal Overshoot rest-to-rest green\n"); +} + +// --------------------------------------------------------------------------- +// Step 12 — Overshoot corners and circle (F6, F6b, F7). +// +// An Overshoot run crosses a vertex with P carrying on an axis that keeps its +// sign and resetting on an axis that reverses or goes idle (section 8.6). The +// shared wall clock is the binding ramp; the path may leave each chord by at +// most overshoot_max. `run_overshoot_polyline` walks a polyline through +// SimPort, samples the maximum squared distance to the current chord, records +// the clock at every vertex and reports whether every vertex was hit. The +// per-axis exit P at the vertices comes from `naxis_overshoot_vertices`. +// --------------------------------------------------------------------------- +struct OvershootPolyResult { + int32_t end[2]; + int64_t issued[2]; + double max_d2; + uint32_t vertex_clock[512]; + int n_vertices; + bool all_vertices; + bool underrun; + uint32_t max_axis_p[2]; // peak per-axis performed ramp-up + bool p_per_axis; // the two axes had different P at some sample + bool scalar_eq_binder; // performedRampUp() == performedRampUpAxis(master) +}; + +template +static void run_overshoot_polyline( + SimPort& px, SimPort& py, + FasNAxis<2, H, SimPort, TestStepperMotionEngine>& path, + const int32_t* wp, int n_wp, const char* fixture, const char* title, + bool do_plot, OvershootPolyResult* res) { + res->end[0] = 0; + res->end[1] = 0; + res->issued[0] = 0; + res->issued[1] = 0; + res->max_d2 = 0.0; + res->n_vertices = 0; + res->all_vertices = false; + res->underrun = false; + res->max_axis_p[0] = 0; + res->max_axis_p[1] = 0; + res->p_per_axis = false; + res->scalar_eq_binder = true; + + NaxisPlot plot; + if (do_plot) { + // The SimPort origin is the planner's first waypoint (setCurrentPosition is + // not a SimPort position setter), so the realized positions are relative to + // wp[0]. Draw the commanded polyline in the same port-relative coordinates, + // otherwise a path that does not start at (0,0) is offset from its trace. + plot.start_plot(fixture, title, 2); + plot.poly_point(0.0, 0.0); + for (int k = 1; k < n_wp; k++) { + plot.poly_point((double)(wp[2 * k] - wp[0]), + (double)(wp[2 * k + 1] - wp[1])); + } + plot.poly_done(); + } + + int32_t cur[2] = {wp[0], wp[1]}; + path.setCurrentPosition(cur); + for (int k = 1; k < n_wp; k++) { + int32_t t[2] = {wp[2 * k], wp[2 * k + 1]}; + path.addWaypoint(t); + } + path.endPath(); + path.pump(); + + int chord = 0; + int iter = 0; + // EMA-smoothed realized-speed sampling (see walk_polyline): the per-command + // lastTicks()/performedRampUp() are binder-global and a multi-step catch-up + // command has a short period, so a per-command rate spikes. + const int kPlotStride = 8; + const double kSpeedTau_s = 0.02; + int32_t last_x = 0, last_y = 0; + uint32_t last_clock = 0; + double ema_v[2] = {0.0, 0.0}; + bool have_sample = true; + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + res->issued[0] += u0 ? s0 : -s0; + res->issued[1] += u1 ? s1 : -s1; + int32_t x = px.position(); + int32_t y = py.position(); + if (chord < n_wp - 1) { + int32_t ax = wp[2 * chord] - wp[0], ay = wp[2 * chord + 1] - wp[1]; + int32_t bx = wp[2 * chord + 2] - wp[0], by = wp[2 * chord + 3] - wp[1]; + double vx = (double)(bx - ax), vy = (double)(by - ay); + double l2 = vx * vx + vy * vy; + if (l2 > 0.0) { + double cross = vx * (double)(y - ay) - vy * (double)(x - ax); + double d2 = cross * cross / l2; + if (d2 > res->max_d2) { + res->max_d2 = d2; + } + } + // SimPort positions are relative to the planner's start (wp[0]); `bx` / + // `by` are already in those port coordinates. + if (x == bx && y == by) { + if (res->n_vertices < 512) { + res->vertex_clock[res->n_vertices] = px.clock(); + } + res->n_vertices++; + chord++; + } + } + // Per-axis performed ramp-up: in Overshoot each axis rides its own + // persistent P, while performedRampUp() reports only the *binding* axis. + // A plot that mirrors that single scalar on every axis jumps whenever the + // binder switches; collect the per-axis value instead. + { + uint32_t pa = path.performedRampUpAxis(0); + uint32_t pb = path.performedRampUpAxis(1); + if (pa > res->max_axis_p[0]) { + res->max_axis_p[0] = pa; + } + if (pb > res->max_axis_p[1]) { + res->max_axis_p[1] = pb; + } + if (pa != pb) { + res->p_per_axis = true; + } + if (path.performedRampUp() != + path.performedRampUpAxis(path.masterAxis())) { + res->scalar_eq_binder = false; + } + } + if (do_plot) { + uint32_t clk = px.clock(); + double dt = (double)(clk - last_clock) / NAXIS_PLOT_TICKS_PER_S; + if (dt > 0.0) { + double alpha = dt / (kSpeedTau_s + dt); + ema_v[0] += alpha * ((double)(x - last_x) / dt - ema_v[0]); + ema_v[1] += alpha * ((double)(y - last_y) / dt - ema_v[1]); + } + last_x = x; + last_y = y; + last_clock = clk; + if ((iter % kPlotStride) == 0 && have_sample) { + double speed[2] = {ema_v[0], ema_v[1]}; + uint32_t ticks = path.lastTicks(); + double Pcol[2] = {(double)path.performedRampUpAxis(0), + (double)path.performedRampUpAxis(1)}; + double Rcol[2] = {(double)path.remainingToStopAxis(0), + (double)path.remainingToStopAxis(1)}; + double tcol[2] = {(double)ticks, (double)ticks}; + plot.row((double)clk / NAXIS_PLOT_TICKS_PER_S, (double)x, (double)y, + 0.0, speed, Pcol, Rcol, tcol); + } + } + iter++; + path.pump(); + } + res->underrun = path.hasUnderrun(); + res->end[0] = px.position(); + res->end[1] = py.position(); + res->all_vertices = (chord == n_wp - 1); + if (do_plot) { + plot.finish_plot(); + } +} + +// Run a polyline in Linear mode and return the final clock (both axes share +// it). +static uint32_t linear_polyline_clock(const int32_t* wp, int n_wp) { + SimPort px(4000, 16), py(4000, 16); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + OvershootPolyResult r; + run_overshoot_polyline(px, py, path, wp, n_wp, "f12_lin_unused", "linear", + false, &r); + return px.clock(); +} + +static void f12_overshoot_corners() { + const uint32_t ticks[2] = {4000, 4000}; + const uint32_t accel[2] = {2000, 2000}; + const uint32_t cap = 8; + + // --- F6: (0,0) -> (1600,1600) -> (3200,0). X continues, Y reverses. ------- + { + const int32_t wp[6] = {0, 0, 1600, 1600, 3200, 0}; + int32_t bx[2] = {1600, 1600}; + int32_t by[2] = {1600, -1600}; + uint64_t Tb[2]; + uint32_t P0[2], P1[2]; + naxis_overshoot_vertices(bx, by, 2, ticks, accel, cap, Tb, P0, P1); + test(P1[0] == 0, "F12 F6 reversing Y has P == 0 at the vertex"); + test(P0[0] > 0, "F12 F6 continuing X keeps a nonzero P at the vertex"); + + SimPort px(4000, 16), py(4000, 16); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = (uint16_t)cap; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F12 F6 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F12 F6 addAxis(1)"); + OvershootPolyResult res; + run_overshoot_polyline(px, py, path, wp, 3, "f6", + "FasNAxis F6 Overshoot continuing corner", true, + &res); + test(res.end[0] == 3200 && res.end[1] == 0, + "F12 F6 end at the last vertex"); + test(res.issued[0] == 3200 && res.issued[1] == 0, "F12 F6 issued == path"); + test(res.all_vertices && res.n_vertices == 2, + "F12 F6 every vertex sampled"); + test(res.max_d2 <= 64.0 + 1e-9, "F12 F6 chord d^2 <= 64"); + test(res.underrun == false, "F12 F6 no underrun"); + uint32_t lin = linear_polyline_clock(wp, 3); + test(px.clock() <= lin, "F12 F6 Overshoot clock <= Linear clock"); + printf("F12 F6 ovs=%u lin=%u Tb=(%llu,%llu) max_d2=%.3f Px=%u Py=%u\n", + px.clock(), lin, (unsigned long long)Tb[0], + (unsigned long long)Tb[1], res.max_d2, P0[0], P1[0]); + } + + // --- F6b: (0,0) -> (4000,1) -> (4000,4000). X ends, Y continues. ---------- + { + const int32_t wp[6] = {0, 0, 4000, 1, 4000, 4000}; + int32_t bx[2] = {4000, 0}; + int32_t by[2] = {1, 3999}; + uint64_t Tb[2]; + uint32_t P0[2], P1[2]; + naxis_overshoot_vertices(bx, by, 2, ticks, accel, cap, Tb, P0, P1); + test(P0[0] == 0, "F12 F6b idle X has P == 0 at the vertex"); + test(P1[0] == 1, "F12 F6b Y P <= 1 after the single-step block"); + + SimPort px(4000, 16), py(4000, 16); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = (uint16_t)cap; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F12 F6b addAxis(0)"); + test(path.addAxis(1, &py) == true, "F12 F6b addAxis(1)"); + OvershootPolyResult res; + run_overshoot_polyline(px, py, path, wp, 3, "f6b", + "FasNAxis F6b anisotropic continuing corner", true, + &res); + test(res.end[0] == 4000 && res.end[1] == 4000, + "F12 F6b end at the last vertex"); + test(res.all_vertices && res.n_vertices == 2, + "F12 F6b every vertex sampled"); + test(res.max_d2 <= 64.0 + 1e-9, "F12 F6b chord d^2 <= 64"); + test(res.underrun == false, "F12 F6b no underrun"); + printf("F12 F6b ovs=%u max_d2=%.3f Px=%u Py=%u\n", px.clock(), res.max_d2, + P0[0], P1[0]); + } + + // --- F7: circle radius 1600, 360 chords of 1 degree. Only a reversing axis + // has P == 0 at a vertex; the continuing axis keeps P. -------------------- + { + const int n = 360; + static int32_t wp[(360 + 1) * 2]; + for (int k = 0; k <= n; k++) { + double a = 2.0 * M_PI * (double)k / (double)n; + wp[2 * k] = iround(1600.0 * cos(a)); + wp[2 * k + 1] = iround(1600.0 * sin(a)); + } + static int32_t bx[360], by[360]; + for (int k = 0; k < n; k++) { + bx[k] = wp[2 * (k + 1)] - wp[2 * k]; + by[k] = wp[2 * (k + 1) + 1] - wp[2 * k + 1]; + } + static uint64_t Tb[360]; + static uint32_t P0[360], P1[360]; + naxis_overshoot_vertices(bx, by, n, ticks, accel, cap, Tb, P0, P1); + int fx = 0, fy = 0; + int last0 = 0, last1 = 0; + for (int pass = 0; pass < 2; pass++) { + for (int k = 0; k < n; k++) { + int nxt = (k + 1) % n; + int s0 = bx[nxt] > 0 ? 1 : (bx[nxt] < 0 ? -1 : 0); + int s1 = by[nxt] > 0 ? 1 : (by[nxt] < 0 ? -1 : 0); + if (s0 != 0) { + if (last0 != 0 && s0 != last0) { + fx++; + test(P0[k] == 0, "F12 F7 reversing X has P == 0"); + } + last0 = s0; + } + if (s1 != 0) { + if (last1 != 0 && s1 != last1) { + fy++; + test(P1[k] == 0, "F12 F7 reversing Y has P == 0"); + } + last1 = s1; + } + } + } + test(fx >= 2 && fy >= 2, "F12 F7 both axes reverse at the circle extrema"); + + SimPort px(4000, 16), py(4000, 16); + FasNAxisConfig cfg; + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = (uint16_t)cap; + FasNAxis<2, 512, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F12 F7 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F12 F7 addAxis(1)"); + OvershootPolyResult res; + run_overshoot_polyline(px, py, path, wp, n + 1, "f7", + "FasNAxis F7 Overshoot circle r=1600", true, &res); + test(res.end[0] == wp[2 * n] - wp[0] && res.end[1] == wp[2 * n + 1] - wp[1], + "F12 F7 closes the circle (net zero)"); + test(res.all_vertices && res.n_vertices == n, + "F12 F7 every chord vertex sampled"); + test(res.max_d2 <= 64.0 + 1e-9, "F12 F7 chord d^2 <= 64"); + test(res.underrun == false, "F12 F7 no underrun"); + // Per-axis performed ramp-up: the reported P must not be a single binder + // scalar mirrored onto both axes (that is what made the F7/F8 plot jump at + // every chord). Each axis has its own P, bounded by its own P_stop. + { + uint32_t pc0 = RampMap(ticks[0], accel[0]).P_coast(); + uint32_t pc1 = RampMap(ticks[1], accel[1]).P_coast(); + test(res.max_axis_p[0] <= pc0 + 2 && res.max_axis_p[1] <= pc1 + 2, + "F12 F7 per-axis P is bounded by that axis's P_stop"); + test(res.p_per_axis, "F12 F7 performed ramp-up is per-axis"); + test(res.scalar_eq_binder, + "F12 F7 performedRampUp() is the binder axis's P"); + } + printf("F12 F7 circle: ovs=%u max_d2=%.3f maxP=(%u,%u) per_axis=%d\n", + px.clock(), res.max_d2, res.max_axis_p[0], res.max_axis_p[1], + res.p_per_axis ? 1 : 0); + } + + printf("F6/F6b/F7 Overshoot corners green\n"); +} + +// --------------------------------------------------------------------------- +// Step 13 — dwell, starve, underrun, lookahead speed cap (F11, F13, F19). +// +// The speed cap is how remaining_path_steps treats the last buffered point of +// an open path as rest (section 8.2 / 14.7); this step exposes it through +// isSpeedLimitedByLookahead() / lookaheadHint() and adds a dwell block plus a +// real starve underrun. No LookaheadTooShort status: a short lookahead slows +// the track (F11/F19), it does not error. +// --------------------------------------------------------------------------- +void f13_lookahead() { + const uint32_t accel = 2000; + const uint32_t P_coast = RampMap(4000, accel).P_coast(); + + // --- Dwell: (0,0) -> (400,0), 80000-tick dwell, then (800,0). ------------- + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> unsynced(cfg, + sim_engine); + unsynced.addAxis(0, &px); + unsynced.addAxis(1, &py); + test(unsynced.addDwellTicks(100) == false, + "F13 dwell addDwellTicks before a sync is illegal"); + + // Baseline: a standalone 400-step rest-to-rest run. The dwell fixture is + // two of those runs separated by exactly 80000 ticks of pauses, so the + // total clock pins both the dwell length and the P == 0 restart. + uint32_t base_clock = 0; + { + SimPort bx(4000), by(4000); + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> bpath(cfg, + sim_engine); + bpath.addAxis(0, &bx); + bpath.addAxis(1, &by); + int32_t cur[2] = {0, 0}; + bpath.setCurrentPosition(cur); + int32_t t[2] = {400, 0}; + bpath.addWaypoint(t); + bpath.endPath(); + bpath.pump(); + while (bpath.isBusy()) { + bx.drain_one(); + by.drain_one(); + bpath.pump(); + } + base_clock = bx.clock(); + test(bx.position() == 400 && by.position() == 0, + "F13 dwell baseline ends at 400"); + } + + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F13 dwell addAxis(0)"); + test(path.addAxis(1, &py) == true, "F13 dwell addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t a[2] = {400, 0}; + int32_t b[2] = {800, 0}; + test(path.addWaypoint(a) == true, "F13 dwell first addWaypoint"); + test(path.addDwellTicks(0) == true, "F13 dwell zero dwell is legal"); + test(path.block_count() == 1, "F13 dwell zero dwell records no block"); + test(path.addDwellTicks(80000) == true, "F13 dwell addDwellTicks"); + test(path.addWaypoint(b) == true, "F13 dwell second addWaypoint"); + test(path.block_count() == 3, "F13 dwell records 3 blocks"); + path.endPath(); + path.pump(); + bool at_400 = false; + bool past_400 = false; + bool held_400 = true; + while (path.isBusy()) { + int64_t s0 = 0; + int64_t s1 = 0; + bool u0 = true; + bool u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + if (!at_400 && px.position() == 400) { + at_400 = true; + } else if (at_400 && !past_400 && s0 != 0) { + past_400 = true; + } else if (at_400 && !past_400 && px.position() != 400) { + held_400 = false; + } + path.pump(); + } + test(at_400 && past_400, "F13 dwell reached 400 and left it"); + test(held_400, "F13 dwell position holds (400,0) through the dwell"); + test(px.clock() == 2 * base_clock + 80000, + "F13 dwell lasts exactly 80000 ticks of clock (two baseline halves)"); + test(px.clock() == py.clock(), "F13 dwell axes stay in lockstep"); + test(px.position() == 800 && py.position() == 0, "F13 dwell end on target"); + test(path.hasUnderrun() == false, "F13 dwell no underrun"); + printf("F13 dwell: base=%u dwell_run=%u (2*base+80000=%u)\n", base_clock, + px.clock(), 2 * base_clock + 80000); + } + + // --- F11: one 800-step chunk caps the speed; ten chunks recover. ---------- + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2] = {800, 0}; + path.addWaypoint(t); // open path: no endPath + PumpStatus first = path.pump(); + test(first == PumpStatus::Running, + "F13 F11 first pump returns Running on an open path"); + test(path.isSpeedLimitedByLookahead(), + "F13 F11 one 800-step chunk caps the speed (R < P_stop)"); + uint32_t peak = 0; + bool p_le_r = true; + while (path.isBusy()) { + px.drain_one(); + py.drain_one(); + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + if (P > peak) { + peak = P; + } + if (P > R) { + p_le_r = false; + } + path.pump(); + } + test(p_le_r, "F13 F11 P <= R on every sample"); + test(peak == 400, "F13 F11 peak P == R/2 (400 of 800, under P_stop)"); + test(peak < P_coast, "F13 F11 capped peak stays under P_stop"); + test(px.position() == 800 && py.position() == 0, + "F13 F11 capped run ends at the buffered point"); + test(path.hasUnderrun() == false, "F13 F11 capped run has no underrun"); + printf("F13 F11 capped: peak_P=%u (R/2=400) P_coast=%u\n", peak, P_coast); + } + + // --- F11 recovery: ten 800-step chunks buffered, R at the head is 8000. --- + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2]; + for (int k = 1; k <= 10; k++) { + t[0] = 800 * k; + t[1] = 0; + path.addWaypoint(t); + } + path.pump(); + test(path.performedRampUp() + path.remainingToStop() == 8000, + "F13 F11 R at the head is 8000"); + test(path.remainingToStop() >= P_coast, + "F13 F11 R >= P_stop once ten chunks are buffered"); + test(!path.isSpeedLimitedByLookahead(), + "F13 F11 R >= P_stop is not lookahead-limited"); + uint8_t hint_axis = 0xFF; + uint32_t hint_R = 0; + uint32_t hint_stop = 0; + uint16_t hint_h = 0; + path.lookaheadHint(&hint_axis, &hint_R, &hint_stop, &hint_h); + test(hint_axis == path.masterAxis(), + "F13 F11 lookaheadHint axis == master"); + test(hint_R == path.remainingToStop(), "F13 F11 lookaheadHint R"); + test(hint_stop == P_coast, "F13 F11 lookaheadHint P_stop"); + test(hint_h == 64, "F13 F11 lookaheadHint HORIZON"); + NaxisPlot plot; + plot.start_scalar("f11", "FasNAxis F11 speed cap then recovery (P vs R)"); + uint32_t peak = 0; + bool p_le_r = true; + while (path.isBusy()) { + px.drain_one(); + py.drain_one(); + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + if (P > peak) { + peak = P; + } + if (P > R) { + p_le_r = false; + } + plot.scalar_row((double)px.clock() / NAXIS_PLOT_TICKS_PER_S, (double)P, + (double)R); + path.pump(); + } + plot.finish_scalar(0.0, (double)px.clock() / NAXIS_PLOT_TICKS_PER_S, + "time [s]", "steps", "P performed ramp-up", + "R remaining to stop"); + test(peak + 64 >= P_coast && peak <= P_coast, + "F13 F11 recovery reaches P_stop within the log2 band"); + test(peak > 400, "F13 F11 recovery peak exceeds the capped peak"); + test(p_le_r, "F13 F11 recovery P <= R on every sample"); + test(px.position() == 8000 && py.position() == 0, + "F13 F11 recovery ends at 8000"); + test(path.hasUnderrun() == false, "F13 F11 recovery has no underrun"); + printf("F13 F11 recovery: peak_P=%u == P_coast=%u\n", peak, P_coast); + printf("F11 scalar plot written: test_26_f11.gnuplot\n"); + } + + // --- F13: starve the queues after kick-off, no pump in between. ----------- + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2] = {10000, 0}; + path.addWaypoint(t); + path.endPath(); + PumpStatus st = path.pump(); + test(st == PumpStatus::Running, "F13 F1 first pump returns Running"); + test(!px.isQueueEmpty() && !py.isQueueEmpty(), + "F13 kick-off has happened (queues are prefilled)"); + NaxisPlot plot; + plot.start_plot("f13", "FasNAxis F13 underrun (samples before the starve)", + 2); + plot.poly_point(0.0, 0.0); + plot.poly_point((double)t[0], (double)t[1]); + plot.poly_done(); + for (int k = 0; k < 200; k++) { + int64_t s0 = 0; + int64_t s1 = 0; + bool u0 = true; + bool u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + double tt = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + uint32_t ticks = path.lastTicks(); + double v = ticks > 0 ? NAXIS_PLOT_TICKS_PER_S / (double)ticks : 0.0; + double speed[2] = {v, v}; + double Pcol[2] = {(double)path.performedRampUp(), + (double)path.performedRampUp()}; + double Rcol[2] = {(double)path.remainingToStop(), + (double)path.remainingToStop()}; + double tcol[2] = {(double)ticks, (double)ticks}; + plot.row(tt, (double)px.position(), (double)py.position(), 0.0, speed, + Pcol, Rcol, tcol); + path.pump(); + } + plot.finish_plot(); + px.drain(); + py.drain(); + test(px.isQueueEmpty() && py.isQueueEmpty(), + "F13 both queues drained to empty without pump"); + test(path.hasUnderrun(), "F13 hasUnderrun after the starve drain"); + test(path.pump() == PumpStatus::Underrun, + "F13 pump() returns Underrun after the starve"); + printf("F13 underrun plot written: test_26_f13.gnuplot\n"); + } + + // --- F19: HORIZON 4 micro-segments cap P; one long block still coasts. ---- + { + static double f19_t_a[512]; + static double f19_p_a[512]; + int n_a = 0; + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 4, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, + "F13 F19 addAxis(0) succeeds at HORIZON 4"); + test(path.addAxis(1, &py) == true, "F13 F19 addAxis(1) succeeds"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2]; + for (int k = 1; k <= 4; k++) { + t[0] = 50 * k; + t[1] = 0; + test(path.addWaypoint(t) == true, "F13 F19 addWaypoint fits HORIZON 4"); + } + path.pump(); + test(path.isSpeedLimitedByLookahead(), + "F13 F19 HORIZON 4 micro-segments cap the speed"); + uint32_t peak_a = 0; + bool p_le_r_a = true; + while (path.isBusy()) { + px.drain_one(); + py.drain_one(); + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + if (P > peak_a) { + peak_a = P; + } + if (P > R) { + p_le_r_a = false; + } + if (n_a < 512) { + f19_t_a[n_a] = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + f19_p_a[n_a] = (double)P; + n_a++; + } + path.pump(); + } + test(p_le_r_a, "F13 F19 micro-segment run P <= R"); + test(peak_a < P_coast, + "F13 F19 micro-segments never reach P_stop (HORIZON caps R)"); + test(px.position() == 200 && py.position() == 0, + "F13 F19 micro-segment run ends at 200"); + + static double f19_t_b[16384]; + static double f19_p_b[16384]; + int n_b = 0; + SimPort qx(4000), qy(4000); + FasNAxis<2, 4, SimPort, TestStepperMotionEngine> path2(cfg, sim_engine); + path2.addAxis(0, &qx); + path2.addAxis(1, &qy); + int32_t cur2[2] = {0, 0}; + path2.setCurrentPosition(cur2); + int32_t big[2] = {10000, 0}; + path2.addWaypoint(big); + path2.endPath(); + path2.pump(); + test(path2.remainingToStop() >= P_coast, + "F13 F19 one long block has R >= P_stop at the same HORIZON"); + uint32_t peak_b = 0; + bool p_le_r_b = true; + while (path2.isBusy()) { + qx.drain_one(); + qy.drain_one(); + uint32_t P = path2.performedRampUp(); + uint32_t R = path2.remainingToStop(); + if (P > peak_b) { + peak_b = P; + } + if (P > R) { + p_le_r_b = false; + } + if (n_b < 16384) { + f19_t_b[n_b] = (double)qx.clock() / NAXIS_PLOT_TICKS_PER_S; + f19_p_b[n_b] = (double)P; + n_b++; + } + path2.pump(); + } + test(p_le_r_b, "F13 F19 long-block run P <= R"); + test(peak_b == P_coast, + "F13 F19 one long block reaches P_stop (coast) at HORIZON 4"); + test(qx.position() == 10000 && qy.position() == 0, + "F13 F19 long-block run ends at 10000"); + + NaxisPlot plot; + plot.start_scalar( + "f19", "FasNAxis F19 HORIZON 4: micro-segment cap vs long-block coast"); + int n = n_b > n_a ? n_b : n_a; + for (int k = 0; k < n; k++) { + double x = k < n_b ? f19_t_b[k] : f19_t_b[n_b - 1]; + double a = k < n_b ? f19_p_b[k] : 0.0; + double b = k < n_a ? f19_p_a[k] : 0.0; + plot.scalar_row(x, a, b); + } + plot.finish_scalar(0.0, f19_t_b[n_b - 1], "time [s]", "P [steps]", + "P one 10000-step block (coasts)", + "P four 50-step blocks (capped)"); + printf("F13 F19: peak capped=%u peak long=%u P_coast=%u\n", peak_a, peak_b, + P_coast); + printf("F19 scalar plot written: test_26_f19.gnuplot\n"); + } + + printf("Dwell/F11/F13/F19 lookahead cap and underrun green\n"); +} + +// --------------------------------------------------------------------------- +// Step 14 — 3-axis SimPort helix (F8). +// +// Helix: 240 chords, radius 8000, one full turn, Z increases by 10 steps per +// chord. Run twice: mode = Linear and mode = Overshoot with overshoot_max = 8. +// Assert each vertex is hit on all three axes, every drained step has tick sum +// >= 4000, the Linear ring never path-stops at an interior vertex, both modes +// keep the realized path speed within 2x between extrema (measured from the +// drained steps/clock, not the binder-global lastTicks), and Overshoot d² in +// XY <= 64. +// --------------------------------------------------------------------------- +void f14_helix() { + // A smooth ring must keep every joint inside the 2 deg collinear band after + // the integer rounding. At radius 1600 / 180 chords the nominal 2 deg step + // plus up to ~0.5 deg of rounding noise lands ~60% of the joints *outside* + // the band, so Linear path-stops at those vertices and the ring is not + // smooth. Radius 8000 / 240 chords puts the worst joint at 1.92 deg, safely + // inside the band, so the whole turn is one collinear cruise. + const int n_chords = 240; + const int32_t radius = 8000; + const uint32_t ticks = 4000; + const uint16_t cap = 8; + + // Helix waypoints: integer XY via the F20 rounding, Z = 10 per chord. The + // points are relative to the first vertex so the SimPort's physical origin + // (0) is the path origin (Step 14; no SimPort setter). + static int32_t wp[(n_chords + 1) * 3]; + const int32_t origin_x = iround(radius * cos(0.0)); + const int32_t origin_y = iround(radius * sin(0.0)); + for (int k = 0; k <= n_chords; k++) { + double a = 2.0 * M_PI * (double)k / (double)n_chords; + wp[3 * k] = iround(radius * cos(a)) - origin_x; + wp[3 * k + 1] = iround(radius * sin(a)) - origin_y; + wp[3 * k + 2] = 10 * k; + } + + struct HelixResult { + int32_t end[3]; + uint32_t clock; + int n_vertices; + bool all_vertices; + double max_d2_xy; + bool min_tick_ok; + bool underrun; + int rest_events; + double mid_speed_min; + double mid_speed_max; + }; + + auto run_helix = [&](SimPort& px, SimPort& py, SimPort& pz, + FasNAxisConfig::Mode mode, uint16_t overshoot_max, + const char* fixture, bool do_plot, NaxisPlot* xzplot, + const char* html_fixture, HelixResult* res) { + res->end[0] = 0; + res->end[1] = 0; + res->end[2] = 0; + res->clock = 0; + res->n_vertices = 0; + res->all_vertices = false; + res->max_d2_xy = 0.0; + res->min_tick_ok = true; + res->underrun = false; + res->rest_events = 0; + res->mid_speed_min = 0.0; + res->mid_speed_max = 0.0; + + FasNAxisConfig cfg; + if (mode == FasNAxisConfig::Overshoot) { + cfg.mode = FasNAxisConfig::Overshoot; + cfg.overshoot_max = overshoot_max; + } + + FasNAxis<3, 4096, SimPort, TestStepperMotionEngine> path(cfg, + sim_engine); + test(path.addAxis(0, &px) == true, "F14 addAxis X"); + test(path.addAxis(1, &py) == true, "F14 addAxis Y"); + test(path.addAxis(2, &pz) == true, "F14 addAxis Z"); + + int32_t cur[3] = {wp[0], wp[1], wp[2]}; + path.setCurrentPosition(cur); + for (int k = 1; k <= n_chords; k++) { + int32_t t[3] = {wp[3 * k], wp[3 * k + 1], wp[3 * k + 2]}; + test(path.addWaypoint(t) == true, "F14 addWaypoint fits"); + } + path.endPath(); + path.pump(); + + NaxisPlot plot; + if (do_plot) { + plot.start_plot(fixture, "FasNAxis F8 helix 3-axis", 3); + plot.poly_point((double)wp[0], (double)wp[1]); + for (int k = 1; k <= n_chords; k++) { + plot.poly_point((double)wp[3 * k], (double)wp[3 * k + 1]); + } + plot.poly_done(); + } +#ifdef FAS_NAXIS_TRACE + NaxisHtmlDump html(html_fixture != NULL ? html_fixture : fixture, + "FasNAxis F8 helix 3-axis"); +#endif + + // chord is the index of the next vertex to reach (1..n_chords). All three + // axes land on the vertex together, so the check is per command. + int chord = 1; + int iter = 0; + const bool linear_mode = (mode != FasNAxisConfig::Overshoot); + bool have_p = false; + // Realized-speed sampling: positions/clock one plot sample back, so a + // per-axis speed comes from actual steps over actual ticks rather than the + // binder-global lastTicks()/performedRampUp() (which are not per-axis in + // Overshoot; non-binding axes issue multi-step catch-up commands). + int32_t ps_x = 0, ps_y = 0, ps_z = 0; + uint32_t ps_clock = 0; + bool have_sample = false; + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0, s2 = 0; + bool u0 = true, u1 = true, u2 = true; + uint32_t t0 = px.drain_one(&s0, &u0); + uint32_t t1 = py.drain_one(&s1, &u1); + uint32_t t2 = pz.drain_one(&s2, &u2); + + // Every drained step command must have a tick sum >= ticks_cfg. + if (s0 != 0 && t0 < ticks) res->min_tick_ok = false; + if (s1 != 0 && t1 < ticks) res->min_tick_ok = false; + if (s2 != 0 && t2 < ticks) res->min_tick_ok = false; + + int32_t x = px.position(); + int32_t y = py.position(); + int32_t z = pz.position(); + + if (chord <= n_chords) { + int32_t ax = wp[3 * (chord - 1)]; + int32_t ay = wp[3 * (chord - 1) + 1]; + int32_t bx = wp[3 * chord]; + int32_t by = wp[3 * chord + 1]; + double vx = (double)(bx - ax), vy = (double)(by - ay); + double l2 = vx * vx + vy * vy; + if (l2 > 0.0) { + double cross = vx * (double)(y - ay) - vy * (double)(x - ax); + double d2 = cross * cross / l2; + if (d2 > res->max_d2_xy) { + res->max_d2_xy = d2; + } + } + if (x == bx && y == by && z == wp[3 * chord + 2]) { + res->n_vertices++; + chord++; + } + } + + // Smoothness: on a collinear ring a continuing Linear run carries P + // across every interior joint, so performedRampUp() stays non-zero from + // the first ramped step until the final deceleration. A path-stop at an + // interior vertex shows up as P == 0 here. + if (linear_mode) { + uint32_t P_now = path.performedRampUp(); + if (P_now > 0) { + have_p = true; + } else if (have_p && chord < n_chords) { + res->rest_events++; + } + } + + double tt = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + // Sample realized per-axis speed/period (and the path speed) every 32nd + // command from the actual position/clock advance. lastTicks() / + // performedRampUp() are binder-global and not per-axis in Overshoot, so + // plotting them per axis shows fictitious jumps; the drained steps over + // the elapsed clock are the real motion. A 32-command window spans the + // Overshoot catch-up bursts (up to the 65535-tick split), so the window + // speed is the path's real speed rather than its per-command aliasing. + if (iter % 32 == 0) { + uint32_t clk = px.clock(); + if (have_sample) { + double dt = (double)(clk - ps_clock) / NAXIS_PLOT_TICKS_PER_S; + double ddx = (double)(x - ps_x); + double ddy = (double)(y - ps_y); + double ddz = (double)(z - ps_z); + double dist = sqrt(ddx * ddx + ddy * ddy + ddz * ddz); + double path_v = dt > 0.0 ? dist / dt : 0.0; + // Middle half of the turn: excludes the start/end ramps, includes + // the X and Y extrema. A smooth ring keeps the path speed from + // collapsing there. + if (chord >= n_chords / 4 && chord <= (3 * n_chords) / 4) { + if (res->mid_speed_max == 0.0 || path_v < res->mid_speed_min) { + res->mid_speed_min = path_v; + } + if (path_v > res->mid_speed_max) { + res->mid_speed_max = path_v; + } + } + if (do_plot) { + double d[3] = {ddx, ddy, ddz}; + double speed[3]; + double tcol[3]; + for (int i = 0; i < 3; i++) { + speed[i] = dt > 0.0 ? d[i] / dt : 0.0; + tcol[i] = + d[i] != 0.0 ? dt * NAXIS_PLOT_TICKS_PER_S / fabs(d[i]) : 0.0; + } + // Per-axis P/R: in Overshoot each axis has its own P, so mirroring + // the binder scalar would jump at every chord. + double Pcol[3] = {(double)path.performedRampUpAxis(0), + (double)path.performedRampUpAxis(1), + (double)path.performedRampUpAxis(2)}; + double Rcol[3] = {(double)path.remainingToStopAxis(0), + (double)path.remainingToStopAxis(1), + (double)path.remainingToStopAxis(2)}; + plot.row(tt, (double)x, (double)y, 0.0, speed, Pcol, Rcol, tcol); + } + } + ps_x = x; + ps_y = y; + ps_z = z; + ps_clock = clk; + have_sample = true; + } + if (xzplot != NULL && (iter % 4 == 0)) { + xzplot->scalar_row(tt, (double)x, (double)z); + } +#ifdef FAS_NAXIS_TRACE + if (html_fixture != NULL && (iter % 4 == 0)) { + html.row(tt, (double)x, (double)y, (double)z); + } +#endif + iter++; + path.pump(); + } + + if (do_plot) { + plot.finish_plot(); + } +#ifdef FAS_NAXIS_TRACE + if (html_fixture != NULL) { + html.finish(); + } +#endif + res->end[0] = px.position(); + res->end[1] = py.position(); + res->end[2] = pz.position(); + res->clock = px.clock(); + res->all_vertices = (chord == n_chords + 1); + res->underrun = path.hasUnderrun(); + }; + + // --- Linear mode ----------------------------------------------------------- + { + SimPort px(4000, 16), py(4000, 16), pz(4000, 16); + HelixResult res; + NaxisPlot xz; + xz.start_scalar("f8_xz", "FasNAxis F8 helix X vs Z"); + run_helix(px, py, pz, FasNAxisConfig::Linear, 0, "f8", true, &xz, "F8", + &res); + xz.finish_scalar(0.0, (double)res.clock / NAXIS_PLOT_TICKS_PER_S, + "time [s]", "steps", "X position", "Z position"); + + test(res.end[0] == wp[3 * n_chords] && res.end[1] == wp[3 * n_chords + 1] && + res.end[2] == wp[3 * n_chords + 2], + "F14 Linear ends at last vertex on all axes"); + test(res.all_vertices && res.n_vertices == n_chords, + "F14 Linear every vertex hit on all axes"); + test(res.min_tick_ok, "F14 Linear every step has tick sum >= 4000"); + test(res.rest_events == 0, + "F14 Linear ring never rests between interior vertices (smooth)"); + test( + res.mid_speed_max > 0.0 && res.mid_speed_min * 2.0 >= res.mid_speed_max, + "F14 Linear path speed stays smooth between extrema"); + test(res.underrun == false, "F14 Linear no underrun"); + printf("F14 Linear helix: clock=%u vertices=%d/%d rest=%d v=[%.0f:%.0f]\n", + res.clock, res.n_vertices, n_chords, res.rest_events, + res.mid_speed_min, res.mid_speed_max); + } + + // --- Overshoot mode -------------------------------------------------------- + { + SimPort px(4000, 16), py(4000, 16), pz(4000, 16); + HelixResult res; + run_helix(px, py, pz, FasNAxisConfig::Overshoot, cap, "f8_ovs", true, NULL, + NULL, &res); + + test(res.end[0] == wp[3 * n_chords] && res.end[1] == wp[3 * n_chords + 1] && + res.end[2] == wp[3 * n_chords + 2], + "F14 Overshoot ends at last vertex on all axes"); + test(res.all_vertices && res.n_vertices == n_chords, + "F14 Overshoot every vertex hit on all axes"); + test(res.min_tick_ok, "F14 Overshoot every step has tick sum >= 4000"); + test(res.max_d2_xy <= 64.0 + 1e-9, "F14 Overshoot d² in XY <= 64"); + printf( + "F14 Overshoot helix: clock=%u vertices=%d/%d max_d2=%.3f " + "v=[%.0f:%.0f]\n", + res.clock, res.n_vertices, n_chords, res.max_d2_xy, res.mid_speed_min, + res.mid_speed_max); + test( + res.mid_speed_max > 0.0 && res.mid_speed_min * 2.0 >= res.mid_speed_max, + "F14 Overshoot path speed stays smooth between extrema"); + test(res.underrun == false, "F14 Overshoot no underrun"); + } + +#ifdef FAS_NAXIS_TRACE + { + char html_path[256]; + snprintf(html_path, sizeof(html_path), "%s/tests/out/F8.html", + NAXIS_HTML_ROOT); + test(gnuplot_has(html_path, "id=\"trace\""), + "F14 F8 HTML trace page written"); + printf("F14 HTML trace written: %s\n", html_path); + } +#endif + + printf("F14 3-axis helix green\n"); +} + +#ifdef FAS_PHYSICAL_STEPPER_ENABLED +// Peak absolute PCM sample in a wav file's data chunk (0 if silent/absent). +static int phys_wav_peak(const char* path) { + FILE* f = fopen(path, "rb"); + if (f == NULL) { + return 0; + } + char hdr[44]; + if (fread(hdr, 1, 44, f) != 44) { + fclose(f); + return 0; + } + int peak = 0; + int16_t s; + while (fread(&s, 2, 1, f) == 1) { + int v = s < 0 ? -s : s; + if (v > peak) { + peak = v; + } + } + fclose(f); + return peak; +} + +static void wav_u16le(FILE* f, uint16_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); +} +static void wav_u32le(FILE* f, uint32_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); + fputc((int)((v >> 16) & 0xff), f); + fputc((int)((v >> 24) & 0xff), f); +} + +// Mix two axes' recorded PCM into one 16-bit stereo wav: X is the left channel, +// Y the right. Both plants run on the same SimPort clock so their sample +// streams are time-aligned; a shorter one is zero-padded. +static bool write_stereo_wav(const char* path, const PhysicalStepper& left, + const PhysicalStepper& right, + uint32_t sr = 44100) { + uint32_t n = left.audio_sample_count(); + if (right.audio_sample_count() > n) { + n = right.audio_sample_count(); + } + FILE* fp = fopen(path, "wb"); + if (fp == NULL) { + return false; + } + const uint16_t bps = 16, ch = 2; + const uint32_t byteRate = sr * ch * bps / 8; + const uint16_t blockAlign = ch * bps / 8; + const uint32_t dataSize = n * ch * bps / 8; + fwrite("RIFF", 1, 4, fp); + wav_u32le(fp, 36 + dataSize); + fwrite("WAVE", 1, 4, fp); + fwrite("fmt ", 1, 4, fp); + wav_u32le(fp, 16); + wav_u16le(fp, 1); // PCM + wav_u16le(fp, ch); + wav_u32le(fp, sr); + wav_u32le(fp, byteRate); + wav_u16le(fp, blockAlign); + wav_u16le(fp, bps); + fwrite("data", 1, 4, fp); + wav_u32le(fp, dataSize); + for (uint32_t i = 0; i < n; i++) { + wav_u16le(fp, (uint16_t)left.audio_sample(i)); + wav_u16le(fp, (uint16_t)right.audio_sample(i)); + } + fclose(fp); + return true; +} + +// Physical-motor multi-panel figure for F21, from the two plants' traces +// (test_27 style). Dat columns: 1:t 2:x 3:x_c 4:delta 5:w 6:a 7:tau +// 8:friction 9:stall 10:phase. +static void write_phys_gnuplot() { + FILE* g = fopen("test_26_f21_phys.gnuplot", "w"); + if (g == NULL) { + return; + } + fprintf( + g, + "set term pngcairo size 1600,1400\n" + "set output \"test_26_f21_phys.gnuplot.png\"\n" + "set multiplot layout 3,2 title \"F21 PhysicalStepper: X (left) / Y " + "(right) rotor\"\n" + "set xlabel \"t [s]\"\n" + "set title \"rotor and commanded position [steps]\"\n" + "plot \"test_26_f21_x.dat\" using 1:2 with lines title \"X rotor\", " + "\"test_26_f21_y.dat\" using 1:2 with lines title \"Y rotor\", " + "\"test_26_f21_x.dat\" using 1:3 with lines dt 2 title \"X cmd\", " + "\"test_26_f21_y.dat\" using 1:3 with lines dt 2 title \"Y cmd\"\n" + "set title \"rotor speed [steps/s]\"\n" + "plot \"test_26_f21_x.dat\" using 1:5 with lines title \"X w\", " + "\"test_26_f21_y.dat\" using 1:5 with lines title \"Y w\"\n" + "set title \"step error x - x_c [steps]\"\n" + "plot \"test_26_f21_x.dat\" using 1:4 with lines title \"X delta\", " + "\"test_26_f21_y.dat\" using 1:4 with lines title \"Y delta\"\n" + "set title \"magnetic force tau\"\n" + "plot \"test_26_f21_x.dat\" using 1:7 with lines title \"X tau\", " + "\"test_26_f21_y.dat\" using 1:7 with lines title \"Y tau\"\n" + "set title \"friction force\"\n" + "plot \"test_26_f21_x.dat\" using 1:8 with lines title \"X friction\", " + "\"test_26_f21_y.dat\" using 1:8 with lines title \"Y friction\"\n" + "set title \"stall observation (1 = slipping)\"\n" + "set yrange [0:1.1]\nset ytics 0,0.5,1\n" + "plot \"test_26_f21_x.dat\" using 1:9 with lines title \"X stall\", " + "\"test_26_f21_y.dat\" using 1:9 with lines title \"Y stall\"\n" + "unset yrange\nunset multiplot\nunset output\n"); + fclose(g); +} + +// F21 (physical_stepper_whitepaper sections 2.2 / 13.3): couple the FasNAxis +// planner to the opt-in rotordynamic plant. Each axis's SimPort gets a +// PhysicalStepper, so the commands the feeder emits drive a real rotor: the +// planner still binds against the ideal commanded count (position()), while +// the plant supplies the realized, lagging position and the acoustic +// emission. The F5 Linear square (1600 steps per side, ticks 4000, accel +// 2000) is driven with a plant on X and Y; the realized path, the +// commanded-minus-realized deviation and the rotor speeds are plotted +// (test_26_f21.gnuplot), the full physical trace (position/error/speed/accel/ +// force/friction/stall) is written to test_26_f21_phys.gnuplot, and the audio +// is one stereo wav (X left, Y right). F21 is the only fixture that attaches a +// plant, so the default suite stays bit-identical. +void f21_physical() { + int32_t verts[5][2] = {{0, 0}, {1600, 0}, {1600, 1600}, {0, 1600}, {0, 0}}; + + SimPort px(4000), py(4000); + PhysicalStepper rotor_x, rotor_y; + px.setPhysicalStepper(&rotor_x); + py.setPhysicalStepper(&rotor_y); + test(px.hasPhysical() && py.hasPhysical(), "F21 plant attached to both axes"); + + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F21 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F21 addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + + NaxisPlot plot; + plot.start_plot("f21", "FasNAxis F21 physical-stepper square 1600 Linear", 2); + for (int k = 0; k < 5; k++) { + plot.poly_point((double)verts[k][0], (double)verts[k][1]); + } + plot.poly_done(); + + for (int k = 1; k < 5; k++) { + test(path.addWaypoint(verts[k]) == true, "F21 addWaypoint fits"); + } + path.endPath(); + + double max_dx = 0.0, max_dy = 0.0, max_dev = 0.0; + double max_vx = 0.0, max_vy = 0.0; + int64_t iter = 0; + // Record the rotordynamic traces (position/error/speed/accel/force/friction/ + // stall) for the physical-motor figure. + rotor_x.trace_begin(2); + rotor_y.trace_begin(2); + // Drain the two queues in lockstep, exactly as run_linear_segment does; the + // plant advances once per consumed command, so its clock tracks px.clock(). + while (path.isBusy()) { + int64_t s0 = 0, s1 = 0; + bool u0 = true, u1 = true; + px.drain_one(&s0, &u0); + py.drain_one(&s1, &u1); + + double cx = (double)px.position(); + double cy = (double)py.position(); + double rx = rotor_x.x(); + double ry = rotor_y.x(); + double dx = cx - rx; + double dy = cy - ry; + double dev = sqrt(dx * dx + dy * dy); + if (fabs(dx) > max_dx) max_dx = fabs(dx); + if (fabs(dy) > max_dy) max_dy = fabs(dy); + if (dev > max_dev) max_dev = dev; + double vx = rotor_x.speed(); + double vy = rotor_y.speed(); + if (vx > max_vx) max_vx = vx; + if (vy > max_vy) max_vy = vy; + + if (iter % 4 == 0) { + uint32_t P = path.performedRampUp(); + uint32_t R = path.remainingToStop(); + uint32_t ticks = path.lastTicks(); + double t = (double)px.clock() / NAXIS_PLOT_TICKS_PER_S; + double speed[2] = {vx, vy}; + double Pcol[2] = {(double)P, (double)P}; + double Rcol[2] = {(double)R, (double)R}; + double tcol[2] = {(double)ticks, (double)ticks}; + // Panel 1 draws the realized rotor path ($data 2:3) on top of the grey + // commanded polyline; column 4 is the commanded-minus-realized radius. + plot.row(t, rx, ry, dev, speed, Pcol, Rcol, tcol); + } + iter++; + path.pump(); + } + plot.finish_plot(); + + // Physical-motor panels (test_27 style) and the stereo wav (X left, Y right). + size_t rows_x = rotor_x.trace_dump("test_26_f21_x.dat"); + size_t rows_y = rotor_y.trace_dump("test_26_f21_y.dat"); + write_phys_gnuplot(); + bool wav = write_stereo_wav("test_26_f21.wav", rotor_x, rotor_y); + int peak = phys_wav_peak("test_26_f21.wav"); + test(rows_x > 100 && rows_y > 100, + "F21 physical trace rows written for both rotors"); + printf("F21 physical panels: test_26_f21_phys.gnuplot (%zu/%zu rows)\n", + rows_x, rows_y); + + printf( + "F21 physical square: max|dx|=%.3f max|dy|=%.3f max_dev=%.3f " + "peak_v=(%.0f,%.0f) stall=(%d,%d) wav_peak=%d\n", + max_dx, max_dy, max_dev, max_vx, max_vy, rotor_x.stall_ever() ? 1 : 0, + rotor_y.stall_ever() ? 1 : 0, peak); + + test(!rotor_x.stall_ever() && !rotor_y.stall_ever(), + "F21 no rotor loses synchronism on the square"); + test(max_dx < 64.0 && max_dy < 64.0, + "F21 per-axis lag stays under one full step"); + test(max_vx > 1000.0 && max_vy > 1000.0, + "F21 both rotors reach a real square-side speed"); + test(abs(rotor_x.getCurrentPosition()) <= 2 && + abs(rotor_y.getCurrentPosition()) <= 2, + "F21 realized position returns to the origin"); + test(path.hasUnderrun() == false, "F21 no underrun"); + test(wav, "F21 the stereo wav was written"); + test(peak > 1000, "F21 the recorded wav carries audible signal, not silence"); + printf( + "F21 plot written: test_26_f21.gnuplot; wav (stereo X=left Y=right): " + "test_26_f21.wav\n"); +} + +// F20 through the physical plant: the same polyline (random walk + collinear +// half-circle + random walk) is fed to a plant on each axis solely to render +// the motor sound. test_26_f20.wav is stereo (X left, Y right). +static void f20_physical_wav() { + int32_t blocks[512][2]; + int32_t sum[2]; + int n_blocks = build_f20_blocks(blocks, sum); + + SimPort px(4000), py(8000); + PhysicalStepper rotor_x, rotor_y; + px.setPhysicalStepper(&rotor_x); + py.setPhysicalStepper(&rotor_y); + FasNAxisConfig cfg; + FasNAxis<2, 512, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F20 phys addAxis(0)"); + test(path.addAxis(1, &py) == true, "F20 phys addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t wx = 0, wy = 0; + for (int b = 0; b < n_blocks; b++) { + wx += blocks[b][0]; + wy += blocks[b][1]; + int32_t t[2] = {wx, wy}; + test(path.addWaypoint(t) == true, "F20 phys addWaypoint fits"); + } + path.endPath(); + while (path.isBusy()) { + px.drain_one(); + py.drain_one(); + path.pump(); + } + bool wav = write_stereo_wav("test_26_f20.wav", rotor_x, rotor_y); + int peak = phys_wav_peak("test_26_f20.wav"); + test(wav && peak > 1000, "F20 stereo wav written and audible"); + test(!rotor_x.stall_ever() && !rotor_y.stall_ever(), + "F20 physical run does not stall"); + printf("F20 physical wav: test_26_f20.wav peak=%d blocks=%d\n", peak, + n_blocks); +} +#endif // FAS_PHYSICAL_STEPPER_ENABLED + +// --- F22: external stop of a member axis aborts the coordinated plan. ------- +// StepperMotion exposes a stop +// cause (StepperStopCause) that FasNAxis polls in pump(); a stop outside the +// planner must abort the plan (PumpStatus::Stopped, isFaulted()) rather than +// continue. +static void f22_external_stop() { + // A manual stopMove-style stop (injected cause) aborts the plan. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F22 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F22 addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2] = {10000, 10000}; + path.addWaypoint(t); + path.endPath(); + test(path.pump() == PumpStatus::Running, "F22 first pump Running"); + test(!path.isFaulted(), "F22 not faulted while running"); + + px.setStopCause(StepperStopCause::StopMove); + test(path.pump() == PumpStatus::Stopped, + "F22 pump returns Stopped on an injected stop cause"); + test(path.isFaulted(), "F22 isFaulted after external stop"); + test(path.pump() == PumpStatus::Stopped, "F22 stays Stopped while faulted"); + } + + // A real abrupt stop of one member (forceStop) aborts the plan. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2] = {10000, 0}; + path.addWaypoint(t); + path.endPath(); + test(path.pump() == PumpStatus::Running, "F22 forceStop setup Running"); + + px.forceStop(); + test(path.pump() == PumpStatus::Stopped, + "F22 pump returns Stopped after a member forceStop"); + test(px.isQueueEmpty(), "F22 forceStop aborted the member queue"); + } + + // emergencyStop() forceStops every member and faults the plan. + { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + path.addAxis(0, &px); + path.addAxis(1, &py); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + int32_t t[2] = {10000, 0}; + path.addWaypoint(t); + path.endPath(); + path.pump(); + path.emergencyStop(); + test(path.isFaulted(), "F22 emergencyStop faults the plan"); + test(px.takeStopCause() == StepperStopCause::ForceStop, + "F22 emergencyStop forceStops axis 0"); + test(py.takeStopCause() == StepperStopCause::ForceStop, + "F22 emergencyStop forceStops axis 1"); + test(path.pump() == PumpStatus::Stopped, + "F22 pump Stopped after emergencyStop"); + } + printf("F22 external stop / emergencyStop green\n"); +} + +// F23: a re-sync is self-sufficient -- it must not be undone by the next +// pump(). clear_path() clears _fault but used not to drain the pending stop +// cause, so pump()'s cause poll re-faulted the plan immediately. The ordering +// that broke was forceStop() -> syncFromSteppers() -> pump(); it only worked +// when a pump() happened first, because that pump drained the cause on its way +// to reporting Stopped. +// +// This also pins the rearm: the member queue was suspended by forceStop(), and +// clear_path() is what re-arms it. Without the rearm the re-planned path would +// plan slices that queue nothing. +static void f23_resync_is_self_sufficient() { + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, 64, SimPort, TestStepperMotionEngine> path(cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F23 addAxis(0)"); + test(path.addAxis(1, &py) == true, "F23 addAxis(1)"); + path.setCurrentPosition((const int32_t[]){0, 0}); + const int32_t t[2] = {10000, 10000}; + test(path.addWaypoint(t) == true, "F23 addWaypoint"); + path.endPath(); + test(path.pump() == PumpStatus::Running, "F23 first pump Running"); + + // Stop a member, then re-sync BEFORE any pump() observes the cause. + px.forceStop(); + path.syncFromSteppers(); + test(!path.isFaulted(), "F23 syncFromSteppers clears the fault"); + + // Re-plan and run. If the cause had not been drained, this pump() would + // return Stopped again. + const int32_t t2[2] = {20000, 20000}; + test(path.addWaypoint(t2) == true, "F23 re-plan waypoint"); + path.endPath(); + PumpStatus st = path.pump(); + test(st != PumpStatus::Stopped, + "F23 a re-sync is not undone by the next pump()"); + test(st != PumpStatus::Error, "F23 the re-planned path is accepted"); + test(!path.isFaulted(), "F23 still unfaulted after re-planning"); + printf("F23 re-sync self-sufficient green\n"); +} + +// One turn of the NaxesAFAP example helix (12 chords per quarter, 7.5 deg, not +// collinear). The master does not reverse at those chords, so the turn +// cruises. The square-corner stop is a different joint and is not in this +// polyline. +static int32_t NaxesAFAP_q_axis(int q, int16_t mag, int16_t rad, bool x_axis) { + if (x_axis) { + switch (q) { + case 0: + return rad; + case 1: + return -mag; + case 2: + return -rad; + default: + return mag; + } + } + switch (q) { + case 0: + return mag; + case 1: + return rad; + case 2: + return -mag; + default: + return -rad; + } +} + +static void f_coarse_helix_cruises() { + const int n = 4 * NAXES_QSAMPLES; + int32_t pts[49][2]; + for (int i = 0; i <= n; i++) { + int j = i % n; + int q = j / NAXES_QSAMPLES; + int k = j % NAXES_QSAMPLES; + pts[i][0] = NaxesAFAP_q_axis(q, NAXES_SIN_Q[k], NAXES_COS_Q[k], true); + pts[i][1] = NaxesAFAP_q_axis(q, NAXES_SIN_Q[k], NAXES_COS_Q[k], false); + } + Remaining rem(2, n); + for (int i = 0; i < n; i++) { + int32_t d[2] = {pts[i + 1][0] - pts[i][0], pts[i + 1][1] - pts[i][1]}; + rem.set_block(i, d); + } + test(collinear_same_sense(rem, 0, 1) == false, + "NaxesAFAP helix chord is outside the 2 deg band"); + const uint32_t ticks[2] = {4000, 4000}; + const uint32_t accel = 2000; + int32_t end_pos[2], issued[2]; + bool env = true, plr = true; + uint32_t vp[64]; + int nv = 0; + ref_walk_polyline(&rem, ticks, accel, end_pos, issued, &env, &plr, vp, &nv, + 64, NULL, NULL, NULL); + test(env && plr, "NaxesAFAP helix envelope and P <= R"); + test(nv == n, "NaxesAFAP helix has one sample per chord"); + int rests = 0; + for (int i = 2; i < n - 2; i++) { + if (vp[i] <= 1) { + rests++; + } + } + test(rests == 0, "NaxesAFAP helix interior chords cruise"); + printf("NaxesAFAP helix: chords=%d interior_rests=%d joint_P_mid=%u\n", n, + rests, vp[n / 2]); +} + +// P3: the block array must be a sliding window of at most HORIZON *pending* +// points, not a buffer that back-pressures after HORIZON points have ever +// been appended. Otherwise any path longer than HORIZON is executed in +// chunks that each ramp to rest, which is what made the NaxesAFAP example stop +// on helix chords in simavr. +static void f_sliding_ring() { + const int horizon = 4; + SimPort px(4000), py(4000); + FasNAxisConfig cfg; + FasNAxis<2, (uint16_t)horizon, SimPort, TestStepperMotionEngine> path( + cfg, sim_engine); + test(path.addAxis(0, &px) == true, "F23 sliding-ring addAxis(0)"); + test(path.addAxis(1, &py) == true, "F23 sliding-ring addAxis(1)"); + int32_t cur[2] = {0, 0}; + path.setCurrentPosition(cur); + + // Fill the ring to HORIZON with one-step blocks. The pump then feeds every + // block (the head advances to HORIZON) while the commands sit in the queue. + int32_t x = 0; + for (int k = 0; k < horizon; k++) { + int32_t t[2] = {x + 1, 0}; + test(path.addWaypoint(t) == true, "F23 addWaypoint fills the ring"); + x += 1; + } + path.pump(); + + // The executed prefix is dropped, so addWaypoint is legal again even though + // HORIZON points have already been appended in total. + int32_t next[2] = {x + 1, 0}; + test(path.addWaypoint(next) == true, + "F23 ring slides: addWaypoint is legal past HORIZON total points"); + x += 1; + test(path.pendingBlocks() <= horizon, "F23 pending stays within HORIZON"); + + // A path much longer than HORIZON keeps accepting points and reaches the + // end without a chunked ramp-to-rest. + const int total = 40; + bool have_p = false; + int rests = 0; + int added = 1; + while (added < total || path.isBusy()) { + if (added < total) { + int32_t t[2] = {x + 1, 0}; + if (path.addWaypoint(t)) { + x += 1; + added++; + if (added == total) { + path.endPath(); + } + } + } + path.pump(); + int64_t s0 = 0; + px.drain_one(&s0, NULL); + py.drain_one(NULL, NULL); + uint32_t P = path.performedRampUp(); + if (P > 0) { + have_p = true; + } else if (have_p && added < total) { + rests++; + have_p = false; + } + test(path.pendingBlocks() <= horizon, "F23 pending stays within HORIZON"); + } + test(added == total, "F23 sliding ring accepts a path longer than HORIZON"); + test(px.position() == x, "F23 sliding ring reaches the end"); + test(rests == 0, "F23 sliding ring has no mid-path chunk-boundary rest"); + printf("F23 sliding ring: horizon=%d total=%d x=%d rests=%d\n", horizon, + total, x, rests); +} + +int main() { + puts("FasNAxis TDD"); +#ifdef FAS_NAXIS_TRACE + naxis_ensure_html_out_dir(); +#endif + plot_smoke(); + f1_kernel(); + f2_remaining(); + f2b_oracle(); + f2c_dda_walk(); + f3_ramp(); + f2d_linear_one_block(); + f2e_issued_periods(); + f2ref_reference(); + f2g_exhaustive(); + f20_long_polyline(); + f_coarse_helix_cruises(); + f_sliding_ring(); + f2f_two_block(); + f2h_nblock_vs_f20(); + f3b_stoppability(); + f4_sim_port(); + f6_linear_sim(); + f7_linear_lookahead(); + f8_feeder(); + f9_dir_pauses(); + f11_overshoot_rest(); + f12_overshoot_corners(); + f13_lookahead(); + f14_helix(); +#ifdef FAS_PHYSICAL_STEPPER_ENABLED + f20_physical_wav(); + f21_physical(); +#endif + f16_skeleton(); + f22_external_stop(); + f23_resync_is_self_sufficient(); + printf("TEST_26 PASSED\n"); + return 0; +} diff --git a/tests/host/test_27.cpp b/tests/host/test_27.cpp new file mode 100644 index 0000000..f6a1456 --- /dev/null +++ b/tests/host/test_27.cpp @@ -0,0 +1,576 @@ +// test_27: physical_stepper — a rotordynamic plant test drive +// +// This is the "test drive" for the opt-in PhysicalStepper plant (see +// physical_stepper.h). It drives +// the plant with the exact step/direction/ticks vocabulary a real queue hands +// a driver and asserts that a real motor's failure modes show up: +// +// * it follows a rest-to-rest profile without stalling, +// * it lags during acceleration and runs ahead during deceleration, +// * a half-step rotor slip mid-coast is the decisive failure mode: the rotor +// is parked on the detent separatrix and the field out-runs it, so |delta| +// runs away — a stall induced while coasting (§5.5), +// * while a full-step slip parks the rotor on the next detent and it only +// loses exactly one step, +// * and — the contract this test exists for — after the stall the profile +// decelerates to a *small* speed the rotor can follow again: it +// re-captures and tracks the field there, then the final decel brings both +// to standstill. +// +// The shared profile (identical for the reference and the stall case): +// +// accelerate 0 -> 2000 step/s in 0.5 s +// coast 2000 step/s for 1 s +// accelerate 2000 -> 10000 step/s in 0.5 s +// coast 10000 step/s for 1 s +// [stall case only: half/full-step rotor slip] +// coast 10000 step/s for 1 s +// decelerate 10000 -> 2000 step/s (at 10000 step/s^2) +// coast 2000 step/s for 3 s <- the stalled rotor follows here +// decelerate 2000 -> 0 step/s +// +// Total 8 s. Both runs are dumped as gnuplot traces (position, error, speed, +// raw rotor acceleration, force/friction, stall). +// +// The plant is opt-in: define FAS_PHYSICAL_STEPPER_ENABLED before including the +// header. The build here always does; every other test keeps the ideal stepper. + +#include +#include +#include +#include +#include +#include + +// must precede StepperMotion.h: the PC test shims define a +// function-like `test` macro that collides with libc++'s . +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +#define FAS_PHYSICAL_STEPPER_ENABLED 1 +#include "physical_stepper.h" + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +// The canonical plant: 64 steps per full step, light inertia, and enough peak +// torque (Fmax) to follow the 10000 step/s ramp. Friction is an independent +// load (Coulomb floor 0.1, 2.25e-5 per step/s) whose pull-out is ~40000 step/s. +// With Fmax = 1.0 the natural frequency is ~50 Hz (a NEMA-17-like mid-band). +static PhysicalStepper g_plant{64, 1.0e-6, 1.0, 0.1, 2.25e-5}; + +// A dedicated plant for the traced coast-stall run (the trace is per instance), +// with a heavier load (friction reaches Fmax at ~11500 step/s). +static PhysicalStepper g_stall{64, 1.0e-6, 1.0, 0.1, 7.83e-5}; + +// A deliberately weak motor: peak accel Fmax/J = 2000 step/s^2, which cannot +// follow a 10000 step/s^2 ramp — it must lose grip. +static PhysicalStepper g_weak{64, 1.0e-6, 2.0e-3, 2.0e-4, 2.25e-6}; + +// Long enough for the rotor to ring down. +static const uint32_t SETTLE_TICKS = 12u * 16000000u; + +// The shared move profile. +static const double VMAX = 10000.0; +static const double VSMALL = 2000.0; // speed the stall can re-join +static const double ACCEL = 10000.0; // deceleration rate +static const double T_SPIN1 = 0.5; // 0 -> vsmall +static const double T_SPIN_HOLD = 1.0; // hold vsmall +static const double T_SPIN2 = 0.5; // vsmall -> vmax +static const double A_SPIN1 = VSMALL / T_SPIN1; // 4000 +static const double A_SPIN2 = (VMAX - VSMALL) / T_SPIN2; // 16000 +static const double T_COAST = 1.0; +static const double T_COAST_SMALL = 3.0; // hold the slow speed for 3 s +static const double T_TOTAL = T_SPIN1 + T_SPIN_HOLD + T_SPIN2 + 2.0 * T_COAST + + (VMAX - VSMALL) / ACCEL + T_COAST_SMALL + + VSMALL / ACCEL; // = 8.0 s + +// Test-labelled trace phases (column 10 of the .dat). +enum { PH_ACCEL = 0, PH_COAST = 1, PH_DECEL = 2, PH_SLIP = 3 }; + +static int failures = 0; +static void check(int cond, const char* msg) { + if (!cond) { + printf(" FAIL: %s\n", msg); + failures++; + } else { + printf(" ok: %s\n", msg); + } +} + +// Ticks per step for a given speed (steps/s), clamped into uint16. +static uint16_t ticks_for_v(double v) { + double t = (double)TICKS_PER_S / v; + if (t > 65535.0) t = 65535.0; + if (t < 1.0) t = 1.0; + return (uint16_t)llround(t); +} + +// A pause longer than uint16, split into chunks the command can carry. +static void dwell(PhysicalStepper& p, uint32_t ticks) { + while (ticks > 65535) { + p.step(0, true, 65535); + ticks -= 65535; + } + if (ticks > 0) p.step(0, true, (uint16_t)ticks); +} + +// Emit a single physical step whose following dwell is `period` ticks, split +// into a step command plus pause(s) exactly as the ramp generator does when +// the period exceeds uint16. +static void issue_single_step(PhysicalStepper& p, bool up, uint32_t period) { + bool first = true; + while (period > 65535) { + if (first) { + p.step(1, up, 65535); + first = false; + } else { + p.step(0, up, 65535); + } + period -= 65535; + } + if (first) { + p.step(1, up, (uint16_t)period); + } else if (period > 0) { + p.step(0, up, (uint16_t)period); + } +} + +// Per-step periods of an acceleration from v0 to v1 at rate `a`. Step i is +// reached at t_i = (−v0 + sqrt(v0² + 2·a·i))/a, so the period is t_i − t_{i−1}. +static std::vector build_ramp(double v0, double v1, double a) { + std::vector seg; + const int n = (int)llround((v1 * v1 - v0 * v0) / (2.0 * a)); + double t_prev = 0.0; + for (int i = 1; i <= n; i++) { + double ti = (-v0 + sqrt(v0 * v0 + 2.0 * a * (double)i)) / a; + uint32_t tk = (uint32_t)llround((ti - t_prev) * (double)TICKS_PER_S); + if (tk < 1) tk = 1; + seg.push_back(tk); + t_prev = ti; + } + return seg; +} + +static void issue_ramp(PhysicalStepper& p, const std::vector& seg, + bool up) { + for (size_t i = 0; i < seg.size(); i++) issue_single_step(p, up, seg[i]); +} + +// Probes captured during the shared profile, for assertions. +struct move_probe { + double delta_stalled; // rotor/field error at the end of the stall coast + double w_stalled; + int stall; + double x_small_start; // rotor position at the start of the small-speed coast + double x_small_end; // ... and at its end + double w_small_end; // rotor speed at the end of the small-speed coast +}; + +// Run the full rest-to-rest profile: +// 0 -> 2000 step/s (0.5 s), hold 2000 (1 s), 2000 -> 10000 (0.5 s), +// coast 10000 (1 s), [slip], coast 10000 (1 s), +// decelerate 10000 -> 2000, hold 2000 (3 s), decelerate 2000 -> 0. +// `slip_steps` is a one-shot rotor displacement applied after the first coast +// (0 = reference; -D/2 = half-step slip that stalls; -D = full-step slip). +static double run_move(PhysicalStepper& p, double slip_steps, bool trace, + move_probe* probe) { + const std::vector spin1 = build_ramp(0.0, VSMALL, A_SPIN1); + const std::vector spin2 = build_ramp(VSMALL, VMAX, A_SPIN2); + const std::vector dec = build_ramp(0.0, VMAX, ACCEL); + const int nd = (int)dec.size(); + const int ns = (int)llround(VSMALL * VSMALL / (2.0 * ACCEL)); + const uint32_t ct = ticks_for_v(VMAX); + const uint32_t cts = ticks_for_v(VSMALL); + const int ncv = (int)llround(T_COAST * VMAX); + const int nch = (int)llround(T_SPIN_HOLD * VSMALL); + const int ncs = (int)llround(T_COAST_SMALL * VSMALL); + + if (trace) p.trace_set_phase(PH_ACCEL); + issue_ramp(p, spin1, true); // 0 -> vsmall (0.5 s) + for (int i = 0; i < nch; i++) p.step(1, true, cts); // hold vsmall (1 s) + issue_ramp(p, spin2, true); // vsmall -> vmax (0.5 s) + + if (trace) p.trace_set_phase(PH_COAST); + for (int i = 0; i < ncv; i++) p.step(1, true, ct); + + if (slip_steps != 0.0) { + p.rotate(slip_steps); + if (trace) p.trace_set_phase(PH_SLIP); + } + + if (trace) p.trace_set_phase(PH_COAST); + for (int i = 0; i < ncv; i++) p.step(1, true, ct); + + if (probe) { + probe->delta_stalled = p.delta(); + probe->w_stalled = p.speed(); + probe->stall = p.last().stall ? 1 : 0; + } + + // Decelerate vmax -> vsmall. + if (trace) p.trace_set_phase(PH_DECEL); + for (int i = nd - 1; i >= ns; i--) issue_single_step(p, true, dec[i]); + + // Coast at vsmall; the re-captured rotor should follow here. + if (trace) p.trace_set_phase(PH_COAST); + if (probe) probe->x_small_start = p.x(); + for (int i = 0; i < ncs; i++) p.step(1, true, cts); + if (probe) { + probe->x_small_end = p.x(); + probe->w_small_end = p.speed(); + } + + // Decelerate vsmall -> 0. + if (trace) p.trace_set_phase(PH_DECEL); + for (int i = ns - 1; i >= 0; i--) issue_single_step(p, true, dec[i]); + + return p.x_c(); +} + +// ---- T1: single pause ------------------------------------------------------ +static void test_dwell() { + printf("=== T1: single pause (dwell) ===\n"); + g_plant.reset(); + observed_s o = g_plant.step(0, true, 50000); + check(o.stall == false, "pause does not stall"); + check(fabs(g_plant.speed()) < 1.0, "speed decays near zero during dwell"); + check(g_plant.getCurrentPosition() == 0, "rotor does not drift during dwell"); +} + +// ---- T2: single step ------------------------------------------------------- +static void test_single_step() { + printf("=== T2: single step (slow) ===\n"); + g_plant.reset(); + // One step, then a long dwell so the rotor has time to settle onto it. + issue_single_step(g_plant, true, 200000); + dwell(g_plant, SETTLE_TICKS); + check(g_plant.last().stall == false, "single step does not stall"); + check(g_plant.x_c() == 1.0, "commanded position advanced by one step"); + check(fabs(g_plant.delta()) < 1.5, + "rotor settles onto the command within the friction deadband"); + printf(" rotor=%.4f cmd=%.1f delta=%.4f\n", g_plant.x(), g_plant.x_c(), + g_plant.delta()); +} + +// ---- T3: gentle burst ------------------------------------------------------ +static void test_gentle_burst() { + printf("=== T3: gentle burst (64 steps @ 16000 ticks) ===\n"); + g_plant.reset(); + for (int i = 0; i < 64; i++) g_plant.step(1, true, 16000); + dwell(g_plant, SETTLE_TICKS); + check(g_plant.last().stall == false, "gentle burst never stalls"); + check(g_plant.x_c() == 64.0, "commanded advance is 64 steps"); + check(fabs(g_plant.delta()) < 1.5, "rotor settles onto the command"); +} + +// ---- T4: too-fast => step loss --------------------------------------------- +static void test_too_fast_stalls() { + printf("=== T4: too-fast burst @ 1 tick (16 Msteps/s) ===\n"); + g_plant.reset(); + observed_s last = g_plant.step(80, true, 1); + check(last.stall, "a too-fast burst is reported as a step loss"); +} + +// ---- T5: reversal ---------------------------------------------------------- +static void test_reversal() { + printf("=== T5: forward then reversal ===\n"); + g_plant.reset(); + for (int i = 0; i < 200; i++) g_plant.step(1, true, 16000); + double peak = g_plant.x_c(); + for (int i = 0; i < 100; i++) g_plant.step(1, false, 16000); + (void)peak; + int32_t pos = g_plant.getCurrentPosition(); + check(pos < 200, "reversal brings position below the forward peak"); + check(pos >= 90, "reversal does not overshoot the origin"); + check(g_plant.last().stall == false, "no stall on a clean forward-then-back"); + printf(" net position after reversal: %d (fwd=200, back=100)\n", pos); +} + +static long file_size(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return -1; + fseek(f, 0, SEEK_END); + long n = ftell(f); + fclose(f); + return n; +} + +// Peak absolute PCM sample in a .wav's data chunk (0 if silent/absent). +static int wav_peak(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return 0; + char hdr[44]; + if (fread(hdr, 1, 44, f) != 44) { + fclose(f); + return 0; + } + int peak = 0; + int16_t s; + while (fread(&s, 2, 1, f) == 1) { + int v = s < 0 ? -s : s; + if (v > peak) peak = v; + } + fclose(f); + return peak; +} + +// ---- T6: the canonical rest-to-rest profile -------------------------------- +static void test_canonical_profile() { + printf( + "=== T6: canonical profile (accel 1s, coast, decel, small, stop) ===\n"); + g_plant.reset(); + g_plant.trace_begin(4); + move_probe probe; + double cmd = run_move(g_plant, 0.0, true, &probe); + size_t rows = g_plant.trace_dump("test_27_trapezoid.dat"); + g_plant.to_wav("test_27_trapezoid.wav"); + long wav = file_size("test_27_trapezoid.wav"); + double sim = (double)g_plant.total_ticks() / (double)TICKS_PER_S; + dwell(g_plant, SETTLE_TICKS); + int32_t pos = g_plant.getCurrentPosition(); + printf( + " sim_time=%.4f s, final pos=%d commanded=%.0f stall=%u, wav=%ld B, " + "trace rows=%zu\n", + sim, pos, cmd, (unsigned)g_plant.last().stall, wav, rows); + check(g_plant.last().stall == false, "the canonical profile never stalls"); + check(fabs(sim - T_TOTAL) < 0.05, "simulated time matches the profile"); + check(fabs((double)pos - cmd) < 2.0, "rotor lands on the commanded position"); + // T_TOTAL at 44100 Hz, 16-bit mono, plus the 44-byte header. + long wav_expect = (long)llround(T_TOTAL * 44100.0 * 2.0) + 44; + check(wav > wav_expect - 2000 && wav < wav_expect + 2000, + "the wav renders the whole move"); + int peak = wav_peak("test_27_trapezoid.wav"); + printf(" wav peak sample: %d\n", peak); + check(peak > 1000, "the recorded wav carries audible signal, not silence"); + check(rows > 100, "the profile gnuplot trace has rows"); +} + +// ---- T7: a weak motor on the same profile must lose a step ----------------- +static void test_weak_motor_stalls() { + printf("=== T7: weak motor (Fmax=2e-3) on the same profile ===\n"); + g_weak.reset(); + run_move(g_weak, 0.0, false, nullptr); + dwell(g_weak, SETTLE_TICKS); + printf(" stall_ever=%d final pos=%d peak|delta|=%.1f\n", g_weak.stall_ever(), + g_weak.getCurrentPosition(), g_weak.peak_abs_delta()); + check(g_weak.stall_ever(), "an under-torqued motor loses synchronism"); +} + +// ---- T8: over-drive outruns the rotor (emergent stall) --------------------- +static void test_overdrive_outruns_rotor() { + printf("=== T8: over-drive outruns the rotor (emergent stall) ===\n"); + g_plant.reset(); + observed_s o = g_plant.step(80, true, 1); + check(o.stall, "a too-fast burst is reported as a step loss"); + printf(" stall observation fired, |delta|=%.1f, x_c=%.0f\n", + fabs(g_plant.delta()), g_plant.x_c()); +} + +// ---- T9: re-engagement latches onto a whole-step detent -------------------- +static void test_reengagement_emerges() { + printf("=== T9: re-engagement emerges from the model ===\n"); + g_plant.reset(); + observed_s o = g_plant.step(80, true, 1); + check(o.stall, "over-drive stalls the rotor"); + printf(" stalled: |delta|=%.1f, x=%.1f, x_c=%.0f\n", fabs(g_plant.delta()), + g_plant.x(), g_plant.x_c()); + + for (int i = 0; i < 64; i++) g_plant.step(1, true, 16000); + dwell(g_plant, SETTLE_TICKS); + + double off = g_plant.delta() / 64.0; + printf(" re-synced: x=%.1f, x_c=%.0f, delta=%.3f (%.2f full steps)\n", + g_plant.x(), g_plant.x_c(), g_plant.delta(), off); + check(fabs(off - llround(off)) < 0.2 || fabs(g_plant.delta()) < 1.0, + "re-engagement latches to a whole-step detent"); + + int32_t before = g_plant.getCurrentPosition(); + for (int i = 0; i < 20; i++) g_plant.step(1, true, 16000); + dwell(g_plant, SETTLE_TICKS); + int32_t after = g_plant.getCurrentPosition(); + printf(" fresh move: %d -> %d\n", before, after); + check(after - before == 20, "the re-synced rotor tracks a fresh slow move"); +} + +// ---- T12: a half-step slip mid-coast stalls, then re-joins ---- +// The rotor is displaced half a full step after the first coast: it is parked +// on the separatrix, the field out-runs it and |delta| runs away. Later the +// profile decelerates to a small speed the rotor can follow again — it +// re-captures there and tracks, then the final decel brings both to rest. +static void test_half_step_slip_stalls() { + printf("=== T12: half-step slip mid-coast stalls, then re-joins ===\n"); + g_stall.reset(); + g_stall.trace_begin(4); + move_probe probe; + run_move(g_stall, -32.0, true, &probe); + size_t rows = g_stall.trace_dump("test_27_coast_stall.dat"); + g_stall.to_wav("test_27_coast_stall.wav"); + long wav = file_size("test_27_coast_stall.wav"); + int peak_sample = wav_peak("test_27_coast_stall.wav"); + double sim = (double)g_stall.total_ticks() / (double)TICKS_PER_S; + + double small_advance = probe.x_small_end - probe.x_small_start; + printf( + " stalled: |delta|=%.0f w=%.0f stall=%d | at %.0f/s: advance=%.0f " + "(expect %.0f), w=%.0f | sim=%.2f s\n", + fabs(probe.delta_stalled), probe.w_stalled, probe.stall, VSMALL, + small_advance, VSMALL * T_COAST_SMALL, probe.w_small_end, sim); + + check(probe.stall == 1, "the half-step slip stalls the rotor mid-coast"); + check(fabs(probe.delta_stalled) > 64.0, + "the slip runs |delta| past a full step"); + // The small-speed coast: the rotor follows the field again. + check(fabs(small_advance - VSMALL * T_COAST_SMALL) < + 0.2 * VSMALL * T_COAST_SMALL, + "the stalled rotor re-joins and follows the field at the small speed"); + check(fabs(probe.w_small_end - VSMALL) < 0.3 * VSMALL, + "the rotor speed matches the small speed"); + check(fabs(sim - T_TOTAL) < 0.05, "the stall trace runs to the profile end"); + check(rows > 100, "the coast-stall gnuplot trace has rows"); + check(wav > 0, "the coast-stall wav was written"); + check(peak_sample > 1000, + "the recorded wav carries the stall transient, not silence"); +} + +// ---- T13: a full-step slip loses exactly one step -------------------------- +static void test_full_step_slip_loses_one_step() { + printf("=== T13: full-step slip loses exactly one step ===\n"); + g_stall.reset(); + move_probe probe; + run_move(g_stall, -64.0, false, &probe); + dwell(g_stall, SETTLE_TICKS); + double off = g_stall.delta() / 64.0; + printf( + " stalled: |delta|=%.1f w=%.0f | final delta=%.1f (%.2f full steps)\n", + fabs(probe.delta_stalled), probe.w_stalled, g_stall.delta(), off); + check(probe.w_stalled > 9000.0, + "a full-step slip keeps the rotor tracking (no runaway)"); + check(fabs(off + 1.0) < 0.15, "it ends exactly one full step behind"); + check(fabs((probe.x_small_end - probe.x_small_start) - + VSMALL * T_COAST_SMALL) < 0.2 * VSMALL * T_COAST_SMALL, + "the rotor followed the field through the small-speed coast"); +} + +static void test_wav_generation(const char* good_wav, const char* bad_wav) { + printf("=== T10: wav synthesis ===\n"); + g_plant.reset(); + for (int i = 0; i < 400; i++) g_plant.step(1, true, 1600); + bool g = g_plant.to_wav(good_wav); + check(g, "to_wav() succeeds for the moving plant"); + + g_plant.reset(); + g_plant.step(80, true, 1); // stall + bool b = g_plant.to_wav(bad_wav); + check(b, "to_wav() succeeds for the stalled plant"); + + FILE* f = fopen(good_wav, "rb"); + check(f != NULL, "moving wav file was written"); + if (f) { + char riff[4]; + size_t n = fread(riff, 1, 4, f); + check(n == 4 && memcmp(riff, "RIFF", 4) == 0, + "moving wav starts with RIFF"); + fclose(f); + } + f = fopen(bad_wav, "rb"); + check(f != NULL, "stalled wav file was written"); + if (f) { + char riff[4]; + size_t n = fread(riff, 1, 4, f); + check(n == 4 && memcmp(riff, "RIFF", 4) == 0, + "stalled wav starts with RIFF"); + fclose(f); + } +} + +// ---- gnuplot figure for the two runs -------------------------------------- +// One six-panel figure per run, side by side, so the shared profile and the +// divergent ending can be read off directly. Dat columns: +// 1:t 2:x 3:x_c 4:delta 5:w 6:a 7:tau 8:friction 9:stall 10:phase +static void write_gnuplot_asset() { + FILE* g = fopen("test_27.gnuplot", "w"); + if (!g) return; + fprintf( + g, + "set term pngcairo size 1600,1400\n" + "set output \"test_27_coast_stall.png\"\n" + "set multiplot layout 3,2 title " + "\"PhysicalStepper: reference vs half-step-slip stall (same ramp)\"\n" + "set xlabel \"t [s]\"\n" + "D=64.0\n" + "set title \"position [steps]\"\n" + "plot \"test_27_trapezoid.dat\" using 1:2 with lines title " + "\"ref x\", \"test_27_trapezoid.dat\" using 1:3 with lines dt 2 " + "title \"ref x_c\", \"test_27_coast_stall.dat\" using 1:2 with " + "lines title \"stall x\", \"test_27_coast_stall.dat\" using 1:3 with " + "lines dt 2 title \"stall x_c\"\n" + "set title \"step error delta [steps]\"\n" + "plot \"test_27_coast_stall.dat\" using 1:4 with lines title " + "\"stall delta\", \"test_27_trapezoid.dat\" using 1:4 with lines dt 2 " + "title \"ref delta\", D lt 0 title \"+D\", -D lt 0 notitle\n" + "set title \"rotor speed [steps/s]\"\n" + "plot \"test_27_coast_stall.dat\" using 1:5 with lines title " + "\"stall w\", \"test_27_trapezoid.dat\" using 1:5 with lines dt 2 " + "title \"ref w\"\n" + "set title \"raw rotor acceleration [steps/s^2]\"\n" + "plot \"test_27_coast_stall.dat\" using 1:6 with lines title " + "\"stall a\", \"test_27_trapezoid.dat\" using 1:6 with lines dt 2 " + "title \"ref a\"\n" + "set title \"magnetic force and friction\"\n" + "plot \"test_27_coast_stall.dat\" using 1:7 with lines title " + "\"tau\", \"test_27_coast_stall.dat\" using 1:8 with lines title " + "\"friction\"\n" + "set title \"stall observation (1 = rotor slipping)\"\n" + "set yrange [0:1.1]\n" + "set ytics 0,0.5,1\n" + "plot \"test_27_coast_stall.dat\" using 1:9 with lines title " + "\"stall\"\n" + "unset yrange\n" + "unset multiplot\n" + "unset output\n"); + fclose(g); +} + +int main() { + printf("=====================================================\n"); + printf(" StepperMotion PC-Based Test 27\n"); + printf(" PhysicalStepper rotordynamic plant test drive\n"); + printf("=====================================================\n"); + + test_dwell(); + test_single_step(); + test_gentle_burst(); + test_too_fast_stalls(); + test_reversal(); + test_canonical_profile(); + test_weak_motor_stalls(); + test_overdrive_outruns_rotor(); + test_reengagement_emerges(); + test_half_step_slip_stalls(); + test_full_step_slip_loses_one_step(); + test_wav_generation("test_27_good.wav", "test_27_bad.wav"); + write_gnuplot_asset(); + + printf("=====================================================\n"); + if (failures != 0) { + printf("TEST_27 FAILED (%d failures)\n", failures); + return 1; + } + printf( + "TEST_27 PASSED (plant follows a rest-to-rest profile; a half-step\n" + "slip mid-coast stalls it while a full-step slip loses one step; the\n" + "stall re-joins the field at the small speed and stops with it)\n"); + return 0; +} diff --git a/tests/host/test_28.cpp b/tests/host/test_28.cpp new file mode 100644 index 0000000..5b3cbdf --- /dev/null +++ b/tests/host/test_28.cpp @@ -0,0 +1,491 @@ +// test_28: NEMA-17 / A4988 pull-out benchmark — fitting the plant to hardware +// +// The rotordynamic plant (physical_stepper.h) was originally parameterised by +// hand as a generic "reference" motor. This test does the opposite: it takes +// the measured pull-out data of a real NEMA-17 driven by an A4988 on an ESP32 +// (whitepaper §10.4) and *finds* the plant parameters that reproduce it. +// +// Hardware (see §10.4): +// 200 full steps/rev (1.8 deg), A4988 set to 16x microstepping +// => 3200 microsteps/rev, D = 16 microsteps per full step +// ~19 V power supply, ESP32 MCPWM/PCNT, StepperMotion stepperdemo +// +// The demo reports `getCurrentSpeedInMilliHz()`; the sweep values in the +// whitepaper are in millisteps/s, so microsteps/s = value / 1000. +// +// Measured pull-out boundary (microsteps/s), by commanded acceleration +// (microsteps/s^2): +// +// A = 1e4 : ~134 000 (133.33 M works, 134.45 M stalls) +// A = 1e5 : ~118 000 (111.11 M works, 125.00 M stalls) +// A = 1e6 : ~123 000 (122.14 M works, 124.03 M stalls) +// A = 1e7 : ~ 21 000 (47 us/step works, 48 us/step stalls) +// +// The first three are the steady-state pull-out (friction reaches the drive +// torque); the last is dominated by the commanded acceleration exceeding +// Fmax/J_eff, which is why the plant can reproduce it at all. +// +// Two parameters are found: +// * friction_viscous, so the A = 1e6 pull-out matches ~123 000 usteps/s +// (the steady-state friction balance v_max = (Fmax - fs)/fv), and +// * the effective plant inertia J_plant, so the A = 1e7 pull-out matches +// ~21 000 usteps/s (the acceleration-capability limit Fmax/J_eff). +// +// The plant's coordinate is the microstep; its inertia is therefore the +// mechanical inertance in microstep units, J_plant = J_eff * theta_u, where +// theta_u = 1.8 deg / 16 is the angle of one microstep. +// +// Opt-in gate as usual. + +#include +#include +#include +#include +#include + +#define TICKS_PER_S 16000000L +#define FAS_PHYSICAL_STEPPER_ENABLED 1 +#include "physical_stepper.h" + +// ---- hardware constants ---------------------------------------------------- +static const uint8_t D = 16; // microsteps per full step (16x) +static const double STEPS_PER_REV = 200.0; +static const double USTEPS_PER_REV = 3200.0; +static const double THETA_U = M_PI / 100.0 / 16.0; // rad per microstep +static const double FMAX = 0.4; // N*m, datasheet-like holding torque +static const double FRIC_STATIC = 0.04; // N*m, Coulomb floor (~10% Fmax) +// Typical bare NEMA-17 rotor inertia. The motor was unloaded (sitting on the +// table), so this is the mechanical inertia to use when reading the fit's +// degeneracy: only Fmax/J_plant is constrained, and J_plant = J*THETA_U. +static const double J_ROTOR = 5.4e-6; // kg*m^2, bare rotor (typical) + +// Fitted parameters, shared with the trace/wav/gnuplot renderers below. +static double g_J_plant = 0.0; +static double g_fv = 0.0; + +// Measured pull-out boundary per commanded acceleration. +struct meas_s { + double accel; // microsteps/s^2 + double pullout; // microsteps/s + const char* why; +}; +static const meas_s MEASURED[] = { + {1.0e4, 134000.0, "steady-state friction balance"}, + {1.0e5, 118000.0, "steady-state friction balance"}, + {1.0e6, 123000.0, "steady-state friction balance"}, + {1.0e7, 21000.0, "acceleration-capability limit (Fmax/J)"}, +}; +static const int NMEAS = (int)(sizeof(MEASURED) / sizeof(MEASURED[0])); + +// The calibration targets used by find_motor_parameters(). +static const double FIT_ACCEL_FRICTION = 1.0e6; // steady pull-out anchor +static const double FIT_PULLOUT_FRICTION = 123000.0; +static const double FIT_ACCEL_INERTIA = 1.0e7; // accel-limit anchor +static const double FIT_PULLOUT_INERTIA = 21000.0; + +// Simulation coast (s) held at top speed before the stop ramp; long enough +// for a slipping rotor to grow |delta| past D. +static const double COAST_S = 0.30; + +static int failures = 0; +static void check(int cond, const char* msg) { + if (!cond) { + printf(" FAIL: %s\n", msg); + failures++; + } else { + printf(" ok: %s\n", msg); + } +} + +// ---- step-train helpers (same vocabulary as test_27) ----------------------- + +// Ticks per step for a given speed (microsteps/s), clamped into uint16. +static uint16_t ticks_for_v(double v) { + double t = (double)TICKS_PER_S / v; + if (t > 65535.0) t = 65535.0; + if (t < 1.0) t = 1.0; + return (uint16_t)llround(t); +} + +// One step whose following period may exceed uint16: emit the step, then +// pause(s), exactly as the ramp generator does. +static void issue_single_step(PhysicalStepper& p, bool up, uint32_t period) { + bool first = true; + while (period > 65535) { + if (first) { + p.step(1, up, 65535); + first = false; + } else { + p.step(0, up, 65535); + } + period -= 65535; + } + if (first) { + p.step(1, up, (uint16_t)period); + } else if (period > 0) { + p.step(0, up, (uint16_t)period); + } +} + +// Per-step periods of an acceleration from v0 to v1 at rate `a`. +static std::vector build_ramp(double v0, double v1, double a) { + std::vector seg; + const int n = (int)llround((v1 * v1 - v0 * v0) / (2.0 * a)); + double t_prev = 0.0; + for (int i = 1; i <= n; i++) { + double ti = (-v0 + sqrt(v0 * v0 + 2.0 * a * (double)i)) / a; + uint32_t tk = (uint32_t)llround((ti - t_prev) * (double)TICKS_PER_S); + if (tk < 1) tk = 1; + seg.push_back(tk); + t_prev = ti; + } + return seg; +} + +// Release from standstill: accelerate 0 -> V at A, then run forward at V for +// COAST_S. Returns whether the plant ever observed a slip. This mirrors the +// hardware protocol exactly (standstill, run forward). +static bool simulate_move(PhysicalStepper& p, double accel, double v) { + p.reset(); + const std::vector up = build_ramp(0.0, v, accel); + for (size_t i = 0; i < up.size(); i++) { + if (p.stall_ever()) break; + issue_single_step(p, true, up[i]); + } + // Coast at top speed. The hardware measurement simply released the motor + // from standstill and let it run forward, so there is deliberately no stop + // ramp here: the slip flag latches the moment the rotor falls behind. + const uint32_t ct = ticks_for_v(v); + const int n = (int)llround(COAST_S * v); + for (int i = 0; i < n; i++) { + if (p.stall_ever()) break; + p.step(1, true, ct); + } + return p.stall_ever(); +} + +// Simulated pull-out boundary: the speed at which a move at acceleration +// `accel` flips from tracking to slipping. +static double boundary(PhysicalStepper& p, double accel) { + double lo = 1.0e3, hi = 4.0e5; + for (int i = 0; i < 16; i++) { + double mid = 0.5 * (lo + hi); + if (simulate_move(p, accel, mid)) { + hi = mid; + } else { + lo = mid; + } + } + return 0.5 * (lo + hi); +} + +// ---- parameter search ------------------------------------------------------ +// +// The plant's steady pull-out is v_max = (Fmax - fs)/fv, so friction_viscous +// sets the low-acceleration boundary. The acceleration-capability limit is +// Fmax / J_plant, so the plant inertia sets the high-acceleration collapse. +// Both dependencies are monotonic, so a bisection on each converges. + +// Find friction_viscous so the A = 1e6 pull-out equals `target`. +static double fit_friction_viscous(double J_plant, double target) { + double lo = 1.0e-7, hi = 1.0e-4; + for (int i = 0; i < 22; i++) { + double fv = 0.5 * (lo + hi); + PhysicalStepper p(D, J_plant, FMAX, FRIC_STATIC, fv); + if (boundary(p, FIT_ACCEL_FRICTION) > target) { + lo = fv; // too little friction -> boundary too high + } else { + hi = fv; + } + } + return 0.5 * (lo + hi); +} + +// Find the plant inertia so the A = 1e7 pull-out equals `target`. +static double fit_inertia(double fv, double target) { + double lo = 1.0e-9, hi = 1.0e-6; + for (int i = 0; i < 22; i++) { + double J = 0.5 * (lo + hi); + PhysicalStepper p(D, J, FMAX, FRIC_STATIC, fv); + if (boundary(p, FIT_ACCEL_INERTIA) > target) { + lo = J; // too little inertia -> accel limit too high + } else { + hi = J; + } + } + return 0.5 * (lo + hi); +} + +// ---- artifact rendering (traces, wav, gnuplot) ----------------------------- + +static long file_size(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return -1; + fseek(f, 0, SEEK_END); + long n = ftell(f); + fclose(f); + return n; +} + +// Peak absolute PCM sample in a 16-bit mono .wav (0 if silent/absent). +static int wav_peak(const char* path) { + FILE* f = fopen(path, "rb"); + if (!f) return 0; + char hdr[44]; + if (fread(hdr, 1, 44, f) != 44) { + fclose(f); + return 0; + } + int peak = 0; + int16_t s; + while (fread(&s, 2, 1, f) == 1) { + int v = s < 0 ? -s : s; + if (v > peak) peak = v; + } + fclose(f); + return peak; +} + +// Release from standstill at `accel` up to `v`, run forward for COAST_S, while +// recording the plant's six-panel trace and its acoustic stream. The whole +// coast is recorded even after the rotor slips, so the divergence is visible +// in the trace and audible in the wav. Writes the trace to `dat` (if non-null) +// and the wav to `wav` (if non-null). Returns whether the rotor slipped. +static bool trace_scenario(double accel, double v, unsigned long decim, + const char* dat, const char* wav) { + PhysicalStepper p(D, g_J_plant, FMAX, FRIC_STATIC, g_fv); + p.trace_begin(decim); + const std::vector up = build_ramp(0.0, v, accel); + p.trace_set_phase(0); // accel + for (size_t i = 0; i < up.size(); i++) { + issue_single_step(p, true, up[i]); + } + const uint32_t ct = ticks_for_v(v); + const int n = (int)llround(COAST_S * v); + p.trace_set_phase(1); // coast + for (int i = 0; i < n; i++) { + p.step(1, true, ct); + } + if (dat) p.trace_dump(dat); + if (wav) p.to_wav(wav); + return p.stall_ever(); +} + +// Boundary-vs-acceleration table for the plot: A, sim, measured, sim fps. +static void write_boundary_dat() { + FILE* f = fopen("test_28_boundary.dat", "w"); + if (!f) return; + PhysicalStepper p(D, g_J_plant, FMAX, FRIC_STATIC, g_fv); + for (int i = 0; i < NMEAS; i++) { + double b = boundary(p, MEASURED[i].accel); + fprintf(f, "%g %g %g %g\n", MEASURED[i].accel, b, MEASURED[i].pullout, + b / D); + } + fclose(f); +} + +// The six-panel figure: the three scenarios overlaid (position, error, speed, +// raw rotor accel, magnetic force) plus the simulated-vs-measured pull-out +// boundary. Dat columns: 1:t 2:x 3:x_c 4:delta 5:w 6:a 7:tau 8:friction +// 9:stall 10:phase. +static void write_gnuplot_asset() { + FILE* g = fopen("test_28.gnuplot", "w"); + if (!g) return; + fprintf(g, + "set term pngcairo size 1600,1400\n" + "set output \"test_28.png\"\n" + "set multiplot layout 3,2 title " + "\"NEMA-17/A4988: fitted plant (D=16, 16x) - run vs stall vs " + "high-accel collapse\"\n" + "D=16.0\n" + "set xlabel \"t [s]\"\n"); + // 1: position + fprintf(g, + "set title \"position [usteps] (x solid, x_c dashed)\"\n" + "plot \"test_28_run.dat\" u 1:2 w l t 'X run x', " + "\"test_28_run.dat\" u 1:3 w l dt 2 t 'X run x_c', " + "\"test_28_stall.dat\" u 1:2 w l t 'S stall x', " + "\"test_28_stall.dat\" u 1:3 w l dt 2 t 'S stall x_c', " + "\"test_28_collapse.dat\" u 1:2 w l t 'C collapse x', " + "\"test_28_collapse.dat\" u 1:3 w l dt 2 t 'C collapse x_c'\n"); + // 2: error + fprintf(g, + "set title \"step error delta [usteps]\"\n" + "plot \"test_28_run.dat\" u 1:4 w l t 'run', " + "\"test_28_stall.dat\" u 1:4 w l t 'stall', " + "\"test_28_collapse.dat\" u 1:4 w l t 'collapse', " + "D lt 0 title '+D', -D lt 0 notitle\n"); + // 3: speed + fprintf(g, + "set title \"rotor speed [usteps/s]\"\n" + "plot \"test_28_run.dat\" u 1:5 w l t 'run', " + "\"test_28_stall.dat\" u 1:5 w l t 'stall', " + "\"test_28_collapse.dat\" u 1:5 w l t 'collapse'\n"); + // 4: accel + fprintf(g, + "set title \"raw rotor acceleration [usteps/s^2]\"\n" + "plot \"test_28_run.dat\" u 1:6 w l t 'run', " + "\"test_28_stall.dat\" u 1:6 w l t 'stall', " + "\"test_28_collapse.dat\" u 1:6 w l t 'collapse'\n"); + // 5: force + fprintf(g, + "set title \"magnetic force tau and friction\"\n" + "plot \"test_28_stall.dat\" u 1:7 w l t 'stall tau', " + "\"test_28_stall.dat\" u 1:8 w l t 'stall friction', " + "\"test_28_collapse.dat\" u 1:7 w l t 'collapse tau'\n"); + // 6: boundary sweep + fprintf(g, + "set title \"pull-out boundary vs acceleration\"\n" + "set logscale x\n" + "set xlabel \"acceleration [usteps/s^2]\"\n" + "set ylabel \"pull-out [usteps/s]\"\n" + "plot \"test_28_boundary.dat\" u 1:2 w lp pt 7 t 'simulated', " + "\"test_28_boundary.dat\" u 1:3 w lp pt 5 t 'measured'\n" + "unset logscale x\n" + "unset ylabel\n" + "unset multiplot\n" + "unset output\n"); + fclose(g); +} + +int main() { + printf("=== test_28: NEMA-17 / A4988 pull-out benchmark ===\n"); + printf("D=%u usteps/full-step, %g full-steps/rev, %g usteps/rev\n", D, + STEPS_PER_REV, USTEPS_PER_REV); + + // ---- 1. find the motor parameters from the measured boundary ------------ + printf("\n=== P1: fit plant parameters to the measured data ===\n"); + // First the inertia (needs a friction estimate to make the accel-limit + // boundary meaningful); then friction; then a second inertia pass so the + // two constraints settle. + double fv = fit_friction_viscous(3.0e-8, FIT_PULLOUT_FRICTION); + double J_plant = fit_inertia(fv, FIT_PULLOUT_INERTIA); + fv = fit_friction_viscous(J_plant, FIT_PULLOUT_FRICTION); + J_plant = fit_inertia(fv, FIT_PULLOUT_INERTIA); + + const double J_eff = J_plant / THETA_U; // mechanical inertia (kg m^2) + const double v_max = (FMAX - FRIC_STATIC) / fv; + printf(" found: J_plant=%.4g J_eff=%.4g kg m^2 (%.1f g cm^2)\n", J_plant, + J_eff, J_eff * 1.0e7); + printf(" friction_viscous=%.4g N m s friction_static=%.4g N m\n", fv, + FRIC_STATIC); + printf(" v_max=(Fmax-fs)/fv=%.0f usteps/s\n", v_max); + + // The fit pins only Fmax/J_plant. Because the motor was UNLOADED, the + // physical reading is: anchor the inertia at the bare rotor and solve for + // the effective torque (much lower than the nominal Fmax). + const double J_bare_plant = J_ROTOR * THETA_U; + const double Fmax_eff = FMAX * J_bare_plant / J_plant; + printf( + " unloaded-rotor equivalent: J_plant=%.4g (%.1f g cm^2) => " + "Fmax_eff=%.4g N m\n", + J_bare_plant, J_ROTOR * 1.0e7, Fmax_eff); + printf( + " (only Fmax/J is determined; the nominal Fmax anchor gives the " + "heavier J above)\n"); + + check(J_plant > 0.0 && J_plant < 1.0e-6, "plant inertia in a sane range"); + check(Fmax_eff > 0.0 && Fmax_eff < FMAX, + "bare-rotor anchor implies a lower effective torque"); + check(fv > 0.0, "friction_viscous positive"); + check(fabs(v_max - FIT_PULLOUT_FRICTION) / FIT_PULLOUT_FRICTION < 0.20, + "v_max within 20% of the measured steady pull-out"); + + PhysicalStepper plant(D, J_plant, FMAX, FRIC_STATIC, fv); + + // ---- 2. reproduce every measured boundary ------------------------------ + printf("\n=== P2: simulated vs measured pull-out boundary ===\n"); + printf(" %-10s %-12s %-12s %-8s %-8s\n", "accel", "sim(ustep/s)", + "meas(ustep/s)", "ratio", "sim fps"); + for (int i = 0; i < NMEAS; i++) { + double b = boundary(plant, MEASURED[i].accel); + double ratio = b / MEASURED[i].pullout; + printf(" %-10.0e %-12.0f %-12.0f %-8.3f %-8.0f\n", MEASURED[i].accel, b, + MEASURED[i].pullout, ratio, b / D); + // The two high-acceleration / steady-state regimes are fit directly; the + // A = 1e5 point carries only 2-point granularity (111k runs, 125k stalls). + double tol = (MEASURED[i].accel >= 1.0e7) ? 0.35 : 0.20; + char msg[96]; + snprintf(msg, sizeof(msg), "A=%.0e boundary within %d%% of measured", + MEASURED[i].accel, (int)(tol * 100)); + check(fabs(ratio - 1.0) < tol, msg); + } + + // ---- 3. the high-acceleration collapse is captured --------------------- + printf("\n=== P3: high acceleration collapses the usable speed ===\n"); + double b_1e6 = boundary(plant, 1.0e6); + double b_1e7 = boundary(plant, 1.0e7); + printf( + " A=1e6 pull-out=%.0f usteps/s (%.0f fps), A=1e7=%.0f usteps/s " + "(%.0f fps)\n", + b_1e6, b_1e6 / D, b_1e7, b_1e7 / D); + check(b_1e7 < 0.45 * b_1e6, + "A=1e7 pull-out is <45% of the A=1e6 pull-out (measured ~6x drop)"); + + // ---- 4. concrete scenario classification ------------------------------- + printf("\n=== P4: scenario runs/stalls at the measured points ===\n"); + // (accel, speed, expect_run, label) + struct scen_s { + double accel, speed; + bool run; + const char* label; + }; + const scen_s runs[] = { + {1.0e6, 110000.0, true, "A=1e6 @110k runs"}, + {1.0e6, 140000.0, false, "A=1e6 @140k stalls"}, + {1.0e7, 10000.0, true, "A=1e7 @10k runs"}, + {1.0e7, 45000.0, false, "A=1e7 @45k stalls"}, + {1.0e4, 120000.0, true, "A=1e4 @120k runs"}, + }; + for (size_t i = 0; i < sizeof(runs) / sizeof(runs[0]); i++) { + plant.reset(); + bool stalled = simulate_move(plant, runs[i].accel, runs[i].speed); + printf(" %-22s -> %s (delta=%.1f usteps)\n", runs[i].label, + stalled ? "STALL" : "run", plant.delta()); + check(stalled != runs[i].run, runs[i].label); + } + + // ---- 5. full-step / RPM conversion sanity ------------------------------ + printf("\n=== P5: unit conversions ===\n"); + printf(" 123000 usteps/s = %.0f full-steps/s = %.0f RPM\n", 123000.0 / D, + 123000.0 / D * 60.0 / STEPS_PER_REV); + check(fabs(123000.0 / D - 7687.5) < 1.0, + "123k usteps/s is ~7688 full-steps/s"); + check(fabs(123000.0 / D * 60.0 / STEPS_PER_REV - 2306.25) < 1.0, + "123k usteps/s is ~2306 RPM"); + + // ---- 6. physical artifacts: traces, wav, gnuplot ----------------------- + printf("\n=== P6: trace + wav + gnuplot artifacts ===\n"); + g_J_plant = J_plant; + g_fv = fv; + bool run_stall = + trace_scenario(1.0e6, 110000.0, 16, "test_28_run.dat", "test_28_run.wav"); + bool mid_stall = trace_scenario(1.0e6, 140000.0, 16, "test_28_stall.dat", + "test_28_stall.wav"); + bool acc_stall = trace_scenario(1.0e7, 45000.0, 16, "test_28_collapse.dat", + "test_28_collapse.wav"); + check(!run_stall, "the run scenario trace does not stall"); + check(mid_stall, "the steady-state stall scenario trace stalls"); + check(acc_stall, "the high-acceleration collapse trace stalls"); + write_boundary_dat(); + write_gnuplot_asset(); + + const char* dats[] = {"test_28_run.dat", "test_28_stall.dat", + "test_28_collapse.dat", "test_28_boundary.dat", + "test_28.gnuplot"}; + for (size_t i = 0; i < sizeof(dats) / sizeof(dats[0]); i++) { + check(file_size(dats[i]) > 0, dats[i]); + } + const char* wavs[] = {"test_28_run.wav", "test_28_stall.wav", + "test_28_collapse.wav"}; + for (size_t i = 0; i < sizeof(wavs) / sizeof(wavs[0]); i++) { + long sz = file_size(wavs[i]); + char msg[64]; + snprintf(msg, sizeof(msg), "%s is a non-empty PCM wav", wavs[i]); + check(sz > 44 && wav_peak(wavs[i]) > 0, msg); + } + + printf("\n%s (%d failure%s)\n", failures ? "FAILED" : "PASSED", failures, + failures == 1 ? "" : "s"); + return failures ? 1 : 0; +} diff --git a/tests/host/test_29.cpp b/tests/host/test_29.cpp new file mode 100644 index 0000000..d31c1ee --- /dev/null +++ b/tests/host/test_29.cpp @@ -0,0 +1,812 @@ +// test_29 — FasTimed, the faithful timed trajectory (problem 2). +// +// A waypoint is one constant rate: per-axis delta steps in [-128, 128] and +// one shared duration in [MIN_CMD_TICKS, 65535] driver ticks. The planner +// does not invent a ramp. PC only; the stepper is SimPort. +// +// Acceleration figures below are the ramp map at TICKS_PER_S = 16 MHz: +// a = 1e6, period 4000 -> P = 8, period 8000 -> P = 2, period 12000 -> P = +// 0 a = 1e7, period 2000 -> P = 3, period 3333 -> P = 1 +// A chunk may change ramp-step by at most its own step count, and a +// reversal or a zero-step axis is legal only from P = 0. + +#include +#include +#include +#include + +#include "FasTimed.h" +#include "fas_arch/test_pc.h" +#include "naxis_sim_port.h" +#include "../../examples/NaxesTimed/NaxesTimed_ramp.h" + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +char TCCR1A; +char TCCR1B; +char TCCR1C; +char TIMSK1; +char TIFR1; +unsigned short OCR1A; +unsigned short OCR1B; + +static TestStepperMotionEngine g_engine; + +static const char* add_name(TimedAdd a) { + if (a == TimedAdd::Ok) { + return "Ok"; + } + if (a == TimedAdd::Rejected) { + return "Rejected"; + } + if (a == TimedAdd::TimingNotAchievable) { + return "TimingNotAchievable"; + } + return "?"; +} + +static void expect_add(TimedAdd got, TimedAdd want, const char* what) { + if (got != want) { + printf("addDelta %s: got %s\n", what, add_name(got)); + } + test(got == want, what); +} + +struct CmdSeen { + uint16_t sum; + uint8_t steps; + bool count_up; +}; + +// Pull up to cap commands. Returns how many were pending. +static int drain_cmds(SimPort* p, CmdSeen* out, int cap) { + int n = 0; + while (n < cap && !p->isQueueEmpty()) { + int64_t st = 0; + bool up = false; + uint32_t sum = p->drain_one(&st, &up); + out[n].sum = (uint16_t)sum; + out[n].steps = (uint8_t)st; + out[n].count_up = up; + n++; + } + return n; +} + +static void anchor_ramp() { + test(MIN_CMD_TICKS == 3200, "PC MIN_CMD_TICKS is 3200"); + RampMap slow(500, 1000000); + test(slow.calculate_ramp_steps(4000) == 8, "P(4000) at 1e6 is 8"); + test(slow.calculate_ramp_steps(8000) == 2, "P(8000) at 1e6 is 2"); + test(slow.calculate_ramp_steps(12000) == 0, "P(12000) at 1e6 is 0"); + RampMap fast(80, 10000000); + test(fast.calculate_ramp_steps(2000) == 3, "P(2000) at 1e7 is 3"); + test(fast.calculate_ramp_steps(3333) == 1, "P(3333) at 1e7 is 1"); + RampMap huge(80, 100000000); + test(huge.calculate_ramp_steps(500) <= 128, "128 steps cover period 500"); + test(huge.calculate_ramp_steps(1066) <= 3, "3 steps cover a 3200-tick split"); +} + +// Limits, the ±128 / tick-window contract, and a dwell at both ends. +static void t_range_and_dwell() { + SimPort x(80, 64); + SimPort y(80, 64); + x.setAcceleration(100000000); + y.setAcceleration(100000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + test(plan.addAxis(0, &x), "range add X"); + test(plan.addAxis(1, &y), "range add Y"); + + int16_t z[2] = {0, 0}; + expect_add(plan.addDelta(z, 3200), TimedAdd::Rejected, "not synced"); + plan.syncFromSteppers(); + + x.setRampGeneratorActive(true); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> busy(g_engine); + test(!busy.addAxis(0, &x), "ramp active rejects addAxis"); + x.setRampGeneratorActive(false); + + int16_t hi[2] = {129, 0}; + int16_t lo[2] = {-129, 0}; + expect_add(plan.addDelta(hi, 64000), TimedAdd::Rejected, "+129 rejected"); + expect_add(plan.addDelta(lo, 64000), TimedAdd::Rejected, "-129 rejected"); + expect_add(plan.addDelta(z, 0), TimedAdd::Rejected, "0 ticks rejected"); + expect_add(plan.addDelta(z, (uint16_t)(MIN_CMD_TICKS - 1)), + TimedAdd::Rejected, "below MIN_CMD_TICKS rejected"); + test(plan.plannedPosition(0) == 0 && plan.actualTicks() == 0, + "a rejected call changes nothing"); + + expect_add(plan.addDelta(z, (uint16_t)MIN_CMD_TICKS), TimedAdd::Ok, + "dwell at MIN_CMD_TICKS"); + expect_add(plan.addDelta(z, 65535), TimedAdd::Ok, "dwell at 65535"); + test(plan.actualTicks() == (uint32_t)MIN_CMD_TICKS + 65535, + "dwell durations add"); + + int32_t origin[2] = {10, -4}; + plan.setCurrentPosition(origin); + test(plan.plannedPosition(0) == 10 && plan.plannedPosition(1) == -4, + "setCurrentPosition rebases and clears the plan"); + test(plan.actualTicks() == 0, "rebase clears actual ticks"); + + int16_t full[2] = {128, -128}; + expect_add(plan.addDelta(full, 64000), TimedAdd::Ok, "+/-128 accepted"); + test(plan.plannedPosition(0) == 138 && plan.plannedPosition(1) == -132, + "planned position sums the deltas"); + test(plan.actualTicks() == 64000, "128-step chunk keeps its duration"); + + test(plan.pump() == TimedStatus::Running, "boundary chunk is running"); + CmdSeen cx[2]; + CmdSeen cy[2]; + test(drain_cmds(&x, cx, 2) == 1, "X is one command"); + test(drain_cmds(&y, cy, 2) == 1, "Y is one command"); + test(cx[0].steps == 128 && cx[0].sum == 64000 && cx[0].count_up, + "X +128 in 64000"); + test(cy[0].steps == 128 && cy[0].sum == 64000 && !cy[0].count_up, + "Y -128 in 64000"); + test(x.clock() == y.clock() && x.clock() == 64000, "boundary clocks match"); + test(x.getCurrentPosition() == 128 && y.getCurrentPosition() == -128, + "steppers moved by the delta, not the rebased origin"); + test(plan.pump() == TimedStatus::Idle, "boundary run settles"); +} + +// Two axes, one command each, then the same rate again (cruise). +static void t_exact_and_cruise() { + SimPort x(500, 64); + SimPort y(500, 64); + x.setAcceleration(1000000); + y.setAcceleration(1000000); + FasTimed<2, 8, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t d[2] = {8, -4}; + expect_add(plan.addDelta(d, 32000), TimedAdd::Ok, "exact (8,-4)"); + expect_add(plan.addDelta(d, 32000), TimedAdd::Ok, "cruise (8,-4)"); + test(plan.plannedPosition(0) == 16 && plan.plannedPosition(1) == -8, + "cruise planned position"); + test(plan.actualTicks() == 64000, "two exact chunks"); + test(plan.isBusy(), "queued chunks are busy before pump"); + + test(plan.pump() == TimedStatus::Running, "exact pump"); + test(x.isRunning() && y.isRunning(), "kick-off started both queues"); + CmdSeen cx[4]; + CmdSeen cy[4]; + test(drain_cmds(&x, cx, 4) == 2, "X two cruise commands"); + test(drain_cmds(&y, cy, 4) == 2, "Y two cruise commands"); + test(cx[0].steps == 8 && cx[0].sum == 32000 && cx[0].count_up, "X cmd 0"); + test(cx[1].steps == 8 && cx[1].sum == 32000 && cx[1].count_up, "X cmd 1"); + test(cy[0].steps == 4 && cy[0].sum == 32000 && !cy[0].count_up, "Y cmd 0"); + test(cy[1].steps == 4 && cy[1].sum == 32000 && !cy[1].count_up, "Y cmd 1"); + test(x.clock() == 64000 && y.clock() == 64000, "cruise clocks"); + test(x.getCurrentPosition() == 16 && y.getCurrentPosition() == -8, + "cruise stepper positions"); + test(plan.pump() == TimedStatus::Idle, "cruise settles"); + test(!plan.isBusy(), "idle is not busy"); +} + +// Master is one command; the short axis splits into q+1 and q groups. +// Idle axis pauses for the same sum. +static void t_split() { + SimPort x(500, 64); + SimPort y(500, 64); + x.setAcceleration(1000000); + y.setAcceleration(1000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t d[2] = {8, 3}; + expect_add(plan.addDelta(d, 32000), TimedAdd::Ok, "split slave (8,3)"); + plan.pump(); + CmdSeen cx[2]; + CmdSeen cy[4]; + test(drain_cmds(&x, cx, 2) == 1, "master is one command"); + test(cx[0].steps == 8 && cx[0].sum == 32000 && cx[0].count_up, "master 8"); + test(drain_cmds(&y, cy, 4) == 2, "slave is two commands"); + // 32000 = 2 * 10667 + 1 * 10666 + test(cy[0].steps == 2 && cy[0].sum == 21334 && cy[0].count_up, + "slave long group"); + test(cy[1].steps == 1 && cy[1].sum == 10666 && cy[1].count_up, + "slave short group"); + test(x.clock() == 32000 && y.clock() == 32000, "split clocks match"); + test(x.getCurrentPosition() == 8 && y.getCurrentPosition() == 3, + "split positions"); + + // 3 steps in 10000: groups 1*3334 and 2*3333. Needs the faster map so + // P(3333) = 1 fits in 3 steps. The partner pauses. + SimPort a(80, 64); + SimPort b(80, 64); + a.setAcceleration(10000000); + b.setAcceleration(10000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> fast(g_engine); + fast.addAxis(0, &a); + fast.addAxis(1, &b); + fast.syncFromSteppers(); + int16_t e[2] = {3, 0}; + expect_add(fast.addDelta(e, 10000), TimedAdd::Ok, "3 steps in 10000"); + fast.pump(); + CmdSeen ca[4]; + CmdSeen cb[2]; + test(drain_cmds(&a, ca, 4) == 2, "3-step split is two commands"); + test(ca[0].steps == 1 && ca[0].sum == 3334 && ca[0].count_up, "remainder 1"); + test(ca[1].steps == 2 && ca[1].sum == 6666 && ca[1].count_up, "pair at q"); + test(drain_cmds(&b, cb, 2) == 1, "idle axis is one pause"); + test(cb[0].steps == 0 && cb[0].sum == 10000 && cb[0].count_up, + "pause keeps DIR and the full duration"); + test(a.clock() == 10000 && b.clock() == 10000, "pause clock matches"); + test(a.getCurrentPosition() == 3 && b.getCurrentPosition() == 0, + "pause axis did not step"); +} + +// 10 * 2000 = 20000 is the nearest legal sum to 20001 (one tick short). +// 3 steps in 3200 cannot be a legal split; the next legal sum is 3 * 1067. +// Acceleration is 1e8 so both periods are inside the 3-step and 10-step ramp. +static void t_quantize() { + SimPort x(80, 64); + SimPort y(80, 64); + x.setAcceleration(100000000); + y.setAcceleration(100000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t d[2] = {10, 0}; + expect_add(plan.addDelta(d, 20001), TimedAdd::Ok, "20001 quantizes"); + test(plan.actualTicks() == 20000, "nearest sum is 20000"); + plan.pump(); + CmdSeen cx[2]; + CmdSeen cy[2]; + test(drain_cmds(&x, cx, 2) == 1, "quantized X is one command"); + test(cx[0].steps == 10 && cx[0].sum == 20000 && cx[0].count_up, "10 * 2000"); + test(drain_cmds(&y, cy, 2) == 1 && cy[0].steps == 0 && cy[0].sum == 20000, + "idle axis follows the issued sum, not 20001"); + test(x.clock() == y.clock() && x.clock() == 20000, "quantize clocks"); + + int16_t up[2] = {3, 0}; + expect_add(plan.addDelta(up, 3200), TimedAdd::Ok, "3200 rounds up"); + test(plan.actualTicks() == 20000 + 3201, "3 * 1067 = 3201"); + plan.pump(); + test(drain_cmds(&x, cx, 2) == 1, "rounded X is one command"); + test(cx[0].steps == 3 && cx[0].sum == 3201, "period 1067"); + test(drain_cmds(&y, cy, 2) == 1 && cy[0].steps == 0 && cy[0].sum == 3201, + "rounded pause matches"); +} + +static void t_too_fast_and_accel() { + SimPort x(500, 64); + SimPort y(500, 64); + x.setAcceleration(1000000); + y.setAcceleration(1000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t fast[2] = {8, 0}; + // 8 * 500 = 4000 > 3200, so the average period is under the speed floor. + expect_add(plan.addDelta(fast, 3200), TimedAdd::TimingNotAchievable, + "faster than ticks_cfg"); + test(plan.plannedPosition(0) == 0 && plan.actualTicks() == 0, + "too-fast does not commit"); + test(plan.pump() == TimedStatus::Idle, "too-fast queues nothing"); + + int16_t four[2] = {4, 0}; + // Period 4000, P = 8, and 4 steps cannot cover that jump from rest. + expect_add(plan.addDelta(four, 16000), TimedAdd::TimingNotAchievable, + "from rest P=8 needs more than 4 steps"); + + int16_t two[2] = {2, 0}; + expect_add(plan.addDelta(two, 16000), TimedAdd::Ok, "from rest P=2 in 2"); + int16_t jump[2] = {4, 0}; + // Period 4000 is P = 8, delta 6, and this chunk has only 4 steps. + expect_add(plan.addDelta(jump, 16000), TimedAdd::TimingNotAchievable, + "accel jump of 6 does not fit in 4 steps"); + test(plan.plannedPosition(0) == 2 && plan.actualTicks() == 16000, + "failed jump leaves the first chunk"); + + int16_t ok[2] = {8, 0}; + expect_add(plan.addDelta(ok, 32000), TimedAdd::Ok, + "delta P of 6 fits in 8 steps"); + test(plan.plannedPosition(0) == 10, "position after the legal accel"); + + // The partner axis is still at rest, so a later chunk may move only X. + int16_t only_y[2] = {0, 2}; + expect_add(plan.addDelta(only_y, 16000), TimedAdd::TimingNotAchievable, + "X at P=8 cannot take a zero-step chunk"); +} + +// Decel to P = 0, then reverse. An immediate reverse, and a dwell while +// still at speed, are TimingNotAchievable. +static void t_reversal_and_dwell() { + SimPort x(500, 64); + x.setAcceleration(1000000); + FasTimed<1, 8, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.syncFromSteppers(); + + int16_t a = 2; + int16_t rev = -2; + int16_t dwell = 0; + expect_add(plan.addDelta(&a, 16000), TimedAdd::Ok, "leave rest at P=2"); + expect_add(plan.addDelta(&rev, 16000), TimedAdd::TimingNotAchievable, + "reverse while P=2"); + expect_add(plan.addDelta(&dwell, 8000), TimedAdd::TimingNotAchievable, + "dwell while P=2"); + test(plan.plannedPosition(0) == 2 && plan.actualTicks() == 16000, + "illegal reverse and dwell do not commit"); + + expect_add(plan.addDelta(&a, 24000), TimedAdd::Ok, "decel to P=0"); + expect_add(plan.addDelta(&dwell, 8000), TimedAdd::Ok, "dwell from rest"); + expect_add(plan.addDelta(&rev, 16000), TimedAdd::Ok, "reverse from P=0"); + test(plan.plannedPosition(0) == 2, "2 + 2 + 0 - 2"); + test(plan.actualTicks() == 64000, "16000+24000+8000+16000"); + + plan.pump(); + CmdSeen c[6]; + test(drain_cmds(&x, c, 6) == 4, "four commands"); + test(c[0].steps == 2 && c[0].sum == 16000 && c[0].count_up, "out"); + test(c[1].steps == 2 && c[1].sum == 24000 && c[1].count_up, "decel"); + test(c[2].steps == 0 && c[2].sum == 8000 && c[2].count_up, + "dwell keeps the last DIR"); + test(c[3].steps == 2 && c[3].sum == 16000 && !c[3].count_up, "back"); + test(x.getCurrentPosition() == 2 && x.clock() == 64000, "reversal landed"); + test(plan.pump() == TimedStatus::Idle, "reversal settles"); +} + +// A one-shot QueueFull holds that axis's command for the next pump. +static void t_retry() { + SimPort x(500, 64); + SimPort y(500, 64); + x.setAcceleration(1000000); + y.setAcceleration(1000000); + FasTimed<2, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t d[2] = {2, 2}; + expect_add(plan.addDelta(d, 16000), TimedAdd::Ok, "retry chunk"); + y.failNext(AQE_QUEUE_FULL); + test(plan.pump() == TimedStatus::Running, "faulting pump still running"); + test(x.queueEntries() == 1, "X took its command"); + test(y.queueEntries() == 0, "Y held the refused command"); + test(plan.isBusy(), "held command keeps the plan busy"); + + test(plan.pump() == TimedStatus::Running, "retry pump"); + test(y.queueEntries() == 1, "Y accepts the held command"); + CmdSeen cx[2]; + CmdSeen cy[2]; + test(drain_cmds(&x, cx, 2) == 1 && drain_cmds(&y, cy, 2) == 1, "one each"); + test(cx[0].steps == 2 && cx[0].sum == 16000, "X retry payload"); + test(cy[0].steps == 2 && cy[0].sum == 16000, "Y retry payload"); + test(x.clock() == y.clock(), "retry clocks"); + test(plan.pump() == TimedStatus::Idle, "retry settles"); +} + +// Queue shorter than the plan: draining it dry while chunks remain is +// Underrun, and the following pumps still deliver the rest. +static void t_underrun() { + SimPort x(500, 4); + SimPort y(500, 4); + x.setAcceleration(1000000); + y.setAcceleration(1000000); + FasTimed<2, 8, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.addAxis(1, &y); + plan.syncFromSteppers(); + + int16_t d[2] = {2, 2}; + for (int i = 0; i < 4; i++) { + expect_add(plan.addDelta(d, 16000), TimedAdd::Ok, "underrun chunk"); + } + TimedStatus st = plan.pump(); + test(st == TimedStatus::Running, "short queue still running"); + test(x.queueEntries() > 0 && x.queueEntries() < 4, "X did not take all 4"); + + while (!x.isQueueEmpty() || !y.isQueueEmpty()) { + x.drain(); + y.drain(); + } + st = plan.pump(); + test(st == TimedStatus::Underrun, "empty queue with chunks left"); + // Underrun latches, but the feeder keeps filling. + for (int i = 0; i < 4 && plan.isBusy(); i++) { + x.drain(); + y.drain(); + plan.pump(); + } + test(x.getCurrentPosition() == 8 && y.getCurrentPosition() == 8, + "underrun still delivers every step"); + test(x.clock() == y.clock() && x.clock() == 64000, "underrun clocks"); +} + +static void t_horizon() { + SimPort x(80, 64); + x.setAcceleration(10000000); + FasTimed<1, 2, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.syncFromSteppers(); + int16_t z = 0; + expect_add(plan.addDelta(&z, 3200), TimedAdd::Ok, "horizon 0"); + expect_add(plan.addDelta(&z, 3200), TimedAdd::Ok, "horizon 1"); + expect_add(plan.addDelta(&z, 3200), TimedAdd::Rejected, "horizon full"); + test(plan.actualTicks() == 6400, "full ring did not take the third"); + plan.pump(); + x.drain(); + test(plan.pump() == TimedStatus::Idle, "horizon drained"); + expect_add(plan.addDelta(&z, 3200), TimedAdd::Ok, "ring slides"); + test(plan.actualTicks() == 9600, "committed sum keeps the drained dwells"); +} + +static void t_stop_and_inject() { + SimPort x(500, 64); + x.setAcceleration(1000000); + FasTimed<1, 4, SimPort, TestStepperMotionEngine> plan(g_engine); + plan.addAxis(0, &x); + plan.syncFromSteppers(); + int16_t d = 2; + expect_add(plan.addDelta(&d, 16000), TimedAdd::Ok, "stop setup"); + x.setStopCause(StepperStopCause::ForceStop); + test(plan.pump() == TimedStatus::Stopped, "external stop"); + test(plan.pump() == TimedStatus::Stopped, "stop latches"); + expect_add(plan.addDelta(&d, 16000), TimedAdd::Rejected, + "no add while stopped"); + plan.syncFromSteppers(); + int16_t z = 0; + expect_add(plan.addDelta(&z, 3200), TimedAdd::Ok, "sync clears the stop"); + + SimPort y(500, 64); + y.setAcceleration(1000000); + y.setInjectMode(SimPort::InjectDirPauses); + FasTimed<1, 4, SimPort, TestStepperMotionEngine> rev(g_engine); + rev.addAxis(0, &y); + rev.syncFromSteppers(); + int16_t a = 2; + int16_t back = -2; + expect_add(rev.addDelta(&a, 16000), TimedAdd::Ok, "inject out"); + expect_add(rev.addDelta(&a, 24000), TimedAdd::Ok, "inject decel"); + expect_add(rev.addDelta(&back, 16000), TimedAdd::Ok, "inject reverse"); + test(rev.pump() == TimedStatus::Error, "unplanned DIR pause is Error"); +} + +// A square streamed through a ring of 8 chunks. The pitch ladder is +// examples/NaxesTimed/NaxesTimed_ramp.h: about one second rising from 440 Hz to +// 2500 Hz, then about one second falling back to a stop. The trace is +// test_29.dat / test_29.gnuplot; the first two motors are the left and +// right channels of test_29.wav. +static const uint32_t kAudioSr = 44100; +static const double kTicksPerS = 16000000.0; + +struct Seg { + int16_t x; + int16_t y; + uint16_t ticks; +}; + +static void push_seg(Seg* s, int* n, int axis, int sign, int steps, + uint16_t ticks) { + s[*n].x = 0; + s[*n].y = 0; + if (axis == 0) { + s[*n].x = (int16_t)(sign * steps); + } else { + s[*n].y = (int16_t)(sign * steps); + } + s[*n].ticks = ticks; + (*n)++; +} + +// Hold one step period. The chunk uses as many steps as fit in 65535 ticks, +// which is enough for the ramp-step change into this period at a = 1e5. +static void push_hold(Seg* s, int* n, int axis, int sign, uint16_t period, + int repeats) { + uint32_t steps = 65535u / period; + if (steps > 128) { + steps = 128; + } + if (steps < 1) { + steps = 1; + } + uint16_t ticks = (uint16_t)(steps * period); + for (int i = 0; i < repeats; i++) { + push_seg(s, n, axis, sign, (int)steps, ticks); + } +} + +static void push_side(Seg* s, int* n, int axis, int sign) { + for (unsigned i = 0; + i < sizeof(kNaxesTimedUpPeriod) / sizeof(kNaxesTimedUpPeriod[0]); i++) { + push_hold(s, n, axis, sign, kNaxesTimedUpPeriod[i], kNaxesTimedUpHold); + } + for (unsigned i = 0; + i < sizeof(kNaxesTimedDownPeriod) / sizeof(kNaxesTimedDownPeriod[0]); + i++) { + push_hold(s, n, axis, sign, kNaxesTimedDownPeriod[i], kNaxesTimedDownHold); + } +} + +static void wav_u16(FILE* f, uint16_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); +} +static void wav_u32(FILE* f, uint32_t v) { + fputc((int)(v & 0xff), f); + fputc((int)((v >> 8) & 0xff), f); + fputc((int)((v >> 16) & 0xff), f); + fputc((int)((v >> 24) & 0xff), f); +} + +static void click(int16_t* pcm, uint32_t frames, uint32_t at, int channel) { + static const int16_t kPulse[4] = {8000, 22000, 14000, 5000}; + for (int s = 0; s < 4; s++) { + uint32_t i = at + (uint32_t)s; + if (i >= frames) { + return; + } + int32_t v = pcm[i * 2 + channel] + kPulse[s]; + if (v > 32767) { + v = 32767; + } + pcm[i * 2 + channel] = (int16_t)v; + } +} + +static uint32_t tick_to_sample(uint32_t tick, uint32_t frames) { + uint32_t s = (uint32_t)(((uint64_t)tick * kAudioSr) / 16000000ull); + if (s >= frames) { + s = frames - 1; + } + return s; +} + +static void write_stereo_wav(const char* path, const int16_t* pcm, + uint32_t frames) { + FILE* fp = fopen(path, "wb"); + test(fp != NULL, "open test_29.wav"); + const uint16_t bps = 16; + const uint16_t ch = 2; + const uint32_t data_bytes = frames * ch * (bps / 8); + fwrite("RIFF", 1, 4, fp); + wav_u32(fp, 36 + data_bytes); + fwrite("WAVE", 1, 4, fp); + fwrite("fmt ", 1, 4, fp); + wav_u32(fp, 16); + wav_u16(fp, 1); + wav_u16(fp, ch); + wav_u32(fp, kAudioSr); + wav_u32(fp, kAudioSr * ch * (bps / 8)); + wav_u16(fp, ch * (bps / 8)); + wav_u16(fp, bps); + fwrite("data", 1, 4, fp); + wav_u32(fp, data_bytes); + for (uint32_t i = 0; i < frames * 2; i++) { + wav_u16(fp, (uint16_t)pcm[i]); + } + fclose(fp); +} + +static void write_gnuplot() { + FILE* g = fopen("test_29.gnuplot", "w"); + test(g != NULL, "open test_29.gnuplot"); + fprintf(g, + "set term pngcairo size 1200,900\n" + "set output \"test_29.png\"\n" + "set multiplot layout 2,2 title " + "\"FasTimed square: pitch rises and falls on each side\"\n" + "set title \"path [steps]\"\n" + "set xlabel \"x\"\n" + "set ylabel \"y\"\n" + "plot \"test_29.dat\" using 2:3 with lines title \"head\"\n" + "set title \"position\"\n" + "set xlabel \"t [s]\"\n" + "set ylabel \"steps\"\n" + "plot \"test_29.dat\" using 1:2 with lines title \"x\", " + "\"test_29.dat\" using 1:3 with lines title \"y\"\n" + "set title \"speed\"\n" + "set ylabel \"steps/s\"\n" + "plot \"test_29.dat\" using 1:4 with lines title \"vx\", " + "\"test_29.dat\" using 1:5 with lines title \"vy\"\n" + "set title \"|speed|\"\n" + "plot \"test_29.dat\" using 1:(abs($4)) with lines title \"|vx|\", " + "\"test_29.dat\" using 1:(abs($5)) with lines title \"|vy|\"\n" + "unset multiplot\n" + "unset output\n"); + fclose(g); +} + +static int wav_peak(const char* path, int* left_nz, int* right_nz) { + FILE* f = fopen(path, "rb"); + test(f != NULL, "reopen wav"); + unsigned char hdr[44]; + test(fread(hdr, 1, 44, f) == 44, "wav header"); + test(memcmp(hdr, "RIFF", 4) == 0 && memcmp(hdr + 8, "WAVE", 4) == 0, + "wav is RIFF/WAVE"); + test(hdr[22] == 2 && hdr[23] == 0, "wav is stereo"); + int peak = 0; + *left_nz = 0; + *right_nz = 0; + unsigned char b[4]; + while (fread(b, 1, 4, f) == 4) { + int16_t l = (int16_t)(b[0] | (b[1] << 8)); + int16_t r = (int16_t)(b[2] | (b[3] << 8)); + int al = l < 0 ? -l : l; + int ar = r < 0 ? -r : r; + if (al > peak) { + peak = al; + } + if (ar > peak) { + peak = ar; + } + if (al > 1000) { + (*left_nz)++; + } + if (ar > 1000) { + (*right_nz)++; + } + } + fclose(f); + return peak; +} + +static void record_pair(SimPort* x, SimPort* y, FILE* dat, int16_t* pcm, + uint32_t frames) { + uint32_t t0 = x->clock(); + test(y->clock() == t0, "axes share the clock before the command"); + int64_t sx = 0; + int64_t sy = 0; + bool ux = true; + bool uy = true; + uint32_t dx = x->drain_one(&sx, &ux); + uint32_t dy = y->drain_one(&sy, &uy); + test(dx == dy && dx > 0, "paired commands cover the same ticks"); + double t = (double)t0 / kTicksPerS; + double vx = 0.0; + double vy = 0.0; + if (sx > 0) { + vx = (ux ? 1.0 : -1.0) * kTicksPerS * (double)sx / (double)dx; + } + if (sy > 0) { + vy = (uy ? 1.0 : -1.0) * kTicksPerS * (double)sy / (double)dy; + } + uint32_t span = dx; + uint32_t nstep = (uint32_t)sx; + if ((uint32_t)sy > nstep) { + nstep = (uint32_t)sy; + } + if (nstep == 0) { + nstep = 1; + } + int32_t x_at = x->getCurrentPosition() - (ux ? (int32_t)sx : -(int32_t)sx); + int32_t y_at = y->getCurrentPosition() - (uy ? (int32_t)sy : -(int32_t)sy); + uint32_t x_left = (uint32_t)sx; + uint32_t y_left = (uint32_t)sy; + uint32_t period = span / nstep; + for (uint32_t k = 0; k < nstep; k++) { + uint32_t tick = t0 + k * period; + if (x_left > 0) { + x_at += ux ? 1 : -1; + x_left--; + click(pcm, frames, tick_to_sample(tick, frames), 0); + } + if (y_left > 0) { + y_at += uy ? 1 : -1; + y_left--; + click(pcm, frames, tick_to_sample(tick, frames), 1); + } + double tk = (double)(tick + period) / kTicksPerS; + fprintf(dat, "%.6f %d %d %.3f %.3f\n", tk, x_at, y_at, vx, vy); + (void)t; + } +} + +static void t_square_trace() { + RampMap map(500, 100000); + test(map.calculate_ramp_steps(36000) == 0, "trace start is ramp-step 0"); + test(map.calculate_ramp_steps(6400) == 31, "trace top is ramp-step 31"); + test(16000000.0 / 6400 > 4.0 * (16000000.0 / 36000), + "top pitch is more than two octaves above the start"); + + Seg segs[2200]; + int n = 0; + push_side(segs, &n, 0, +1); + push_side(segs, &n, 1, +1); + push_side(segs, &n, 0, -1); + push_side(segs, &n, 1, -1); + uint32_t total_ticks = 0; + for (int i = 0; i < n; i++) { + total_ticks += segs[i].ticks; + } + uint32_t frames = + (uint32_t)(((uint64_t)total_ticks * kAudioSr) / 16000000ull) + 8; + int16_t* pcm = (int16_t*)calloc(frames * 2, sizeof(int16_t)); + test(pcm != NULL, "pcm buffer"); + FILE* dat = fopen("test_29.dat", "w"); + test(dat != NULL, "open test_29.dat"); + fprintf(dat, "0.000000 0 0 0.000 0.000\n"); + + SimPort x(500, 64); + SimPort y(500, 64); + x.setAcceleration(kNaxesTimedAccel); + y.setAcceleration(kNaxesTimedAccel); + FasTimed<2, 8, SimPort, TestStepperMotionEngine> plan(g_engine); + test(plan.addAxis(0, &x), "trace add X"); + test(plan.addAxis(1, &y), "trace add Y"); + plan.syncFromSteppers(); + + int i = 0; + while (i < n) { + int16_t d[2] = {segs[i].x, segs[i].y}; + TimedAdd a = plan.addDelta(d, segs[i].ticks); + if (a == TimedAdd::Ok) { + i++; + continue; + } + expect_add(a, TimedAdd::Rejected, "horizon 8 backpressure"); + test(plan.pump() == TimedStatus::Running, "trace pump while streaming"); + while (!x.isQueueEmpty() && !y.isQueueEmpty()) { + record_pair(&x, &y, dat, pcm, frames); + } + test(plan.pump() == TimedStatus::Idle, "drained batch settles the ring"); + } + test(plan.pump() == TimedStatus::Running, "trace flushes the tail"); + while (!x.isQueueEmpty() && !y.isQueueEmpty()) { + record_pair(&x, &y, dat, pcm, frames); + } + test(plan.pump() == TimedStatus::Idle, "trace settles"); + test(x.getCurrentPosition() == 0 && y.getCurrentPosition() == 0, + "square closes"); + test(x.clock() == y.clock() && x.clock() == total_ticks, + "square clocks match the script"); + fclose(dat); + write_stereo_wav("test_29.wav", pcm, frames); + write_gnuplot(); + free(pcm); + + int left_nz = 0; + int right_nz = 0; + int peak = wav_peak("test_29.wav", &left_nz, &right_nz); + test(peak > 1000, "stereo wav is audible"); + test(left_nz > 100 && right_nz > 100, "both motors are in the wav"); + FILE* g = fopen("test_29.gnuplot", "rb"); + test(g != NULL, "gnuplot exists"); + char buf[256]; + size_t got = fread(buf, 1, sizeof(buf) - 1, g); + buf[got] = 0; + fclose(g); + test(strstr(buf, "test_29.dat") != NULL, "gnuplot reads the trace"); + FILE* rows = fopen("test_29.dat", "rb"); + test(rows != NULL, "dat exists"); + int lines = 0; + int c; + while ((c = fgetc(rows)) != EOF) { + if (c == '\n') { + lines++; + } + } + fclose(rows); + test(lines > 200, "gnuplot trace has the square"); + printf("test_29 trace: test_29.gnuplot test_29.dat test_29.wav (%u frames)\n", + frames); +} + +int main() { + anchor_ramp(); + t_range_and_dwell(); + t_exact_and_cruise(); + t_split(); + t_quantize(); + t_too_fast_and_accel(); + t_reversal_and_dwell(); + t_retry(); + t_underrun(); + t_horizon(); + t_stop_and_inject(); + t_square_trace(); + puts("test_29 passed"); + return 0; +} diff --git a/tests/host/test_30.cpp b/tests/host/test_30.cpp new file mode 100644 index 0000000..eff248b --- /dev/null +++ b/tests/host/test_30.cpp @@ -0,0 +1,268 @@ +// test_30 - ESP32 RMT V2 fill: read-ahead window invariant. +// +// The encoder splits long steps into RMT symbols so that no PART_SIZE-symbol +// window (one RMT half) spans more than RMT_BLOCK_TICKS. That is the whole +// read-ahead guarantee: the buffer cannot hold more time than the ramp +// lookahead, so the queue cannot be drained mid-move. +// +// The fill carries only the remaining low phase. The step high is +// min(ticks >> 1, RMT_MAX_SYMBOL_TICKS), i.e. just another sub-entry. +// +// The second half is the direction-change invariant. LL_TOGGLE_PIN runs while +// *encoding*, and a pause entry is consumed when it is scheduled rather than +// when it is played, so a pause delays the toggle only by the share of the RMT +// buffer it occupies. A pause that fits in the buffer delays it not at all and +// the toggle lands while the previous segment is still stepping -- which is +// what SR_11/SR_12 caught on hardware. + +#include +#include + +uint16_t debug_part_size = 32; + +#include "StepperMotion.h" + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +static int dir_toggles = 0; +static uint32_t cur_rises; +static uint32_t toggle_after_rise[8]; +#define SUPPORT_ESP32_RMT_V2 +#define IRAM_ATTR +#define RMT_CHANNEL_T int +#define LL_TOGGLE_PIN(dirPin) \ + do { \ + if (dir_toggles < 8) toggle_after_rise[dir_toggles] = cur_rises; \ + dir_toggles++; \ + } while (0) +#include "pd_esp32/StepperISR_rmt_v2_encode.cpp" + +static int failures = 0; + +static void expect(bool ok, const char* msg) { + if (!ok) { + printf("FAIL: %s\n", msg); + failures++; + } +} + +static void decode(uint32_t word, uint16_t* dur0, bool* lvl0, uint16_t* dur1, + bool* lvl1) { + *dur0 = (uint16_t)(word & 0x7fff); + *lvl0 = (word & 0x8000) != 0; + *dur1 = (uint16_t)((word >> 16) & 0x7fff); + *lvl1 = (word & 0x80000000) != 0; +} + +static uint32_t symbol_ticks(uint32_t word) { + return (uint32_t)(word & 0x7fff) + (uint32_t)((word >> 16) & 0x7fff); +} + +static void reset_queue() { + fas_queue[0]._initVars(); + fas_queue[0].read_idx = 0; + fas_queue[0].next_write_idx = 0; + dir_toggles = 0; + cur_rises = 0; +} + +static void push(uint8_t steps, uint16_t ticks, bool toggle) { + uint8_t idx = fas_queue[0].next_write_idx & QUEUE_LEN_MASK; + fas_queue[0].entry[idx].steps = steps; + fas_queue[0].entry[idx].ticks = ticks; + fas_queue[0].entry[idx].toggle_dir = toggle ? 1 : 0; + fas_queue[0].entry[idx].countUp = 1; + fas_queue[0].entry[idx].hasSteps = steps != 0; + fas_queue[0].next_write_idx++; +} + +// --- sliding PART_SIZE-symbol window --------------------------------------- +static uint32_t win[64]; +static uint32_t win_pos, win_count, win_sum, win_max; + +static void window_reset() { win_pos = win_count = win_sum = win_max = 0; } + +static void window_add(uint32_t ticks) { + if (win_count == (uint32_t)PART_SIZE) { + win_sum -= win[win_pos]; + } else { + win_count++; + } + win[win_pos] = ticks; + win_sum += ticks; + if (++win_pos == (uint32_t)PART_SIZE) { + win_pos = 0; + } + if (win_count == (uint32_t)PART_SIZE && win_sum > win_max) { + win_max = win_sum; + } +} + +// --- one command: fill until the queue and the fill state are drained ------ +static uint64_t commanded_ticks, emitted_ticks; +static uint32_t emitted_edges, expected_edges; +static uint16_t min_subentry; +static bool last_level; + +static void emit(const uint32_t* sym, uint32_t n) { + for (uint32_t i = 0; i < n; i++) { + uint16_t d0, d1; + bool l0, l1; + decode(sym[i], &d0, &l0, &d1, &l1); + if (d0 < min_subentry) min_subentry = d0; + if (d1 < min_subentry) min_subentry = d1; + if (l0 && !last_level) { + emitted_edges++; + cur_rises++; + } + last_level = l0; + if (l1 && !last_level) { + emitted_edges++; + cur_rises++; + } + last_level = l1; + emitted_ticks += symbol_ticks(sym[i]); + window_add(symbol_ticks(sym[i])); + } +} + +static void run_case(uint8_t steps, uint16_t ticks, bool toggle) { + reset_queue(); + window_reset(); + commanded_ticks = (uint64_t)ticks * (steps ? steps : 1); + emitted_ticks = 0; + emitted_edges = 0; + expected_edges = steps; + min_subentry = 0xffff; + last_level = false; + + push(steps, ticks, toggle); + + struct rmt_fill_state state = {}; + uint32_t sym[2 * 64]; + uint32_t guard = 0; + while (fas_queue[0].read_idx != fas_queue[0].next_write_idx || + state.remaining_low_ticks != 0) { + uint32_t n = + rmt_encode_fill(&fas_queue[0], &state, sym, 2 * (uint32_t)PART_SIZE); + if (n == 0) { + break; + } + emit(sym, n); + if (++guard > 100000) { + break; + } + } + + expect(emitted_ticks == commanded_ticks, "symbol ticks == commanded ticks"); + expect(emitted_edges == expected_edges, "one rising edge per step"); + expect(state.remaining_low_ticks == 0, "fill state drained"); + expect(min_subentry >= 2, "every sub-entry >= 2 ticks (relation 1)"); + expect(win_max <= RMT_MAX_INFLIGHT_TICKS, + "every PART_SIZE-symbol window <= RMT_MAX_INFLIGHT_TICKS"); +} + +// --- direction change +// --------------------------------------------------------- The queue the +// library builds for a direction change is +// [steps_a @ticks, no toggle] [drain pause] [steps_b @ticks, TOGGLE] +// The first entry carries no toggle because standstill sets the pin directly +// (queue empty). The toggle therefore has exactly one job: it must not run +// before the pin has finished steps_a. +// +// `free_per_call` models how many symbols the RMT driver hands the encoder per +// callback. Which value the driver really uses is not established here, so both +// the half and the whole buffer are exercised. +static void run_dir_case(uint8_t steps_a, uint16_t ticks, uint16_t drain, + uint32_t free_per_call) { + reset_queue(); + window_reset(); + emitted_ticks = 0; + emitted_edges = 0; + min_subentry = 0xffff; + last_level = false; + emitted_edges = 0; + + push(steps_a, ticks, false); + push(0, drain, false); + push(255, ticks, true); + + struct rmt_fill_state state = {}; + uint32_t sym[512]; + uint32_t guard = 0; + uint32_t n_a = 0; + while (fas_queue[0].read_idx != fas_queue[0].next_write_idx || + state.remaining_low_ticks != 0) { + uint32_t n = rmt_encode_fill(&fas_queue[0], &state, sym, free_per_call); + if (n == 0) { + break; + } + emit(sym, n); + if (dir_toggles == 1 && n_a == 0) { + n_a = toggle_after_rise[0]; + } + if (++guard > 100000) { + break; + } + } + + expect(dir_toggles == 1, "exactly one DIR toggle"); + expect(n_a == steps_a, + "DIR toggle runs only after the previous segment's last step"); + expect(state.remaining_low_ticks == 0, "fill state drained"); +} + +static void run_dir_suite(uint16_t part) { + debug_part_size = part; + printf( + "\n--- PART_SIZE %u: DIR drain (buffer=%u ticks, drain=%u ticks) ---\n", + part, (uint32_t)RMT_BUFFER_TICKS, (uint32_t)RMT_DIR_DRAIN_TICKS); + expect(RMT_DIR_DRAIN_TICKS > RMT_BUFFER_TICKS, + "DIR drain exceeds the RMT buffer's playback content"); + + static const uint16_t ticks[] = {80, 160, 320, 640, 3200, 20000}; + static const uint8_t steps[] = {1, 10, 20, 51, 255}; + const uint32_t frees[] = {(uint32_t)PART_SIZE, 2 * (uint32_t)PART_SIZE}; + for (uint32_t f = 0; f < sizeof(frees) / sizeof(frees[0]); f++) { + for (uint32_t t = 0; t < sizeof(ticks) / sizeof(ticks[0]); t++) { + for (uint32_t s = 0; s < sizeof(steps) / sizeof(steps[0]); s++) { + run_dir_case(steps[s], ticks[t], RMT_DIR_DRAIN_TICKS, frees[f]); + } + } + } +} + +static void run_suite(uint16_t part) { + debug_part_size = part; + printf("\n=== PART_SIZE %u (cap=%u, window limit=%u) ===\n", part, + (uint32_t)RMT_MAX_SYMBOL_TICKS, (uint32_t)RMT_MAX_INFLIGHT_TICKS); + + static const uint16_t ticks[] = {4, 5, 8, 99, 250, + 251, 500, 640, 3200, 5000, + 7500, 10000, 20000, 32767, 65535}; + static const uint8_t steps[] = {1, 2, 5, 51, 255}; + for (uint32_t t = 0; t < sizeof(ticks) / sizeof(ticks[0]); t++) { + for (uint32_t s = 0; s < sizeof(steps) / sizeof(steps[0]); s++) { + run_case(steps[s], ticks[t], false); + } + } + run_case(0, 3200, false); // pause + run_case(0, 65535, false); // long pause + run_case(1, 640, true); // direction toggle + run_case(255, 65535, true); +} + +int main() { + run_suite(32); + run_suite(24); + run_dir_suite(32); + run_dir_suite(24); + if (failures != 0) { + printf("%d failure(s)\n", failures); + return 1; + } + printf("PASS\n"); + return 0; +} diff --git a/tests/host/test_31.cpp b/tests/host/test_31.cpp new file mode 100644 index 0000000..1d8c91b --- /dev/null +++ b/tests/host/test_31.cpp @@ -0,0 +1,202 @@ +// test_31: the queue admission latch +// +// A forceStop() / forceStopAndNewPosition() sets a latch that makes +// addQueueEntry() refuse every command. Before the fix the latch: +// - was cleared by fill_queue() before it could refuse anything (so it was +// inert for a ramp user), and never cleared on the addQueueEntry() path +// (so it was permanent for a low-level user), +// - sat *inside* the function, after the entry fields were written and after +// the DIR pin was driven, so a refused command still moved the pin, still +// updated queue_end.dir, and still counted towards the pause statistics, +// - returned AQE_OK for the dropped command, so the caller advanced its own +// position model by steps that were never queued, +// - and let addQueueEntry(NULL, start) start a suspended queue anyway. +// +// Keep the connection across resets: reconnecting with stepperConnectToPin() +// would zero the queue and rearm the latch. +// +// StepperISR_test.cpp stubs StepperQueue::forceStop() to an empty body, so the +// queue is not emptied here. That is irrelevant: the defect is the refusal, not +// the emptying, and the real StepperMotion.o sets the latch for real. + +#include + +#include "StepperMotion.h" +#include "fas_queue/stepper_queue.h" + +// `test` is a macro in fas_arch/test_pc.h, so this file's helper is `check`. +static int failures = 0; +static void check(bool cond, const char* msg) { + if (!cond) { + printf("FAIL: %s\n", msg); + failures++; + } +} + +// StepperISR_test.cpp, which links into LIB_O. Not declared in a library header +// because no production caller needs it; test_23 declares it the same way. +extern void fas_reset_stepper_allocation(); + +void inject_fill_interrupt(int mark) {} +void noInterrupts() {} +void interrupts() {} + +static StepperMotionEngine engine; +static StepperMotion s; + +// StepperMotion declares this class a friend (StepperMotion.h:1007), which +// is how the other tests reach fill_queue() and _queue() without the library +// widening its public API for a test. +class StepperMotionTest { + public: + StepperQueue* q(StepperMotion* sp) const { return sp->_queue(); } + void fill(StepperMotion* sp) { sp->fill_queue(); } +}; + +static StepperMotionTest t; + +// A fresh connection per case: stepperConnectToPin() is the one thing that +// rearms the latch, so reusing a stepper across cases would test nothing. +// MIN_CMD_TICKS is 3200 here, so 40 steps at 80 ticks is the smallest single +// command the queue accepts (1 step at 80 ticks is refused as too low). +static struct stepper_command_s cmd = {80, 40, true}; + +static void connect() { + fas_reset_stepper_allocation(); + // StepperMotion::init() memsets the stepper but never touches the queue. + // The queue is rearmed by _initVars() -- which is exactly why every Saleae + // scenario, all of which reconnect, misses this defect. + fas_queue[0]._initVars(); + fas_queue[1]._initVars(); + s.init(&engine, 0, 0); + s.setDirectionPin(PIN_UNDEFINED, false); + s.setSpeedInTicks(80); +} + +// A: after forceStop() every command is refused with a terminal code, not OK. +static void a_refused_not_ok() { + connect(); + s.forceStop(); + check(s.areCommandsSuspended(), "A: latch is set by forceStop()"); + AqeResultCode rc = s.addQueueEntry(&cmd, true); + check(rc == AQE_ERROR_COMMANDS_SUSPENDED, + "A: forceStop() refuses with ErrorCommandsSuspended"); + // Terminal, so a caller looping on a retryable code stops rather than spins. + check(!aqeRetry(rc), "A: the refusal is not retryable"); +} + +// B: nothing about the queue moved. This is the silent divergence: the caller +// was told OK, so it advanced its own position model by 40 steps the queue +// never accepted. +static void b_queue_untouched() { + connect(); + s.forceStop(); + int32_t pos_before = s.getCurrentPosition(); + uint8_t entries_before = s.queueEntries(); + int32_t queued_before = t.q(&s)->queue_end.pos; + + s.addQueueEntry(&cmd, true); + + check(s.getCurrentPosition() == pos_before, "B: position does not move"); + check(s.queueEntries() == entries_before, "B: no queue entry is added"); + check(t.q(&s)->queue_end.pos == queued_before, + "B: queue_end.pos is not advanced"); +} + +// C: a suspended queue cannot be started either. addQueueEntry(NULL, start) +// returned before the gate, so the queue could be released after an abort. +static void c_cannot_start() { + connect(); + // Fill a command in *before* the stop: the queue has to be non-empty for the + // start path to be reachable at all. + check(s.addQueueEntry(&cmd, false) == AQE_OK, "C: prefill accepted"); + s.forceStop(); + check(s.addQueueEntry(NULL, true) == AQE_ERROR_COMMANDS_SUSPENDED, + "C: a suspended queue cannot be started"); +} + +// D: resumeCommands() is the key. Without it a low-level caller that aborted +// could never queue again on the same connection -- the whole point of the +// documented addQueueEntry() interface. +static void d_rearm() { + connect(); + s.forceStop(); + check(s.addQueueEntry(&cmd, false) == AQE_ERROR_COMMANDS_SUSPENDED, + "D: refused while suspended"); + s.resumeCommands(); + check(!s.areCommandsSuspended(), "D: resumeCommands() clears the latch"); + check(s.addQueueEntry(&cmd, false) == AQE_OK, + "D: queueing works again on the same connection"); + check(s.queueEntries() == 1, "D: and the command is really queued"); + // queue_end.pos, not getCurrentPosition(): the pc_based queue has no ISR + // stepping it, so the performed count stays 0 and only the queued position + // moves. That divergence is the point of the original defect. + check(t.q(&s)->queue_end.pos == 40, + "D: the queued position advanced by the queued steps"); +} + +// E: forceStopAndNewPosition() sets it too, and the caller's new position is +// the base later commands build on. +static void e_force_stop_and_new_position() { + connect(); + s.addQueueEntry(&cmd, false); + s.forceStopAndNewPosition(1234); + check(s.areCommandsSuspended(), + "E: latch is set by forceStopAndNewPosition()"); + check(s.addQueueEntry(&cmd, false) == AQE_ERROR_COMMANDS_SUSPENDED, + "E: refused after forceStopAndNewPosition()"); + s.resumeCommands(); + check(s.addQueueEntry(&cmd, false) == AQE_OK, "E: queueable after rearm"); + // queue_end.pos was set to 1234 by the stop; +40 for the queued command. + check(t.q(&s)->queue_end.pos == 1274, + "E: the new position is the base for later commands"); +} + +// F: the refusal must not be laundered through moveTimed(). tmrFrom() is a +// value-preserving cast, so AQE_ERROR_COMMANDS_SUSPENDED needs its own value in +// MoveTimedResultCode: -4 would alias MOVE_TIMED_TOO_LARGE_ERROR. +static void f_movetimed_value_preserved() { + check(static_cast(AQE_ERROR_COMMANDS_SUSPENDED) == -5, + "F: the AQE code is -5"); + check(static_cast(AQE_ERROR_COMMANDS_SUSPENDED) != + static_cast(MOVE_TIMED_TOO_LARGE_ERROR), + "F: distinct from MOVE_TIMED_TOO_LARGE_ERROR"); + check(static_cast(AQE_ERROR_COMMANDS_SUSPENDED) == + MOVE_TIMED_COMMANDS_SUSPENDED, + "F: tmrFrom() preserves it, no aliasing"); + + connect(); + s.forceStop(); + uint32_t actual = 0; + MoveTimedResultCode rc = s.moveTimed(40, 80 * 40, &actual, false); + check(rc == MOVE_TIMED_COMMANDS_SUSPENDED, + "F: moveTimed() surfaces the suspension, not a move error"); +} + +// G: the ramp path is unaffected. fill_queue() clears the latch on every active +// pass, which is why the old placement made the gate inert here. +static void g_ramp_rearms_itself() { + connect(); + s.setSpeedInUs(1000); + s.setAcceleration(1000); + s.move(2000); + t.fill(&s); + check(!s.areCommandsSuspended(), "G: an active ramp leaves the latch clear"); + check(!s.isQueueEmpty(), "G: and the ramp queued commands"); +} + +int main() { + a_refused_not_ok(); + b_queue_untouched(); + c_cannot_start(); + d_rearm(); + e_force_stop_and_new_position(); + f_movetimed_value_preserved(); + g_ramp_rearms_itself(); + if (failures != 0) { + printf("%d failure(s)\n", failures); + return 1; + } + printf("TEST_31 PASSED\n"); + return 0; +} diff --git a/tests/host/viewer_template.html b/tests/host/viewer_template.html new file mode 100644 index 0000000..d41bb02 --- /dev/null +++ b/tests/host/viewer_template.html @@ -0,0 +1,23 @@ + + + + + FasNAxis trace + + + +

FasNAxis trace

+

+
+