My Marlin configs for Fabrikator Mini and CTC i3 Pro B
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  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. *
  60. * The fast inverse function needed for Bézier interpolation for AVR
  61. * was designed, written and tested by Eduardo José Tagle on April/2018
  62. */
  63. #include "planner.h"
  64. #include "stepper.h"
  65. #include "motion.h"
  66. #include "../module/temperature.h"
  67. #include "../lcd/ultralcd.h"
  68. #include "../core/language.h"
  69. #include "../gcode/parser.h"
  70. #include "../Marlin.h"
  71. #if HAS_LEVELING
  72. #include "../feature/bedlevel/bedlevel.h"
  73. #endif
  74. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  75. #include "../feature/filwidth.h"
  76. #endif
  77. #if ENABLED(BARICUDA)
  78. #include "../feature/baricuda.h"
  79. #endif
  80. #if ENABLED(MIXING_EXTRUDER)
  81. #include "../feature/mixing.h"
  82. #endif
  83. #if ENABLED(AUTO_POWER_CONTROL)
  84. #include "../feature/power.h"
  85. #endif
  86. Planner planner;
  87. // public:
  88. /**
  89. * A ring buffer of moves described in steps
  90. */
  91. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  92. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  93. Planner::block_buffer_tail;
  94. float Planner::max_feedrate_mm_s[XYZE_N], // Max speeds in mm per second
  95. Planner::axis_steps_per_mm[XYZE_N],
  96. Planner::steps_to_mm[XYZE_N];
  97. #if ENABLED(DISTINCT_E_FACTORS)
  98. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  99. #endif
  100. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  101. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0); // The flow percentage and volumetric multiplier combine to scale E movement
  102. #if DISABLED(NO_VOLUMETRICS)
  103. float Planner::filament_size[EXTRUDERS], // diameter of filament (in millimeters), typically around 1.75 or 2.85, 0 disables the volumetric calculations for the extruder
  104. Planner::volumetric_area_nominal = CIRCLE_AREA((DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5), // Nominal cross-sectional area
  105. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  106. #endif
  107. uint32_t Planner::max_acceleration_steps_per_s2[XYZE_N],
  108. Planner::max_acceleration_mm_per_s2[XYZE_N]; // Use M201 to override by software
  109. uint32_t Planner::min_segment_time_us;
  110. // Initialized by settings.load()
  111. float Planner::min_feedrate_mm_s,
  112. Planner::acceleration, // Normal acceleration mm/s^2 DEFAULT ACCELERATION for all printing moves. M204 SXXXX
  113. Planner::retract_acceleration, // Retract acceleration mm/s^2 filament pull-back and push-forward while standing still in the other axes M204 TXXXX
  114. Planner::travel_acceleration, // Travel acceleration mm/s^2 DEFAULT ACCELERATION for all NON printing moves. M204 MXXXX
  115. Planner::max_jerk[XYZE], // The largest speed change requiring no acceleration
  116. Planner::min_travel_feedrate_mm_s;
  117. #if HAS_LEVELING
  118. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  119. #if ABL_PLANAR
  120. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  121. #endif
  122. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  123. float Planner::z_fade_height, // Initialized by settings.load()
  124. Planner::inverse_z_fade_height,
  125. Planner::last_fade_z;
  126. #endif
  127. #else
  128. constexpr bool Planner::leveling_active;
  129. #endif
  130. #if ENABLED(SKEW_CORRECTION)
  131. #if ENABLED(SKEW_CORRECTION_GCODE)
  132. float Planner::xy_skew_factor;
  133. #else
  134. constexpr float Planner::xy_skew_factor;
  135. #endif
  136. #if ENABLED(SKEW_CORRECTION_FOR_Z) && ENABLED(SKEW_CORRECTION_GCODE)
  137. float Planner::xz_skew_factor, Planner::yz_skew_factor;
  138. #else
  139. constexpr float Planner::xz_skew_factor, Planner::yz_skew_factor;
  140. #endif
  141. #endif
  142. #if ENABLED(AUTOTEMP)
  143. float Planner::autotemp_max = 250,
  144. Planner::autotemp_min = 210,
  145. Planner::autotemp_factor = 0.1;
  146. bool Planner::autotemp_enabled = false;
  147. #endif
  148. // private:
  149. int32_t Planner::position[NUM_AXIS] = { 0 };
  150. uint32_t Planner::cutoff_long;
  151. float Planner::previous_speed[NUM_AXIS],
  152. Planner::previous_nominal_speed;
  153. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  154. uint8_t Planner::g_uc_extruder_last_move[EXTRUDERS] = { 0 };
  155. #endif
  156. #ifdef XY_FREQUENCY_LIMIT
  157. // Old direction bits. Used for speed calculations
  158. unsigned char Planner::old_direction_bits = 0;
  159. // Segment times (in µs). Used for speed calculations
  160. uint32_t Planner::axis_segment_time_us[2][3] = { { MAX_FREQ_TIME_US + 1, 0, 0 }, { MAX_FREQ_TIME_US + 1, 0, 0 } };
  161. #endif
  162. #if ENABLED(LIN_ADVANCE)
  163. float Planner::extruder_advance_K; // Initialized by settings.load()
  164. #endif
  165. #if HAS_POSITION_FLOAT
  166. float Planner::position_float[XYZE]; // Needed for accurate maths. Steps cannot be used!
  167. #endif
  168. #if ENABLED(ULTRA_LCD)
  169. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  170. #endif
  171. /**
  172. * Class and Instance Methods
  173. */
  174. Planner::Planner() { init(); }
  175. void Planner::init() {
  176. ZERO(position);
  177. #if HAS_POSITION_FLOAT
  178. ZERO(position_float);
  179. #endif
  180. ZERO(previous_speed);
  181. previous_nominal_speed = 0.0;
  182. #if ABL_PLANAR
  183. bed_level_matrix.set_to_identity();
  184. #endif
  185. clear_block_buffer();
  186. }
  187. #if ENABLED(BEZIER_JERK_CONTROL)
  188. #ifdef __AVR__
  189. // This routine, for AVR, returns 0x1000000 / d, but trying to get the inverse as
  190. // fast as possible. A fast converging iterative Newton-Raphson method is able to
  191. // reach full precision in just 1 iteration, and takes 211 cycles (worst case, mean
  192. // case is less, up to 30 cycles for small divisors), instead of the 500 cycles a
  193. // normal division would take.
  194. //
  195. // Inspired by the following page,
  196. // https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  197. //
  198. // Suppose we want to calculate
  199. // floor(2 ^ k / B) where B is a positive integer
  200. // Then
  201. // B must be <= 2^k, otherwise, the quotient is 0.
  202. //
  203. // The Newton - Raphson iteration for x = B / 2 ^ k yields:
  204. // q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  205. //
  206. // We can rearrange it as:
  207. // q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  208. //
  209. // Each iteration of this kind requires only integer multiplications
  210. // and bit shifts.
  211. // Does it converge to floor(2 ^ k / B) ?: Not necessarily, but, in
  212. // the worst case, it eventually alternates between floor(2 ^ k / B)
  213. // and ceiling(2 ^ k / B)).
  214. // So we can use some not-so-clever test to see if we are in this
  215. // case, and extract floor(2 ^ k / B).
  216. // Lastly, a simple but important optimization for this approach is to
  217. // truncate multiplications (i.e.calculate only the higher bits of the
  218. // product) in the early iterations of the Newton - Raphson method.The
  219. // reason to do so, is that the results of the early iterations are far
  220. // from the quotient, and it doesn't matter to perform them inaccurately.
  221. // Finally, we should pick a good starting value for x. Knowing how many
  222. // digits the divisor has, we can estimate it:
  223. //
  224. // 2^k / x = 2 ^ log2(2^k / x)
  225. // 2^k / x = 2 ^(log2(2^k)-log2(x))
  226. // 2^k / x = 2 ^(k*log2(2)-log2(x))
  227. // 2^k / x = 2 ^ (k-log2(x))
  228. // 2^k / x >= 2 ^ (k-floor(log2(x)))
  229. // floor(log2(x)) simply is the index of the most significant bit set.
  230. //
  231. // If we could improve this estimation even further, then the number of
  232. // iterations can be dropped quite a bit, thus saving valuable execution time.
  233. // The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  234. // Research, Silicon Valley,August 26, 2008, that is available at
  235. // https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  236. // suggests , for its integer division algorithm, that using a table to supply the
  237. // first 8 bits of precision, and due to the quadratic convergence nature of the
  238. // Newton-Raphon iteration, then just 2 iterations should be enough to get
  239. // maximum precision of the division.
  240. // If we precompute values of inverses for small denominator values, then
  241. // just one Newton-Raphson iteration is enough to reach full precision
  242. // We will use the top 9 bits of the denominator as index.
  243. //
  244. // The AVR assembly function is implementing the following C code, included
  245. // here as reference:
  246. //
  247. // uint32_t get_period_inverse(uint32_t d) {
  248. // static const uint8_t inv_tab[256] = {
  249. // 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  250. // 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  251. // 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  252. // 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  253. // 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  254. // 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  255. // 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  256. // 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  257. // 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  258. // 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  259. // 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  260. // 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  261. // 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  262. // 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  263. // 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  264. // 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  265. // };
  266. //
  267. // // For small denominators, it is cheaper to directly store the result,
  268. // // because those denominators would require 2 Newton-Raphson iterations
  269. // // to converge to the required result precision. For bigger ones, just
  270. // // ONE Newton-Raphson iteration is enough to get maximum precision!
  271. // static const uint32_t small_inv_tab[111] PROGMEM = {
  272. // 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  273. // 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  274. // 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  275. // 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  276. // 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  277. // 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  278. // 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  279. // };
  280. //
  281. // // For small divisors, it is best to directly retrieve the results
  282. // if (d <= 110)
  283. // return pgm_read_dword(&small_inv_tab[d]);
  284. //
  285. // // Compute initial estimation of 0x1000000/x -
  286. // // Get most significant bit set on divider
  287. // uint8_t idx = 0;
  288. // uint32_t nr = d;
  289. // if (!(nr & 0xFF0000)) {
  290. // nr <<= 8;
  291. // idx += 8;
  292. // if (!(nr & 0xFF0000)) {
  293. // nr <<= 8;
  294. // idx += 8;
  295. // }
  296. // }
  297. // if (!(nr & 0xF00000)) {
  298. // nr <<= 4;
  299. // idx += 4;
  300. // }
  301. // if (!(nr & 0xC00000)) {
  302. // nr <<= 2;
  303. // idx += 2;
  304. // }
  305. // if (!(nr & 0x800000)) {
  306. // nr <<= 1;
  307. // idx += 1;
  308. // }
  309. //
  310. // // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  311. // uint32_t tidx = nr >> 15; // top 9 bits. bit8 is always set
  312. // uint32_t ie = inv_tab[tidx & 0xFF] + 256; // Get the table value. bit9 is always set
  313. // uint32_t x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  314. //
  315. // // Now, refine estimation by newton-raphson. 1 iteration is enough
  316. // x = uint32_t((x * uint64_t((1 << 25) - x * d)) >> 24);
  317. //
  318. // // Estimate remainder
  319. // uint32_t r = (1 << 24) - x * d;
  320. //
  321. // // Check if we must adjust result
  322. // if (r >= d) x++;
  323. //
  324. // // x holds the proper estimation
  325. // return uint32_t(x);
  326. // }
  327. //
  328. static uint32_t get_period_inverse(uint32_t d) {
  329. static const uint8_t inv_tab[256] PROGMEM = {
  330. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  331. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  332. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  333. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  334. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  335. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  336. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  337. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  338. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  339. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  340. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  341. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  342. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  343. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  344. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  345. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  346. };
  347. // For small denominators, it is cheaper to directly store the result.
  348. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  349. // maximum precision we need
  350. static const uint32_t small_inv_tab[111] PROGMEM = {
  351. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  352. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  353. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  354. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  355. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  356. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  357. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  358. };
  359. // For small divisors, it is best to directly retrieve the results
  360. if (d <= 110)
  361. return pgm_read_dword(&small_inv_tab[d]);
  362. register uint8_t r8 = d & 0xFF;
  363. register uint8_t r9 = (d >> 8) & 0xFF;
  364. register uint8_t r10 = (d >> 16) & 0xFF;
  365. register uint8_t r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  366. register const uint8_t* ptab = inv_tab;
  367. __asm__ __volatile__(
  368. // %8:%7:%6 = interval
  369. // r31:r30: MUST be those registers, and they must point to the inv_tab
  370. " clr %13" "\n\t" // %13 = 0
  371. // Now we must compute
  372. // result = 0xFFFFFF / d
  373. // %8:%7:%6 = interval
  374. // %16:%15:%14 = nr
  375. // %13 = 0
  376. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  377. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  378. // for the same result - Using C division, it takes 500cycles to complete .
  379. " clr %3" "\n\t" // idx = 0
  380. " mov %14,%6" "\n\t"
  381. " mov %15,%7" "\n\t"
  382. " mov %16,%8" "\n\t" // nr = interval
  383. " tst %16" "\n\t" // nr & 0xFF0000 == 0 ?
  384. " brne 2f" "\n\t" // No, skip this
  385. " mov %16,%15" "\n\t"
  386. " mov %15,%14" "\n\t" // nr <<= 8, %14 not needed
  387. " subi %3,-8" "\n\t" // idx += 8
  388. " tst %16" "\n\t" // nr & 0xFF0000 == 0 ?
  389. " brne 2f" "\n\t" // No, skip this
  390. " mov %16,%15" "\n\t" // nr <<= 8, %14 not needed
  391. " clr %15" "\n\t" // We clear %14
  392. " subi %3,-8" "\n\t" // idx += 8
  393. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  394. "2:" "\n\t"
  395. " cpi %16,0x10" "\n\t" // (nr & 0xf00000) == 0 ?
  396. " brcc 3f" "\n\t" // No, skip this
  397. " swap %15" "\n\t" // Swap nibbles
  398. " swap %16" "\n\t" // Swap nibbles. Low nibble is 0
  399. " mov %14, %15" "\n\t"
  400. " andi %14,0x0f" "\n\t" // Isolate low nibble
  401. " andi %15,0xf0" "\n\t" // Keep proper nibble in %15
  402. " or %16, %14" "\n\t" // %16:%15 <<= 4
  403. " subi %3,-4" "\n\t" // idx += 4
  404. "3:" "\n\t"
  405. " cpi %16,0x40" "\n\t" // (nr & 0xc00000) == 0 ?
  406. " brcc 4f" "\n\t" // No, skip this
  407. " add %15,%15" "\n\t"
  408. " adc %16,%16" "\n\t"
  409. " add %15,%15" "\n\t"
  410. " adc %16,%16" "\n\t" // %16:%15 <<= 2
  411. " subi %3,-2" "\n\t" // idx += 2
  412. "4:" "\n\t"
  413. " cpi %16,0x80" "\n\t" // (nr & 0x800000) == 0 ?
  414. " brcc 5f" "\n\t" // No, skip this
  415. " add %15,%15" "\n\t"
  416. " adc %16,%16" "\n\t" // %16:%15 <<= 1
  417. " inc %3" "\n\t" // idx += 1
  418. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  419. // we have at least 9 MSBits available to enter the initial estimation table
  420. "5:" "\n\t"
  421. " add %15,%15" "\n\t"
  422. " adc %16,%16" "\n\t" // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
  423. " add r30,%16" "\n\t" // Only use top 8 bits
  424. " adc r31,%13" "\n\t" // r31:r30 = inv_tab + (tidx)
  425. " lpm %14, Z" "\n\t" // %14 = inv_tab[tidx]
  426. " ldi %15, 1" "\n\t" // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  427. // We must scale the approximation to the proper place
  428. " clr %16" "\n\t" // %16 will always be 0 here
  429. " subi %3,8" "\n\t" // idx == 8 ?
  430. " breq 6f" "\n\t" // yes, no need to scale
  431. " brcs 7f" "\n\t" // If C=1, means idx < 8, result was negative!
  432. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  433. " sbrs %3,0" "\n\t" // shift by 1bit position?
  434. " rjmp 8f" "\n\t" // No
  435. " add %14,%14" "\n\t"
  436. " adc %15,%15" "\n\t" // %15:16 <<= 1
  437. "8:" "\n\t"
  438. " sbrs %3,1" "\n\t" // shift by 2bit position?
  439. " rjmp 9f" "\n\t" // No
  440. " add %14,%14" "\n\t"
  441. " adc %15,%15" "\n\t"
  442. " add %14,%14" "\n\t"
  443. " adc %15,%15" "\n\t" // %15:16 <<= 1
  444. "9:" "\n\t"
  445. " sbrs %3,2" "\n\t" // shift by 4bits position?
  446. " rjmp 16f" "\n\t" // No
  447. " swap %15" "\n\t" // Swap nibbles. lo nibble of %15 will always be 0
  448. " swap %14" "\n\t" // Swap nibbles
  449. " mov %12,%14" "\n\t"
  450. " andi %12,0x0f" "\n\t" // isolate low nibble
  451. " andi %14,0xf0" "\n\t" // and clear it
  452. " or %15,%12" "\n\t" // %15:%16 <<= 4
  453. "16:" "\n\t"
  454. " sbrs %3,3" "\n\t" // shift by 8bits position?
  455. " rjmp 6f" "\n\t" // No, we are done
  456. " mov %16,%15" "\n\t"
  457. " mov %15,%14" "\n\t"
  458. " clr %14" "\n\t"
  459. " jmp 6f" "\n\t"
  460. // idx < 8, now %3 = idx - 8. Get the count of bits
  461. "7:" "\n\t"
  462. " neg %3" "\n\t" // %3 = -idx = count of bits to move right. idx range:[1...8]
  463. " sbrs %3,0" "\n\t" // shift by 1 bit position ?
  464. " rjmp 10f" "\n\t" // No, skip it
  465. " asr %15" "\n\t" // (bit7 is always 0 here)
  466. " ror %14" "\n\t"
  467. "10:" "\n\t"
  468. " sbrs %3,1" "\n\t" // shift by 2 bit position ?
  469. " rjmp 11f" "\n\t" // No, skip it
  470. " asr %15" "\n\t" // (bit7 is always 0 here)
  471. " ror %14" "\n\t"
  472. " asr %15" "\n\t" // (bit7 is always 0 here)
  473. " ror %14" "\n\t"
  474. "11:" "\n\t"
  475. " sbrs %3,2" "\n\t" // shift by 4 bit position ?
  476. " rjmp 12f" "\n\t" // No, skip it
  477. " swap %15" "\n\t" // Swap nibbles
  478. " andi %14, 0xf0" "\n\t" // Lose the lowest nibble
  479. " swap %14" "\n\t" // Swap nibbles. Upper nibble is 0
  480. " or %14,%15" "\n\t" // Pass nibble from upper byte
  481. " andi %15, 0x0f" "\n\t" // And get rid of that nibble
  482. "12:" "\n\t"
  483. " sbrs %3,3" "\n\t" // shift by 8 bit position ?
  484. " rjmp 6f" "\n\t" // No, skip it
  485. " mov %14,%15" "\n\t"
  486. " clr %15" "\n\t"
  487. "6:" "\n\t" // %16:%15:%14 = initial estimation of 0x1000000 / d
  488. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  489. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  490. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  491. // precision to start from). 18bits of precision is all what is needed here for result
  492. // %8:%7:%6 = d = interval
  493. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  494. // %13 = 0
  495. // %3:%2:%1:%0 = working accumulator
  496. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  497. " clr %0" "\n\t"
  498. " clr %1" "\n\t"
  499. " clr %2" "\n\t"
  500. " ldi %3,2" "\n\t" // %3:%2:%1:%0 = 0x2000000
  501. " mul %6,%14" "\n\t" // r1:r0 = LO(d) * LO(x)
  502. " sub %0,r0" "\n\t"
  503. " sbc %1,r1" "\n\t"
  504. " sbc %2,%13" "\n\t"
  505. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * LO(x)
  506. " mul %7,%14" "\n\t" // r1:r0 = MI(d) * LO(x)
  507. " sub %1,r0" "\n\t"
  508. " sbc %2,r1" "\n\t"
  509. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  510. " mul %8,%14" "\n\t" // r1:r0 = HI(d) * LO(x)
  511. " sub %2,r0" "\n\t"
  512. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  513. " mul %6,%15" "\n\t" // r1:r0 = LO(d) * MI(x)
  514. " sub %1,r0" "\n\t"
  515. " sbc %2,r1" "\n\t"
  516. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  517. " mul %7,%15" "\n\t" // r1:r0 = MI(d) * MI(x)
  518. " sub %2,r0" "\n\t"
  519. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  520. " mul %8,%15" "\n\t" // r1:r0 = HI(d) * MI(x)
  521. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  522. " mul %6,%16" "\n\t" // r1:r0 = LO(d) * HI(x)
  523. " sub %2,r0" "\n\t"
  524. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  525. " mul %7,%16" "\n\t" // r1:r0 = MI(d) * HI(x)
  526. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  527. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  528. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  529. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  530. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  531. // %13 = 0
  532. // result = %11:%10:%9:%5:%4
  533. " mul %14,%0" "\n\t" // r1:r0 = LO(x) * LO(acc)
  534. " mov %4,r1" "\n\t"
  535. " clr %5" "\n\t"
  536. " clr %9" "\n\t"
  537. " clr %10" "\n\t"
  538. " clr %11" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  539. " mul %15,%0" "\n\t" // r1:r0 = MI(x) * LO(acc)
  540. " add %4,r0" "\n\t"
  541. " adc %5,r1" "\n\t"
  542. " adc %9,%13" "\n\t"
  543. " adc %10,%13" "\n\t"
  544. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  545. " mul %16,%0" "\n\t" // r1:r0 = HI(x) * LO(acc)
  546. " add %5,r0" "\n\t"
  547. " adc %9,r1" "\n\t"
  548. " adc %10,%13" "\n\t"
  549. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  550. " mul %14,%1" "\n\t" // r1:r0 = LO(x) * MIL(acc)
  551. " add %4,r0" "\n\t"
  552. " adc %5,r1" "\n\t"
  553. " adc %9,%13" "\n\t"
  554. " adc %10,%13" "\n\t"
  555. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  556. " mul %15,%1" "\n\t" // r1:r0 = MI(x) * MIL(acc)
  557. " add %5,r0" "\n\t"
  558. " adc %9,r1" "\n\t"
  559. " adc %10,%13" "\n\t"
  560. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
  561. " mul %16,%1" "\n\t" // r1:r0 = HI(x) * MIL(acc)
  562. " add %9,r0" "\n\t"
  563. " adc %10,r1" "\n\t"
  564. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  565. " mul %14,%2" "\n\t" // r1:r0 = LO(x) * MIH(acc)
  566. " add %5,r0" "\n\t"
  567. " adc %9,r1" "\n\t"
  568. " adc %10,%13" "\n\t"
  569. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  570. " mul %15,%2" "\n\t" // r1:r0 = MI(x) * MIH(acc)
  571. " add %9,r0" "\n\t"
  572. " adc %10,r1" "\n\t"
  573. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  574. " mul %16,%2" "\n\t" // r1:r0 = HI(x) * MIH(acc)
  575. " add %10,r0" "\n\t"
  576. " adc %11,r1" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  577. " mul %14,%3" "\n\t" // r1:r0 = LO(x) * HI(acc)
  578. " add %9,r0" "\n\t"
  579. " adc %10,r1" "\n\t"
  580. " adc %11,%13" "\n\t" // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  581. " mul %15,%3" "\n\t" // r1:r0 = MI(x) * HI(acc)
  582. " add %10,r0" "\n\t"
  583. " adc %11,r1" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  584. " mul %16,%3" "\n\t" // r1:r0 = HI(x) * HI(acc)
  585. " add %11,r0" "\n\t" // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  586. // At this point, %11:%10:%9 contains the new estimation of x.
  587. // Finally, we must correct the result. Estimate remainder as
  588. // (1<<24) - x*d
  589. // %11:%10:%9 = x
  590. // %8:%7:%6 = d = interval" "\n\t"
  591. " ldi %3,1" "\n\t"
  592. " clr %2" "\n\t"
  593. " clr %1" "\n\t"
  594. " clr %0" "\n\t" // %3:%2:%1:%0 = 0x1000000
  595. " mul %6,%9" "\n\t" // r1:r0 = LO(d) * LO(x)
  596. " sub %0,r0" "\n\t"
  597. " sbc %1,r1" "\n\t"
  598. " sbc %2,%13" "\n\t"
  599. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * LO(x)
  600. " mul %7,%9" "\n\t" // r1:r0 = MI(d) * LO(x)
  601. " sub %1,r0" "\n\t"
  602. " sbc %2,r1" "\n\t"
  603. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  604. " mul %8,%9" "\n\t" // r1:r0 = HI(d) * LO(x)
  605. " sub %2,r0" "\n\t"
  606. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  607. " mul %6,%10" "\n\t" // r1:r0 = LO(d) * MI(x)
  608. " sub %1,r0" "\n\t"
  609. " sbc %2,r1" "\n\t"
  610. " sbc %3,%13" "\n\t" // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  611. " mul %7,%10" "\n\t" // r1:r0 = MI(d) * MI(x)
  612. " sub %2,r0" "\n\t"
  613. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  614. " mul %8,%10" "\n\t" // r1:r0 = HI(d) * MI(x)
  615. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  616. " mul %6,%11" "\n\t" // r1:r0 = LO(d) * HI(x)
  617. " sub %2,r0" "\n\t"
  618. " sbc %3,r1" "\n\t" // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  619. " mul %7,%11" "\n\t" // r1:r0 = MI(d) * HI(x)
  620. " sub %3,r0" "\n\t" // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  621. // %3:%2:%1:%0 = r = (1<<24) - x*d
  622. // %8:%7:%6 = d = interval
  623. // Perform the final correction
  624. " sub %0,%6" "\n\t"
  625. " sbc %1,%7" "\n\t"
  626. " sbc %2,%8" "\n\t" // r -= d
  627. " brcs 14f" "\n\t" // if ( r >= d)
  628. // %11:%10:%9 = x
  629. " ldi %3,1" "\n\t"
  630. " add %9,%3" "\n\t"
  631. " adc %10,%13" "\n\t"
  632. " adc %11,%13" "\n\t" // x++
  633. "14:" "\n\t"
  634. // Estimation is done. %11:%10:%9 = x
  635. " clr __zero_reg__" "\n\t" // Make C runtime happy
  636. // [211 cycles total]
  637. : "=r" (r2),
  638. "=r" (r3),
  639. "=r" (r4),
  640. "=d" (r5),
  641. "=r" (r6),
  642. "=r" (r7),
  643. "+r" (r8),
  644. "+r" (r9),
  645. "+r" (r10),
  646. "=d" (r11),
  647. "=r" (r12),
  648. "=r" (r13),
  649. "=d" (r14),
  650. "=d" (r15),
  651. "=d" (r16),
  652. "=d" (r17),
  653. "=d" (r18),
  654. "+z" (ptab)
  655. :
  656. : "r0", "r1", "cc"
  657. );
  658. // Return the result
  659. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  660. }
  661. #else
  662. // All the other 32 CPUs can easily perform the inverse using hardware division,
  663. // so we don´t need to reduce precision or to use assembly language at all.
  664. // This routine, for all the other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  665. static FORCE_INLINE uint32_t get_period_inverse(uint32_t d) {
  666. return 0xFFFFFFFF / d;
  667. }
  668. #endif
  669. #endif
  670. #define MINIMAL_STEP_RATE 120
  671. /**
  672. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  673. * by the provided factors.
  674. */
  675. void Planner::calculate_trapezoid_for_block(block_t* const block, const float &entry_factor, const float &exit_factor) {
  676. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  677. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  678. // Limit minimal step rate (Otherwise the timer will overflow.)
  679. NOLESS(initial_rate, MINIMAL_STEP_RATE);
  680. NOLESS(final_rate, MINIMAL_STEP_RATE);
  681. #if ENABLED(BEZIER_JERK_CONTROL)
  682. uint32_t cruise_rate = initial_rate;
  683. #endif
  684. const int32_t accel = block->acceleration_steps_per_s2;
  685. // Steps required for acceleration, deceleration to/from nominal rate
  686. int32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  687. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel)),
  688. // Steps between acceleration and deceleration, if any
  689. plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  690. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  691. // Then we can't possibly reach the nominal rate, there will be no cruising.
  692. // Use intersection_distance() to calculate accel / braking time in order to
  693. // reach the final_rate exactly at the end of this block.
  694. if (plateau_steps < 0) {
  695. accelerate_steps = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  696. NOLESS(accelerate_steps, 0); // Check limits due to numerical round-off
  697. 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)
  698. plateau_steps = 0;
  699. #if ENABLED(BEZIER_JERK_CONTROL)
  700. // We won't reach the cruising rate. Let's calculate the speed we will reach
  701. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  702. #endif
  703. }
  704. #if ENABLED(BEZIER_JERK_CONTROL)
  705. else // We have some plateau time, so the cruise rate will be the nominal rate
  706. cruise_rate = block->nominal_rate;
  707. #endif
  708. // block->accelerate_until = accelerate_steps;
  709. // block->decelerate_after = accelerate_steps+plateau_steps;
  710. #if ENABLED(BEZIER_JERK_CONTROL)
  711. // Jerk controlled speed requires to express speed versus time, NOT steps
  712. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * HAL_STEPPER_TIMER_RATE,
  713. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * HAL_STEPPER_TIMER_RATE;
  714. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  715. uint32_t acceleration_time_inverse = get_period_inverse(acceleration_time);
  716. uint32_t deceleration_time_inverse = get_period_inverse(deceleration_time);
  717. #endif
  718. CRITICAL_SECTION_START; // Fill variables used by the stepper in a critical section
  719. if (!TEST(block->flag, BLOCK_BIT_BUSY)) { // Don't update variables if block is busy.
  720. block->accelerate_until = accelerate_steps;
  721. block->decelerate_after = accelerate_steps + plateau_steps;
  722. block->initial_rate = initial_rate;
  723. #if ENABLED(BEZIER_JERK_CONTROL)
  724. block->acceleration_time = acceleration_time;
  725. block->deceleration_time = deceleration_time;
  726. block->acceleration_time_inverse = acceleration_time_inverse;
  727. block->deceleration_time_inverse = deceleration_time_inverse;
  728. block->cruise_rate = cruise_rate;
  729. #endif
  730. block->final_rate = final_rate;
  731. }
  732. CRITICAL_SECTION_END;
  733. }
  734. // "Junction jerk" in this context is the immediate change in speed at the junction of two blocks.
  735. // This method will calculate the junction jerk as the euclidean distance between the nominal
  736. // velocities of the respective blocks.
  737. //inline float junction_jerk(block_t *before, block_t *after) {
  738. // return SQRT(
  739. // POW((before->speed_x-after->speed_x), 2)+POW((before->speed_y-after->speed_y), 2));
  740. //}
  741. // The kernel called by recalculate() when scanning the plan from last to first entry.
  742. void Planner::reverse_pass_kernel(block_t* const current, const block_t * const next) {
  743. if (!current || !next) return;
  744. // If entry speed is already at the maximum entry speed, no need to recheck. Block is cruising.
  745. // If not, block in state of acceleration or deceleration. Reset entry speed to maximum and
  746. // check for maximum allowable speed reductions to ensure maximum possible planned speed.
  747. float max_entry_speed = current->max_entry_speed;
  748. if (current->entry_speed != max_entry_speed) {
  749. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  750. // for max allowable speed if block is decelerating and nominal length is false.
  751. current->entry_speed = (TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH) || max_entry_speed <= next->entry_speed)
  752. ? max_entry_speed
  753. : min(max_entry_speed, max_allowable_speed(-current->acceleration, next->entry_speed, current->millimeters));
  754. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  755. }
  756. }
  757. /**
  758. * recalculate() needs to go over the current plan twice.
  759. * Once in reverse and once forward. This implements the reverse pass.
  760. */
  761. void Planner::reverse_pass() {
  762. if (movesplanned() > 2) {
  763. const uint8_t endnr = BLOCK_MOD(block_buffer_tail + 1); // tail is running. tail+1 shouldn't be altered because it's connected to the running block.
  764. uint8_t blocknr = prev_block_index(block_buffer_head);
  765. block_t* current = &block_buffer[blocknr];
  766. // Last/newest block in buffer:
  767. const float max_entry_speed = current->max_entry_speed;
  768. if (current->entry_speed != max_entry_speed) {
  769. // If nominal length true, max junction speed is guaranteed to be reached. Only compute
  770. // for max allowable speed if block is decelerating and nominal length is false.
  771. current->entry_speed = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  772. ? max_entry_speed
  773. : min(max_entry_speed, max_allowable_speed(-current->acceleration, MINIMUM_PLANNER_SPEED, current->millimeters));
  774. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  775. }
  776. do {
  777. const block_t * const next = current;
  778. blocknr = prev_block_index(blocknr);
  779. current = &block_buffer[blocknr];
  780. reverse_pass_kernel(current, next);
  781. } while (blocknr != endnr);
  782. }
  783. }
  784. // The kernel called by recalculate() when scanning the plan from first to last entry.
  785. void Planner::forward_pass_kernel(const block_t * const previous, block_t* const current) {
  786. if (!previous) return;
  787. // If the previous block is an acceleration block, but it is not long enough to complete the
  788. // full speed change within the block, we need to adjust the entry speed accordingly. Entry
  789. // speeds have already been reset, maximized, and reverse planned by reverse planner.
  790. // If nominal length is true, max junction speed is guaranteed to be reached. No need to recheck.
  791. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH)) {
  792. if (previous->entry_speed < current->entry_speed) {
  793. float entry_speed = min(current->entry_speed,
  794. max_allowable_speed(-previous->acceleration, previous->entry_speed, previous->millimeters));
  795. // Check for junction speed change
  796. if (current->entry_speed != entry_speed) {
  797. current->entry_speed = entry_speed;
  798. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  799. }
  800. }
  801. }
  802. }
  803. /**
  804. * recalculate() needs to go over the current plan twice.
  805. * Once in reverse and once forward. This implements the forward pass.
  806. */
  807. void Planner::forward_pass() {
  808. block_t* block[3] = { NULL, NULL, NULL };
  809. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  810. block[0] = block[1];
  811. block[1] = block[2];
  812. block[2] = &block_buffer[b];
  813. forward_pass_kernel(block[0], block[1]);
  814. }
  815. forward_pass_kernel(block[1], block[2]);
  816. }
  817. /**
  818. * Recalculate the trapezoid speed profiles for all blocks in the plan
  819. * according to the entry_factor for each junction. Must be called by
  820. * recalculate() after updating the blocks.
  821. */
  822. void Planner::recalculate_trapezoids() {
  823. int8_t block_index = block_buffer_tail;
  824. block_t *current, *next = NULL;
  825. while (block_index != block_buffer_head) {
  826. current = next;
  827. next = &block_buffer[block_index];
  828. if (current) {
  829. // Recalculate if current block entry or exit junction speed has changed.
  830. if (TEST(current->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  831. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  832. const float nomr = 1.0 / current->nominal_speed;
  833. calculate_trapezoid_for_block(current, current->entry_speed * nomr, next->entry_speed * nomr);
  834. #if ENABLED(LIN_ADVANCE)
  835. if (current->use_advance_lead) {
  836. const float comp = current->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  837. current->max_adv_steps = current->nominal_speed * comp;
  838. current->final_adv_steps = next->entry_speed * comp;
  839. }
  840. #endif
  841. CBI(current->flag, BLOCK_BIT_RECALCULATE); // Reset current only to ensure next trapezoid is computed
  842. }
  843. }
  844. block_index = next_block_index(block_index);
  845. }
  846. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  847. if (next) {
  848. const float nomr = 1.0 / next->nominal_speed;
  849. calculate_trapezoid_for_block(next, next->entry_speed * nomr, (MINIMUM_PLANNER_SPEED) * nomr);
  850. #if ENABLED(LIN_ADVANCE)
  851. if (next->use_advance_lead) {
  852. const float comp = next->e_D_ratio * extruder_advance_K * axis_steps_per_mm[E_AXIS];
  853. next->max_adv_steps = next->nominal_speed * comp;
  854. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  855. }
  856. #endif
  857. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  858. }
  859. }
  860. /**
  861. * Recalculate the motion plan according to the following algorithm:
  862. *
  863. * 1. Go over every block in reverse order...
  864. *
  865. * Calculate a junction speed reduction (block_t.entry_factor) so:
  866. *
  867. * a. The junction jerk is within the set limit, and
  868. *
  869. * b. No speed reduction within one block requires faster
  870. * deceleration than the one, true constant acceleration.
  871. *
  872. * 2. Go over every block in chronological order...
  873. *
  874. * Dial down junction speed reduction values if:
  875. * a. The speed increase within one block would require faster
  876. * acceleration than the one, true constant acceleration.
  877. *
  878. * After that, all blocks will have an entry_factor allowing all speed changes to
  879. * be performed using only the one, true constant acceleration, and where no junction
  880. * jerk is jerkier than the set limit, Jerky. Finally it will:
  881. *
  882. * 3. Recalculate "trapezoids" for all blocks.
  883. */
  884. void Planner::recalculate() {
  885. reverse_pass();
  886. forward_pass();
  887. recalculate_trapezoids();
  888. }
  889. #if ENABLED(AUTOTEMP)
  890. void Planner::getHighESpeed() {
  891. static float oldt = 0;
  892. if (!autotemp_enabled) return;
  893. if (thermalManager.degTargetHotend(0) + 2 < autotemp_min) return; // probably temperature set to zero.
  894. float high = 0.0;
  895. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  896. block_t* block = &block_buffer[b];
  897. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS]) {
  898. float se = (float)block->steps[E_AXIS] / block->step_event_count * block->nominal_speed; // mm/sec;
  899. NOLESS(high, se);
  900. }
  901. }
  902. float t = autotemp_min + high * autotemp_factor;
  903. t = constrain(t, autotemp_min, autotemp_max);
  904. if (t < oldt) t = t * (1 - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT);
  905. oldt = t;
  906. thermalManager.setTargetHotend(t, 0);
  907. }
  908. #endif // AUTOTEMP
  909. /**
  910. * Maintain fans, paste extruder pressure,
  911. */
  912. void Planner::check_axes_activity() {
  913. unsigned char axis_active[NUM_AXIS] = { 0 },
  914. tail_fan_speed[FAN_COUNT];
  915. #if ENABLED(BARICUDA)
  916. #if HAS_HEATER_1
  917. uint8_t tail_valve_pressure;
  918. #endif
  919. #if HAS_HEATER_2
  920. uint8_t tail_e_to_p_pressure;
  921. #endif
  922. #endif
  923. if (has_blocks_queued()) {
  924. #if FAN_COUNT > 0
  925. for (uint8_t i = 0; i < FAN_COUNT; i++)
  926. tail_fan_speed[i] = block_buffer[block_buffer_tail].fan_speed[i];
  927. #endif
  928. block_t* block;
  929. #if ENABLED(BARICUDA)
  930. block = &block_buffer[block_buffer_tail];
  931. #if HAS_HEATER_1
  932. tail_valve_pressure = block->valve_pressure;
  933. #endif
  934. #if HAS_HEATER_2
  935. tail_e_to_p_pressure = block->e_to_p_pressure;
  936. #endif
  937. #endif
  938. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  939. block = &block_buffer[b];
  940. LOOP_XYZE(i) if (block->steps[i]) axis_active[i]++;
  941. }
  942. }
  943. else {
  944. #if FAN_COUNT > 0
  945. for (uint8_t i = 0; i < FAN_COUNT; i++) tail_fan_speed[i] = fanSpeeds[i];
  946. #endif
  947. #if ENABLED(BARICUDA)
  948. #if HAS_HEATER_1
  949. tail_valve_pressure = baricuda_valve_pressure;
  950. #endif
  951. #if HAS_HEATER_2
  952. tail_e_to_p_pressure = baricuda_e_to_p_pressure;
  953. #endif
  954. #endif
  955. }
  956. #if ENABLED(DISABLE_X)
  957. if (!axis_active[X_AXIS]) disable_X();
  958. #endif
  959. #if ENABLED(DISABLE_Y)
  960. if (!axis_active[Y_AXIS]) disable_Y();
  961. #endif
  962. #if ENABLED(DISABLE_Z)
  963. if (!axis_active[Z_AXIS]) disable_Z();
  964. #endif
  965. #if ENABLED(DISABLE_E)
  966. if (!axis_active[E_AXIS]) disable_e_steppers();
  967. #endif
  968. #if FAN_COUNT > 0
  969. #if FAN_KICKSTART_TIME > 0
  970. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  971. #define KICKSTART_FAN(f) \
  972. if (tail_fan_speed[f]) { \
  973. millis_t ms = millis(); \
  974. if (fan_kick_end[f] == 0) { \
  975. fan_kick_end[f] = ms + FAN_KICKSTART_TIME; \
  976. tail_fan_speed[f] = 255; \
  977. } else if (PENDING(ms, fan_kick_end[f])) \
  978. tail_fan_speed[f] = 255; \
  979. } else fan_kick_end[f] = 0
  980. #if HAS_FAN0
  981. KICKSTART_FAN(0);
  982. #endif
  983. #if HAS_FAN1
  984. KICKSTART_FAN(1);
  985. #endif
  986. #if HAS_FAN2
  987. KICKSTART_FAN(2);
  988. #endif
  989. #endif // FAN_KICKSTART_TIME > 0
  990. #ifdef FAN_MIN_PWM
  991. #define CALC_FAN_SPEED(f) (tail_fan_speed[f] ? ( FAN_MIN_PWM + (tail_fan_speed[f] * (255 - FAN_MIN_PWM)) / 255 ) : 0)
  992. #else
  993. #define CALC_FAN_SPEED(f) tail_fan_speed[f]
  994. #endif
  995. #if ENABLED(FAN_SOFT_PWM)
  996. #if HAS_FAN0
  997. thermalManager.soft_pwm_amount_fan[0] = CALC_FAN_SPEED(0);
  998. #endif
  999. #if HAS_FAN1
  1000. thermalManager.soft_pwm_amount_fan[1] = CALC_FAN_SPEED(1);
  1001. #endif
  1002. #if HAS_FAN2
  1003. thermalManager.soft_pwm_amount_fan[2] = CALC_FAN_SPEED(2);
  1004. #endif
  1005. #else
  1006. #if HAS_FAN0
  1007. analogWrite(FAN_PIN, CALC_FAN_SPEED(0));
  1008. #endif
  1009. #if HAS_FAN1
  1010. analogWrite(FAN1_PIN, CALC_FAN_SPEED(1));
  1011. #endif
  1012. #if HAS_FAN2
  1013. analogWrite(FAN2_PIN, CALC_FAN_SPEED(2));
  1014. #endif
  1015. #endif
  1016. #endif // FAN_COUNT > 0
  1017. #if ENABLED(AUTOTEMP)
  1018. getHighESpeed();
  1019. #endif
  1020. #if ENABLED(BARICUDA)
  1021. #if HAS_HEATER_1
  1022. analogWrite(HEATER_1_PIN, tail_valve_pressure);
  1023. #endif
  1024. #if HAS_HEATER_2
  1025. analogWrite(HEATER_2_PIN, tail_e_to_p_pressure);
  1026. #endif
  1027. #endif
  1028. }
  1029. #if DISABLED(NO_VOLUMETRICS)
  1030. /**
  1031. * Get a volumetric multiplier from a filament diameter.
  1032. * This is the reciprocal of the circular cross-section area.
  1033. * Return 1.0 with volumetric off or a diameter of 0.0.
  1034. */
  1035. inline float calculate_volumetric_multiplier(const float &diameter) {
  1036. return (parser.volumetric_enabled && diameter) ? 1.0 / CIRCLE_AREA(diameter * 0.5) : 1.0;
  1037. }
  1038. /**
  1039. * Convert the filament sizes into volumetric multipliers.
  1040. * The multiplier converts a given E value into a length.
  1041. */
  1042. void Planner::calculate_volumetric_multipliers() {
  1043. for (uint8_t i = 0; i < COUNT(filament_size); i++) {
  1044. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1045. refresh_e_factor(i);
  1046. }
  1047. }
  1048. #endif // !NO_VOLUMETRICS
  1049. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1050. /**
  1051. * Convert the ratio value given by the filament width sensor
  1052. * into a volumetric multiplier. Conversion differs when using
  1053. * linear extrusion vs volumetric extrusion.
  1054. */
  1055. void Planner::calculate_volumetric_for_width_sensor(const int8_t encoded_ratio) {
  1056. // Reconstitute the nominal/measured ratio
  1057. const float nom_meas_ratio = 1.0 + 0.01 * encoded_ratio,
  1058. ratio_2 = sq(nom_meas_ratio);
  1059. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1060. ? ratio_2 / CIRCLE_AREA(filament_width_nominal * 0.5) // Volumetric uses a true volumetric multiplier
  1061. : ratio_2; // Linear squares the ratio, which scales the volume
  1062. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1063. }
  1064. #endif
  1065. #if PLANNER_LEVELING
  1066. /**
  1067. * rx, ry, rz - Cartesian positions in mm
  1068. * Leveled XYZ on completion
  1069. */
  1070. void Planner::apply_leveling(float &rx, float &ry, float &rz) {
  1071. #if ENABLED(SKEW_CORRECTION)
  1072. skew(rx, ry, rz);
  1073. #endif
  1074. if (!leveling_active) return;
  1075. #if ABL_PLANAR
  1076. float dx = rx - (X_TILT_FULCRUM),
  1077. dy = ry - (Y_TILT_FULCRUM);
  1078. apply_rotation_xyz(bed_level_matrix, dx, dy, rz);
  1079. rx = dx + X_TILT_FULCRUM;
  1080. ry = dy + Y_TILT_FULCRUM;
  1081. #elif HAS_MESH
  1082. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1083. const float fade_scaling_factor = fade_scaling_factor_for_z(rz);
  1084. #else
  1085. constexpr float fade_scaling_factor = 1.0;
  1086. #endif
  1087. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1088. const float raw[XYZ] = { rx, ry, 0 };
  1089. #endif
  1090. rz += (
  1091. #if ENABLED(MESH_BED_LEVELING)
  1092. mbl.get_z(rx, ry
  1093. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1094. , fade_scaling_factor
  1095. #endif
  1096. )
  1097. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1098. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(rx, ry) : 0.0
  1099. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1100. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1101. #endif
  1102. );
  1103. #endif
  1104. }
  1105. void Planner::unapply_leveling(float raw[XYZ]) {
  1106. if (leveling_active) {
  1107. #if ABL_PLANAR
  1108. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1109. float dx = raw[X_AXIS] - (X_TILT_FULCRUM),
  1110. dy = raw[Y_AXIS] - (Y_TILT_FULCRUM);
  1111. apply_rotation_xyz(inverse, dx, dy, raw[Z_AXIS]);
  1112. raw[X_AXIS] = dx + X_TILT_FULCRUM;
  1113. raw[Y_AXIS] = dy + Y_TILT_FULCRUM;
  1114. #elif HAS_MESH
  1115. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1116. const float fade_scaling_factor = fade_scaling_factor_for_z(raw[Z_AXIS]);
  1117. #else
  1118. constexpr float fade_scaling_factor = 1.0;
  1119. #endif
  1120. raw[Z_AXIS] -= (
  1121. #if ENABLED(MESH_BED_LEVELING)
  1122. mbl.get_z(raw[X_AXIS], raw[Y_AXIS]
  1123. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1124. , fade_scaling_factor
  1125. #endif
  1126. )
  1127. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1128. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw[X_AXIS], raw[Y_AXIS]) : 0.0
  1129. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1130. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1131. #endif
  1132. );
  1133. #endif
  1134. }
  1135. #if ENABLED(SKEW_CORRECTION)
  1136. unskew(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS]);
  1137. #endif
  1138. }
  1139. #endif // PLANNER_LEVELING
  1140. /**
  1141. * Planner::_buffer_steps
  1142. *
  1143. * Add a new linear movement to the buffer (in terms of steps).
  1144. *
  1145. * target - target position in steps units
  1146. * fr_mm_s - (target) speed of the move
  1147. * extruder - target extruder
  1148. */
  1149. void Planner::_buffer_steps(const int32_t (&target)[XYZE]
  1150. #if HAS_POSITION_FLOAT
  1151. , const float (&target_float)[XYZE]
  1152. #endif
  1153. , float fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/
  1154. ) {
  1155. const int32_t da = target[A_AXIS] - position[A_AXIS],
  1156. db = target[B_AXIS] - position[B_AXIS],
  1157. dc = target[C_AXIS] - position[C_AXIS];
  1158. int32_t de = target[E_AXIS] - position[E_AXIS];
  1159. /* <-- add a slash to enable
  1160. SERIAL_ECHOPAIR(" _buffer_steps FR:", fr_mm_s);
  1161. SERIAL_ECHOPAIR(" A:", target[A_AXIS]);
  1162. SERIAL_ECHOPAIR(" (", da);
  1163. SERIAL_ECHOPAIR(" steps) B:", target[B_AXIS]);
  1164. SERIAL_ECHOPAIR(" (", db);
  1165. SERIAL_ECHOPAIR(" steps) C:", target[C_AXIS]);
  1166. SERIAL_ECHOPAIR(" (", dc);
  1167. SERIAL_ECHOPAIR(" steps) E:", target[E_AXIS]);
  1168. SERIAL_ECHOPAIR(" (", de);
  1169. SERIAL_ECHOLNPGM(" steps)");
  1170. //*/
  1171. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1172. if (de) {
  1173. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1174. if (thermalManager.tooColdToExtrude(extruder)) {
  1175. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1176. #if HAS_POSITION_FLOAT
  1177. position_float[E_AXIS] = target_float[E_AXIS];
  1178. #endif
  1179. de = 0; // no difference
  1180. SERIAL_ECHO_START();
  1181. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  1182. }
  1183. #endif // PREVENT_COLD_EXTRUSION
  1184. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1185. if (labs(de * e_factor[extruder]) > (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
  1186. position[E_AXIS] = target[E_AXIS]; // Behave as if the move really took place, but ignore E part
  1187. #if HAS_POSITION_FLOAT
  1188. position_float[E_AXIS] = target_float[E_AXIS];
  1189. #endif
  1190. de = 0; // no difference
  1191. SERIAL_ECHO_START();
  1192. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  1193. }
  1194. #endif // PREVENT_LENGTHY_EXTRUDE
  1195. }
  1196. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1197. // Compute direction bit-mask for this block
  1198. uint8_t dm = 0;
  1199. #if CORE_IS_XY
  1200. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1201. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1202. if (dc < 0) SBI(dm, Z_AXIS);
  1203. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1204. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1205. #elif CORE_IS_XZ
  1206. if (da < 0) SBI(dm, X_HEAD); // Save the real Extruder (head) direction in X Axis
  1207. if (db < 0) SBI(dm, Y_AXIS);
  1208. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1209. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1210. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1211. #elif CORE_IS_YZ
  1212. if (da < 0) SBI(dm, X_AXIS);
  1213. if (db < 0) SBI(dm, Y_HEAD); // Save the real Extruder (head) direction in Y Axis
  1214. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1215. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1216. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1217. #else
  1218. if (da < 0) SBI(dm, X_AXIS);
  1219. if (db < 0) SBI(dm, Y_AXIS);
  1220. if (dc < 0) SBI(dm, Z_AXIS);
  1221. #endif
  1222. if (de < 0) SBI(dm, E_AXIS);
  1223. const float esteps_float = de * e_factor[extruder];
  1224. const int32_t esteps = abs(esteps_float) + 0.5;
  1225. // Wait for the next available block
  1226. uint8_t next_buffer_head;
  1227. block_t * const block = get_next_free_block(next_buffer_head);
  1228. // Clear all flags, including the "busy" bit
  1229. block->flag = 0x00;
  1230. // Set direction bits
  1231. block->direction_bits = dm;
  1232. // Number of steps for each axis
  1233. // See http://www.corexy.com/theory.html
  1234. #if CORE_IS_XY
  1235. block->steps[A_AXIS] = labs(da + db);
  1236. block->steps[B_AXIS] = labs(da - db);
  1237. block->steps[Z_AXIS] = labs(dc);
  1238. #elif CORE_IS_XZ
  1239. block->steps[A_AXIS] = labs(da + dc);
  1240. block->steps[Y_AXIS] = labs(db);
  1241. block->steps[C_AXIS] = labs(da - dc);
  1242. #elif CORE_IS_YZ
  1243. block->steps[X_AXIS] = labs(da);
  1244. block->steps[B_AXIS] = labs(db + dc);
  1245. block->steps[C_AXIS] = labs(db - dc);
  1246. #elif IS_SCARA
  1247. block->steps[A_AXIS] = labs(da);
  1248. block->steps[B_AXIS] = labs(db);
  1249. block->steps[Z_AXIS] = labs(dc);
  1250. #else
  1251. // default non-h-bot planning
  1252. block->steps[A_AXIS] = labs(da);
  1253. block->steps[B_AXIS] = labs(db);
  1254. block->steps[C_AXIS] = labs(dc);
  1255. #endif
  1256. block->steps[E_AXIS] = esteps;
  1257. block->step_event_count = MAX4(block->steps[A_AXIS], block->steps[B_AXIS], block->steps[C_AXIS], esteps);
  1258. // Bail if this is a zero-length block
  1259. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return;
  1260. // For a mixing extruder, get a magnified step_event_count for each
  1261. #if ENABLED(MIXING_EXTRUDER)
  1262. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  1263. block->mix_event_count[i] = mixing_factor[i] * block->step_event_count;
  1264. #endif
  1265. #if FAN_COUNT > 0
  1266. for (uint8_t i = 0; i < FAN_COUNT; i++) block->fan_speed[i] = fanSpeeds[i];
  1267. #endif
  1268. #if ENABLED(BARICUDA)
  1269. block->valve_pressure = baricuda_valve_pressure;
  1270. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1271. #endif
  1272. block->active_extruder = extruder;
  1273. #if ENABLED(AUTO_POWER_CONTROL)
  1274. if (block->steps[X_AXIS] || block->steps[Y_AXIS] || block->steps[Z_AXIS])
  1275. powerManager.power_on();
  1276. #endif
  1277. // Enable active axes
  1278. #if CORE_IS_XY
  1279. if (block->steps[A_AXIS] || block->steps[B_AXIS]) {
  1280. enable_X();
  1281. enable_Y();
  1282. }
  1283. #if DISABLED(Z_LATE_ENABLE)
  1284. if (block->steps[Z_AXIS]) enable_Z();
  1285. #endif
  1286. #elif CORE_IS_XZ
  1287. if (block->steps[A_AXIS] || block->steps[C_AXIS]) {
  1288. enable_X();
  1289. enable_Z();
  1290. }
  1291. if (block->steps[Y_AXIS]) enable_Y();
  1292. #elif CORE_IS_YZ
  1293. if (block->steps[B_AXIS] || block->steps[C_AXIS]) {
  1294. enable_Y();
  1295. enable_Z();
  1296. }
  1297. if (block->steps[X_AXIS]) enable_X();
  1298. #else
  1299. if (block->steps[X_AXIS]) enable_X();
  1300. if (block->steps[Y_AXIS]) enable_Y();
  1301. #if DISABLED(Z_LATE_ENABLE)
  1302. if (block->steps[Z_AXIS]) enable_Z();
  1303. #endif
  1304. #endif
  1305. // Enable extruder(s)
  1306. if (esteps) {
  1307. #if ENABLED(AUTO_POWER_CONTROL)
  1308. powerManager.power_on();
  1309. #endif
  1310. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1311. #define DISABLE_IDLE_E(N) if (!g_uc_extruder_last_move[N]) disable_E##N();
  1312. for (uint8_t i = 0; i < EXTRUDERS; i++)
  1313. if (g_uc_extruder_last_move[i] > 0) g_uc_extruder_last_move[i]--;
  1314. switch (extruder) {
  1315. case 0:
  1316. #if EXTRUDERS > 1
  1317. DISABLE_IDLE_E(1);
  1318. #if EXTRUDERS > 2
  1319. DISABLE_IDLE_E(2);
  1320. #if EXTRUDERS > 3
  1321. DISABLE_IDLE_E(3);
  1322. #if EXTRUDERS > 4
  1323. DISABLE_IDLE_E(4);
  1324. #endif // EXTRUDERS > 4
  1325. #endif // EXTRUDERS > 3
  1326. #endif // EXTRUDERS > 2
  1327. #endif // EXTRUDERS > 1
  1328. enable_E0();
  1329. g_uc_extruder_last_move[0] = (BLOCK_BUFFER_SIZE) * 2;
  1330. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1331. if (extruder_duplication_enabled) {
  1332. enable_E1();
  1333. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1334. }
  1335. #endif
  1336. break;
  1337. #if EXTRUDERS > 1
  1338. case 1:
  1339. DISABLE_IDLE_E(0);
  1340. #if EXTRUDERS > 2
  1341. DISABLE_IDLE_E(2);
  1342. #if EXTRUDERS > 3
  1343. DISABLE_IDLE_E(3);
  1344. #if EXTRUDERS > 4
  1345. DISABLE_IDLE_E(4);
  1346. #endif // EXTRUDERS > 4
  1347. #endif // EXTRUDERS > 3
  1348. #endif // EXTRUDERS > 2
  1349. enable_E1();
  1350. g_uc_extruder_last_move[1] = (BLOCK_BUFFER_SIZE) * 2;
  1351. break;
  1352. #if EXTRUDERS > 2
  1353. case 2:
  1354. DISABLE_IDLE_E(0);
  1355. DISABLE_IDLE_E(1);
  1356. #if EXTRUDERS > 3
  1357. DISABLE_IDLE_E(3);
  1358. #if EXTRUDERS > 4
  1359. DISABLE_IDLE_E(4);
  1360. #endif
  1361. #endif
  1362. enable_E2();
  1363. g_uc_extruder_last_move[2] = (BLOCK_BUFFER_SIZE) * 2;
  1364. break;
  1365. #if EXTRUDERS > 3
  1366. case 3:
  1367. DISABLE_IDLE_E(0);
  1368. DISABLE_IDLE_E(1);
  1369. DISABLE_IDLE_E(2);
  1370. #if EXTRUDERS > 4
  1371. DISABLE_IDLE_E(4);
  1372. #endif
  1373. enable_E3();
  1374. g_uc_extruder_last_move[3] = (BLOCK_BUFFER_SIZE) * 2;
  1375. break;
  1376. #if EXTRUDERS > 4
  1377. case 4:
  1378. DISABLE_IDLE_E(0);
  1379. DISABLE_IDLE_E(1);
  1380. DISABLE_IDLE_E(2);
  1381. DISABLE_IDLE_E(3);
  1382. enable_E4();
  1383. g_uc_extruder_last_move[4] = (BLOCK_BUFFER_SIZE) * 2;
  1384. break;
  1385. #endif // EXTRUDERS > 4
  1386. #endif // EXTRUDERS > 3
  1387. #endif // EXTRUDERS > 2
  1388. #endif // EXTRUDERS > 1
  1389. }
  1390. #else
  1391. enable_E0();
  1392. enable_E1();
  1393. enable_E2();
  1394. enable_E3();
  1395. enable_E4();
  1396. #endif
  1397. }
  1398. if (esteps)
  1399. NOLESS(fr_mm_s, min_feedrate_mm_s);
  1400. else
  1401. NOLESS(fr_mm_s, min_travel_feedrate_mm_s);
  1402. /**
  1403. * This part of the code calculates the total length of the movement.
  1404. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1405. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1406. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1407. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1408. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1409. */
  1410. #if IS_CORE
  1411. float delta_mm[Z_HEAD + 1];
  1412. #if CORE_IS_XY
  1413. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1414. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1415. delta_mm[Z_AXIS] = dc * steps_to_mm[Z_AXIS];
  1416. delta_mm[A_AXIS] = (da + db) * steps_to_mm[A_AXIS];
  1417. delta_mm[B_AXIS] = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1418. #elif CORE_IS_XZ
  1419. delta_mm[X_HEAD] = da * steps_to_mm[A_AXIS];
  1420. delta_mm[Y_AXIS] = db * steps_to_mm[Y_AXIS];
  1421. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1422. delta_mm[A_AXIS] = (da + dc) * steps_to_mm[A_AXIS];
  1423. delta_mm[C_AXIS] = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1424. #elif CORE_IS_YZ
  1425. delta_mm[X_AXIS] = da * steps_to_mm[X_AXIS];
  1426. delta_mm[Y_HEAD] = db * steps_to_mm[B_AXIS];
  1427. delta_mm[Z_HEAD] = dc * steps_to_mm[C_AXIS];
  1428. delta_mm[B_AXIS] = (db + dc) * steps_to_mm[B_AXIS];
  1429. delta_mm[C_AXIS] = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1430. #endif
  1431. #else
  1432. float delta_mm[ABCE];
  1433. delta_mm[A_AXIS] = da * steps_to_mm[A_AXIS];
  1434. delta_mm[B_AXIS] = db * steps_to_mm[B_AXIS];
  1435. delta_mm[C_AXIS] = dc * steps_to_mm[C_AXIS];
  1436. #endif
  1437. delta_mm[E_AXIS] = esteps_float * steps_to_mm[E_AXIS_N];
  1438. if (block->steps[A_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[B_AXIS] < MIN_STEPS_PER_SEGMENT && block->steps[C_AXIS] < MIN_STEPS_PER_SEGMENT) {
  1439. block->millimeters = FABS(delta_mm[E_AXIS]);
  1440. }
  1441. else if (!millimeters) {
  1442. block->millimeters = SQRT(
  1443. #if CORE_IS_XY
  1444. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_AXIS])
  1445. #elif CORE_IS_XZ
  1446. sq(delta_mm[X_HEAD]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_HEAD])
  1447. #elif CORE_IS_YZ
  1448. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_HEAD]) + sq(delta_mm[Z_HEAD])
  1449. #else
  1450. sq(delta_mm[X_AXIS]) + sq(delta_mm[Y_AXIS]) + sq(delta_mm[Z_AXIS])
  1451. #endif
  1452. );
  1453. }
  1454. else
  1455. block->millimeters = millimeters;
  1456. const float inverse_millimeters = 1.0 / block->millimeters; // Inverse millimeters to remove multiple divides
  1457. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1458. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1459. float inverse_secs = fr_mm_s * inverse_millimeters;
  1460. const uint8_t moves_queued = movesplanned();
  1461. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1462. #if ENABLED(SLOWDOWN) || ENABLED(ULTRA_LCD) || defined(XY_FREQUENCY_LIMIT)
  1463. // Segment time im micro seconds
  1464. uint32_t segment_time_us = LROUND(1000000.0 / inverse_secs);
  1465. #endif
  1466. #if ENABLED(SLOWDOWN)
  1467. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / 2 - 1)) {
  1468. if (segment_time_us < min_segment_time_us) {
  1469. // buffer is draining, add extra time. The amount of time added increases if the buffer is still emptied more.
  1470. const uint32_t nst = segment_time_us + LROUND(2 * (min_segment_time_us - segment_time_us) / moves_queued);
  1471. inverse_secs = 1000000.0 / nst;
  1472. #if defined(XY_FREQUENCY_LIMIT) || ENABLED(ULTRA_LCD)
  1473. segment_time_us = nst;
  1474. #endif
  1475. }
  1476. }
  1477. #endif
  1478. #if ENABLED(ULTRA_LCD)
  1479. CRITICAL_SECTION_START
  1480. block_buffer_runtime_us += segment_time_us;
  1481. CRITICAL_SECTION_END
  1482. #endif
  1483. block->nominal_speed = block->millimeters * inverse_secs; // (mm/sec) Always > 0
  1484. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1485. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1486. static float filwidth_e_count = 0, filwidth_delay_dist = 0;
  1487. //FMM update ring buffer used for delay with filament measurements
  1488. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM && filwidth_delay_index[1] >= 0) { //only for extruder with filament sensor and if ring buffer is initialized
  1489. constexpr int MMD_CM = MAX_MEASUREMENT_DELAY + 1, MMD_MM = MMD_CM * 10;
  1490. // increment counters with next move in e axis
  1491. filwidth_e_count += delta_mm[E_AXIS];
  1492. filwidth_delay_dist += delta_mm[E_AXIS];
  1493. // Only get new measurements on forward E movement
  1494. if (!UNEAR_ZERO(filwidth_e_count)) {
  1495. // Loop the delay distance counter (modulus by the mm length)
  1496. while (filwidth_delay_dist >= MMD_MM) filwidth_delay_dist -= MMD_MM;
  1497. // Convert into an index into the measurement array
  1498. filwidth_delay_index[0] = int8_t(filwidth_delay_dist * 0.1);
  1499. // If the index has changed (must have gone forward)...
  1500. if (filwidth_delay_index[0] != filwidth_delay_index[1]) {
  1501. filwidth_e_count = 0; // Reset the E movement counter
  1502. const int8_t meas_sample = thermalManager.widthFil_to_size_ratio();
  1503. do {
  1504. filwidth_delay_index[1] = (filwidth_delay_index[1] + 1) % MMD_CM; // The next unused slot
  1505. measurement_delay[filwidth_delay_index[1]] = meas_sample; // Store the measurement
  1506. } while (filwidth_delay_index[0] != filwidth_delay_index[1]); // More slots to fill?
  1507. }
  1508. }
  1509. }
  1510. #endif
  1511. // Calculate and limit speed in mm/sec for each axis
  1512. float current_speed[NUM_AXIS], speed_factor = 1.0; // factor <1 decreases speed
  1513. LOOP_XYZE(i) {
  1514. const float cs = FABS((current_speed[i] = delta_mm[i] * inverse_secs));
  1515. #if ENABLED(DISTINCT_E_FACTORS)
  1516. if (i == E_AXIS) i += extruder;
  1517. #endif
  1518. if (cs > max_feedrate_mm_s[i]) NOMORE(speed_factor, max_feedrate_mm_s[i] / cs);
  1519. }
  1520. // Max segment time in µs.
  1521. #ifdef XY_FREQUENCY_LIMIT
  1522. // Check and limit the xy direction change frequency
  1523. const unsigned char direction_change = block->direction_bits ^ old_direction_bits;
  1524. old_direction_bits = block->direction_bits;
  1525. segment_time_us = LROUND((float)segment_time_us / speed_factor);
  1526. uint32_t xs0 = axis_segment_time_us[X_AXIS][0],
  1527. xs1 = axis_segment_time_us[X_AXIS][1],
  1528. xs2 = axis_segment_time_us[X_AXIS][2],
  1529. ys0 = axis_segment_time_us[Y_AXIS][0],
  1530. ys1 = axis_segment_time_us[Y_AXIS][1],
  1531. ys2 = axis_segment_time_us[Y_AXIS][2];
  1532. if (TEST(direction_change, X_AXIS)) {
  1533. xs2 = axis_segment_time_us[X_AXIS][2] = xs1;
  1534. xs1 = axis_segment_time_us[X_AXIS][1] = xs0;
  1535. xs0 = 0;
  1536. }
  1537. xs0 = axis_segment_time_us[X_AXIS][0] = xs0 + segment_time_us;
  1538. if (TEST(direction_change, Y_AXIS)) {
  1539. ys2 = axis_segment_time_us[Y_AXIS][2] = axis_segment_time_us[Y_AXIS][1];
  1540. ys1 = axis_segment_time_us[Y_AXIS][1] = axis_segment_time_us[Y_AXIS][0];
  1541. ys0 = 0;
  1542. }
  1543. ys0 = axis_segment_time_us[Y_AXIS][0] = ys0 + segment_time_us;
  1544. const uint32_t max_x_segment_time = MAX3(xs0, xs1, xs2),
  1545. max_y_segment_time = MAX3(ys0, ys1, ys2),
  1546. min_xy_segment_time = min(max_x_segment_time, max_y_segment_time);
  1547. if (min_xy_segment_time < MAX_FREQ_TIME_US) {
  1548. const float low_sf = speed_factor * min_xy_segment_time / (MAX_FREQ_TIME_US);
  1549. NOMORE(speed_factor, low_sf);
  1550. }
  1551. #endif // XY_FREQUENCY_LIMIT
  1552. // Correct the speed
  1553. if (speed_factor < 1.0) {
  1554. LOOP_XYZE(i) current_speed[i] *= speed_factor;
  1555. block->nominal_speed *= speed_factor;
  1556. block->nominal_rate *= speed_factor;
  1557. }
  1558. // Compute and limit the acceleration rate for the trapezoid generator.
  1559. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  1560. uint32_t accel;
  1561. if (!block->steps[A_AXIS] && !block->steps[B_AXIS] && !block->steps[C_AXIS]) {
  1562. // convert to: acceleration steps/sec^2
  1563. accel = CEIL(retract_acceleration * steps_per_mm);
  1564. #if ENABLED(LIN_ADVANCE)
  1565. block->use_advance_lead = false;
  1566. #endif
  1567. }
  1568. else {
  1569. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  1570. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1571. const uint32_t comp = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count; \
  1572. if (accel * block->steps[AXIS] > comp) accel = comp / block->steps[AXIS]; \
  1573. } \
  1574. }while(0)
  1575. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  1576. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  1577. const float comp = (float)max_acceleration_steps_per_s2[AXIS+INDX] * (float)block->step_event_count; \
  1578. if ((float)accel * (float)block->steps[AXIS] > comp) accel = comp / (float)block->steps[AXIS]; \
  1579. } \
  1580. }while(0)
  1581. // Start with print or travel acceleration
  1582. accel = CEIL((esteps ? acceleration : travel_acceleration) * steps_per_mm);
  1583. #if ENABLED(LIN_ADVANCE)
  1584. /**
  1585. *
  1586. * Use LIN_ADVANCE for blocks if all these are true:
  1587. *
  1588. * esteps : This is a print move, because we checked for A, B, C steps before.
  1589. *
  1590. * extruder_advance_K : There is an advance factor set.
  1591. *
  1592. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  1593. */
  1594. block->use_advance_lead = esteps
  1595. && extruder_advance_K
  1596. && de > 0;
  1597. if (block->use_advance_lead) {
  1598. block->e_D_ratio = (target_float[E_AXIS] - position_float[E_AXIS]) /
  1599. #if IS_KINEMATIC
  1600. block->millimeters
  1601. #else
  1602. SQRT(sq(target_float[X_AXIS] - position_float[X_AXIS])
  1603. + sq(target_float[Y_AXIS] - position_float[Y_AXIS])
  1604. + sq(target_float[Z_AXIS] - position_float[Z_AXIS]))
  1605. #endif
  1606. ;
  1607. // Check for unusual high e_D ratio to detect if a retract move was combined with the last print move due to min. steps per segment. Never execute this with advance!
  1608. // This assumes no one will use a retract length of 0mm < retr_length < ~0.2mm and no one will print 100mm wide lines using 3mm filament or 35mm wide lines using 1.75mm filament.
  1609. if (block->e_D_ratio > 3.0)
  1610. block->use_advance_lead = false;
  1611. else {
  1612. const uint32_t max_accel_steps_per_s2 = max_jerk[E_AXIS] / (extruder_advance_K * block->e_D_ratio) * steps_per_mm;
  1613. #if ENABLED(LA_DEBUG)
  1614. if (accel > max_accel_steps_per_s2)
  1615. SERIAL_ECHOLNPGM("Acceleration limited.");
  1616. #endif
  1617. NOMORE(accel, max_accel_steps_per_s2);
  1618. }
  1619. }
  1620. #endif
  1621. #if ENABLED(DISTINCT_E_FACTORS)
  1622. #define ACCEL_IDX extruder
  1623. #else
  1624. #define ACCEL_IDX 0
  1625. #endif
  1626. // Limit acceleration per axis
  1627. if (block->step_event_count <= cutoff_long) {
  1628. LIMIT_ACCEL_LONG(A_AXIS, 0);
  1629. LIMIT_ACCEL_LONG(B_AXIS, 0);
  1630. LIMIT_ACCEL_LONG(C_AXIS, 0);
  1631. LIMIT_ACCEL_LONG(E_AXIS, ACCEL_IDX);
  1632. }
  1633. else {
  1634. LIMIT_ACCEL_FLOAT(A_AXIS, 0);
  1635. LIMIT_ACCEL_FLOAT(B_AXIS, 0);
  1636. LIMIT_ACCEL_FLOAT(C_AXIS, 0);
  1637. LIMIT_ACCEL_FLOAT(E_AXIS, ACCEL_IDX);
  1638. }
  1639. }
  1640. block->acceleration_steps_per_s2 = accel;
  1641. block->acceleration = accel / steps_per_mm;
  1642. #if DISABLED(BEZIER_JERK_CONTROL)
  1643. block->acceleration_rate = (long)(accel * (4096.0 * 4096.0 / (HAL_STEPPER_TIMER_RATE)));
  1644. #endif
  1645. #if ENABLED(LIN_ADVANCE)
  1646. if (block->use_advance_lead) {
  1647. block->advance_speed = (HAL_STEPPER_TIMER_RATE) / (extruder_advance_K * block->e_D_ratio * block->acceleration * axis_steps_per_mm[E_AXIS_N]);
  1648. #if ENABLED(LA_DEBUG)
  1649. if (extruder_advance_K * block->e_D_ratio * block->acceleration * 2 < block->nominal_speed * block->e_D_ratio)
  1650. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  1651. if (block->advance_speed < 200)
  1652. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  1653. #endif
  1654. }
  1655. #endif
  1656. // Initial limit on the segment entry velocity
  1657. float vmax_junction;
  1658. #if 0 // Use old jerk for now
  1659. float junction_deviation = 0.1;
  1660. // Compute path unit vector
  1661. double unit_vec[XYZ] = {
  1662. delta_mm[A_AXIS] * inverse_millimeters,
  1663. delta_mm[B_AXIS] * inverse_millimeters,
  1664. delta_mm[C_AXIS] * inverse_millimeters
  1665. };
  1666. /*
  1667. Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  1668. Let a circle be tangent to both previous and current path line segments, where the junction
  1669. deviation is defined as the distance from the junction to the closest edge of the circle,
  1670. collinear with the circle center.
  1671. The circular segment joining the two paths represents the path of centripetal acceleration.
  1672. Solve for max velocity based on max acceleration about the radius of the circle, defined
  1673. indirectly by junction deviation.
  1674. This may be also viewed as path width or max_jerk in the previous grbl version. This approach
  1675. does not actually deviate from path, but used as a robust way to compute cornering speeds, as
  1676. it takes into account the nonlinearities of both the junction angle and junction velocity.
  1677. */
  1678. vmax_junction = MINIMUM_PLANNER_SPEED; // Set default max junction speed
  1679. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  1680. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1681. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  1682. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  1683. const float cos_theta = - previous_unit_vec[X_AXIS] * unit_vec[X_AXIS]
  1684. - previous_unit_vec[Y_AXIS] * unit_vec[Y_AXIS]
  1685. - previous_unit_vec[Z_AXIS] * unit_vec[Z_AXIS];
  1686. // Skip and use default max junction speed for 0 degree acute junction.
  1687. if (cos_theta < 0.95) {
  1688. vmax_junction = min(previous_nominal_speed, block->nominal_speed);
  1689. // Skip and avoid divide by zero for straight junctions at 180 degrees. Limit to min() of nominal speeds.
  1690. if (cos_theta > -0.95) {
  1691. // Compute maximum junction velocity based on maximum acceleration and junction deviation
  1692. float sin_theta_d2 = SQRT(0.5 * (1.0 - cos_theta)); // Trig half angle identity. Always positive.
  1693. NOMORE(vmax_junction, SQRT(block->acceleration * junction_deviation * sin_theta_d2 / (1.0 - sin_theta_d2)));
  1694. }
  1695. }
  1696. }
  1697. #endif
  1698. /**
  1699. * Adapted from Průša MKS firmware
  1700. * https://github.com/prusa3d/Prusa-Firmware
  1701. *
  1702. * Start with a safe speed (from which the machine may halt to stop immediately).
  1703. */
  1704. // Exit speed limited by a jerk to full halt of a previous last segment
  1705. static float previous_safe_speed;
  1706. float safe_speed = block->nominal_speed;
  1707. uint8_t limited = 0;
  1708. LOOP_XYZE(i) {
  1709. const float jerk = FABS(current_speed[i]), maxj = max_jerk[i];
  1710. if (jerk > maxj) {
  1711. if (limited) {
  1712. const float mjerk = maxj * block->nominal_speed;
  1713. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk;
  1714. }
  1715. else {
  1716. ++limited;
  1717. safe_speed = maxj;
  1718. }
  1719. }
  1720. }
  1721. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed)) {
  1722. // Estimate a maximum velocity allowed at a joint of two successive segments.
  1723. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  1724. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  1725. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  1726. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  1727. vmax_junction = min(block->nominal_speed, previous_nominal_speed);
  1728. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  1729. float v_factor = 1;
  1730. limited = 0;
  1731. // Now limit the jerk in all axes.
  1732. const float smaller_speed_factor = vmax_junction / previous_nominal_speed;
  1733. LOOP_XYZE(axis) {
  1734. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  1735. float v_exit = previous_speed[axis] * smaller_speed_factor,
  1736. v_entry = current_speed[axis];
  1737. if (limited) {
  1738. v_exit *= v_factor;
  1739. v_entry *= v_factor;
  1740. }
  1741. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  1742. const float jerk = (v_exit > v_entry)
  1743. ? // coasting axis reversal
  1744. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : max(v_exit, -v_entry) )
  1745. : // v_exit <= v_entry coasting axis reversal
  1746. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : max(-v_exit, v_entry) );
  1747. if (jerk > max_jerk[axis]) {
  1748. v_factor *= max_jerk[axis] / jerk;
  1749. ++limited;
  1750. }
  1751. }
  1752. if (limited) vmax_junction *= v_factor;
  1753. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  1754. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  1755. const float vmax_junction_threshold = vmax_junction * 0.99f;
  1756. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  1757. vmax_junction = safe_speed;
  1758. }
  1759. else
  1760. vmax_junction = safe_speed;
  1761. // Max entry speed of this block equals the max exit speed of the previous block.
  1762. block->max_entry_speed = vmax_junction;
  1763. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  1764. const float v_allowable = max_allowable_speed(-block->acceleration, MINIMUM_PLANNER_SPEED, block->millimeters);
  1765. // If stepper ISR is disabled, this indicates buffer_segment wants to add a split block.
  1766. // In this case start with the max. allowed speed to avoid an interrupted first move.
  1767. block->entry_speed = STEPPER_ISR_ENABLED() ? MINIMUM_PLANNER_SPEED : min(vmax_junction, v_allowable);
  1768. // Initialize planner efficiency flags
  1769. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  1770. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  1771. // the current block and next block junction speeds are guaranteed to always be at their maximum
  1772. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  1773. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  1774. // the reverse and forward planners, the corresponding block junction speed will always be at the
  1775. // the maximum junction speed and may always be ignored for any speed reduction checks.
  1776. block->flag |= block->nominal_speed <= v_allowable ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  1777. // Update previous path unit_vector and nominal speed
  1778. COPY(previous_speed, current_speed);
  1779. previous_nominal_speed = block->nominal_speed;
  1780. previous_safe_speed = safe_speed;
  1781. // Move buffer head
  1782. block_buffer_head = next_buffer_head;
  1783. // Update the position (only when a move was queued)
  1784. static_assert(COUNT(target) > 1, "Parameter to _buffer_steps must be (&target)[XYZE]!");
  1785. COPY(position, target);
  1786. #if HAS_POSITION_FLOAT
  1787. COPY(position_float, target_float);
  1788. #endif
  1789. recalculate();
  1790. } // _buffer_steps()
  1791. /**
  1792. * Planner::buffer_sync_block
  1793. * Add a block to the buffer that just updates the position
  1794. */
  1795. void Planner::buffer_sync_block() {
  1796. // Wait for the next available block
  1797. uint8_t next_buffer_head;
  1798. block_t * const block = get_next_free_block(next_buffer_head);
  1799. block->flag = BLOCK_FLAG_SYNC_POSITION;
  1800. block->steps[A_AXIS] = position[A_AXIS];
  1801. block->steps[B_AXIS] = position[B_AXIS];
  1802. block->steps[C_AXIS] = position[C_AXIS];
  1803. block->steps[E_AXIS] = position[E_AXIS];
  1804. #if ENABLED(LIN_ADVANCE)
  1805. block->use_advance_lead = false;
  1806. #endif
  1807. block->nominal_speed =
  1808. block->entry_speed =
  1809. block->max_entry_speed =
  1810. block->millimeters =
  1811. block->acceleration = 0;
  1812. block->step_event_count =
  1813. block->nominal_rate =
  1814. block->initial_rate =
  1815. block->final_rate =
  1816. block->acceleration_steps_per_s2 =
  1817. block->segment_time_us = 0;
  1818. block_buffer_head = next_buffer_head;
  1819. stepper.wake_up();
  1820. } // buffer_sync_block()
  1821. /**
  1822. * Planner::buffer_segment
  1823. *
  1824. * Add a new linear movement to the buffer in axis units.
  1825. *
  1826. * Leveling and kinematics should be applied ahead of calling this.
  1827. *
  1828. * a,b,c,e - target positions in mm and/or degrees
  1829. * fr_mm_s - (target) speed of the move
  1830. * extruder - target extruder
  1831. * millimeters - the length of the movement, if known
  1832. */
  1833. void Planner::buffer_segment(const float &a, const float &b, const float &c, const float &e, const float &fr_mm_s, const uint8_t extruder, const float &millimeters/*=0.0*/) {
  1834. // When changing extruders recalculate steps corresponding to the E position
  1835. #if ENABLED(DISTINCT_E_FACTORS)
  1836. if (last_extruder != extruder && axis_steps_per_mm[E_AXIS_N] != axis_steps_per_mm[E_AXIS + last_extruder]) {
  1837. position[E_AXIS] = LROUND(position[E_AXIS] * axis_steps_per_mm[E_AXIS_N] * steps_to_mm[E_AXIS + last_extruder]);
  1838. last_extruder = extruder;
  1839. }
  1840. #endif
  1841. // The target position of the tool in absolute steps
  1842. // Calculate target position in absolute steps
  1843. const int32_t target[ABCE] = {
  1844. LROUND(a * axis_steps_per_mm[A_AXIS]),
  1845. LROUND(b * axis_steps_per_mm[B_AXIS]),
  1846. LROUND(c * axis_steps_per_mm[C_AXIS]),
  1847. LROUND(e * axis_steps_per_mm[E_AXIS_N])
  1848. };
  1849. #if HAS_POSITION_FLOAT
  1850. const float target_float[XYZE] = { a, b, c, e };
  1851. #endif
  1852. // DRYRUN prevents E moves from taking place
  1853. if (DEBUGGING(DRYRUN)) {
  1854. position[E_AXIS] = target[E_AXIS];
  1855. #if HAS_POSITION_FLOAT
  1856. position_float[E_AXIS] = e;
  1857. #endif
  1858. }
  1859. /* <-- add a slash to enable
  1860. SERIAL_ECHOPAIR(" buffer_segment FR:", fr_mm_s);
  1861. #if IS_KINEMATIC
  1862. SERIAL_ECHOPAIR(" A:", a);
  1863. SERIAL_ECHOPAIR(" (", position[A_AXIS]);
  1864. SERIAL_ECHOPAIR("->", target[A_AXIS]);
  1865. SERIAL_ECHOPAIR(") B:", b);
  1866. #else
  1867. SERIAL_ECHOPAIR(" X:", a);
  1868. SERIAL_ECHOPAIR(" (", position[X_AXIS]);
  1869. SERIAL_ECHOPAIR("->", target[X_AXIS]);
  1870. SERIAL_ECHOPAIR(") Y:", b);
  1871. #endif
  1872. SERIAL_ECHOPAIR(" (", position[Y_AXIS]);
  1873. SERIAL_ECHOPAIR("->", target[Y_AXIS]);
  1874. #if ENABLED(DELTA)
  1875. SERIAL_ECHOPAIR(") C:", c);
  1876. #else
  1877. SERIAL_ECHOPAIR(") Z:", c);
  1878. #endif
  1879. SERIAL_ECHOPAIR(" (", position[Z_AXIS]);
  1880. SERIAL_ECHOPAIR("->", target[Z_AXIS]);
  1881. SERIAL_ECHOPAIR(") E:", e);
  1882. SERIAL_ECHOPAIR(" (", position[E_AXIS]);
  1883. SERIAL_ECHOPAIR("->", target[E_AXIS]);
  1884. SERIAL_ECHOLNPGM(")");
  1885. //*/
  1886. // Always split the first move into two (if not homing or probing)
  1887. if (!has_blocks_queued()) {
  1888. #define _BETWEEN(A) (position[A##_AXIS] + target[A##_AXIS]) >> 1
  1889. const int32_t between[ABCE] = { _BETWEEN(A), _BETWEEN(B), _BETWEEN(C), _BETWEEN(E) };
  1890. #if HAS_POSITION_FLOAT
  1891. #define _BETWEEN_F(A) (position_float[A##_AXIS] + target_float[A##_AXIS]) * 0.5
  1892. const float between_float[ABCE] = { _BETWEEN_F(A), _BETWEEN_F(B), _BETWEEN_F(C), _BETWEEN_F(E) };
  1893. #endif
  1894. DISABLE_STEPPER_DRIVER_INTERRUPT();
  1895. _buffer_steps(between
  1896. #if HAS_POSITION_FLOAT
  1897. , between_float
  1898. #endif
  1899. , fr_mm_s, extruder, millimeters * 0.5
  1900. );
  1901. const uint8_t next = block_buffer_head;
  1902. _buffer_steps(target
  1903. #if HAS_POSITION_FLOAT
  1904. , target_float
  1905. #endif
  1906. , fr_mm_s, extruder, millimeters * 0.5
  1907. );
  1908. SBI(block_buffer[next].flag, BLOCK_BIT_CONTINUED);
  1909. ENABLE_STEPPER_DRIVER_INTERRUPT();
  1910. }
  1911. else
  1912. _buffer_steps(target
  1913. #if HAS_POSITION_FLOAT
  1914. , target_float
  1915. #endif
  1916. , fr_mm_s, extruder, millimeters
  1917. );
  1918. stepper.wake_up();
  1919. } // buffer_segment()
  1920. /**
  1921. * Directly set the planner XYZ position (and stepper positions)
  1922. * converting mm (or angles for SCARA) into steps.
  1923. *
  1924. * On CORE machines stepper ABC will be translated from the given XYZ.
  1925. */
  1926. void Planner::_set_position_mm(const float &a, const float &b, const float &c, const float &e) {
  1927. #if ENABLED(DISTINCT_E_FACTORS)
  1928. #define _EINDEX (E_AXIS + active_extruder)
  1929. last_extruder = active_extruder;
  1930. #else
  1931. #define _EINDEX E_AXIS
  1932. #endif
  1933. position[A_AXIS] = LROUND(a * axis_steps_per_mm[A_AXIS]),
  1934. position[B_AXIS] = LROUND(b * axis_steps_per_mm[B_AXIS]),
  1935. position[C_AXIS] = LROUND(c * axis_steps_per_mm[C_AXIS]),
  1936. position[E_AXIS] = LROUND(e * axis_steps_per_mm[_EINDEX]);
  1937. #if HAS_POSITION_FLOAT
  1938. position_float[A_AXIS] = a;
  1939. position_float[B_AXIS] = b;
  1940. position_float[C_AXIS] = c;
  1941. position_float[E_AXIS] = e;
  1942. #endif
  1943. previous_nominal_speed = 0.0; // Resets planner junction speeds. Assumes start from rest.
  1944. ZERO(previous_speed);
  1945. buffer_sync_block();
  1946. }
  1947. void Planner::set_position_mm_kinematic(const float (&cart)[XYZE]) {
  1948. #if PLANNER_LEVELING
  1949. float raw[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  1950. apply_leveling(raw);
  1951. #else
  1952. const float (&raw)[XYZE] = cart;
  1953. #endif
  1954. #if IS_KINEMATIC
  1955. inverse_kinematics(raw);
  1956. _set_position_mm(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_AXIS]);
  1957. #else
  1958. _set_position_mm(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], cart[E_AXIS]);
  1959. #endif
  1960. }
  1961. /**
  1962. * Sync from the stepper positions. (e.g., after an interrupted move)
  1963. */
  1964. void Planner::sync_from_steppers() {
  1965. LOOP_XYZE(i) {
  1966. position[i] = stepper.position((AxisEnum)i);
  1967. #if HAS_POSITION_FLOAT
  1968. position_float[i] = position[i] * steps_to_mm[i
  1969. #if ENABLED(DISTINCT_E_FACTORS)
  1970. + (i == E_AXIS ? active_extruder : 0)
  1971. #endif
  1972. ];
  1973. #endif
  1974. }
  1975. }
  1976. /**
  1977. * Setters for planner position (also setting stepper position).
  1978. */
  1979. void Planner::set_position_mm(const AxisEnum axis, const float &v) {
  1980. #if ENABLED(DISTINCT_E_FACTORS)
  1981. const uint8_t axis_index = axis + (axis == E_AXIS ? active_extruder : 0);
  1982. last_extruder = active_extruder;
  1983. #else
  1984. const uint8_t axis_index = axis;
  1985. #endif
  1986. position[axis] = LROUND(v * axis_steps_per_mm[axis_index]);
  1987. #if HAS_POSITION_FLOAT
  1988. position_float[axis] = v;
  1989. #endif
  1990. previous_speed[axis] = 0.0;
  1991. buffer_sync_block();
  1992. }
  1993. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  1994. void Planner::reset_acceleration_rates() {
  1995. #if ENABLED(DISTINCT_E_FACTORS)
  1996. #define AXIS_CONDITION (i < E_AXIS || i == E_AXIS + active_extruder)
  1997. #else
  1998. #define AXIS_CONDITION true
  1999. #endif
  2000. uint32_t highest_rate = 1;
  2001. LOOP_XYZE_N(i) {
  2002. max_acceleration_steps_per_s2[i] = max_acceleration_mm_per_s2[i] * axis_steps_per_mm[i];
  2003. if (AXIS_CONDITION) NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2004. }
  2005. cutoff_long = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2006. }
  2007. // Recalculate position, steps_to_mm if axis_steps_per_mm changes!
  2008. void Planner::refresh_positioning() {
  2009. LOOP_XYZE_N(i) steps_to_mm[i] = 1.0 / axis_steps_per_mm[i];
  2010. set_position_mm_kinematic(current_position);
  2011. reset_acceleration_rates();
  2012. }
  2013. #if ENABLED(AUTOTEMP)
  2014. void Planner::autotemp_M104_M109() {
  2015. if ((autotemp_enabled = parser.seen('F'))) autotemp_factor = parser.value_float();
  2016. if (parser.seen('S')) autotemp_min = parser.value_celsius();
  2017. if (parser.seen('B')) autotemp_max = parser.value_celsius();
  2018. }
  2019. #endif