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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161
  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 "Marlin.h"
  60. #include "planner.h"
  61. #include "stepper.h"
  62. #include "temperature.h"
  63. #include "ultralcd.h"
  64. #include "language.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[NUM_AXIS]; // Max speeds in mm per minute
  77. float Planner::axis_steps_per_unit[NUM_AXIS];
  78. unsigned long Planner::axis_steps_per_sqr_second[NUM_AXIS];
  79. unsigned long Planner::max_acceleration_units_per_sq_second[NUM_AXIS]; // Use M201 to override by software
  80. millis_t Planner::min_segment_time;
  81. float Planner::min_feedrate;
  82. float Planner::acceleration; // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  83. float Planner::retract_acceleration; // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  84. float Planner::travel_acceleration; // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  85. float Planner::max_xy_jerk; // The largest speed change requiring no acceleration
  86. float Planner::max_z_jerk;
  87. float Planner::max_e_jerk;
  88. float Planner::min_travel_feedrate;
  89. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  90. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  91. #endif
  92. #if ENABLED(AUTOTEMP)
  93. float Planner::autotemp_max = 250;
  94. float Planner::autotemp_min = 210;
  95. float Planner::autotemp_factor = 0.1;
  96. bool Planner::autotemp_enabled = false;
  97. #endif
  98. // private:
  99. long Planner::position[NUM_AXIS] = { 0 };
  100. float Planner::previous_speed[NUM_AXIS];
  101. float Planner::previous_nominal_speed;
  102. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  103. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  104. #endif // DISABLE_INACTIVE_EXTRUDER
  105. #ifdef XY_FREQUENCY_LIMIT
  106. // Old direction bits. Used for speed calculations
  107. unsigned char Planner::old_direction_bits = 0;
  108. // Segment times (in µs). Used for speed calculations
  109. long Planner::axis_segment_time[2][3] = { {MAX_FREQ_TIME + 1, 0, 0}, {MAX_FREQ_TIME + 1, 0, 0} };
  110. #endif
  111. /**
  112. * Class and Instance Methods
  113. */
  114. Planner::Planner() {
  115. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  116. bed_level_matrix.set_to_identity();
  117. #endif
  118. init();
  119. }
  120. void Planner::init() {
  121. block_buffer_head = block_buffer_tail = 0;
  122. memset(position, 0, sizeof(position)); // clear position
  123. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  124. previous_nominal_speed = 0.0;
  125. }
  126. /**
  127. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  128. * by the provided factors.
  129. */
  130. void Planner::calculate_trapezoid_for_block(block_t* block, float entry_factor, float exit_factor) {
  131. unsigned long initial_rate = ceil(block->nominal_rate * entry_factor),
  132. final_rate = ceil(block->nominal_rate * exit_factor); // (steps per second)
  133. // Limit minimal step rate (Otherwise the timer will overflow.)
  134. NOLESS(initial_rate, 120);
  135. NOLESS(final_rate, 120);
  136. long acceleration = block->acceleration_st;
  137. int32_t accelerate_steps = ceil(estimate_acceleration_distance(initial_rate, block->nominal_rate, acceleration));
  138. int32_t decelerate_steps = floor(estimate_acceleration_distance(block->nominal_rate, final_rate, -acceleration));
  139. // Calculate the size of Plateau of Nominal Rate.
  140. int32_t 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 acceleration 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, acceleration, block->step_event_count));
  146. accelerate_steps = max(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. #if ENABLED(ADVANCE)
  151. volatile long initial_advance = block->advance * entry_factor * entry_factor;
  152. volatile long final_advance = block->advance * exit_factor * exit_factor;
  153. #endif // ADVANCE
  154. // block->accelerate_until = accelerate_steps;
  155. // block->decelerate_after = accelerate_steps+plateau_steps;
  156. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  157. if (!block->busy) { // Don't update variables if block is busy.
  158. block->accelerate_until = accelerate_steps;
  159. block->decelerate_after = accelerate_steps + plateau_steps;
  160. block->initial_rate = initial_rate;
  161. block->final_rate = final_rate;
  162. #if ENABLED(ADVANCE)
  163. block->initial_advance = initial_advance;
  164. block->final_advance = final_advance;
  165. #endif
  166. }
  167. CRITICAL_SECTION_END;
  168. }
  169. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  170. // This method will calculate the junction jerk as the euclidean distance between the nominal
  171. // velocities of the respective blocks.
  172. //inline float junction_jerk(block_t *before, block_t *after) {
  173. // return sqrt(
  174. // pow((before->speed_x-after->speed_x), 2)+pow((before->speed_y-after->speed_y), 2));
  175. //}
  176. // The kernel called by recalculate() when scanning the plan from last to first entry.
  177. void Planner::reverse_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  178. if (!current) return;
  179. UNUSED(previous);
  180. if (next) {
  181. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  182. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  183. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  184. float max_entry_speed = current->max_entry_speed;
  185. if (current->entry_speed != max_entry_speed) {
  186. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  187. // for max allowable speed if block is decelerating and nominal length is false.
  188. if (!current->nominal_length_flag && max_entry_speed > next->entry_speed) {
  189. current->entry_speed = min(max_entry_speed,
  190. max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  191. }
  192. else {
  193. current->entry_speed = max_entry_speed;
  194. }
  195. current->recalculate_flag = true;
  196. }
  197. } // Skip last block. Already initialized and set for recalculation.
  198. }
  199. /**
  200. * recalculate() needs to go over the current plan twice.
  201. * Once in reverse and once forward. This implements the reverse pass.
  202. */
  203. void Planner::reverse_pass() {
  204. if (movesplanned() > 3) {
  205. block_t* block[3] = { NULL, NULL, NULL };
  206. // Make a local copy of block_buffer_tail, because the interrupt can alter it
  207. CRITICAL_SECTION_START;
  208. uint8_t tail = block_buffer_tail;
  209. CRITICAL_SECTION_END
  210. uint8_t b = BLOCK_MOD(block_buffer_head - 3);
  211. while (b != tail) {
  212. b = prev_block_index(b);
  213. block[2] = block[1];
  214. block[1] = block[0];
  215. block[0] = &block_buffer[b];
  216. reverse_pass_kernel(block[0], block[1], block[2]);
  217. }
  218. }
  219. }
  220. // The kernel called by recalculate() when scanning the plan from first to last entry.
  221. void Planner::forward_pass_kernel(block_t* previous, block_t* current, block_t* next) {
  222. if (!previous) return;
  223. UNUSED(next);
  224. // If the previous block is an acceleration block, but it is not long enough to complete the
  225. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  226. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  227. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  228. if (!previous->nominal_length_flag) {
  229. if (previous->entry_speed < current->entry_speed) {
  230. double entry_speed = min(current->entry_speed,
  231. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  232. // Check for junction speed change
  233. if (current->entry_speed != entry_speed) {
  234. current->entry_speed = entry_speed;
  235. current->recalculate_flag = true;
  236. }
  237. }
  238. }
  239. }
  240. /**
  241. * recalculate() needs to go over the current plan twice.
  242. * Once in reverse and once forward. This implements the forward pass.
  243. */
  244. void Planner::forward_pass() {
  245. block_t* block[3] = { NULL, NULL, NULL };
  246. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  247. block[0] = block[1];
  248. block[1] = block[2];
  249. block[2] = &block_buffer[b];
  250. forward_pass_kernel(block[0], block[1], block[2]);
  251. }
  252. forward_pass_kernel(block[1], block[2], NULL);
  253. }
  254. /**
  255. * Recalculate the trapezoid speed profiles for all blocks in the plan
  256. * according to the entry_factor for each junction. Must be called by
  257. * recalculate() after updating the blocks.
  258. */
  259. void Planner::recalculate_trapezoids() {
  260. int8_t block_index = block_buffer_tail;
  261. block_t* current;
  262. block_t* next = NULL;
  263. while (block_index != block_buffer_head) {
  264. current = next;
  265. next = &block_buffer[block_index];
  266. if (current) {
  267. // Recalculate if current block entry or exit junction speed has changed.
  268. if (current->recalculate_flag || next->recalculate_flag) {
  269. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  270. float nom = current->nominal_speed;
  271. calculate_trapezoid_for_block(current, current->entry_speed / nom, next->entry_speed / nom);
  272. current->recalculate_flag = false; // Reset current only to ensure next trapezoid is computed
  273. }
  274. }
  275. block_index = next_block_index(block_index);
  276. }
  277. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  278. if (next) {
  279. float nom = next->nominal_speed;
  280. calculate_trapezoid_for_block(next, next->entry_speed / nom, (MINIMUM_PLANNER_SPEED) / nom);
  281. next->recalculate_flag = false;
  282. }
  283. }
  284. /*
  285. * Recalculate the motion plan according to the following algorithm:
  286. *
  287. * 1. Go over every block in reverse order...
  288. *
  289. * Calculate a junction speed reduction (block_t.entry_factor) so:
  290. *
  291. * a. The junction jerk is within the set limit, and
  292. *
  293. * b. No speed reduction within one block requires faster
  294. * deceleration than the one, true constant acceleration.
  295. *
  296. * 2. Go over every block in chronological order...
  297. *
  298. * Dial down junction speed reduction values if:
  299. * a. The speed increase within one block would require faster
  300. * acceleration than the one, true constant acceleration.
  301. *
  302. * After that, all blocks will have an entry_factor allowing all speed changes to
  303. * be performed using only the one, true constant acceleration, and where no junction
  304. * jerk is jerkier than the set limit, Jerky. Finally it will:
  305. *
  306. * 3. Recalculate "trapezoids" for all blocks.
  307. */
  308. void Planner::recalculate() {
  309. reverse_pass();
  310. forward_pass();
  311. recalculate_trapezoids();
  312. }
  313. #if ENABLED(AUTOTEMP)
  314. void Planner::getHighESpeed() {
  315. static float oldt = 0;
  316. if (!autotemp_enabled) return;
  317. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  318. float high = 0.0;
  319. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  320. block_t* block = &block_buffer[b];
  321. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  322. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  323. NOLESS(high, se);
  324. }
  325. }
  326. float t = autotemp_min + high * autotemp_factor;
  327. t = constrain(t, autotemp_min, autotemp_max);
  328. if (oldt > t) {
  329. t *= (1 - (AUTOTEMP_OLDWEIGHT));
  330. t += (AUTOTEMP_OLDWEIGHT) * oldt;
  331. }
  332. oldt = t;
  333. thermalManager.setTargetHotend(t, 0);
  334. }
  335. #endif //AUTOTEMP
  336. /**
  337. * Maintain fans, paste extruder pressure,
  338. */
  339. void Planner::check_axes_activity() {
  340. unsigned char axis_active[NUM_AXIS] = { 0 },
  341. tail_fan_speed[FAN_COUNT];
  342. #if FAN_COUNT > 0
  343. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  344. #endif
  345. #if ENABLED(BARICUDA)
  346. unsigned char tail_valve_pressure = baricuda_valve_pressure,
  347. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  348. #endif
  349. if (blocks_queued()) {
  350. #if FAN_COUNT > 0
  351. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  352. #endif
  353. block_t* block;
  354. #if ENABLED(BARICUDA)
  355. block = &block_buffer[block_buffer_tail];
  356. tail_valve_pressure = block->valve_pressure;
  357. tail_e_to_p_pressure = block->e_to_p_pressure;
  358. #endif
  359. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  360. block = &block_buffer[b];
  361. for (int i = 0; i < NUM_AXIS; i++) if (block->steps[i]) axis_active[i]++;
  362. }
  363. }
  364. #if ENABLED(DISABLE_X)
  365. if (!axis_active[X_AXIS]) disable_x();
  366. #endif
  367. #if ENABLED(DISABLE_Y)
  368. if (!axis_active[Y_AXIS]) disable_y();
  369. #endif
  370. #if ENABLED(DISABLE_Z)
  371. if (!axis_active[Z_AXIS]) disable_z();
  372. #endif
  373. #if ENABLED(DISABLE_E)
  374. if (!axis_active[E_AXIS]) {
  375. disable_e0();
  376. disable_e1();
  377. disable_e2();
  378. disable_e3();
  379. }
  380. #endif
  381. #if FAN_COUNT > 0
  382. #if defined(FAN_MIN_PWM)
  383. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  384. #else
  385. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  386. #endif
  387. #ifdef FAN_KICKSTART_TIME
  388. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  389. #define KICKSTART_FAN(f) \
  390. if (tail_fan_speed[f]) { \
  391. millis_t ms = millis(); \
  392. if (fan_kick_end[f] == 0) { \
  393. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  394. tail_fan_speed[f] = 255; \
  395. } else { \
  396. if (PENDING(ms, fan_kick_end[f])) { \
  397. tail_fan_speed[f] = 255; \
  398. } \
  399. } \
  400. } else { \
  401. fan_kick_end[f] = 0; \
  402. }
  403. #if HAS_FAN0
  404. KICKSTART_FAN(0);
  405. #endif
  406. #if HAS_FAN1
  407. KICKSTART_FAN(1);
  408. #endif
  409. #if HAS_FAN2
  410. KICKSTART_FAN(2);
  411. #endif
  412. #endif //FAN_KICKSTART_TIME
  413. #if ENABLED(FAN_SOFT_PWM)
  414. #if HAS_FAN0
  415. thermalManager.fanSpeedSoftPwm[0] = CALC_FAN_SPEED(0);
  416. #endif
  417. #if HAS_FAN1
  418. thermalManager.fanSpeedSoftPwm[1] = CALC_FAN_SPEED(1);
  419. #endif
  420. #if HAS_FAN2
  421. thermalManager.fanSpeedSoftPwm[2] = CALC_FAN_SPEED(2);
  422. #endif
  423. #else
  424. #if HAS_FAN0
  425. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  426. #endif
  427. #if HAS_FAN1
  428. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  429. #endif
  430. #if HAS_FAN2
  431. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  432. #endif
  433. #endif
  434. #endif // FAN_COUNT > 0
  435. #if ENABLED(AUTOTEMP)
  436. getHighESpeed();
  437. #endif
  438. #if ENABLED(BARICUDA)
  439. #if HAS_HEATER_1
  440. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  441. #endif
  442. #if HAS_HEATER_2
  443. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  444. #endif
  445. #endif
  446. }
  447. /**
  448. * Planner::buffer_line
  449. *
  450. * Add a new linear movement to the buffer.
  451. *
  452. * x,y,z,e - target position in mm
  453. * feed_rate - (target) speed of the move
  454. * extruder - target extruder
  455. */
  456. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  457. void Planner::buffer_line(float x, float y, float z, const float& e, float feed_rate, const uint8_t extruder)
  458. #else
  459. void Planner::buffer_line(const float& x, const float& y, const float& z, const float& e, float feed_rate, const uint8_t extruder)
  460. #endif // AUTO_BED_LEVELING_FEATURE
  461. {
  462. // Calculate the buffer head after we push this byte
  463. int next_buffer_head = next_block_index(block_buffer_head);
  464. // If the buffer is full: good! That means we are well ahead of the robot.
  465. // Rest here until there is room in the buffer.
  466. while (block_buffer_tail == next_buffer_head) idle();
  467. #if ENABLED(MESH_BED_LEVELING)
  468. if (mbl.active) z += mbl.get_z(x - home_offset[X_AXIS], y - home_offset[Y_AXIS]);
  469. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  470. apply_rotation_xyz(bed_level_matrix, x, y, z);
  471. #endif
  472. // The target position of the tool in absolute steps
  473. // Calculate target position in absolute steps
  474. //this should be done after the wait, because otherwise a M92 code within the gcode disrupts this calculation somehow
  475. long target[NUM_AXIS] = {
  476. lround(x * axis_steps_per_unit[X_AXIS]),
  477. lround(y * axis_steps_per_unit[Y_AXIS]),
  478. lround(z * axis_steps_per_unit[Z_AXIS]),
  479. lround(e * axis_steps_per_unit[E_AXIS])
  480. };
  481. long dx = target[X_AXIS] - position[X_AXIS],
  482. dy = target[Y_AXIS] - position[Y_AXIS],
  483. dz = target[Z_AXIS] - position[Z_AXIS];
  484. // DRYRUN ignores all temperature constraints and assures that the extruder is instantly satisfied
  485. if (DEBUGGING(DRYRUN))
  486. position[E_AXIS] = target[E_AXIS];
  487. long de = target[E_AXIS] - position[E_AXIS];
  488. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  489. if (de) {
  490. if (thermalManager.tooColdToExtrude(extruder)) {
  491. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  492. de = 0; // no difference
  493. SERIAL_ECHO_START;
  494. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  495. }
  496. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  497. if (labs(de) > axis_steps_per_unit[E_AXIS] * (EXTRUDE_MAXLENGTH)) {
  498. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  499. de = 0; // no difference
  500. SERIAL_ECHO_START;
  501. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  502. }
  503. #endif
  504. }
  505. #endif
  506. // Prepare to set up new block
  507. block_t* block = &block_buffer[block_buffer_head];
  508. // Mark block as not busy (Not executed by the stepper interrupt)
  509. block->busy = false;
  510. // Number of steps for each axis
  511. #if ENABLED(COREXY)
  512. // corexy planning
  513. // these equations follow the form of the dA and dB equations on http://www.corexy.com/theory.html
  514. block->steps[A_AXIS] = labs(dx + dy);
  515. block->steps[B_AXIS] = labs(dx - dy);
  516. block->steps[Z_AXIS] = labs(dz);
  517. #elif ENABLED(COREXZ)
  518. // corexz planning
  519. block->steps[A_AXIS] = labs(dx + dz);
  520. block->steps[Y_AXIS] = labs(dy);
  521. block->steps[C_AXIS] = labs(dx - dz);
  522. #elif ENABLED(COREYZ)
  523. // coreyz planning
  524. block->steps[X_AXIS] = labs(dx);
  525. block->steps[B_AXIS] = labs(dy + dz);
  526. block->steps[C_AXIS] = labs(dy - dz);
  527. #else
  528. // default non-h-bot planning
  529. block->steps[X_AXIS] = labs(dx);
  530. block->steps[Y_AXIS] = labs(dy);
  531. block->steps[Z_AXIS] = labs(dz);
  532. #endif
  533. block->steps[E_AXIS] = labs(de);
  534. block->steps[E_AXIS] *= volumetric_multiplier[extruder];
  535. block->steps[E_AXIS] *= extruder_multiplier[extruder];
  536. block->steps[E_AXIS] /= 100;
  537. block->step_event_count = max(block->steps[X_AXIS], max(block->steps[Y_AXIS], max(block->steps[Z_AXIS], block->steps[E_AXIS])));
  538. // Bail if this is a zero-length block
  539. if (block->step_event_count <= dropsegments) return;
  540. #if FAN_COUNT > 0
  541. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  542. #endif
  543. #if ENABLED(BARICUDA)
  544. block->valve_pressure = baricuda_valve_pressure;
  545. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  546. #endif
  547. // Compute direction bits for this block
  548. uint8_t db = 0;
  549. #if ENABLED(COREXY)
  550. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  551. if (dy < 0) SBI(db, Y_HEAD); // ...and Y
  552. if (dz < 0) SBI(db, Z_AXIS);
  553. if (dx + dy < 0) SBI(db, A_AXIS); // Motor A direction
  554. if (dx - dy < 0) SBI(db, B_AXIS); // Motor B direction
  555. #elif ENABLED(COREXZ)
  556. if (dx < 0) SBI(db, X_HEAD); // Save the real Extruder (head) direction in X Axis
  557. if (dy < 0) SBI(db, Y_AXIS);
  558. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  559. if (dx + dz < 0) SBI(db, A_AXIS); // Motor A direction
  560. if (dx - dz < 0) SBI(db, C_AXIS); // Motor C direction
  561. #elif ENABLED(COREYZ)
  562. if (dx < 0) SBI(db, X_AXIS);
  563. if (dy < 0) SBI(db, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  564. if (dz < 0) SBI(db, Z_HEAD); // ...and Z
  565. if (dy + dz < 0) SBI(db, B_AXIS); // Motor B direction
  566. if (dy - dz < 0) SBI(db, C_AXIS); // Motor C direction
  567. #else
  568. if (dx < 0) SBI(db, X_AXIS);
  569. if (dy < 0) SBI(db, Y_AXIS);
  570. if (dz < 0) SBI(db, Z_AXIS);
  571. #endif
  572. if (de < 0) SBI(db, E_AXIS);
  573. block->direction_bits = db;
  574. block->active_extruder = extruder;
  575. //enable active axes
  576. #if ENABLED(COREXY)
  577. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  578. enable_x();
  579. enable_y();
  580. }
  581. #if DISABLED(Z_LATE_ENABLE)
  582. if (block->steps[Z_AXIS]) enable_z();
  583. #endif
  584. #elif ENABLED(COREXZ)
  585. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  586. enable_x();
  587. enable_z();
  588. }
  589. if (block->steps[Y_AXIS]) enable_y();
  590. #else
  591. if (block->steps[X_AXIS]) enable_x();
  592. if (block->steps[Y_AXIS]) enable_y();
  593. #if DISABLED(Z_LATE_ENABLE)
  594. if (block->steps[Z_AXIS]) enable_z();
  595. #endif
  596. #endif
  597. // Enable extruder(s)
  598. if (block->steps[E_AXIS]) {
  599. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  600. for (int i = 0; i < EXTRUDERS; i++)
  601. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  602. switch(extruder) {
  603. case 0:
  604. enable_e0();
  605. #if ENABLED(DUAL_X_CARRIAGE)
  606. if (extruder_duplication_enabled) {
  607. enable_e1();
  608. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  609. }
  610. #endif
  611. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  612. #if EXTRUDERS > 1
  613. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  614. #if EXTRUDERS > 2
  615. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  616. #if EXTRUDERS > 3
  617. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  618. #endif
  619. #endif
  620. #endif
  621. break;
  622. #if EXTRUDERS > 1
  623. case 1:
  624. enable_e1();
  625. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  626. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  627. #if EXTRUDERS > 2
  628. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  629. #if EXTRUDERS > 3
  630. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  631. #endif
  632. #endif
  633. break;
  634. #if EXTRUDERS > 2
  635. case 2:
  636. enable_e2();
  637. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  638. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  639. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  640. #if EXTRUDERS > 3
  641. if (g_uc_extruder_last_move[3] == 0) disable_e3();
  642. #endif
  643. break;
  644. #if EXTRUDERS > 3
  645. case 3:
  646. enable_e3();
  647. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  648. if (g_uc_extruder_last_move[0] == 0) disable_e0();
  649. if (g_uc_extruder_last_move[1] == 0) disable_e1();
  650. if (g_uc_extruder_last_move[2] == 0) disable_e2();
  651. break;
  652. #endif // EXTRUDERS > 3
  653. #endif // EXTRUDERS > 2
  654. #endif // EXTRUDERS > 1
  655. }
  656. #else
  657. enable_e0();
  658. enable_e1();
  659. enable_e2();
  660. enable_e3();
  661. #endif
  662. }
  663. if (block->steps[E_AXIS])
  664. NOLESS(feed_rate, min_feedrate);
  665. else
  666. NOLESS(feed_rate, min_travel_feedrate);
  667. /**
  668. * This part of the code calculates the total length of the movement.
  669. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  670. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  671. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  672. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  673. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  674. */
  675. #if ENABLED(COREXY) || ENABLED(COREXZ) || ENABLED(COREYZ)
  676. float delta_mm[6];
  677. #if ENABLED(COREXY)
  678. delta_mm[X_HEAD] = dx / axis_steps_per_unit[A_AXIS];
  679. delta_mm[Y_HEAD] = dy / axis_steps_per_unit[B_AXIS];
  680. delta_mm[Z_AXIS] = dz / axis_steps_per_unit[Z_AXIS];
  681. delta_mm[A_AXIS] = (dx + dy) / axis_steps_per_unit[A_AXIS];
  682. delta_mm[B_AXIS] = (dx - dy) / axis_steps_per_unit[B_AXIS];
  683. #elif ENABLED(COREXZ)
  684. delta_mm[X_HEAD] = dx / axis_steps_per_unit[A_AXIS];
  685. delta_mm[Y_AXIS] = dy / axis_steps_per_unit[Y_AXIS];
  686. delta_mm[Z_HEAD] = dz / axis_steps_per_unit[C_AXIS];
  687. delta_mm[A_AXIS] = (dx + dz) / axis_steps_per_unit[A_AXIS];
  688. delta_mm[C_AXIS] = (dx - dz) / axis_steps_per_unit[C_AXIS];
  689. #elif ENABLED(COREYZ)
  690. delta_mm[X_AXIS] = dx / axis_steps_per_unit[A_AXIS];
  691. delta_mm[Y_HEAD] = dy / axis_steps_per_unit[Y_AXIS];
  692. delta_mm[Z_HEAD] = dz / axis_steps_per_unit[C_AXIS];
  693. delta_mm[B_AXIS] = (dy + dz) / axis_steps_per_unit[B_AXIS];
  694. delta_mm[C_AXIS] = (dy - dz) / axis_steps_per_unit[C_AXIS];
  695. #endif
  696. #else
  697. float delta_mm[4];
  698. delta_mm[X_AXIS] = dx / axis_steps_per_unit[X_AXIS];
  699. delta_mm[Y_AXIS] = dy / axis_steps_per_unit[Y_AXIS];
  700. delta_mm[Z_AXIS] = dz / axis_steps_per_unit[Z_AXIS];
  701. #endif
  702. delta_mm[E_AXIS] = (de / axis_steps_per_unit[E_AXIS]) * volumetric_multiplier[extruder] * extruder_multiplier[extruder] / 100.0;
  703. if (block->steps[X_AXIS] <= dropsegments && block->steps[Y_AXIS] <= dropsegments && block->steps[Z_AXIS] <= dropsegments) {
  704. block->millimeters = fabs(delta_mm[E_AXIS]);
  705. }
  706. else {
  707. block->millimeters = sqrt(
  708. #if ENABLED(COREXY)
  709. square(delta_mm[X_HEAD]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_AXIS])
  710. #elif ENABLED(COREXZ)
  711. square(delta_mm[X_HEAD]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_HEAD])
  712. #elif ENABLED(COREYZ)
  713. square(delta_mm[X_AXIS]) + square(delta_mm[Y_HEAD]) + square(delta_mm[Z_HEAD])
  714. #else
  715. square(delta_mm[X_AXIS]) + square(delta_mm[Y_AXIS]) + square(delta_mm[Z_AXIS])
  716. #endif
  717. );
  718. }
  719. float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  720. // Calculate moves/second for this move. No divide by zero due to previous checks.
  721. float inverse_second = feed_rate * inverse_millimeters;
  722. int moves_queued = movesplanned();
  723. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  724. #if ENABLED(OLD_SLOWDOWN) || ENABLED(SLOWDOWN)
  725. bool mq = moves_queued > 1 && moves_queued < (BLOCK_BUFFER_SIZE) / 2;
  726. #if ENABLED(OLD_SLOWDOWN)
  727. if (mq) feed_rate *= 2.0 * moves_queued / (BLOCK_BUFFER_SIZE);
  728. #endif
  729. #if ENABLED(SLOWDOWN)
  730. // segment time im micro seconds
  731. unsigned long segment_time = lround(1000000.0/inverse_second);
  732. if (mq) {
  733. if (segment_time < min_segment_time) {
  734. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  735. inverse_second = 1000000.0 / (segment_time + lround(2 * (min_segment_time - segment_time) / moves_queued));
  736. #ifdef XY_FREQUENCY_LIMIT
  737. segment_time = lround(1000000.0 / inverse_second);
  738. #endif
  739. }
  740. }
  741. #endif
  742. #endif
  743. block->nominal_speed = block->millimeters * inverse_second; // (mm/sec) Always > 0
  744. block->nominal_rate = ceil(block->step_event_count * inverse_second); // (step/sec) Always > 0
  745. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  746. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  747. //FMM update ring buffer used for delay with filament measurements
  748. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index2 >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  749. const int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  750. // increment counters with next move in e axis
  751. filwidth_e_count += delta_mm[E_AXIS];
  752. filwidth_delay_dist += delta_mm[E_AXIS];
  753. // Only get new measurements on forward E movement
  754. if (filwidth_e_count > 0.0001) {
  755. // Loop the delay distance counter (modulus by the mm length)
  756. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  757. // Convert into an index into the measurement array
  758. filwidth_delay_index1 = (int)(filwidth_delay_dist / 10.0 + 0.0001);
  759. // If the index has changed (must have gone forward)...
  760. if (filwidth_delay_index1 != filwidth_delay_index2) {
  761. filwidth_e_count = 0; // Reset the E movement counter
  762. int8_t meas_sample = thermalManager.widthFil_to_size_ratio() - 100; // Subtract 100 to reduce magnitude - to store in a signed char
  763. do {
  764. filwidth_delay_index2 = (filwidth_delay_index2 + 1) % MMD_CM; // The next unused slot
  765. measurement_delay[filwidth_delay_index2] = meas_sample; // Store the measurement
  766. } while (filwidth_delay_index1 != filwidth_delay_index2); // More slots to fill?
  767. }
  768. }
  769. }
  770. #endif
  771. // Calculate and limit speed in mm/sec for each axis
  772. float current_speed[NUM_AXIS];
  773. float speed_factor = 1.0; //factor <=1 do decrease speed
  774. for (int i = 0; i < NUM_AXIS; i++) {
  775. current_speed[i] = delta_mm[i] * inverse_second;
  776. float cs = fabs(current_speed[i]), mf = max_feedrate[i];
  777. if (cs > mf) speed_factor = min(speed_factor, mf / cs);
  778. }
  779. // Max segement time in us.
  780. #ifdef XY_FREQUENCY_LIMIT
  781. // Check and limit the xy direction change frequency
  782. unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  783. old_direction_bits = block->direction_bits;
  784. segment_time = lround((float)segment_time / speed_factor);
  785. long xs0 = axis_segment_time[X_AXIS][0],
  786. xs1 = axis_segment_time[X_AXIS][1],
  787. xs2 = axis_segment_time[X_AXIS][2],
  788. ys0 = axis_segment_time[Y_AXIS][0],
  789. ys1 = axis_segment_time[Y_AXIS][1],
  790. ys2 = axis_segment_time[Y_AXIS][2];
  791. if (TEST(direction_change, X_AXIS)) {
  792. xs2 = axis_segment_time[X_AXIS][2] = xs1;
  793. xs1 = axis_segment_time[X_AXIS][1] = xs0;
  794. xs0 = 0;
  795. }
  796. xs0 = axis_segment_time[X_AXIS][0] = xs0 + segment_time;
  797. if (TEST(direction_change, Y_AXIS)) {
  798. ys2 = axis_segment_time[Y_AXIS][2] = axis_segment_time[Y_AXIS][1];
  799. ys1 = axis_segment_time[Y_AXIS][1] = axis_segment_time[Y_AXIS][0];
  800. ys0 = 0;
  801. }
  802. ys0 = axis_segment_time[Y_AXIS][0] = ys0 + segment_time;
  803. long max_x_segment_time = max(xs0, max(xs1, xs2)),
  804. max_y_segment_time = max(ys0, max(ys1, ys2)),
  805. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  806. if (min_xy_segment_time < MAX_FREQ_TIME) {
  807. float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME);
  808. speed_factor = min(speed_factor, low_sf);
  809. }
  810. #endif // XY_FREQUENCY_LIMIT
  811. // Correct the speed
  812. if (speed_factor < 1.0) {
  813. for (unsigned char i = 0; i < NUM_AXIS; i++) current_speed[i] *= speed_factor;
  814. block->nominal_speed *= speed_factor;
  815. block->nominal_rate *= speed_factor;
  816. }
  817. // Compute and limit the acceleration rate for the trapezoid generator.
  818. float steps_per_mm = block->step_event_count / block->millimeters;
  819. long bsx = block->steps[X_AXIS], bsy = block->steps[Y_AXIS], bsz = block->steps[Z_AXIS], bse = block->steps[E_AXIS];
  820. if (bsx == 0 && bsy == 0 && bsz == 0) {
  821. block->acceleration_st = ceil(retract_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  822. }
  823. else if (bse == 0) {
  824. block->acceleration_st = ceil(travel_acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  825. }
  826. else {
  827. block->acceleration_st = ceil(acceleration * steps_per_mm); // convert to: acceleration steps/sec^2
  828. }
  829. // Limit acceleration per axis
  830. unsigned long acc_st = block->acceleration_st,
  831. xsteps = axis_steps_per_sqr_second[X_AXIS],
  832. ysteps = axis_steps_per_sqr_second[Y_AXIS],
  833. zsteps = axis_steps_per_sqr_second[Z_AXIS],
  834. esteps = axis_steps_per_sqr_second[E_AXIS],
  835. allsteps = block->step_event_count;
  836. if (xsteps < (acc_st * bsx) / allsteps) acc_st = (xsteps * allsteps) / bsx;
  837. if (ysteps < (acc_st * bsy) / allsteps) acc_st = (ysteps * allsteps) / bsy;
  838. if (zsteps < (acc_st * bsz) / allsteps) acc_st = (zsteps * allsteps) / bsz;
  839. if (esteps < (acc_st * bse) / allsteps) acc_st = (esteps * allsteps) / bse;
  840. block->acceleration_st = acc_st;
  841. block->acceleration = acc_st / steps_per_mm;
  842. block->acceleration_rate = (long)(acc_st * 16777216.0 / (F_CPU / 8.0));
  843. #if 0 // Use old jerk for now
  844. float junction_deviation = 0.1;
  845. // Compute path unit vector
  846. double unit_vec[3];
  847. unit_vec[X_AXIS] = delta_mm[X_AXIS] * inverse_millimeters;
  848. unit_vec[Y_AXIS] = delta_mm[Y_AXIS] * inverse_millimeters;
  849. unit_vec[Z_AXIS] = delta_mm[Z_AXIS] * inverse_millimeters;
  850. // Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  851. // Let a circle be tangent to both previous and current path line segments, where the junction
  852. // deviation is defined as the distance from the junction to the closest edge of the circle,
  853. // collinear with the circle center. The circular segment joining the two paths represents the
  854. // path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  855. // radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  856. // path width or max_jerk in the previous grbl version. This approach does not actually deviate
  857. // from path, but used as a robust way to compute cornering speeds, as it takes into account the
  858. // nonlinearities of both the junction angle and junction velocity.
  859. double vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  860. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  861. if ((block_buffer_head != block_buffer_tail) && (previous_nominal_speed > 0.0)) {
  862. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  863. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  864. double cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  865. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  866. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS] ;
  867. // Skip and use default max junction speed for 0 degree acute junction.
  868. if (cos_theta < 0.95) {
  869. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  870. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  871. if (cos_theta > -0.95) {
  872. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  873. double sin_theta_d2 = sqrt(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  874. vmax_junction = min(vmax_junction,
  875. sqrt(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  876. }
  877. }
  878. }
  879. #endif
  880. // Start with a safe speed
  881. float vmax_junction = max_xy_jerk / 2;
  882. float vmax_junction_factor = 1.0;
  883. float mz2 = max_z_jerk / 2, me2 = max_e_jerk / 2;
  884. float csz = current_speed[Z_AXIS], cse = current_speed[E_AXIS];
  885. if (fabs(csz) > mz2) vmax_junction = min(vmax_junction, mz2);
  886. if (fabs(cse) > me2) vmax_junction = min(vmax_junction, me2);
  887. vmax_junction = min(vmax_junction, block->nominal_speed);
  888. float safe_speed = vmax_junction;
  889. if ((moves_queued > 1) && (previous_nominal_speed > 0.0001)) {
  890. float dsx = current_speed[X_AXIS] - previous_speed[X_AXIS],
  891. dsy = current_speed[Y_AXIS] - previous_speed[Y_AXIS],
  892. dsz = fabs(csz - previous_speed[Z_AXIS]),
  893. dse = fabs(cse - previous_speed[E_AXIS]),
  894. jerk = sqrt(dsx * dsx + dsy * dsy);
  895. // if ((fabs(previous_speed[X_AXIS]) > 0.0001) || (fabs(previous_speed[Y_AXIS]) > 0.0001)) {
  896. vmax_junction = block->nominal_speed;
  897. // }
  898. if (jerk > max_xy_jerk) vmax_junction_factor = max_xy_jerk / jerk;
  899. if (dsz > max_z_jerk) vmax_junction_factor = min(vmax_junction_factor, max_z_jerk / dsz);
  900. if (dse > max_e_jerk) vmax_junction_factor = min(vmax_junction_factor, max_e_jerk / dse);
  901. vmax_junction = min(previous_nominal_speed, vmax_junction * vmax_junction_factor); // Limit speed to max previous speed
  902. }
  903. block->max_entry_speed = vmax_junction;
  904. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  905. double v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  906. block->entry_speed = min(vmax_junction, v_allowable);
  907. // Initialize planner efficiency flags
  908. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  909. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  910. // the current block and next block junction speeds are guaranteed to always be at their maximum
  911. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  912. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  913. // the reverse and forward planners, the corresponding block junction speed will always be at the
  914. // the maximum junction speed and may always be ignored for any speed reduction checks.
  915. block->nominal_length_flag = (block->nominal_speed <= v_allowable);
  916. block->recalculate_flag = true; // Always calculate trapezoid for new block
  917. // Update previous path unit_vector and nominal speed
  918. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = current_speed[i];
  919. previous_nominal_speed = block->nominal_speed;
  920. #if ENABLED(ADVANCE)
  921. // Calculate advance rate
  922. if (!bse || (!bsx && !bsy && !bsz)) {
  923. block->advance_rate = 0;
  924. block->advance = 0;
  925. }
  926. else {
  927. long acc_dist = estimate_acceleration_distance(0, block->nominal_rate, block->acceleration_st);
  928. float advance = ((STEPS_PER_CUBIC_MM_E) * (EXTRUDER_ADVANCE_K)) * (cse * cse * (EXTRUSION_AREA) * (EXTRUSION_AREA)) * 256;
  929. block->advance = advance;
  930. block->advance_rate = acc_dist ? advance / (float)acc_dist : 0;
  931. }
  932. /**
  933. SERIAL_ECHO_START;
  934. SERIAL_ECHOPGM("advance :");
  935. SERIAL_ECHO(block->advance/256.0);
  936. SERIAL_ECHOPGM("advance rate :");
  937. SERIAL_ECHOLN(block->advance_rate/256.0);
  938. */
  939. #endif // ADVANCE
  940. calculate_trapezoid_for_block(block, block->entry_speed / block->nominal_speed, safe_speed / block->nominal_speed);
  941. // Move buffer head
  942. block_buffer_head = next_buffer_head;
  943. // Update position
  944. for (int i = 0; i < NUM_AXIS; i++) position[i] = target[i];
  945. recalculate();
  946. stepper.wake_up();
  947. } // buffer_line()
  948. #if ENABLED(AUTO_BED_LEVELING_FEATURE) && DISABLED(DELTA)
  949. /**
  950. * Get the XYZ position of the steppers as a vector_3.
  951. *
  952. * On CORE machines XYZ is derived from ABC.
  953. */
  954. vector_3 Planner::adjusted_position() {
  955. vector_3 pos = vector_3(stepper.get_axis_position_mm(X_AXIS), stepper.get_axis_position_mm(Y_AXIS), stepper.get_axis_position_mm(Z_AXIS));
  956. //pos.debug("in Planner::adjusted_position");
  957. //bed_level_matrix.debug("in Planner::adjusted_position");
  958. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  959. //inverse.debug("in Planner::inverse");
  960. pos.apply_rotation(inverse);
  961. //pos.debug("after rotation");
  962. return pos;
  963. }
  964. #endif // AUTO_BED_LEVELING_FEATURE && !DELTA
  965. /**
  966. * Directly set the planner XYZ position (hence the stepper positions).
  967. *
  968. * On CORE machines stepper ABC will be translated from the given XYZ.
  969. */
  970. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  971. void Planner::set_position_mm(float x, float y, float z, const float& e)
  972. #else
  973. void Planner::set_position_mm(const float& x, const float& y, const float& z, const float& e)
  974. #endif // AUTO_BED_LEVELING_FEATURE || MESH_BED_LEVELING
  975. {
  976. #if ENABLED(MESH_BED_LEVELING)
  977. if (mbl.active) z += mbl.get_z(x - home_offset[X_AXIS], y - home_offset[Y_AXIS]);
  978. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  979. apply_rotation_xyz(bed_level_matrix, x, y, z);
  980. #endif
  981. long nx = position[X_AXIS] = lround(x * axis_steps_per_unit[X_AXIS]),
  982. ny = position[Y_AXIS] = lround(y * axis_steps_per_unit[Y_AXIS]),
  983. nz = position[Z_AXIS] = lround(z * axis_steps_per_unit[Z_AXIS]),
  984. ne = position[E_AXIS] = lround(e * axis_steps_per_unit[E_AXIS]);
  985. stepper.set_position(nx, ny, nz, ne);
  986. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  987. for (int i = 0; i < NUM_AXIS; i++) previous_speed[i] = 0.0;
  988. }
  989. /**
  990. * Directly set the planner E position (hence the stepper E position).
  991. */
  992. void Planner::set_e_position_mm(const float& e) {
  993. position[E_AXIS] = lround(e * axis_steps_per_unit[E_AXIS]);
  994. stepper.set_e_position(position[E_AXIS]);
  995. }
  996. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  997. void Planner::reset_acceleration_rates() {
  998. for (int i = 0; i < NUM_AXIS; i++)
  999. axis_steps_per_sqr_second[i] = max_acceleration_units_per_sq_second[i] * axis_steps_per_unit[i];
  1000. }
  1001. #if ENABLED(AUTOTEMP)
  1002. void Planner::autotemp_M109() {
  1003. autotemp_enabled = code_seen('F');
  1004. if (autotemp_enabled) autotemp_factor = code_value();
  1005. if (code_seen('S')) autotemp_min = code_value();
  1006. if (code_seen('B')) autotemp_max = code_value();
  1007. }
  1008. #endif