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

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