My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TMC2660.cpp 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. /**
  2. * TMC26XStepper.cpp - - TMC26X Stepper library for Wiring/Arduino
  3. *
  4. * based on the stepper library by Tom Igoe, et. al.
  5. *
  6. * Copyright (c) 2011, Interactive Matter, Marcus Nowotny
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be included in
  16. * all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. *
  26. */
  27. #if defined(STM32GENERIC) && defined(STM32F7)
  28. #include "../../../inc/MarlinConfigPre.h"
  29. #if HAS_DRIVER(TMC2660)
  30. #include <stdbool.h>
  31. #include <SPI.h>
  32. #include "TMC2660.h"
  33. #include "../../../inc/MarlinConfig.h"
  34. #include "../../../MarlinCore.h"
  35. #include "../../../module/stepper/indirection.h"
  36. #include "../../../module/printcounter.h"
  37. #include "../../../libs/duration_t.h"
  38. #include "../../../libs/hex_print_routines.h"
  39. //some default values used in initialization
  40. #define DEFAULT_MICROSTEPPING_VALUE 32
  41. //TMC26X register definitions
  42. #define DRIVER_CONTROL_REGISTER 0x0ul
  43. #define CHOPPER_CONFIG_REGISTER 0x80000ul
  44. #define COOL_STEP_REGISTER 0xA0000ul
  45. #define STALL_GUARD2_LOAD_MEASURE_REGISTER 0xC0000ul
  46. #define DRIVER_CONFIG_REGISTER 0xE0000ul
  47. #define REGISTER_BIT_PATTERN 0xFFFFFul
  48. //definitions for the driver control register
  49. #define MICROSTEPPING_PATTERN 0xFul
  50. #define STEP_INTERPOLATION 0x200ul
  51. #define DOUBLE_EDGE_STEP 0x100ul
  52. #define VSENSE 0x40ul
  53. #define READ_MICROSTEP_POSTION 0x0ul
  54. #define READ_STALL_GUARD_READING 0x10ul
  55. #define READ_STALL_GUARD_AND_COOL_STEP 0x20ul
  56. #define READ_SELECTION_PATTERN 0x30ul
  57. //definitions for the chopper config register
  58. #define CHOPPER_MODE_STANDARD 0x0ul
  59. #define CHOPPER_MODE_T_OFF_FAST_DECAY 0x4000ul
  60. #define T_OFF_PATTERN 0xFul
  61. #define RANDOM_TOFF_TIME 0x2000ul
  62. #define BLANK_TIMING_PATTERN 0x18000ul
  63. #define BLANK_TIMING_SHIFT 15
  64. #define HYSTERESIS_DECREMENT_PATTERN 0x1800ul
  65. #define HYSTERESIS_DECREMENT_SHIFT 11
  66. #define HYSTERESIS_LOW_VALUE_PATTERN 0x780ul
  67. #define HYSTERESIS_LOW_SHIFT 7
  68. #define HYSTERESIS_START_VALUE_PATTERN 0x78ul
  69. #define HYSTERESIS_START_VALUE_SHIFT 4
  70. #define T_OFF_TIMING_PATERN 0xFul
  71. //definitions for cool step register
  72. #define MINIMUM_CURRENT_FOURTH 0x8000ul
  73. #define CURRENT_DOWN_STEP_SPEED_PATTERN 0x6000ul
  74. #define SE_MAX_PATTERN 0xF00ul
  75. #define SE_CURRENT_STEP_WIDTH_PATTERN 0x60ul
  76. #define SE_MIN_PATTERN 0xFul
  77. //definitions for StallGuard2 current register
  78. #define STALL_GUARD_FILTER_ENABLED 0x10000ul
  79. #define STALL_GUARD_TRESHHOLD_VALUE_PATTERN 0x17F00ul
  80. #define CURRENT_SCALING_PATTERN 0x1Ful
  81. #define STALL_GUARD_CONFIG_PATTERN 0x17F00ul
  82. #define STALL_GUARD_VALUE_PATTERN 0x7F00ul
  83. //definitions for the input from the TMC2660
  84. #define STATUS_STALL_GUARD_STATUS 0x1ul
  85. #define STATUS_OVER_TEMPERATURE_SHUTDOWN 0x2ul
  86. #define STATUS_OVER_TEMPERATURE_WARNING 0x4ul
  87. #define STATUS_SHORT_TO_GROUND_A 0x8ul
  88. #define STATUS_SHORT_TO_GROUND_B 0x10ul
  89. #define STATUS_OPEN_LOAD_A 0x20ul
  90. #define STATUS_OPEN_LOAD_B 0x40ul
  91. #define STATUS_STAND_STILL 0x80ul
  92. #define READOUT_VALUE_PATTERN 0xFFC00ul
  93. #define CPU_32_BIT
  94. //default values
  95. #define INITIAL_MICROSTEPPING 0x3ul //32th microstepping
  96. SPIClass SPI_6(SPI6, SPI6_MOSI_PIN, SPI6_MISO_PIN, SPI6_SCK_PIN);
  97. #define STEPPER_SPI SPI_6
  98. //debuging output
  99. //#define TMC_DEBUG1
  100. uint8_t current_scaling = 0;
  101. /**
  102. * Constructor
  103. * number_of_steps - the steps per rotation
  104. * cs_pin - the SPI client select pin
  105. * dir_pin - the pin where the direction pin is connected
  106. * step_pin - the pin where the step pin is connected
  107. */
  108. TMC26XStepper::TMC26XStepper(const int16_t in_steps, int16_t cs_pin, int16_t dir_pin, int16_t step_pin, uint16_t current, uint16_t resistor) {
  109. // We are not started yet
  110. started = false;
  111. // By default cool step is not enabled
  112. cool_step_enabled = false;
  113. // Save the pins for later use
  114. this->cs_pin = cs_pin;
  115. this->dir_pin = dir_pin;
  116. this->step_pin = step_pin;
  117. // Store the current sense resistor value for later use
  118. this->resistor = resistor;
  119. // Initizalize our status values
  120. this->steps_left = 0;
  121. this->direction = 0;
  122. // Initialize register values
  123. driver_control_register_value = DRIVER_CONTROL_REGISTER | INITIAL_MICROSTEPPING;
  124. chopper_config_register = CHOPPER_CONFIG_REGISTER;
  125. // Setting the default register values
  126. driver_control_register_value = DRIVER_CONTROL_REGISTER|INITIAL_MICROSTEPPING;
  127. microsteps = _BV(INITIAL_MICROSTEPPING);
  128. chopper_config_register = CHOPPER_CONFIG_REGISTER;
  129. cool_step_register_value = COOL_STEP_REGISTER;
  130. stallguard2_current_register_value = STALL_GUARD2_LOAD_MEASURE_REGISTER;
  131. driver_configuration_register_value = DRIVER_CONFIG_REGISTER | READ_STALL_GUARD_READING;
  132. // Set the current
  133. setCurrent(current);
  134. // Set to a conservative start value
  135. setConstantOffTimeChopper(7, 54, 13,12,1);
  136. // Set a nice microstepping value
  137. setMicrosteps(DEFAULT_MICROSTEPPING_VALUE);
  138. // Save the number of steps
  139. number_of_steps = in_steps;
  140. }
  141. /**
  142. * start & configure the stepper driver
  143. * just must be called.
  144. */
  145. void TMC26XStepper::start() {
  146. #ifdef TMC_DEBUG1
  147. SERIAL_ECHOLNPGM("\n TMC26X stepper library");
  148. SERIAL_ECHOPAIR("\n CS pin: ", cs_pin);
  149. SERIAL_ECHOPAIR("\n DIR pin: ", dir_pin);
  150. SERIAL_ECHOPAIR("\n STEP pin: ", step_pin);
  151. SERIAL_PRINTF("\n current scaling: %d", current_scaling);
  152. SERIAL_PRINTF("\n Resistor: %d", resistor);
  153. //SERIAL_PRINTF("\n current: %d", current);
  154. SERIAL_ECHOPAIR("\n Microstepping: ", microsteps);
  155. #endif
  156. //set the pins as output & its initial value
  157. pinMode(step_pin, OUTPUT);
  158. pinMode(dir_pin, OUTPUT);
  159. pinMode(cs_pin, OUTPUT);
  160. extDigitalWrite(step_pin, LOW);
  161. extDigitalWrite(dir_pin, LOW);
  162. extDigitalWrite(cs_pin, HIGH);
  163. STEPPER_SPI.begin();
  164. STEPPER_SPI.beginTransaction(SPISettings(4000000, MSBFIRST, SPI_MODE3));
  165. //set the initial values
  166. send262(driver_control_register_value);
  167. send262(chopper_config_register);
  168. send262(cool_step_register_value);
  169. send262(stallguard2_current_register_value);
  170. send262(driver_configuration_register_value);
  171. //save that we are in running mode
  172. started = true;
  173. }
  174. /**
  175. * Mark the driver as unstarted to be able to start it again
  176. */
  177. void TMC26XStepper::un_start() { started = false; }
  178. /**
  179. * Sets the speed in revs per minute
  180. */
  181. void TMC26XStepper::setSpeed(uint16_t whatSpeed) {
  182. this->speed = whatSpeed;
  183. this->step_delay = 60UL * sq(1000UL) / ((uint32_t)this->number_of_steps * (uint32_t)whatSpeed * (uint32_t)this->microsteps);
  184. #ifdef TMC_DEBUG0 // crashes
  185. SERIAL_ECHOPAIR("\nStep delay in micros: ", this->step_delay);
  186. #endif
  187. // Update the next step time
  188. this->next_step_time = this->last_step_time + this->step_delay;
  189. }
  190. uint16_t TMC26XStepper::getSpeed() { return this->speed; }
  191. /**
  192. * Moves the motor steps_to_move steps.
  193. * Negative indicates the reverse direction.
  194. */
  195. char TMC26XStepper::step(int16_t steps_to_move) {
  196. if (this->steps_left == 0) {
  197. this->steps_left = ABS(steps_to_move); // how many steps to take
  198. // determine direction based on whether steps_to_move is + or -:
  199. if (steps_to_move > 0)
  200. this->direction = 1;
  201. else if (steps_to_move < 0)
  202. this->direction = 0;
  203. return 0;
  204. }
  205. return -1;
  206. }
  207. char TMC26XStepper::move() {
  208. // decrement the number of steps, moving one step each time:
  209. if (this->steps_left > 0) {
  210. uint32_t time = micros();
  211. // move only if the appropriate delay has passed:
  212. // rem if (time >= this->next_step_time) {
  213. if (ABS(time - this->last_step_time) > this->step_delay) {
  214. // increment or decrement the step number,
  215. // depending on direction:
  216. if (this->direction == 1)
  217. extDigitalWrite(step_pin, HIGH);
  218. else {
  219. extDigitalWrite(dir_pin, HIGH);
  220. extDigitalWrite(step_pin, HIGH);
  221. }
  222. // get the timeStamp of when you stepped:
  223. this->last_step_time = time;
  224. this->next_step_time = time + this->step_delay;
  225. // decrement the steps left:
  226. steps_left--;
  227. //disable the step & dir pins
  228. extDigitalWrite(step_pin, LOW);
  229. extDigitalWrite(dir_pin, LOW);
  230. }
  231. return -1;
  232. }
  233. return 0;
  234. }
  235. char TMC26XStepper::isMoving() { return this->steps_left > 0; }
  236. uint16_t TMC26XStepper::getStepsLeft() { return this->steps_left; }
  237. char TMC26XStepper::stop() {
  238. //note to self if the motor is currently moving
  239. char state = isMoving();
  240. //stop the motor
  241. this->steps_left = 0;
  242. this->direction = 0;
  243. //return if it was moving
  244. return state;
  245. }
  246. void TMC26XStepper::setCurrent(uint16_t current) {
  247. uint8_t current_scaling = 0;
  248. //calculate the current scaling from the max current setting (in mA)
  249. float mASetting = (float)current,
  250. resistor_value = (float)this->resistor;
  251. // remove vsense flag
  252. this->driver_configuration_register_value &= ~(VSENSE);
  253. // Derived from I = (cs + 1) / 32 * (Vsense / Rsense)
  254. // leading to cs = 32 * R * I / V (with V = 0,31V oder 0,165V and I = 1000 * current)
  255. // with Rsense = 0,15
  256. // for vsense = 0,310V (VSENSE not set)
  257. // or vsense = 0,165V (VSENSE set)
  258. current_scaling = (byte)((resistor_value * mASetting * 32.0 / (0.31 * sq(1000.0))) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
  259. // Check if the current scalingis too low
  260. if (current_scaling < 16) {
  261. // Set the csense bit to get a use half the sense voltage (to support lower motor currents)
  262. this->driver_configuration_register_value |= VSENSE;
  263. // and recalculate the current setting
  264. current_scaling = (byte)((resistor_value * mASetting * 32.0 / (0.165 * sq(1000.0))) - 0.5); //theoretically - 1.0 for better rounding it is 0.5
  265. #ifdef TMC_DEBUG0 // crashes
  266. SERIAL_ECHOPAIR("\nCS (Vsense=1): ",current_scaling);
  267. #endif
  268. }
  269. #ifdef TMC_DEBUG0 // crashes
  270. else
  271. SERIAL_ECHOPAIR("\nCS: ", current_scaling);
  272. #endif
  273. // do some sanity checks
  274. NOMORE(current_scaling, 31);
  275. // delete the old value
  276. stallguard2_current_register_value &= ~(CURRENT_SCALING_PATTERN);
  277. // set the new current scaling
  278. stallguard2_current_register_value |= current_scaling;
  279. // if started we directly send it to the motor
  280. if (started) {
  281. send262(driver_configuration_register_value);
  282. send262(stallguard2_current_register_value);
  283. }
  284. }
  285. uint16_t TMC26XStepper::getCurrent() {
  286. // Calculate the current according to the datasheet to be on the safe side.
  287. // This is not the fastest but the most accurate and illustrative way.
  288. float result = (float)(stallguard2_current_register_value & CURRENT_SCALING_PATTERN),
  289. resistor_value = (float)this->resistor,
  290. voltage = (driver_configuration_register_value & VSENSE) ? 0.165 : 0.31;
  291. result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
  292. return (uint16_t)result;
  293. }
  294. void TMC26XStepper::setStallGuardThreshold(char stallguard_threshold, char stallguard_filter_enabled) {
  295. // We just have 5 bits
  296. LIMIT(stallguard_threshold, -64, 63);
  297. // Add trim down to 7 bits
  298. stallguard_threshold &= 0x7F;
  299. // Delete old StallGuard settings
  300. stallguard2_current_register_value &= ~(STALL_GUARD_CONFIG_PATTERN);
  301. if (stallguard_filter_enabled)
  302. stallguard2_current_register_value |= STALL_GUARD_FILTER_ENABLED;
  303. // Set the new StallGuard threshold
  304. stallguard2_current_register_value |= (((uint32_t)stallguard_threshold << 8) & STALL_GUARD_CONFIG_PATTERN);
  305. // If started we directly send it to the motor
  306. if (started) send262(stallguard2_current_register_value);
  307. }
  308. char TMC26XStepper::getStallGuardThreshold() {
  309. uint32_t stallguard_threshold = stallguard2_current_register_value & STALL_GUARD_VALUE_PATTERN;
  310. //shift it down to bit 0
  311. stallguard_threshold >>= 8;
  312. //convert the value to an int16_t to correctly handle the negative numbers
  313. char result = stallguard_threshold;
  314. //check if it is negative and fill it up with leading 1 for proper negative number representation
  315. //rem if (result & _BV(6)) {
  316. if (TEST(result, 6)) result |= 0xC0;
  317. return result;
  318. }
  319. char TMC26XStepper::getStallGuardFilter() {
  320. if (stallguard2_current_register_value & STALL_GUARD_FILTER_ENABLED)
  321. return -1;
  322. return 0;
  323. }
  324. /**
  325. * Set the number of microsteps per step.
  326. * 0,2,4,8,16,32,64,128,256 is supported
  327. * any value in between will be mapped to the next smaller value
  328. * 0 and 1 set the motor in full step mode
  329. */
  330. void TMC26XStepper::setMicrosteps(const int16_t in_steps) {
  331. uint16_t setting_pattern;
  332. if (in_steps >= 256) setting_pattern = 0;
  333. else if (in_steps >= 128) setting_pattern = 1;
  334. else if (in_steps >= 64) setting_pattern = 2;
  335. else if (in_steps >= 32) setting_pattern = 3;
  336. else if (in_steps >= 16) setting_pattern = 4;
  337. else if (in_steps >= 8) setting_pattern = 5;
  338. else if (in_steps >= 4) setting_pattern = 6;
  339. else if (in_steps >= 2) setting_pattern = 7;
  340. else if (in_steps <= 1) setting_pattern = 8; // 1 and 0 lead to full step
  341. microsteps = _BV(8 - setting_pattern);
  342. #ifdef TMC_DEBUG0 // crashes
  343. SERIAL_ECHOPAIR("\n Microstepping: ", microsteps);
  344. #endif
  345. // Delete the old value
  346. this->driver_control_register_value &= 0x000FFFF0UL;
  347. // Set the new value
  348. this->driver_control_register_value |= setting_pattern;
  349. // If started we directly send it to the motor
  350. if (started) send262(driver_control_register_value);
  351. // Recalculate the stepping delay by simply setting the speed again
  352. this->setSpeed(this->speed);
  353. }
  354. /**
  355. * returns the effective number of microsteps at the moment
  356. */
  357. int16_t TMC26XStepper::getMicrosteps() { return microsteps; }
  358. /**
  359. * constant_off_time: The off time setting controls the minimum chopper frequency.
  360. * For most applications an off time within the range of 5μs to 20μs will fit.
  361. * 2...15: off time setting
  362. *
  363. * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
  364. * duration of the ringing on the sense resistor. For
  365. * 0: min. setting 3: max. setting
  366. *
  367. * fast_decay_time_setting: Fast decay time setting. With CHM=1, these bits control the portion of fast decay for each chopper cycle.
  368. * 0: slow decay only
  369. * 1...15: duration of fast decay phase
  370. *
  371. * sine_wave_offset: Sine wave offset. With CHM=1, these bits control the sine wave offset.
  372. * A positive offset corrects for zero crossing error.
  373. * -3..-1: negative offset 0: no offset 1...12: positive offset
  374. *
  375. * use_current_comparator: Selects usage of the current comparator for termination of the fast decay cycle.
  376. * If current comparator is enabled, it terminates the fast decay cycle in case the current
  377. * reaches a higher negative value than the actual positive value.
  378. * 1: enable comparator termination of fast decay cycle
  379. * 0: end by time only
  380. */
  381. void TMC26XStepper::setConstantOffTimeChopper(char constant_off_time, char blank_time, char fast_decay_time_setting, char sine_wave_offset, uint8_t use_current_comparator) {
  382. // Perform some sanity checks
  383. LIMIT(constant_off_time, 2, 15);
  384. // Save the constant off time
  385. this->constant_off_time = constant_off_time;
  386. // Calculate the value acc to the clock cycles
  387. const char blank_value = blank_time >= 54 ? 3 :
  388. blank_time >= 36 ? 2 :
  389. blank_time >= 24 ? 1 : 0;
  390. LIMIT(fast_decay_time_setting, 0, 15);
  391. LIMIT(sine_wave_offset, -3, 12);
  392. // Shift the sine_wave_offset
  393. sine_wave_offset += 3;
  394. // Calculate the register setting
  395. // First of all delete all the values for this
  396. chopper_config_register &= ~(_BV(12) | BLANK_TIMING_PATTERN | HYSTERESIS_DECREMENT_PATTERN | HYSTERESIS_LOW_VALUE_PATTERN | HYSTERESIS_START_VALUE_PATTERN | T_OFF_TIMING_PATERN);
  397. // Set the constant off pattern
  398. chopper_config_register |= CHOPPER_MODE_T_OFF_FAST_DECAY;
  399. // Set the blank timing value
  400. chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
  401. // Setting the constant off time
  402. chopper_config_register |= constant_off_time;
  403. // Set the fast decay time
  404. // Set msb
  405. chopper_config_register |= (((uint32_t)(fast_decay_time_setting & 0x8)) << HYSTERESIS_DECREMENT_SHIFT);
  406. // Other bits
  407. chopper_config_register |= (((uint32_t)(fast_decay_time_setting & 0x7)) << HYSTERESIS_START_VALUE_SHIFT);
  408. // Set the sine wave offset
  409. chopper_config_register |= (uint32_t)sine_wave_offset << HYSTERESIS_LOW_SHIFT;
  410. // Using the current comparator?
  411. if (!use_current_comparator)
  412. chopper_config_register |= _BV(12);
  413. // If started we directly send it to the motor
  414. if (started) {
  415. // rem send262(driver_control_register_value);
  416. send262(chopper_config_register);
  417. }
  418. }
  419. /**
  420. * constant_off_time: The off time setting controls the minimum chopper frequency.
  421. * For most applications an off time within the range of 5μs to 20μs will fit.
  422. * 2...15: off time setting
  423. *
  424. * blank_time: Selects the comparator blank time. This time needs to safely cover the switching event and the
  425. * duration of the ringing on the sense resistor. For
  426. * 0: min. setting 3: max. setting
  427. *
  428. * hysteresis_start: Hysteresis start setting. Please remark, that this value is an offset to the hysteresis end value HEND.
  429. * 1...8
  430. *
  431. * hysteresis_end: Hysteresis end setting. Sets the hysteresis end value after a number of decrements. Decrement interval time is controlled by HDEC.
  432. * The sum HSTRT+HEND must be <16. At a current setting CS of max. 30 (amplitude reduced to 240), the sum is not limited.
  433. * -3..-1: negative HEND 0: zero HEND 1...12: positive HEND
  434. *
  435. * hysteresis_decrement: Hysteresis decrement setting. This setting determines the slope of the hysteresis during on time and during fast decay time.
  436. * 0: fast decrement 3: very slow decrement
  437. */
  438. void TMC26XStepper::setSpreadCycleChopper(char constant_off_time, char blank_time, char hysteresis_start, char hysteresis_end, char hysteresis_decrement) {
  439. // Perform some sanity checks
  440. LIMIT(constant_off_time, 2, 15);
  441. // Save the constant off time
  442. this->constant_off_time = constant_off_time;
  443. // Calculate the value acc to the clock cycles
  444. const char blank_value = blank_time >= 54 ? 3 :
  445. blank_time >= 36 ? 2 :
  446. blank_time >= 24 ? 1 : 0;
  447. LIMIT(hysteresis_start, 1, 8);
  448. hysteresis_start--;
  449. LIMIT(hysteresis_start, -3, 12);
  450. // Shift the hysteresis_end
  451. hysteresis_end += 3;
  452. LIMIT(hysteresis_decrement, 0, 3);
  453. //first of all delete all the values for this
  454. 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);
  455. //set the blank timing value
  456. chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
  457. //setting the constant off time
  458. chopper_config_register |= constant_off_time;
  459. //set the hysteresis_start
  460. chopper_config_register |= ((uint32_t)hysteresis_start) << HYSTERESIS_START_VALUE_SHIFT;
  461. //set the hysteresis end
  462. chopper_config_register |= ((uint32_t)hysteresis_end) << HYSTERESIS_LOW_SHIFT;
  463. //set the hystereis decrement
  464. chopper_config_register |= ((uint32_t)blank_value) << BLANK_TIMING_SHIFT;
  465. //if started we directly send it to the motor
  466. if (started) {
  467. //rem send262(driver_control_register_value);
  468. send262(chopper_config_register);
  469. }
  470. }
  471. /**
  472. * In a constant off time chopper scheme both coil choppers run freely, i.e. are not synchronized.
  473. * 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.
  474. * 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
  475. * few microstep positions within each quarter wave. This effect normally is not audible when compared to mechanical noise generated by ball bearings, etc.
  476. * Further factors which can cause a similar effect are a poor layout of sense resistor GND connection.
  477. * Hint: A common factor, which can cause motor noise, is a bad PCB layout causing coupling of both sense resistor voltages
  478. * (please refer to sense resistor layout hint in chapter 8.1).
  479. * In order to minimize the effect of a beat between both chopper frequencies, an internal random generator is provided.
  480. * It modulates the slow decay time setting when switched on by the RNDTF bit. The RNDTF feature further spreads the chopper spectrum,
  481. * reducing electromagnetic emission on single frequencies.
  482. */
  483. void TMC26XStepper::setRandomOffTime(char value) {
  484. if (value)
  485. chopper_config_register |= RANDOM_TOFF_TIME;
  486. else
  487. chopper_config_register &= ~(RANDOM_TOFF_TIME);
  488. //if started we directly send it to the motor
  489. if (started) {
  490. //rem send262(driver_control_register_value);
  491. send262(chopper_config_register);
  492. }
  493. }
  494. void TMC26XStepper::setCoolStepConfiguration(
  495. uint16_t lower_SG_threshold,
  496. uint16_t SG_hysteresis,
  497. uint8_t current_decrement_step_size,
  498. uint8_t current_increment_step_size,
  499. uint8_t lower_current_limit
  500. ) {
  501. // Sanitize the input values
  502. NOMORE(lower_SG_threshold, 480);
  503. // Divide by 32
  504. lower_SG_threshold >>= 5;
  505. NOMORE(SG_hysteresis, 480);
  506. // Divide by 32
  507. SG_hysteresis >>= 5;
  508. NOMORE(current_decrement_step_size, 3);
  509. NOMORE(current_increment_step_size, 3);
  510. NOMORE(lower_current_limit, 1);
  511. // Store the lower level in order to enable/disable the cool step
  512. this->cool_step_lower_threshold=lower_SG_threshold;
  513. // If cool step is not enabled we delete the lower value to keep it disabled
  514. if (!this->cool_step_enabled) lower_SG_threshold = 0;
  515. // The good news is that we can start with a complete new cool step register value
  516. // And simply set the values in the register
  517. cool_step_register_value = ((uint32_t)lower_SG_threshold)
  518. | (((uint32_t)SG_hysteresis) << 8)
  519. | (((uint32_t)current_decrement_step_size) << 5)
  520. | (((uint32_t)current_increment_step_size) << 13)
  521. | (((uint32_t)lower_current_limit) << 15)
  522. | COOL_STEP_REGISTER; // Register signature
  523. if (started) send262(cool_step_register_value);
  524. }
  525. void TMC26XStepper::setCoolStepEnabled(boolean enabled) {
  526. // Simply delete the lower limit to disable the cool step
  527. cool_step_register_value &= ~SE_MIN_PATTERN;
  528. // And set it to the proper value if cool step is to be enabled
  529. if (enabled)
  530. cool_step_register_value |= this->cool_step_lower_threshold;
  531. // And save the enabled status
  532. this->cool_step_enabled = enabled;
  533. // Save the register value
  534. if (started) send262(cool_step_register_value);
  535. }
  536. boolean TMC26XStepper::isCoolStepEnabled() { return this->cool_step_enabled; }
  537. uint16_t TMC26XStepper::getCoolStepLowerSgThreshold() {
  538. // We return our internally stored value - in order to provide the correct setting even if cool step is not enabled
  539. return this->cool_step_lower_threshold<<5;
  540. }
  541. uint16_t TMC26XStepper::getCoolStepUpperSgThreshold() {
  542. return uint8_t((cool_step_register_value & SE_MAX_PATTERN) >> 8) << 5;
  543. }
  544. uint8_t TMC26XStepper::getCoolStepCurrentIncrementSize() {
  545. return uint8_t((cool_step_register_value & CURRENT_DOWN_STEP_SPEED_PATTERN) >> 13);
  546. }
  547. uint8_t TMC26XStepper::getCoolStepNumberOfSGReadings() {
  548. return uint8_t((cool_step_register_value & SE_CURRENT_STEP_WIDTH_PATTERN) >> 5);
  549. }
  550. uint8_t TMC26XStepper::getCoolStepLowerCurrentLimit() {
  551. return uint8_t((cool_step_register_value & MINIMUM_CURRENT_FOURTH) >> 15);
  552. }
  553. void TMC26XStepper::setEnabled(boolean enabled) {
  554. //delete the t_off in the chopper config to get sure
  555. chopper_config_register &= ~(T_OFF_PATTERN);
  556. if (enabled) {
  557. //and set the t_off time
  558. chopper_config_register |= this->constant_off_time;
  559. }
  560. //if not enabled we don't have to do anything since we already delete t_off from the register
  561. if (started) send262(chopper_config_register);
  562. }
  563. boolean TMC26XStepper::isEnabled() { return !!(chopper_config_register & T_OFF_PATTERN); }
  564. /**
  565. * reads a value from the TMC26X status register. The value is not obtained directly but can then
  566. * be read by the various status routines.
  567. *
  568. */
  569. void TMC26XStepper::readStatus(char read_value) {
  570. uint32_t old_driver_configuration_register_value = driver_configuration_register_value;
  571. //reset the readout configuration
  572. driver_configuration_register_value &= ~(READ_SELECTION_PATTERN);
  573. //this now equals TMC26X_READOUT_POSITION - so we just have to check the other two options
  574. if (read_value == TMC26X_READOUT_STALLGUARD)
  575. driver_configuration_register_value |= READ_STALL_GUARD_READING;
  576. else if (read_value == TMC26X_READOUT_CURRENT)
  577. driver_configuration_register_value |= READ_STALL_GUARD_AND_COOL_STEP;
  578. //all other cases are ignored to prevent funny values
  579. //check if the readout is configured for the value we are interested in
  580. if (driver_configuration_register_value != old_driver_configuration_register_value) {
  581. //because then we need to write the value twice - one time for configuring, second time to get the value, see below
  582. send262(driver_configuration_register_value);
  583. }
  584. //write the configuration to get the last status
  585. send262(driver_configuration_register_value);
  586. }
  587. int16_t TMC26XStepper::getMotorPosition() {
  588. //we read it out even if we are not started yet - perhaps it is useful information for somebody
  589. readStatus(TMC26X_READOUT_POSITION);
  590. return getReadoutValue();
  591. }
  592. //reads the StallGuard setting from last status
  593. //returns -1 if StallGuard information is not present
  594. int16_t TMC26XStepper::getCurrentStallGuardReading() {
  595. //if we don't yet started there cannot be a StallGuard value
  596. if (!started) return -1;
  597. //not time optimal, but solution optiomal:
  598. //first read out the StallGuard value
  599. readStatus(TMC26X_READOUT_STALLGUARD);
  600. return getReadoutValue();
  601. }
  602. uint8_t TMC26XStepper::getCurrentCSReading() {
  603. //if we don't yet started there cannot be a StallGuard value
  604. if (!started) return 0;
  605. //not time optimal, but solution optiomal:
  606. //first read out the StallGuard value
  607. readStatus(TMC26X_READOUT_CURRENT);
  608. return (getReadoutValue() & 0x1F);
  609. }
  610. uint16_t TMC26XStepper::getCurrentCurrent() {
  611. float result = (float)getCurrentCSReading(),
  612. resistor_value = (float)this->resistor,
  613. voltage = (driver_configuration_register_value & VSENSE)? 0.165 : 0.31;
  614. result = (result + 1.0) / 32.0 * voltage / resistor_value * sq(1000.0);
  615. return (uint16_t)result;
  616. }
  617. /**
  618. * Return true if the StallGuard threshold has been reached
  619. */
  620. boolean TMC26XStepper::isStallGuardOverThreshold() {
  621. if (!this->started) return false;
  622. return (driver_status_result & STATUS_STALL_GUARD_STATUS);
  623. }
  624. /**
  625. * returns if there is any over temperature condition:
  626. * OVER_TEMPERATURE_PREWARING if pre warning level has been reached
  627. * OVER_TEMPERATURE_SHUTDOWN if the temperature is so hot that the driver is shut down
  628. * Any of those levels are not too good.
  629. */
  630. char TMC26XStepper::getOverTemperature() {
  631. if (!this->started) return 0;
  632. if (driver_status_result & STATUS_OVER_TEMPERATURE_SHUTDOWN)
  633. return TMC26X_OVERTEMPERATURE_SHUTDOWN;
  634. if (driver_status_result & STATUS_OVER_TEMPERATURE_WARNING)
  635. return TMC26X_OVERTEMPERATURE_PREWARING;
  636. return 0;
  637. }
  638. // Is motor channel A shorted to ground
  639. boolean TMC26XStepper::isShortToGroundA() {
  640. if (!this->started) return false;
  641. return (driver_status_result & STATUS_SHORT_TO_GROUND_A);
  642. }
  643. // Is motor channel B shorted to ground
  644. boolean TMC26XStepper::isShortToGroundB() {
  645. if (!this->started) return false;
  646. return (driver_status_result & STATUS_SHORT_TO_GROUND_B);
  647. }
  648. // Is motor channel A connected
  649. boolean TMC26XStepper::isOpenLoadA() {
  650. if (!this->started) return false;
  651. return (driver_status_result & STATUS_OPEN_LOAD_A);
  652. }
  653. // Is motor channel B connected
  654. boolean TMC26XStepper::isOpenLoadB() {
  655. if (!this->started) return false;
  656. return (driver_status_result & STATUS_OPEN_LOAD_B);
  657. }
  658. // Is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
  659. boolean TMC26XStepper::isStandStill() {
  660. if (!this->started) return false;
  661. return (driver_status_result & STATUS_STAND_STILL);
  662. }
  663. //is chopper inactive since 2^20 clock cycles - defaults to ~0,08s
  664. boolean TMC26XStepper::isStallGuardReached() {
  665. if (!this->started) return false;
  666. return (driver_status_result & STATUS_STALL_GUARD_STATUS);
  667. }
  668. //reads the StallGuard setting from last status
  669. //returns -1 if StallGuard information is not present
  670. int16_t TMC26XStepper::getReadoutValue() {
  671. return (int)(driver_status_result >> 10);
  672. }
  673. int16_t TMC26XStepper::getResistor() { return this->resistor; }
  674. boolean TMC26XStepper::isCurrentScalingHalfed() {
  675. return !!(this->driver_configuration_register_value & VSENSE);
  676. }
  677. /**
  678. * version() returns the version of the library:
  679. */
  680. int16_t TMC26XStepper::version() { return 1; }
  681. void TMC26XStepper::debugLastStatus() {
  682. #ifdef TMC_DEBUG1
  683. if (this->started) {
  684. if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_PREWARING)
  685. SERIAL_ECHOLNPGM("\n WARNING: Overtemperature Prewarning!");
  686. else if (this->getOverTemperature()&TMC26X_OVERTEMPERATURE_SHUTDOWN)
  687. SERIAL_ECHOLNPGM("\n ERROR: Overtemperature Shutdown!");
  688. if (this->isShortToGroundA())
  689. SERIAL_ECHOLNPGM("\n ERROR: SHORT to ground on channel A!");
  690. if (this->isShortToGroundB())
  691. SERIAL_ECHOLNPGM("\n ERROR: SHORT to ground on channel B!");
  692. if (this->isOpenLoadA())
  693. SERIAL_ECHOLNPGM("\n ERROR: Channel A seems to be unconnected!");
  694. if (this->isOpenLoadB())
  695. SERIAL_ECHOLNPGM("\n ERROR: Channel B seems to be unconnected!");
  696. if (this->isStallGuardReached())
  697. SERIAL_ECHOLNPGM("\n INFO: Stall Guard level reached!");
  698. if (this->isStandStill())
  699. SERIAL_ECHOLNPGM("\n INFO: Motor is standing still.");
  700. uint32_t readout_config = driver_configuration_register_value & READ_SELECTION_PATTERN;
  701. const int16_t value = getReadoutValue();
  702. if (readout_config == READ_MICROSTEP_POSTION) {
  703. SERIAL_ECHOPAIR("\n Microstep position phase A: ", value);
  704. }
  705. else if (readout_config == READ_STALL_GUARD_READING) {
  706. SERIAL_ECHOPAIR("\n Stall Guard value:", value);
  707. }
  708. else if (readout_config == READ_STALL_GUARD_AND_COOL_STEP) {
  709. SERIAL_ECHOPAIR("\n Approx Stall Guard: ", value & 0xF);
  710. SERIAL_ECHOPAIR("\n Current level", value & 0x1F0);
  711. }
  712. }
  713. #endif
  714. }
  715. /**
  716. * send register settings to the stepper driver via SPI
  717. * returns the current status
  718. */
  719. inline void TMC26XStepper::send262(uint32_t datagram) {
  720. uint32_t i_datagram;
  721. //preserver the previous spi mode
  722. //uint8_t oldMode = SPCR & SPI_MODE_MASK;
  723. //if the mode is not correct set it to mode 3
  724. //if (oldMode != SPI_MODE3) {
  725. // SPI.setDataMode(SPI_MODE3);
  726. //}
  727. //select the TMC driver
  728. extDigitalWrite(cs_pin, LOW);
  729. //ensure that only valid bist are set (0-19)
  730. //datagram &=REGISTER_BIT_PATTERN;
  731. #ifdef TMC_DEBUG1
  732. //SERIAL_PRINTF("Sending ");
  733. //SERIAL_PRINTF("Sending ", datagram,HEX);
  734. //SERIAL_ECHOPAIR("\n\nSending \n", print_hex_long(datagram));
  735. SERIAL_PRINTF("\n\nSending %x", datagram);
  736. #endif
  737. //write/read the values
  738. i_datagram = STEPPER_SPI.transfer((datagram >> 16) & 0xFF);
  739. i_datagram <<= 8;
  740. i_datagram |= STEPPER_SPI.transfer((datagram >> 8) & 0xFF);
  741. i_datagram <<= 8;
  742. i_datagram |= STEPPER_SPI.transfer((datagram) & 0xFF);
  743. i_datagram >>= 4;
  744. #ifdef TMC_DEBUG1
  745. //SERIAL_PRINTF("Received ");
  746. //SERIAL_PRINTF("Received ", i_datagram,HEX);
  747. //SERIAL_ECHOPAIR("\n\nReceived \n", i_datagram);
  748. SERIAL_PRINTF("\n\nReceived %x", i_datagram);
  749. debugLastStatus();
  750. #endif
  751. //deselect the TMC chip
  752. extDigitalWrite(cs_pin, HIGH);
  753. //restore the previous SPI mode if neccessary
  754. //if the mode is not correct set it to mode 3
  755. //if (oldMode != SPI_MODE3) {
  756. // SPI.setDataMode(oldMode);
  757. //}
  758. //store the datagram as status result
  759. driver_status_result = i_datagram;
  760. }
  761. #endif // HAS_DRIVER(TMC2660)
  762. #endif // STM32GENERIC && STM32F7