added TMC26X driver library (fixed up)
authorJim Morris <morris@wolfman.com>
Thu, 12 Nov 2015 00:49:06 +0000 (16:49 -0800)
committerJim Morris <morris@wolfman.com>
Thu, 12 Nov 2015 00:49:06 +0000 (16:49 -0800)
implemented settings for the TMC chip

src/modules/utils/motordrivercontrol/MotorDriverControl.cpp
src/modules/utils/motordrivercontrol/MotorDriverControl.h
src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.cpp [new file with mode: 0644]
src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.h [new file with mode: 0644]

index 5656287..e79ffeb 100644 (file)
@@ -6,6 +6,7 @@
 #include "libs/StreamOutput.h"
 #include "libs/StreamOutputPool.h"
 
+
 #include "Gcode.h"
 #include "Config.h"
 #include "checksumm.h"
@@ -13,6 +14,8 @@
 
 #include "mbed.h" // for SPI
 
+#include "drivers/TMC26X/TMC26X.h"
+
 #include <string>
 
 #define motor_driver_control_checksum  CHECKSUM("motor_driver_control")
 #define max_current_checksum           CHECKSUM("max_current")
 #define current_factor_checksum        CHECKSUM("current_factor")
 
-#define microsteps_checksum             CHECKSUM("microsteps")
+#define microsteps_checksum            CHECKSUM("microsteps")
 #define decay_mode_checksum            CHECKSUM("decay_mode")
+#define torque_checksum                CHECKSUM("torque")
+#define gain_checksum                  CHECKSUM("gain")
 
 
-
-#define spi_channel_checksum       CHECKSUM("spi_channel")
-#define spi_cs_pin_checksum        CHECKSUM("spi_cs_pin")
-#define spi_frequency_checksum     CHECKSUM("spi_frequency")
+#define spi_channel_checksum           CHECKSUM("spi_channel")
+#define spi_cs_pin_checksum            CHECKSUM("spi_cs_pin")
+#define spi_frequency_checksum         CHECKSUM("spi_frequency")
 
 MotorDriverControl::MotorDriverControl(uint16_t cs, uint8_t id) : cs(cs), id(id)
 {
@@ -65,6 +69,8 @@ bool MotorDriverControl::config_module()
         THEKERNEL->streams->printf("MotorDriverControl ERROR: chip select not defined\n");
         return false; // if not defined then we can't use this instance
     }
+    spi_cs_pin.set(1);
+
     std::string str= THEKERNEL->config->value( motor_driver_control_checksum, cs, designator)->by_default("")->as_string();
     if(str.empty()) {
         THEKERNEL->streams->printf("MotorDriverControl ERROR: designator not defined\n");
@@ -78,10 +84,18 @@ bool MotorDriverControl::config_module()
         return false; // chip type required
     }
 
+    using std::placeholders::_1;
+    using std::placeholders::_2;
+    using std::placeholders::_3;
+
     if(str == "DRV8711") {
         chip= DRV8711;
+        //drv8711= new DRV8711DRV(sendSPI);
+
     }else if(str == "TMC2660") {
         chip= TMC2660;
+        tmc26x= new TMC26X(std::bind( &MotorDriverControl::sendSPI, this, _1, _2, _3));
+
     }else{
         THEKERNEL->streams->printf("MotorDriverControl ERROR: Unknown chip type: %s\n", str.c_str());
         return false;
@@ -91,6 +105,7 @@ bool MotorDriverControl::config_module()
     int spi_channel = THEKERNEL->config->value(motor_driver_control_checksum, cs, spi_channel_checksum)->by_default(1)->as_number();
     int spi_frequency = THEKERNEL->config->value(motor_driver_control_checksum, cs, spi_frequency_checksum)->by_default(1000000)->as_number();
 
+    // select SPI channel to use
     PinName mosi, miso, sclk;
     if(spi_channel == 0) {
         mosi = P0_18; miso = P0_17; sclk = P0_15;
@@ -104,31 +119,55 @@ bool MotorDriverControl::config_module()
     this->spi = new mbed::SPI(mosi, miso, sclk);
     this->spi->frequency(spi_frequency);
 
-    // chip select
-    this->spi_cs_pin.set(0);
 
     max_current= THEKERNEL->config->value(motor_driver_control_checksum, cs, max_current_checksum )->by_default(2.0f)->as_number();
     current_factor= THEKERNEL->config->value(motor_driver_control_checksum, cs, current_factor_checksum )->by_default(1.0F)->as_number();
 
     current= THEKERNEL->config->value(motor_driver_control_checksum, cs, current_checksum )->by_default(1.0F)->as_number();
-    set_current(current);
     microsteps= THEKERNEL->config->value(motor_driver_control_checksum, cs, microsteps_checksum )->by_default(4)->as_number(); // 2^n
-    set_microstep(microsteps);
     decay_mode= THEKERNEL->config->value(motor_driver_control_checksum, cs, decay_mode_checksum )->by_default(1)->as_number();
-    set_decay_mode(decay_mode);
 
+    if(chip == DRV8711) {
+        torque= THEKERNEL->config->value(motor_driver_control_checksum, cs, torque_checksum )->by_default(-1)->as_number();
+        gain= THEKERNEL->config->value(motor_driver_control_checksum, cs, gain_checksum )->by_default(-1)->as_number();
+    }
+
+    // setup the chip via SPI
+    initialize_chip();
 
     this->register_for_event(ON_GCODE_RECEIVED);
+    this->register_for_event(ON_GCODE_EXECUTE);
     return true;
 }
 
+// React to enable/disable gcodes
+void MotorDriverControl::on_gcode_execute(void *argument)
+{
+    Gcode *gcode = static_cast<Gcode *>(argument);
+
+    if( gcode->has_m) {
+        if( gcode->m == 17 ) {
+            enable(true);
+        }
+        if( (gcode->m == 84 || gcode->m == 18) && !gcode->has_letter('E') ) {
+            enable(false);
+        }
+    }
+}
+
+
 void MotorDriverControl::on_gcode_received(void *argument)
 {
     Gcode *gcode = static_cast<Gcode*>(argument);
 
     if (gcode->has_m) {
-        if(gcode->m == 906) { // set motor currents in mA (Note not using M907 as digipots use that)
-            if (gcode->has_letter(designator)) {
+        if(gcode->m == 906) {
+            if(gcode->subcode == 1) {
+                // M906.1 dump status for all drivers
+                dump_status(gcode->stream);
+
+            }else if (gcode->has_letter(designator)) {
+                // set motor currents in mA (Note not using M907 as digipots use that)
                 current= gcode->get_value(designator);
                 set_current(current);
             }
@@ -145,12 +184,12 @@ void MotorDriverControl::on_gcode_received(void *argument)
                 set_decay_mode(decay_mode);
             }
 
-        } else if(chip == DRV8711 && gcode->m == 911) { // M911.1 set torque, M911.2 set gain
+        } else if(chip == DRV8711 && gcode->m == 911) { // M911.1 set torque, M911.2 set gain (MAYBE could be subcodes for 906 as DRV8711 doesn't set current directly)
             if (gcode->has_letter(designator)) {
                 if(gcode->subcode == 1) {
                     torque= gcode->get_value(designator);
 
-                }else  if(gcode->subcode == 1) {
+                }else  if(gcode->subcode == 2) {
                     gain= gcode->get_value(designator);
 
                 }else{
@@ -160,8 +199,8 @@ void MotorDriverControl::on_gcode_received(void *argument)
             }
 
         } else if(gcode->m == 500 || gcode->m == 503) {
-            gcode->stream->printf(";Motor id %d current, microsteps, decay mode:\n", id);
-            gcode->stream->printf("M906 %c%1.5f\n", designator, current);
+            gcode->stream->printf(";Motor id %d current mA, microsteps, decay mode:\n", id);
+            gcode->stream->printf("M906 %c%lu\n", designator, current);
             gcode->stream->printf("M909 %c%d\n", designator, microsteps);
             gcode->stream->printf("M910 %c%d\n", designator, decay_mode);
             if(torque >= 0 && gain >= 0) {
@@ -172,20 +211,43 @@ void MotorDriverControl::on_gcode_received(void *argument)
     }
 }
 
-void MotorDriverControl::set_current(float c)
+void MotorDriverControl::initialize_chip()
+{
+    // send initialization sequence to chips
+    if(chip == DRV8711) {
+        set_torque(torque, gain);
+
+    }else if(chip == TMC2660){
+        //setResistor(150);
+        tmc26x->init();
+        set_current(current);
+    }
+
+    set_microstep(microsteps);
+    set_decay_mode(decay_mode);
+}
+
+// set curent in milliamps
+void MotorDriverControl::set_current(uint32_t c)
 {
-    // TODO set current for chip type in mA
     switch(chip) {
-        case DRV8711: break;
-        case TMC2660: break;
+        case DRV8711: break; // doesn't use current
+
+        case TMC2660:
+            tmc26x->setCurrent(c);
+            break;
     }
 }
 
-void MotorDriverControl::set_microstep( uint8_t ms )
+// set microsteps where n is the number of microsteps eg 64 for 1/64
+void MotorDriverControl::set_microstep( uint32_t n )
 {
     switch(chip) {
         case DRV8711: break;
-        case TMC2660: break;
+
+        case TMC2660:
+            tmc26x->setMicrosteps(n);
+            break;
     }
 }
 
@@ -201,3 +263,35 @@ void MotorDriverControl::set_torque(float torque, float gain)
 {
 
 }
+
+void MotorDriverControl::enable(bool on)
+{
+    switch(chip) {
+        case DRV8711: break;
+        case TMC2660:
+            tmc26x->setEnabled(on);
+            break;
+    }
+}
+
+void MotorDriverControl::dump_status(StreamOutput *stream)
+{
+    switch(chip) {
+        case DRV8711: break;
+        case TMC2660:
+            tmc26x->dumpStatus(stream);
+            break;
+    }
+}
+
+
+int MotorDriverControl::sendSPI(uint8_t *b, int cnt, uint8_t *r)
+{
+    spi_cs_pin.set(0);
+    for (int i = 0; i < cnt; ++i) {
+        r[i]= spi->write(b[i]);
+    }
+    spi_cs_pin.set(1);
+    return cnt;
+}
+
index 3fbde4c..0a3ab3a 100644 (file)
@@ -9,6 +9,10 @@ namespace mbed {
     class SPI;
 }
 
+class DRV8711DRV;
+class TMC26X;
+class StreamOutput;
+
 class MotorDriverControl : public Module {
     public:
         MotorDriverControl(uint16_t cs, uint8_t id);
@@ -16,13 +20,18 @@ class MotorDriverControl : public Module {
 
         void on_module_loaded();
         void on_gcode_received(void *);
+        void on_gcode_execute(void *);
 
     private:
         bool config_module();
-        void set_current( float current );
-        void set_microstep( uint8_t ms );
+        void initialize_chip();
+        void set_current( uint32_t current );
+        void set_microstep( uint32_t ms );
         void set_decay_mode( uint8_t dm );
         void set_torque(float torque, float gain);
+        void dump_status(StreamOutput*);
+        void enable(bool on);
+        int sendSPI(uint8_t *b, int cnt, uint8_t *r);
 
         Pin spi_cs_pin;
         mbed::SPI *spi;
@@ -33,9 +42,15 @@ class MotorDriverControl : public Module {
         };
         CHIP_TYPE chip;
 
+        // one of these drivers
+        union {
+            DRV8711DRV *drv8711;
+            TMC26X *tmc26x;
+        };
+
         float current_factor;
-        float max_current;
-        float current;
+        uint32_t max_current; // in milliamps
+        uint32_t current; // in milliamps
         float torque{-1}, gain{-1};
 
         char designator;
diff --git a/src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.cpp b/src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.cpp
new file mode 100644 (file)
index 0000000..816501b
--- /dev/null
@@ -0,0 +1,841 @@
+/*
+ Highly modifed from....
+
+ TMC26X.cpp - - TMC26X Stepper library for Wiring/Arduino
+
+ based on the stepper library by Tom Igoe, et. al.
+
+ Copyright (c) 2011, Interactive Matter, Marcus Nowotny
+
+ 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.
+
+ */
+
+#include "TMC26X.h"
+#include "mbed.h"
+#include "StreamOutput.h"
+
+//some default values used in initialization
+#define DEFAULT_MICROSTEPPING_VALUE 32
+
+//TMC26X register definitions
+#define DRIVER_CONTROL_REGISTER 0x0ul
+#define CHOPPER_CONFIG_REGISTER 0x80000ul
+#define COOL_STEP_REGISTER  0xA0000ul
+#define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul
+#define DRIVER_CONFIG_REGISTER 0xE0000ul
+
+#define REGISTER_BIT_PATTERN 0xFFFFFul
+
+//definitions for the driver control register
+#define MICROSTEPPING_PATTERN 0xFul
+#define STEP_INTERPOLATION 0x200ul
+#define DOUBLE_EDGE_STEP 0x100ul
+#define VSENSE 0x40ul
+#define READ_MICROSTEP_POSTION 0x0ul
+#define READ_STALL_GUARD_READING 0x10ul
+#define READ_STALL_GUARD_AND_COOL_STEP 0x20ul
+#define READ_SELECTION_PATTERN 0x30ul
+
+//definitions for the chopper config register
+#define CHOPPER_MODE_STANDARD 0x0ul
+#define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul
+#define T_OFF_PATTERN 0xful
+#define RANDOM_TOFF_TIME 0x2000ul
+#define BLANK_TIMING_PATTERN 0x18000ul
+#define BLANK_TIMING_SHIFT 15
+#define HYSTERESIS_DECREMENT_PATTERN 0x1800ul
+#define HYSTERESIS_DECREMENT_SHIFT 11
+#define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul
+#define HYSTERESIS_LOW_SHIFT 7
+#define HYSTERESIS_START_VALUE_PATTERN 0x78ul
+#define HYSTERESIS_START_VALUE_SHIFT 4
+#define T_OFF_TIMING_PATERN 0xFul
+
+//definitions for cool step register
+#define MINIMUM_CURRENT_FOURTH 0x8000ul
+#define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul
+#define SE_MAX_PATTERN 0xF00ul
+#define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul
+#define SE_MIN_PATTERN 0xful
+
+//definitions for stall guard2 current register
+#define STALL_GUARD_FILTER_ENABLED 0x10000ul
+#define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x17F00ul
+#define CURRENT_SCALING_PATTERN 0x1Ful
+#define STALL_GUARD_CONFIG_PATTERN 0x17F00ul
+#define STALL_GUARD_VALUE_PATTERN 0x7F00ul
+
+//definitions for the input from the TCM260
+#define STATUS_STALL_GUARD_STATUS 0x1ul
+#define STATUS_OVER_TEMPERATURE_SHUTDOWN 0x2ul
+#define STATUS_OVER_TEMPERATURE_WARNING 0x4ul
+#define STATUS_SHORT_TO_GROUND_A 0x8ul
+#define STATUS_SHORT_TO_GROUND_B 0x10ul
+#define STATUS_OPEN_LOAD_A 0x20ul
+#define STATUS_OPEN_LOAD_B 0x40ul
+#define STATUS_STAND_STILL 0x80ul
+#define READOUT_VALUE_PATTERN 0xFFC00ul
+
+//default values
+#define INITIAL_MICROSTEPPING 0x3ul //32th microstepping
+
+//debuging output
+//#define DEBUG
+
+/*
+ * Constructor
+ */
+TMC26X::TMC26X(std::function<int(uint8_t *b, int cnt, uint8_t *r)> spi) : spi(spi)
+{
+    //we are not started yet
+    started = false;
+    //by default cool step is not enabled
+    cool_step_enabled = false;
+}
+
+void TMC26X::setResistor(unsigned int resistor)
+{
+    //store the current sense resistor value for later use
+    this->resistor = resistor;
+}
+
+/*
+ * configure the stepper driver
+ * just must be called.
+ */
+void TMC26X::init()
+{
+    //setting the default register values
+    driver_control_register_value = DRIVER_CONTROL_REGISTER | INITIAL_MICROSTEPPING;
+    microsteps = (1 << INITIAL_MICROSTEPPING);
+    chopper_config_register = CHOPPER_CONFIG_REGISTER;
+    cool_step_register_value = COOL_STEP_REGISTER;
+    stall_guard2_current_register_value = STALL_GUARD2_LOAD_MEASURE_REGISTER;
+    driver_configuration_register_value = DRIVER_CONFIG_REGISTER | READ_STALL_GUARD_READING;
+
+    //set the initial values
+    send262(driver_control_register_value);
+    send262(chopper_config_register);
+    send262(cool_step_register_value);
+    send262(stall_guard2_current_register_value);
+    send262(driver_configuration_register_value);
+
+    //save that we are in running mode
+    started = true;
+
+    //set to a conservative start value
+    setConstantOffTimeChopper(7, 54, 13, 12, 1);
+
+    //set a nice microstepping value
+    setMicrosteps(DEFAULT_MICROSTEPPING_VALUE);
+}
+
+void TMC26X::setCurrent(unsigned int current)
+{
+    uint8_t current_scaling = 0;
+    //calculate the current scaling from the max current setting (in mA)
+    double mASetting = (double)current;
+    double resistor_value = (double) this->resistor;
+    // remove vesense flag
+    this->driver_configuration_register_value &= ~(VSENSE);
+    //this is derrived from I=(cs+1)/32*(Vsense/Rsense)
+    //leading to cs = CS = 32*R*I/V (with V = 0,31V oder 0,165V  and I = 1000*current)
+    //with Rsense=0,15
+    //for vsense = 0,310V (VSENSE not set)
+    //or vsense = 0,165V (VSENSE set)
+    current_scaling = (uint8_t)((resistor_value * mASetting * 32.0 / (0.31 * 1000.0 * 1000.0)) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
+
+    //check if the current scalingis too low
+    if (current_scaling < 16) {
+        //set the csense bit to get a use half the sense voltage (to support lower motor currents)
+        this->driver_configuration_register_value |= VSENSE;
+        //and recalculate the current setting
+        current_scaling = (uint8_t)((resistor_value * mASetting * 32.0 / (0.165 * 1000.0 * 1000.0)) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
+    }
+
+    //do some sanity checks
+    if (current_scaling > 31) {
+        current_scaling = 31;
+    }
+    //delete the old value
+    stall_guard2_current_register_value &= ~(CURRENT_SCALING_PATTERN);
+    //set the new current scaling
+    stall_guard2_current_register_value |= current_scaling;
+    //if started we directly send it to the motor
+    if (started) {
+        send262(driver_configuration_register_value);
+        send262(stall_guard2_current_register_value);
+    }
+}
+
+unsigned int TMC26X::getCurrent(void)
+{
+    //we calculate the current according to the datasheet to be on the safe side
+    //this is not the fastest but the most accurate and illustrative way
+    double result = (double)(stall_guard2_current_register_value & CURRENT_SCALING_PATTERN);
+    double resistor_value = (double)this->resistor;
+    double voltage = (driver_configuration_register_value & VSENSE) ? 0.165 : 0.31;
+    result = (result + 1.0) / 32.0 * voltage / resistor_value * 1000.0 * 1000.0;
+    return (unsigned int)result;
+}
+
+void TMC26X::setStallGuardThreshold(int8_t stall_guard_threshold, int8_t stall_guard_filter_enabled)
+{
+    if (stall_guard_threshold < -64) {
+        stall_guard_threshold = -64;
+        //We just have 5 bits
+    } else if (stall_guard_threshold > 63) {
+        stall_guard_threshold = 63;
+    }
+    //add trim down to 7 bits
+    stall_guard_threshold &= 0x7f;
+    //delete old stall guard settings
+    stall_guard2_current_register_value &= ~(STALL_GUARD_CONFIG_PATTERN);
+    if (stall_guard_filter_enabled) {
+        stall_guard2_current_register_value |= STALL_GUARD_FILTER_ENABLED;
+    }
+    //Set the new stall guard threshold
+    stall_guard2_current_register_value |= (((unsigned long)stall_guard_threshold << 8) & STALL_GUARD_CONFIG_PATTERN);
+    //if started we directly send it to the motor
+    if (started) {
+        send262(stall_guard2_current_register_value);
+    }
+}
+
+int8_t TMC26X::getStallGuardThreshold(void)
+{
+    unsigned long stall_guard_threshold = stall_guard2_current_register_value & STALL_GUARD_VALUE_PATTERN;
+    //shift it down to bit 0
+    stall_guard_threshold >>= 8;
+    //convert the value to an int to correctly handle the negative numbers
+    int8_t result = stall_guard_threshold;
+    //check if it is negative and fill it up with leading 1 for proper negative number representation
+    if (result & (1<<6)) {
+        result |= 0xC0;
+    }
+    return result;
+}
+
+int8_t TMC26X::getStallGuardFilter(void)
+{
+    if (stall_guard2_current_register_value & STALL_GUARD_FILTER_ENABLED) {
+        return -1;
+    } else {
+        return 0;
+    }
+}
+/*
+ * Set the number of microsteps per step.
+ * 0,2,4,8,16,32,64,128,256 is supported
+ * any value in between will be mapped to the next smaller value
+ * 0 and 1 set the motor in full step mode
+ */
+void TMC26X::setMicrosteps(int number_of_steps)
+{
+    long setting_pattern;
+    //poor mans log
+    if (number_of_steps >= 256) {
+        setting_pattern = 0;
+        microsteps = 256;
+    } else if (number_of_steps >= 128) {
+        setting_pattern = 1;
+        microsteps = 128;
+    } else if (number_of_steps >= 64) {
+        setting_pattern = 2;
+        microsteps = 64;
+    } else if (number_of_steps >= 32) {
+        setting_pattern = 3;
+        microsteps = 32;
+    } else if (number_of_steps >= 16) {
+        setting_pattern = 4;
+        microsteps = 16;
+    } else if (number_of_steps >= 8) {
+        setting_pattern = 5;
+        microsteps = 8;
+    } else if (number_of_steps >= 4) {
+        setting_pattern = 6;
+        microsteps = 4;
+    } else if (number_of_steps >= 2) {
+        setting_pattern = 7;
+        microsteps = 2;
+        //1 and 0 lead to full step
+    } else if (number_of_steps <= 1) {
+        setting_pattern = 8;
+        microsteps = 1;
+    }
+
+    //delete the old value
+    this->driver_control_register_value &= 0xFFFF0ul;
+    //set the new value
+    this->driver_control_register_value |= setting_pattern;
+
+    //if started we directly send it to the motor
+    if (started) {
+        send262(driver_control_register_value);
+    }
+}
+
+/*
+ * returns the effective number of microsteps at the moment
+ */
+int TMC26X::getMicrosteps(void)
+{
+    return microsteps;
+}
+
+/*
+ * constant_off_time: The off time setting controls the minimum chopper frequency.
+ * For most applications an off time within the range of 5μs to 20μs will fit.
+ *      2...15: off time setting
+ *
+ * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
+ * duration of the ringing on the sense resistor. For
+ *      0: min. setting 3: max. setting
+ *
+ * fast_decay_time_setting: Fast decay time setting. With CHM=1, these bits control the portion of fast decay for each chopper cycle.
+ *      0: slow decay only
+ *      1...15: duration of fast decay phase
+ *
+ * sine_wave_offset: Sine wave offset. With CHM=1, these bits control the sine wave offset.
+ * A positive offset corrects for zero crossing error.
+ *      -3..-1: negative offset 0: no offset 1...12: positive offset
+ *
+ * use_current_comparator: Selects usage of the current comparator for termination of the fast decay cycle.
+ * If current comparator is enabled, it terminates the fast decay cycle in case the current
+ * reaches a higher negative value than the actual positive value.
+ *      1: enable comparator termination of fast decay cycle
+ *      0: end by time only
+ */
+void TMC26X::setConstantOffTimeChopper(int8_t constant_off_time, int8_t blank_time, int8_t fast_decay_time_setting, int8_t sine_wave_offset, uint8_t use_current_comparator)
+{
+    //perform some sanity checks
+    if (constant_off_time < 2) {
+        constant_off_time = 2;
+    } else if (constant_off_time > 15) {
+        constant_off_time = 15;
+    }
+    //save the constant off time
+    this->constant_off_time = constant_off_time;
+    int8_t blank_value;
+    //calculate the value acc to the clock cycles
+    if (blank_time >= 54) {
+        blank_value = 3;
+    } else if (blank_time >= 36) {
+        blank_value = 2;
+    } else if (blank_time >= 24) {
+        blank_value = 1;
+    } else {
+        blank_value = 0;
+    }
+    if (fast_decay_time_setting < 0) {
+        fast_decay_time_setting = 0;
+    } else if (fast_decay_time_setting > 15) {
+        fast_decay_time_setting = 15;
+    }
+    if (sine_wave_offset < -3) {
+        sine_wave_offset = -3;
+    } else if (sine_wave_offset > 12) {
+        sine_wave_offset = 12;
+    }
+    //shift the sine_wave_offset
+    sine_wave_offset += 3;
+
+    //calculate the register setting
+    //first of all delete all the values for this
+    chopper_config_register &= ~((1 << 12) | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
+    //set the constant off pattern
+    chopper_config_register |= CHOPPER_MODE_T_OFF_FAST_DECAY;
+    //set the blank timing value
+    chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
+    //setting the constant off time
+    chopper_config_register |= constant_off_time;
+    //set the fast decay time
+    //set msb
+    chopper_config_register |= (((unsigned long)(fast_decay_time_setting & 0x8)) << HYSTERESIS_DECREMENT_SHIFT);
+    //other bits
+    chopper_config_register |= (((unsigned long)(fast_decay_time_setting & 0x7)) << HYSTERESIS_START_VALUE_SHIFT);
+    //set the sine wave offset
+    chopper_config_register |= (unsigned long)sine_wave_offset << HYSTERESIS_LOW_SHIFT;
+    //using the current comparator?
+    if (!use_current_comparator) {
+        chopper_config_register |= (1 << 12);
+    }
+    //if started we directly send it to the motor
+    if (started) {
+        send262(chopper_config_register);
+    }
+}
+
+/*
+ * constant_off_time: The off time setting controls the minimum chopper frequency.
+ * For most applications an off time within the range of 5μs to 20μs will fit.
+ *      2...15: off time setting
+ *
+ * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
+ * duration of the ringing on the sense resistor. For
+ *      0: min. setting 3: max. setting
+ *
+ * hysteresis_start: Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value HEND.
+ *      1...8
+ *
+ * hysteresis_end: Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by HDEC.
+ * The sum HSTRT+HEND must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
+ *      -3..-1: negative HEND 0: zero HEND 1...12: positive HEND
+ *
+ * hysteresis_decrement: Hysteresis decrement setting. This setting determines the slope of the hysteresis during on time and during fast decay time.
+ *      0: fast decrement 3: very slow decrement
+ */
+
+void TMC26X::setSpreadCycleChopper(int8_t constant_off_time, int8_t blank_time, int8_t hysteresis_start, int8_t hysteresis_end, int8_t hysteresis_decrement)
+{
+    //perform some sanity checks
+    if (constant_off_time < 2) {
+        constant_off_time = 2;
+    } else if (constant_off_time > 15) {
+        constant_off_time = 15;
+    }
+    //save the constant off time
+    this->constant_off_time = constant_off_time;
+    int8_t blank_value;
+    //calculate the value acc to the clock cycles
+    if (blank_time >= 54) {
+        blank_value = 3;
+    } else if (blank_time >= 36) {
+        blank_value = 2;
+    } else if (blank_time >= 24) {
+        blank_value = 1;
+    } else {
+        blank_value = 0;
+    }
+    if (hysteresis_start < 1) {
+        hysteresis_start = 1;
+    } else if (hysteresis_start > 8) {
+        hysteresis_start = 8;
+    }
+    hysteresis_start--;
+
+    if (hysteresis_end < -3) {
+        hysteresis_end = -3;
+    } else if (hysteresis_end > 12) {
+        hysteresis_end = 12;
+    }
+    //shift the hysteresis_end
+    hysteresis_end += 3;
+
+    if (hysteresis_decrement < 0) {
+        hysteresis_decrement = 0;
+    } else if (hysteresis_decrement > 3) {
+        hysteresis_decrement = 3;
+    }
+
+    //first of all delete all the values for this
+    chopper_config_register &= ~(CHOPPER_MODE_T_OFF_FAST_DECAY | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
+
+    //set the blank timing value
+    chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
+    //setting the constant off time
+    chopper_config_register |= constant_off_time;
+    //set the hysteresis_start
+    chopper_config_register |= ((unsigned long)hysteresis_start) << HYSTERESIS_START_VALUE_SHIFT;
+    //set the hysteresis end
+    chopper_config_register |= ((unsigned long)hysteresis_end) << HYSTERESIS_LOW_SHIFT;
+    //set the hystereis decrement
+    chopper_config_register |= ((unsigned long)blank_value) << BLANK_TIMING_SHIFT;
+    //if started we directly send it to the motor
+    if (started) {
+        send262(chopper_config_register);
+    }
+}
+
+/*
+ * In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
+ * The frequency of each chopper mainly depends on the coil current and the position dependant motor coil inductivity, thus it depends on the microstep position.
+ * With some motors a slightly audible beat can occur between the chopper frequencies, especially when they are near to each other. This typically occurs at a
+ * few microstep positions within each quarter wave. This effect normally is not audible when compared to mechanical noise generated by ball bearings, etc.
+ * Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
+ * Hint: A common factor, which can cause motor noise, is a bad PCB layout causing coupling of both sense resistor voltages
+ * (please refer to sense resistor layout hint in chapter 8.1).
+ * In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
+ * It modulates the slow decay time setting when switched on by the RNDTF bit. The RNDTF feature further spreads the chopper spectrum,
+ * reducing electromagnetic emission on single frequencies.
+ */
+void TMC26X::setRandomOffTime(int8_t value)
+{
+    if (value) {
+        chopper_config_register |= RANDOM_TOFF_TIME;
+    } else {
+        chopper_config_register &= ~(RANDOM_TOFF_TIME);
+    }
+    //if started we directly send it to the motor
+    if (started) {
+        send262(chopper_config_register);
+    }
+}
+
+void TMC26X::setCoolStepConfiguration(unsigned int lower_SG_threshold, unsigned int SG_hysteresis, uint8_t current_decrement_step_size,
+        uint8_t current_increment_step_size, uint8_t lower_current_limit)
+{
+    //sanitize the input values
+    if (lower_SG_threshold > 480) {
+        lower_SG_threshold = 480;
+    }
+    //divide by 32
+    lower_SG_threshold >>= 5;
+    if (SG_hysteresis > 480) {
+        SG_hysteresis = 480;
+    }
+    //divide by 32
+    SG_hysteresis >>= 5;
+    if (current_decrement_step_size > 3) {
+        current_decrement_step_size = 3;
+    }
+    if (current_increment_step_size > 3) {
+        current_increment_step_size = 3;
+    }
+    if (lower_current_limit > 1) {
+        lower_current_limit = 1;
+    }
+    //store the lower level in order to enable/disable the cool step
+    this->cool_step_lower_threshold = lower_SG_threshold;
+    //if cool step is not enabled we delete the lower value to keep it disabled
+    if (!this->cool_step_enabled) {
+        lower_SG_threshold = 0;
+    }
+    //the good news is that we can start with a complete new cool step register value
+    //and simply set the values in the register
+    cool_step_register_value = ((unsigned long)lower_SG_threshold) | (((unsigned long)SG_hysteresis) << 8) | (((unsigned long)current_decrement_step_size) << 5)
+                               | (((unsigned long)current_increment_step_size) << 13) | (((unsigned long)lower_current_limit) << 15)
+                               //and of course we have to include the signature of the register
+                               | COOL_STEP_REGISTER;
+
+    if (started) {
+        send262(cool_step_register_value);
+    }
+}
+
+void TMC26X::setCoolStepEnabled(bool enabled)
+{
+    //simply delete the lower limit to disable the cool step
+    cool_step_register_value &= ~SE_MIN_PATTERN;
+    //and set it to the proper value if cool step is to be enabled
+    if (enabled) {
+        cool_step_register_value |= this->cool_step_lower_threshold;
+    }
+    //and save the enabled status
+    this->cool_step_enabled = enabled;
+    //save the register value
+    if (started) {
+        send262(cool_step_register_value);
+    }
+}
+
+bool TMC26X::isCoolStepEnabled(void)
+{
+    return this->cool_step_enabled;
+}
+
+unsigned int TMC26X::getCoolStepLowerSgThreshold()
+{
+    //we return our internally stored value - in order to provide the correct setting even if cool step is not enabled
+    return this->cool_step_lower_threshold << 5;
+}
+
+unsigned int TMC26X::getCoolStepUpperSgThreshold()
+{
+    return (uint8_t)((cool_step_register_value & SE_MAX_PATTERN) >> 8) << 5;
+}
+
+uint8_t TMC26X::getCoolStepCurrentIncrementSize()
+{
+    return (uint8_t)((cool_step_register_value & CURRENT_DOWN_STEP_SPEED_PATTERN) >> 13);
+}
+
+uint8_t TMC26X::getCoolStepNumberOfSGReadings()
+{
+    return (uint8_t)((cool_step_register_value & SE_CURRENT_STEP_WIDTH_PATTERN) >> 5);
+}
+
+uint8_t TMC26X::getCoolStepLowerCurrentLimit()
+{
+    return (uint8_t)((cool_step_register_value & MINIMUM_CURRENT_FOURTH) >> 15);
+}
+
+void TMC26X::setEnabled(bool enabled)
+{
+    //delete the t_off in the chopper config to get sure
+    chopper_config_register &= ~(T_OFF_PATTERN);
+    if (enabled) {
+        //and set the t_off time
+        chopper_config_register |= this->constant_off_time;
+    }
+    //if not enabled we don't have to do anything since we already delete t_off from the register
+    if (started) {
+        send262(chopper_config_register);
+    }
+}
+
+bool TMC26X::isEnabled()
+{
+    if (chopper_config_register & T_OFF_PATTERN) {
+        return true;
+    } else {
+        return false;
+    }
+}
+
+/*
+ * reads a value from the TMC26X status register. The value is not obtained directly but can then
+ * be read by the various status routines.
+ *
+ */
+void TMC26X::readStatus(int8_t read_value)
+{
+    unsigned long old_driver_configuration_register_value = driver_configuration_register_value;
+    //reset the readout configuration
+    driver_configuration_register_value &= ~(READ_SELECTION_PATTERN);
+    //this now equals TMC26X_READOUT_POSITION - so we just have to check the other two options
+    if (read_value == TMC26X_READOUT_STALLGUARD) {
+        driver_configuration_register_value |= READ_STALL_GUARD_READING;
+    } else if (read_value == TMC26X_READOUT_CURRENT) {
+        driver_configuration_register_value |= READ_STALL_GUARD_AND_COOL_STEP;
+    }
+    //all other cases are ignored to prevent funny values
+    //check if the readout is configured for the value we are interested in
+    if (driver_configuration_register_value != old_driver_configuration_register_value) {
+        //because then we need to write the value twice - one time for configuring, second time to get the value, see below
+        send262(driver_configuration_register_value);
+    }
+    //write the configuration to get the last status
+    send262(driver_configuration_register_value);
+}
+
+//reads the stall guard setting from last status
+//returns -1 if stallguard information is not present
+int TMC26X::getCurrentStallGuardReading(void)
+{
+    //if we don't yet started there cannot be a stall guard value
+    if (!started) {
+        return -1;
+    }
+    //not time optimal, but solution optiomal:
+    //first read out the stall guard value
+    readStatus(TMC26X_READOUT_STALLGUARD);
+    return getReadoutValue();
+}
+
+uint8_t TMC26X::getCurrentCSReading(void)
+{
+    //if we don't yet started there cannot be a stall guard value
+    if (!started) {
+        return 0;
+    }
+    //not time optimal, but solution optiomal:
+    //first read out the stall guard value
+    readStatus(TMC26X_READOUT_CURRENT);
+    return (getReadoutValue() & 0x1f);
+}
+
+unsigned int TMC26X::getCurrentCurrent(void)
+{
+    double result = (double)getCurrentCSReading();
+    double resistor_value = (double)this->resistor;
+    double voltage = (driver_configuration_register_value & VSENSE) ? 0.165 : 0.31;
+    result = (result + 1.0) / 32.0 * voltage / resistor_value * 1000.0 * 1000.0;
+    return (unsigned int)result;
+}
+
+/*
+ return true if the stallguard threshold has been reached
+*/
+bool TMC26X::isStallGuardOverThreshold(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_STALL_GUARD_STATUS);
+}
+
+/*
+ returns if there is any over temperature condition:
+ OVER_TEMPERATURE_PREWARING if pre warning level has been reached
+ OVER_TEMPERATURE_SHUTDOWN if the temperature is so hot that the driver is shut down
+ Any of those levels are not too good.
+*/
+int8_t TMC26X::getOverTemperature(void)
+{
+    if (!this->started) {
+        return 0;
+    }
+    if (driver_status_result & STATUS_OVER_TEMPERATURE_SHUTDOWN) {
+        return TMC26X_OVERTEMPERATURE_SHUTDOWN;
+    }
+    if (driver_status_result & STATUS_OVER_TEMPERATURE_WARNING) {
+        return TMC26X_OVERTEMPERATURE_PREWARING;
+    }
+    return 0;
+}
+
+//is motor channel A shorted to ground
+bool TMC26X::isShortToGroundA(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_SHORT_TO_GROUND_A);
+}
+
+//is motor channel B shorted to ground
+bool TMC26X::isShortToGroundB(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_SHORT_TO_GROUND_B);
+}
+
+//is motor channel A connected
+bool TMC26X::isOpenLoadA(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_OPEN_LOAD_A);
+}
+
+//is motor channel B connected
+bool TMC26X::isOpenLoadB(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_OPEN_LOAD_B);
+}
+
+//is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
+bool TMC26X::isStandStill(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_STAND_STILL);
+}
+
+//is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
+bool TMC26X::isStallGuardReached(void)
+{
+    if (!this->started) {
+        return false;
+    }
+    return (driver_status_result & STATUS_STALL_GUARD_STATUS);
+}
+
+//reads the stall guard setting from last status
+//returns -1 if stallguard inforamtion is not present
+int TMC26X::getReadoutValue(void)
+{
+    return (int)(driver_status_result >> 10);
+}
+
+int TMC26X::getResistor()
+{
+    return this->resistor;
+}
+
+bool TMC26X::isCurrentScalingHalfed()
+{
+    if (this->driver_configuration_register_value & VSENSE) {
+        return true;
+    } else {
+        return false;
+    }
+}
+/*
+ version() returns the version of the library:
+ */
+int TMC26X::version(void)
+{
+    return 1;
+}
+
+void TMC26X::dumpStatus(StreamOutput *stream)
+{
+    if (this->started) {
+        if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_PREWARING) {
+            stream->printf("WARNING: Overtemperature Prewarning!\n");
+        } else if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_SHUTDOWN) {
+            stream->printf("ERROR: Overtemperature Shutdown!\n");
+        }
+        if (this->isShortToGroundA()) {
+            stream->printf("ERROR: SHORT to ground on channel A!\n");
+        }
+        if (this->isShortToGroundB()) {
+            stream->printf("ERROR: SHORT to ground on channel A!\n");
+        }
+        if (this->isOpenLoadA()) {
+            stream->printf("ERROR: Channel A seems to be unconnected!\n");
+        }
+        if (this->isOpenLoadB()) {
+            stream->printf("ERROR: Channel B seems to be unconnected!\n");
+        }
+        if (this->isStallGuardReached()) {
+            stream->printf("INFO: Stall Guard level reached!\n");
+        }
+        if (this->isStandStill()) {
+            stream->printf("INFO: Motor is standing still.\n");
+        }
+
+        unsigned long readout_config = driver_configuration_register_value & READ_SELECTION_PATTERN;
+        int value = getReadoutValue();
+        if (readout_config == READ_MICROSTEP_POSTION) {
+            stream->printf("Microstep postion phase A: %d\n", value);
+
+        } else if (readout_config == READ_STALL_GUARD_READING) {
+            stream->printf("Stall Guard value: %d\n", value);
+
+        } else if (readout_config == READ_STALL_GUARD_AND_COOL_STEP) {
+            int stallGuard = value & 0xf;
+            int current = value & 0x1F0;
+            stream->printf("Approx Stall Guard: %d\n", stallGuard);
+            stream->printf("Current level %d\n", current);
+        }
+    }
+}
+
+/*
+ * send register settings to the stepper driver via SPI
+ * returns the current status
+ */
+void TMC26X::send262(unsigned long datagram)
+{
+    uint8_t buf[]{(uint8_t)((datagram >> 16) & 0xff), (uint8_t)((datagram >>  8) & 0xff), (uint8_t)(datagram & 0xff)};
+    uint8_t rbuf[3];
+
+    //ensure that only valid bist are set (0-19)
+    //datagram &=REGISTER_BIT_PATTERN;
+
+    //write/read the values
+    spi(buf, 3, rbuf);
+
+    // construct reply
+    unsigned long i_datagram = ((rbuf[0] << 16) | (rbuf[1] << 8) | (rbuf[2])) >> 4;
+
+    //store the datagram as status result
+    driver_status_result = i_datagram;
+}
diff --git a/src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.h b/src/modules/utils/motordrivercontrol/drivers/TMC26X/TMC26X.h
new file mode 100644 (file)
index 0000000..d1f2130
--- /dev/null
@@ -0,0 +1,482 @@
+/*
+ modified from...
+ TMC26X.cpp - - TMC26X Stepper library for Wiring/Arduino
+
+ based on the stepper library by Tom Igoe, et. al.
+
+ Copyright (c) 2011, Interactive Matter, Marcus Nowotny
+
+ 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.
+
+ */
+
+
+// ensure this library description is only included once
+#pragma once
+
+#include <functional>
+
+//! return value for TMC26X.getOverTemperature() if there is a overtemperature situation in the TMC chip
+/*!
+ * This warning indicates that the TCM chip is too warm.
+ * It is still working but some parameters may be inferior.
+ * You should do something against it.
+ */
+#define TMC26X_OVERTEMPERATURE_PREWARING 1
+//! return value for TMC26X.getOverTemperature() if there is a overtemperature shutdown in the TMC chip
+/*!
+ * This warning indicates that the TCM chip is too warm to operate and has shut down to prevent damage.
+ * It will stop working until it cools down again.
+ * If you encouter this situation you must do something against it. Like reducing the current or improving the PCB layout
+ * and/or heat management.
+ */
+#define TMC26X_OVERTEMPERATURE_SHUTDOWN 2
+
+//which values can be read out
+/*!
+ * Selects to readout the microstep position from the motor.
+ *\sa readStatus()
+ */
+#define TMC26X_READOUT_POSITION 0
+/*!
+ * Selects to read out the StallGuard value of the motor.
+ *\sa readStatus()
+ */
+#define TMC26X_READOUT_STALLGUARD 1
+/*!
+ * Selects to read out the current current setting (acc. to CoolStep) and the upper bits of the StallGuard value from the motor.
+ *\sa readStatus(), setCurrent()
+ */
+#define TMC26X_READOUT_CURRENT 3
+
+/*!
+ * Define to set the minimum current for CoolStep operation to 1/2 of the selected CS minium.
+ *\sa setCoolStepConfiguration()
+ */
+#define COOL_STEP_HALF_CS_LIMIT 0
+/*!
+ * Define to set the minimum current for CoolStep operation to 1/4 of the selected CS minium.
+ *\sa setCoolStepConfiguration()
+ */
+#define COOL_STEP_QUARTDER_CS_LIMIT 1
+
+class StreamOutput;
+
+/*!
+ * \class TMC26X
+ * \brief Class representing a TMC26X stepper driver
+ */
+class TMC26X
+{
+public:
+    /*!
+     * \brief creates a new represenatation of a stepper motor connected to a TMC26X stepper driver
+     *
+     * This is the main constructor. If in doubt use this. You must provide all parameters as described below.
+     *
+     * \param spi send function
+     *
+     * By default the Constant Off Time chopper is used, see TCM262Stepper.setConstantOffTimeChopper() for details.
+     * This should work on most motors (YMMV). You may want to configure and use the Spread Cycle Chopper, see  setSpreadCycleChopper().
+     *
+     * By default a microstepping of 1/32th is used to provide a smooth motor run, while still giving a good progression per step.
+     * You can select a different stepping with setMicrosteps() to aa different value.
+     * \sa start(), setMicrosteps()
+     */
+    TMC26X(std::function<int(uint8_t *b, int cnt, uint8_t *r)> spi);
+
+    /*!
+     * \brief configures the TMC26X stepper driver. Before you called this function the stepper driver is in nonfunctional mode.
+     *
+     * \param rms_current the maximum current to privide to the motor in mA (!). A value of 200 would send up to 200mA to the motor
+     * \param resistor the current sense resistor in milli Ohm, defaults to ,15 Ohm ( or 150 milli Ohm) as in the TMC260 Arduino Shield
+
+     * This routine configures the TMC26X stepper driver for the given values via SPI.
+     * Most member functions are non functional if the driver has not been started.
+     * Therefore it is best to call this in your Arduino setup() function.
+     */
+    void init();
+
+    /*!
+     * \brief Set the number of microsteps in 2^i values (rounded) up to 256
+     *
+     * This method set's the number of microsteps per step in 2^i interval.
+     * This means you can select 1, 2, 4, 16, 32, 64, 128 or 256 as valid microsteps.
+     * If you give any other value it will be rounded to the next smaller number (3 would give a microstepping of 2).
+     * You can always check the current microstepping with getMicrosteps().
+     */
+    void setMicrosteps(int number_of_steps);
+
+    /*!
+     * \brief returns the effective current number of microsteps selected.
+     *
+     * This function always returns the effective number of microsteps.
+     * This can be a bit different than the micro steps set in setMicrosteps() since it is rounded to 2^i.
+     *
+     * \sa setMicrosteps()
+     */
+    int getMicrosteps(void);
+
+    /*!
+     * \brief Sets and configure the classical Constant Off Timer Chopper
+     * \param constant_off_time The off time setting controls the minimum chopper frequency. For most applications an off time within the range of 5μs to 20μs will fit. Setting this parameter to zero completely disables all driver transistors and the motor can free-wheel. 0: chopper off, 1:15: off time setting (1 will work with minimum blank time of 24 clocks)
+     * \param blank_time Selects the comparator blank time. This time needs to safely cover the switching event and the duration of the ringing on the sense resistor. For most low current drivers, a setting of 1 or 2 is good. For high current applications with large MOSFETs, a setting of 2 or 3 will be required. 0 (min setting) … (3) amx setting
+     * \param fast_decay_time_setting Fast decay time setting. Controls the portion of fast decay for each chopper cycle. 0: slow decay only, 1…15: duration of fast decay phase
+     * \param sine_wave_offset Sine wave offset. Controls the sine wave offset. A positive offset corrects for zero crossing error. -3…-1: negative offset, 0: no offset,1…12: positive offset
+     * \param use_curreent_comparator Selects usage of the current comparator for termination of the fast decay cycle. If current comparator is enabled, it terminates the fast decay cycle in case the current reaches a higher negative value than the actual positive value. (0 disable, -1 enable).
+     *
+     * The classic constant off time chopper uses a fixed portion of fast decay following each on phase.
+     * While the duration of the on time is determined by the chopper comparator, the fast decay time needs
+     * to be set by the user in a way, that the current decay is enough for the driver to be able to follow
+     * the falling slope of the sine wave, and on the other hand it should not be too long, in order to minimize
+     * motor current ripple and power dissipation. This best can be tuned using an oscilloscope or
+     * trying out motor smoothness at different velocities. A good starting value is a fast decay time setting
+     * similar to the slow decay time setting.
+     * After tuning of the fast decay time, the offset should be determined, in order to have a smooth zero transition.
+     * This is necessary, because the fast decay phase leads to the absolute value of the motor current being lower
+     * than the target current (see figure 17). If the zero offset is too low, the motor stands still for a short
+     * moment during current zero crossing, if it is set too high, it makes a larger microstep.
+     * Typically, a positive offset setting is required for optimum operation.
+     *
+     * \sa setSpreadCycleChoper() for other alternatives.
+     * \sa setRandomOffTime() for spreading the noise over a wider spectrum
+     */
+    void setConstantOffTimeChopper(int8_t constant_off_time, int8_t blank_time, int8_t fast_decay_time_setting, int8_t sine_wave_offset, uint8_t use_current_comparator);
+
+    /*!
+     * \brief Sets and configures with spread cycle chopper.
+     * \param constant_off_time The off time setting controls the minimum chopper frequency. For most applications an off time within the range of 5μs to 20μs will fit. Setting this parameter to zero completely disables all driver transistors and the motor can free-wheel. 0: chopper off, 1:15: off time setting (1 will work with minimum blank time of 24 clocks)
+     * \param blank_time Selects the comparator blank time. This time needs to safely cover the switching event and the duration of the ringing on the sense resistor. For most low current drivers, a setting of 1 or 2 is good. For high current applications with large MOSFETs, a setting of 2 or 3 will be required. 0 (min setting) … (3) amx setting
+     * \param hysteresis_start Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value. 1 … 8
+     * \param hysteresis_end Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by hysteresis_decrement. The sum hysteresis_start + hysteresis_end must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
+     * \param hysteresis_decrement Hysteresis decrement setting. This setting determines the slope of the hysteresis during on time and during fast decay time. 0 (fast decrement) … 3 (slow decrement).
+     *
+     * The spreadCycle chopper scheme (pat.fil.) is a precise and simple to use chopper principle, which automatically determines
+     * the optimum fast decay portion for the motor. Anyhow, a number of settings can be made in order to optimally fit the driver
+     * to the motor.
+     * Each chopper cycle is comprised of an on-phase, a slow decay phase, a fast decay phase and a second slow decay phase.
+     * The slow decay phases limit the maximum chopper frequency and are important for low motor and driver power dissipation.
+     * The hysteresis start setting limits the chopper frequency by forcing the driver to introduce a minimum amount of
+     * current ripple into the motor coils. The motor inductivity determines the ability to follow a changing motor current.
+     * The duration of the on- and fast decay phase needs to cover at least the blank time, because the current comparator is
+     * disabled during this time.
+     *
+     * \sa setRandomOffTime() for spreading the noise over a wider spectrum
+     */
+    void setSpreadCycleChopper(int8_t constant_off_time, int8_t blank_time, int8_t hysteresis_start, int8_t hysteresis_end, int8_t hysteresis_decrement);
+
+    /*!
+     * \brief Use random off time for noise reduction (0 for off, -1 for on).
+     * \param value 0 for off, -1 for on
+     *
+     * In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
+     * The frequency of each chopper mainly depends on the coil current and the position dependant motor coil inductivity,
+     * thus it depends on the microstep position. With some motors a slightly audible beat can occur between the chopper
+     * frequencies, especially when they are near to each other. This typically occurs at a few microstep positions within
+     * each quarter wave.
+     * This effect normally is not audible when compared to mechanical noise generated by ball bearings,
+     * etc. Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
+     * In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
+     * It modulates the slow decay time setting when switched on. The random off time feature further spreads the chopper spectrum,
+     * reducing electromagnetic emission on single frequencies.
+     */
+    void setRandomOffTime(int8_t value);
+
+    /*!
+     * \brief set the maximum motor current in mA (1000 is 1 Amp)
+     * Keep in mind this is the maximum peak Current. The RMS current will be 1/sqrt(2) smaller. The actual current can also be smaller
+     * by employing CoolStep.
+     * \param current the maximum motor current in mA
+     * \sa getCurrent(), getCurrentCurrent()
+     */
+    void setCurrent(unsigned int current);
+
+    /*!
+     * \brief readout the motor maximum current in mA (1000 is an Amp)
+     * This is the maximum current. to get the current current - which may be affected by CoolStep us getCurrentCurrent()
+     *\return the maximum motor current in milli amps
+     * \sa getCurrentCurrent()
+     */
+    unsigned int getCurrent(void);
+
+    /*!
+     * \brief set the StallGuard threshold in order to get sensible StallGuard readings.
+     * \param stall_guard_threshold -64 … 63 the StallGuard threshold
+     * \param stall_guard_filter_enabled 0 if the filter is disabled, -1 if it is enabled
+     *
+     * The StallGuard threshold is used to optimize the StallGuard reading to sensible values. It should be at 0 at
+     * the maximum allowable load on the otor (but not before). = is a good starting point (and the default)
+     * If you get Stall Gaurd readings of 0 without any load or with too little laod increase the value.
+     * If you get readings of 1023 even with load decrease the setting.
+     *
+     * If you switch on the filter the StallGuard reading is only updated each 4th full step to reduce the noise in the
+     * reading.
+     *
+     * \sa getCurrentStallGuardReading() to read out the current value.
+     */
+    void setStallGuardThreshold(int8_t stall_guard_threshold, int8_t stall_guard_filter_enabled);
+
+    /*!
+     * \brief reads out the StallGuard threshold
+     * \return a number between -64 and 63.
+     */
+    int8_t getStallGuardThreshold(void);
+
+    /*!
+     * \brief returns the current setting of the StallGuard filter
+     * \return 0 if not set, -1 if set
+     */
+    int8_t getStallGuardFilter(void);
+
+    /*!
+     * \brief This method configures the CoolStep smart energy operation. You must have a proper StallGuard configuration for the motor situation (current, voltage, speed) in rder to use this feature.
+     * \param lower_SG_threshold Sets the lower threshold for stallGuard2TM reading. Below this value, the motor current becomes increased. Allowed values are 0...480
+     * \param SG_hysteresis Sets the distance between the lower and the upper threshold for stallGuard2TM reading. Above the upper threshold (which is lower_SG_threshold+SG_hysteresis+1) the motor current becomes decreased. Allowed values are 0...480
+     * \param current_decrement_step_size Sets the current decrement steps. If the StallGuard value is above the threshold the current gets decremented by this step size. 0...32
+     * \param current_increment_step_size Sets the current increment step. The current becomes incremented for each measured stallGuard2TM value below the lower threshold. 0...8
+     * \param lower_current_limit Sets the lower motor current limit for coolStepTM operation by scaling the CS value. Values can be COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
+     * The CoolStep smart energy operation automatically adjust the current sent into the motor according to the current load,
+     * read out by the StallGuard in order to provide the optimum torque with the minimal current consumption.
+     * You configure the CoolStep current regulator by defining upper and lower bounds of StallGuard readouts. If the readout is above the
+     * limit the current gets increased, below the limit the current gets decreased.
+     * You can specify the upper an lower threshold of the StallGuard readout in order to adjust the current. You can also set the number of
+     * StallGuard readings neccessary above or below the limit to get a more stable current adjustement.
+     * The current adjustement itself is configured by the number of steps the current gests in- or decreased and the absolut minimum current
+     * (1/2 or 1/4th otf the configured current).
+     * \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
+     */
+    void setCoolStepConfiguration(unsigned int lower_SG_threshold, unsigned int SG_hysteresis, uint8_t current_decrement_step_size,
+                                  uint8_t current_increment_step_size, uint8_t lower_current_limit);
+
+    /*!
+     * \brief enables or disables the CoolStep smart energy operation feature. It must be configured before enabling it.
+     * \param enabled true if CoolStep should be enabled, false if not.
+     * \sa setCoolStepConfiguration()
+     */
+    void setCoolStepEnabled(bool enabled);
+
+
+    /*!
+     * \brief check if the CoolStep feature is enabled
+     * \sa setCoolStepEnabled()
+     */
+    bool isCoolStepEnabled();
+
+    /*!
+     * \brief returns the lower StallGuard threshold for the CoolStep operation
+     * \sa setCoolStepConfiguration()
+     */
+    unsigned int getCoolStepLowerSgThreshold();
+
+    /*!
+     * \brief returns the upper StallGuard threshold for the CoolStep operation
+     * \sa setCoolStepConfiguration()
+     */
+    unsigned int getCoolStepUpperSgThreshold();
+
+    /*!
+     * \brief returns the number of StallGuard readings befor CoolStep adjusts the motor current.
+     * \sa setCoolStepConfiguration()
+     */
+    uint8_t getCoolStepNumberOfSGReadings();
+
+    /*!
+     * \brief returns the increment steps for the current for the CoolStep operation
+     * \sa setCoolStepConfiguration()
+     */
+    uint8_t getCoolStepCurrentIncrementSize();
+
+    /*!
+     * \brief returns the absolut minium current for the CoolStep operation
+     * \sa setCoolStepConfiguration()
+     * \sa COOL_STEP_HALF_CS_LIMIT, COOL_STEP_QUARTER_CS_LIMIT
+     */
+    uint8_t getCoolStepLowerCurrentLimit();
+
+    /*!
+     * \brief Reads the current StallGuard value.
+     * \return The current StallGuard value, lesser values indicate higher load, 0 means stall detected.
+     * Keep in mind that this routine reads and writes a value via SPI - so this may take a bit time.
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
+     */
+    int getCurrentStallGuardReading(void);
+
+    /*!
+     * \brief Reads the current current setting value as fraction of the maximum current
+     * Returns values between 0 and 31, representing 1/32 to 32/32 (=1)
+     * \sa setCoolStepConfiguration()
+     */
+    uint8_t getCurrentCSReading(void);
+
+
+    /*!
+     *\brief a convenience method to determine if the current scaling uses 0.31V or 0.165V as reference.
+     *\return false if 0.13V is the reference voltage, true if 0.165V is used.
+     */
+    bool isCurrentScalingHalfed();
+
+    /*!
+     * \brief Reads the current current setting value and recalculates the absolute current in mA (1A would be 1000).
+     * This method calculates the currently used current setting (either by setting or by CoolStep) and reconstructs
+     * the current in mA by usinge the VSENSE and resistor value. This method uses floating point math - so it
+     * may not be the fastest.
+     * \sa getCurrentCSReading(), getResistor(), isCurrentScalingHalfed(), getCurrent()
+     */
+    unsigned int getCurrentCurrent(void);
+
+    /*!
+     * \brief checks if there is a StallGuard warning in the last status
+     * \return 0 if there was no warning, -1 if there was some warning.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     *
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
+     */
+    bool isStallGuardOverThreshold(void);
+
+    /*!
+     * \brief Return over temperature status of the last status readout
+     * return 0 is everything is OK, TMC26X_OVERTEMPERATURE_PREWARING if status is reached, TMC26X_OVERTEMPERATURE_SHUTDOWN is the chip is shutdown, -1 if the status is unknown.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+    int8_t getOverTemperature(void);
+
+    /*!
+     * \brief Is motor channel A shorted to ground detected in the last status readout.
+     * \return true is yes, false if not.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+
+    bool isShortToGroundA(void);
+
+    /*!
+     * \brief Is motor channel B shorted to ground detected in the last status readout.
+     * \return true is yes, false if not.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+    bool isShortToGroundB(void);
+    /*!
+     * \brief iIs motor channel A connected according to the last statu readout.
+     * \return true is yes, false if not.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+    bool isOpenLoadA(void);
+
+    /*!
+     * \brief iIs motor channel A connected according to the last statu readout.
+     * \return true is yes, false if not.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+    bool isOpenLoadB(void);
+
+    /*!
+     * \brief Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
+     * \return true is yes, false if not.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     */
+    bool isStandStill(void);
+
+    /*!
+     * \brief checks if there is a StallGuard warning in the last status
+     * \return 0 if there was no warning, -1 if there was some warning.
+     * Keep in mind that this method does not enforce a readout but uses the value of the last status readout.
+     * You may want to use getMotorPosition() or getCurrentStallGuardReading() to enforce an updated status readout.
+     *
+     * \sa isStallGuardOverThreshold()
+     * TODO why?
+     *
+     * \sa setStallGuardThreshold() for tuning the readout to sensible ranges.
+     */
+    bool isStallGuardReached(void);
+
+    /*!
+     *\brief enables or disables the motor driver bridges. If disabled the motor can run freely. If enabled not.
+     *\param enabled a bool value true if the motor should be enabled, false otherwise.
+     */
+    void setEnabled(bool enabled);
+
+    /*!
+     *\brief checks if the output bridges are enabled. If the bridges are not enabled the motor can run freely
+     *\return true if the bridges and by that the motor driver are enabled, false if not.
+     *\sa setEnabled()
+     */
+    bool isEnabled();
+
+    /*!
+     * \brief Manually read out the status register
+     * This function sends a byte to the motor driver in order to get the current readout. The parameter read_value
+     * seletcs which value will get returned. If the read_vlaue changes in respect to the previous readout this method
+     * automatically send two bytes to the motor: one to set the redout and one to get the actual readout. So this method
+     * may take time to send and read one or two bits - depending on the previous readout.
+     * \param read_value selects which value to read out (0..3). You can use the defines TMC26X_READOUT_POSITION, TMC_262_READOUT_STALLGUARD, or TMC_262_READOUT_CURRENT
+     * \sa TMC26X_READOUT_POSITION, TMC_262_READOUT_STALLGUARD, TMC_262_READOUT_CURRENT
+     */
+    void readStatus(int8_t read_value);
+
+    /*!
+     * \brief Returns the current sense resistor value in milliohm.
+     * The default value of ,15 Ohm will return 150.
+     */
+    int getResistor();
+    void setResistor(unsigned int resistor);
+
+    /*!
+     * \brief Prints out all the information that can be found in the last status read out - it does not force a status readout.
+     * The result is printed via Serial
+     */
+    void dumpStatus(StreamOutput *stream);
+    /*!
+     * \brief library version
+     * \return the version number as int.
+     */
+    int version(void);
+
+private:
+    unsigned int resistor{150}; //current sense resitor value in milliohm
+
+    //driver control register copies to easily set & modify the registers
+    unsigned long driver_control_register_value;
+    unsigned long chopper_config_register;
+    unsigned long cool_step_register_value;
+    unsigned long stall_guard2_current_register_value;
+    unsigned long driver_configuration_register_value;
+    //the driver status result
+    unsigned long driver_status_result;
+
+    //helper routione to get the top 10 bit of the readout
+    inline int getReadoutValue();
+
+    //status values
+    bool started; //if the stepper has been started yet
+    int microsteps; //the current number of micro steps
+    int8_t constant_off_time; //we need to remember this value in order to enable and disable the motor
+    uint8_t cool_step_lower_threshold; // we need to remember the threshold to enable and disable the CoolStep feature
+    bool cool_step_enabled; //we need to remember this to configure the coolstep if it si enabled
+
+    // SPI sender
+    std::function<int(uint8_t *b, int cnt, uint8_t *r)> spi;
+    inline void send262(unsigned long datagram);
+};
+