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.

planner.cpp 52KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * planner.cpp
  24. *
  25. * Buffer movement commands and manage the acceleration profile plan
  26. *
  27. * Derived from Grbl
  28. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  29. *
  30. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  31. *
  32. *
  33. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  34. *
  35. * s == speed, a == acceleration, t == time, d == distance
  36. *
  37. * Basic definitions:
  38. * Speed[s_, a_, t_] := s + (a*t)
  39. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  40. *
  41. * Distance to reach a specific speed with a constant acceleration:
  42. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  43. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  44. *
  45. * Speed after a given distance of travel with constant acceleration:
  46. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  47. * m -> Sqrt[2 a d + s^2]
  48. *
  49. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  50. *
  51. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  52. * from initial speed s1 without ever stopping at a plateau:
  53. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  54. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  55. *
  56. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  57. *
  58. */
  59. #include "planner.h"
  60. #include "stepper.h"
  61. #include "temperature.h"
  62. #include "ultralcd.h"
  63. #include "language.h"
  64. #include "Marlin.h"
  65. #if ENABLED(MESH_BED_LEVELING)
  66. #include "mesh_bed_leveling.h"
  67. #endif
  68. Planner planner;
  69. // public:
  70. /**
  71. * A ring buffer of moves described in steps
  72. */
  73. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  74. volatile uint8_t Planner::block_buffer_head = 0; // Index of the next block to be pushed
  75. volatile uint8_t Planner::block_buffer_tail = 0;
  76. float Planner::max_feedrate_mm_s[NUM_AXIS], // Max speeds in mm per second
  77. Planner::axis_steps_per_mm[NUM_AXIS],
  78. Planner::steps_to_mm[NUM_AXIS];
  79. uint32_t Planner::max_acceleration_steps_per_s2[NUM_AXIS],
  80. Planner::max_acceleration_mm_per_s2[NUM_AXIS]; // Use M201 to override by software
  81. millis_t Planner::min_segment_time;
  82. float Planner::min_feedrate_mm_s,
  83. Planner::acceleration, // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  84. Planner::retract_acceleration, // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  85. Planner::travel_acceleration, // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  86. Planner::max_jerk[XYZE], // The largest speed change requiring no acceleration
  87. Planner::min_travel_feedrate_mm_s;
  88. #if HAS_ABL
  89. bool Planner::abl_enabled = false; // Flag that auto bed leveling is enabled
  90. #endif
  91. #if ABL_PLANAR
  92. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  93. #endif
  94. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  95. float Planner::z_fade_height = 0.0,
  96. Planner::inverse_z_fade_height = 0.0;
  97. #endif
  98. #if ENABLED(AUTOTEMP)
  99. float Planner::autotemp_max = 250,
  100. Planner::autotemp_min = 210,
  101. Planner::autotemp_factor = 0.1;
  102. bool Planner::autotemp_enabled = false;
  103. #endif
  104. // private:
  105. long Planner::position[NUM_AXIS] = { 0 };
  106. uint32_t Planner::cutoff_long;
  107. float Planner::previous_speed[NUM_AXIS],
  108. Planner::previous_nominal_speed;
  109. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  110. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  111. #endif // DISABLE_INACTIVE_EXTRUDER
  112. #ifdef XY_FREQUENCY_LIMIT
  113. // Old direction bits. Used for speed calculations
  114. unsigned char Planner::old_direction_bits = 0;
  115. // Segment times (in µs). Used for speed calculations
  116. long Planner::axis_segment_time[2][3] = { {MAX_FREQ_TIME + 1, 0, 0}, {MAX_FREQ_TIME + 1, 0, 0} };
  117. #endif
  118. #if ENABLED(LIN_ADVANCE)
  119. float Planner::extruder_advance_k = LIN_ADVANCE_K;
  120. float Planner::position_float[NUM_AXIS] = { 0 };
  121. #endif
  122. #if ENABLED(ENSURE_SMOOTH_MOVES)
  123. uint32_t Planner::block_buffer_runtime_us = 0;
  124. #endif
  125. /**
  126. * Class and Instance Methods
  127. */
  128. Planner::Planner() { init(); }
  129. void Planner::init() {
  130. block_buffer_head = block_buffer_tail = 0;
  131. ZERO(position);
  132. #if ENABLED(LIN_ADVANCE)
  133. ZERO(position_float);
  134. #endif
  135. ZERO(previous_speed);
  136. previous_nominal_speed = 0.0;
  137. #if ABL_PLANAR
  138. bed_level_matrix.set_to_identity();
  139. #endif
  140. }
  141. #define MINIMAL_STEP_RATE 120
  142. /**
  143. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  144. * by the provided factors.
  145. */
  146. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  147. uint32_t initial_rate = ceil(block->nominal_rate * entry_factor),
  148. final_rate = ceil(block->nominal_rate * exit_factor); // (steps per second)
  149. // Limit minimal step rate (Otherwise the timer will overflow.)
  150. NOLESS(initial_rate, MINIMAL_STEP_RATE);
  151. NOLESS(final_rate, MINIMAL_STEP_RATE);
  152. int32_t accel = block->acceleration_steps_per_s2,
  153. accelerate_steps = ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  154. decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel)),
  155. plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  156. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  157. // have to use intersection_distance() to calculate when to abort accel and start braking
  158. // in order to reach the final_rate exactly at the end of this block.
  159. if (plateau_steps < 0) {
  160. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  161. NOLESS(accelerate_steps, 0); // Check limits due to numerical round-off
  162. accelerate_steps = min((uint32_t)accelerate_steps, block->step_event_count);//(We can cast here to unsigned, because the above line ensures that we are above zero)
  163. plateau_steps = 0;
  164. }
  165. // block->accelerate_until = accelerate_steps;
  166. // block->decelerate_after = accelerate_steps+plateau_steps;
  167. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  168. if (!TEST(block->flag, BLOCK_BIT_BUSY)) { // Don't update variables if block is busy.
  169. block->accelerate_until = accelerate_steps;
  170. block->decelerate_after = accelerate_steps + plateau_steps;
  171. block->initial_rate = initial_rate;
  172. block->final_rate = final_rate;
  173. #if ENABLED(ADVANCE)
  174. block->initial_advance = block->advance * sq(entry_factor);
  175. block->final_advance = block->advance * sq(exit_factor);
  176. #endif
  177. }
  178. CRITICAL_SECTION_END;
  179. }
  180. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  181. // This method will calculate the junction jerk as the euclidean distance between the nominal
  182. // velocities of the respective blocks.
  183. //inline float junction_jerk(block_t *before, block_t *after) {
  184. // return sqrt(
  185. // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
  186. //}
  187. // The kernel called by recalculate() when scanning the plan from last to first entry.
  188. void Planner::reverse_pass_kernel(block_t* const current, const block_t *next) {
  189. if (!current || !next) return;
  190. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  191. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  192. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  193. float max_entry_speed = current->max_entry_speed;
  194. if (current->entry_speed != max_entry_speed) {
  195. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  196. // for max allowable speed if block is decelerating and nominal length is false.
  197. current->entry_speed = (TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH) || max_entry_speed <= next->entry_speed)
  198. ? max_entry_speed
  199. : min(max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  200. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  201. }
  202. }
  203. /**
  204. * recalculate() needs to go over the current plan twice.
  205. * Once in reverse and once forward. This implements the reverse pass.
  206. */
  207. void Planner::reverse_pass() {
  208. if (movesplanned() > 3) {
  209. block_t* block[3] = { NULL, NULL, NULL };
  210. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  211. // Is a critical section REALLY needed for a single byte change?
  212. //CRITICAL_SECTION_START;
  213. uint8_t tail = block_buffer_tail;
  214. //CRITICAL_SECTION_END
  215. uint8_t b = BLOCK_MOD(block_buffer_head - 3);
  216. while (b != tail) {
  217. if (block[0] && TEST(block[0]->flag, BLOCK_BIT_START_FROM_FULL_HALT)) break;
  218. b = prev_block_index(b);
  219. block[2] = block[1];
  220. block[1] = block[0];
  221. block[0] = &block_buffer[b];
  222. reverse_pass_kernel(block[1], block[2]);
  223. }
  224. }
  225. }
  226. // The kernel called by recalculate() when scanning the plan from first to last entry.
  227. void Planner::forward_pass_kernel(const block_t* previous, block_t* const current) {
  228. if (!previous) return;
  229. // If the previous block is an acceleration block, but it is not long enough to complete the
  230. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  231. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  232. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  233. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH)) {
  234. if (previous->entry_speed < current->entry_speed) {
  235. float entry_speed = min(current->entry_speed,
  236. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  237. // Check for junction speed change
  238. if (current->entry_speed != entry_speed) {
  239. current->entry_speed = entry_speed;
  240. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  241. }
  242. }
  243. }
  244. }
  245. /**
  246. * recalculate() needs to go over the current plan twice.
  247. * Once in reverse and once forward. This implements the forward pass.
  248. */
  249. void Planner::forward_pass() {
  250. block_t* block[3] = { NULL, NULL, NULL };
  251. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  252. block[0] = block[1];
  253. block[1] = block[2];
  254. block[2] = &block_buffer[b];
  255. forward_pass_kernel(block[0], block[1]);
  256. }
  257. forward_pass_kernel(block[1], block[2]);
  258. }
  259. /**
  260. * Recalculate the trapezoid speed profiles for all blocks in the plan
  261. * according to the entry_factor for each junction. Must be called by
  262. * recalculate() after updating the blocks.
  263. */
  264. void Planner::recalculate_trapezoids() {
  265. int8_t block_index = block_buffer_tail;
  266. block_t *current, *next = NULL;
  267. while (block_index != block_buffer_head) {
  268. current = next;
  269. next = &block_buffer[block_index];
  270. if (current) {
  271. // Recalculate if current block entry or exit junction speed has changed.
  272. if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  273. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  274. float nom = current->nominal_speed;
  275. calculate_trapezoid_for_block(current, current->entry_speed / nom, next->entry_speed / nom);
  276. CBI(current->flag, BLOCK_BIT_RECALCULATE); // Reset current only to ensure next trapezoid is computed
  277. }
  278. }
  279. block_index = next_block_index(block_index);
  280. }
  281. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  282. if (next) {
  283. float nom = next->nominal_speed;
  284. calculate_trapezoid_for_block(next, next->entry_speed / nom, (MINIMUM_PLANNER_SPEED) / nom);
  285. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  286. }
  287. }
  288. /*
  289. * Recalculate the motion plan according to the following algorithm:
  290. *
  291. * 1. Go over every block in reverse order...
  292. *
  293. * Calculate a junction speed reduction (block_t.entry_factor) so:
  294. *
  295. * a. The junction jerk is within the set limit, and
  296. *
  297. * b. No speed reduction within one block requires faster
  298. * deceleration than the one, true constant acceleration.
  299. *
  300. * 2. Go over every block in chronological order...
  301. *
  302. * Dial down junction speed reduction values if:
  303. * a. The speed increase within one block would require faster
  304. * acceleration than the one, true constant acceleration.
  305. *
  306. * After that, all blocks will have an entry_factor allowing all speed changes to
  307. * be performed using only the one, true constant acceleration, and where no junction
  308. * jerk is jerkier than the set limit, Jerky. Finally it will:
  309. *
  310. * 3. Recalculate "trapezoids" for all blocks.
  311. */
  312. void Planner::recalculate() {
  313. reverse_pass();
  314. forward_pass();
  315. recalculate_trapezoids();
  316. }
  317. #if ENABLED(AUTOTEMP)
  318. void Planner::getHighESpeed() {
  319. static float oldt = 0;
  320. if (!autotemp_enabled) return;
  321. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  322. float high = 0.0;
  323. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  324. block_t* block = &block_buffer[b];
  325. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  326. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  327. NOLESS(high, se);
  328. }
  329. }
  330. float t = autotemp_min + high * autotemp_factor;
  331. t = constrain(t, autotemp_min, autotemp_max);
  332. if (oldt > t) {
  333. t *= (1 - (AUTOTEMP_OLDWEIGHT));
  334. t += (AUTOTEMP_OLDWEIGHT) * oldt;
  335. }
  336. oldt = t;
  337. thermalManager.setTargetHotend(t, 0);
  338. }
  339. #endif //AUTOTEMP
  340. /**
  341. * Maintain fans, paste extruder pressure,
  342. */
  343. void Planner::check_axes_activity() {
  344. unsigned char axis_active[NUM_AXIS] = { 0 },
  345. tail_fan_speed[FAN_COUNT];
  346. #if FAN_COUNT > 0
  347. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  348. #endif
  349. #if ENABLED(BARICUDA)
  350. #if HAS_HEATER_1
  351. unsigned char tail_valve_pressure = baricuda_valve_pressure;
  352. #endif
  353. #if HAS_HEATER_2
  354. unsigned char tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  355. #endif
  356. #endif
  357. if (blocks_queued()) {
  358. #if FAN_COUNT > 0
  359. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  360. #endif
  361. block_t* block;
  362. #if ENABLED(BARICUDA)
  363. block = &block_buffer[block_buffer_tail];
  364. #if HAS_HEATER_1
  365. tail_valve_pressure = block->valve_pressure;
  366. #endif
  367. #if HAS_HEATER_2
  368. tail_e_to_p_pressure = block->e_to_p_pressure;
  369. #endif
  370. #endif
  371. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  372. block = &block_buffer[b];
  373. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  374. }
  375. }
  376. #if ENABLED(DISABLE_X)
  377. if (!axis_active[X_AXIS]) disable_x();
  378. #endif
  379. #if ENABLED(DISABLE_Y)
  380. if (!axis_active[Y_AXIS]) disable_y();
  381. #endif
  382. #if ENABLED(DISABLE_Z)
  383. if (!axis_active[Z_AXIS]) disable_z();
  384. #endif
  385. #if ENABLED(DISABLE_E)
  386. if (!axis_active[E_AXIS]) {
  387. disable_e0();
  388. disable_e1();
  389. disable_e2();
  390. disable_e3();
  391. }
  392. #endif
  393. #if FAN_COUNT > 0
  394. #if defined(FAN_MIN_PWM)
  395. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  396. #else
  397. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  398. #endif
  399. #ifdef FAN_KICKSTART_TIME
  400. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  401. #define KICKSTART_FAN(f) \
  402. if (tail_fan_speed[f]) { \
  403. millis_t ms = millis(); \
  404. if (fan_kick_end[f] == 0) { \
  405. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  406. tail_fan_speed[f] = 255; \
  407. } else { \
  408. if (PENDING(ms, fan_kick_end[f])) { \
  409. tail_fan_speed[f] = 255; \
  410. } \
  411. } \
  412. } else { \
  413. fan_kick_end[f] = 0; \
  414. }
  415. #if HAS_FAN0
  416. KICKSTART_FAN(0);
  417. #endif
  418. #if HAS_FAN1
  419. KICKSTART_FAN(1);
  420. #endif
  421. #if HAS_FAN2
  422. KICKSTART_FAN(2);
  423. #endif
  424. #endif //FAN_KICKSTART_TIME
  425. #if ENABLED(FAN_SOFT_PWM)
  426. #if HAS_FAN0
  427. thermalManager.fanSpeedSoftPwm[0] = CALC_FAN_SPEED(0);
  428. #endif
  429. #if HAS_FAN1
  430. thermalManager.fanSpeedSoftPwm[1] = CALC_FAN_SPEED(1);
  431. #endif
  432. #if HAS_FAN2
  433. thermalManager.fanSpeedSoftPwm[2] = CALC_FAN_SPEED(2);
  434. #endif
  435. #else
  436. #if HAS_FAN0
  437. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  438. #endif
  439. #if HAS_FAN1
  440. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  441. #endif
  442. #if HAS_FAN2
  443. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  444. #endif
  445. #endif
  446. #endif // FAN_COUNT > 0
  447. #if ENABLED(AUTOTEMP)
  448. getHighESpeed();
  449. #endif
  450. #if ENABLED(BARICUDA)
  451. #if HAS_HEATER_1
  452. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  453. #endif
  454. #if HAS_HEATER_2
  455. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  456. #endif
  457. #endif
  458. }
  459. #if PLANNER_LEVELING
  460. /**
  461. * lx, ly, lz - logical (cartesian, not delta) positions in mm
  462. */
  463. void Planner::apply_leveling(float &lx, float &ly, float &lz) {
  464. #if HAS_ABL
  465. if (!abl_enabled) return;
  466. #endif
  467. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  468. static float z_fade_factor = 1.0, last_raw_lz = -999.0;
  469. if (z_fade_height) {
  470. const float raw_lz = RAW_Z_POSITION(lz);
  471. if (raw_lz >= z_fade_height) return;
  472. if (last_raw_lz != raw_lz) {
  473. last_raw_lz = raw_lz;
  474. z_fade_factor = 1.0 - raw_lz * inverse_z_fade_height;
  475. }
  476. }
  477. else
  478. z_fade_factor = 1.0;
  479. #else
  480. constexpr float z_fade_factor = 1.0;
  481. #endif
  482. #if ENABLED(MESH_BED_LEVELING)
  483. if (mbl.active())
  484. lz += mbl.get_z(RAW_X_POSITION(lx), RAW_Y_POSITION(ly), z_fade_factor);
  485. #elif ABL_PLANAR
  486. float dx = RAW_X_POSITION(lx) - (X_TILT_FULCRUM),
  487. dy = RAW_Y_POSITION(ly) - (Y_TILT_FULCRUM),
  488. dz = RAW_Z_POSITION(lz);
  489. apply_rotation_xyz(bed_level_matrix, dx, dy, dz);
  490. lx = LOGICAL_X_POSITION(dx + X_TILT_FULCRUM);
  491. ly = LOGICAL_Y_POSITION(dy + Y_TILT_FULCRUM);
  492. lz = LOGICAL_Z_POSITION(dz);
  493. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  494. float tmp[XYZ] = { lx, ly, 0 };
  495. lz += bilinear_z_offset(tmp) * z_fade_factor;
  496. #endif
  497. }
  498. void Planner::unapply_leveling(float logical[XYZ]) {
  499. #if HAS_ABL
  500. if (!abl_enabled) return;
  501. #endif
  502. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  503. if (z_fade_height && RAW_Z_POSITION(logical[Z_AXIS]) >= z_fade_height) return;
  504. #endif
  505. #if ENABLED(MESH_BED_LEVELING)
  506. if (mbl.active()) {
  507. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  508. const float c = mbl.get_z(RAW_X_POSITION(logical[X_AXIS]), RAW_Y_POSITION(logical[Y_AXIS]), 1.0);
  509. logical[Z_AXIS] = (z_fade_height * (RAW_Z_POSITION(logical[Z_AXIS]) - c)) / (z_fade_height - c);
  510. #else
  511. logical[Z_AXIS] -= mbl.get_z(RAW_X_POSITION(logical[X_AXIS]), RAW_Y_POSITION(logical[Y_AXIS]));
  512. #endif
  513. }
  514. #elif ABL_PLANAR
  515. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  516. float dx = RAW_X_POSITION(logical[X_AXIS]) - (X_TILT_FULCRUM),
  517. dy = RAW_Y_POSITION(logical[Y_AXIS]) - (Y_TILT_FULCRUM),
  518. dz = RAW_Z_POSITION(logical[Z_AXIS]);
  519. apply_rotation_xyz(inverse, dx, dy, dz);
  520. logical[X_AXIS] = LOGICAL_X_POSITION(dx + X_TILT_FULCRUM);
  521. logical[Y_AXIS] = LOGICAL_Y_POSITION(dy + Y_TILT_FULCRUM);
  522. logical[Z_AXIS] = LOGICAL_Z_POSITION(dz);
  523. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  524. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  525. const float c = bilinear_z_offset(logical);
  526. logical[Z_AXIS] = (z_fade_height * (RAW_Z_POSITION(logical[Z_AXIS]) - c)) / (z_fade_height - c);
  527. #else
  528. logical[Z_AXIS] -= bilinear_z_offset(logical);
  529. #endif
  530. #endif
  531. }
  532. #endif // PLANNER_LEVELING
  533. /**
  534. * Planner::_buffer_line
  535. *
  536. * Add a new linear movement to the buffer.
  537. *
  538. * Leveling and kinematics should be applied ahead of calling this.
  539. *
  540. * a,b,c,e - target positions in mm or degrees
  541. * fr_mm_s - (target) speed of the move
  542. * extruder - target extruder
  543. */
  544. void Planner::_buffer_line(const float &a, const float &b, const float &c, const float &e, float fr_mm_s, const uint8_t extruder) {
  545. // The target position of the tool in absolute steps
  546. // Calculate target position in absolute steps
  547. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  548. long target[XYZE] = {
  549. lround(a * axis_steps_per_mm[X_AXIS]),
  550. lround(b * axis_steps_per_mm[Y_AXIS]),
  551. lround(c * axis_steps_per_mm[Z_AXIS]),
  552. lround(e * axis_steps_per_mm[E_AXIS])
  553. };
  554. #if ENABLED(LIN_ADVANCE)
  555. float target_float[XYZE] = {a, b, c, e};
  556. float de_float = target_float[E_AXIS] - position_float[E_AXIS];
  557. float mm_D_float = sqrt(sq(target_float[X_AXIS] - position_float[X_AXIS]) + sq(target_float[Y_AXIS] - position_float[Y_AXIS]));
  558. memcpy(position_float, target_float, sizeof(position_float));
  559. #endif
  560. long da = target[X_AXIS] - position[X_AXIS],
  561. db = target[Y_AXIS] - position[Y_AXIS],
  562. dc = target[Z_AXIS] - position[Z_AXIS];
  563. /*
  564. SERIAL_ECHOPAIR(" Planner FR:", fr_mm_s);
  565. SERIAL_CHAR(' ');
  566. #if IS_KINEMATIC
  567. SERIAL_ECHOPAIR("A:", a);
  568. SERIAL_ECHOPAIR(" (", da);
  569. SERIAL_ECHOPAIR(") B:", b);
  570. #else
  571. SERIAL_ECHOPAIR("X:", a);
  572. SERIAL_ECHOPAIR(" (", da);
  573. SERIAL_ECHOPAIR(") Y:", b);
  574. #endif
  575. SERIAL_ECHOPAIR(" (", db);
  576. #if ENABLED(DELTA)
  577. SERIAL_ECHOPAIR(") C:", c);
  578. #else
  579. SERIAL_ECHOPAIR(") Z:", c);
  580. #endif
  581. SERIAL_ECHOPAIR(" (", dc);
  582. SERIAL_CHAR(')');
  583. SERIAL_EOL;
  584. //*/
  585. // DRYRUN ignores all temperature constraints and assures that the extruder is instantly satisfied
  586. if (DEBUGGING(DRYRUN)) position[E_AXIS] = target[E_AXIS];
  587. long de = target[E_AXIS] - position[E_AXIS];
  588. #if ENABLED(PREVENT_COLD_EXTRUSION)
  589. if (de) {
  590. if (thermalManager.tooColdToExtrude(extruder)) {
  591. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  592. de = 0; // no difference
  593. SERIAL_ECHO_START;
  594. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  595. }
  596. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  597. if (labs(de) > (int32_t)axis_steps_per_mm[E_AXIS] * (EXTRUDE_MAXLENGTH)) { // It's not important to get max. extrusion length in a precision < 1mm, so save some cycles and cast to int
  598. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  599. de = 0; // no difference
  600. SERIAL_ECHO_START;
  601. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  602. }
  603. #endif
  604. }
  605. #endif
  606. // Compute direction bit-mask for this block
  607. uint8_t dm = 0;
  608. #if CORE_IS_XY
  609. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  610. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  611. if (dc < 0) SBI(dm, Z_AXIS);
  612. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  613. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  614. #elif CORE_IS_XZ
  615. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  616. if (db < 0) SBI(dm, Y_AXIS);
  617. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  618. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  619. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  620. #elif CORE_IS_YZ
  621. if (da < 0) SBI(dm, X_AXIS);
  622. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  623. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  624. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  625. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  626. #else
  627. if (da < 0) SBI(dm, X_AXIS);
  628. if (db < 0) SBI(dm, Y_AXIS);
  629. if (dc < 0) SBI(dm, Z_AXIS);
  630. #endif
  631. if (de < 0) SBI(dm, E_AXIS);
  632. float esteps_float = de * volumetric_multiplier[extruder] * flow_percentage[extruder] * 0.01;
  633. int32_t esteps = abs(esteps_float) + 0.5;
  634. // Calculate the buffer head after we push this byte
  635. int8_t next_buffer_head = next_block_index(block_buffer_head);
  636. // If the buffer is full: good! That means we are well ahead of the robot.
  637. // Rest here until there is room in the buffer.
  638. while (block_buffer_tail == next_buffer_head) idle();
  639. // Prepare to set up new block
  640. block_t* block = &block_buffer[block_buffer_head];
  641. // Clear all flags, including the "busy" bit
  642. block->flag = 0;
  643. // Set direction bits
  644. block->direction_bits = dm;
  645. // Number of steps for each axis
  646. // See http://www.corexy.com/theory.html
  647. #if CORE_IS_XY
  648. block->steps[A_AXIS] = labs(da + db);
  649. block->steps[B_AXIS] = labs(da - db);
  650. block->steps[Z_AXIS] = labs(dc);
  651. #elif CORE_IS_XZ
  652. block->steps[A_AXIS] = labs(da + dc);
  653. block->steps[Y_AXIS] = labs(db);
  654. block->steps[C_AXIS] = labs(da - dc);
  655. #elif CORE_IS_YZ
  656. block->steps[X_AXIS] = labs(da);
  657. block->steps[B_AXIS] = labs(db + dc);
  658. block->steps[C_AXIS] = labs(db - dc);
  659. #else
  660. // default non-h-bot planning
  661. block->steps[X_AXIS] = labs(da);
  662. block->steps[Y_AXIS] = labs(db);
  663. block->steps[Z_AXIS] = labs(dc);
  664. #endif
  665. block->steps[E_AXIS] = esteps;
  666. block->step_event_count = MAX4(block->steps[X_AXIS], block->steps[Y_AXIS], block->steps[Z_AXIS], esteps);
  667. // Bail if this is a zero-length block
  668. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return;
  669. // For a mixing extruder, get a magnified step_event_count for each
  670. #if ENABLED(MIXING_EXTRUDER)
  671. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  672. block->mix_event_count[i] = mixing_factor[i] * block->step_event_count;
  673. #endif
  674. #if FAN_COUNT > 0
  675. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  676. #endif
  677. #if ENABLED(BARICUDA)
  678. block->valve_pressure = baricuda_valve_pressure;
  679. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  680. #endif
  681. block->active_extruder = extruder;
  682. //enable active axes
  683. #if CORE_IS_XY
  684. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  685. enable_x();
  686. enable_y();
  687. }
  688. #if DISABLED(Z_LATE_ENABLE)
  689. if (block->steps[Z_AXIS]) enable_z();
  690. #endif
  691. #elif CORE_IS_XZ
  692. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  693. enable_x();
  694. enable_z();
  695. }
  696. if (block->steps[Y_AXIS]) enable_y();
  697. #elif CORE_IS_YZ
  698. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  699. enable_y();
  700. enable_z();
  701. }
  702. if (block->steps[X_AXIS]) enable_x();
  703. #else
  704. if (block->steps[X_AXIS]) enable_x();
  705. if (block->steps[Y_AXIS]) enable_y();
  706. #if DISABLED(Z_LATE_ENABLE)
  707. if (block->steps[Z_AXIS]) enable_z();
  708. #endif
  709. #endif
  710. // Enable extruder(s)
  711. if (esteps) {
  712. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  713. for (int8_t i = 0; i < EXTRUDERS; i++)
  714. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  715. switch(extruder) {
  716. case 0:
  717. enable_e0();
  718. #if ENABLED(DUAL_X_CARRIAGE)
  719. if (extruder_duplication_enabled) {
  720. enable_e1();
  721. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  722. }
  723. #endif
  724. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  725. #if EXTRUDERS > 1
  726. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  727. #if EXTRUDERS > 2
  728. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  729. #if EXTRUDERS > 3
  730. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  731. #endif
  732. #endif
  733. #endif
  734. break;
  735. #if EXTRUDERS > 1
  736. case 1:
  737. enable_e1();
  738. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  739. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  740. #if EXTRUDERS > 2
  741. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  742. #if EXTRUDERS > 3
  743. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  744. #endif
  745. #endif
  746. break;
  747. #if EXTRUDERS > 2
  748. case 2:
  749. enable_e2();
  750. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  751. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  752. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  753. #if EXTRUDERS > 3
  754. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  755. #endif
  756. break;
  757. #if EXTRUDERS > 3
  758. case 3:
  759. enable_e3();
  760. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  761. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  762. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  763. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  764. break;
  765. #endif // EXTRUDERS > 3
  766. #endif // EXTRUDERS > 2
  767. #endif // EXTRUDERS > 1
  768. }
  769. #else
  770. enable_e0();
  771. enable_e1();
  772. enable_e2();
  773. enable_e3();
  774. #endif
  775. }
  776. if (esteps)
  777. NOLESS(fr_mm_s, min_feedrate_mm_s);
  778. else
  779. NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
  780. /**
  781. * This part of the code calculates the total length of the movement.
  782. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  783. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  784. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  785. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  786. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  787. */
  788. #if IS_CORE
  789. float delta_mm[7];
  790. #if CORE_IS_XY
  791. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  792. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  793. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  794. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  795. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  796. #elif CORE_IS_XZ
  797. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  798. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  799. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  800. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  801. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  802. #elif CORE_IS_YZ
  803. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  804. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  805. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  806. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  807. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  808. #endif
  809. #else
  810. float delta_mm[4];
  811. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  812. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  813. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  814. #endif
  815. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS];
  816. if (block->steps[X_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[Y_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[Z_AXIS] < MIN_STEPS_PER_SEGMENT) {
  817. block->millimeters = fabs(delta_mm[E_AXIS]);
  818. }
  819. else {
  820. block->millimeters = sqrt(
  821. #if CORE_IS_XY
  822. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  823. #elif CORE_IS_XZ
  824. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  825. #elif CORE_IS_YZ
  826. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  827. #else
  828. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  829. #endif
  830. );
  831. }
  832. float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  833. // Calculate moves/second for this move. No divide by zero due to previous checks.
  834. float inverse_mm_s = fr_mm_s * inverse_millimeters;
  835. int moves_queued = movesplanned();
  836. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  837. #if ENABLED(SLOWDOWN)
  838. // Segment time im micro seconds
  839. unsigned long segment_time = lround(1000000.0 / inverse_mm_s);
  840. if (moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE) / 2) {
  841. if (segment_time < min_segment_time) {
  842. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  843. inverse_mm_s = 1000000.0 / (segment_time + lround(2 * (min_segment_time - segment_time) / moves_queued));
  844. #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ENSURE_SMOOTH_MOVES)
  845. segment_time = lround(1000000.0 / inverse_mm_s);
  846. #endif
  847. }
  848. }
  849. #endif
  850. #if ENABLED(ENSURE_SMOOTH_MOVES)
  851. #if DISABLED(SLOWDOWN)
  852. unsigned long segment_time = lround(1000000.0 / inverse_mm_s);
  853. #endif
  854. if (segment_time < (MIN_BLOCK_TIME) * 1000UL) {
  855. // buffer will be draining, set to MIN_BLOCK_TIME.
  856. inverse_mm_s = 1000000.0 / (1000.0 * (MIN_BLOCK_TIME));
  857. segment_time = (MIN_BLOCK_TIME) * 1000UL;
  858. }
  859. block->segment_time = segment_time;
  860. block_buffer_runtime_us += segment_time;
  861. #endif
  862. block->nominal_speed = block->millimeters * inverse_mm_s; // (mm/sec) Always > 0
  863. block->nominal_rate = ceil(block->step_event_count * inverse_mm_s); // (step/sec) Always > 0
  864. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  865. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  866. //FMM update ring buffer used for delay with filament measurements
  867. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  868. const int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  869. // increment counters with next move in e axis
  870. filwidth_e_count += delta_mm[E_AXIS];
  871. filwidth_delay_dist += delta_mm[E_AXIS];
  872. // Only get new measurements on forward E movement
  873. if (filwidth_e_count > 0.0001) {
  874. // Loop the delay distance counter (modulus by the mm length)
  875. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  876. // Convert into an index into the measurement array
  877. filwidth_delay_index[0] = (int)(filwidth_delay_dist * 0.1 + 0.0001);
  878. // If the index has changed (must have gone forward)...
  879. if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
  880. filwidth_e_count = 0; // Reset the E movement counter
  881. int8_t meas_sample = thermalManager.widthFil_to_size_ratio() - 100; // Subtract 100 to reduce magnitude - to store in a signed char
  882. do {
  883. filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
  884. measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
  885. } while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
  886. }
  887. }
  888. }
  889. #endif
  890. // Calculate and limit speed in mm/sec for each axis
  891. float current_speed[NUM_AXIS], speed_factor = 1.0; // factor <1 decreases speed
  892. LOOP_XYZE(i) {
  893. float cs = fabs(current_speed[i] = delta_mm[i] * inverse_mm_s);
  894. if (cs > max_feedrate_mm_s[i]) NOMORE(speed_factor, max_feedrate_mm_s[i] / cs);
  895. }
  896. // Max segment time in µs.
  897. #ifdef XY_FREQUENCY_LIMIT
  898. // Check and limit the xy direction change frequency
  899. unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  900. old_direction_bits = block->direction_bits;
  901. segment_time = lround((float)segment_time / speed_factor);
  902. long xs0 = axis_segment_time[X_AXIS][0],
  903. xs1 = axis_segment_time[X_AXIS][1],
  904. xs2 = axis_segment_time[X_AXIS][2],
  905. ys0 = axis_segment_time[Y_AXIS][0],
  906. ys1 = axis_segment_time[Y_AXIS][1],
  907. ys2 = axis_segment_time[Y_AXIS][2];
  908. if (TEST(direction_change, X_AXIS)) {
  909. xs2 = axis_segment_time[X_AXIS][2] = xs1;
  910. xs1 = axis_segment_time[X_AXIS][1] = xs0;
  911. xs0 = 0;
  912. }
  913. xs0 = axis_segment_time[X_AXIS][0] = xs0 + segment_time;
  914. if (TEST(direction_change, Y_AXIS)) {
  915. ys2 = axis_segment_time[Y_AXIS][2] = axis_segment_time[Y_AXIS][1];
  916. ys1 = axis_segment_time[Y_AXIS][1] = axis_segment_time[Y_AXIS][0];
  917. ys0 = 0;
  918. }
  919. ys0 = axis_segment_time[Y_AXIS][0] = ys0 + segment_time;
  920. long max_x_segment_time = MAX3(xs0, xs1, xs2),
  921. max_y_segment_time = MAX3(ys0, ys1, ys2),
  922. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  923. if (min_xy_segment_time < MAX_FREQ_TIME) {
  924. float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME);
  925. NOMORE(speed_factor, low_sf);
  926. }
  927. #endif // XY_FREQUENCY_LIMIT
  928. // Correct the speed
  929. if (speed_factor < 1.0) {
  930. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  931. block->nominal_speed *= speed_factor;
  932. block->nominal_rate *= speed_factor;
  933. }
  934. // Compute and limit the acceleration rate for the trapezoid generator.
  935. float steps_per_mm = block->step_event_count * inverse_millimeters;
  936. uint32_t accel;
  937. if (!block->steps[X_AXIS] && !block->steps[Y_AXIS] && !block->steps[Z_AXIS]) {
  938. // convert to: acceleration steps/sec^2
  939. accel = ceil(retract_acceleration * steps_per_mm);
  940. }
  941. else {
  942. #define LIMIT_ACCEL_LONG(AXIS) do{ \
  943. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS] < accel) { \
  944. const uint32_t comp = max_acceleration_steps_per_s2[AXIS] * block->step_event_count; \
  945. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  946. } \
  947. }while(0)
  948. #define LIMIT_ACCEL_FLOAT(AXIS) do{ \
  949. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS] < accel) { \
  950. const float comp = (float)max_acceleration_steps_per_s2[AXIS] * (float)block->step_event_count; \
  951. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  952. } \
  953. }while(0)
  954. // Start with print or travel acceleration
  955. accel = ceil((esteps ? acceleration : travel_acceleration) * steps_per_mm);
  956. // Limit acceleration per axis
  957. if (block->step_event_count <= cutoff_long){
  958. LIMIT_ACCEL_LONG(X_AXIS);
  959. LIMIT_ACCEL_LONG(Y_AXIS);
  960. LIMIT_ACCEL_LONG(Z_AXIS);
  961. LIMIT_ACCEL_LONG(E_AXIS);
  962. } else {
  963. LIMIT_ACCEL_FLOAT(X_AXIS);
  964. LIMIT_ACCEL_FLOAT(Y_AXIS);
  965. LIMIT_ACCEL_FLOAT(Z_AXIS);
  966. LIMIT_ACCEL_FLOAT(E_AXIS);
  967. }
  968. }
  969. block->acceleration_steps_per_s2 = accel;
  970. block->acceleration = accel / steps_per_mm;
  971. block->acceleration_rate = (long)(accel * 16777216.0 / ((F_CPU) * 0.125)); // * 8.388608
  972. // Initial limit on the segment entry velocity
  973. float vmax_junction;
  974. #if 0 // Use old jerk for now
  975. float junction_deviation = 0.1;
  976. // Compute path unit vector
  977. double unit_vec[XYZ] = {
  978. delta_mm[X_AXIS] * inverse_millimeters,
  979. delta_mm[Y_AXIS] * inverse_millimeters,
  980. delta_mm[Z_AXIS] * inverse_millimeters
  981. };
  982. /*
  983. Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  984. Let a circle be tangent to both previous and current path line segments, where the junction
  985. deviation is defined as the distance from the junction to the closest edge of the circle,
  986. collinear with the circle center.
  987. The circular segment joining the two paths represents the path of centripetal acceleration.
  988. Solve for max velocity based on max acceleration about the radius of the circle, defined
  989. indirectly by junction deviation.
  990. This may be also viewed as path width or max_jerk in the previous grbl version. This approach
  991. does not actually deviate from path, but used as a robust way to compute cornering speeds, as
  992. it takes into account the nonlinearities of both the junction angle and junction velocity.
  993. */
  994. vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  995. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  996. if (block_buffer_head != block_buffer_tail && previous_nominal_speed > 0.0) {
  997. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  998. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  999. float cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  1000. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  1001. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  1002. // Skip and use default max junction speed for 0 degree acute junction.
  1003. if (cos_theta < 0.95) {
  1004. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  1005. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  1006. if (cos_theta > -0.95) {
  1007. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  1008. float sin_theta_d2 = sqrt(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  1009. NOMORE(vmax_junction, sqrt(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  1010. }
  1011. }
  1012. }
  1013. #endif
  1014. /**
  1015. * Adapted from Prusa MKS firmware
  1016. *
  1017. * Start with a safe speed (from which the machine may halt to stop immediately).
  1018. */
  1019. // Exit speed limited by a jerk to full halt of a previous last segment
  1020. static float previous_safe_speed;
  1021. float safe_speed = block->nominal_speed;
  1022. bool limited = false;
  1023. LOOP_XYZE(i) {
  1024. float jerk = fabs(current_speed[i]);
  1025. if (jerk > max_jerk[i]) {
  1026. // The actual jerk is lower if it has been limited by the XY jerk.
  1027. if (limited) {
  1028. // Spare one division by a following gymnastics:
  1029. // Instead of jerk *= safe_speed / block->nominal_speed,
  1030. // multiply max_jerk[i] by the divisor.
  1031. jerk *= safe_speed;
  1032. float mjerk = max_jerk[i] * block->nominal_speed;
  1033. if (jerk > mjerk) safe_speed *= mjerk / jerk;
  1034. }
  1035. else {
  1036. safe_speed = max_jerk[i];
  1037. limited = true;
  1038. }
  1039. }
  1040. }
  1041. if (moves_queued > 1 && previous_nominal_speed > 0.0001) {
  1042. // Estimate a maximum velocity allowed at a joint of two successive segments.
  1043. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  1044. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  1045. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  1046. bool prev_speed_larger = previous_nominal_speed > block->nominal_speed;
  1047. float smaller_speed_factor = prev_speed_larger ? (block->nominal_speed / previous_nominal_speed) : (previous_nominal_speed / block->nominal_speed);
  1048. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  1049. vmax_junction = prev_speed_larger ? block->nominal_speed : previous_nominal_speed;
  1050. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  1051. float v_factor = 1.f;
  1052. limited = false;
  1053. // Now limit the jerk in all axes.
  1054. LOOP_XYZE(axis) {
  1055. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  1056. float v_exit = previous_speed[axis], v_entry = current_speed[axis];
  1057. if (prev_speed_larger) v_exit *= smaller_speed_factor;
  1058. if (limited) {
  1059. v_exit *= v_factor;
  1060. v_entry *= v_factor;
  1061. }
  1062. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  1063. float jerk =
  1064. (v_exit > v_entry) ?
  1065. ((v_entry > 0.f || v_exit < 0.f) ?
  1066. // coasting
  1067. (v_exit - v_entry) :
  1068. // axis reversal
  1069. max(v_exit, -v_entry)) :
  1070. // v_exit <= v_entry
  1071. ((v_entry < 0.f || v_exit > 0.f) ?
  1072. // coasting
  1073. (v_entry - v_exit) :
  1074. // axis reversal
  1075. max(-v_exit, v_entry));
  1076. if (jerk > max_jerk[axis]) {
  1077. v_factor *= max_jerk[axis] / jerk;
  1078. limited = true;
  1079. }
  1080. }
  1081. if (limited) vmax_junction *= v_factor;
  1082. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  1083. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  1084. float vmax_junction_threshold = vmax_junction * 0.99f;
  1085. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold) {
  1086. // Not coasting. The machine will stop and start the movements anyway,
  1087. // better to start the segment from start.
  1088. SBI(block->flag, BLOCK_BIT_START_FROM_FULL_HALT);
  1089. vmax_junction = safe_speed;
  1090. }
  1091. }
  1092. else {
  1093. SBI(block->flag, BLOCK_BIT_START_FROM_FULL_HALT);
  1094. vmax_junction = safe_speed;
  1095. }
  1096. // Max entry speed of this block equals the max exit speed of the previous block.
  1097. block->max_entry_speed = vmax_junction;
  1098. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  1099. float v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  1100. block->entry_speed = min(vmax_junction, v_allowable);
  1101. // Initialize planner efficiency flags
  1102. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  1103. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  1104. // the current block and next block junction speeds are guaranteed to always be at their maximum
  1105. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  1106. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  1107. // the reverse and forward planners, the corresponding block junction speed will always be at the
  1108. // the maximum junction speed and may always be ignored for any speed reduction checks.
  1109. block->flag |= BLOCK_FLAG_RECALCULATE | (block->nominal_speed <= v_allowable ? BLOCK_FLAG_NOMINAL_LENGTH : 0);
  1110. // Update previous path unit_vector and nominal speed
  1111. memcpy(previous_speed, current_speed, sizeof(previous_speed));
  1112. previous_nominal_speed = block->nominal_speed;
  1113. previous_safe_speed = safe_speed;
  1114. #if ENABLED(LIN_ADVANCE)
  1115. // Don't use LIN_ADVANCE for blocks if:
  1116. // !block->steps[E_AXIS]: We don't have E steps todo (Travel move)
  1117. // !block->steps[X_AXIS] && !block->steps[Y_AXIS]: We don't have a movement in XY direction (Retract / Prime moves)
  1118. // extruder_advance_k == 0.0: There is no advance factor set
  1119. // block->steps[E_AXIS] == block->step_event_count: A problem occurs when there's a very tiny move before a retract.
  1120. // In this case, the retract and the move will be executed together.
  1121. // This leads to an enormous number of advance steps due to a huge e_acceleration.
  1122. // The math is correct, but you don't want a retract move done with advance!
  1123. // de_float <= 0.0: Extruder is running in reverse direction (for example during "Wipe while retracting" (Slic3r) or "Combing" (Cura) movements)
  1124. if (!esteps || (!block->steps[X_AXIS] && !block->steps[Y_AXIS]) || extruder_advance_k == 0.0 || (uint32_t)esteps == block->step_event_count || de_float <= 0.0) {
  1125. block->use_advance_lead = false;
  1126. }
  1127. else {
  1128. block->use_advance_lead = true;
  1129. block->abs_adv_steps_multiplier8 = lround(extruder_advance_k * (de_float / mm_D_float) * block->nominal_speed / (float)block->nominal_rate * axis_steps_per_mm[E_AXIS] * 256.0);
  1130. }
  1131. #elif ENABLED(ADVANCE)
  1132. // Calculate advance rate
  1133. if (!esteps || (!block->steps[X_AXIS] && !block->steps[Y_AXIS] && !block->steps[Z_AXIS])) {
  1134. block->advance_rate = 0;
  1135. block->advance = 0;
  1136. }
  1137. else {
  1138. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_steps_per_s2);
  1139. float advance = ((STEPS_PER_CUBIC_MM_E) * (EXTRUDER_ADVANCE_K)) * HYPOT(current_speed[E_AXIS], EXTRUSION_AREA) * 256;
  1140. block->advance = advance;
  1141. block->advance_rate = acc_dist ? advance / (float)acc_dist : 0;
  1142. }
  1143. /**
  1144. SERIAL_ECHO_START;
  1145. SERIAL_ECHOPGM("advance :");
  1146. SERIAL_ECHO(block->advance/256.0);
  1147. SERIAL_ECHOPGM("advance rate :");
  1148. SERIAL_ECHOLN(block->advance_rate/256.0);
  1149. */
  1150. #endif // ADVANCE or LIN_ADVANCE
  1151. calculate_trapezoid_for_block(block, block->entry_speed / block->nominal_speed, safe_speed / block->nominal_speed);
  1152. // Move buffer head
  1153. block_buffer_head = next_buffer_head;
  1154. // Update the position (only when a move was queued)
  1155. memcpy(position, target, sizeof(position));
  1156. recalculate();
  1157. stepper.wake_up();
  1158. } // buffer_line()
  1159. /**
  1160. * Directly set the planner XYZ position (and stepper positions)
  1161. * converting mm (or angles for SCARA) into steps.
  1162. *
  1163. * On CORE machines stepper ABC will be translated from the given XYZ.
  1164. */
  1165. void Planner::_set_position_mm(const float &a, const float &b, const float &c, const float &e) {
  1166. long na = position[X_AXIS] = lround(a * axis_steps_per_mm[X_AXIS]),
  1167. nb = position[Y_AXIS] = lround(b * axis_steps_per_mm[Y_AXIS]),
  1168. nc = position[Z_AXIS] = lround(c * axis_steps_per_mm[Z_AXIS]),
  1169. ne = position[E_AXIS] = lround(e * axis_steps_per_mm[E_AXIS]);
  1170. stepper.set_position(na, nb, nc, ne);
  1171. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1172. ZERO(previous_speed);
  1173. }
  1174. void Planner::set_position_mm_kinematic(const float position[NUM_AXIS]) {
  1175. #if PLANNER_LEVELING
  1176. float pos[XYZ] = { position[X_AXIS], position[Y_AXIS], position[Z_AXIS] };
  1177. apply_leveling(pos);
  1178. #else
  1179. const float * const pos = position;
  1180. #endif
  1181. #if IS_KINEMATIC
  1182. inverse_kinematics(pos);
  1183. _set_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], position[E_AXIS]);
  1184. #else
  1185. _set_position_mm(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], position[E_AXIS]);
  1186. #endif
  1187. }
  1188. /**
  1189. * Sync from the stepper positions. (e.g., after an interrupted move)
  1190. */
  1191. void Planner::sync_from_steppers() {
  1192. LOOP_XYZE(i) position[i] = stepper.position((AxisEnum)i);
  1193. }
  1194. /**
  1195. * Setters for planner position (also setting stepper position).
  1196. */
  1197. void Planner::set_position_mm(const AxisEnum axis, const float& v) {
  1198. position[axis] = lround(v * axis_steps_per_mm[axis]);
  1199. stepper.set_position(axis, v);
  1200. previous_speed[axis] = 0.0;
  1201. }
  1202. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1203. void Planner::reset_acceleration_rates() {
  1204. uint32_t highest_rate = 1;
  1205. LOOP_XYZE(i) {
  1206. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  1207. NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  1208. }
  1209. cutoff_long = 4294967295UL / highest_rate;
  1210. }
  1211. // Recalculate position, steps_to_mm if axis_steps_per_mm changes!
  1212. void Planner::refresh_positioning() {
  1213. LOOP_XYZE(i) steps_to_mm[i] = 1.0 / axis_steps_per_mm[i];
  1214. set_position_mm_kinematic(current_position);
  1215. reset_acceleration_rates();
  1216. }
  1217. #if ENABLED(AUTOTEMP)
  1218. void Planner::autotemp_M104_M109() {
  1219. autotemp_enabled = code_seen('F');
  1220. if (autotemp_enabled) autotemp_factor = code_value_temp_diff();
  1221. if (code_seen('S')) autotemp_min = code_value_temp_abs();
  1222. if (code_seen('B')) autotemp_max = code_value_temp_abs();
  1223. }
  1224. #endif
  1225. #if ENABLED(LIN_ADVANCE)
  1226. void Planner::advance_M905(const float &k) {
  1227. if (k >= 0.0) extruder_advance_k = k;
  1228. SERIAL_ECHO_START;
  1229. SERIAL_ECHOPAIR("Advance factor: ", extruder_advance_k);
  1230. SERIAL_EOL;
  1231. }
  1232. #endif