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

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