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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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 - Buffer movement commands and manage the acceleration profile plan
  24. * Part of Grbl
  25. *
  26. * Copyright (c) 2009-2011 Simen Svale Skogsrud
  27. *
  28. * Grbl is free software: you can redistribute it and/or modify
  29. * it under the terms of the GNU General Public License as published by
  30. * the Free Software Foundation, either version 3 of the License, or
  31. * (at your option) any later version.
  32. *
  33. * Grbl is distributed in the hope that it will be useful,
  34. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  35. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  36. * GNU General Public License for more details.
  37. *
  38. * You should have received a copy of the GNU General Public License
  39. * along with Grbl. If not, see <http://www.gnu.org/licenses/>.
  40. *
  41. *
  42. * The ring buffer implementation gleaned from the wiring_serial library by David A. Mellis.
  43. *
  44. *
  45. * Reasoning behind the mathematics in this module (in the key of 'Mathematica'):
  46. *
  47. * s == speed, a == acceleration, t == time, d == distance
  48. *
  49. * Basic definitions:
  50. * Speed[s_, a_, t_] := s + (a*t)
  51. * Travel[s_, a_, t_] := Integrate[Speed[s, a, t], t]
  52. *
  53. * Distance to reach a specific speed with a constant acceleration:
  54. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, d, t]
  55. * d -> (m^2 - s^2)/(2 a) --> estimate_acceleration_distance()
  56. *
  57. * Speed after a given distance of travel with constant acceleration:
  58. * Solve[{Speed[s, a, t] == m, Travel[s, a, t] == d}, m, t]
  59. * m -> Sqrt[2 a d + s^2]
  60. *
  61. * DestinationSpeed[s_, a_, d_] := Sqrt[2 a d + s^2]
  62. *
  63. * When to start braking (di) to reach a specified destination speed (s2) after accelerating
  64. * from initial speed s1 without ever stopping at a plateau:
  65. * Solve[{DestinationSpeed[s1, a, di] == DestinationSpeed[s2, a, d - di]}, di]
  66. * di -> (2 a d - s1^2 + s2^2)/(4 a) --> intersection_distance()
  67. *
  68. * IntersectionDistance[s1_, s2_, a_, d_] := (2 a d - s1^2 + s2^2)/(4 a)
  69. *
  70. */
  71. #include "Marlin.h"
  72. #include "planner.h"
  73. #include "stepper.h"
  74. #include "temperature.h"
  75. #include "ultralcd.h"
  76. #include "language.h"
  77. #if ENABLED(MESH_BED_LEVELING)
  78. #include "mesh_bed_leveling.h"
  79. #endif
  80. //===========================================================================
  81. //============================= public variables ============================
  82. //===========================================================================
  83. millis_t minsegmenttime;
  84. float max_feedrate[NUM_AXIS]; // Max speeds in mm per minute
  85. float axis_steps_per_unit[NUM_AXIS];
  86. unsigned long max_acceleration_units_per_sq_second[NUM_AXIS]; // Use M201 to override by software
  87. float minimumfeedrate;
  88. float acceleration; // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  89. float retract_acceleration; // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  90. float travel_acceleration; // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  91. float max_xy_jerk; // The largest speed change requiring no acceleration
  92. float max_z_jerk;
  93. float max_e_jerk;
  94. float mintravelfeedrate;
  95. unsigned long axis_steps_per_sqr_second[NUM_AXIS];
  96. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  97. // Transform required to compensate for bed level
  98. matrix_3x3 plan_bed_level_matrix = {
  99. 1.0, 0.0, 0.0,
  100. 0.0, 1.0, 0.0,
  101. 0.0, 0.0, 1.0
  102. };
  103. #endif // AUTO_BED_LEVELING_FEATURE
  104. #if ENABLED(AUTOTEMP)
  105. float autotemp_max = 250;
  106. float autotemp_min = 210;
  107. float autotemp_factor = 0.1;
  108. bool autotemp_enabled = false;
  109. #endif
  110. #if ENABLED(FAN_SOFT_PWM)
  111. extern unsigned char fanSpeedSoftPwm[FAN_COUNT];
  112. #endif
  113. //===========================================================================
  114. //============ semi-private variables, used in inline functions =============
  115. //===========================================================================
  116. block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instfructions
  117. volatile unsigned char block_buffer_head; // Index of the next block to be pushed
  118. volatile unsigned char block_buffer_tail; // Index of the block to process now
  119. //===========================================================================
  120. //============================ private variables ============================
  121. //===========================================================================
  122. // The current position of the tool in absolute steps
  123. long position[NUM_AXIS]; // Rescaled from extern when axis_steps_per_unit are changed by gcode
  124. static float previous_speed[NUM_AXIS]; // Speed of previous path line segment
  125. static float previous_nominal_speed; // Nominal speed of previous path line segment
  126. uint8_t g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  127. #ifdef XY_FREQUENCY_LIMIT
  128. // Used for the frequency limit
  129. #define MAX_FREQ_TIME (1000000.0/XY_FREQUENCY_LIMIT)
  130. // Old direction bits. Used for speed calculations
  131. static unsigned char old_direction_bits = 0;
  132. // Segment times (in µs). Used for speed calculations
  133. static long axis_segment_time[2][3] = { {MAX_FREQ_TIME + 1, 0, 0}, {MAX_FREQ_TIME + 1, 0, 0} };
  134. #endif
  135. #if ENABLED(DUAL_X_CARRIAGE)
  136. extern bool extruder_duplication_enabled;
  137. #endif
  138. //===========================================================================
  139. //================================ functions ================================
  140. //===========================================================================
  141. // Get the next / previous index of the next block in the ring buffer
  142. // NOTE: Using & here (not %) because BLOCK_BUFFER_SIZE is always a power of 2
  143. FORCE_INLINE int8_t next_block_index(int8_t block_index) { return BLOCK_MOD(block_index + 1); }
  144. FORCE_INLINE int8_t prev_block_index(int8_t block_index) { return BLOCK_MOD(block_index - 1); }
  145. // Calculates the distance (not time) it takes to accelerate from initial_rate to target_rate using the
  146. // given acceleration:
  147. FORCE_INLINE float estimate_acceleration_distance(float initial_rate, float target_rate, float acceleration) {
  148. if (acceleration == 0) return 0; // acceleration was 0, set acceleration distance to 0
  149. return (target_rate * target_rate - initial_rate * initial_rate) / (acceleration * 2);
  150. }
  151. // This function gives you the point at which you must start braking (at the rate of -acceleration) if
  152. // you started at speed initial_rate and accelerated until this point and want to end at the final_rate after
  153. // a total travel of distance. This can be used to compute the intersection point between acceleration and
  154. // deceleration in the cases where the trapezoid has no plateau (i.e. never reaches maximum speed)
  155. FORCE_INLINE float intersection_distance(float initial_rate, float final_rate, float acceleration, float distance) {
  156. if (acceleration == 0) return 0; // acceleration was 0, set intersection distance to 0
  157. return (acceleration * 2 * distance - initial_rate * initial_rate + final_rate * final_rate) / (acceleration * 4);
  158. }
  159. // Calculates trapezoid parameters so that the entry- and exit-speed is compensated by the provided factors.
  160. void calculate_trapezoid_for_block(block_t* block, float entry_factor, float exit_factor) {
  161. unsigned long initial_rate = ceil(block->nominal_rate * entry_factor); // (step/min)
  162. unsigned long final_rate = ceil(block->nominal_rate * exit_factor); // (step/min)
  163. // Limit minimal step rate (Otherwise the timer will overflow.)
  164. NOLESS(initial_rate, 120);
  165. NOLESS(final_rate, 120);
  166. long acceleration = block->acceleration_st;
  167. int32_t accelerate_steps = ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, acceleration));
  168. int32_t decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -acceleration));
  169. // Calculate the size of Plateau of Nominal Rate.
  170. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  171. // Is the Plateau of Nominal Rate smaller than nothing? That means no cruising, and we will
  172. // have to use intersection_distance() to calculate when to abort acceleration and start braking
  173. // in order to reach the final_rate exactly at the end of this block.
  174. if (plateau_steps < 0) {
  175. accelerate_steps = ceil(intersection_distance(initial_rate, final_rate, acceleration, block->step_event_count));
  176. accelerate_steps = max(accelerate_steps, 0); // Check limits due to numerical round-off
  177. 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)
  178. plateau_steps = 0;
  179. }
  180. #if ENABLED(ADVANCE)
  181. volatile long initial_advance = block->advance * entry_factor * entry_factor;
  182. volatile long final_advance = block->advance * exit_factor * exit_factor;
  183. #endif // ADVANCE
  184. // block->accelerate_until = accelerate_steps;
  185. // block->decelerate_after = accelerate_steps+plateau_steps;
  186. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  187. if (!block->busy) { // Don't update variables if block is busy.
  188. block->accelerate_until = accelerate_steps;
  189. block->decelerate_after = accelerate_steps + plateau_steps;
  190. block->initial_rate = initial_rate;
  191. block->final_rate = final_rate;
  192. #if ENABLED(ADVANCE)
  193. block->initial_advance = initial_advance;
  194. block->final_advance = final_advance;
  195. #endif
  196. }
  197. CRITICAL_SECTION_END;
  198. }
  199. // Calculates the maximum allowable speed at this point when you must be able to reach target_velocity using the
  200. // acceleration within the allotted distance.
  201. FORCE_INLINE float max_allowable_speed(float acceleration, float target_velocity, float distance) {
  202. return sqrt(target_velocity * target_velocity - 2 * acceleration * distance);
  203. }
  204. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  205. // This method will calculate the junction jerk as the euclidean distance between the nominal
  206. // velocities of the respective blocks.
  207. //inline float junction_jerk(block_t *before, block_t *after) {
  208. // return sqrt(
  209. // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
  210. //}
  211. // The kernel called by planner_recalculate() when scanning the plan from last to first entry.
  212. void planner_reverse_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  213. if (!current) return;
  214. UNUSED(previous);
  215. if (next) {
  216. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  217. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  218. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  219. float max_entry_speed = current->max_entry_speed;
  220. if (current->entry_speed != max_entry_speed) {
  221. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  222. // for max allowable speed if block is decelerating and nominal length is false.
  223. if (!current->nominal_length_flag && max_entry_speed > next->entry_speed) {
  224. current->entry_speed = min(max_entry_speed,
  225. max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  226. }
  227. else {
  228. current->entry_speed = max_entry_speed;
  229. }
  230. current->recalculate_flag = true;
  231. }
  232. } // Skip last block. Already initialized and set for recalculation.
  233. }
  234. // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
  235. // implements the reverse pass.
  236. void planner_reverse_pass() {
  237. uint8_t block_index = block_buffer_head;
  238. //Make a local copy of block_buffer_tail, because the interrupt can alter it
  239. CRITICAL_SECTION_START;
  240. unsigned char tail = block_buffer_tail;
  241. CRITICAL_SECTION_END
  242. if (BLOCK_MOD(block_buffer_head - tail + BLOCK_BUFFER_SIZE) > 3) { // moves queued
  243. block_index = BLOCK_MOD(block_buffer_head - 3);
  244. block_t* block[3] = { NULL, NULL, NULL };
  245. while (block_index != tail) {
  246. block_index = prev_block_index(block_index);
  247. block[2] = block[1];
  248. block[1] = block[0];
  249. block[0] = &block_buffer[block_index];
  250. planner_reverse_pass_kernel(block[0], block[1], block[2]);
  251. }
  252. }
  253. }
  254. // The kernel called by planner_recalculate() when scanning the plan from first to last entry.
  255. void planner_forward_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  256. if (!previous) return;
  257. UNUSED(next);
  258. // If the previous block is an acceleration block, but it is not long enough to complete the
  259. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  260. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  261. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  262. if (!previous->nominal_length_flag) {
  263. if (previous->entry_speed < current->entry_speed) {
  264. double entry_speed = min(current->entry_speed,
  265. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  266. // Check for junction speed change
  267. if (current->entry_speed != entry_speed) {
  268. current->entry_speed = entry_speed;
  269. current->recalculate_flag = true;
  270. }
  271. }
  272. }
  273. }
  274. // planner_recalculate() needs to go over the current plan twice. Once in reverse and once forward. This
  275. // implements the forward pass.
  276. void planner_forward_pass() {
  277. uint8_t block_index = block_buffer_tail;
  278. block_t* block[3] = { NULL, NULL, NULL };
  279. while (block_index != block_buffer_head) {
  280. block[0] = block[1];
  281. block[1] = block[2];
  282. block[2] = &block_buffer[block_index];
  283. planner_forward_pass_kernel(block[0], block[1], block[2]);
  284. block_index = next_block_index(block_index);
  285. }
  286. planner_forward_pass_kernel(block[1], block[2], NULL);
  287. }
  288. // Recalculates the trapezoid speed profiles for all blocks in the plan according to the
  289. // entry_factor for each junction. Must be called by planner_recalculate() after
  290. // updating the blocks.
  291. void planner_recalculate_trapezoids() {
  292. int8_t block_index = block_buffer_tail;
  293. block_t* current;
  294. block_t* next = NULL;
  295. while (block_index != block_buffer_head) {
  296. current = next;
  297. next = &block_buffer[block_index];
  298. if (current) {
  299. // Recalculate if current block entry or exit junction speed has changed.
  300. if (current->recalculate_flag || next->recalculate_flag) {
  301. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  302. float nom = current->nominal_speed;
  303. calculate_trapezoid_for_block(current, current->entry_speed / nom, next->entry_speed / nom);
  304. current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
  305. }
  306. }
  307. block_index = next_block_index(block_index);
  308. }
  309. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  310. if (next) {
  311. float nom = next->nominal_speed;
  312. calculate_trapezoid_for_block(next, next->entry_speed / nom, (MINIMUM_PLANNER_SPEED) / nom);
  313. next->recalculate_flag = false;
  314. }
  315. }
  316. // Recalculates the motion plan according to the following algorithm:
  317. //
  318. // 1. Go over every block in reverse order and calculate a junction speed reduction (i.e. block_t.entry_factor)
  319. // so that:
  320. // a. The junction jerk is within the set limit
  321. // b. No speed reduction within one block requires faster deceleration than the one, true constant
  322. // acceleration.
  323. // 2. Go over every block in chronological order and dial down junction speed reduction values if
  324. // a. The speed increase within one block would require faster acceleration than the one, true
  325. // constant acceleration.
  326. //
  327. // When these stages are complete all blocks have an entry_factor that will allow all speed changes to
  328. // be performed using only the one, true constant acceleration, and where no junction jerk is jerkier than
  329. // the set limit. Finally it will:
  330. //
  331. // 3. Recalculate trapezoids for all blocks.
  332. void planner_recalculate() {
  333. planner_reverse_pass();
  334. planner_forward_pass();
  335. planner_recalculate_trapezoids();
  336. }
  337. void plan_init() {
  338. block_buffer_head = block_buffer_tail = 0;
  339. memset(position, 0, sizeof(position)); // clear position
  340. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  341. previous_nominal_speed = 0.0;
  342. }
  343. #if ENABLED(AUTOTEMP)
  344. void getHighESpeed() {
  345. static float oldt = 0;
  346. if (!autotemp_enabled) return;
  347. if (degTargetHotend0() + 2 < autotemp_min) return; // probably temperature set to zero.
  348. float high = 0.0;
  349. uint8_t block_index = block_buffer_tail;
  350. while (block_index != block_buffer_head) {
  351. block_t* block = &block_buffer[block_index];
  352. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  353. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  354. NOLESS(high, se);
  355. }
  356. block_index = next_block_index(block_index);
  357. }
  358. float t = autotemp_min + high * autotemp_factor;
  359. t = constrain(t, autotemp_min, autotemp_max);
  360. if (oldt > t) {
  361. t *= (1 - (AUTOTEMP_OLDWEIGHT));
  362. t += (AUTOTEMP_OLDWEIGHT) * oldt;
  363. }
  364. oldt = t;
  365. setTargetHotend0(t);
  366. }
  367. #endif //AUTOTEMP
  368. void check_axes_activity() {
  369. unsigned char axis_active[NUM_AXIS] = { 0 },
  370. tail_fan_speed[FAN_COUNT];
  371. #if FAN_COUNT > 0
  372. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  373. #endif
  374. #if ENABLED(BARICUDA)
  375. unsigned char tail_valve_pressure = ValvePressure,
  376. tail_e_to_p_pressure = EtoPPressure;
  377. #endif
  378. block_t* block;
  379. if (blocks_queued()) {
  380. uint8_t block_index = block_buffer_tail;
  381. #if FAN_COUNT > 0
  382. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = block_buffer[block_index].fan_speed[i];
  383. #endif
  384. #if ENABLED(BARICUDA)
  385. block = &block_buffer[block_index];
  386. tail_valve_pressure = block->valve_pressure;
  387. tail_e_to_p_pressure = block->e_to_p_pressure;
  388. #endif
  389. while (block_index != block_buffer_head) {
  390. block = &block_buffer[block_index];
  391. for (int i = 0; i < NUM_AXIS; i++) if (block->steps[i]) axis_active[i]++;
  392. block_index = next_block_index(block_index);
  393. }
  394. }
  395. #if ENABLED(DISABLE_X)
  396. if (!axis_active[X_AXIS]) disable_x();
  397. #endif
  398. #if ENABLED(DISABLE_Y)
  399. if (!axis_active[Y_AXIS]) disable_y();
  400. #endif
  401. #if ENABLED(DISABLE_Z)
  402. if (!axis_active[Z_AXIS]) disable_z();
  403. #endif
  404. #if ENABLED(DISABLE_E)
  405. if (!axis_active[E_AXIS]) {
  406. disable_e0();
  407. disable_e1();
  408. disable_e2();
  409. disable_e3();
  410. }
  411. #endif
  412. #if FAN_COUNT > 0
  413. #if defined(FAN_MIN_PWM)
  414. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  415. #else
  416. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  417. #endif
  418. #ifdef FAN_KICKSTART_TIME
  419. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  420. #define KICKSTART_FAN(f) \
  421. if (tail_fan_speed[f]) { \
  422. millis_t ms = millis(); \
  423. if (fan_kick_end[f] == 0) { \
  424. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  425. tail_fan_speed[f] = 255; \
  426. } else { \
  427. if (fan_kick_end[f] > ms) { \
  428. tail_fan_speed[f] = 255; \
  429. } \
  430. } \
  431. } else { \
  432. fan_kick_end[f] = 0; \
  433. }
  434. #if HAS_FAN0
  435. KICKSTART_FAN(0);
  436. #endif
  437. #if HAS_FAN1
  438. KICKSTART_FAN(1);
  439. #endif
  440. #if HAS_FAN2
  441. KICKSTART_FAN(2);
  442. #endif
  443. #endif //FAN_KICKSTART_TIME
  444. #if ENABLED(FAN_SOFT_PWM)
  445. #if HAS_FAN0
  446. fanSpeedSoftPwm[0] = CALC_FAN_SPEED(0);
  447. #endif
  448. #if HAS_FAN1
  449. fanSpeedSoftPwm[1] = CALC_FAN_SPEED(1);
  450. #endif
  451. #if HAS_FAN2
  452. fanSpeedSoftPwm[2] = CALC_FAN_SPEED(2);
  453. #endif
  454. #else
  455. #if HAS_FAN0
  456. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  457. #endif
  458. #if HAS_FAN1
  459. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  460. #endif
  461. #if HAS_FAN2
  462. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  463. #endif
  464. #endif
  465. #endif // FAN_COUNT > 0
  466. #if ENABLED(AUTOTEMP)
  467. getHighESpeed();
  468. #endif
  469. #if ENABLED(BARICUDA)
  470. #if HAS_HEATER_1
  471. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  472. #endif
  473. #if HAS_HEATER_2
  474. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  475. #endif
  476. #endif
  477. }
  478. float junction_deviation = 0.1;
  479. // Add a new linear movement to the buffer. steps[X_AXIS], _y and _z is the absolute position in
  480. // mm. Microseconds specify how many microseconds the move should take to perform. To aid acceleration
  481. // calculation the caller must also provide the physical length of the line in millimeters.
  482. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  483. void plan_buffer_line(float x, float y, float z, const float& e, float feed_rate, const uint8_t extruder)
  484. #else
  485. void plan_buffer_line(const float& x, const float& y, const float& z, const float& e, float feed_rate, const uint8_t extruder)
  486. #endif // AUTO_BED_LEVELING_FEATURE
  487. {
  488. // Calculate the buffer head after we push this byte
  489. int next_buffer_head = next_block_index(block_buffer_head);
  490. // If the buffer is full: good! That means we are well ahead of the robot.
  491. // Rest here until there is room in the buffer.
  492. while (block_buffer_tail == next_buffer_head) idle();
  493. #if ENABLED(MESH_BED_LEVELING)
  494. if (mbl.active) z += mbl.get_z(x, y);
  495. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  496. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  497. #endif
  498. // The target position of the tool in absolute steps
  499. // Calculate target position in absolute steps
  500. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  501. long target[NUM_AXIS];
  502. target[X_AXIS] = lround(x * axis_steps_per_unit[X_AXIS]);
  503. target[Y_AXIS] = lround(y * axis_steps_per_unit[Y_AXIS]);
  504. target[Z_AXIS] = lround(z * axis_steps_per_unit[Z_AXIS]);
  505. target[E_AXIS] = lround(e * axis_steps_per_unit[E_AXIS]);
  506. long dx = target[X_AXIS] - position[X_AXIS],
  507. dy = target[Y_AXIS] - position[Y_AXIS],
  508. dz = target[Z_AXIS] - position[Z_AXIS];
  509. // DRYRUN ignores all temperature constraints and assures that the extruder is instantly satisfied
  510. if (DEBUGGING(DRYRUN))
  511. position[E_AXIS] = target[E_AXIS];
  512. long de = target[E_AXIS] - position[E_AXIS];
  513. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  514. if (de) {
  515. if (degHotend(extruder) < extrude_min_temp) {
  516. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  517. de = 0; // no difference
  518. SERIAL_ECHO_START;
  519. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  520. }
  521. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  522. if (labs(de) > axis_steps_per_unit[E_AXIS] * (EXTRUDE_MAXLENGTH)) {
  523. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  524. de = 0; // no difference
  525. SERIAL_ECHO_START;
  526. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  527. }
  528. #endif
  529. }
  530. #endif
  531. // Prepare to set up new block
  532. block_t* block = &block_buffer[block_buffer_head];
  533. // Mark block as not busy (Not executed by the stepper interrupt)
  534. block->busy = false;
  535. // Number of steps for each axis
  536. #if ENABLED(COREXY)
  537. // corexy planning
  538. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  539. block->steps[A_AXIS] = labs(dx + dy);
  540. block->steps[B_AXIS] = labs(dx - dy);
  541. block->steps[Z_AXIS] = labs(dz);
  542. #elif ENABLED(COREXZ)
  543. // corexz planning
  544. block->steps[A_AXIS] = labs(dx + dz);
  545. block->steps[Y_AXIS] = labs(dy);
  546. block->steps[C_AXIS] = labs(dx - dz);
  547. #else
  548. // default non-h-bot planning
  549. block->steps[X_AXIS] = labs(dx);
  550. block->steps[Y_AXIS] = labs(dy);
  551. block->steps[Z_AXIS] = labs(dz);
  552. #endif
  553. block->steps[E_AXIS] = labs(de);
  554. block->steps[E_AXIS] *= volumetric_multiplier[extruder];
  555. block->steps[E_AXIS] *= extruder_multiplier[extruder];
  556. block->steps[E_AXIS] /= 100;
  557. block->step_event_count = max(block->steps[X_AXIS], max(block->steps[Y_AXIS], max(block->steps[Z_AXIS], block->steps[E_AXIS])));
  558. // Bail if this is a zero-length block
  559. if (block->step_event_count <= dropsegments) return;
  560. #if FAN_COUNT > 0
  561. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  562. #endif
  563. #if ENABLED(BARICUDA)
  564. block->valve_pressure = ValvePressure;
  565. block->e_to_p_pressure = EtoPPressure;
  566. #endif
  567. // Compute direction bits for this block
  568. uint8_t db = 0;
  569. #if ENABLED(COREXY)
  570. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  571. if (dy < 0) SBI(db, Y_HEAD); // ...and Y
  572. if (dz < 0) SBI(db, Z_AXIS);
  573. if (dx + dy < 0) SBI(db, A_AXIS); // Motor A direction
  574. if (dx - dy < 0) SBI(db, B_AXIS); // Motor B direction
  575. #elif ENABLED(COREXZ)
  576. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  577. if (dy < 0) SBI(db, Y_AXIS);
  578. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  579. if (dx + dz < 0) SBI(db, A_AXIS); // Motor A direction
  580. if (dx - dz < 0) SBI(db, C_AXIS); // Motor B direction
  581. #else
  582. if (dx < 0) SBI(db, X_AXIS);
  583. if (dy < 0) SBI(db, Y_AXIS);
  584. if (dz < 0) SBI(db, Z_AXIS);
  585. #endif
  586. if (de < 0) SBI(db, E_AXIS);
  587. block->direction_bits = db;
  588. block->active_extruder = extruder;
  589. //enable active axes
  590. #if ENABLED(COREXY)
  591. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  592. enable_x();
  593. enable_y();
  594. }
  595. #if DISABLED(Z_LATE_ENABLE)
  596. if (block->steps[Z_AXIS]) enable_z();
  597. #endif
  598. #elif ENABLED(COREXZ)
  599. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  600. enable_x();
  601. enable_z();
  602. }
  603. if (block->steps[Y_AXIS]) enable_y();
  604. #else
  605. if (block->steps[X_AXIS]) enable_x();
  606. if (block->steps[Y_AXIS]) enable_y();
  607. #if DISABLED(Z_LATE_ENABLE)
  608. if (block->steps[Z_AXIS]) enable_z();
  609. #endif
  610. #endif
  611. // Enable extruder(s)
  612. if (block->steps[E_AXIS]) {
  613. if (DISABLE_INACTIVE_EXTRUDER) { //enable only selected extruder
  614. for (int i = 0; i < EXTRUDERS; i++)
  615. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  616. switch(extruder) {
  617. case 0:
  618. enable_e0();
  619. #if ENABLED(DUAL_X_CARRIAGE)
  620. if (extruder_duplication_enabled) {
  621. enable_e1();
  622. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  623. }
  624. #endif
  625. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  626. #if EXTRUDERS > 1
  627. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  628. #if EXTRUDERS > 2
  629. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  630. #if EXTRUDERS > 3
  631. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  632. #endif
  633. #endif
  634. #endif
  635. break;
  636. #if EXTRUDERS > 1
  637. case 1:
  638. enable_e1();
  639. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  640. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  641. #if EXTRUDERS > 2
  642. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  643. #if EXTRUDERS > 3
  644. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  645. #endif
  646. #endif
  647. break;
  648. #if EXTRUDERS > 2
  649. case 2:
  650. enable_e2();
  651. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  652. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  653. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  654. #if EXTRUDERS > 3
  655. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  656. #endif
  657. break;
  658. #if EXTRUDERS > 3
  659. case 3:
  660. enable_e3();
  661. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  662. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  663. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  664. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  665. break;
  666. #endif // EXTRUDERS > 3
  667. #endif // EXTRUDERS > 2
  668. #endif // EXTRUDERS > 1
  669. }
  670. }
  671. else { // enable all
  672. enable_e0();
  673. enable_e1();
  674. enable_e2();
  675. enable_e3();
  676. }
  677. }
  678. if (block->steps[E_AXIS])
  679. NOLESS(feed_rate, minimumfeedrate);
  680. else
  681. NOLESS(feed_rate, mintravelfeedrate);
  682. /**
  683. * This part of the code calculates the total length of the movement.
  684. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  685. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  686. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  687. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  688. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  689. */
  690. #if ENABLED(COREXY)
  691. float delta_mm[6];
  692. delta_mm[X_HEAD] = dx / axis_steps_per_unit[A_AXIS];
  693. delta_mm[Y_HEAD] = dy / axis_steps_per_unit[B_AXIS];
  694. delta_mm[Z_AXIS] = dz / axis_steps_per_unit[Z_AXIS];
  695. delta_mm[A_AXIS] = (dx + dy) / axis_steps_per_unit[A_AXIS];
  696. delta_mm[B_AXIS] = (dx - dy) / axis_steps_per_unit[B_AXIS];
  697. #elif ENABLED(COREXZ)
  698. float delta_mm[6];
  699. delta_mm[X_HEAD] = dx / axis_steps_per_unit[A_AXIS];
  700. delta_mm[Y_AXIS] = dy / axis_steps_per_unit[Y_AXIS];
  701. delta_mm[Z_HEAD] = dz / axis_steps_per_unit[C_AXIS];
  702. delta_mm[A_AXIS] = (dx + dz) / axis_steps_per_unit[A_AXIS];
  703. delta_mm[C_AXIS] = (dx - dz) / axis_steps_per_unit[C_AXIS];
  704. #else
  705. float delta_mm[4];
  706. delta_mm[X_AXIS] = dx / axis_steps_per_unit[X_AXIS];
  707. delta_mm[Y_AXIS] = dy / axis_steps_per_unit[Y_AXIS];
  708. delta_mm[Z_AXIS] = dz / axis_steps_per_unit[Z_AXIS];
  709. #endif
  710. delta_mm[E_AXIS] = (de / axis_steps_per_unit[E_AXIS]) * volumetric_multiplier[extruder] * extruder_multiplier[extruder] / 100.0;
  711. if (block->steps[X_AXIS] <= dropsegments && block->steps[Y_AXIS] <= dropsegments && block->steps[Z_AXIS] <= dropsegments) {
  712. block->millimeters = fabs(delta_mm[E_AXIS]);
  713. }
  714. else {
  715. block->millimeters = sqrt(
  716. #if ENABLED(COREXY)
  717. square(delta_mm[X_HEAD]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_AXIS])
  718. #elif ENABLED(COREXZ)
  719. square(delta_mm[X_HEAD]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_HEAD])
  720. #else
  721. square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS])
  722. #endif
  723. );
  724. }
  725. float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  726. // Calculate moves/second for this move. No divide by zero due to previous checks.
  727. float inverse_second = feed_rate * inverse_millimeters;
  728. int moves_queued = movesplanned();
  729. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  730. #if ENABLED(OLD_SLOWDOWN) || ENABLED(SLOWDOWN)
  731. bool mq = moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE) / 2;
  732. #if ENABLED(OLD_SLOWDOWN)
  733. if (mq) feed_rate *= 2.0 * moves_queued / (BLOCK_BUFFER_SIZE);
  734. #endif
  735. #if ENABLED(SLOWDOWN)
  736. // segment time im micro seconds
  737. unsigned long segment_time = lround(1000000.0/inverse_second);
  738. if (mq) {
  739. if (segment_time < minsegmenttime) {
  740. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  741. inverse_second = 1000000.0 / (segment_time + lround(2 * (minsegmenttime - segment_time) / moves_queued));
  742. #ifdef XY_FREQUENCY_LIMIT
  743. segment_time = lround(1000000.0 / inverse_second);
  744. #endif
  745. }
  746. }
  747. #endif
  748. #endif
  749. block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
  750. block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
  751. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  752. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  753. //FMM update ring buffer used for delay with filament measurements
  754. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index2 >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  755. const int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  756. // increment counters with next move in e axis
  757. filwidth_e_count += delta_mm[E_AXIS];
  758. filwidth_delay_dist += delta_mm[E_AXIS];
  759. // Only get new measurements on forward E movement
  760. if (filwidth_e_count > 0.0001) {
  761. // Loop the delay distance counter (modulus by the mm length)
  762. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  763. // Convert into an index into the measurement array
  764. filwidth_delay_index1 = (int)(filwidth_delay_dist / 10.0 + 0.0001);
  765. // If the index has changed (must have gone forward)...
  766. if (filwidth_delay_index1 != filwidth_delay_index2) {
  767. filwidth_e_count = 0; // Reset the E movement counter
  768. int8_t meas_sample = widthFil_to_size_ratio() - 100; // Subtract 100 to reduce magnitude - to store in a signed char
  769. do {
  770. filwidth_delay_index2 = (filwidth_delay_index2 + 1) % MMD_CM; // The next unused slot
  771. measurement_delay[filwidth_delay_index2] = meas_sample; // Store the measurement
  772. } while (filwidth_delay_index1 != filwidth_delay_index2); // More slots to fill?
  773. }
  774. }
  775. }
  776. #endif
  777. // Calculate and limit speed in mm/sec for each axis
  778. float current_speed[NUM_AXIS];
  779. float speed_factor = 1.0; //factor <=1 do decrease speed
  780. for (int i = 0; i < NUM_AXIS; i++) {
  781. current_speed[i] = delta_mm[i] * inverse_second;
  782. float cs = fabs(current_speed[i]), mf = max_feedrate[i];
  783. if (cs > mf) speed_factor = min(speed_factor, mf / cs);
  784. }
  785. // Max segement time in us.
  786. #ifdef XY_FREQUENCY_LIMIT
  787. // Check and limit the xy direction change frequency
  788. unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  789. old_direction_bits = block->direction_bits;
  790. segment_time = lround((float)segment_time / speed_factor);
  791. long xs0 = axis_segment_time[X_AXIS][0],
  792. xs1 = axis_segment_time[X_AXIS][1],
  793. xs2 = axis_segment_time[X_AXIS][2],
  794. ys0 = axis_segment_time[Y_AXIS][0],
  795. ys1 = axis_segment_time[Y_AXIS][1],
  796. ys2 = axis_segment_time[Y_AXIS][2];
  797. if (TEST(direction_change, X_AXIS)) {
  798. xs2 = axis_segment_time[X_AXIS][2] = xs1;
  799. xs1 = axis_segment_time[X_AXIS][1] = xs0;
  800. xs0 = 0;
  801. }
  802. xs0 = axis_segment_time[X_AXIS][0] = xs0 + segment_time;
  803. if (TEST(direction_change, Y_AXIS)) {
  804. ys2 = axis_segment_time[Y_AXIS][2] = axis_segment_time[Y_AXIS][1];
  805. ys1 = axis_segment_time[Y_AXIS][1] = axis_segment_time[Y_AXIS][0];
  806. ys0 = 0;
  807. }
  808. ys0 = axis_segment_time[Y_AXIS][0] = ys0 + segment_time;
  809. long max_x_segment_time = max(xs0, max(xs1, xs2)),
  810. max_y_segment_time = max(ys0, max(ys1, ys2)),
  811. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  812. if (min_xy_segment_time < MAX_FREQ_TIME) {
  813. float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME);
  814. speed_factor = min(speed_factor, low_sf);
  815. }
  816. #endif // XY_FREQUENCY_LIMIT
  817. // Correct the speed
  818. if (speed_factor < 1.0) {
  819. for (unsigned char i = 0; i < NUM_AXIS; i++) current_speed[i] *= speed_factor;
  820. block->nominal_speed *= speed_factor;
  821. block->nominal_rate *= speed_factor;
  822. }
  823. // Compute and limit the acceleration rate for the trapezoid generator.
  824. float steps_per_mm = block->step_event_count / block->millimeters;
  825. unsigned long bsx = block->steps[X_AXIS], bsy = block->steps[Y_AXIS], bsz = block->steps[Z_AXIS], bse = block->steps[E_AXIS];
  826. if (bsx == 0 && bsy == 0 && bsz == 0) {
  827. block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  828. }
  829. else if (bse == 0) {
  830. block->acceleration_st = ceil(travel_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  831. }
  832. else {
  833. block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  834. }
  835. // Limit acceleration per axis
  836. unsigned long acc_st = block->acceleration_st,
  837. xsteps = axis_steps_per_sqr_second[X_AXIS],
  838. ysteps = axis_steps_per_sqr_second[Y_AXIS],
  839. zsteps = axis_steps_per_sqr_second[Z_AXIS],
  840. esteps = axis_steps_per_sqr_second[E_AXIS],
  841. allsteps = block->step_event_count;
  842. if (xsteps < (acc_st * bsx) / allsteps) acc_st = (xsteps * allsteps) / bsx;
  843. if (ysteps < (acc_st * bsy) / allsteps) acc_st = (ysteps * allsteps) / bsy;
  844. if (zsteps < (acc_st * bsz) / allsteps) acc_st = (zsteps * allsteps) / bsz;
  845. if (esteps < (acc_st * bse) / allsteps) acc_st = (esteps * allsteps) / bse;
  846. block->acceleration_st = acc_st;
  847. block->acceleration = acc_st / steps_per_mm;
  848. block->acceleration_rate = (long)(acc_st * 16777216.0 / (F_CPU / 8.0));
  849. #if 0 // Use old jerk for now
  850. // Compute path unit vector
  851. double unit_vec[3];
  852. unit_vec[X_AXIS] = delta_mm[X_AXIS] * inverse_millimeters;
  853. unit_vec[Y_AXIS] = delta_mm[Y_AXIS] * inverse_millimeters;
  854. unit_vec[Z_AXIS] = delta_mm[Z_AXIS] * inverse_millimeters;
  855. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  856. // Let a circle be tangent to both previous and current path line segments, where the junction
  857. // deviation is defined as the distance from the junction to the closest edge of the circle,
  858. // collinear with the circle center. The circular segment joining the two paths represents the
  859. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  860. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  861. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  862. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  863. // nonlinearities of both the junction angle and junction velocity.
  864. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  865. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  866. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  867. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  868. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  869. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  870. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  871. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  872. // Skip and use default max junction speed for 0 degree acute junction.
  873. if (cos_theta < 0.95) {
  874. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  875. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  876. if (cos_theta > -0.95) {
  877. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  878. double sin_theta_d2 = sqrt(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  879. vmax_junction = min(vmax_junction,
  880. sqrt(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  881. }
  882. }
  883. }
  884. #endif
  885. // Start with a safe speed
  886. float vmax_junction = max_xy_jerk / 2;
  887. float vmax_junction_factor = 1.0;
  888. float mz2 = max_z_jerk / 2, me2 = max_e_jerk / 2;
  889. float csz = current_speed[Z_AXIS], cse = current_speed[E_AXIS];
  890. if (fabs(csz) > mz2) vmax_junction = min(vmax_junction, mz2);
  891. if (fabs(cse) > me2) vmax_junction = min(vmax_junction, me2);
  892. vmax_junction = min(vmax_junction, block->nominal_speed);
  893. float safe_speed = vmax_junction;
  894. if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
  895. float dsx = current_speed[X_AXIS] - previous_speed[X_AXIS],
  896. dsy = current_speed[Y_AXIS] - previous_speed[Y_AXIS],
  897. dsz = fabs(csz - previous_speed[Z_AXIS]),
  898. dse = fabs(cse - previous_speed[E_AXIS]),
  899. jerk = sqrt(dsx * dsx + dsy * dsy);
  900. // if ((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
  901. vmax_junction = block->nominal_speed;
  902. // }
  903. if (jerk > max_xy_jerk) vmax_junction_factor = max_xy_jerk / jerk;
  904. if (dsz > max_z_jerk) vmax_junction_factor = min(vmax_junction_factor, max_z_jerk / dsz);
  905. if (dse > max_e_jerk) vmax_junction_factor = min(vmax_junction_factor, max_e_jerk / dse);
  906. vmax_junction = min(previous_nominal_speed, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed
  907. }
  908. block->max_entry_speed = vmax_junction;
  909. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  910. double v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  911. block->entry_speed = min(vmax_junction, v_allowable);
  912. // Initialize planner efficiency flags
  913. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  914. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  915. // the current block and next block junction speeds are guaranteed to always be at their maximum
  916. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  917. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  918. // the reverse and forward planners, the corresponding block junction speed will always be at the
  919. // the maximum junction speed and may always be ignored for any speed reduction checks.
  920. block->nominal_length_flag = (block->nominal_speed <= v_allowable);
  921. block->recalculate_flag = true; // Always calculate trapezoid for new block
  922. // Update previous path unit_vector and nominal speed
  923. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = current_speed[i];
  924. previous_nominal_speed = block->nominal_speed;
  925. #if ENABLED(ADVANCE)
  926. // Calculate advance rate
  927. if (!bse || (!bsx && !bsy && !bsz)) {
  928. block->advance_rate = 0;
  929. block->advance = 0;
  930. }
  931. else {
  932. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
  933. float advance = ((STEPS_PER_CUBIC_MM_E) * (EXTRUDER_ADVANCE_K)) * (cse * cse * (EXTRUSION_AREA) * (EXTRUSION_AREA)) * 256;
  934. block->advance = advance;
  935. block->advance_rate = acc_dist ? advance / (float)acc_dist : 0;
  936. }
  937. /**
  938. SERIAL_ECHO_START;
  939. SERIAL_ECHOPGM("advance :");
  940. SERIAL_ECHO(block->advance/256.0);
  941. SERIAL_ECHOPGM("advance rate :");
  942. SERIAL_ECHOLN(block->advance_rate/256.0);
  943. */
  944. #endif // ADVANCE
  945. calculate_trapezoid_for_block(block, block->entry_speed / block->nominal_speed, safe_speed / block->nominal_speed);
  946. // Move buffer head
  947. block_buffer_head = next_buffer_head;
  948. // Update position
  949. for (int i = 0; i < NUM_AXIS; i++) position[i] = target[i];
  950. planner_recalculate();
  951. st_wake_up();
  952. } // plan_buffer_line()
  953. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(DELTA)
  954. vector_3 plan_get_position() {
  955. vector_3 position = vector_3(st_get_axis_position_mm(X_AXIS), st_get_axis_position_mm(Y_AXIS), st_get_axis_position_mm(Z_AXIS));
  956. //position.debug("in plan_get position");
  957. //plan_bed_level_matrix.debug("in plan_get_position");
  958. matrix_3x3 inverse = matrix_3x3::transpose(plan_bed_level_matrix);
  959. //inverse.debug("in plan_get inverse");
  960. position.apply_rotation(inverse);
  961. //position.debug("after rotation");
  962. return position;
  963. }
  964. #endif // AUTO_BED_LEVELING_FEATURE && !DELTA
  965. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  966. void plan_set_position(float x, float y, float z, const float& e)
  967. #else
  968. void plan_set_position(const float& x, const float& y, const float& z, const float& e)
  969. #endif // AUTO_BED_LEVELING_FEATURE || MESH_BED_LEVELING
  970. {
  971. #if ENABLED(MESH_BED_LEVELING)
  972. if (mbl.active) z += mbl.get_z(x, y);
  973. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  974. apply_rotation_xyz(plan_bed_level_matrix, x, y, z);
  975. #endif
  976. long nx = position[X_AXIS] = lround(x * axis_steps_per_unit[X_AXIS]),
  977. ny = position[Y_AXIS] = lround(y * axis_steps_per_unit[Y_AXIS]),
  978. nz = position[Z_AXIS] = lround(z * axis_steps_per_unit[Z_AXIS]),
  979. ne = position[E_AXIS] = lround(e * axis_steps_per_unit[E_AXIS]);
  980. st_set_position(nx, ny, nz, ne);
  981. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  982. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  983. }
  984. void plan_set_e_position(const float& e) {
  985. position[E_AXIS] = lround(e * axis_steps_per_unit[E_AXIS]);
  986. st_set_e_position(position[E_AXIS]);
  987. }
  988. // Calculate the steps/s^2 acceleration rates, based on the mm/s^s
  989. void reset_acceleration_rates() {
  990. for (int i = 0; i < NUM_AXIS; i++)
  991. axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i];
  992. }