My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

planner.cpp 49KB

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