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

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