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

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