My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

planner.cpp 131KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (c) 2020 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 <https://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 "temperature.h"
  67. #include "../lcd/marlinui.h"
  68. #include "../gcode/parser.h"
  69. #include "../MarlinCore.h"
  70. #if HAS_LEVELING
  71. #include "../feature/bedlevel/bedlevel.h"
  72. #endif
  73. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  74. #include "../feature/filwidth.h"
  75. #endif
  76. #if ENABLED(BARICUDA)
  77. #include "../feature/baricuda.h"
  78. #endif
  79. #if ENABLED(MIXING_EXTRUDER)
  80. #include "../feature/mixing.h"
  81. #endif
  82. #if ENABLED(AUTO_POWER_CONTROL)
  83. #include "../feature/power.h"
  84. #endif
  85. #if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
  86. #include "../feature/closedloop.h"
  87. #endif
  88. #if ENABLED(BACKLASH_COMPENSATION)
  89. #include "../feature/backlash.h"
  90. #endif
  91. #if ENABLED(CANCEL_OBJECTS)
  92. #include "../feature/cancel_object.h"
  93. #endif
  94. #if ENABLED(POWER_LOSS_RECOVERY)
  95. #include "../feature/powerloss.h"
  96. #endif
  97. #if HAS_CUTTER
  98. #include "../feature/spindle_laser.h"
  99. #endif
  100. // Delay for delivery of first block to the stepper ISR, if the queue contains 2 or
  101. // fewer movements. The delay is measured in milliseconds, and must be less than 250ms
  102. #define BLOCK_DELAY_FOR_1ST_MOVE 100
  103. Planner planner;
  104. // public:
  105. /**
  106. * A ring buffer of moves described in steps
  107. */
  108. block_t Planner::block_buffer[BLOCK_BUFFER_SIZE];
  109. volatile uint8_t Planner::block_buffer_head, // Index of the next block to be pushed
  110. Planner::block_buffer_nonbusy, // Index of the first non-busy block
  111. Planner::block_buffer_planned, // Index of the optimally planned block
  112. Planner::block_buffer_tail; // Index of the busy block, if any
  113. uint16_t Planner::cleaning_buffer_counter; // A counter to disable queuing of blocks
  114. uint8_t Planner::delay_before_delivering; // This counter delays delivery of blocks when queue becomes empty to allow the opportunity of merging blocks
  115. planner_settings_t Planner::settings; // Initialized by settings.load()
  116. #if ENABLED(LASER_POWER_INLINE)
  117. laser_state_t Planner::laser_inline; // Current state for blocks
  118. #endif
  119. uint32_t Planner::max_acceleration_steps_per_s2[DISTINCT_AXES]; // (steps/s^2) Derived from mm_per_s2
  120. float Planner::steps_to_mm[DISTINCT_AXES]; // (mm) Millimeters per step
  121. #if HAS_JUNCTION_DEVIATION
  122. float Planner::junction_deviation_mm; // (mm) M205 J
  123. #if HAS_LINEAR_E_JERK
  124. float Planner::max_e_jerk[DISTINCT_E]; // Calculated from junction_deviation_mm
  125. #endif
  126. #endif
  127. #if HAS_CLASSIC_JERK
  128. TERN(HAS_LINEAR_E_JERK, xyz_pos_t, xyze_pos_t) Planner::max_jerk;
  129. #endif
  130. #if ENABLED(SD_ABORT_ON_ENDSTOP_HIT)
  131. bool Planner::abort_on_endstop_hit = false;
  132. #endif
  133. #if ENABLED(DISTINCT_E_FACTORS)
  134. uint8_t Planner::last_extruder = 0; // Respond to extruder change
  135. #endif
  136. #if ENABLED(DIRECT_STEPPING)
  137. uint32_t Planner::last_page_step_rate = 0;
  138. xyze_bool_t Planner::last_page_dir{0};
  139. #endif
  140. #if HAS_EXTRUDERS
  141. int16_t Planner::flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100); // Extrusion factor for each extruder
  142. float Planner::e_factor[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0f); // The flow percentage and volumetric multiplier combine to scale E movement
  143. #endif
  144. #if DISABLED(NO_VOLUMETRICS)
  145. 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
  146. Planner::volumetric_area_nominal = CIRCLE_AREA(float(DEFAULT_NOMINAL_FILAMENT_DIA) * 0.5f), // Nominal cross-sectional area
  147. Planner::volumetric_multiplier[EXTRUDERS]; // Reciprocal of cross-sectional area of filament (in mm^2). Pre-calculated to reduce computation in the planner
  148. #endif
  149. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  150. float Planner::volumetric_extruder_limit[EXTRUDERS], // max mm^3/sec the extruder is able to handle
  151. Planner::volumetric_extruder_feedrate_limit[EXTRUDERS]; // pre calculated extruder feedrate limit based on volumetric_extruder_limit; pre-calculated to reduce computation in the planner
  152. #endif
  153. #if HAS_LEVELING
  154. bool Planner::leveling_active = false; // Flag that auto bed leveling is enabled
  155. #if ABL_PLANAR
  156. matrix_3x3 Planner::bed_level_matrix; // Transform to compensate for bed level
  157. #endif
  158. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  159. float Planner::z_fade_height, // Initialized by settings.load()
  160. Planner::inverse_z_fade_height,
  161. Planner::last_fade_z;
  162. #endif
  163. #else
  164. constexpr bool Planner::leveling_active;
  165. #endif
  166. skew_factor_t Planner::skew_factor; // Initialized by settings.load()
  167. #if ENABLED(AUTOTEMP)
  168. celsius_t Planner::autotemp_max = 250,
  169. Planner::autotemp_min = 210;
  170. float Planner::autotemp_factor = 0.1f;
  171. bool Planner::autotemp_enabled = false;
  172. #endif
  173. // private:
  174. xyze_long_t Planner::position{0};
  175. uint32_t Planner::acceleration_long_cutoff;
  176. xyze_float_t Planner::previous_speed;
  177. float Planner::previous_nominal_speed_sqr;
  178. #if ENABLED(DISABLE_INACTIVE_EXTRUDER)
  179. last_move_t Planner::g_uc_extruder_last_move[E_STEPPERS] = { 0 };
  180. #endif
  181. #ifdef XY_FREQUENCY_LIMIT
  182. int8_t Planner::xy_freq_limit_hz = XY_FREQUENCY_LIMIT;
  183. float Planner::xy_freq_min_speed_factor = (XY_FREQUENCY_MIN_PERCENT) * 0.01f;
  184. int32_t Planner::xy_freq_min_interval_us = LROUND(1000000.0 / (XY_FREQUENCY_LIMIT));
  185. #endif
  186. #if ENABLED(LIN_ADVANCE)
  187. float Planner::extruder_advance_K[EXTRUDERS]; // Initialized by settings.load()
  188. #endif
  189. #if HAS_POSITION_FLOAT
  190. xyze_pos_t Planner::position_float; // Needed for accurate maths. Steps cannot be used!
  191. #endif
  192. #if IS_KINEMATIC
  193. xyze_pos_t Planner::position_cart;
  194. #endif
  195. #if HAS_WIRED_LCD
  196. volatile uint32_t Planner::block_buffer_runtime_us = 0;
  197. #endif
  198. /**
  199. * Class and Instance Methods
  200. */
  201. Planner::Planner() { init(); }
  202. void Planner::init() {
  203. position.reset();
  204. TERN_(HAS_POSITION_FLOAT, position_float.reset());
  205. TERN_(IS_KINEMATIC, position_cart.reset());
  206. previous_speed.reset();
  207. previous_nominal_speed_sqr = 0;
  208. TERN_(ABL_PLANAR, bed_level_matrix.set_to_identity());
  209. clear_block_buffer();
  210. delay_before_delivering = 0;
  211. #if ENABLED(DIRECT_STEPPING)
  212. last_page_step_rate = 0;
  213. last_page_dir.reset();
  214. #endif
  215. }
  216. #if ENABLED(S_CURVE_ACCELERATION)
  217. #ifdef __AVR__
  218. /**
  219. * This routine returns 0x1000000 / d, getting the inverse as fast as possible.
  220. * A fast-converging iterative Newton-Raphson method can reach full precision in
  221. * just 1 iteration, and takes 211 cycles (worst case; the mean case is less, up
  222. * to 30 cycles for small divisors), instead of the 500 cycles a normal division
  223. * would take.
  224. *
  225. * Inspired by the following page:
  226. * https://stackoverflow.com/questions/27801397/newton-raphson-division-with-big-integers
  227. *
  228. * Suppose we want to calculate floor(2 ^ k / B) where B is a positive integer
  229. * Then, B must be <= 2^k, otherwise, the quotient is 0.
  230. *
  231. * The Newton - Raphson iteration for x = B / 2 ^ k yields:
  232. * q[n + 1] = q[n] * (2 - q[n] * B / 2 ^ k)
  233. *
  234. * This can be rearranged to:
  235. * q[n + 1] = q[n] * (2 ^ (k + 1) - q[n] * B) >> k
  236. *
  237. * Each iteration requires only integer multiplications and bit shifts.
  238. * It doesn't necessarily converge to floor(2 ^ k / B) but in the worst case
  239. * it eventually alternates between floor(2 ^ k / B) and ceil(2 ^ k / B).
  240. * So it checks for this case and extracts floor(2 ^ k / B).
  241. *
  242. * A simple but important optimization for this approach is to truncate
  243. * multiplications (i.e., calculate only the higher bits of the product) in the
  244. * early iterations of the Newton - Raphson method. This is done so the results
  245. * of the early iterations are far from the quotient. Then it doesn't matter if
  246. * they are done inaccurately.
  247. * It's important to pick a good starting value for x. Knowing how many
  248. * digits the divisor has, it can be estimated:
  249. *
  250. * 2^k / x = 2 ^ log2(2^k / x)
  251. * 2^k / x = 2 ^(log2(2^k)-log2(x))
  252. * 2^k / x = 2 ^(k*log2(2)-log2(x))
  253. * 2^k / x = 2 ^ (k-log2(x))
  254. * 2^k / x >= 2 ^ (k-floor(log2(x)))
  255. * floor(log2(x)) is simply the index of the most significant bit set.
  256. *
  257. * If this estimation can be improved even further the number of iterations can be
  258. * reduced a lot, saving valuable execution time.
  259. * The paper "Software Integer Division" by Thomas L.Rodeheffer, Microsoft
  260. * Research, Silicon Valley,August 26, 2008, available at
  261. * https://www.microsoft.com/en-us/research/wp-content/uploads/2008/08/tr-2008-141.pdf
  262. * suggests, for its integer division algorithm, using a table to supply the first
  263. * 8 bits of precision, then, due to the quadratic convergence nature of the
  264. * Newton-Raphon iteration, just 2 iterations should be enough to get maximum
  265. * precision of the division.
  266. * By precomputing values of inverses for small denominator values, just one
  267. * Newton-Raphson iteration is enough to reach full precision.
  268. * This code uses the top 9 bits of the denominator as index.
  269. *
  270. * The AVR assembly function implements this C code using the data below:
  271. *
  272. * // For small divisors, it is best to directly retrieve the results
  273. * if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  274. *
  275. * // Compute initial estimation of 0x1000000/x -
  276. * // Get most significant bit set on divider
  277. * uint8_t idx = 0;
  278. * uint32_t nr = d;
  279. * if (!(nr & 0xFF0000)) {
  280. * nr <<= 8; idx += 8;
  281. * if (!(nr & 0xFF0000)) { nr <<= 8; idx += 8; }
  282. * }
  283. * if (!(nr & 0xF00000)) { nr <<= 4; idx += 4; }
  284. * if (!(nr & 0xC00000)) { nr <<= 2; idx += 2; }
  285. * if (!(nr & 0x800000)) { nr <<= 1; idx += 1; }
  286. *
  287. * // Isolate top 9 bits of the denominator, to be used as index into the initial estimation table
  288. * uint32_t tidx = nr >> 15, // top 9 bits. bit8 is always set
  289. * ie = inv_tab[tidx & 0xFF] + 256, // Get the table value. bit9 is always set
  290. * x = idx <= 8 ? (ie >> (8 - idx)) : (ie << (idx - 8)); // Position the estimation at the proper place
  291. *
  292. * x = uint32_t((x * uint64_t(_BV(25) - x * d)) >> 24); // Refine estimation by newton-raphson. 1 iteration is enough
  293. * const uint32_t r = _BV(24) - x * d; // Estimate remainder
  294. * if (r >= d) x++; // Check whether to adjust result
  295. * return uint32_t(x); // x holds the proper estimation
  296. */
  297. static uint32_t get_period_inverse(uint32_t d) {
  298. static const uint8_t inv_tab[256] PROGMEM = {
  299. 255,253,252,250,248,246,244,242,240,238,236,234,233,231,229,227,
  300. 225,224,222,220,218,217,215,213,212,210,208,207,205,203,202,200,
  301. 199,197,195,194,192,191,189,188,186,185,183,182,180,179,178,176,
  302. 175,173,172,170,169,168,166,165,164,162,161,160,158,157,156,154,
  303. 153,152,151,149,148,147,146,144,143,142,141,139,138,137,136,135,
  304. 134,132,131,130,129,128,127,126,125,123,122,121,120,119,118,117,
  305. 116,115,114,113,112,111,110,109,108,107,106,105,104,103,102,101,
  306. 100,99,98,97,96,95,94,93,92,91,90,89,88,88,87,86,
  307. 85,84,83,82,81,80,80,79,78,77,76,75,74,74,73,72,
  308. 71,70,70,69,68,67,66,66,65,64,63,62,62,61,60,59,
  309. 59,58,57,56,56,55,54,53,53,52,51,50,50,49,48,48,
  310. 47,46,46,45,44,43,43,42,41,41,40,39,39,38,37,37,
  311. 36,35,35,34,33,33,32,32,31,30,30,29,28,28,27,27,
  312. 26,25,25,24,24,23,22,22,21,21,20,19,19,18,18,17,
  313. 17,16,15,15,14,14,13,13,12,12,11,10,10,9,9,8,
  314. 8,7,7,6,6,5,5,4,4,3,3,2,2,1,0,0
  315. };
  316. // For small denominators, it is cheaper to directly store the result.
  317. // For bigger ones, just ONE Newton-Raphson iteration is enough to get
  318. // maximum precision we need
  319. static const uint32_t small_inv_tab[111] PROGMEM = {
  320. 16777216,16777216,8388608,5592405,4194304,3355443,2796202,2396745,2097152,1864135,1677721,1525201,1398101,1290555,1198372,1118481,
  321. 1048576,986895,932067,883011,838860,798915,762600,729444,699050,671088,645277,621378,599186,578524,559240,541200,
  322. 524288,508400,493447,479349,466033,453438,441505,430185,419430,409200,399457,390167,381300,372827,364722,356962,
  323. 349525,342392,335544,328965,322638,316551,310689,305040,299593,294337,289262,284359,279620,275036,270600,266305,
  324. 262144,258111,254200,250406,246723,243148,239674,236298,233016,229824,226719,223696,220752,217885,215092,212369,
  325. 209715,207126,204600,202135,199728,197379,195083,192841,190650,188508,186413,184365,182361,180400,178481,176602,
  326. 174762,172960,171196,169466,167772,166111,164482,162885,161319,159783,158275,156796,155344,153919,152520
  327. };
  328. // For small divisors, it is best to directly retrieve the results
  329. if (d <= 110) return pgm_read_dword(&small_inv_tab[d]);
  330. uint8_t r8 = d & 0xFF,
  331. r9 = (d >> 8) & 0xFF,
  332. r10 = (d >> 16) & 0xFF,
  333. r2,r3,r4,r5,r6,r7,r11,r12,r13,r14,r15,r16,r17,r18;
  334. const uint8_t *ptab = inv_tab;
  335. __asm__ __volatile__(
  336. // %8:%7:%6 = interval
  337. // r31:r30: MUST be those registers, and they must point to the inv_tab
  338. A("clr %13") // %13 = 0
  339. // Now we must compute
  340. // result = 0xFFFFFF / d
  341. // %8:%7:%6 = interval
  342. // %16:%15:%14 = nr
  343. // %13 = 0
  344. // A plain division of 24x24 bits should take 388 cycles to complete. We will
  345. // use Newton-Raphson for the calculation, and will strive to get way less cycles
  346. // for the same result - Using C division, it takes 500cycles to complete .
  347. A("clr %3") // idx = 0
  348. A("mov %14,%6")
  349. A("mov %15,%7")
  350. A("mov %16,%8") // nr = interval
  351. A("tst %16") // nr & 0xFF0000 == 0 ?
  352. A("brne 2f") // No, skip this
  353. A("mov %16,%15")
  354. A("mov %15,%14") // nr <<= 8, %14 not needed
  355. A("subi %3,-8") // idx += 8
  356. A("tst %16") // nr & 0xFF0000 == 0 ?
  357. A("brne 2f") // No, skip this
  358. A("mov %16,%15") // nr <<= 8, %14 not needed
  359. A("clr %15") // We clear %14
  360. A("subi %3,-8") // idx += 8
  361. // here %16 != 0 and %16:%15 contains at least 9 MSBits, or both %16:%15 are 0
  362. L("2")
  363. A("cpi %16,0x10") // (nr & 0xF00000) == 0 ?
  364. A("brcc 3f") // No, skip this
  365. A("swap %15") // Swap nybbles
  366. A("swap %16") // Swap nybbles. Low nybble is 0
  367. A("mov %14, %15")
  368. A("andi %14,0x0F") // Isolate low nybble
  369. A("andi %15,0xF0") // Keep proper nybble in %15
  370. A("or %16, %14") // %16:%15 <<= 4
  371. A("subi %3,-4") // idx += 4
  372. L("3")
  373. A("cpi %16,0x40") // (nr & 0xC00000) == 0 ?
  374. A("brcc 4f") // No, skip this
  375. A("add %15,%15")
  376. A("adc %16,%16")
  377. A("add %15,%15")
  378. A("adc %16,%16") // %16:%15 <<= 2
  379. A("subi %3,-2") // idx += 2
  380. L("4")
  381. A("cpi %16,0x80") // (nr & 0x800000) == 0 ?
  382. A("brcc 5f") // No, skip this
  383. A("add %15,%15")
  384. A("adc %16,%16") // %16:%15 <<= 1
  385. A("inc %3") // idx += 1
  386. // Now %16:%15 contains its MSBit set to 1, or %16:%15 is == 0. We are now absolutely sure
  387. // we have at least 9 MSBits available to enter the initial estimation table
  388. L("5")
  389. A("add %15,%15")
  390. A("adc %16,%16") // %16:%15 = tidx = (nr <<= 1), we lose the top MSBit (always set to 1, %16 is the index into the inverse table)
  391. A("add r30,%16") // Only use top 8 bits
  392. A("adc r31,%13") // r31:r30 = inv_tab + (tidx)
  393. A("lpm %14, Z") // %14 = inv_tab[tidx]
  394. A("ldi %15, 1") // %15 = 1 %15:%14 = inv_tab[tidx] + 256
  395. // We must scale the approximation to the proper place
  396. A("clr %16") // %16 will always be 0 here
  397. A("subi %3,8") // idx == 8 ?
  398. A("breq 6f") // yes, no need to scale
  399. A("brcs 7f") // If C=1, means idx < 8, result was negative!
  400. // idx > 8, now %3 = idx - 8. We must perform a left shift. idx range:[1-8]
  401. A("sbrs %3,0") // shift by 1bit position?
  402. A("rjmp 8f") // No
  403. A("add %14,%14")
  404. A("adc %15,%15") // %15:16 <<= 1
  405. L("8")
  406. A("sbrs %3,1") // shift by 2bit position?
  407. A("rjmp 9f") // No
  408. A("add %14,%14")
  409. A("adc %15,%15")
  410. A("add %14,%14")
  411. A("adc %15,%15") // %15:16 <<= 1
  412. L("9")
  413. A("sbrs %3,2") // shift by 4bits position?
  414. A("rjmp 16f") // No
  415. A("swap %15") // Swap nybbles. lo nybble of %15 will always be 0
  416. A("swap %14") // Swap nybbles
  417. A("mov %12,%14")
  418. A("andi %12,0x0F") // isolate low nybble
  419. A("andi %14,0xF0") // and clear it
  420. A("or %15,%12") // %15:%16 <<= 4
  421. L("16")
  422. A("sbrs %3,3") // shift by 8bits position?
  423. A("rjmp 6f") // No, we are done
  424. A("mov %16,%15")
  425. A("mov %15,%14")
  426. A("clr %14")
  427. A("jmp 6f")
  428. // idx < 8, now %3 = idx - 8. Get the count of bits
  429. L("7")
  430. A("neg %3") // %3 = -idx = count of bits to move right. idx range:[1...8]
  431. A("sbrs %3,0") // shift by 1 bit position ?
  432. A("rjmp 10f") // No, skip it
  433. A("asr %15") // (bit7 is always 0 here)
  434. A("ror %14")
  435. L("10")
  436. A("sbrs %3,1") // shift by 2 bit position ?
  437. A("rjmp 11f") // No, skip it
  438. A("asr %15") // (bit7 is always 0 here)
  439. A("ror %14")
  440. A("asr %15") // (bit7 is always 0 here)
  441. A("ror %14")
  442. L("11")
  443. A("sbrs %3,2") // shift by 4 bit position ?
  444. A("rjmp 12f") // No, skip it
  445. A("swap %15") // Swap nybbles
  446. A("andi %14, 0xF0") // Lose the lowest nybble
  447. A("swap %14") // Swap nybbles. Upper nybble is 0
  448. A("or %14,%15") // Pass nybble from upper byte
  449. A("andi %15, 0x0F") // And get rid of that nybble
  450. L("12")
  451. A("sbrs %3,3") // shift by 8 bit position ?
  452. A("rjmp 6f") // No, skip it
  453. A("mov %14,%15")
  454. A("clr %15")
  455. L("6") // %16:%15:%14 = initial estimation of 0x1000000 / d
  456. // Now, we must refine the estimation present on %16:%15:%14 using 1 iteration
  457. // of Newton-Raphson. As it has a quadratic convergence, 1 iteration is enough
  458. // to get more than 18bits of precision (the initial table lookup gives 9 bits of
  459. // precision to start from). 18bits of precision is all what is needed here for result
  460. // %8:%7:%6 = d = interval
  461. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  462. // %13 = 0
  463. // %3:%2:%1:%0 = working accumulator
  464. // Compute 1<<25 - x*d. Result should never exceed 25 bits and should always be positive
  465. A("clr %0")
  466. A("clr %1")
  467. A("clr %2")
  468. A("ldi %3,2") // %3:%2:%1:%0 = 0x2000000
  469. A("mul %6,%14") // r1:r0 = LO(d) * LO(x)
  470. A("sub %0,r0")
  471. A("sbc %1,r1")
  472. A("sbc %2,%13")
  473. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  474. A("mul %7,%14") // r1:r0 = MI(d) * LO(x)
  475. A("sub %1,r0")
  476. A("sbc %2,r1" )
  477. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  478. A("mul %8,%14") // r1:r0 = HI(d) * LO(x)
  479. A("sub %2,r0")
  480. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  481. A("mul %6,%15") // r1:r0 = LO(d) * MI(x)
  482. A("sub %1,r0")
  483. A("sbc %2,r1")
  484. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  485. A("mul %7,%15") // r1:r0 = MI(d) * MI(x)
  486. A("sub %2,r0")
  487. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  488. A("mul %8,%15") // r1:r0 = HI(d) * MI(x)
  489. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  490. A("mul %6,%16") // r1:r0 = LO(d) * HI(x)
  491. A("sub %2,r0")
  492. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  493. A("mul %7,%16") // r1:r0 = MI(d) * HI(x)
  494. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  495. // %3:%2:%1:%0 = (1<<25) - x*d [169]
  496. // We need to multiply that result by x, and we are only interested in the top 24bits of that multiply
  497. // %16:%15:%14 = x = initial estimation of 0x1000000 / d
  498. // %3:%2:%1:%0 = (1<<25) - x*d = acc
  499. // %13 = 0
  500. // result = %11:%10:%9:%5:%4
  501. A("mul %14,%0") // r1:r0 = LO(x) * LO(acc)
  502. A("mov %4,r1")
  503. A("clr %5")
  504. A("clr %9")
  505. A("clr %10")
  506. A("clr %11") // %11:%10:%9:%5:%4 = LO(x) * LO(acc) >> 8
  507. A("mul %15,%0") // r1:r0 = MI(x) * LO(acc)
  508. A("add %4,r0")
  509. A("adc %5,r1")
  510. A("adc %9,%13")
  511. A("adc %10,%13")
  512. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc)
  513. A("mul %16,%0") // r1:r0 = HI(x) * LO(acc)
  514. A("add %5,r0")
  515. A("adc %9,r1")
  516. A("adc %10,%13")
  517. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * LO(acc) << 8
  518. A("mul %14,%1") // r1:r0 = LO(x) * MIL(acc)
  519. A("add %4,r0")
  520. A("adc %5,r1")
  521. A("adc %9,%13")
  522. A("adc %10,%13")
  523. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIL(acc)
  524. A("mul %15,%1") // r1:r0 = MI(x) * MIL(acc)
  525. A("add %5,r0")
  526. A("adc %9,r1")
  527. A("adc %10,%13")
  528. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 8
  529. A("mul %16,%1") // r1:r0 = HI(x) * MIL(acc)
  530. A("add %9,r0")
  531. A("adc %10,r1")
  532. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIL(acc) << 16
  533. A("mul %14,%2") // r1:r0 = LO(x) * MIH(acc)
  534. A("add %5,r0")
  535. A("adc %9,r1")
  536. A("adc %10,%13")
  537. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * MIH(acc) << 8
  538. A("mul %15,%2") // r1:r0 = MI(x) * MIH(acc)
  539. A("add %9,r0")
  540. A("adc %10,r1")
  541. A("adc %11,%13") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 16
  542. A("mul %16,%2") // r1:r0 = HI(x) * MIH(acc)
  543. A("add %10,r0")
  544. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * MIH(acc) << 24
  545. A("mul %14,%3") // r1:r0 = LO(x) * HI(acc)
  546. A("add %9,r0")
  547. A("adc %10,r1")
  548. A("adc %11,%13") // %11:%10:%9:%5:%4 = LO(x) * HI(acc) << 16
  549. A("mul %15,%3") // r1:r0 = MI(x) * HI(acc)
  550. A("add %10,r0")
  551. A("adc %11,r1") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 24
  552. A("mul %16,%3") // r1:r0 = HI(x) * HI(acc)
  553. A("add %11,r0") // %11:%10:%9:%5:%4 += MI(x) * HI(acc) << 32
  554. // At this point, %11:%10:%9 contains the new estimation of x.
  555. // Finally, we must correct the result. Estimate remainder as
  556. // (1<<24) - x*d
  557. // %11:%10:%9 = x
  558. // %8:%7:%6 = d = interval" "\n\t"
  559. A("ldi %3,1")
  560. A("clr %2")
  561. A("clr %1")
  562. A("clr %0") // %3:%2:%1:%0 = 0x1000000
  563. A("mul %6,%9") // r1:r0 = LO(d) * LO(x)
  564. A("sub %0,r0")
  565. A("sbc %1,r1")
  566. A("sbc %2,%13")
  567. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * LO(x)
  568. A("mul %7,%9") // r1:r0 = MI(d) * LO(x)
  569. A("sub %1,r0")
  570. A("sbc %2,r1")
  571. A("sbc %3,%13") // %3:%2:%1:%0 -= MI(d) * LO(x) << 8
  572. A("mul %8,%9") // r1:r0 = HI(d) * LO(x)
  573. A("sub %2,r0")
  574. A("sbc %3,r1") // %3:%2:%1:%0 -= MIL(d) * LO(x) << 16
  575. A("mul %6,%10") // r1:r0 = LO(d) * MI(x)
  576. A("sub %1,r0")
  577. A("sbc %2,r1")
  578. A("sbc %3,%13") // %3:%2:%1:%0 -= LO(d) * MI(x) << 8
  579. A("mul %7,%10") // r1:r0 = MI(d) * MI(x)
  580. A("sub %2,r0")
  581. A("sbc %3,r1") // %3:%2:%1:%0 -= MI(d) * MI(x) << 16
  582. A("mul %8,%10") // r1:r0 = HI(d) * MI(x)
  583. A("sub %3,r0") // %3:%2:%1:%0 -= MIL(d) * MI(x) << 24
  584. A("mul %6,%11") // r1:r0 = LO(d) * HI(x)
  585. A("sub %2,r0")
  586. A("sbc %3,r1") // %3:%2:%1:%0 -= LO(d) * HI(x) << 16
  587. A("mul %7,%11") // r1:r0 = MI(d) * HI(x)
  588. A("sub %3,r0") // %3:%2:%1:%0 -= MI(d) * HI(x) << 24
  589. // %3:%2:%1:%0 = r = (1<<24) - x*d
  590. // %8:%7:%6 = d = interval
  591. // Perform the final correction
  592. A("sub %0,%6")
  593. A("sbc %1,%7")
  594. A("sbc %2,%8") // r -= d
  595. A("brcs 14f") // if ( r >= d)
  596. // %11:%10:%9 = x
  597. A("ldi %3,1")
  598. A("add %9,%3")
  599. A("adc %10,%13")
  600. A("adc %11,%13") // x++
  601. L("14")
  602. // Estimation is done. %11:%10:%9 = x
  603. A("clr __zero_reg__") // Make C runtime happy
  604. // [211 cycles total]
  605. : "=r" (r2),
  606. "=r" (r3),
  607. "=r" (r4),
  608. "=d" (r5),
  609. "=r" (r6),
  610. "=r" (r7),
  611. "+r" (r8),
  612. "+r" (r9),
  613. "+r" (r10),
  614. "=d" (r11),
  615. "=r" (r12),
  616. "=r" (r13),
  617. "=d" (r14),
  618. "=d" (r15),
  619. "=d" (r16),
  620. "=d" (r17),
  621. "=d" (r18),
  622. "+z" (ptab)
  623. :
  624. : "r0", "r1", "cc"
  625. );
  626. // Return the result
  627. return r11 | (uint16_t(r12) << 8) | (uint32_t(r13) << 16);
  628. }
  629. #else
  630. // All other 32-bit MPUs can easily do inverse using hardware division,
  631. // so we don't need to reduce precision or to use assembly language at all.
  632. // This routine, for all other archs, returns 0x100000000 / d ~= 0xFFFFFFFF / d
  633. static FORCE_INLINE uint32_t get_period_inverse(const uint32_t d) {
  634. return d ? 0xFFFFFFFF / d : 0xFFFFFFFF;
  635. }
  636. #endif
  637. #endif
  638. #define MINIMAL_STEP_RATE 120
  639. /**
  640. * Get the current block for processing
  641. * and mark the block as busy.
  642. * Return nullptr if the buffer is empty
  643. * or if there is a first-block delay.
  644. *
  645. * WARNING: Called from Stepper ISR context!
  646. */
  647. block_t* Planner::get_current_block() {
  648. // Get the number of moves in the planner queue so far
  649. const uint8_t nr_moves = movesplanned();
  650. // If there are any moves queued ...
  651. if (nr_moves) {
  652. // If there is still delay of delivery of blocks running, decrement it
  653. if (delay_before_delivering) {
  654. --delay_before_delivering;
  655. // If the number of movements queued is less than 3, and there is still time
  656. // to wait, do not deliver anything
  657. if (nr_moves < 3 && delay_before_delivering) return nullptr;
  658. delay_before_delivering = 0;
  659. }
  660. // If we are here, there is no excuse to deliver the block
  661. block_t * const block = &block_buffer[block_buffer_tail];
  662. // No trapezoid calculated? Don't execute yet.
  663. if (TEST(block->flag, BLOCK_BIT_RECALCULATE)) return nullptr;
  664. // We can't be sure how long an active block will take, so don't count it.
  665. TERN_(HAS_WIRED_LCD, block_buffer_runtime_us -= block->segment_time_us);
  666. // As this block is busy, advance the nonbusy block pointer
  667. block_buffer_nonbusy = next_block_index(block_buffer_tail);
  668. // Push block_buffer_planned pointer, if encountered.
  669. if (block_buffer_tail == block_buffer_planned)
  670. block_buffer_planned = block_buffer_nonbusy;
  671. // Return the block
  672. return block;
  673. }
  674. // The queue became empty
  675. TERN_(HAS_WIRED_LCD, clear_block_buffer_runtime()); // paranoia. Buffer is empty now - so reset accumulated time to zero.
  676. return nullptr;
  677. }
  678. /**
  679. * Calculate trapezoid parameters, multiplying the entry- and exit-speeds
  680. * by the provided factors.
  681. **
  682. * ############ VERY IMPORTANT ############
  683. * NOTE that the PRECONDITION to call this function is that the block is
  684. * NOT BUSY and it is marked as RECALCULATE. That WARRANTIES the Stepper ISR
  685. * is not and will not use the block while we modify it, so it is safe to
  686. * alter its values.
  687. */
  688. void Planner::calculate_trapezoid_for_block(block_t * const block, const_float_t entry_factor, const_float_t exit_factor) {
  689. uint32_t initial_rate = CEIL(block->nominal_rate * entry_factor),
  690. final_rate = CEIL(block->nominal_rate * exit_factor); // (steps per second)
  691. // Limit minimal step rate (Otherwise the timer will overflow.)
  692. NOLESS(initial_rate, uint32_t(MINIMAL_STEP_RATE));
  693. NOLESS(final_rate, uint32_t(MINIMAL_STEP_RATE));
  694. #if ENABLED(S_CURVE_ACCELERATION)
  695. uint32_t cruise_rate = initial_rate;
  696. #endif
  697. const int32_t accel = block->acceleration_steps_per_s2;
  698. // Steps required for acceleration, deceleration to/from nominal rate
  699. uint32_t accelerate_steps = CEIL(estimate_acceleration_distance(initial_rate, block->nominal_rate, accel)),
  700. decelerate_steps = FLOOR(estimate_acceleration_distance(block->nominal_rate, final_rate, -accel));
  701. // Steps between acceleration and deceleration, if any
  702. int32_t plateau_steps = block->step_event_count - accelerate_steps - decelerate_steps;
  703. // Does accelerate_steps + decelerate_steps exceed step_event_count?
  704. // Then we can't possibly reach the nominal rate, there will be no cruising.
  705. // Use intersection_distance() to calculate accel / braking time in order to
  706. // reach the final_rate exactly at the end of this block.
  707. if (plateau_steps < 0) {
  708. const float accelerate_steps_float = CEIL(intersection_distance(initial_rate, final_rate, accel, block->step_event_count));
  709. accelerate_steps = _MIN(uint32_t(_MAX(accelerate_steps_float, 0)), block->step_event_count);
  710. plateau_steps = 0;
  711. #if ENABLED(S_CURVE_ACCELERATION)
  712. // We won't reach the cruising rate. Let's calculate the speed we will reach
  713. cruise_rate = final_speed(initial_rate, accel, accelerate_steps);
  714. #endif
  715. }
  716. #if ENABLED(S_CURVE_ACCELERATION)
  717. else // We have some plateau time, so the cruise rate will be the nominal rate
  718. cruise_rate = block->nominal_rate;
  719. #endif
  720. #if ENABLED(S_CURVE_ACCELERATION)
  721. // Jerk controlled speed requires to express speed versus time, NOT steps
  722. uint32_t acceleration_time = ((float)(cruise_rate - initial_rate) / accel) * (STEPPER_TIMER_RATE),
  723. deceleration_time = ((float)(cruise_rate - final_rate) / accel) * (STEPPER_TIMER_RATE),
  724. // And to offload calculations from the ISR, we also calculate the inverse of those times here
  725. acceleration_time_inverse = get_period_inverse(acceleration_time),
  726. deceleration_time_inverse = get_period_inverse(deceleration_time);
  727. #endif
  728. // Store new block parameters
  729. block->accelerate_until = accelerate_steps;
  730. block->decelerate_after = accelerate_steps + plateau_steps;
  731. block->initial_rate = initial_rate;
  732. #if ENABLED(S_CURVE_ACCELERATION)
  733. block->acceleration_time = acceleration_time;
  734. block->deceleration_time = deceleration_time;
  735. block->acceleration_time_inverse = acceleration_time_inverse;
  736. block->deceleration_time_inverse = deceleration_time_inverse;
  737. block->cruise_rate = cruise_rate;
  738. #endif
  739. block->final_rate = final_rate;
  740. /**
  741. * Laser trapezoid calculations
  742. *
  743. * Approximate the trapezoid with the laser, incrementing the power every `entry_per` while accelerating
  744. * and decrementing it every `exit_power_per` while decelerating, thus ensuring power is related to feedrate.
  745. *
  746. * LASER_POWER_INLINE_TRAPEZOID_CONT doesn't need this as it continuously approximates
  747. *
  748. * Note this may behave unreliably when running with S_CURVE_ACCELERATION
  749. */
  750. #if ENABLED(LASER_POWER_INLINE_TRAPEZOID)
  751. if (block->laser.power > 0) { // No need to care if power == 0
  752. const uint8_t entry_power = block->laser.power * entry_factor; // Power on block entry
  753. #if DISABLED(LASER_POWER_INLINE_TRAPEZOID_CONT)
  754. // Speedup power
  755. const uint8_t entry_power_diff = block->laser.power - entry_power;
  756. if (entry_power_diff) {
  757. block->laser.entry_per = accelerate_steps / entry_power_diff;
  758. block->laser.power_entry = entry_power;
  759. }
  760. else {
  761. block->laser.entry_per = 0;
  762. block->laser.power_entry = block->laser.power;
  763. }
  764. // Slowdown power
  765. const uint8_t exit_power = block->laser.power * exit_factor, // Power on block entry
  766. exit_power_diff = block->laser.power - exit_power;
  767. if (exit_power_diff) {
  768. block->laser.exit_per = (block->step_event_count - block->decelerate_after) / exit_power_diff;
  769. block->laser.power_exit = exit_power;
  770. }
  771. else {
  772. block->laser.exit_per = 0;
  773. block->laser.power_exit = block->laser.power;
  774. }
  775. #else
  776. block->laser.power_entry = entry_power;
  777. #endif
  778. }
  779. #endif
  780. }
  781. /* PLANNER SPEED DEFINITION
  782. +--------+ <- current->nominal_speed
  783. / \
  784. current->entry_speed -> + \
  785. | + <- next->entry_speed (aka exit speed)
  786. +-------------+
  787. time -->
  788. Recalculates the motion plan according to the following basic guidelines:
  789. 1. Go over every feasible block sequentially in reverse order and calculate the junction speeds
  790. (i.e. current->entry_speed) such that:
  791. a. No junction speed exceeds the pre-computed maximum junction speed limit or nominal speeds of
  792. neighboring blocks.
  793. b. A block entry speed cannot exceed one reverse-computed from its exit speed (next->entry_speed)
  794. with a maximum allowable deceleration over the block travel distance.
  795. c. The last (or newest appended) block is planned from a complete stop (an exit speed of zero).
  796. 2. Go over every block in chronological (forward) order and dial down junction speed values if
  797. a. The exit speed exceeds the one forward-computed from its entry speed with the maximum allowable
  798. acceleration over the block travel distance.
  799. When these stages are complete, the planner will have maximized the velocity profiles throughout the all
  800. of the planner blocks, where every block is operating at its maximum allowable acceleration limits. In
  801. other words, for all of the blocks in the planner, the plan is optimal and no further speed improvements
  802. are possible. If a new block is added to the buffer, the plan is recomputed according to the said
  803. guidelines for a new optimal plan.
  804. To increase computational efficiency of these guidelines, a set of planner block pointers have been
  805. created to indicate stop-compute points for when the planner guidelines cannot logically make any further
  806. changes or improvements to the plan when in normal operation and new blocks are streamed and added to the
  807. planner buffer. For example, if a subset of sequential blocks in the planner have been planned and are
  808. bracketed by junction velocities at their maximums (or by the first planner block as well), no new block
  809. added to the planner buffer will alter the velocity profiles within them. So we no longer have to compute
  810. them. Or, if a set of sequential blocks from the first block in the planner (or a optimal stop-compute
  811. point) are all accelerating, they are all optimal and can not be altered by a new block added to the
  812. planner buffer, as this will only further increase the plan speed to chronological blocks until a maximum
  813. junction velocity is reached. However, if the operational conditions of the plan changes from infrequently
  814. used feed holds or feedrate overrides, the stop-compute pointers will be reset and the entire plan is
  815. recomputed as stated in the general guidelines.
  816. Planner buffer index mapping:
  817. - block_buffer_tail: Points to the beginning of the planner buffer. First to be executed or being executed.
  818. - block_buffer_head: Points to the buffer block after the last block in the buffer. Used to indicate whether
  819. the buffer is full or empty. As described for standard ring buffers, this block is always empty.
  820. - block_buffer_planned: Points to the first buffer block after the last optimally planned block for normal
  821. streaming operating conditions. Use for planning optimizations by avoiding recomputing parts of the
  822. planner buffer that don't change with the addition of a new block, as describe above. In addition,
  823. this block can never be less than block_buffer_tail and will always be pushed forward and maintain
  824. this requirement when encountered by the Planner::release_current_block() routine during a cycle.
  825. NOTE: Since the planner only computes on what's in the planner buffer, some motions with lots of short
  826. line segments, like G2/3 arcs or complex curves, may seem to move slow. This is because there simply isn't
  827. enough combined distance traveled in the entire buffer to accelerate up to the nominal speed and then
  828. decelerate to a complete stop at the end of the buffer, as stated by the guidelines. If this happens and
  829. becomes an annoyance, there are a few simple solutions: (1) Maximize the machine acceleration. The planner
  830. will be able to compute higher velocity profiles within the same combined distance. (2) Maximize line
  831. motion(s) distance per block to a desired tolerance. The more combined distance the planner has to use,
  832. the faster it can go. (3) Maximize the planner buffer size. This also will increase the combined distance
  833. for the planner to compute over. It also increases the number of computations the planner has to perform
  834. to compute an optimal plan, so select carefully.
  835. */
  836. // The kernel called by recalculate() when scanning the plan from last to first entry.
  837. void Planner::reverse_pass_kernel(block_t * const current, const block_t * const next) {
  838. if (current) {
  839. // If entry speed is already at the maximum entry speed, and there was no change of speed
  840. // in the next block, there is no need to recheck. Block is cruising and there is no need to
  841. // compute anything for this block,
  842. // If not, block entry speed needs to be recalculated to ensure maximum possible planned speed.
  843. const float max_entry_speed_sqr = current->max_entry_speed_sqr;
  844. // Compute maximum entry speed decelerating over the current block from its exit speed.
  845. // If not at the maximum entry speed, or the previous block entry speed changed
  846. if (current->entry_speed_sqr != max_entry_speed_sqr || (next && TEST(next->flag, BLOCK_BIT_RECALCULATE))) {
  847. // If nominal length true, max junction speed is guaranteed to be reached.
  848. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  849. // the current block and next block junction speeds are guaranteed to always be at their maximum
  850. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  851. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  852. // the reverse and forward planners, the corresponding block junction speed will always be at the
  853. // the maximum junction speed and may always be ignored for any speed reduction checks.
  854. const float new_entry_speed_sqr = TEST(current->flag, BLOCK_BIT_NOMINAL_LENGTH)
  855. ? max_entry_speed_sqr
  856. : _MIN(max_entry_speed_sqr, max_allowable_speed_sqr(-current->acceleration, next ? next->entry_speed_sqr : sq(float(MINIMUM_PLANNER_SPEED)), current->millimeters));
  857. if (current->entry_speed_sqr != new_entry_speed_sqr) {
  858. // Need to recalculate the block speed - Mark it now, so the stepper
  859. // ISR does not consume the block before being recalculated
  860. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  861. // But there is an inherent race condition here, as the block may have
  862. // become BUSY just before being marked RECALCULATE, so check for that!
  863. if (stepper.is_block_busy(current)) {
  864. // Block became busy. Clear the RECALCULATE flag (no point in
  865. // recalculating BUSY blocks). And don't set its speed, as it can't
  866. // be updated at this time.
  867. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  868. }
  869. else {
  870. // Block is not BUSY so this is ahead of the Stepper ISR:
  871. // Just Set the new entry speed.
  872. current->entry_speed_sqr = new_entry_speed_sqr;
  873. }
  874. }
  875. }
  876. }
  877. }
  878. /**
  879. * recalculate() needs to go over the current plan twice.
  880. * Once in reverse and once forward. This implements the reverse pass.
  881. */
  882. void Planner::reverse_pass() {
  883. // Initialize block index to the last block in the planner buffer.
  884. uint8_t block_index = prev_block_index(block_buffer_head);
  885. // Read the index of the last buffer planned block.
  886. // The ISR may change it so get a stable local copy.
  887. uint8_t planned_block_index = block_buffer_planned;
  888. // If there was a race condition and block_buffer_planned was incremented
  889. // or was pointing at the head (queue empty) break loop now and avoid
  890. // planning already consumed blocks
  891. if (planned_block_index == block_buffer_head) return;
  892. // Reverse Pass: Coarsely maximize all possible deceleration curves back-planning from the last
  893. // block in buffer. Cease planning when the last optimal planned or tail pointer is reached.
  894. // NOTE: Forward pass will later refine and correct the reverse pass to create an optimal plan.
  895. const block_t *next = nullptr;
  896. while (block_index != planned_block_index) {
  897. // Perform the reverse pass
  898. block_t *current = &block_buffer[block_index];
  899. // Only consider non sync-and-page blocks
  900. if (!(current->flag & BLOCK_MASK_SYNC) && !IS_PAGE(current)) {
  901. reverse_pass_kernel(current, next);
  902. next = current;
  903. }
  904. // Advance to the next
  905. block_index = prev_block_index(block_index);
  906. // The ISR could advance the block_buffer_planned while we were doing the reverse pass.
  907. // We must try to avoid using an already consumed block as the last one - So follow
  908. // changes to the pointer and make sure to limit the loop to the currently busy block
  909. while (planned_block_index != block_buffer_planned) {
  910. // If we reached the busy block or an already processed block, break the loop now
  911. if (block_index == planned_block_index) return;
  912. // Advance the pointer, following the busy block
  913. planned_block_index = next_block_index(planned_block_index);
  914. }
  915. }
  916. }
  917. // The kernel called by recalculate() when scanning the plan from first to last entry.
  918. void Planner::forward_pass_kernel(const block_t * const previous, block_t * const current, const uint8_t block_index) {
  919. if (previous) {
  920. // If the previous block is an acceleration block, too short to complete the full speed
  921. // change, adjust the entry speed accordingly. Entry speeds have already been reset,
  922. // maximized, and reverse-planned. If nominal length is set, max junction speed is
  923. // guaranteed to be reached. No need to recheck.
  924. if (!TEST(previous->flag, BLOCK_BIT_NOMINAL_LENGTH) &&
  925. previous->entry_speed_sqr < current->entry_speed_sqr) {
  926. // Compute the maximum allowable speed
  927. const float new_entry_speed_sqr = max_allowable_speed_sqr(-previous->acceleration, previous->entry_speed_sqr, previous->millimeters);
  928. // If true, current block is full-acceleration and we can move the planned pointer forward.
  929. if (new_entry_speed_sqr < current->entry_speed_sqr) {
  930. // Mark we need to recompute the trapezoidal shape, and do it now,
  931. // so the stepper ISR does not consume the block before being recalculated
  932. SBI(current->flag, BLOCK_BIT_RECALCULATE);
  933. // But there is an inherent race condition here, as the block maybe
  934. // became BUSY, just before it was marked as RECALCULATE, so check
  935. // if that is the case!
  936. if (stepper.is_block_busy(current)) {
  937. // Block became busy. Clear the RECALCULATE flag (no point in
  938. // recalculating BUSY blocks and don't set its speed, as it can't
  939. // be updated at this time.
  940. CBI(current->flag, BLOCK_BIT_RECALCULATE);
  941. }
  942. else {
  943. // Block is not BUSY, we won the race against the Stepper ISR:
  944. // Always <= max_entry_speed_sqr. Backward pass sets this.
  945. current->entry_speed_sqr = new_entry_speed_sqr; // Always <= max_entry_speed_sqr. Backward pass sets this.
  946. // Set optimal plan pointer.
  947. block_buffer_planned = block_index;
  948. }
  949. }
  950. }
  951. // Any block set at its maximum entry speed also creates an optimal plan up to this
  952. // point in the buffer. When the plan is bracketed by either the beginning of the
  953. // buffer and a maximum entry speed or two maximum entry speeds, every block in between
  954. // cannot logically be further improved. Hence, we don't have to recompute them anymore.
  955. if (current->entry_speed_sqr == current->max_entry_speed_sqr)
  956. block_buffer_planned = block_index;
  957. }
  958. }
  959. /**
  960. * recalculate() needs to go over the current plan twice.
  961. * Once in reverse and once forward. This implements the forward pass.
  962. */
  963. void Planner::forward_pass() {
  964. // Forward Pass: Forward plan the acceleration curve from the planned pointer onward.
  965. // Also scans for optimal plan breakpoints and appropriately updates the planned pointer.
  966. // Begin at buffer planned pointer. Note that block_buffer_planned can be modified
  967. // by the stepper ISR, so read it ONCE. It it guaranteed that block_buffer_planned
  968. // will never lead head, so the loop is safe to execute. Also note that the forward
  969. // pass will never modify the values at the tail.
  970. uint8_t block_index = block_buffer_planned;
  971. block_t *block;
  972. const block_t * previous = nullptr;
  973. while (block_index != block_buffer_head) {
  974. // Perform the forward pass
  975. block = &block_buffer[block_index];
  976. // Skip SYNC and page blocks
  977. if (!(block->flag & BLOCK_MASK_SYNC) && !IS_PAGE(block)) {
  978. // If there's no previous block or the previous block is not
  979. // BUSY (thus, modifiable) run the forward_pass_kernel. Otherwise,
  980. // the previous block became BUSY, so assume the current block's
  981. // entry speed can't be altered (since that would also require
  982. // updating the exit speed of the previous block).
  983. if (!previous || !stepper.is_block_busy(previous))
  984. forward_pass_kernel(previous, block, block_index);
  985. previous = block;
  986. }
  987. // Advance to the previous
  988. block_index = next_block_index(block_index);
  989. }
  990. }
  991. /**
  992. * Recalculate the trapezoid speed profiles for all blocks in the plan
  993. * according to the entry_factor for each junction. Must be called by
  994. * recalculate() after updating the blocks.
  995. */
  996. void Planner::recalculate_trapezoids() {
  997. // The tail may be changed by the ISR so get a local copy.
  998. uint8_t block_index = block_buffer_tail,
  999. head_block_index = block_buffer_head;
  1000. // Since there could be a sync block in the head of the queue, and the
  1001. // next loop must not recalculate the head block (as it needs to be
  1002. // specially handled), scan backwards to the first non-SYNC block.
  1003. while (head_block_index != block_index) {
  1004. // Go back (head always point to the first free block)
  1005. const uint8_t prev_index = prev_block_index(head_block_index);
  1006. // Get the pointer to the block
  1007. block_t *prev = &block_buffer[prev_index];
  1008. // If not dealing with a sync block, we are done. The last block is not a SYNC block
  1009. if (!(prev->flag & BLOCK_MASK_SYNC)) break;
  1010. // Examine the previous block. This and all following are SYNC blocks
  1011. head_block_index = prev_index;
  1012. }
  1013. // Go from the tail (currently executed block) to the first block, without including it)
  1014. block_t *block = nullptr, *next = nullptr;
  1015. float current_entry_speed = 0.0, next_entry_speed = 0.0;
  1016. while (block_index != head_block_index) {
  1017. next = &block_buffer[block_index];
  1018. // Skip sync and page blocks
  1019. if (!(next->flag & BLOCK_MASK_SYNC) && !IS_PAGE(next)) {
  1020. next_entry_speed = SQRT(next->entry_speed_sqr);
  1021. if (block) {
  1022. // Recalculate if current block entry or exit junction speed has changed.
  1023. if (TEST(block->flag, BLOCK_BIT_RECALCULATE) || TEST(next->flag, BLOCK_BIT_RECALCULATE)) {
  1024. // Mark the current block as RECALCULATE, to protect it from the Stepper ISR running it.
  1025. // Note that due to the above condition, there's a chance the current block isn't marked as
  1026. // RECALCULATE yet, but the next one is. That's the reason for the following line.
  1027. SBI(block->flag, BLOCK_BIT_RECALCULATE);
  1028. // But there is an inherent race condition here, as the block maybe
  1029. // became BUSY, just before it was marked as RECALCULATE, so check
  1030. // if that is the case!
  1031. if (!stepper.is_block_busy(block)) {
  1032. // Block is not BUSY, we won the race against the Stepper ISR:
  1033. // NOTE: Entry and exit factors always > 0 by all previous logic operations.
  1034. const float current_nominal_speed = SQRT(block->nominal_speed_sqr),
  1035. nomr = 1.0f / current_nominal_speed;
  1036. calculate_trapezoid_for_block(block, current_entry_speed * nomr, next_entry_speed * nomr);
  1037. #if ENABLED(LIN_ADVANCE)
  1038. if (block->use_advance_lead) {
  1039. const float comp = block->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1040. block->max_adv_steps = current_nominal_speed * comp;
  1041. block->final_adv_steps = next_entry_speed * comp;
  1042. }
  1043. #endif
  1044. }
  1045. // Reset current only to ensure next trapezoid is computed - The
  1046. // stepper is free to use the block from now on.
  1047. CBI(block->flag, BLOCK_BIT_RECALCULATE);
  1048. }
  1049. }
  1050. block = next;
  1051. current_entry_speed = next_entry_speed;
  1052. }
  1053. block_index = next_block_index(block_index);
  1054. }
  1055. // Last/newest block in buffer. Exit speed is set with MINIMUM_PLANNER_SPEED. Always recalculated.
  1056. if (next) {
  1057. // Mark the next(last) block as RECALCULATE, to prevent the Stepper ISR running it.
  1058. // As the last block is always recalculated here, there is a chance the block isn't
  1059. // marked as RECALCULATE yet. That's the reason for the following line.
  1060. SBI(next->flag, BLOCK_BIT_RECALCULATE);
  1061. // But there is an inherent race condition here, as the block maybe
  1062. // became BUSY, just before it was marked as RECALCULATE, so check
  1063. // if that is the case!
  1064. if (!stepper.is_block_busy(block)) {
  1065. // Block is not BUSY, we won the race against the Stepper ISR:
  1066. const float next_nominal_speed = SQRT(next->nominal_speed_sqr),
  1067. nomr = 1.0f / next_nominal_speed;
  1068. calculate_trapezoid_for_block(next, next_entry_speed * nomr, float(MINIMUM_PLANNER_SPEED) * nomr);
  1069. #if ENABLED(LIN_ADVANCE)
  1070. if (next->use_advance_lead) {
  1071. const float comp = next->e_D_ratio * extruder_advance_K[active_extruder] * settings.axis_steps_per_mm[E_AXIS];
  1072. next->max_adv_steps = next_nominal_speed * comp;
  1073. next->final_adv_steps = (MINIMUM_PLANNER_SPEED) * comp;
  1074. }
  1075. #endif
  1076. }
  1077. // Reset next only to ensure its trapezoid is computed - The stepper is free to use
  1078. // the block from now on.
  1079. CBI(next->flag, BLOCK_BIT_RECALCULATE);
  1080. }
  1081. }
  1082. void Planner::recalculate() {
  1083. // Initialize block index to the last block in the planner buffer.
  1084. const uint8_t block_index = prev_block_index(block_buffer_head);
  1085. // If there is just one block, no planning can be done. Avoid it!
  1086. if (block_index != block_buffer_planned) {
  1087. reverse_pass();
  1088. forward_pass();
  1089. }
  1090. recalculate_trapezoids();
  1091. }
  1092. #if HAS_FAN && DISABLED(LASER_SYNCHRONOUS_M106_M107)
  1093. #define HAS_TAIL_FAN_SPEED 1
  1094. #endif
  1095. /**
  1096. * Apply fan speeds
  1097. */
  1098. #if HAS_FAN
  1099. void Planner::sync_fan_speeds(uint8_t (&fan_speed)[FAN_COUNT]) {
  1100. #if FAN_MIN_PWM != 0 || FAN_MAX_PWM != 255
  1101. #define CALC_FAN_SPEED(f) (fan_speed[f] ? map(fan_speed[f], 1, 255, FAN_MIN_PWM, FAN_MAX_PWM) : FAN_OFF_PWM)
  1102. #else
  1103. #define CALC_FAN_SPEED(f) (fan_speed[f] ?: FAN_OFF_PWM)
  1104. #endif
  1105. #if ENABLED(FAN_SOFT_PWM)
  1106. #define _FAN_SET(F) thermalManager.soft_pwm_amount_fan[F] = CALC_FAN_SPEED(F);
  1107. #elif ENABLED(FAST_PWM_FAN)
  1108. #define _FAN_SET(F) set_pwm_duty(FAN##F##_PIN, CALC_FAN_SPEED(F));
  1109. #else
  1110. #define _FAN_SET(F) analogWrite(pin_t(FAN##F##_PIN), CALC_FAN_SPEED(F));
  1111. #endif
  1112. #define FAN_SET(F) do{ kickstart_fan(fan_speed, ms, F); _FAN_SET(F); }while(0)
  1113. const millis_t ms = millis();
  1114. TERN_(HAS_FAN0, FAN_SET(0));
  1115. TERN_(HAS_FAN1, FAN_SET(1));
  1116. TERN_(HAS_FAN2, FAN_SET(2));
  1117. TERN_(HAS_FAN3, FAN_SET(3));
  1118. TERN_(HAS_FAN4, FAN_SET(4));
  1119. TERN_(HAS_FAN5, FAN_SET(5));
  1120. TERN_(HAS_FAN6, FAN_SET(6));
  1121. TERN_(HAS_FAN7, FAN_SET(7));
  1122. }
  1123. #if FAN_KICKSTART_TIME
  1124. void Planner::kickstart_fan(uint8_t (&fan_speed)[FAN_COUNT], const millis_t &ms, const uint8_t f) {
  1125. static millis_t fan_kick_end[FAN_COUNT] = { 0 };
  1126. if (fan_speed[f]) {
  1127. if (fan_kick_end[f] == 0) {
  1128. fan_kick_end[f] = ms + FAN_KICKSTART_TIME;
  1129. fan_speed[f] = 255;
  1130. }
  1131. else if (PENDING(ms, fan_kick_end[f]))
  1132. fan_speed[f] = 255;
  1133. }
  1134. else
  1135. fan_kick_end[f] = 0;
  1136. }
  1137. #endif
  1138. #endif // HAS_FAN
  1139. /**
  1140. * Maintain fans, paste extruder pressure,
  1141. */
  1142. void Planner::check_axes_activity() {
  1143. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z , DISABLE_I , DISABLE_J , DISABLE_K, DISABLE_E)
  1144. xyze_bool_t axis_active = { false };
  1145. #endif
  1146. #if HAS_TAIL_FAN_SPEED
  1147. uint8_t tail_fan_speed[FAN_COUNT];
  1148. #endif
  1149. #if ENABLED(BARICUDA)
  1150. #if HAS_HEATER_1
  1151. uint8_t tail_valve_pressure;
  1152. #endif
  1153. #if HAS_HEATER_2
  1154. uint8_t tail_e_to_p_pressure;
  1155. #endif
  1156. #endif
  1157. if (has_blocks_queued()) {
  1158. #if EITHER(HAS_TAIL_FAN_SPEED, BARICUDA)
  1159. block_t *block = &block_buffer[block_buffer_tail];
  1160. #endif
  1161. #if HAS_TAIL_FAN_SPEED
  1162. FANS_LOOP(i) tail_fan_speed[i] = thermalManager.scaledFanSpeed(i, block->fan_speed[i]);
  1163. #endif
  1164. #if ENABLED(BARICUDA)
  1165. TERN_(HAS_HEATER_1, tail_valve_pressure = block->valve_pressure);
  1166. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = block->e_to_p_pressure);
  1167. #endif
  1168. #if ANY(DISABLE_X, DISABLE_Y, DISABLE_Z, DISABLE_I, DISABLE_J, DISABLE_K, DISABLE_E)
  1169. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1170. block_t *block = &block_buffer[b];
  1171. LOGICAL_AXIS_CODE(
  1172. if (TERN0(DISABLE_E, block->steps.e)) axis_active.e = true,
  1173. if (TERN0(DISABLE_X, block->steps.x)) axis_active.x = true,
  1174. if (TERN0(DISABLE_Y, block->steps.y)) axis_active.y = true,
  1175. if (TERN0(DISABLE_Z, block->steps.z)) axis_active.z = true,
  1176. if (TERN0(DISABLE_I, block->steps.i)) axis_active.i = true,
  1177. if (TERN0(DISABLE_J, block->steps.j)) axis_active.j = true,
  1178. if (TERN0(DISABLE_K, block->steps.k)) axis_active.k = true
  1179. );
  1180. }
  1181. #endif
  1182. }
  1183. else {
  1184. TERN_(HAS_CUTTER, cutter.refresh());
  1185. #if HAS_TAIL_FAN_SPEED
  1186. FANS_LOOP(i) tail_fan_speed[i] = thermalManager.scaledFanSpeed(i);
  1187. #endif
  1188. #if ENABLED(BARICUDA)
  1189. TERN_(HAS_HEATER_1, tail_valve_pressure = baricuda_valve_pressure);
  1190. TERN_(HAS_HEATER_2, tail_e_to_p_pressure = baricuda_e_to_p_pressure);
  1191. #endif
  1192. }
  1193. //
  1194. // Disable inactive axes
  1195. //
  1196. LOGICAL_AXIS_CODE(
  1197. if (TERN0(DISABLE_E, !axis_active.e)) disable_e_steppers(),
  1198. if (TERN0(DISABLE_X, !axis_active.x)) DISABLE_AXIS_X(),
  1199. if (TERN0(DISABLE_Y, !axis_active.y)) DISABLE_AXIS_Y(),
  1200. if (TERN0(DISABLE_Z, !axis_active.z)) DISABLE_AXIS_Z(),
  1201. if (TERN0(DISABLE_I, !axis_active.i)) DISABLE_AXIS_I(),
  1202. if (TERN0(DISABLE_J, !axis_active.j)) DISABLE_AXIS_J(),
  1203. if (TERN0(DISABLE_K, !axis_active.k)) DISABLE_AXIS_K()
  1204. );
  1205. //
  1206. // Update Fan speeds
  1207. // Only if synchronous M106/M107 is disabled
  1208. //
  1209. TERN_(HAS_TAIL_FAN_SPEED, sync_fan_speeds(tail_fan_speed));
  1210. TERN_(AUTOTEMP, autotemp_task());
  1211. #if ENABLED(BARICUDA)
  1212. TERN_(HAS_HEATER_1, analogWrite(pin_t(HEATER_1_PIN), tail_valve_pressure));
  1213. TERN_(HAS_HEATER_2, analogWrite(pin_t(HEATER_2_PIN), tail_e_to_p_pressure));
  1214. #endif
  1215. }
  1216. #if ENABLED(AUTOTEMP)
  1217. #if ENABLED(AUTOTEMP_PROPORTIONAL)
  1218. void Planner::_autotemp_update_from_hotend() {
  1219. const celsius_t target = thermalManager.degTargetHotend(active_extruder);
  1220. autotemp_min = target + AUTOTEMP_MIN_P;
  1221. autotemp_max = target + AUTOTEMP_MAX_P;
  1222. }
  1223. #endif
  1224. /**
  1225. * Called after changing tools to:
  1226. * - Reset or re-apply the default proportional autotemp factor.
  1227. * - Enable autotemp if the factor is non-zero.
  1228. */
  1229. void Planner::autotemp_update() {
  1230. _autotemp_update_from_hotend();
  1231. autotemp_factor = TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0);
  1232. autotemp_enabled = autotemp_factor != 0;
  1233. }
  1234. /**
  1235. * Called by the M104/M109 commands after setting Hotend Temperature
  1236. *
  1237. */
  1238. void Planner::autotemp_M104_M109() {
  1239. _autotemp_update_from_hotend();
  1240. if (parser.seenval('S')) autotemp_min = parser.value_celsius();
  1241. if (parser.seenval('B')) autotemp_max = parser.value_celsius();
  1242. // When AUTOTEMP_PROPORTIONAL is enabled, F0 disables autotemp.
  1243. // Normally, leaving off F also disables autotemp.
  1244. autotemp_factor = parser.seen('F') ? parser.value_float() : TERN(AUTOTEMP_PROPORTIONAL, AUTOTEMP_FACTOR_P, 0);
  1245. autotemp_enabled = autotemp_factor != 0;
  1246. }
  1247. /**
  1248. * Called every so often to adjust the hotend target temperature
  1249. * based on the extrusion speed, which is calculated from the blocks
  1250. * currently in the planner.
  1251. */
  1252. void Planner::autotemp_task() {
  1253. static float oldt = 0;
  1254. if (!autotemp_enabled) return;
  1255. if (thermalManager.degTargetHotend(active_extruder) < autotemp_min - 2) return; // Below the min?
  1256. float high = 0.0;
  1257. for (uint8_t b = block_buffer_tail; b != block_buffer_head; b = next_block_index(b)) {
  1258. block_t *block = &block_buffer[b];
  1259. if (LINEAR_AXIS_GANG(block->steps.x, || block->steps.y, || block->steps.z, || block->steps.i, || block->steps.j, || block->steps.k)) {
  1260. const float se = (float)block->steps.e / block->step_event_count * SQRT(block->nominal_speed_sqr); // mm/sec;
  1261. NOLESS(high, se);
  1262. }
  1263. }
  1264. float t = autotemp_min + high * autotemp_factor;
  1265. LIMIT(t, autotemp_min, autotemp_max);
  1266. if (t < oldt) t *= (1.0f - (AUTOTEMP_OLDWEIGHT)) + oldt * (AUTOTEMP_OLDWEIGHT);
  1267. oldt = t;
  1268. thermalManager.setTargetHotend(t, active_extruder);
  1269. }
  1270. #endif
  1271. #if DISABLED(NO_VOLUMETRICS)
  1272. /**
  1273. * Get a volumetric multiplier from a filament diameter.
  1274. * This is the reciprocal of the circular cross-section area.
  1275. * Return 1.0 with volumetric off or a diameter of 0.0.
  1276. */
  1277. inline float calculate_volumetric_multiplier(const_float_t diameter) {
  1278. return (parser.volumetric_enabled && diameter) ? 1.0f / CIRCLE_AREA(diameter * 0.5f) : 1;
  1279. }
  1280. /**
  1281. * Convert the filament sizes into volumetric multipliers.
  1282. * The multiplier converts a given E value into a length.
  1283. */
  1284. void Planner::calculate_volumetric_multipliers() {
  1285. LOOP_L_N(i, COUNT(filament_size)) {
  1286. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  1287. refresh_e_factor(i);
  1288. }
  1289. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  1290. calculate_volumetric_extruder_limits(); // update volumetric_extruder_limits as well.
  1291. #endif
  1292. }
  1293. #endif // !NO_VOLUMETRICS
  1294. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  1295. /**
  1296. * Convert volumetric based limits into pre calculated extruder feedrate limits.
  1297. */
  1298. void Planner::calculate_volumetric_extruder_limit(const uint8_t e) {
  1299. const float &lim = volumetric_extruder_limit[e], &siz = filament_size[e];
  1300. volumetric_extruder_feedrate_limit[e] = (lim && siz) ? lim / CIRCLE_AREA(siz * 0.5f) : 0;
  1301. }
  1302. void Planner::calculate_volumetric_extruder_limits() {
  1303. LOOP_L_N(e, EXTRUDERS) calculate_volumetric_extruder_limit(e);
  1304. }
  1305. #endif
  1306. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1307. /**
  1308. * Convert the ratio value given by the filament width sensor
  1309. * into a volumetric multiplier. Conversion differs when using
  1310. * linear extrusion vs volumetric extrusion.
  1311. */
  1312. void Planner::apply_filament_width_sensor(const int8_t encoded_ratio) {
  1313. // Reconstitute the nominal/measured ratio
  1314. const float nom_meas_ratio = 1 + 0.01f * encoded_ratio,
  1315. ratio_2 = sq(nom_meas_ratio);
  1316. volumetric_multiplier[FILAMENT_SENSOR_EXTRUDER_NUM] = parser.volumetric_enabled
  1317. ? ratio_2 / CIRCLE_AREA(filwidth.nominal_mm * 0.5f) // Volumetric uses a true volumetric multiplier
  1318. : ratio_2; // Linear squares the ratio, which scales the volume
  1319. refresh_e_factor(FILAMENT_SENSOR_EXTRUDER_NUM);
  1320. }
  1321. #endif
  1322. #if ENABLED(IMPROVE_HOMING_RELIABILITY)
  1323. void Planner::enable_stall_prevention(const bool onoff) {
  1324. static motion_state_t saved_motion_state;
  1325. if (onoff) {
  1326. saved_motion_state.acceleration.x = settings.max_acceleration_mm_per_s2[X_AXIS];
  1327. saved_motion_state.acceleration.y = settings.max_acceleration_mm_per_s2[Y_AXIS];
  1328. settings.max_acceleration_mm_per_s2[X_AXIS] = settings.max_acceleration_mm_per_s2[Y_AXIS] = 100;
  1329. #if ENABLED(DELTA)
  1330. saved_motion_state.acceleration.z = settings.max_acceleration_mm_per_s2[Z_AXIS];
  1331. settings.max_acceleration_mm_per_s2[Z_AXIS] = 100;
  1332. #endif
  1333. #if HAS_CLASSIC_JERK
  1334. saved_motion_state.jerk_state = max_jerk;
  1335. max_jerk.set(0, 0 OPTARG(DELTA, 0));
  1336. #endif
  1337. }
  1338. else {
  1339. settings.max_acceleration_mm_per_s2[X_AXIS] = saved_motion_state.acceleration.x;
  1340. settings.max_acceleration_mm_per_s2[Y_AXIS] = saved_motion_state.acceleration.y;
  1341. TERN_(DELTA, settings.max_acceleration_mm_per_s2[Z_AXIS] = saved_motion_state.acceleration.z);
  1342. TERN_(HAS_CLASSIC_JERK, max_jerk = saved_motion_state.jerk_state);
  1343. }
  1344. reset_acceleration_rates();
  1345. }
  1346. #endif
  1347. #if HAS_LEVELING
  1348. constexpr xy_pos_t level_fulcrum = {
  1349. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_X_POINT, X_HOME_POS),
  1350. TERN(Z_SAFE_HOMING, Z_SAFE_HOMING_Y_POINT, Y_HOME_POS)
  1351. };
  1352. /**
  1353. * rx, ry, rz - Cartesian positions in mm
  1354. * Leveled XYZ on completion
  1355. */
  1356. void Planner::apply_leveling(xyz_pos_t &raw) {
  1357. if (!leveling_active) return;
  1358. #if ABL_PLANAR
  1359. xy_pos_t d = raw - level_fulcrum;
  1360. bed_level_matrix.apply_rotation_xyz(d.x, d.y, raw.z);
  1361. raw = d + level_fulcrum;
  1362. #elif HAS_MESH
  1363. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1364. const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z);
  1365. #elif DISABLED(MESH_BED_LEVELING)
  1366. constexpr float fade_scaling_factor = 1.0;
  1367. #endif
  1368. raw.z += (
  1369. #if ENABLED(MESH_BED_LEVELING)
  1370. mbl.get_z(raw OPTARG(ENABLE_LEVELING_FADE_HEIGHT, fade_scaling_factor))
  1371. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1372. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw) : 0.0
  1373. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1374. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1375. #endif
  1376. );
  1377. #endif
  1378. }
  1379. void Planner::unapply_leveling(xyz_pos_t &raw) {
  1380. if (leveling_active) {
  1381. #if ABL_PLANAR
  1382. matrix_3x3 inverse = matrix_3x3::transpose(bed_level_matrix);
  1383. xy_pos_t d = raw - level_fulcrum;
  1384. inverse.apply_rotation_xyz(d.x, d.y, raw.z);
  1385. raw = d + level_fulcrum;
  1386. #elif HAS_MESH
  1387. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1388. const float fade_scaling_factor = fade_scaling_factor_for_z(raw.z);
  1389. #elif DISABLED(MESH_BED_LEVELING)
  1390. constexpr float fade_scaling_factor = 1.0;
  1391. #endif
  1392. raw.z -= (
  1393. #if ENABLED(MESH_BED_LEVELING)
  1394. mbl.get_z(raw OPTARG(ENABLE_LEVELING_FADE_HEIGHT, fade_scaling_factor))
  1395. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1396. fade_scaling_factor ? fade_scaling_factor * ubl.get_z_correction(raw) : 0.0
  1397. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1398. fade_scaling_factor ? fade_scaling_factor * bilinear_z_offset(raw) : 0.0
  1399. #endif
  1400. );
  1401. #endif
  1402. }
  1403. }
  1404. #endif // HAS_LEVELING
  1405. #if ENABLED(FWRETRACT)
  1406. /**
  1407. * rz, e - Cartesian positions in mm
  1408. */
  1409. void Planner::apply_retract(float &rz, float &e) {
  1410. rz += fwretract.current_hop;
  1411. e -= fwretract.current_retract[active_extruder];
  1412. }
  1413. void Planner::unapply_retract(float &rz, float &e) {
  1414. rz -= fwretract.current_hop;
  1415. e += fwretract.current_retract[active_extruder];
  1416. }
  1417. #endif
  1418. void Planner::quick_stop() {
  1419. // Remove all the queued blocks. Note that this function is NOT
  1420. // called from the Stepper ISR, so we must consider tail as readonly!
  1421. // that is why we set head to tail - But there is a race condition that
  1422. // must be handled: The tail could change between the read and the assignment
  1423. // so this must be enclosed in a critical section
  1424. const bool was_enabled = stepper.suspend();
  1425. // Drop all queue entries
  1426. block_buffer_nonbusy = block_buffer_planned = block_buffer_head = block_buffer_tail;
  1427. // Restart the block delay for the first movement - As the queue was
  1428. // forced to empty, there's no risk the ISR will touch this.
  1429. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1430. #if HAS_WIRED_LCD
  1431. // Clear the accumulated runtime
  1432. clear_block_buffer_runtime();
  1433. #endif
  1434. // Make sure to drop any attempt of queuing moves for 1 second
  1435. cleaning_buffer_counter = TEMP_TIMER_FREQUENCY;
  1436. // Reenable Stepper ISR
  1437. if (was_enabled) stepper.wake_up();
  1438. // And stop the stepper ISR
  1439. stepper.quick_stop();
  1440. }
  1441. #if ENABLED(REALTIME_REPORTING_COMMANDS)
  1442. void Planner::quick_pause() {
  1443. // Suspend until quick_resume is called
  1444. // Don't empty buffers or queues
  1445. const bool did_suspend = stepper.suspend();
  1446. if (did_suspend)
  1447. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(M_HOLD));
  1448. }
  1449. // Resume if suspended
  1450. void Planner::quick_resume() {
  1451. TERN_(FULL_REPORT_TO_HOST_FEATURE, set_and_report_grblstate(grbl_state_for_marlin_state()));
  1452. stepper.wake_up();
  1453. }
  1454. #endif
  1455. void Planner::endstop_triggered(const AxisEnum axis) {
  1456. // Record stepper position and discard the current block
  1457. stepper.endstop_triggered(axis);
  1458. }
  1459. float Planner::triggered_position_mm(const AxisEnum axis) {
  1460. return stepper.triggered_position(axis) * steps_to_mm[axis];
  1461. }
  1462. void Planner::finish_and_disable() {
  1463. while (has_blocks_queued() || cleaning_buffer_counter) idle();
  1464. disable_all_steppers();
  1465. }
  1466. /**
  1467. * Get an axis position according to stepper position(s)
  1468. * For CORE machines apply translation from ABC to XYZ.
  1469. */
  1470. float Planner::get_axis_position_mm(const AxisEnum axis) {
  1471. float axis_steps;
  1472. #if IS_CORE
  1473. // Requesting one of the "core" axes?
  1474. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1475. // Protect the access to the position.
  1476. const bool was_enabled = stepper.suspend();
  1477. const int32_t p1 = stepper.position(CORE_AXIS_1),
  1478. p2 = stepper.position(CORE_AXIS_2);
  1479. if (was_enabled) stepper.wake_up();
  1480. // ((a1+a2)+(a1-a2))/2 -> (a1+a2+a1-a2)/2 -> (a1+a1)/2 -> a1
  1481. // ((a1+a2)-(a1-a2))/2 -> (a1+a2-a1+a2)/2 -> (a2+a2)/2 -> a2
  1482. axis_steps = (axis == CORE_AXIS_2 ? CORESIGN(p1 - p2) : p1 + p2) * 0.5f;
  1483. }
  1484. else
  1485. axis_steps = stepper.position(axis);
  1486. #elif ENABLED(MARKFORGED_XY)
  1487. // Requesting one of the joined axes?
  1488. if (axis == CORE_AXIS_1 || axis == CORE_AXIS_2) {
  1489. // Protect the access to the position.
  1490. const bool was_enabled = stepper.suspend();
  1491. const int32_t p1 = stepper.position(CORE_AXIS_1),
  1492. p2 = stepper.position(CORE_AXIS_2);
  1493. if (was_enabled) stepper.wake_up();
  1494. axis_steps = ((axis == CORE_AXIS_1) ? p1 - p2 : p2);
  1495. }
  1496. else
  1497. axis_steps = stepper.position(axis);
  1498. #else
  1499. axis_steps = stepper.position(axis);
  1500. #endif
  1501. return axis_steps * steps_to_mm[axis];
  1502. }
  1503. /**
  1504. * Block until all buffered steps are executed / cleaned
  1505. */
  1506. void Planner::synchronize() {
  1507. while (has_blocks_queued() || cleaning_buffer_counter
  1508. || TERN0(EXTERNAL_CLOSED_LOOP_CONTROLLER, CLOSED_LOOP_WAITING())
  1509. ) idle();
  1510. }
  1511. /**
  1512. * Planner::_buffer_steps
  1513. *
  1514. * Add a new linear movement to the planner queue (in terms of steps).
  1515. *
  1516. * target - target position in steps units
  1517. * target_float - target position in direct (mm, degrees) units. optional
  1518. * fr_mm_s - (target) speed of the move
  1519. * extruder - target extruder
  1520. * millimeters - the length of the movement, if known
  1521. *
  1522. * Returns true if movement was properly queued, false otherwise (if cleaning)
  1523. */
  1524. bool Planner::_buffer_steps(const xyze_long_t &target
  1525. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  1526. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  1527. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters
  1528. ) {
  1529. // Wait for the next available block
  1530. uint8_t next_buffer_head;
  1531. block_t * const block = get_next_free_block(next_buffer_head);
  1532. // If we are cleaning, do not accept queuing of movements
  1533. // This must be after get_next_free_block() because it calls idle()
  1534. // where cleaning_buffer_counter can be changed
  1535. if (cleaning_buffer_counter) return false;
  1536. // Fill the block with the specified movement
  1537. if (!_populate_block(block, false, target
  1538. OPTARG(HAS_POSITION_FLOAT, target_float)
  1539. OPTARG(HAS_DIST_MM_ARG, cart_dist_mm)
  1540. , fr_mm_s, extruder, millimeters
  1541. )) {
  1542. // Movement was not queued, probably because it was too short.
  1543. // Simply accept that as movement queued and done
  1544. return true;
  1545. }
  1546. // If this is the first added movement, reload the delay, otherwise, cancel it.
  1547. if (block_buffer_head == block_buffer_tail) {
  1548. // If it was the first queued block, restart the 1st block delivery delay, to
  1549. // give the planner an opportunity to queue more movements and plan them
  1550. // As there are no queued movements, the Stepper ISR will not touch this
  1551. // variable, so there is no risk setting this here (but it MUST be done
  1552. // before the following line!!)
  1553. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  1554. }
  1555. // Move buffer head
  1556. block_buffer_head = next_buffer_head;
  1557. // Recalculate and optimize trapezoidal speed profiles
  1558. recalculate();
  1559. // Movement successfully queued!
  1560. return true;
  1561. }
  1562. /**
  1563. * Planner::_populate_block
  1564. *
  1565. * Fills a new linear movement in the block (in terms of steps).
  1566. *
  1567. * target - target position in steps units
  1568. * fr_mm_s - (target) speed of the move
  1569. * extruder - target extruder
  1570. *
  1571. * Returns true if movement is acceptable, false otherwise
  1572. */
  1573. bool Planner::_populate_block(block_t * const block, bool split_move,
  1574. const abce_long_t &target
  1575. OPTARG(HAS_POSITION_FLOAT, const xyze_pos_t &target_float)
  1576. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  1577. , feedRate_t fr_mm_s, const uint8_t extruder, const_float_t millimeters/*=0.0*/
  1578. ) {
  1579. int32_t LOGICAL_AXIS_LIST(
  1580. de = target.e - position.e,
  1581. da = target.a - position.a,
  1582. db = target.b - position.b,
  1583. dc = target.c - position.c,
  1584. di = target.i - position.i,
  1585. dj = target.j - position.j,
  1586. dk = target.k - position.k
  1587. );
  1588. /* <-- add a slash to enable
  1589. SERIAL_ECHOLNPGM(
  1590. " _populate_block FR:", fr_mm_s,
  1591. " A:", target.a, " (", da, " steps)"
  1592. " B:", target.b, " (", db, " steps)"
  1593. " C:", target.c, " (", dc, " steps)"
  1594. #if LINEAR_AXES >= 4
  1595. " " AXIS4_STR ":", target.i, " (", di, " steps)"
  1596. #endif
  1597. #if LINEAR_AXES >= 5
  1598. " " AXIS5_STR ":", target.j, " (", dj, " steps)"
  1599. #endif
  1600. #if LINEAR_AXES >= 6
  1601. " " AXIS6_STR ":", target.k, " (", dk, " steps)"
  1602. #endif
  1603. #if HAS_EXTRUDERS
  1604. " E:", target.e, " (", de, " steps)"
  1605. #endif
  1606. );
  1607. //*/
  1608. #if EITHER(PREVENT_COLD_EXTRUSION, PREVENT_LENGTHY_EXTRUDE)
  1609. if (de) {
  1610. #if ENABLED(PREVENT_COLD_EXTRUSION)
  1611. if (thermalManager.tooColdToExtrude(extruder)) {
  1612. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1613. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1614. de = 0; // no difference
  1615. SERIAL_ECHO_MSG(STR_ERR_COLD_EXTRUDE_STOP);
  1616. }
  1617. #endif // PREVENT_COLD_EXTRUSION
  1618. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  1619. const float e_steps = ABS(de * e_factor[extruder]);
  1620. const float max_e_steps = settings.axis_steps_per_mm[E_AXIS_N(extruder)] * (EXTRUDE_MAXLENGTH);
  1621. if (e_steps > max_e_steps) {
  1622. #if ENABLED(MIXING_EXTRUDER)
  1623. bool ignore_e = false;
  1624. float collector[MIXING_STEPPERS];
  1625. mixer.refresh_collector(1.0, mixer.get_current_vtool(), collector);
  1626. MIXER_STEPPER_LOOP(e)
  1627. if (e_steps * collector[e] > max_e_steps) { ignore_e = true; break; }
  1628. #else
  1629. constexpr bool ignore_e = true;
  1630. #endif
  1631. if (ignore_e) {
  1632. position.e = target.e; // Behave as if the move really took place, but ignore E part
  1633. TERN_(HAS_POSITION_FLOAT, position_float.e = target_float.e);
  1634. de = 0; // no difference
  1635. SERIAL_ECHO_MSG(STR_ERR_LONG_EXTRUDE_STOP);
  1636. }
  1637. }
  1638. #endif // PREVENT_LENGTHY_EXTRUDE
  1639. }
  1640. #endif // PREVENT_COLD_EXTRUSION || PREVENT_LENGTHY_EXTRUDE
  1641. // Compute direction bit-mask for this block
  1642. uint8_t dm = 0;
  1643. #if CORE_IS_XY
  1644. if (da < 0) SBI(dm, X_HEAD); // Save the toolhead's true direction in X
  1645. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1646. if (dc < 0) SBI(dm, Z_AXIS);
  1647. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1648. if (CORESIGN(da - db) < 0) SBI(dm, B_AXIS); // Motor B direction
  1649. #elif CORE_IS_XZ
  1650. if (da < 0) SBI(dm, X_HEAD); // Save the toolhead's true direction in X
  1651. if (db < 0) SBI(dm, Y_AXIS);
  1652. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1653. if (da + dc < 0) SBI(dm, A_AXIS); // Motor A direction
  1654. if (CORESIGN(da - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1655. #elif CORE_IS_YZ
  1656. if (da < 0) SBI(dm, X_AXIS);
  1657. if (db < 0) SBI(dm, Y_HEAD); // Save the toolhead's true direction in Y
  1658. if (dc < 0) SBI(dm, Z_HEAD); // ...and Z
  1659. if (db + dc < 0) SBI(dm, B_AXIS); // Motor B direction
  1660. if (CORESIGN(db - dc) < 0) SBI(dm, C_AXIS); // Motor C direction
  1661. #elif ENABLED(MARKFORGED_XY)
  1662. if (da < 0) SBI(dm, X_HEAD); // Save the toolhead's true direction in X
  1663. if (db < 0) SBI(dm, Y_HEAD); // ...and Y
  1664. if (dc < 0) SBI(dm, Z_AXIS);
  1665. if (da + db < 0) SBI(dm, A_AXIS); // Motor A direction
  1666. if (db < 0) SBI(dm, B_AXIS); // Motor B direction
  1667. #else
  1668. LINEAR_AXIS_CODE(
  1669. if (da < 0) SBI(dm, X_AXIS),
  1670. if (db < 0) SBI(dm, Y_AXIS),
  1671. if (dc < 0) SBI(dm, Z_AXIS),
  1672. if (di < 0) SBI(dm, I_AXIS),
  1673. if (dj < 0) SBI(dm, J_AXIS),
  1674. if (dk < 0) SBI(dm, K_AXIS)
  1675. );
  1676. #endif
  1677. #if IS_CORE
  1678. #if LINEAR_AXES >= 4
  1679. if (di < 0) SBI(dm, I_AXIS);
  1680. #endif
  1681. #if LINEAR_AXES >= 5
  1682. if (dj < 0) SBI(dm, J_AXIS);
  1683. #endif
  1684. #if LINEAR_AXES >= 6
  1685. if (dk < 0) SBI(dm, K_AXIS);
  1686. #endif
  1687. #endif
  1688. TERN_(HAS_EXTRUDERS, if (de < 0) SBI(dm, E_AXIS));
  1689. #if HAS_EXTRUDERS
  1690. const float esteps_float = de * e_factor[extruder];
  1691. const uint32_t esteps = ABS(esteps_float) + 0.5f;
  1692. #else
  1693. constexpr uint32_t esteps = 0;
  1694. #endif
  1695. // Clear all flags, including the "busy" bit
  1696. block->flag = 0x00;
  1697. // Set direction bits
  1698. block->direction_bits = dm;
  1699. // Update block laser power
  1700. #if ENABLED(LASER_POWER_INLINE)
  1701. laser_inline.status.isPlanned = true;
  1702. block->laser.status = laser_inline.status;
  1703. block->laser.power = laser_inline.power;
  1704. #endif
  1705. // Number of steps for each axis
  1706. // See https://www.corexy.com/theory.html
  1707. #if CORE_IS_XY
  1708. block->steps.set(LINEAR_AXIS_LIST(ABS(da + db), ABS(da - db), ABS(dc), ABS(di), ABS(dj), ABS(dk)));
  1709. #elif CORE_IS_XZ
  1710. block->steps.set(LINEAR_AXIS_LIST(ABS(da + dc), ABS(db), ABS(da - dc), ABS(di), ABS(dj), ABS(dk)));
  1711. #elif CORE_IS_YZ
  1712. block->steps.set(LINEAR_AXIS_LIST(ABS(da), ABS(db + dc), ABS(db - dc), ABS(di), ABS(dj), ABS(dk)));
  1713. #elif ENABLED(MARKFORGED_XY)
  1714. block->steps.set(LINEAR_AXIS_LIST(ABS(da + db), ABS(db), ABS(dc), ABS(di), ABS(dj), ABS(dk)));
  1715. #elif IS_SCARA
  1716. block->steps.set(LINEAR_AXIS_LIST(ABS(da), ABS(db), ABS(dc), ABS(di), ABS(dj), ABS(dk)));
  1717. #else
  1718. // default non-h-bot planning
  1719. block->steps.set(LINEAR_AXIS_LIST(ABS(da), ABS(db), ABS(dc), ABS(di), ABS(dj), ABS(dk)));
  1720. #endif
  1721. /**
  1722. * This part of the code calculates the total length of the movement.
  1723. * For cartesian bots, the X_AXIS is the real X movement and same for Y_AXIS.
  1724. * But for corexy bots, that is not true. The "X_AXIS" and "Y_AXIS" motors (that should be named to A_AXIS
  1725. * and B_AXIS) cannot be used for X and Y length, because A=X+Y and B=X-Y.
  1726. * So we need to create other 2 "AXIS", named X_HEAD and Y_HEAD, meaning the real displacement of the Head.
  1727. * Having the real displacement of the head, we can calculate the total movement length and apply the desired speed.
  1728. */
  1729. struct DistanceMM : abce_float_t {
  1730. #if EITHER(IS_CORE, MARKFORGED_XY)
  1731. struct { float x, y, z; } head;
  1732. #endif
  1733. } steps_dist_mm;
  1734. #if IS_CORE
  1735. #if CORE_IS_XY
  1736. steps_dist_mm.head.x = da * steps_to_mm[A_AXIS];
  1737. steps_dist_mm.head.y = db * steps_to_mm[B_AXIS];
  1738. steps_dist_mm.z = dc * steps_to_mm[Z_AXIS];
  1739. steps_dist_mm.a = (da + db) * steps_to_mm[A_AXIS];
  1740. steps_dist_mm.b = CORESIGN(da - db) * steps_to_mm[B_AXIS];
  1741. #elif CORE_IS_XZ
  1742. steps_dist_mm.head.x = da * steps_to_mm[A_AXIS];
  1743. steps_dist_mm.y = db * steps_to_mm[Y_AXIS];
  1744. steps_dist_mm.head.z = dc * steps_to_mm[C_AXIS];
  1745. steps_dist_mm.a = (da + dc) * steps_to_mm[A_AXIS];
  1746. steps_dist_mm.c = CORESIGN(da - dc) * steps_to_mm[C_AXIS];
  1747. #elif CORE_IS_YZ
  1748. steps_dist_mm.x = da * steps_to_mm[X_AXIS];
  1749. steps_dist_mm.head.y = db * steps_to_mm[B_AXIS];
  1750. steps_dist_mm.head.z = dc * steps_to_mm[C_AXIS];
  1751. steps_dist_mm.b = (db + dc) * steps_to_mm[B_AXIS];
  1752. steps_dist_mm.c = CORESIGN(db - dc) * steps_to_mm[C_AXIS];
  1753. #endif
  1754. #if LINEAR_AXES >= 4
  1755. steps_dist_mm.i = di * steps_to_mm[I_AXIS];
  1756. #endif
  1757. #if LINEAR_AXES >= 5
  1758. steps_dist_mm.j = dj * steps_to_mm[J_AXIS];
  1759. #endif
  1760. #if LINEAR_AXES >= 6
  1761. steps_dist_mm.k = dk * steps_to_mm[K_AXIS];
  1762. #endif
  1763. #elif ENABLED(MARKFORGED_XY)
  1764. steps_dist_mm.head.x = da * steps_to_mm[A_AXIS];
  1765. steps_dist_mm.head.y = db * steps_to_mm[B_AXIS];
  1766. steps_dist_mm.z = dc * steps_to_mm[Z_AXIS];
  1767. steps_dist_mm.a = (da - db) * steps_to_mm[A_AXIS];
  1768. steps_dist_mm.b = db * steps_to_mm[B_AXIS];
  1769. #else
  1770. LINEAR_AXIS_CODE(
  1771. steps_dist_mm.a = da * steps_to_mm[A_AXIS],
  1772. steps_dist_mm.b = db * steps_to_mm[B_AXIS],
  1773. steps_dist_mm.c = dc * steps_to_mm[C_AXIS],
  1774. steps_dist_mm.i = di * steps_to_mm[I_AXIS],
  1775. steps_dist_mm.j = dj * steps_to_mm[J_AXIS],
  1776. steps_dist_mm.k = dk * steps_to_mm[K_AXIS]
  1777. );
  1778. #endif
  1779. TERN_(HAS_EXTRUDERS, steps_dist_mm.e = esteps_float * steps_to_mm[E_AXIS_N(extruder)]);
  1780. TERN_(LCD_SHOW_E_TOTAL, e_move_accumulator += steps_dist_mm.e);
  1781. if (true LINEAR_AXIS_GANG(
  1782. && block->steps.a < MIN_STEPS_PER_SEGMENT,
  1783. && block->steps.b < MIN_STEPS_PER_SEGMENT,
  1784. && block->steps.c < MIN_STEPS_PER_SEGMENT,
  1785. && block->steps.i < MIN_STEPS_PER_SEGMENT,
  1786. && block->steps.j < MIN_STEPS_PER_SEGMENT,
  1787. && block->steps.k < MIN_STEPS_PER_SEGMENT
  1788. )
  1789. ) {
  1790. block->millimeters = TERN0(HAS_EXTRUDERS, ABS(steps_dist_mm.e));
  1791. }
  1792. else {
  1793. if (millimeters)
  1794. block->millimeters = millimeters;
  1795. else {
  1796. block->millimeters = SQRT(
  1797. #if EITHER(CORE_IS_XY, MARKFORGED_XY)
  1798. LINEAR_AXIS_GANG(
  1799. sq(steps_dist_mm.head.x), + sq(steps_dist_mm.head.y), + sq(steps_dist_mm.z),
  1800. + sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k)
  1801. )
  1802. #elif CORE_IS_XZ
  1803. LINEAR_AXIS_GANG(
  1804. sq(steps_dist_mm.head.x), + sq(steps_dist_mm.y), + sq(steps_dist_mm.head.z),
  1805. + sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k)
  1806. )
  1807. #elif CORE_IS_YZ
  1808. LINEAR_AXIS_GANG(
  1809. sq(steps_dist_mm.x) + sq(steps_dist_mm.head.y) + sq(steps_dist_mm.head.z)
  1810. + sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k)
  1811. )
  1812. #elif ENABLED(FOAMCUTTER_XYUV)
  1813. // Return the largest distance move from either X/Y or I/J plane
  1814. #if LINEAR_AXES >= 5
  1815. _MAX(sq(steps_dist_mm.x) + sq(steps_dist_mm.y), sq(steps_dist_mm.i) + sq(steps_dist_mm.j))
  1816. #else
  1817. sq(steps_dist_mm.x) + sq(steps_dist_mm.y)
  1818. #endif
  1819. #else
  1820. LINEAR_AXIS_GANG(
  1821. sq(steps_dist_mm.x), + sq(steps_dist_mm.y), + sq(steps_dist_mm.z),
  1822. + sq(steps_dist_mm.i), + sq(steps_dist_mm.j), + sq(steps_dist_mm.k)
  1823. )
  1824. #endif
  1825. );
  1826. }
  1827. /**
  1828. * At this point at least one of the axes has more steps than
  1829. * MIN_STEPS_PER_SEGMENT, ensuring the segment won't get dropped as
  1830. * zero-length. It's important to not apply corrections
  1831. * to blocks that would get dropped!
  1832. *
  1833. * A correction function is permitted to add steps to an axis, it
  1834. * should *never* remove steps!
  1835. */
  1836. TERN_(BACKLASH_COMPENSATION, backlash.add_correction_steps(da, db, dc, dm, block));
  1837. }
  1838. TERN_(HAS_EXTRUDERS, block->steps.e = esteps);
  1839. block->step_event_count = _MAX(LOGICAL_AXIS_LIST(
  1840. esteps, block->steps.a, block->steps.b, block->steps.c, block->steps.i, block->steps.j, block->steps.k
  1841. ));
  1842. // Bail if this is a zero-length block
  1843. if (block->step_event_count < MIN_STEPS_PER_SEGMENT) return false;
  1844. TERN_(MIXING_EXTRUDER, mixer.populate_block(block->b_color));
  1845. TERN_(HAS_CUTTER, block->cutter_power = cutter.power);
  1846. #if HAS_FAN
  1847. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  1848. #endif
  1849. #if ENABLED(BARICUDA)
  1850. block->valve_pressure = baricuda_valve_pressure;
  1851. block->e_to_p_pressure = baricuda_e_to_p_pressure;
  1852. #endif
  1853. TERN_(HAS_MULTI_EXTRUDER, block->extruder = extruder);
  1854. #if ENABLED(AUTO_POWER_CONTROL)
  1855. if (LINEAR_AXIS_GANG(
  1856. block->steps.x,
  1857. || block->steps.y,
  1858. || block->steps.z,
  1859. || block->steps.i,
  1860. || block->steps.j,
  1861. || block->steps.k
  1862. )) powerManager.power_on();
  1863. #endif
  1864. // Enable active axes
  1865. #if EITHER(CORE_IS_XY, MARKFORGED_XY)
  1866. if (block->steps.a || block->steps.b) {
  1867. ENABLE_AXIS_X();
  1868. ENABLE_AXIS_Y();
  1869. }
  1870. #if DISABLED(Z_LATE_ENABLE)
  1871. if (block->steps.z) ENABLE_AXIS_Z();
  1872. #endif
  1873. #elif CORE_IS_XZ
  1874. if (block->steps.a || block->steps.c) {
  1875. ENABLE_AXIS_X();
  1876. ENABLE_AXIS_Z();
  1877. }
  1878. if (block->steps.y) ENABLE_AXIS_Y();
  1879. #elif CORE_IS_YZ
  1880. if (block->steps.b || block->steps.c) {
  1881. ENABLE_AXIS_Y();
  1882. ENABLE_AXIS_Z();
  1883. }
  1884. if (block->steps.x) ENABLE_AXIS_X();
  1885. #else
  1886. LINEAR_AXIS_CODE(
  1887. if (block->steps.x) ENABLE_AXIS_X(),
  1888. if (block->steps.y) ENABLE_AXIS_Y(),
  1889. if (TERN(Z_LATE_ENABLE, 0, block->steps.z)) ENABLE_AXIS_Z(),
  1890. if (block->steps.i) ENABLE_AXIS_I(),
  1891. if (block->steps.j) ENABLE_AXIS_J(),
  1892. if (block->steps.k) ENABLE_AXIS_K()
  1893. );
  1894. #endif
  1895. #if EITHER(IS_CORE, MARKFORGED_XY)
  1896. #if LINEAR_AXES >= 4
  1897. if (block->steps.i) ENABLE_AXIS_I();
  1898. #endif
  1899. #if LINEAR_AXES >= 5
  1900. if (block->steps.j) ENABLE_AXIS_J();
  1901. #endif
  1902. #if LINEAR_AXES >= 6
  1903. if (block->steps.k) ENABLE_AXIS_K();
  1904. #endif
  1905. #endif
  1906. // Enable extruder(s)
  1907. #if HAS_EXTRUDERS
  1908. if (esteps) {
  1909. TERN_(AUTO_POWER_CONTROL, powerManager.power_on());
  1910. #if ENABLED(DISABLE_INACTIVE_EXTRUDER) // Enable only the selected extruder
  1911. LOOP_L_N(i, E_STEPPERS)
  1912. if (g_uc_extruder_last_move[i]) g_uc_extruder_last_move[i]--;
  1913. #define E_STEPPER_INDEX(E) TERN(SWITCHING_EXTRUDER, (E) / 2, E)
  1914. #define ENABLE_ONE_E(N) do{ \
  1915. if (E_STEPPER_INDEX(extruder) == N) { \
  1916. ENABLE_AXIS_E##N(); \
  1917. g_uc_extruder_last_move[N] = (BLOCK_BUFFER_SIZE) * 2; \
  1918. if ((N) == 0 && TERN0(HAS_DUPLICATION_MODE, extruder_duplication_enabled)) \
  1919. ENABLE_AXIS_E1(); \
  1920. } \
  1921. else if (!g_uc_extruder_last_move[N]) { \
  1922. DISABLE_AXIS_E##N(); \
  1923. if ((N) == 0 && TERN0(HAS_DUPLICATION_MODE, extruder_duplication_enabled)) \
  1924. DISABLE_AXIS_E1(); \
  1925. } \
  1926. }while(0);
  1927. #else
  1928. #define ENABLE_ONE_E(N) ENABLE_AXIS_E##N();
  1929. #endif
  1930. REPEAT(E_STEPPERS, ENABLE_ONE_E); // (ENABLE_ONE_E must end with semicolon)
  1931. }
  1932. #endif // EXTRUDERS
  1933. if (esteps)
  1934. NOLESS(fr_mm_s, settings.min_feedrate_mm_s);
  1935. else
  1936. NOLESS(fr_mm_s, settings.min_travel_feedrate_mm_s);
  1937. const float inverse_millimeters = 1.0f / block->millimeters; // Inverse millimeters to remove multiple divides
  1938. // Calculate inverse time for this move. No divide by zero due to previous checks.
  1939. // Example: At 120mm/s a 60mm move takes 0.5s. So this will give 2.0.
  1940. float inverse_secs = fr_mm_s * inverse_millimeters;
  1941. // Get the number of non busy movements in queue (non busy means that they can be altered)
  1942. const uint8_t moves_queued = nonbusy_movesplanned();
  1943. // Slow down when the buffer starts to empty, rather than wait at the corner for a buffer refill
  1944. #if EITHER(SLOWDOWN, HAS_WIRED_LCD) || defined(XY_FREQUENCY_LIMIT)
  1945. // Segment time im micro seconds
  1946. int32_t segment_time_us = LROUND(1000000.0f / inverse_secs);
  1947. #endif
  1948. #if ENABLED(SLOWDOWN)
  1949. #ifndef SLOWDOWN_DIVISOR
  1950. #define SLOWDOWN_DIVISOR 2
  1951. #endif
  1952. if (WITHIN(moves_queued, 2, (BLOCK_BUFFER_SIZE) / (SLOWDOWN_DIVISOR) - 1)) {
  1953. const int32_t time_diff = settings.min_segment_time_us - segment_time_us;
  1954. if (time_diff > 0) {
  1955. // Buffer is draining so add extra time. The amount of time added increases if the buffer is still emptied more.
  1956. const int32_t nst = segment_time_us + LROUND(2 * time_diff / moves_queued);
  1957. inverse_secs = 1000000.0f / nst;
  1958. #if defined(XY_FREQUENCY_LIMIT) || HAS_WIRED_LCD
  1959. segment_time_us = nst;
  1960. #endif
  1961. }
  1962. }
  1963. #endif
  1964. #if HAS_WIRED_LCD
  1965. // Protect the access to the position.
  1966. const bool was_enabled = stepper.suspend();
  1967. block_buffer_runtime_us += segment_time_us;
  1968. block->segment_time_us = segment_time_us;
  1969. if (was_enabled) stepper.wake_up();
  1970. #endif
  1971. block->nominal_speed_sqr = sq(block->millimeters * inverse_secs); // (mm/sec)^2 Always > 0
  1972. block->nominal_rate = CEIL(block->step_event_count * inverse_secs); // (step/sec) Always > 0
  1973. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  1974. if (extruder == FILAMENT_SENSOR_EXTRUDER_NUM) // Only for extruder with filament sensor
  1975. filwidth.advance_e(steps_dist_mm.e);
  1976. #endif
  1977. // Calculate and limit speed in mm/sec
  1978. xyze_float_t current_speed;
  1979. float speed_factor = 1.0f; // factor <1 decreases speed
  1980. // Linear axes first with less logic
  1981. LOOP_LINEAR_AXES(i) {
  1982. current_speed[i] = steps_dist_mm[i] * inverse_secs;
  1983. const feedRate_t cs = ABS(current_speed[i]),
  1984. max_fr = settings.max_feedrate_mm_s[i];
  1985. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs);
  1986. }
  1987. // Limit speed on extruders, if any
  1988. #if HAS_EXTRUDERS
  1989. {
  1990. current_speed.e = steps_dist_mm.e * inverse_secs;
  1991. #if HAS_MIXER_SYNC_CHANNEL
  1992. // Move all mixing extruders at the specified rate
  1993. if (mixer.get_current_vtool() == MIXER_AUTORETRACT_TOOL)
  1994. current_speed.e *= MIXING_STEPPERS;
  1995. #endif
  1996. const feedRate_t cs = ABS(current_speed.e),
  1997. max_fr = settings.max_feedrate_mm_s[E_AXIS_N(extruder)]
  1998. * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1);
  1999. if (cs > max_fr) NOMORE(speed_factor, max_fr / cs); //respect max feedrate on any movement (doesn't matter if E axes only or not)
  2000. #if ENABLED(VOLUMETRIC_EXTRUDER_LIMIT)
  2001. const feedRate_t max_vfr = volumetric_extruder_feedrate_limit[extruder]
  2002. * TERN(HAS_MIXER_SYNC_CHANNEL, MIXING_STEPPERS, 1);
  2003. // TODO: Doesn't work properly for joined segments. Set MIN_STEPS_PER_SEGMENT 1 as workaround.
  2004. if (block->steps.a || block->steps.b || block->steps.c) {
  2005. if (max_vfr > 0 && cs > max_vfr) {
  2006. NOMORE(speed_factor, max_vfr / cs); // respect volumetric extruder limit (if any)
  2007. /* <-- add a slash to enable
  2008. SERIAL_ECHOPGM("volumetric extruder limit enforced: ", (cs * CIRCLE_AREA(filament_size[extruder] * 0.5f)));
  2009. SERIAL_ECHOPGM(" mm^3/s (", cs);
  2010. SERIAL_ECHOPGM(" mm/s) limited to ", (max_vfr * CIRCLE_AREA(filament_size[extruder] * 0.5f)));
  2011. SERIAL_ECHOPGM(" mm^3/s (", max_vfr);
  2012. SERIAL_ECHOLNPGM(" mm/s)");
  2013. //*/
  2014. }
  2015. }
  2016. #endif
  2017. }
  2018. #endif
  2019. #ifdef XY_FREQUENCY_LIMIT
  2020. static uint8_t old_direction_bits; // = 0
  2021. if (xy_freq_limit_hz) {
  2022. // Check and limit the xy direction change frequency
  2023. const uint8_t direction_change = block->direction_bits ^ old_direction_bits;
  2024. old_direction_bits = block->direction_bits;
  2025. segment_time_us = LROUND(float(segment_time_us) / speed_factor);
  2026. static int32_t xs0, xs1, xs2, ys0, ys1, ys2;
  2027. if (segment_time_us > xy_freq_min_interval_us)
  2028. xs2 = xs1 = ys2 = ys1 = xy_freq_min_interval_us;
  2029. else {
  2030. xs2 = xs1; xs1 = xs0;
  2031. ys2 = ys1; ys1 = ys0;
  2032. }
  2033. xs0 = TEST(direction_change, X_AXIS) ? segment_time_us : xy_freq_min_interval_us;
  2034. ys0 = TEST(direction_change, Y_AXIS) ? segment_time_us : xy_freq_min_interval_us;
  2035. if (segment_time_us < xy_freq_min_interval_us) {
  2036. const int32_t least_xy_segment_time = _MIN(_MAX(xs0, xs1, xs2), _MAX(ys0, ys1, ys2));
  2037. if (least_xy_segment_time < xy_freq_min_interval_us) {
  2038. float freq_xy_feedrate = (speed_factor * least_xy_segment_time) / xy_freq_min_interval_us;
  2039. NOLESS(freq_xy_feedrate, xy_freq_min_speed_factor);
  2040. NOMORE(speed_factor, freq_xy_feedrate);
  2041. }
  2042. }
  2043. }
  2044. #endif // XY_FREQUENCY_LIMIT
  2045. // Correct the speed
  2046. if (speed_factor < 1.0f) {
  2047. current_speed *= speed_factor;
  2048. block->nominal_rate *= speed_factor;
  2049. block->nominal_speed_sqr = block->nominal_speed_sqr * sq(speed_factor);
  2050. }
  2051. // Compute and limit the acceleration rate for the trapezoid generator.
  2052. const float steps_per_mm = block->step_event_count * inverse_millimeters;
  2053. uint32_t accel;
  2054. if (LINEAR_AXIS_GANG(
  2055. !block->steps.a, && !block->steps.b, && !block->steps.c,
  2056. && !block->steps.i, && !block->steps.j, && !block->steps.k)
  2057. ) { // Is this a retract / recover move?
  2058. accel = CEIL(settings.retract_acceleration * steps_per_mm); // Convert to: acceleration steps/sec^2
  2059. TERN_(LIN_ADVANCE, block->use_advance_lead = false); // No linear advance for simple retract/recover
  2060. }
  2061. else {
  2062. #define LIMIT_ACCEL_LONG(AXIS,INDX) do{ \
  2063. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  2064. const uint32_t max_possible = max_acceleration_steps_per_s2[AXIS+INDX] * block->step_event_count / block->steps[AXIS]; \
  2065. NOMORE(accel, max_possible); \
  2066. } \
  2067. }while(0)
  2068. #define LIMIT_ACCEL_FLOAT(AXIS,INDX) do{ \
  2069. if (block->steps[AXIS] && max_acceleration_steps_per_s2[AXIS+INDX] < accel) { \
  2070. const float max_possible = float(max_acceleration_steps_per_s2[AXIS+INDX]) * float(block->step_event_count) / float(block->steps[AXIS]); \
  2071. NOMORE(accel, max_possible); \
  2072. } \
  2073. }while(0)
  2074. // Start with print or travel acceleration
  2075. accel = CEIL((esteps ? settings.acceleration : settings.travel_acceleration) * steps_per_mm);
  2076. #if ENABLED(LIN_ADVANCE)
  2077. #define MAX_E_JERK(N) TERN(HAS_LINEAR_E_JERK, max_e_jerk[E_INDEX_N(N)], max_jerk.e)
  2078. /**
  2079. * Use LIN_ADVANCE for blocks if all these are true:
  2080. *
  2081. * esteps : This is a print move, because we checked for A, B, C steps before.
  2082. *
  2083. * extruder_advance_K[active_extruder] : There is an advance factor set for this extruder.
  2084. *
  2085. * de > 0 : Extruder is running forward (e.g., for "Wipe while retracting" (Slic3r) or "Combing" (Cura) moves)
  2086. */
  2087. block->use_advance_lead = esteps
  2088. && extruder_advance_K[active_extruder]
  2089. && de > 0;
  2090. if (block->use_advance_lead) {
  2091. block->e_D_ratio = (target_float.e - position_float.e) /
  2092. #if IS_KINEMATIC
  2093. block->millimeters
  2094. #else
  2095. SQRT(sq(target_float.x - position_float.x)
  2096. + sq(target_float.y - position_float.y)
  2097. + sq(target_float.z - position_float.z))
  2098. #endif
  2099. ;
  2100. // 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!
  2101. // 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.
  2102. if (block->e_D_ratio > 3.0f)
  2103. block->use_advance_lead = false;
  2104. else {
  2105. const uint32_t max_accel_steps_per_s2 = MAX_E_JERK(extruder) / (extruder_advance_K[active_extruder] * block->e_D_ratio) * steps_per_mm;
  2106. if (TERN0(LA_DEBUG, accel > max_accel_steps_per_s2))
  2107. SERIAL_ECHOLNPGM("Acceleration limited.");
  2108. NOMORE(accel, max_accel_steps_per_s2);
  2109. }
  2110. }
  2111. #endif
  2112. // Limit acceleration per axis
  2113. if (block->step_event_count <= acceleration_long_cutoff) {
  2114. LOGICAL_AXIS_CODE(
  2115. LIMIT_ACCEL_LONG(E_AXIS, E_INDEX_N(extruder)),
  2116. LIMIT_ACCEL_LONG(A_AXIS, 0),
  2117. LIMIT_ACCEL_LONG(B_AXIS, 0),
  2118. LIMIT_ACCEL_LONG(C_AXIS, 0),
  2119. LIMIT_ACCEL_LONG(I_AXIS, 0),
  2120. LIMIT_ACCEL_LONG(J_AXIS, 0),
  2121. LIMIT_ACCEL_LONG(K_AXIS, 0)
  2122. );
  2123. }
  2124. else {
  2125. LOGICAL_AXIS_CODE(
  2126. LIMIT_ACCEL_FLOAT(E_AXIS, E_INDEX_N(extruder)),
  2127. LIMIT_ACCEL_FLOAT(A_AXIS, 0),
  2128. LIMIT_ACCEL_FLOAT(B_AXIS, 0),
  2129. LIMIT_ACCEL_FLOAT(C_AXIS, 0),
  2130. LIMIT_ACCEL_FLOAT(I_AXIS, 0),
  2131. LIMIT_ACCEL_FLOAT(J_AXIS, 0),
  2132. LIMIT_ACCEL_FLOAT(K_AXIS, 0)
  2133. );
  2134. }
  2135. }
  2136. block->acceleration_steps_per_s2 = accel;
  2137. block->acceleration = accel / steps_per_mm;
  2138. #if DISABLED(S_CURVE_ACCELERATION)
  2139. block->acceleration_rate = (uint32_t)(accel * (sq(4096.0f) / (STEPPER_TIMER_RATE)));
  2140. #endif
  2141. #if ENABLED(LIN_ADVANCE)
  2142. if (block->use_advance_lead) {
  2143. block->advance_speed = (STEPPER_TIMER_RATE) / (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * settings.axis_steps_per_mm[E_AXIS_N(extruder)]);
  2144. #if ENABLED(LA_DEBUG)
  2145. if (extruder_advance_K[active_extruder] * block->e_D_ratio * block->acceleration * 2 < SQRT(block->nominal_speed_sqr) * block->e_D_ratio)
  2146. SERIAL_ECHOLNPGM("More than 2 steps per eISR loop executed.");
  2147. if (block->advance_speed < 200)
  2148. SERIAL_ECHOLNPGM("eISR running at > 10kHz.");
  2149. #endif
  2150. }
  2151. #endif
  2152. float vmax_junction_sqr; // Initial limit on the segment entry velocity (mm/s)^2
  2153. #if HAS_JUNCTION_DEVIATION
  2154. /**
  2155. * Compute maximum allowable entry speed at junction by centripetal acceleration approximation.
  2156. * Let a circle be tangent to both previous and current path line segments, where the junction
  2157. * deviation is defined as the distance from the junction to the closest edge of the circle,
  2158. * colinear with the circle center. The circular segment joining the two paths represents the
  2159. * path of centripetal acceleration. Solve for max velocity based on max acceleration about the
  2160. * radius of the circle, defined indirectly by junction deviation. This may be also viewed as
  2161. * path width or max_jerk in the previous Grbl version. This approach does not actually deviate
  2162. * from path, but used as a robust way to compute cornering speeds, as it takes into account the
  2163. * nonlinearities of both the junction angle and junction velocity.
  2164. *
  2165. * NOTE: If the junction deviation value is finite, Grbl executes the motions in an exact path
  2166. * mode (G61). If the junction deviation value is zero, Grbl will execute the motion in an exact
  2167. * stop mode (G61.1) manner. In the future, if continuous mode (G64) is desired, the math here
  2168. * is exactly the same. Instead of motioning all the way to junction point, the machine will
  2169. * just follow the arc circle defined here. The Arduino doesn't have the CPU cycles to perform
  2170. * a continuous mode path, but ARM-based microcontrollers most certainly do.
  2171. *
  2172. * NOTE: The max junction speed is a fixed value, since machine acceleration limits cannot be
  2173. * changed dynamically during operation nor can the line move geometry. This must be kept in
  2174. * memory in the event of a feedrate override changing the nominal speeds of blocks, which can
  2175. * change the overall maximum entry speed conditions of all blocks.
  2176. *
  2177. * #######
  2178. * https://github.com/MarlinFirmware/Marlin/issues/10341#issuecomment-388191754
  2179. *
  2180. * hoffbaked: on May 10 2018 tuned and improved the GRBL algorithm for Marlin:
  2181. Okay! It seems to be working good. I somewhat arbitrarily cut it off at 1mm
  2182. on then on anything with less sides than an octagon. With this, and the
  2183. reverse pass actually recalculating things, a corner acceleration value
  2184. of 1000 junction deviation of .05 are pretty reasonable. If the cycles
  2185. can be spared, a better acos could be used. For all I know, it may be
  2186. already calculated in a different place. */
  2187. // Unit vector of previous path line segment
  2188. static xyze_float_t prev_unit_vec;
  2189. xyze_float_t unit_vec =
  2190. #if HAS_DIST_MM_ARG
  2191. cart_dist_mm
  2192. #else
  2193. LOGICAL_AXIS_ARRAY(steps_dist_mm.e, steps_dist_mm.x, steps_dist_mm.y, steps_dist_mm.z, steps_dist_mm.i, steps_dist_mm.j, steps_dist_mm.k)
  2194. #endif
  2195. ;
  2196. /**
  2197. * On CoreXY the length of the vector [A,B] is SQRT(2) times the length of the head movement vector [X,Y].
  2198. * So taking Z and E into account, we cannot scale to a unit vector with "inverse_millimeters".
  2199. * => normalize the complete junction vector.
  2200. * Elsewise, when needed JD will factor-in the E component
  2201. */
  2202. if (EITHER(IS_CORE, MARKFORGED_XY) || esteps > 0)
  2203. normalize_junction_vector(unit_vec); // Normalize with XYZE components
  2204. else
  2205. unit_vec *= inverse_millimeters; // Use pre-calculated (1 / SQRT(x^2 + y^2 + z^2))
  2206. // Skip first block or when previous_nominal_speed is used as a flag for homing and offset cycles.
  2207. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2208. // Compute cosine of angle between previous and current path. (prev_unit_vec is negative)
  2209. // NOTE: Max junction velocity is computed without sin() or acos() by trig half angle identity.
  2210. float junction_cos_theta = LOGICAL_AXIS_GANG(
  2211. + (-prev_unit_vec.e * unit_vec.e),
  2212. (-prev_unit_vec.x * unit_vec.x),
  2213. + (-prev_unit_vec.y * unit_vec.y),
  2214. + (-prev_unit_vec.z * unit_vec.z),
  2215. + (-prev_unit_vec.i * unit_vec.i),
  2216. + (-prev_unit_vec.j * unit_vec.j),
  2217. + (-prev_unit_vec.k * unit_vec.k)
  2218. );
  2219. // NOTE: Computed without any expensive trig, sin() or acos(), by trig half angle identity of cos(theta).
  2220. if (junction_cos_theta > 0.999999f) {
  2221. // For a 0 degree acute junction, just set minimum junction speed.
  2222. vmax_junction_sqr = sq(float(MINIMUM_PLANNER_SPEED));
  2223. }
  2224. else {
  2225. NOLESS(junction_cos_theta, -0.999999f); // Check for numerical round-off to avoid divide by zero.
  2226. // Convert delta vector to unit vector
  2227. xyze_float_t junction_unit_vec = unit_vec - prev_unit_vec;
  2228. normalize_junction_vector(junction_unit_vec);
  2229. const float junction_acceleration = limit_value_by_axis_maximum(block->acceleration, junction_unit_vec),
  2230. sin_theta_d2 = SQRT(0.5f * (1.0f - junction_cos_theta)); // Trig half angle identity. Always positive.
  2231. vmax_junction_sqr = junction_acceleration * junction_deviation_mm * sin_theta_d2 / (1.0f - sin_theta_d2);
  2232. #if ENABLED(JD_HANDLE_SMALL_SEGMENTS)
  2233. // For small moves with >135° junction (octagon) find speed for approximate arc
  2234. if (block->millimeters < 1 && junction_cos_theta < -0.7071067812f) {
  2235. #if ENABLED(JD_USE_MATH_ACOS)
  2236. #error "TODO: Inline maths with the MCU / FPU."
  2237. #elif ENABLED(JD_USE_LOOKUP_TABLE)
  2238. // Fast acos approximation (max. error +-0.01 rads)
  2239. // Based on LUT table and linear interpolation
  2240. /**
  2241. * // Generate the JD Lookup Table
  2242. * constexpr float c = 1.00751495f; // Correction factor to center error around 0
  2243. * for (int i = 0; i < jd_lut_count - 1; ++i) {
  2244. * const float x0 = (sq(i) - 1) / sq(i),
  2245. * y0 = acos(x0) * (i == 0 ? 1 : c),
  2246. * x1 = i < jd_lut_count - 1 ? 0.5 * x0 + 0.5 : 0.999999f,
  2247. * y1 = acos(x1) * (i < jd_lut_count - 1 ? c : 1);
  2248. * jd_lut_k[i] = (y0 - y1) / (x0 - x1);
  2249. * jd_lut_b[i] = (y1 * x0 - y0 * x1) / (x0 - x1);
  2250. * }
  2251. *
  2252. * // Compute correction factor (Set c to 1.0f first!)
  2253. * float min = INFINITY, max = -min;
  2254. * for (float t = 0; t <= 1; t += 0.0003f) {
  2255. * const float e = acos(t) / approx(t);
  2256. * if (isfinite(e)) {
  2257. * if (e < min) min = e;
  2258. * if (e > max) max = e;
  2259. * }
  2260. * }
  2261. * fprintf(stderr, "%.9gf, ", (min + max) / 2);
  2262. */
  2263. static constexpr int16_t jd_lut_count = 16;
  2264. static constexpr uint16_t jd_lut_tll = _BV(jd_lut_count - 1);
  2265. static constexpr int16_t jd_lut_tll0 = __builtin_clz(jd_lut_tll) + 1; // i.e., 16 - jd_lut_count + 1
  2266. static constexpr float jd_lut_k[jd_lut_count] PROGMEM = {
  2267. -1.03145837f, -1.30760646f, -1.75205851f, -2.41705704f,
  2268. -3.37769222f, -4.74888992f, -6.69649887f, -9.45661736f,
  2269. -13.3640480f, -18.8928222f, -26.7136841f, -37.7754593f,
  2270. -53.4201813f, -75.5458374f, -106.836761f, -218.532821f };
  2271. static constexpr float jd_lut_b[jd_lut_count] PROGMEM = {
  2272. 1.57079637f, 1.70887053f, 2.04220939f, 2.62408352f,
  2273. 3.52467871f, 4.85302639f, 6.77020454f, 9.50875854f,
  2274. 13.4009285f, 18.9188995f, 26.7321243f, 37.7885055f,
  2275. 53.4293975f, 75.5523529f, 106.841369f, 218.534011f };
  2276. const float neg = junction_cos_theta < 0 ? -1 : 1,
  2277. t = neg * junction_cos_theta;
  2278. const int16_t idx = (t < 0.00000003f) ? 0 : __builtin_clz(uint16_t((1.0f - t) * jd_lut_tll)) - jd_lut_tll0;
  2279. float junction_theta = t * pgm_read_float(&jd_lut_k[idx]) + pgm_read_float(&jd_lut_b[idx]);
  2280. if (neg > 0) junction_theta = RADIANS(180) - junction_theta; // acos(-t)
  2281. #else
  2282. // Fast acos(-t) approximation (max. error +-0.033rad = 1.89°)
  2283. // Based on MinMax polynomial published by W. Randolph Franklin, see
  2284. // https://wrf.ecse.rpi.edu/Research/Short_Notes/arcsin/onlyelem.html
  2285. // acos( t) = pi / 2 - asin(x)
  2286. // acos(-t) = pi - acos(t) ... pi / 2 + asin(x)
  2287. const float neg = junction_cos_theta < 0 ? -1 : 1,
  2288. t = neg * junction_cos_theta,
  2289. asinx = 0.032843707f
  2290. + t * (-1.451838349f
  2291. + t * ( 29.66153956f
  2292. + t * (-131.1123477f
  2293. + t * ( 262.8130562f
  2294. + t * (-242.7199627f
  2295. + t * ( 84.31466202f ) ))))),
  2296. junction_theta = RADIANS(90) + neg * asinx; // acos(-t)
  2297. // NOTE: junction_theta bottoms out at 0.033 which avoids divide by 0.
  2298. #endif
  2299. const float limit_sqr = (block->millimeters * junction_acceleration) / junction_theta;
  2300. NOMORE(vmax_junction_sqr, limit_sqr);
  2301. }
  2302. #endif // JD_HANDLE_SMALL_SEGMENTS
  2303. }
  2304. // Get the lowest speed
  2305. vmax_junction_sqr = _MIN(vmax_junction_sqr, block->nominal_speed_sqr, previous_nominal_speed_sqr);
  2306. }
  2307. else // Init entry speed to zero. Assume it starts from rest. Planner will correct this later.
  2308. vmax_junction_sqr = 0;
  2309. prev_unit_vec = unit_vec;
  2310. #endif
  2311. #ifdef USE_CACHED_SQRT
  2312. #define CACHED_SQRT(N, V) \
  2313. static float saved_V, N; \
  2314. if (V != saved_V) { N = SQRT(V); saved_V = V; }
  2315. #else
  2316. #define CACHED_SQRT(N, V) const float N = SQRT(V)
  2317. #endif
  2318. #if HAS_CLASSIC_JERK
  2319. /**
  2320. * Adapted from Průša MKS firmware
  2321. * https://github.com/prusa3d/Prusa-Firmware
  2322. */
  2323. CACHED_SQRT(nominal_speed, block->nominal_speed_sqr);
  2324. // Exit speed limited by a jerk to full halt of a previous last segment
  2325. static float previous_safe_speed;
  2326. // Start with a safe speed (from which the machine may halt to stop immediately).
  2327. float safe_speed = nominal_speed;
  2328. #ifndef TRAVEL_EXTRA_XYJERK
  2329. #define TRAVEL_EXTRA_XYJERK 0
  2330. #endif
  2331. const float extra_xyjerk = TERN0(HAS_EXTRUDERS, de <= 0) ? TRAVEL_EXTRA_XYJERK : 0;
  2332. uint8_t limited = 0;
  2333. TERN(HAS_LINEAR_E_JERK, LOOP_LINEAR_AXES, LOOP_LOGICAL_AXES)(i) {
  2334. const float jerk = ABS(current_speed[i]), // cs : Starting from zero, change in speed for this axis
  2335. maxj = (max_jerk[i] + (i == X_AXIS || i == Y_AXIS ? extra_xyjerk : 0.0f)); // mj : The max jerk setting for this axis
  2336. if (jerk > maxj) { // cs > mj : New current speed too fast?
  2337. if (limited) { // limited already?
  2338. const float mjerk = nominal_speed * maxj; // ns*mj
  2339. if (jerk * safe_speed > mjerk) safe_speed = mjerk / jerk; // ns*mj/cs
  2340. }
  2341. else {
  2342. safe_speed *= maxj / jerk; // Initial limit: ns*mj/cs
  2343. ++limited; // Initially limited
  2344. }
  2345. }
  2346. }
  2347. float vmax_junction;
  2348. if (moves_queued && !UNEAR_ZERO(previous_nominal_speed_sqr)) {
  2349. // Estimate a maximum velocity allowed at a joint of two successive segments.
  2350. // If this maximum velocity allowed is lower than the minimum of the entry / exit safe velocities,
  2351. // then the machine is not coasting anymore and the safe entry / exit velocities shall be used.
  2352. // Factor to multiply the previous / current nominal velocities to get componentwise limited velocities.
  2353. float v_factor = 1;
  2354. limited = 0;
  2355. // The junction velocity will be shared between successive segments. Limit the junction velocity to their minimum.
  2356. // Pick the smaller of the nominal speeds. Higher speed shall not be achieved at the junction during coasting.
  2357. CACHED_SQRT(previous_nominal_speed, previous_nominal_speed_sqr);
  2358. float smaller_speed_factor = 1.0f;
  2359. if (nominal_speed < previous_nominal_speed) {
  2360. vmax_junction = nominal_speed;
  2361. smaller_speed_factor = vmax_junction / previous_nominal_speed;
  2362. }
  2363. else
  2364. vmax_junction = previous_nominal_speed;
  2365. // Now limit the jerk in all axes.
  2366. TERN(HAS_LINEAR_E_JERK, LOOP_LINEAR_AXES, LOOP_LOGICAL_AXES)(axis) {
  2367. // Limit an axis. We have to differentiate: coasting, reversal of an axis, full stop.
  2368. float v_exit = previous_speed[axis] * smaller_speed_factor,
  2369. v_entry = current_speed[axis];
  2370. if (limited) {
  2371. v_exit *= v_factor;
  2372. v_entry *= v_factor;
  2373. }
  2374. // Calculate jerk depending on whether the axis is coasting in the same direction or reversing.
  2375. const float jerk = (v_exit > v_entry)
  2376. ? // coasting axis reversal
  2377. ( (v_entry > 0 || v_exit < 0) ? (v_exit - v_entry) : _MAX(v_exit, -v_entry) )
  2378. : // v_exit <= v_entry coasting axis reversal
  2379. ( (v_entry < 0 || v_exit > 0) ? (v_entry - v_exit) : _MAX(-v_exit, v_entry) );
  2380. const float maxj = (max_jerk[axis] + (axis == X_AXIS || axis == Y_AXIS ? extra_xyjerk : 0.0f));
  2381. if (jerk > maxj) {
  2382. v_factor *= maxj / jerk;
  2383. ++limited;
  2384. }
  2385. }
  2386. if (limited) vmax_junction *= v_factor;
  2387. // Now the transition velocity is known, which maximizes the shared exit / entry velocity while
  2388. // respecting the jerk factors, it may be possible, that applying separate safe exit / entry velocities will achieve faster prints.
  2389. const float vmax_junction_threshold = vmax_junction * 0.99f;
  2390. if (previous_safe_speed > vmax_junction_threshold && safe_speed > vmax_junction_threshold)
  2391. vmax_junction = safe_speed;
  2392. }
  2393. else
  2394. vmax_junction = safe_speed;
  2395. previous_safe_speed = safe_speed;
  2396. #if HAS_JUNCTION_DEVIATION
  2397. NOMORE(vmax_junction_sqr, sq(vmax_junction)); // Throttle down to max speed
  2398. #else
  2399. vmax_junction_sqr = sq(vmax_junction); // Go up or down to the new speed
  2400. #endif
  2401. #endif // Classic Jerk Limiting
  2402. // Max entry speed of this block equals the max exit speed of the previous block.
  2403. block->max_entry_speed_sqr = vmax_junction_sqr;
  2404. // Initialize block entry speed. Compute based on deceleration to user-defined MINIMUM_PLANNER_SPEED.
  2405. const float v_allowable_sqr = max_allowable_speed_sqr(-block->acceleration, sq(float(MINIMUM_PLANNER_SPEED)), block->millimeters);
  2406. // If we are trying to add a split block, start with the
  2407. // max. allowed speed to avoid an interrupted first move.
  2408. block->entry_speed_sqr = !split_move ? sq(float(MINIMUM_PLANNER_SPEED)) : _MIN(vmax_junction_sqr, v_allowable_sqr);
  2409. // Initialize planner efficiency flags
  2410. // Set flag if block will always reach maximum junction speed regardless of entry/exit speeds.
  2411. // If a block can de/ac-celerate from nominal speed to zero within the length of the block, then
  2412. // the current block and next block junction speeds are guaranteed to always be at their maximum
  2413. // junction speeds in deceleration and acceleration, respectively. This is due to how the current
  2414. // block nominal speed limits both the current and next maximum junction speeds. Hence, in both
  2415. // the reverse and forward planners, the corresponding block junction speed will always be at the
  2416. // the maximum junction speed and may always be ignored for any speed reduction checks.
  2417. block->flag |= block->nominal_speed_sqr <= v_allowable_sqr ? BLOCK_FLAG_RECALCULATE | BLOCK_FLAG_NOMINAL_LENGTH : BLOCK_FLAG_RECALCULATE;
  2418. // Update previous path unit_vector and nominal speed
  2419. previous_speed = current_speed;
  2420. previous_nominal_speed_sqr = block->nominal_speed_sqr;
  2421. position = target; // Update the position
  2422. TERN_(HAS_POSITION_FLOAT, position_float = target_float);
  2423. TERN_(GRADIENT_MIX, mixer.gradient_control(target_float.z));
  2424. TERN_(POWER_LOSS_RECOVERY, block->sdpos = recovery.command_sdpos());
  2425. return true; // Movement was accepted
  2426. } // _populate_block()
  2427. /**
  2428. * Planner::buffer_sync_block
  2429. * Add a block to the buffer that just updates the position,
  2430. * or in case of LASER_SYNCHRONOUS_M106_M107 the fan PWM
  2431. */
  2432. void Planner::buffer_sync_block(TERN_(LASER_SYNCHRONOUS_M106_M107, uint8_t sync_flag)) {
  2433. #if DISABLED(LASER_SYNCHRONOUS_M106_M107)
  2434. constexpr uint8_t sync_flag = BLOCK_FLAG_SYNC_POSITION;
  2435. #endif
  2436. // Wait for the next available block
  2437. uint8_t next_buffer_head;
  2438. block_t * const block = get_next_free_block(next_buffer_head);
  2439. // Clear block
  2440. memset(block, 0, sizeof(block_t));
  2441. block->flag = sync_flag;
  2442. block->position = position;
  2443. #if BOTH(HAS_FAN, LASER_SYNCHRONOUS_M106_M107)
  2444. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  2445. #endif
  2446. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2447. if (block_buffer_head == block_buffer_tail) {
  2448. // If it was the first queued block, restart the 1st block delivery delay, to
  2449. // give the planner an opportunity to queue more movements and plan them
  2450. // As there are no queued movements, the Stepper ISR will not touch this
  2451. // variable, so there is no risk setting this here (but it MUST be done
  2452. // before the following line!!)
  2453. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2454. }
  2455. block_buffer_head = next_buffer_head;
  2456. stepper.wake_up();
  2457. } // buffer_sync_block()
  2458. /**
  2459. * Planner::buffer_segment
  2460. *
  2461. * Add a new linear movement to the buffer in axis units.
  2462. *
  2463. * Leveling and kinematics should be applied ahead of calling this.
  2464. *
  2465. * a,b,c,e - target positions in mm and/or degrees
  2466. * fr_mm_s - (target) speed of the move
  2467. * extruder - target extruder
  2468. * millimeters - the length of the movement, if known
  2469. *
  2470. * Return 'false' if no segment was queued due to cleaning, cold extrusion, full queue, etc.
  2471. */
  2472. bool Planner::buffer_segment(const abce_pos_t &abce
  2473. OPTARG(HAS_DIST_MM_ARG, const xyze_float_t &cart_dist_mm)
  2474. , const_feedRate_t fr_mm_s, const uint8_t extruder/*=active_extruder*/, const_float_t millimeters/*=0.0*/
  2475. ) {
  2476. // If we are cleaning, do not accept queuing of movements
  2477. if (cleaning_buffer_counter) return false;
  2478. // When changing extruders recalculate steps corresponding to the E position
  2479. #if ENABLED(DISTINCT_E_FACTORS)
  2480. if (last_extruder != extruder && settings.axis_steps_per_mm[E_AXIS_N(extruder)] != settings.axis_steps_per_mm[E_AXIS_N(last_extruder)]) {
  2481. position.e = LROUND(position.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)] * steps_to_mm[E_AXIS_N(last_extruder)]);
  2482. last_extruder = extruder;
  2483. }
  2484. #endif
  2485. // The target position of the tool in absolute steps
  2486. // Calculate target position in absolute steps
  2487. const abce_long_t target = {
  2488. LOGICAL_AXIS_LIST(
  2489. int32_t(LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(extruder)])),
  2490. int32_t(LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS])),
  2491. int32_t(LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS])),
  2492. int32_t(LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS])),
  2493. int32_t(LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS])),
  2494. int32_t(LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS])),
  2495. int32_t(LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS]))
  2496. )
  2497. };
  2498. #if HAS_POSITION_FLOAT
  2499. const xyze_pos_t target_float = abce;
  2500. #endif
  2501. #if HAS_EXTRUDERS
  2502. // DRYRUN prevents E moves from taking place
  2503. if (DEBUGGING(DRYRUN) || TERN0(CANCEL_OBJECTS, cancelable.skipping)) {
  2504. position.e = target.e;
  2505. TERN_(HAS_POSITION_FLOAT, position_float.e = abce.e);
  2506. }
  2507. #endif
  2508. /* <-- add a slash to enable
  2509. SERIAL_ECHOPGM(" buffer_segment FR:", fr_mm_s);
  2510. #if IS_KINEMATIC
  2511. SERIAL_ECHOPGM(" A:", abce.a, " (", position.a, "->", target.a, ") B:", abce.b);
  2512. #else
  2513. SERIAL_ECHOPGM_P(SP_X_LBL, abce.a);
  2514. SERIAL_ECHOPGM(" (", position.x, "->", target.x);
  2515. SERIAL_CHAR(')');
  2516. SERIAL_ECHOPGM_P(SP_Y_LBL, abce.b);
  2517. #endif
  2518. SERIAL_ECHOPGM(" (", position.y, "->", target.y);
  2519. #if LINEAR_AXES >= ABC
  2520. #if ENABLED(DELTA)
  2521. SERIAL_ECHOPGM(") C:", abce.c);
  2522. #else
  2523. SERIAL_CHAR(')');
  2524. SERIAL_ECHOPGM_P(SP_Z_LBL, abce.c);
  2525. #endif
  2526. SERIAL_ECHOPGM(" (", position.z, "->", target.z);
  2527. SERIAL_CHAR(')');
  2528. #endif
  2529. #if LINEAR_AXES >= 4
  2530. SERIAL_ECHOPGM_P(SP_I_LBL, abce.i);
  2531. SERIAL_ECHOPGM(" (", position.i, "->", target.i);
  2532. SERIAL_CHAR(')');
  2533. #endif
  2534. #if LINEAR_AXES >= 5
  2535. SERIAL_ECHOPGM_P(SP_J_LBL, abce.j);
  2536. SERIAL_ECHOPGM(" (", position.j, "->", target.j);
  2537. SERIAL_CHAR(')');
  2538. #endif
  2539. #if LINEAR_AXES >= 6
  2540. SERIAL_ECHOPGM_P(SP_K_LBL, abce.k);
  2541. SERIAL_ECHOPGM(" (", position.k, "->", target.k);
  2542. SERIAL_CHAR(')');
  2543. #endif
  2544. #if HAS_EXTRUDERS
  2545. SERIAL_ECHOPGM_P(SP_E_LBL, abce.e);
  2546. SERIAL_ECHOLNPGM(" (", position.e, "->", target.e, ")");
  2547. #else
  2548. SERIAL_EOL();
  2549. #endif
  2550. //*/
  2551. // Queue the movement. Return 'false' if the move was not queued.
  2552. if (!_buffer_steps(target
  2553. OPTARG(HAS_POSITION_FLOAT, target_float)
  2554. OPTARG(HAS_DIST_MM_ARG, cart_dist_mm)
  2555. , fr_mm_s, extruder, millimeters)
  2556. ) return false;
  2557. stepper.wake_up();
  2558. return true;
  2559. } // buffer_segment()
  2560. /**
  2561. * Add a new linear movement to the buffer.
  2562. * The target is cartesian. It's translated to
  2563. * delta/scara if needed.
  2564. *
  2565. * cart - target position in mm or degrees
  2566. * fr_mm_s - (target) speed of the move (mm/s)
  2567. * extruder - target extruder
  2568. * millimeters - the length of the movement, if known
  2569. * inv_duration - the reciprocal if the duration of the movement, if known (kinematic only if feeedrate scaling is enabled)
  2570. */
  2571. bool Planner::buffer_line(const xyze_pos_t &cart, const_feedRate_t fr_mm_s, const uint8_t extruder/*=active_extruder*/, const float millimeters/*=0.0*/
  2572. OPTARG(SCARA_FEEDRATE_SCALING, const_float_t inv_duration/*=0.0*/)
  2573. ) {
  2574. xyze_pos_t machine = cart;
  2575. TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine));
  2576. #if IS_KINEMATIC
  2577. #if HAS_JUNCTION_DEVIATION
  2578. const xyze_pos_t cart_dist_mm = LOGICAL_AXIS_ARRAY(
  2579. cart.e - position_cart.e,
  2580. cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z,
  2581. cart.i - position_cart.i, cart.j - position_cart.j, cart.j - position_cart.k
  2582. );
  2583. #else
  2584. const xyz_pos_t cart_dist_mm = LINEAR_AXIS_ARRAY(
  2585. cart.x - position_cart.x, cart.y - position_cart.y, cart.z - position_cart.z,
  2586. cart.i - position_cart.i, cart.j - position_cart.j, cart.j - position_cart.k
  2587. );
  2588. #endif
  2589. const float mm = millimeters ?: (cart_dist_mm.x || cart_dist_mm.y) ? cart_dist_mm.magnitude() : TERN0(HAS_Z_AXIS, ABS(cart_dist_mm.z));
  2590. // Cartesian XYZ to kinematic ABC, stored in global 'delta'
  2591. inverse_kinematics(machine);
  2592. #if ENABLED(SCARA_FEEDRATE_SCALING)
  2593. // For SCARA scale the feed rate from mm/s to degrees/s
  2594. // i.e., Complete the angular vector in the given time.
  2595. const float duration_recip = inv_duration ?: fr_mm_s / mm;
  2596. const xyz_pos_t diff = delta - position_float;
  2597. const feedRate_t feedrate = diff.magnitude() * duration_recip;
  2598. #else
  2599. const feedRate_t feedrate = fr_mm_s;
  2600. #endif
  2601. TERN_(HAS_EXTRUDERS, delta.e = machine.e);
  2602. if (buffer_segment(delta OPTARG(HAS_DIST_MM_ARG, cart_dist_mm), feedrate, extruder, mm)) {
  2603. position_cart = cart;
  2604. return true;
  2605. }
  2606. return false;
  2607. #else
  2608. return buffer_segment(machine, fr_mm_s, extruder, millimeters);
  2609. #endif
  2610. } // buffer_line()
  2611. #if ENABLED(DIRECT_STEPPING)
  2612. void Planner::buffer_page(const page_idx_t page_idx, const uint8_t extruder, const uint16_t num_steps) {
  2613. if (!last_page_step_rate) {
  2614. kill(GET_TEXT(MSG_BAD_PAGE_SPEED));
  2615. return;
  2616. }
  2617. uint8_t next_buffer_head;
  2618. block_t * const block = get_next_free_block(next_buffer_head);
  2619. block->flag = BLOCK_FLAG_IS_PAGE;
  2620. #if HAS_FAN
  2621. FANS_LOOP(i) block->fan_speed[i] = thermalManager.fan_speed[i];
  2622. #endif
  2623. TERN_(HAS_MULTI_EXTRUDER, block->extruder = extruder);
  2624. block->page_idx = page_idx;
  2625. block->step_event_count = num_steps;
  2626. block->initial_rate = block->final_rate = block->nominal_rate = last_page_step_rate; // steps/s
  2627. block->accelerate_until = 0;
  2628. block->decelerate_after = block->step_event_count;
  2629. // Will be set to last direction later if directional format.
  2630. block->direction_bits = 0;
  2631. #define PAGE_UPDATE_DIR(AXIS) \
  2632. if (!last_page_dir[_AXIS(AXIS)]) SBI(block->direction_bits, _AXIS(AXIS));
  2633. if (!DirectStepping::Config::DIRECTIONAL) {
  2634. PAGE_UPDATE_DIR(X);
  2635. PAGE_UPDATE_DIR(Y);
  2636. PAGE_UPDATE_DIR(Z);
  2637. PAGE_UPDATE_DIR(E);
  2638. }
  2639. // If this is the first added movement, reload the delay, otherwise, cancel it.
  2640. if (block_buffer_head == block_buffer_tail) {
  2641. // If it was the first queued block, restart the 1st block delivery delay, to
  2642. // give the planner an opportunity to queue more movements and plan them
  2643. // As there are no queued movements, the Stepper ISR will not touch this
  2644. // variable, so there is no risk setting this here (but it MUST be done
  2645. // before the following line!!)
  2646. delay_before_delivering = BLOCK_DELAY_FOR_1ST_MOVE;
  2647. }
  2648. // Move buffer head
  2649. block_buffer_head = next_buffer_head;
  2650. enable_all_steppers();
  2651. stepper.wake_up();
  2652. }
  2653. #endif // DIRECT_STEPPING
  2654. /**
  2655. * Directly set the planner ABCE position (and stepper positions)
  2656. * converting mm (or angles for SCARA) into steps.
  2657. *
  2658. * The provided ABCE position is in machine units.
  2659. */
  2660. void Planner::set_machine_position_mm(const abce_pos_t &abce) {
  2661. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2662. TERN_(HAS_POSITION_FLOAT, position_float = abce);
  2663. position.set(
  2664. LOGICAL_AXIS_LIST(
  2665. LROUND(abce.e * settings.axis_steps_per_mm[E_AXIS_N(active_extruder)]),
  2666. LROUND(abce.a * settings.axis_steps_per_mm[A_AXIS]),
  2667. LROUND(abce.b * settings.axis_steps_per_mm[B_AXIS]),
  2668. LROUND(abce.c * settings.axis_steps_per_mm[C_AXIS]),
  2669. LROUND(abce.i * settings.axis_steps_per_mm[I_AXIS]),
  2670. LROUND(abce.j * settings.axis_steps_per_mm[J_AXIS]),
  2671. LROUND(abce.k * settings.axis_steps_per_mm[K_AXIS])
  2672. )
  2673. );
  2674. if (has_blocks_queued()) {
  2675. //previous_nominal_speed_sqr = 0.0; // Reset planner junction speeds. Assume start from rest.
  2676. //previous_speed.reset();
  2677. buffer_sync_block();
  2678. }
  2679. else
  2680. stepper.set_position(position);
  2681. }
  2682. void Planner::set_position_mm(const xyze_pos_t &xyze) {
  2683. xyze_pos_t machine = xyze;
  2684. TERN_(HAS_POSITION_MODIFIERS, apply_modifiers(machine, true));
  2685. #if IS_KINEMATIC
  2686. position_cart = xyze;
  2687. inverse_kinematics(machine);
  2688. TERN_(HAS_EXTRUDERS, delta.e = machine.e);
  2689. set_machine_position_mm(delta);
  2690. #else
  2691. set_machine_position_mm(machine);
  2692. #endif
  2693. }
  2694. #if HAS_EXTRUDERS
  2695. /**
  2696. * Setters for planner position (also setting stepper position).
  2697. */
  2698. void Planner::set_e_position_mm(const_float_t e) {
  2699. const uint8_t axis_index = E_AXIS_N(active_extruder);
  2700. TERN_(DISTINCT_E_FACTORS, last_extruder = active_extruder);
  2701. const float e_new = DIFF_TERN(FWRETRACT, e, fwretract.current_retract[active_extruder]);
  2702. position.e = LROUND(settings.axis_steps_per_mm[axis_index] * e_new);
  2703. TERN_(HAS_POSITION_FLOAT, position_float.e = e_new);
  2704. TERN_(IS_KINEMATIC, TERN_(HAS_EXTRUDERS, position_cart.e = e));
  2705. if (has_blocks_queued())
  2706. buffer_sync_block();
  2707. else
  2708. stepper.set_axis_position(E_AXIS, position.e);
  2709. }
  2710. #endif
  2711. // Recalculate the steps/s^2 acceleration rates, based on the mm/s^2
  2712. void Planner::reset_acceleration_rates() {
  2713. uint32_t highest_rate = 1;
  2714. LOOP_DISTINCT_AXES(i) {
  2715. max_acceleration_steps_per_s2[i] = settings.max_acceleration_mm_per_s2[i] * settings.axis_steps_per_mm[i];
  2716. if (TERN1(DISTINCT_E_FACTORS, i < E_AXIS || i == E_AXIS_N(active_extruder)))
  2717. NOLESS(highest_rate, max_acceleration_steps_per_s2[i]);
  2718. }
  2719. acceleration_long_cutoff = 4294967295UL / highest_rate; // 0xFFFFFFFFUL
  2720. TERN_(HAS_LINEAR_E_JERK, recalculate_max_e_jerk());
  2721. }
  2722. /**
  2723. * Recalculate 'position' and 'steps_to_mm'.
  2724. * Must be called whenever settings.axis_steps_per_mm changes!
  2725. */
  2726. void Planner::refresh_positioning() {
  2727. LOOP_DISTINCT_AXES(i) steps_to_mm[i] = 1.0f / settings.axis_steps_per_mm[i];
  2728. set_position_mm(current_position);
  2729. reset_acceleration_rates();
  2730. }
  2731. // Apply limits to a variable and give a warning if the value was out of range
  2732. inline void limit_and_warn(float &val, const uint8_t axis, PGM_P const setting_name, const xyze_float_t &max_limit) {
  2733. const uint8_t lim_axis = TERN_(HAS_EXTRUDERS, axis > E_AXIS ? E_AXIS :) axis;
  2734. const float before = val;
  2735. LIMIT(val, 0.1, max_limit[lim_axis]);
  2736. if (before != val) {
  2737. SERIAL_CHAR(AXIS_CHAR(lim_axis));
  2738. SERIAL_ECHOPGM(" Max ");
  2739. SERIAL_ECHOPGM_P(setting_name);
  2740. SERIAL_ECHOLNPGM(" limited to ", val);
  2741. }
  2742. }
  2743. /**
  2744. * For the specified 'axis' set the Maximum Acceleration to the given value (mm/s^2)
  2745. * The value may be limited with warning feedback, if configured.
  2746. * Calls reset_acceleration_rates to precalculate planner terms in steps.
  2747. *
  2748. * This hard limit is applied as a block is being added to the planner queue.
  2749. */
  2750. void Planner::set_max_acceleration(const uint8_t axis, float inMaxAccelMMS2) {
  2751. #if ENABLED(LIMITED_MAX_ACCEL_EDITING)
  2752. #ifdef MAX_ACCEL_EDIT_VALUES
  2753. constexpr xyze_float_t max_accel_edit = MAX_ACCEL_EDIT_VALUES;
  2754. const xyze_float_t &max_acc_edit_scaled = max_accel_edit;
  2755. #else
  2756. constexpr xyze_float_t max_accel_edit = DEFAULT_MAX_ACCELERATION;
  2757. const xyze_float_t max_acc_edit_scaled = max_accel_edit * 2;
  2758. #endif
  2759. limit_and_warn(inMaxAccelMMS2, axis, PSTR("Acceleration"), max_acc_edit_scaled);
  2760. #endif
  2761. settings.max_acceleration_mm_per_s2[axis] = inMaxAccelMMS2;
  2762. // Update steps per s2 to agree with the units per s2 (since they are used in the planner)
  2763. reset_acceleration_rates();
  2764. }
  2765. /**
  2766. * For the specified 'axis' set the Maximum Feedrate to the given value (mm/s)
  2767. * The value may be limited with warning feedback, if configured.
  2768. *
  2769. * This hard limit is applied as a block is being added to the planner queue.
  2770. */
  2771. void Planner::set_max_feedrate(const uint8_t axis, float inMaxFeedrateMMS) {
  2772. #if ENABLED(LIMITED_MAX_FR_EDITING)
  2773. #ifdef MAX_FEEDRATE_EDIT_VALUES
  2774. constexpr xyze_float_t max_fr_edit = MAX_FEEDRATE_EDIT_VALUES;
  2775. const xyze_float_t &max_fr_edit_scaled = max_fr_edit;
  2776. #else
  2777. constexpr xyze_float_t max_fr_edit = DEFAULT_MAX_FEEDRATE;
  2778. const xyze_float_t max_fr_edit_scaled = max_fr_edit * 2;
  2779. #endif
  2780. limit_and_warn(inMaxFeedrateMMS, axis, PSTR("Feedrate"), max_fr_edit_scaled);
  2781. #endif
  2782. settings.max_feedrate_mm_s[axis] = inMaxFeedrateMMS;
  2783. }
  2784. #if HAS_CLASSIC_JERK
  2785. /**
  2786. * For the specified 'axis' set the Maximum Jerk (instant change) to the given value (mm/s)
  2787. * The value may be limited with warning feedback, if configured.
  2788. *
  2789. * This hard limit is applied (to the block start speed) as the block is being added to the planner queue.
  2790. */
  2791. void Planner::set_max_jerk(const AxisEnum axis, float inMaxJerkMMS) {
  2792. #if ENABLED(LIMITED_JERK_EDITING)
  2793. constexpr xyze_float_t max_jerk_edit =
  2794. #ifdef MAX_JERK_EDIT_VALUES
  2795. MAX_JERK_EDIT_VALUES
  2796. #else
  2797. { (DEFAULT_XJERK) * 2, (DEFAULT_YJERK) * 2,
  2798. (DEFAULT_ZJERK) * 2, (DEFAULT_EJERK) * 2 }
  2799. #endif
  2800. ;
  2801. limit_and_warn(inMaxJerkMMS, axis, PSTR("Jerk"), max_jerk_edit);
  2802. #endif
  2803. max_jerk[axis] = inMaxJerkMMS;
  2804. }
  2805. #endif
  2806. #if HAS_WIRED_LCD
  2807. uint16_t Planner::block_buffer_runtime() {
  2808. #ifdef __AVR__
  2809. // Protect the access to the variable. Only required for AVR, as
  2810. // any 32bit CPU offers atomic access to 32bit variables
  2811. const bool was_enabled = stepper.suspend();
  2812. #endif
  2813. uint32_t bbru = block_buffer_runtime_us;
  2814. #ifdef __AVR__
  2815. // Reenable Stepper ISR
  2816. if (was_enabled) stepper.wake_up();
  2817. #endif
  2818. // To translate µs to ms a division by 1000 would be required.
  2819. // We introduce 2.4% error here by dividing by 1024.
  2820. // Doesn't matter because block_buffer_runtime_us is already too small an estimation.
  2821. bbru >>= 10;
  2822. // limit to about a minute.
  2823. NOMORE(bbru, 0x0000FFFFUL);
  2824. return bbru;
  2825. }
  2826. void Planner::clear_block_buffer_runtime() {
  2827. #ifdef __AVR__
  2828. // Protect the access to the variable. Only required for AVR, as
  2829. // any 32bit CPU offers atomic access to 32bit variables
  2830. const bool was_enabled = stepper.suspend();
  2831. #endif
  2832. block_buffer_runtime_us = 0;
  2833. #ifdef __AVR__
  2834. // Reenable Stepper ISR
  2835. if (was_enabled) stepper.wake_up();
  2836. #endif
  2837. }
  2838. #endif