My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

planner.cpp 53KB

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