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

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