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

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