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 48KB

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