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

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