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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696
  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 "motion.h"
  62. #include "../module/temperature.h"
  63. #include "../lcd/ultralcd.h"
  64. #include "../core/language.h"
  65. #include "../gcode/parser.h"
  66. #include "../Marlin.h"
  67. #if HAS_LEVELING
  68. #include "../feature/bedlevel/bedlevel.h"
  69. #endif
  70. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  71. #include "../feature/filwidth.h"
  72. #endif
  73. #if ENABLED(BARICUDA)
  74. #include "../feature/baricuda.h"
  75. #endif
  76. #if ENABLED(MIXING_EXTRUDER)
  77. #include "../feature/mixing.h"
  78. #endif
  79. #if ENABLED(AUTO_POWER_CONTROL)
  80. #include "../feature/power.h"
  81. #endif
  82. Planner planner;
  83. // public:
  84. /**
  85. * A ring buffer of moves described in steps
  86. */
  87. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  88. volatile uint8_t Planner::block_buffer_head = 0, // Index of the next block to be pushed
  89. Planner::block_buffer_tail = 0;
  90. float Planner::max_feedrate_mm_s[XYZE_N], // Max speeds in mm per second
  91. Planner::axis_steps_per_mm[XYZE_N],
  92. Planner::steps_to_mm[XYZE_N];
  93. #if ENABLED(DISTINCT_E_FACTORS)
  94. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  95. #endif
  96. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  97. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0); // The flow percentage and volumetric multiplier combine to scale E movement
  98. #if DISABLED(NO_VOLUMETRICS)
  99. float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  100. Planner::volumetric_area_nominal = CIRCLE_AREA((DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5), // Nominal cross-sectional area
  101. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  102. #endif
  103. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N],
  104. Planner::max_acceleration_mm_per_s2[XYZE_N]; // Use M201 to override by software
  105. uint32_t Planner::min_segment_time_us;
  106. // Initialized by settings.load()
  107. float Planner::min_feedrate_mm_s,
  108. Planner::acceleration, // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  109. Planner::retract_acceleration, // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  110. Planner::travel_acceleration, // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  111. Planner::max_jerk[XYZE], // The largest speed change requiring no acceleration
  112. Planner::min_travel_feedrate_mm_s;
  113. #if HAS_LEVELING
  114. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  115. #if ABL_PLANAR
  116. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  117. #endif
  118. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  119. float Planner::z_fade_height, // Initialized by settings.load()
  120. Planner::inverse_z_fade_height,
  121. Planner::last_fade_z;
  122. #endif
  123. #else
  124. constexpr bool Planner::leveling_active;
  125. #endif
  126. #if ENABLED(SKEW_CORRECTION)
  127. #if ENABLED(SKEW_CORRECTION_GCODE)
  128. float Planner::xy_skew_factor;
  129. #else
  130. constexpr float Planner::xy_skew_factor;
  131. #endif
  132. #if ENABLED(SKEW_CORRECTION_FOR_Z) && ENABLED(SKEW_CORRECTION_GCODE)
  133. float Planner::xz_skew_factor, Planner::yz_skew_factor;
  134. #else
  135. constexpr float Planner::xz_skew_factor, Planner::yz_skew_factor;
  136. #endif
  137. #endif
  138. #if ENABLED(AUTOTEMP)
  139. float Planner::autotemp_max = 250,
  140. Planner::autotemp_min = 210,
  141. Planner::autotemp_factor = 0.1;
  142. bool Planner::autotemp_enabled = false;
  143. #endif
  144. // private:
  145. int32_t Planner::position[NUM_AXIS] = { 0 };
  146. uint32_t Planner::cutoff_long;
  147. float Planner::previous_speed[NUM_AXIS],
  148. Planner::previous_nominal_speed;
  149. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  150. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  151. #endif
  152. #ifdef XY_FREQUENCY_LIMIT
  153. // Old direction bits. Used for speed calculations
  154. unsigned char Planner::old_direction_bits = 0;
  155. // Segment times (in µs). Used for speed calculations
  156. uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
  157. #endif
  158. #if ENABLED(LIN_ADVANCE)
  159. float Planner::extruder_advance_K, // Initialized by settings.load()
  160. Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
  161. #endif
  162. #if ENABLED(ULTRA_LCD)
  163. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  164. #endif
  165. /**
  166. * Class and Instance Methods
  167. */
  168. Planner::Planner() { init(); }
  169. void Planner::init() {
  170. block_buffer_head = block_buffer_tail = 0;
  171. ZERO(position);
  172. #if ENABLED(LIN_ADVANCE)
  173. ZERO(position_float);
  174. #endif
  175. ZERO(previous_speed);
  176. previous_nominal_speed = 0.0;
  177. #if ABL_PLANAR
  178. bed_level_matrix.set_to_identity();
  179. #endif
  180. }
  181. #define MINIMAL_STEP_RATE 120
  182. /**
  183. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  184. * by the provided factors.
  185. */
  186. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  187. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  188. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  189. // Limit minimal step rate (Otherwise the timer will overflow.)
  190. NOLESS(initial_rate, MINIMAL_STEP_RATE);
  191. NOLESS(final_rate, MINIMAL_STEP_RATE);
  192. const int32_t accel = block->acceleration_steps_per_s2;
  193. // Steps required for acceleration, deceleration to/from nominal rate
  194. int32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  195. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel)),
  196. // Steps between acceleration and deceleration, if any
  197. plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  198. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  199. // Then we can't possibly reach the nominal rate, there will be no cruising.
  200. // Use intersection_distance() to calculate accel / braking time in order to
  201. // reach the final_rate exactly at the end of this block.
  202. if (plateau_steps < 0) {
  203. accelerate_steps = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  204. NOLESS(accelerate_steps, 0); // Check limits due to numerical round-off
  205. 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)
  206. plateau_steps = 0;
  207. }
  208. // block->accelerate_until = accelerate_steps;
  209. // block->decelerate_after = accelerate_steps+plateau_steps;
  210. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  211. if (!TEST(block->flag, BLOCK_BIT_BUSY)) { // Don't update variables if block is busy.
  212. block->accelerate_until = accelerate_steps;
  213. block->decelerate_after = accelerate_steps + plateau_steps;
  214. block->initial_rate = initial_rate;
  215. block->final_rate = final_rate;
  216. }
  217. CRITICAL_SECTION_END;
  218. }
  219. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  220. // This method will calculate the junction jerk as the euclidean distance between the nominal
  221. // velocities of the respective blocks.
  222. //inline float junction_jerk(block_t *before, block_t *after) {
  223. // return SQRT(
  224. // POW((before->speed_x-after->speed_x), 2)+POW((before->speed_y-after->speed_y), 2));
  225. //}
  226. // The kernel called by recalculate() when scanning the plan from last to first entry.
  227. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  228. if (!current || !next) return;
  229. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  230. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  231. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  232. float max_entry_speed = current->max_entry_speed;
  233. if (current->entry_speed != max_entry_speed) {
  234. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  235. // for max allowable speed if block is decelerating and nominal length is false.
  236. current->entry_speed = (TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH) || max_entry_speed <= next->entry_speed)
  237. ? max_entry_speed
  238. : min(max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  239. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  240. }
  241. }
  242. /**
  243. * recalculate() needs to go over the current plan twice.
  244. * Once in reverse and once forward. This implements the reverse pass.
  245. */
  246. void Planner::reverse_pass() {
  247. if (movesplanned() > 2) {
  248. const uint8_t endnr = BLOCK_MOD(block_buffer_tail + 1); // tail is running. tail+1 shouldn't be altered because it's connected to the running block.
  249. uint8_t blocknr = prev_block_index(block_buffer_head);
  250. block_t* current = &block_buffer[blocknr];
  251. // Last/newest block in buffer:
  252. const float max_entry_speed = current->max_entry_speed;
  253. if (current->entry_speed != max_entry_speed) {
  254. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  255. // for max allowable speed if block is decelerating and nominal length is false.
  256. current->entry_speed = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  257. ? max_entry_speed
  258. : min(max_entry_speed, max_allowable_speed(-current->acceleration, MINIMUM_PLANNER_SPEED, current->millimeters));
  259. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  260. }
  261. do {
  262. const block_t * const next = current;
  263. blocknr = prev_block_index(blocknr);
  264. current = &block_buffer[blocknr];
  265. reverse_pass_kernel(current, next);
  266. } while (blocknr != endnr);
  267. }
  268. }
  269. // The kernel called by recalculate() when scanning the plan from first to last entry.
  270. void Planner::forward_pass_kernel(const block_t * const previous, block_t* const current) {
  271. if (!previous) return;
  272. // If the previous block is an acceleration block, but it is not long enough to complete the
  273. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  274. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  275. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  276. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH)) {
  277. if (previous->entry_speed < current->entry_speed) {
  278. float entry_speed = min(current->entry_speed,
  279. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  280. // Check for junction speed change
  281. if (current->entry_speed != entry_speed) {
  282. current->entry_speed = entry_speed;
  283. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  284. }
  285. }
  286. }
  287. }
  288. /**
  289. * recalculate() needs to go over the current plan twice.
  290. * Once in reverse and once forward. This implements the forward pass.
  291. */
  292. void Planner::forward_pass() {
  293. block_t* block[3] = { NULL, NULL, NULL };
  294. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  295. block[0] = block[1];
  296. block[1] = block[2];
  297. block[2] = &block_buffer[b];
  298. forward_pass_kernel(block[0], block[1]);
  299. }
  300. forward_pass_kernel(block[1], block[2]);
  301. }
  302. /**
  303. * Recalculate the trapezoid speed profiles for all blocks in the plan
  304. * according to the entry_factor for each junction. Must be called by
  305. * recalculate() after updating the blocks.
  306. */
  307. void Planner::recalculate_trapezoids() {
  308. int8_t block_index = block_buffer_tail;
  309. block_t *current, *next = NULL;
  310. while (block_index != block_buffer_head) {
  311. current = next;
  312. next = &block_buffer[block_index];
  313. if (current) {
  314. // Recalculate if current block entry or exit junction speed has changed.
  315. if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  316. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  317. const float nomr = 1.0 / current->nominal_speed;
  318. calculate_trapezoid_for_block(current, current->entry_speed * nomr, next->entry_speed * nomr);
  319. #if ENABLED(LIN_ADVANCE)
  320. if (current->use_advance_lead) {
  321. const float comp = current->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  322. current->max_adv_steps = current->nominal_speed * comp;
  323. current->final_adv_steps = next->entry_speed * comp;
  324. }
  325. #endif
  326. CBI(current->flag, BLOCK_BIT_RECALCULATE); // Reset current only to ensure next trapezoid is computed
  327. }
  328. }
  329. block_index = next_block_index(block_index);
  330. }
  331. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  332. if (next) {
  333. const float nomr = 1.0 / next->nominal_speed;
  334. calculate_trapezoid_for_block(next, next->entry_speed * nomr, (MINIMUM_PLANNER_SPEED) * nomr);
  335. #if ENABLED(LIN_ADVANCE)
  336. if (next->use_advance_lead) {
  337. const float comp = next->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  338. next->max_adv_steps = next->nominal_speed * comp;
  339. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  340. }
  341. #endif
  342. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  343. }
  344. }
  345. /**
  346. * Recalculate the motion plan according to the following algorithm:
  347. *
  348. * 1. Go over every block in reverse order...
  349. *
  350. * Calculate a junction speed reduction (block_t.entry_factor) so:
  351. *
  352. * a. The junction jerk is within the set limit, and
  353. *
  354. * b. No speed reduction within one block requires faster
  355. * deceleration than the one, true constant acceleration.
  356. *
  357. * 2. Go over every block in chronological order...
  358. *
  359. * Dial down junction speed reduction values if:
  360. * a. The speed increase within one block would require faster
  361. * acceleration than the one, true constant acceleration.
  362. *
  363. * After that, all blocks will have an entry_factor allowing all speed changes to
  364. * be performed using only the one, true constant acceleration, and where no junction
  365. * jerk is jerkier than the set limit, Jerky. Finally it will:
  366. *
  367. * 3. Recalculate "trapezoids" for all blocks.
  368. */
  369. void Planner::recalculate() {
  370. reverse_pass();
  371. forward_pass();
  372. recalculate_trapezoids();
  373. }
  374. #if ENABLED(AUTOTEMP)
  375. void Planner::getHighESpeed() {
  376. static float oldt = 0;
  377. if (!autotemp_enabled) return;
  378. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  379. float high = 0.0;
  380. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  381. block_t* block = &block_buffer[b];
  382. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  383. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  384. NOLESS(high, se);
  385. }
  386. }
  387. float t = autotemp_min + high * autotemp_factor;
  388. t = constrain(t, autotemp_min, autotemp_max);
  389. if (t < oldt) t = t * (1 - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT);
  390. oldt = t;
  391. thermalManager.setTargetHotend(t, 0);
  392. }
  393. #endif // AUTOTEMP
  394. /**
  395. * Maintain fans, paste extruder pressure,
  396. */
  397. void Planner::check_axes_activity() {
  398. unsigned char axis_active[NUM_AXIS] = { 0 },
  399. tail_fan_speed[FAN_COUNT];
  400. #if ENABLED(BARICUDA)
  401. #if HAS_HEATER_1
  402. uint8_t tail_valve_pressure;
  403. #endif
  404. #if HAS_HEATER_2
  405. uint8_t tail_e_to_p_pressure;
  406. #endif
  407. #endif
  408. if (has_blocks_queued()) {
  409. #if FAN_COUNT > 0
  410. for (uint8_t i = 0; i < FAN_COUNT; i++)
  411. tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  412. #endif
  413. block_t* block;
  414. #if ENABLED(BARICUDA)
  415. block = &block_buffer[block_buffer_tail];
  416. #if HAS_HEATER_1
  417. tail_valve_pressure = block->valve_pressure;
  418. #endif
  419. #if HAS_HEATER_2
  420. tail_e_to_p_pressure = block->e_to_p_pressure;
  421. #endif
  422. #endif
  423. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  424. block = &block_buffer[b];
  425. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  426. }
  427. }
  428. else {
  429. #if FAN_COUNT > 0
  430. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  431. #endif
  432. #if ENABLED(BARICUDA)
  433. #if HAS_HEATER_1
  434. tail_valve_pressure = baricuda_valve_pressure;
  435. #endif
  436. #if HAS_HEATER_2
  437. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  438. #endif
  439. #endif
  440. }
  441. #if ENABLED(DISABLE_X)
  442. if (!axis_active[X_AXIS]) disable_X();
  443. #endif
  444. #if ENABLED(DISABLE_Y)
  445. if (!axis_active[Y_AXIS]) disable_Y();
  446. #endif
  447. #if ENABLED(DISABLE_Z)
  448. if (!axis_active[Z_AXIS]) disable_Z();
  449. #endif
  450. #if ENABLED(DISABLE_E)
  451. if (!axis_active[E_AXIS]) disable_e_steppers();
  452. #endif
  453. #if FAN_COUNT > 0
  454. #if FAN_KICKSTART_TIME > 0
  455. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  456. #define KICKSTART_FAN(f) \
  457. if (tail_fan_speed[f]) { \
  458. millis_t ms = millis(); \
  459. if (fan_kick_end[f] == 0) { \
  460. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  461. tail_fan_speed[f] = 255; \
  462. } else if (PENDING(ms, fan_kick_end[f])) \
  463. tail_fan_speed[f] = 255; \
  464. } else fan_kick_end[f] = 0
  465. #if HAS_FAN0
  466. KICKSTART_FAN(0);
  467. #endif
  468. #if HAS_FAN1
  469. KICKSTART_FAN(1);
  470. #endif
  471. #if HAS_FAN2
  472. KICKSTART_FAN(2);
  473. #endif
  474. #endif // FAN_KICKSTART_TIME > 0
  475. #ifdef FAN_MIN_PWM
  476. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  477. #else
  478. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  479. #endif
  480. #if ENABLED(FAN_SOFT_PWM)
  481. #if HAS_FAN0
  482. thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
  483. #endif
  484. #if HAS_FAN1
  485. thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
  486. #endif
  487. #if HAS_FAN2
  488. thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
  489. #endif
  490. #else
  491. #if HAS_FAN0
  492. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  493. #endif
  494. #if HAS_FAN1
  495. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  496. #endif
  497. #if HAS_FAN2
  498. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  499. #endif
  500. #endif
  501. #endif // FAN_COUNT > 0
  502. #if ENABLED(AUTOTEMP)
  503. getHighESpeed();
  504. #endif
  505. #if ENABLED(BARICUDA)
  506. #if HAS_HEATER_1
  507. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  508. #endif
  509. #if HAS_HEATER_2
  510. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  511. #endif
  512. #endif
  513. }
  514. #if DISABLED(NO_VOLUMETRICS)
  515. /**
  516. * Get a volumetric multiplier from a filament diameter.
  517. * This is the reciprocal of the circular cross-section area.
  518. * Return 1.0 with volumetric off or a diameter of 0.0.
  519. */
  520. inline float calculate_volumetric_multiplier(const float &diameter) {
  521. return (parser.volumetric_enabled && diameter) ? 1.0 / CIRCLE_AREA(diameter * 0.5) : 1.0;
  522. }
  523. /**
  524. * Convert the filament sizes into volumetric multipliers.
  525. * The multiplier converts a given E value into a length.
  526. */
  527. void Planner::calculate_volumetric_multipliers() {
  528. for (uint8_t i = 0; i < COUNT(filament_size); i++) {
  529. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  530. refresh_e_factor(i);
  531. }
  532. }
  533. #endif // !NO_VOLUMETRICS
  534. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  535. /**
  536. * Convert the ratio value given by the filament width sensor
  537. * into a volumetric multiplier. Conversion differs when using
  538. * linear extrusion vs volumetric extrusion.
  539. */
  540. void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
  541. // Reconstitute the nominal/measured ratio
  542. const float nom_meas_ratio = 1.0 + 0.01 * encoded_ratio,
  543. ratio_2 = sq(nom_meas_ratio);
  544. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  545. ? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5) // Volumetric uses a true volumetric multiplier
  546. : ratio_2; // Linear squares the ratio, which scales the volume
  547. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  548. }
  549. #endif
  550. #if PLANNER_LEVELING
  551. /**
  552. * rx, ry, rz - Cartesian positions in mm
  553. * Leveled XYZ on completion
  554. */
  555. void Planner::apply_leveling(float &rx, float &ry, float &rz) {
  556. #if ENABLED(SKEW_CORRECTION)
  557. skew(rx, ry, rz);
  558. #endif
  559. if (!leveling_active) return;
  560. #if ABL_PLANAR
  561. float dx = rx - (X_TILT_FULCRUM),
  562. dy = ry - (Y_TILT_FULCRUM);
  563. apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
  564. rx = dx + X_TILT_FULCRUM;
  565. ry = dy + Y_TILT_FULCRUM;
  566. #elif HAS_MESH
  567. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  568. const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
  569. #else
  570. constexpr float fade_scaling_factor = 1.0;
  571. #endif
  572. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  573. const float raw[XYZ] = { rx, ry, 0 };
  574. #endif
  575. rz += (
  576. #if ENABLED(MESH_BED_LEVELING)
  577. mbl.get_z(rx, ry
  578. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  579. , fade_scaling_factor
  580. #endif
  581. )
  582. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  583. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
  584. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  585. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  586. #endif
  587. );
  588. #endif
  589. }
  590. void Planner::unapply_leveling(float raw[XYZ]) {
  591. if (leveling_active) {
  592. #if ABL_PLANAR
  593. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  594. float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
  595. dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
  596. apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
  597. raw[X_AXIS] = dx + X_TILT_FULCRUM;
  598. raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
  599. #elif HAS_MESH
  600. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  601. const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
  602. #else
  603. constexpr float fade_scaling_factor = 1.0;
  604. #endif
  605. raw[Z_AXIS] -= (
  606. #if ENABLED(MESH_BED_LEVELING)
  607. mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
  608. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  609. , fade_scaling_factor
  610. #endif
  611. )
  612. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  613. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
  614. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  615. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  616. #endif
  617. );
  618. #endif
  619. }
  620. #if ENABLED(SKEW_CORRECTION)
  621. unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
  622. #endif
  623. }
  624. #endif // PLANNER_LEVELING
  625. /**
  626. * Planner::_buffer_steps
  627. *
  628. * Add a new linear movement to the buffer (in terms of steps).
  629. *
  630. * target - target position in steps units
  631. * fr_mm_s - (target) speed of the move
  632. * extruder - target extruder
  633. */
  634. void Planner::_buffer_steps(const int32_t (&target)[XYZE]
  635. #if ENABLED(LIN_ADVANCE)
  636. , const float (&target_float)[XYZE]
  637. #endif
  638. , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  639. ) {
  640. const int32_t da = target[A_AXIS] - position[A_AXIS],
  641. db = target[B_AXIS] - position[B_AXIS],
  642. dc = target[C_AXIS] - position[C_AXIS];
  643. int32_t de = target[E_AXIS] - position[E_AXIS];
  644. /* <-- add a slash to enable
  645. SERIAL_ECHOPAIR(" _buffer_steps FR:", fr_mm_s);
  646. SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
  647. SERIAL_ECHOPAIR(" (", da);
  648. SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
  649. SERIAL_ECHOPAIR(" (", db);
  650. SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
  651. SERIAL_ECHOPAIR(" (", dc);
  652. SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
  653. SERIAL_ECHOPAIR(" (", de);
  654. SERIAL_ECHOLNPGM(" steps)");
  655. //*/
  656. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  657. if (de) {
  658. #if ENABLED(PREVENT_COLD_EXTRUSION)
  659. if (thermalManager.tooColdToExtrude(extruder)) {
  660. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  661. #if ENABLED(LIN_ADVANCE)
  662. position_float[E_AXIS] = target_float[E_AXIS];
  663. #endif
  664. de = 0; // no difference
  665. SERIAL_ECHO_START();
  666. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  667. }
  668. #endif // PREVENT_COLD_EXTRUSION
  669. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  670. if (labs(de * e_factor[extruder]) > (int32_t)axis_steps_per_mm[E_AXIS_N] * (EXTRUDE_MAXLENGTH)) { // It's not important to get max. extrusion length in a precision < 1mm, so save some cycles and cast to int
  671. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  672. #if ENABLED(LIN_ADVANCE)
  673. position_float[E_AXIS] = target_float[E_AXIS];
  674. #endif
  675. de = 0; // no difference
  676. SERIAL_ECHO_START();
  677. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  678. }
  679. #endif // PREVENT_LENGTHY_EXTRUDE
  680. }
  681. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  682. // Compute direction bit-mask for this block
  683. uint8_t dm = 0;
  684. #if CORE_IS_XY
  685. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  686. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  687. if (dc < 0) SBI(dm, Z_AXIS);
  688. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  689. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  690. #elif CORE_IS_XZ
  691. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  692. if (db < 0) SBI(dm, Y_AXIS);
  693. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  694. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  695. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  696. #elif CORE_IS_YZ
  697. if (da < 0) SBI(dm, X_AXIS);
  698. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  699. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  700. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  701. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  702. #else
  703. if (da < 0) SBI(dm, X_AXIS);
  704. if (db < 0) SBI(dm, Y_AXIS);
  705. if (dc < 0) SBI(dm, Z_AXIS);
  706. #endif
  707. if (de < 0) SBI(dm, E_AXIS);
  708. const float esteps_float = de * e_factor[extruder];
  709. const int32_t esteps = abs(esteps_float) + 0.5;
  710. // Calculate the buffer head after we push this byte
  711. const uint8_t next_buffer_head = next_block_index(block_buffer_head);
  712. // If the buffer is full: good! That means we are well ahead of the robot.
  713. // Rest here until there is room in the buffer.
  714. while (block_buffer_tail == next_buffer_head) idle();
  715. // Prepare to set up new block
  716. block_t* block = &block_buffer[block_buffer_head];
  717. // Clear all flags, including the "busy" bit
  718. block->flag = 0x00;
  719. // Set direction bits
  720. block->direction_bits = dm;
  721. // Number of steps for each axis
  722. // See http://www.corexy.com/theory.html
  723. #if CORE_IS_XY
  724. block->steps[A_AXIS] = labs(da + db);
  725. block->steps[B_AXIS] = labs(da - db);
  726. block->steps[Z_AXIS] = labs(dc);
  727. #elif CORE_IS_XZ
  728. block->steps[A_AXIS] = labs(da + dc);
  729. block->steps[Y_AXIS] = labs(db);
  730. block->steps[C_AXIS] = labs(da - dc);
  731. #elif CORE_IS_YZ
  732. block->steps[X_AXIS] = labs(da);
  733. block->steps[B_AXIS] = labs(db + dc);
  734. block->steps[C_AXIS] = labs(db - dc);
  735. #else
  736. // default non-h-bot planning
  737. block->steps[A_AXIS] = labs(da);
  738. block->steps[B_AXIS] = labs(db);
  739. block->steps[C_AXIS] = labs(dc);
  740. #endif
  741. block->steps[E_AXIS] = esteps;
  742. block->step_event_count = MAX4(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
  743. // Bail if this is a zero-length block
  744. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return;
  745. // For a mixing extruder, get a magnified step_event_count for each
  746. #if ENABLED(MIXING_EXTRUDER)
  747. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  748. block->mix_event_count[i] = mixing_factor[i] * block->step_event_count;
  749. #endif
  750. #if FAN_COUNT > 0
  751. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  752. #endif
  753. #if ENABLED(BARICUDA)
  754. block->valve_pressure = baricuda_valve_pressure;
  755. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  756. #endif
  757. block->active_extruder = extruder;
  758. #if ENABLED(AUTO_POWER_CONTROL)
  759. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
  760. powerManager.power_on();
  761. #endif
  762. //enable active axes
  763. #if CORE_IS_XY
  764. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  765. enable_X();
  766. enable_Y();
  767. }
  768. #if DISABLED(Z_LATE_ENABLE)
  769. if (block->steps[Z_AXIS]) enable_Z();
  770. #endif
  771. #elif CORE_IS_XZ
  772. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  773. enable_X();
  774. enable_Z();
  775. }
  776. if (block->steps[Y_AXIS]) enable_Y();
  777. #elif CORE_IS_YZ
  778. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  779. enable_Y();
  780. enable_Z();
  781. }
  782. if (block->steps[X_AXIS]) enable_X();
  783. #else
  784. if (block->steps[X_AXIS]) enable_X();
  785. if (block->steps[Y_AXIS]) enable_Y();
  786. #if DISABLED(Z_LATE_ENABLE)
  787. if (block->steps[Z_AXIS]) enable_Z();
  788. #endif
  789. #endif
  790. // Enable extruder(s)
  791. if (esteps) {
  792. #if ENABLED(AUTO_POWER_CONTROL)
  793. powerManager.power_on();
  794. #endif
  795. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  796. #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
  797. for (uint8_t i = 0; i < EXTRUDERS; i++)
  798. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  799. switch (extruder) {
  800. case 0:
  801. #if EXTRUDERS > 1
  802. DISABLE_IDLE_E(1);
  803. #if EXTRUDERS > 2
  804. DISABLE_IDLE_E(2);
  805. #if EXTRUDERS > 3
  806. DISABLE_IDLE_E(3);
  807. #if EXTRUDERS > 4
  808. DISABLE_IDLE_E(4);
  809. #endif // EXTRUDERS > 4
  810. #endif // EXTRUDERS > 3
  811. #endif // EXTRUDERS > 2
  812. #endif // EXTRUDERS > 1
  813. enable_E0();
  814. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  815. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  816. if (extruder_duplication_enabled) {
  817. enable_E1();
  818. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  819. }
  820. #endif
  821. break;
  822. #if EXTRUDERS > 1
  823. case 1:
  824. DISABLE_IDLE_E(0);
  825. #if EXTRUDERS > 2
  826. DISABLE_IDLE_E(2);
  827. #if EXTRUDERS > 3
  828. DISABLE_IDLE_E(3);
  829. #if EXTRUDERS > 4
  830. DISABLE_IDLE_E(4);
  831. #endif // EXTRUDERS > 4
  832. #endif // EXTRUDERS > 3
  833. #endif // EXTRUDERS > 2
  834. enable_E1();
  835. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  836. break;
  837. #if EXTRUDERS > 2
  838. case 2:
  839. DISABLE_IDLE_E(0);
  840. DISABLE_IDLE_E(1);
  841. #if EXTRUDERS > 3
  842. DISABLE_IDLE_E(3);
  843. #if EXTRUDERS > 4
  844. DISABLE_IDLE_E(4);
  845. #endif
  846. #endif
  847. enable_E2();
  848. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  849. break;
  850. #if EXTRUDERS > 3
  851. case 3:
  852. DISABLE_IDLE_E(0);
  853. DISABLE_IDLE_E(1);
  854. DISABLE_IDLE_E(2);
  855. #if EXTRUDERS > 4
  856. DISABLE_IDLE_E(4);
  857. #endif
  858. enable_E3();
  859. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  860. break;
  861. #if EXTRUDERS > 4
  862. case 4:
  863. DISABLE_IDLE_E(0);
  864. DISABLE_IDLE_E(1);
  865. DISABLE_IDLE_E(2);
  866. DISABLE_IDLE_E(3);
  867. enable_E4();
  868. g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
  869. break;
  870. #endif // EXTRUDERS > 4
  871. #endif // EXTRUDERS > 3
  872. #endif // EXTRUDERS > 2
  873. #endif // EXTRUDERS > 1
  874. }
  875. #else
  876. enable_E0();
  877. enable_E1();
  878. enable_E2();
  879. enable_E3();
  880. enable_E4();
  881. #endif
  882. }
  883. if (esteps)
  884. NOLESS(fr_mm_s, min_feedrate_mm_s);
  885. else
  886. NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
  887. /**
  888. * This part of the code calculates the total length of the movement.
  889. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  890. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  891. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  892. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  893. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  894. */
  895. #if IS_CORE
  896. float delta_mm[Z_HEAD + 1];
  897. #if CORE_IS_XY
  898. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  899. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  900. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  901. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  902. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  903. #elif CORE_IS_XZ
  904. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  905. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  906. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  907. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  908. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  909. #elif CORE_IS_YZ
  910. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  911. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  912. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  913. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  914. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  915. #endif
  916. #else
  917. float delta_mm[ABCE];
  918. delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
  919. delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
  920. delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
  921. #endif
  922. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N];
  923. if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT) {
  924. block->millimeters = FABS(delta_mm[E_AXIS]);
  925. }
  926. else if (!millimeters) {
  927. block->millimeters = SQRT(
  928. #if CORE_IS_XY
  929. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  930. #elif CORE_IS_XZ
  931. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  932. #elif CORE_IS_YZ
  933. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  934. #else
  935. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  936. #endif
  937. );
  938. }
  939. else
  940. block->millimeters = millimeters;
  941. const float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  942. // Calculate inverse time for this move. No divide by zero due to previous checks.
  943. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  944. float inverse_secs = fr_mm_s * inverse_millimeters;
  945. const uint8_t moves_queued = movesplanned();
  946. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  947. #if ENABLED(SLOWDOWN) || ENABLED(ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  948. // Segment time im micro seconds
  949. uint32_t segment_time_us = LROUND(1000000.0 / inverse_secs);
  950. #endif
  951. #if ENABLED(SLOWDOWN)
  952. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
  953. if (segment_time_us < min_segment_time_us) {
  954. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  955. const uint32_t nst = segment_time_us + LROUND(2 * (min_segment_time_us - segment_time_us) / moves_queued);
  956. inverse_secs = 1000000.0 / nst;
  957. #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
  958. segment_time_us = nst;
  959. #endif
  960. }
  961. }
  962. #endif
  963. #if ENABLED(ULTRA_LCD)
  964. CRITICAL_SECTION_START
  965. block_buffer_runtime_us += segment_time_us;
  966. CRITICAL_SECTION_END
  967. #endif
  968. block->nominal_speed = block->millimeters * inverse_secs; // (mm/sec) Always > 0
  969. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  970. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  971. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  972. //FMM update ring buffer used for delay with filament measurements
  973. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  974. constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  975. // increment counters with next move in e axis
  976. filwidth_e_count += delta_mm[E_AXIS];
  977. filwidth_delay_dist += delta_mm[E_AXIS];
  978. // Only get new measurements on forward E movement
  979. if (!UNEAR_ZERO(filwidth_e_count)) {
  980. // Loop the delay distance counter (modulus by the mm length)
  981. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  982. // Convert into an index into the measurement array
  983. filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1);
  984. // If the index has changed (must have gone forward)...
  985. if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
  986. filwidth_e_count = 0; // Reset the E movement counter
  987. const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
  988. do {
  989. filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
  990. measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
  991. } while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
  992. }
  993. }
  994. }
  995. #endif
  996. // Calculate and limit speed in mm/sec for each axis
  997. float current_speed[NUM_AXIS], speed_factor = 1.0; // factor <1 decreases speed
  998. LOOP_XYZE(i) {
  999. const float cs = FABS((current_speed[i] = delta_mm[i] * inverse_secs));
  1000. #if ENABLED(DISTINCT_E_FACTORS)
  1001. if (i == E_AXIS) i += extruder;
  1002. #endif
  1003. if (cs > max_feedrate_mm_s[i]) NOMORE(speed_factor, max_feedrate_mm_s[i] / cs);
  1004. }
  1005. // Max segment time in µs.
  1006. #ifdef XY_FREQUENCY_LIMIT
  1007. // Check and limit the xy direction change frequency
  1008. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1009. old_direction_bits = block->direction_bits;
  1010. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1011. uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
  1012. xs1 = axis_segment_time_us[X_AXIS][1],
  1013. xs2 = axis_segment_time_us[X_AXIS][2],
  1014. ys0 = axis_segment_time_us[Y_AXIS][0],
  1015. ys1 = axis_segment_time_us[Y_AXIS][1],
  1016. ys2 = axis_segment_time_us[Y_AXIS][2];
  1017. if (TEST(direction_change, X_AXIS)) {
  1018. xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
  1019. xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
  1020. xs0 = 0;
  1021. }
  1022. xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
  1023. if (TEST(direction_change, Y_AXIS)) {
  1024. ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
  1025. ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
  1026. ys0 = 0;
  1027. }
  1028. ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
  1029. const uint32_t max_x_segment_time = MAX3(xs0, xs1, xs2),
  1030. max_y_segment_time = MAX3(ys0, ys1, ys2),
  1031. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  1032. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1033. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1034. NOMORE(speed_factor, low_sf);
  1035. }
  1036. #endif // XY_FREQUENCY_LIMIT
  1037. // Correct the speed
  1038. if (speed_factor < 1.0) {
  1039. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  1040. block->nominal_speed *= speed_factor;
  1041. block->nominal_rate *= speed_factor;
  1042. }
  1043. // Compute and limit the acceleration rate for the trapezoid generator.
  1044. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1045. uint32_t accel;
  1046. if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
  1047. // convert to: acceleration steps/sec^2
  1048. accel = CEIL(retract_acceleration * steps_per_mm);
  1049. #if ENABLED(LIN_ADVANCE)
  1050. block->use_advance_lead = false;
  1051. #endif
  1052. }
  1053. else {
  1054. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1055. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1056. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1057. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1058. } \
  1059. }while(0)
  1060. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1061. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1062. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1063. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1064. } \
  1065. }while(0)
  1066. // Start with print or travel acceleration
  1067. accel = CEIL((esteps ? acceleration : travel_acceleration) * steps_per_mm);
  1068. #if ENABLED(LIN_ADVANCE)
  1069. /**
  1070. *
  1071. * Use LIN_ADVANCE for blocks if all these are true:
  1072. *
  1073. * esteps : This is a print move, because we checked for A, B, C steps before.
  1074. *
  1075. * extruder_advance_K : There is an advance factor set.
  1076. *
  1077. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1078. */
  1079. block->use_advance_lead = esteps
  1080. && extruder_advance_K
  1081. && de > 0;
  1082. if (block->use_advance_lead) {
  1083. block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
  1084. #if IS_KINEMATIC
  1085. block->millimeters
  1086. #else
  1087. SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
  1088. + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
  1089. + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
  1090. #endif
  1091. ;
  1092. // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
  1093. // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
  1094. if (block->e_D_ratio > 3.0)
  1095. block->use_advance_lead = false;
  1096. else {
  1097. const uint32_t max_accel_steps_per_s2 = max_jerk[E_AXIS] / (extruder_advance_K * block->e_D_ratio) * steps_per_mm;
  1098. #if ENABLED(LA_DEBUG)
  1099. if (accel > max_accel_steps_per_s2)
  1100. SERIAL_ECHOLNPGM("Acceleration limited.");
  1101. #endif
  1102. NOMORE(accel, max_accel_steps_per_s2);
  1103. }
  1104. }
  1105. #endif
  1106. #if ENABLED(DISTINCT_E_FACTORS)
  1107. #define ACCEL_IDX extruder
  1108. #else
  1109. #define ACCEL_IDX 0
  1110. #endif
  1111. // Limit acceleration per axis
  1112. if (block->step_event_count <= cutoff_long) {
  1113. LIMIT_ACCEL_LONG(A_AXIS, 0);
  1114. LIMIT_ACCEL_LONG(B_AXIS, 0);
  1115. LIMIT_ACCEL_LONG(C_AXIS, 0);
  1116. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  1117. }
  1118. else {
  1119. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  1120. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  1121. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  1122. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  1123. }
  1124. }
  1125. block->acceleration_steps_per_s2 = accel;
  1126. block->acceleration = accel / steps_per_mm;
  1127. block->acceleration_rate = (long)(accel * (4096.0 * 4096.0 / (HAL_STEPPER_TIMER_RATE)));
  1128. #if ENABLED(LIN_ADVANCE)
  1129. if (block->use_advance_lead) {
  1130. block->advance_speed = (HAL_STEPPER_TIMER_RATE) / (extruder_advance_K * block->e_D_ratio * block->acceleration * axis_steps_per_mm[E_AXIS_N]);
  1131. #if ENABLED(LA_DEBUG)
  1132. if (extruder_advance_K * block->e_D_ratio * block->acceleration * 2 < block->nominal_speed * block->e_D_ratio)
  1133. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  1134. if (block->advance_speed < 200)
  1135. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  1136. #endif
  1137. }
  1138. #endif
  1139. // Initial limit on the segment entry velocity
  1140. float vmax_junction;
  1141. #if 0 // Use old jerk for now
  1142. float junction_deviation = 0.1;
  1143. // Compute path unit vector
  1144. double unit_vec[XYZ] = {
  1145. delta_mm[A_AXIS] * inverse_millimeters,
  1146. delta_mm[B_AXIS] * inverse_millimeters,
  1147. delta_mm[C_AXIS] * inverse_millimeters
  1148. };
  1149. /*
  1150. Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  1151. Let a circle be tangent to both previous and current path line segments, where the junction
  1152. deviation is defined as the distance from the junction to the closest edge of the circle,
  1153. collinear with the circle center.
  1154. The circular segment joining the two paths represents the path of centripetal acceleration.
  1155. Solve for max velocity based on max acceleration about the radius of the circle, defined
  1156. indirectly by junction deviation.
  1157. This may be also viewed as path width or max_jerk in the previous grbl version. This approach
  1158. does not actually deviate from path, but used as a robust way to compute cornering speeds, as
  1159. it takes into account the nonlinearities of both the junction angle and junction velocity.
  1160. */
  1161. vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  1162. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  1163. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1164. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  1165. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  1166. const float cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  1167. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  1168. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS];
  1169. // Skip and use default max junction speed for 0 degree acute junction.
  1170. if (cos_theta < 0.95) {
  1171. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  1172. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  1173. if (cos_theta > -0.95) {
  1174. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  1175. float sin_theta_d2 = SQRT(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  1176. NOMORE(vmax_junction, SQRT(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  1177. }
  1178. }
  1179. }
  1180. #endif
  1181. /**
  1182. * Adapted from Průša MKS firmware
  1183. * https://github.com/prusa3d/Prusa-Firmware
  1184. *
  1185. * Start with a safe speed (from which the machine may halt to stop immediately).
  1186. */
  1187. // Exit speed limited by a jerk to full halt of a previous last segment
  1188. static float previous_safe_speed;
  1189. float safe_speed = block->nominal_speed;
  1190. uint8_t limited = 0;
  1191. LOOP_XYZE(i) {
  1192. const float jerk = FABS(current_speed[i]), maxj = max_jerk[i];
  1193. if (jerk > maxj) {
  1194. if (limited) {
  1195. const float mjerk = maxj * block->nominal_speed;
  1196. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk;
  1197. }
  1198. else {
  1199. ++limited;
  1200. safe_speed = maxj;
  1201. }
  1202. }
  1203. }
  1204. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1205. // Estimate a maximum velocity allowed at a joint of two successive segments.
  1206. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  1207. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  1208. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  1209. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  1210. vmax_junction = min(block->nominal_speed, previous_nominal_speed);
  1211. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  1212. float v_factor = 1;
  1213. limited = 0;
  1214. // Now limit the jerk in all axes.
  1215. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  1216. LOOP_XYZE(axis) {
  1217. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  1218. float v_exit = previous_speed[axis] * smaller_speed_factor,
  1219. v_entry = current_speed[axis];
  1220. if (limited) {
  1221. v_exit *= v_factor;
  1222. v_entry *= v_factor;
  1223. }
  1224. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  1225. const float jerk = (v_exit > v_entry)
  1226. ? // coasting axis reversal
  1227. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : max(v_exit, -v_entry) )
  1228. : // v_exit <= v_entry coasting axis reversal
  1229. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : max(-v_exit, v_entry) );
  1230. if (jerk > max_jerk[axis]) {
  1231. v_factor *= max_jerk[axis] / jerk;
  1232. ++limited;
  1233. }
  1234. }
  1235. if (limited) vmax_junction *= v_factor;
  1236. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  1237. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  1238. const float vmax_junction_threshold = vmax_junction * 0.99f;
  1239. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  1240. vmax_junction = safe_speed;
  1241. }
  1242. else
  1243. vmax_junction = safe_speed;
  1244. // Max entry speed of this block equals the max exit speed of the previous block.
  1245. block->max_entry_speed = vmax_junction;
  1246. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  1247. const float v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  1248. // If stepper ISR is disabled, this indicates buffer_segment wants to add a split block.
  1249. // In this case start with the max. allowed speed to avoid an interrupted first move.
  1250. block->entry_speed = STEPPER_ISR_ENABLED() ? MINIMUM_PLANNER_SPEED : min(vmax_junction, v_allowable);
  1251. // Initialize planner efficiency flags
  1252. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  1253. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  1254. // the current block and next block junction speeds are guaranteed to always be at their maximum
  1255. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  1256. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  1257. // the reverse and forward planners, the corresponding block junction speed will always be at the
  1258. // the maximum junction speed and may always be ignored for any speed reduction checks.
  1259. block->flag |= block->nominal_speed <= v_allowable ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  1260. // Update previous path unit_vector and nominal speed
  1261. COPY(previous_speed, current_speed);
  1262. previous_nominal_speed = block->nominal_speed;
  1263. previous_safe_speed = safe_speed;
  1264. // Move buffer head
  1265. block_buffer_head = next_buffer_head;
  1266. // Update the position (only when a move was queued)
  1267. static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
  1268. COPY(position, target);
  1269. #if ENABLED(LIN_ADVANCE)
  1270. COPY(position_float, target_float);
  1271. #endif
  1272. recalculate();
  1273. } // _buffer_steps()
  1274. /**
  1275. * Planner::buffer_segment
  1276. *
  1277. * Add a new linear movement to the buffer in axis units.
  1278. *
  1279. * Leveling and kinematics should be applied ahead of calling this.
  1280. *
  1281. * a,b,c,e - target positions in mm and/or degrees
  1282. * fr_mm_s - (target) speed of the move
  1283. * extruder - target extruder
  1284. * millimeters - the length of the movement, if known
  1285. */
  1286. void Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e, const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/) {
  1287. // When changing extruders recalculate steps corresponding to the E position
  1288. #if ENABLED(DISTINCT_E_FACTORS)
  1289. if (last_extruder != extruder && axis_steps_per_mm[E_AXIS_N] != axis_steps_per_mm[E_AXIS + last_extruder]) {
  1290. position[E_AXIS] = LROUND(position[E_AXIS] * axis_steps_per_mm[E_AXIS_N] * steps_to_mm[E_AXIS + last_extruder]);
  1291. last_extruder = extruder;
  1292. }
  1293. #endif
  1294. // The target position of the tool in absolute steps
  1295. // Calculate target position in absolute steps
  1296. const int32_t target[ABCE] = {
  1297. LROUND(a * axis_steps_per_mm[A_AXIS]),
  1298. LROUND(b * axis_steps_per_mm[B_AXIS]),
  1299. LROUND(c * axis_steps_per_mm[C_AXIS]),
  1300. LROUND(e * axis_steps_per_mm[E_AXIS_N])
  1301. };
  1302. #if ENABLED(LIN_ADVANCE)
  1303. const float target_float[XYZE] = { a, b, c, e };
  1304. #endif
  1305. // DRYRUN prevents E moves from taking place
  1306. if (DEBUGGING(DRYRUN)) {
  1307. position[E_AXIS] = target[E_AXIS];
  1308. #if ENABLED(LIN_ADVANCE)
  1309. position_float[E_AXIS] = e;
  1310. #endif
  1311. }
  1312. /* <-- add a slash to enable
  1313. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  1314. #if IS_KINEMATIC
  1315. SERIAL_ECHOPAIR(" A:", a);
  1316. SERIAL_ECHOPAIR(" (", position[A_AXIS]);
  1317. SERIAL_ECHOPAIR("->", target[A_AXIS]);
  1318. SERIAL_ECHOPAIR(") B:", b);
  1319. #else
  1320. SERIAL_ECHOPAIR(" X:", a);
  1321. SERIAL_ECHOPAIR(" (", position[X_AXIS]);
  1322. SERIAL_ECHOPAIR("->", target[X_AXIS]);
  1323. SERIAL_ECHOPAIR(") Y:", b);
  1324. #endif
  1325. SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
  1326. SERIAL_ECHOPAIR("->", target[Y_AXIS]);
  1327. #if ENABLED(DELTA)
  1328. SERIAL_ECHOPAIR(") C:", c);
  1329. #else
  1330. SERIAL_ECHOPAIR(") Z:", c);
  1331. #endif
  1332. SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
  1333. SERIAL_ECHOPAIR("->", target[Z_AXIS]);
  1334. SERIAL_ECHOPAIR(") E:", e);
  1335. SERIAL_ECHOPAIR(" (", position[E_AXIS]);
  1336. SERIAL_ECHOPAIR("->", target[E_AXIS]);
  1337. SERIAL_ECHOLNPGM(")");
  1338. //*/
  1339. // Always split the first move into two (if not homing or probing)
  1340. if (!has_blocks_queued()) {
  1341. #define _BETWEEN(A) (position[A##_AXIS] + target[A##_AXIS]) >> 1
  1342. const int32_t between[ABCE] = { _BETWEEN(A), _BETWEEN(B), _BETWEEN(C), _BETWEEN(E) };
  1343. #if ENABLED(LIN_ADVANCE)
  1344. #define _BETWEEN_F(A) (position_float[A##_AXIS] + target_float[A##_AXIS]) * 0.5
  1345. const float between_float[ABCE] = { _BETWEEN_F(A), _BETWEEN_F(B), _BETWEEN_F(C), _BETWEEN_F(E) };
  1346. #endif
  1347. DISABLE_STEPPER_DRIVER_INTERRUPT();
  1348. _buffer_steps(between
  1349. #if ENABLED(LIN_ADVANCE)
  1350. , between_float
  1351. #endif
  1352. , fr_mm_s, extruder, millimeters * 0.5
  1353. );
  1354. const uint8_t next = block_buffer_head;
  1355. _buffer_steps(target
  1356. #if ENABLED(LIN_ADVANCE)
  1357. , target_float
  1358. #endif
  1359. , fr_mm_s, extruder, millimeters * 0.5
  1360. );
  1361. SBI(block_buffer[next].flag, BLOCK_BIT_CONTINUED);
  1362. ENABLE_STEPPER_DRIVER_INTERRUPT();
  1363. }
  1364. else
  1365. _buffer_steps(target
  1366. #if ENABLED(LIN_ADVANCE)
  1367. , target_float
  1368. #endif
  1369. , fr_mm_s, extruder, millimeters
  1370. );
  1371. stepper.wake_up();
  1372. } // buffer_segment()
  1373. /**
  1374. * Directly set the planner XYZ position (and stepper positions)
  1375. * converting mm (or angles for SCARA) into steps.
  1376. *
  1377. * On CORE machines stepper ABC will be translated from the given XYZ.
  1378. */
  1379. void Planner::_set_position_mm(const float &a, const float &b, const float &c, const float &e) {
  1380. #if ENABLED(DISTINCT_E_FACTORS)
  1381. #define _EINDEX (E_AXIS + active_extruder)
  1382. last_extruder = active_extruder;
  1383. #else
  1384. #define _EINDEX E_AXIS
  1385. #endif
  1386. const int32_t na = position[A_AXIS] = LROUND(a * axis_steps_per_mm[A_AXIS]),
  1387. nb = position[B_AXIS] = LROUND(b * axis_steps_per_mm[B_AXIS]),
  1388. nc = position[C_AXIS] = LROUND(c * axis_steps_per_mm[C_AXIS]),
  1389. ne = position[E_AXIS] = LROUND(e * axis_steps_per_mm[_EINDEX]);
  1390. #if ENABLED(LIN_ADVANCE)
  1391. position_float[X_AXIS] = a;
  1392. position_float[Y_AXIS] = b;
  1393. position_float[Z_AXIS] = c;
  1394. position_float[E_AXIS] = e;
  1395. #endif
  1396. stepper.set_position(na, nb, nc, ne);
  1397. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1398. ZERO(previous_speed);
  1399. }
  1400. void Planner::set_position_mm_kinematic(const float (&cart)[XYZE]) {
  1401. #if PLANNER_LEVELING
  1402. float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  1403. apply_leveling(raw);
  1404. #else
  1405. const float (&raw)[XYZE] = cart;
  1406. #endif
  1407. #if IS_KINEMATIC
  1408. inverse_kinematics(raw);
  1409. _set_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_AXIS]);
  1410. #else
  1411. _set_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], cart[E_AXIS]);
  1412. #endif
  1413. }
  1414. /**
  1415. * Sync from the stepper positions. (e.g., after an interrupted move)
  1416. */
  1417. void Planner::sync_from_steppers() {
  1418. LOOP_XYZE(i) {
  1419. position[i] = stepper.position((AxisEnum)i);
  1420. #if ENABLED(LIN_ADVANCE)
  1421. position_float[i] = position[i] * steps_to_mm[i
  1422. #if ENABLED(DISTINCT_E_FACTORS)
  1423. + (i == E_AXIS ? active_extruder : 0)
  1424. #endif
  1425. ];
  1426. #endif
  1427. }
  1428. }
  1429. /**
  1430. * Setters for planner position (also setting stepper position).
  1431. */
  1432. void Planner::set_position_mm(const AxisEnum axis, const float &v) {
  1433. #if ENABLED(DISTINCT_E_FACTORS)
  1434. const uint8_t axis_index = axis + (axis == E_AXIS ? active_extruder : 0);
  1435. last_extruder = active_extruder;
  1436. #else
  1437. const uint8_t axis_index = axis;
  1438. #endif
  1439. position[axis] = LROUND(v * axis_steps_per_mm[axis_index]);
  1440. #if ENABLED(LIN_ADVANCE)
  1441. position_float[axis] = v;
  1442. #endif
  1443. stepper.set_position(axis, v);
  1444. previous_speed[axis] = 0.0;
  1445. }
  1446. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1447. void Planner::reset_acceleration_rates() {
  1448. #if ENABLED(DISTINCT_E_FACTORS)
  1449. #define HIGHEST_CONDITION (i < E_AXIS || i == E_AXIS + active_extruder)
  1450. #else
  1451. #define HIGHEST_CONDITION true
  1452. #endif
  1453. uint32_t highest_rate = 1;
  1454. LOOP_XYZE_N(i) {
  1455. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  1456. if (HIGHEST_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  1457. }
  1458. cutoff_long = 4294967295UL / highest_rate;
  1459. }
  1460. // Recalculate position, steps_to_mm if axis_steps_per_mm changes!
  1461. void Planner::refresh_positioning() {
  1462. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0 / axis_steps_per_mm[i];
  1463. set_position_mm_kinematic(current_position);
  1464. reset_acceleration_rates();
  1465. }
  1466. #if ENABLED(AUTOTEMP)
  1467. void Planner::autotemp_M104_M109() {
  1468. if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
  1469. if (parser.seen('S')) autotemp_min = parser.value_celsius();
  1470. if (parser.seen('B')) autotemp_max = parser.value_celsius();
  1471. }
  1472. #endif