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.

Marlin_main.cpp 403KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/simen/grbl/tree
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G10 - Retract filament according to settings of M207
  53. * G11 - Retract recover filament according to settings of M208
  54. * G12 - Clean tool
  55. * G20 - Set input units to inches
  56. * G21 - Set input units to millimeters
  57. * G26 - Mesh Validation Pattern (Requires UBL_G26_MESH_VALIDATION)
  58. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  59. * G28 - Home one or more axes
  60. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  61. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  62. * G31 - Dock sled (Z_PROBE_SLED only)
  63. * G32 - Undock sled (Z_PROBE_SLED only)
  64. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  65. * G38 - Probe target - similar to G28 except it uses the Z_MIN_PROBE for all three axes
  66. * G42 - Coordinated move to a mesh point (Requires AUTO_BED_LEVELING_UBL)
  67. * G90 - Use Absolute Coordinates
  68. * G91 - Use Relative Coordinates
  69. * G92 - Set current position to coordinates given
  70. *
  71. * "M" Codes
  72. *
  73. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  74. * M1 - Same as M0
  75. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  76. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  77. * M5 - Turn laser/spindle off
  78. * M17 - Enable/Power all stepper motors
  79. * M18 - Disable all stepper motors; same as M84
  80. * M20 - List SD card. (Requires SDSUPPORT)
  81. * M21 - Init SD card. (Requires SDSUPPORT)
  82. * M22 - Release SD card. (Requires SDSUPPORT)
  83. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  84. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  85. * M25 - Pause SD print. (Requires SDSUPPORT)
  86. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  87. * M27 - Report SD print status. (Requires SDSUPPORT)
  88. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  89. * M29 - Stop SD write. (Requires SDSUPPORT)
  90. * M30 - Delete file from SD: "M30 /path/file.gco"
  91. * M31 - Report time since last M109 or SD card start to serial.
  92. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  93. * Use P to run other files as sub-programs: "M32 P !filename#"
  94. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  95. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  96. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  97. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  98. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  99. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  100. * M75 - Start the print job timer.
  101. * M76 - Pause the print job timer.
  102. * M77 - Stop the print job timer.
  103. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  104. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  105. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  106. * M82 - Set E codes absolute (default).
  107. * M83 - Set E codes relative while in Absolute (G90) mode.
  108. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  109. * duration after which steppers should turn off. S0 disables the timeout.
  110. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  111. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  112. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  113. * M104 - Set extruder target temp.
  114. * M105 - Report current temperatures.
  115. * M106 - Fan on.
  116. * M107 - Fan off.
  117. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  118. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  119. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  120. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  121. * M110 - Set the current line number. (Used by host printing)
  122. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  123. * M112 - Emergency stop.
  124. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  125. * M114 - Report current position.
  126. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  127. * M117 - Display a message on the controller screen. (Requires an LCD)
  128. * M119 - Report endstops status.
  129. * M120 - Enable endstops detection.
  130. * M121 - Disable endstops detection.
  131. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  132. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  133. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  134. * M128 - EtoP Open. (Requires BARICUDA)
  135. * M129 - EtoP Closed. (Requires BARICUDA)
  136. * M140 - Set bed target temp. S<temp>
  137. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  138. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  139. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM or RGB_LED)
  140. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  141. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  142. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  143. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  144. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  145. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  146. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  147. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  148. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  149. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  150. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  151. * M205 - Set advanced settings. Current units apply:
  152. S<print> T<travel> minimum speeds
  153. B<minimum segment time>
  154. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  155. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  156. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  157. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  158. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  159. Every normal extrude-only move will be classified as retract depending on the direction.
  160. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  161. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  162. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  163. * M221 - Set Flow Percentage: "M221 S<percent>"
  164. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  165. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  166. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  167. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  168. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  169. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  170. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  171. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  172. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  173. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  174. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  175. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  176. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  177. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  178. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  179. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  180. * M400 - Finish all moves.
  181. * M401 - Lower Z probe. (Requires a probe)
  182. * M402 - Raise Z probe. (Requires a probe)
  183. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  184. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  185. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  186. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  187. * M410 - Quickstop. Abort all planned moves.
  188. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  189. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING or AUTO_BED_LEVELING_UBL)
  190. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  191. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  192. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  193. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  194. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  195. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  196. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  197. * M665 - Set delta configurations: "M665 L<diagonal rod> R<delta radius> S<segments/s> A<rod A trim mm> B<rod B trim mm> C<rod C trim mm> I<tower A trim angle> J<tower B trim angle> K<tower C trim angle>" (Requires DELTA)
  198. * M666 - Set delta endstop adjustment. (Requires DELTA)
  199. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  200. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  201. * M900 - Get and/or Set advance K factor and WH/D ratio. (Requires LIN_ADVANCE)
  202. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires HAVE_TMC2130)
  203. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  204. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  205. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  206. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  207. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  208. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  209. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  210. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  211. *
  212. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  213. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  214. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  215. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  216. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  217. *
  218. * ************ Custom codes - This can change to suit future G-code regulations
  219. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  220. * M999 - Restart after being stopped by error
  221. *
  222. * "T" Codes
  223. *
  224. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  225. *
  226. */
  227. #include "Marlin.h"
  228. #include "ultralcd.h"
  229. #include "planner.h"
  230. #include "stepper.h"
  231. #include "endstops.h"
  232. #include "temperature.h"
  233. #include "cardreader.h"
  234. #include "configuration_store.h"
  235. #include "language.h"
  236. #include "pins_arduino.h"
  237. #include "math.h"
  238. #include "nozzle.h"
  239. #include "duration_t.h"
  240. #include "types.h"
  241. #include "gcode.h"
  242. #if HAS_ABL
  243. #include "vector_3.h"
  244. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  245. #include "qr_solve.h"
  246. #endif
  247. #elif ENABLED(MESH_BED_LEVELING)
  248. #include "mesh_bed_leveling.h"
  249. #endif
  250. #if ENABLED(BEZIER_CURVE_SUPPORT)
  251. #include "planner_bezier.h"
  252. #endif
  253. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  254. #include "buzzer.h"
  255. #endif
  256. #if ENABLED(USE_WATCHDOG)
  257. #include "watchdog.h"
  258. #endif
  259. #if ENABLED(BLINKM)
  260. #include "blinkm.h"
  261. #include "Wire.h"
  262. #endif
  263. #if HAS_SERVOS
  264. #include "servo.h"
  265. #endif
  266. #if HAS_DIGIPOTSS
  267. #include <SPI.h>
  268. #endif
  269. #if ENABLED(DAC_STEPPER_CURRENT)
  270. #include "stepper_dac.h"
  271. #endif
  272. #if ENABLED(EXPERIMENTAL_I2CBUS)
  273. #include "twibus.h"
  274. #endif
  275. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  276. #include "endstop_interrupts.h"
  277. #endif
  278. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  279. void gcode_M100();
  280. void M100_dump_routine(const char * const title, const char *start, const char *end);
  281. #endif
  282. #if ENABLED(SDSUPPORT)
  283. CardReader card;
  284. #endif
  285. #if ENABLED(EXPERIMENTAL_I2CBUS)
  286. TWIBus i2c;
  287. #endif
  288. #if ENABLED(G38_PROBE_TARGET)
  289. bool G38_move = false,
  290. G38_endstop_hit = false;
  291. #endif
  292. #if ENABLED(AUTO_BED_LEVELING_UBL)
  293. #include "ubl.h"
  294. unified_bed_leveling ubl;
  295. #define UBL_MESH_VALID !( ( ubl.z_values[0][0] == ubl.z_values[0][1] && ubl.z_values[0][1] == ubl.z_values[0][2] \
  296. && ubl.z_values[1][0] == ubl.z_values[1][1] && ubl.z_values[1][1] == ubl.z_values[1][2] \
  297. && ubl.z_values[2][0] == ubl.z_values[2][1] && ubl.z_values[2][1] == ubl.z_values[2][2] \
  298. && ubl.z_values[0][0] == 0 && ubl.z_values[1][0] == 0 && ubl.z_values[2][0] == 0 ) \
  299. || isnan(ubl.z_values[0][0]))
  300. #endif
  301. bool Running = true;
  302. uint8_t marlin_debug_flags = DEBUG_NONE;
  303. /**
  304. * Cartesian Current Position
  305. * Used to track the logical position as moves are queued.
  306. * Used by 'line_to_current_position' to do a move after changing it.
  307. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  308. */
  309. float current_position[XYZE] = { 0.0 };
  310. /**
  311. * Cartesian Destination
  312. * A temporary position, usually applied to 'current_position'.
  313. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  314. * 'line_to_destination' sets 'current_position' to 'destination'.
  315. */
  316. float destination[XYZE] = { 0.0 };
  317. /**
  318. * axis_homed
  319. * Flags that each linear axis was homed.
  320. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  321. *
  322. * axis_known_position
  323. * Flags that the position is known in each linear axis. Set when homed.
  324. * Cleared whenever a stepper powers off, potentially losing its position.
  325. */
  326. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  327. /**
  328. * GCode line number handling. Hosts may opt to include line numbers when
  329. * sending commands to Marlin, and lines will be checked for sequentiality.
  330. * M110 N<int> sets the current line number.
  331. */
  332. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  333. /**
  334. * GCode Command Queue
  335. * A simple ring buffer of BUFSIZE command strings.
  336. *
  337. * Commands are copied into this buffer by the command injectors
  338. * (immediate, serial, sd card) and they are processed sequentially by
  339. * the main loop. The process_next_command function parses the next
  340. * command and hands off execution to individual handler functions.
  341. */
  342. uint8_t commands_in_queue = 0; // Count of commands in the queue
  343. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  344. cmd_queue_index_w = 0; // Ring buffer write position
  345. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  346. char command_queue[BUFSIZE][MAX_CMD_SIZE]; // Necessary so M100 Free Memory Dumper can show us the commands and any corruption
  347. #else // This can be collapsed back to the way it was soon.
  348. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  349. #endif
  350. /**
  351. * Next Injected Command pointer. NULL if no commands are being injected.
  352. * Used by Marlin internally to ensure that commands initiated from within
  353. * are enqueued ahead of any pending serial or sd card commands.
  354. */
  355. static const char *injected_commands_P = NULL;
  356. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  357. TempUnit input_temp_units = TEMPUNIT_C;
  358. #endif
  359. /**
  360. * Feed rates are often configured with mm/m
  361. * but the planner and stepper like mm/s units.
  362. */
  363. float constexpr homing_feedrate_mm_s[] = {
  364. #if ENABLED(DELTA)
  365. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  366. #else
  367. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  368. #endif
  369. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  370. };
  371. float feedrate_mm_s = MMM_TO_MMS(1500.0);
  372. static float saved_feedrate_mm_s;
  373. int feedrate_percentage = 100, saved_feedrate_percentage,
  374. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  375. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  376. volumetric_enabled =
  377. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  378. true
  379. #else
  380. false
  381. #endif
  382. ;
  383. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  384. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  385. #if HAS_WORKSPACE_OFFSET
  386. #if HAS_POSITION_SHIFT
  387. // The distance that XYZ has been offset by G92. Reset by G28.
  388. float position_shift[XYZ] = { 0 };
  389. #endif
  390. #if HAS_HOME_OFFSET
  391. // This offset is added to the configured home position.
  392. // Set by M206, M428, or menu item. Saved to EEPROM.
  393. float home_offset[XYZ] = { 0 };
  394. #endif
  395. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  396. // The above two are combined to save on computes
  397. float workspace_offset[XYZ] = { 0 };
  398. #endif
  399. #endif
  400. // Software Endstops are based on the configured limits.
  401. #if HAS_SOFTWARE_ENDSTOPS
  402. bool soft_endstops_enabled = true;
  403. #endif
  404. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  405. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  406. #if FAN_COUNT > 0
  407. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  408. #if ENABLED(PROBING_FANS_OFF)
  409. bool fans_paused = false;
  410. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  411. #endif
  412. #endif
  413. // The active extruder (tool). Set with T<extruder> command.
  414. uint8_t active_extruder = 0;
  415. // Relative Mode. Enable with G91, disable with G90.
  416. static bool relative_mode = false;
  417. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  418. volatile bool wait_for_heatup = true;
  419. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  420. #if HAS_RESUME_CONTINUE
  421. volatile bool wait_for_user = false;
  422. #endif
  423. const char axis_codes[XYZE] = {'X', 'Y', 'Z', 'E'};
  424. // Number of characters read in the current line of serial input
  425. static int serial_count = 0;
  426. // Inactivity shutdown
  427. millis_t previous_cmd_ms = 0;
  428. static millis_t max_inactive_time = 0;
  429. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  430. // Print Job Timer
  431. #if ENABLED(PRINTCOUNTER)
  432. PrintCounter print_job_timer = PrintCounter();
  433. #else
  434. Stopwatch print_job_timer = Stopwatch();
  435. #endif
  436. // Buzzer - I2C on the LCD or a BEEPER_PIN
  437. #if ENABLED(LCD_USE_I2C_BUZZER)
  438. #define BUZZ(d,f) lcd_buzz(d, f)
  439. #elif PIN_EXISTS(BEEPER)
  440. Buzzer buzzer;
  441. #define BUZZ(d,f) buzzer.tone(d, f)
  442. #else
  443. #define BUZZ(d,f) NOOP
  444. #endif
  445. static uint8_t target_extruder;
  446. #if HAS_BED_PROBE
  447. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  448. #endif
  449. #if HAS_ABL
  450. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  451. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  452. #elif defined(XY_PROBE_SPEED)
  453. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  454. #else
  455. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  456. #endif
  457. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  458. #if ENABLED(DELTA)
  459. #define ADJUST_DELTA(V) \
  460. if (planner.abl_enabled) { \
  461. const float zadj = bilinear_z_offset(V); \
  462. delta[A_AXIS] += zadj; \
  463. delta[B_AXIS] += zadj; \
  464. delta[C_AXIS] += zadj; \
  465. }
  466. #else
  467. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  468. #endif
  469. #elif IS_KINEMATIC
  470. #define ADJUST_DELTA(V) NOOP
  471. #endif
  472. #if ENABLED(Z_DUAL_ENDSTOPS)
  473. float z_endstop_adj =
  474. #ifdef Z_DUAL_ENDSTOPS_ADJUSTMENT
  475. Z_DUAL_ENDSTOPS_ADJUSTMENT
  476. #else
  477. 0
  478. #endif
  479. ;
  480. #endif
  481. // Extruder offsets
  482. #if HOTENDS > 1
  483. float hotend_offset[XYZ][HOTENDS];
  484. #endif
  485. #if HAS_Z_SERVO_ENDSTOP
  486. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  487. #endif
  488. #if ENABLED(BARICUDA)
  489. int baricuda_valve_pressure = 0;
  490. int baricuda_e_to_p_pressure = 0;
  491. #endif
  492. #if ENABLED(FWRETRACT)
  493. bool autoretract_enabled = false;
  494. bool retracted[EXTRUDERS] = { false };
  495. bool retracted_swap[EXTRUDERS] = { false };
  496. float retract_length = RETRACT_LENGTH;
  497. float retract_length_swap = RETRACT_LENGTH_SWAP;
  498. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  499. float retract_zlift = RETRACT_ZLIFT;
  500. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  501. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  502. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  503. #endif // FWRETRACT
  504. #if HAS_POWER_SWITCH
  505. bool powersupply_on =
  506. #if ENABLED(PS_DEFAULT_OFF)
  507. false
  508. #else
  509. true
  510. #endif
  511. ;
  512. #endif
  513. #if ENABLED(DELTA)
  514. float delta[ABC],
  515. endstop_adj[ABC] = { 0 };
  516. // These values are loaded or reset at boot time when setup() calls
  517. // settings.load(), which calls recalc_delta_settings().
  518. float delta_radius,
  519. delta_tower_angle_trim[2],
  520. delta_tower[ABC][2],
  521. delta_diagonal_rod,
  522. delta_calibration_radius,
  523. delta_diagonal_rod_2_tower[ABC],
  524. delta_segments_per_second,
  525. delta_clip_start_height = Z_MAX_POS;
  526. float delta_safe_distance_from_top();
  527. #endif
  528. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  529. int bilinear_grid_spacing[2], bilinear_start[2];
  530. float bilinear_grid_factor[2],
  531. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  532. #endif
  533. #if IS_SCARA
  534. // Float constants for SCARA calculations
  535. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  536. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  537. L2_2 = sq(float(L2));
  538. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  539. delta[ABC];
  540. #endif
  541. float cartes[XYZ] = { 0 };
  542. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  543. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  544. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  545. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  546. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  547. int filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  548. int meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  549. #endif
  550. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  551. static bool filament_ran_out = false;
  552. #endif
  553. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  554. AdvancedPauseMenuResponse advanced_pause_menu_response;
  555. #endif
  556. #if ENABLED(MIXING_EXTRUDER)
  557. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  558. #if MIXING_VIRTUAL_TOOLS > 1
  559. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  560. #endif
  561. #endif
  562. static bool send_ok[BUFSIZE];
  563. #if HAS_SERVOS
  564. Servo servo[NUM_SERVOS];
  565. #define MOVE_SERVO(I, P) servo[I].move(P)
  566. #if HAS_Z_SERVO_ENDSTOP
  567. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  568. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  569. #endif
  570. #endif
  571. #ifdef CHDK
  572. millis_t chdkHigh = 0;
  573. bool chdkActive = false;
  574. #endif
  575. #ifdef AUTOMATIC_CURRENT_CONTROL
  576. bool auto_current_control = 0;
  577. #endif
  578. #if ENABLED(PID_EXTRUSION_SCALING)
  579. int lpq_len = 20;
  580. #endif
  581. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  582. MarlinBusyState busy_state = NOT_BUSY;
  583. static millis_t next_busy_signal_ms = 0;
  584. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  585. #else
  586. #define host_keepalive() NOOP
  587. #endif
  588. static inline float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  589. static inline signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  590. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  591. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  592. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  593. typedef void __void_##CONFIG##__
  594. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  595. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  596. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  597. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  598. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  599. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  600. /**
  601. * ***************************************************************************
  602. * ******************************** FUNCTIONS ********************************
  603. * ***************************************************************************
  604. */
  605. void stop();
  606. void get_available_commands();
  607. void process_next_command();
  608. void prepare_move_to_destination();
  609. void get_cartesian_from_steppers();
  610. void set_current_from_steppers_for_axis(const AxisEnum axis);
  611. #if ENABLED(ARC_SUPPORT)
  612. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  613. #endif
  614. #if ENABLED(BEZIER_CURVE_SUPPORT)
  615. void plan_cubic_move(const float offset[4]);
  616. #endif
  617. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  618. static void report_current_position();
  619. #if ENABLED(DEBUG_LEVELING_FEATURE)
  620. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  621. serialprintPGM(prefix);
  622. SERIAL_CHAR('(');
  623. SERIAL_ECHO(x);
  624. SERIAL_ECHOPAIR(", ", y);
  625. SERIAL_ECHOPAIR(", ", z);
  626. SERIAL_CHAR(')');
  627. if (suffix) {serialprintPGM(suffix);} //won't compile for Teensy with the previous construction
  628. else SERIAL_EOL;
  629. }
  630. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  631. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  632. }
  633. #if HAS_ABL
  634. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  635. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  636. }
  637. #endif
  638. #define DEBUG_POS(SUFFIX,VAR) do { \
  639. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  640. #endif
  641. /**
  642. * sync_plan_position
  643. *
  644. * Set the planner/stepper positions directly from current_position with
  645. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  646. */
  647. inline void sync_plan_position() {
  648. #if ENABLED(DEBUG_LEVELING_FEATURE)
  649. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  650. #endif
  651. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  652. }
  653. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  654. #if IS_KINEMATIC
  655. inline void sync_plan_position_kinematic() {
  656. #if ENABLED(DEBUG_LEVELING_FEATURE)
  657. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  658. #endif
  659. planner.set_position_mm_kinematic(current_position);
  660. }
  661. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  662. #else
  663. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  664. #endif
  665. #if ENABLED(SDSUPPORT)
  666. #include "SdFatUtil.h"
  667. int freeMemory() { return SdFatUtil::FreeRam(); }
  668. #else
  669. extern "C" {
  670. extern char __bss_end;
  671. extern char __heap_start;
  672. extern void* __brkval;
  673. int freeMemory() {
  674. int free_memory;
  675. if ((int)__brkval == 0)
  676. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  677. else
  678. free_memory = ((int)&free_memory) - ((int)__brkval);
  679. return free_memory;
  680. }
  681. }
  682. #endif // !SDSUPPORT
  683. #if ENABLED(DIGIPOT_I2C)
  684. extern void digipot_i2c_set_current(int channel, float current);
  685. extern void digipot_i2c_init();
  686. #endif
  687. /**
  688. * Inject the next "immediate" command, when possible, onto the front of the queue.
  689. * Return true if any immediate commands remain to inject.
  690. */
  691. static bool drain_injected_commands_P() {
  692. if (injected_commands_P != NULL) {
  693. size_t i = 0;
  694. char c, cmd[30];
  695. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  696. cmd[sizeof(cmd) - 1] = '\0';
  697. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  698. cmd[i] = '\0';
  699. if (enqueue_and_echo_command(cmd)) // success?
  700. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  701. }
  702. return (injected_commands_P != NULL); // return whether any more remain
  703. }
  704. /**
  705. * Record one or many commands to run from program memory.
  706. * Aborts the current queue, if any.
  707. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  708. */
  709. void enqueue_and_echo_commands_P(const char * const pgcode) {
  710. injected_commands_P = pgcode;
  711. drain_injected_commands_P(); // first command executed asap (when possible)
  712. }
  713. /**
  714. * Clear the Marlin command queue
  715. */
  716. void clear_command_queue() {
  717. cmd_queue_index_r = cmd_queue_index_w;
  718. commands_in_queue = 0;
  719. }
  720. /**
  721. * Once a new command is in the ring buffer, call this to commit it
  722. */
  723. inline void _commit_command(bool say_ok) {
  724. send_ok[cmd_queue_index_w] = say_ok;
  725. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  726. commands_in_queue++;
  727. }
  728. /**
  729. * Copy a command from RAM into the main command buffer.
  730. * Return true if the command was successfully added.
  731. * Return false for a full buffer, or if the 'command' is a comment.
  732. */
  733. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  734. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  735. strcpy(command_queue[cmd_queue_index_w], cmd);
  736. _commit_command(say_ok);
  737. return true;
  738. }
  739. /**
  740. * Enqueue with Serial Echo
  741. */
  742. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  743. if (_enqueuecommand(cmd, say_ok)) {
  744. SERIAL_ECHO_START;
  745. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  746. SERIAL_CHAR('"');
  747. SERIAL_EOL;
  748. return true;
  749. }
  750. return false;
  751. }
  752. void setup_killpin() {
  753. #if HAS_KILL
  754. SET_INPUT_PULLUP(KILL_PIN);
  755. #endif
  756. }
  757. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  758. void setup_filrunoutpin() {
  759. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  760. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  761. #else
  762. SET_INPUT(FIL_RUNOUT_PIN);
  763. #endif
  764. }
  765. #endif
  766. void setup_homepin(void) {
  767. #if HAS_HOME
  768. SET_INPUT_PULLUP(HOME_PIN);
  769. #endif
  770. }
  771. void setup_powerhold() {
  772. #if HAS_SUICIDE
  773. OUT_WRITE(SUICIDE_PIN, HIGH);
  774. #endif
  775. #if HAS_POWER_SWITCH
  776. #if ENABLED(PS_DEFAULT_OFF)
  777. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  778. #else
  779. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  780. #endif
  781. #endif
  782. }
  783. void suicide() {
  784. #if HAS_SUICIDE
  785. OUT_WRITE(SUICIDE_PIN, LOW);
  786. #endif
  787. }
  788. void servo_init() {
  789. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  790. servo[0].attach(SERVO0_PIN);
  791. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  792. #endif
  793. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  794. servo[1].attach(SERVO1_PIN);
  795. servo[1].detach();
  796. #endif
  797. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  798. servo[2].attach(SERVO2_PIN);
  799. servo[2].detach();
  800. #endif
  801. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  802. servo[3].attach(SERVO3_PIN);
  803. servo[3].detach();
  804. #endif
  805. #if HAS_Z_SERVO_ENDSTOP
  806. /**
  807. * Set position of Z Servo Endstop
  808. *
  809. * The servo might be deployed and positioned too low to stow
  810. * when starting up the machine or rebooting the board.
  811. * There's no way to know where the nozzle is positioned until
  812. * homing has been done - no homing with z-probe without init!
  813. *
  814. */
  815. STOW_Z_SERVO();
  816. #endif
  817. }
  818. /**
  819. * Stepper Reset (RigidBoard, et.al.)
  820. */
  821. #if HAS_STEPPER_RESET
  822. void disableStepperDrivers() {
  823. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  824. }
  825. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  826. #endif
  827. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  828. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  829. i2c.receive(bytes);
  830. }
  831. void i2c_on_request() { // just send dummy data for now
  832. i2c.reply("Hello World!\n");
  833. }
  834. #endif
  835. #if HAS_COLOR_LEDS
  836. void set_led_color(
  837. const uint8_t r, const uint8_t g, const uint8_t b
  838. #if ENABLED(RGBW_LED)
  839. , const uint8_t w=0
  840. #endif
  841. ) {
  842. #if ENABLED(BLINKM)
  843. // This variant uses i2c to send the RGB components to the device.
  844. SendColors(r, g, b);
  845. #else
  846. // This variant uses 3 separate pins for the RGB components.
  847. // If the pins can do PWM then their intensity will be set.
  848. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  849. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  850. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  851. analogWrite(RGB_LED_R_PIN, r);
  852. analogWrite(RGB_LED_G_PIN, g);
  853. analogWrite(RGB_LED_B_PIN, b);
  854. #if ENABLED(RGBW_LED)
  855. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  856. analogWrite(RGB_LED_W_PIN, w);
  857. #endif
  858. #endif
  859. }
  860. #endif // HAS_COLOR_LEDS
  861. void gcode_line_error(const char* err, bool doFlush = true) {
  862. SERIAL_ERROR_START;
  863. serialprintPGM(err);
  864. SERIAL_ERRORLN(gcode_LastN);
  865. //Serial.println(gcode_N);
  866. if (doFlush) FlushSerialRequestResend();
  867. serial_count = 0;
  868. }
  869. /**
  870. * Get all commands waiting on the serial port and queue them.
  871. * Exit when the buffer is full or when no more characters are
  872. * left on the serial port.
  873. */
  874. inline void get_serial_commands() {
  875. static char serial_line_buffer[MAX_CMD_SIZE];
  876. static bool serial_comment_mode = false;
  877. // If the command buffer is empty for too long,
  878. // send "wait" to indicate Marlin is still waiting.
  879. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  880. static millis_t last_command_time = 0;
  881. const millis_t ms = millis();
  882. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  883. SERIAL_ECHOLNPGM(MSG_WAIT);
  884. last_command_time = ms;
  885. }
  886. #endif
  887. /**
  888. * Loop while serial characters are incoming and the queue is not full
  889. */
  890. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  891. char serial_char = MYSERIAL.read();
  892. /**
  893. * If the character ends the line
  894. */
  895. if (serial_char == '\n' || serial_char == '\r') {
  896. serial_comment_mode = false; // end of line == end of comment
  897. if (!serial_count) continue; // skip empty lines
  898. serial_line_buffer[serial_count] = 0; // terminate string
  899. serial_count = 0; //reset buffer
  900. char* command = serial_line_buffer;
  901. while (*command == ' ') command++; // skip any leading spaces
  902. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  903. *apos = strchr(command, '*');
  904. if (npos) {
  905. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  906. if (M110) {
  907. char* n2pos = strchr(command + 4, 'N');
  908. if (n2pos) npos = n2pos;
  909. }
  910. gcode_N = strtol(npos + 1, NULL, 10);
  911. if (gcode_N != gcode_LastN + 1 && !M110) {
  912. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  913. return;
  914. }
  915. if (apos) {
  916. byte checksum = 0, count = 0;
  917. while (command[count] != '*') checksum ^= command[count++];
  918. if (strtol(apos + 1, NULL, 10) != checksum) {
  919. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  920. return;
  921. }
  922. // if no errors, continue parsing
  923. }
  924. else {
  925. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  926. return;
  927. }
  928. gcode_LastN = gcode_N;
  929. // if no errors, continue parsing
  930. }
  931. else if (apos) { // No '*' without 'N'
  932. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  933. return;
  934. }
  935. // Movement commands alert when stopped
  936. if (IsStopped()) {
  937. char* gpos = strchr(command, 'G');
  938. if (gpos) {
  939. const int codenum = strtol(gpos + 1, NULL, 10);
  940. switch (codenum) {
  941. case 0:
  942. case 1:
  943. case 2:
  944. case 3:
  945. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  946. LCD_MESSAGEPGM(MSG_STOPPED);
  947. break;
  948. }
  949. }
  950. }
  951. #if DISABLED(EMERGENCY_PARSER)
  952. // If command was e-stop process now
  953. if (strcmp(command, "M108") == 0) {
  954. wait_for_heatup = false;
  955. #if ENABLED(ULTIPANEL)
  956. wait_for_user = false;
  957. #endif
  958. }
  959. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  960. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  961. #endif
  962. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  963. last_command_time = ms;
  964. #endif
  965. // Add the command to the queue
  966. _enqueuecommand(serial_line_buffer, true);
  967. }
  968. else if (serial_count >= MAX_CMD_SIZE - 1) {
  969. // Keep fetching, but ignore normal characters beyond the max length
  970. // The command will be injected when EOL is reached
  971. }
  972. else if (serial_char == '\\') { // Handle escapes
  973. if (MYSERIAL.available() > 0) {
  974. // if we have one more character, copy it over
  975. serial_char = MYSERIAL.read();
  976. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  977. }
  978. // otherwise do nothing
  979. }
  980. else { // it's not a newline, carriage return or escape char
  981. if (serial_char == ';') serial_comment_mode = true;
  982. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  983. }
  984. } // queue has space, serial has data
  985. }
  986. #if ENABLED(SDSUPPORT)
  987. /**
  988. * Get commands from the SD Card until the command buffer is full
  989. * or until the end of the file is reached. The special character '#'
  990. * can also interrupt buffering.
  991. */
  992. inline void get_sdcard_commands() {
  993. static bool stop_buffering = false,
  994. sd_comment_mode = false;
  995. if (!card.sdprinting) return;
  996. /**
  997. * '#' stops reading from SD to the buffer prematurely, so procedural
  998. * macro calls are possible. If it occurs, stop_buffering is triggered
  999. * and the buffer is run dry; this character _can_ occur in serial com
  1000. * due to checksums, however, no checksums are used in SD printing.
  1001. */
  1002. if (commands_in_queue == 0) stop_buffering = false;
  1003. uint16_t sd_count = 0;
  1004. bool card_eof = card.eof();
  1005. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1006. const int16_t n = card.get();
  1007. char sd_char = (char)n;
  1008. card_eof = card.eof();
  1009. if (card_eof || n == -1
  1010. || sd_char == '\n' || sd_char == '\r'
  1011. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1012. ) {
  1013. if (card_eof) {
  1014. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1015. card.printingHasFinished();
  1016. #if ENABLED(PRINTER_EVENT_LEDS)
  1017. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1018. set_led_color(0, 255, 0); // Green
  1019. #if HAS_RESUME_CONTINUE
  1020. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1021. #else
  1022. safe_delay(1000);
  1023. #endif
  1024. set_led_color(0, 0, 0); // OFF
  1025. #endif
  1026. card.checkautostart(true);
  1027. }
  1028. else if (n == -1) {
  1029. SERIAL_ERROR_START;
  1030. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1031. }
  1032. if (sd_char == '#') stop_buffering = true;
  1033. sd_comment_mode = false; // for new command
  1034. if (!sd_count) continue; // skip empty lines (and comment lines)
  1035. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1036. sd_count = 0; // clear sd line buffer
  1037. _commit_command(false);
  1038. }
  1039. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1040. /**
  1041. * Keep fetching, but ignore normal characters beyond the max length
  1042. * The command will be injected when EOL is reached
  1043. */
  1044. }
  1045. else {
  1046. if (sd_char == ';') sd_comment_mode = true;
  1047. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1048. }
  1049. }
  1050. }
  1051. #endif // SDSUPPORT
  1052. /**
  1053. * Add to the circular command queue the next command from:
  1054. * - The command-injection queue (injected_commands_P)
  1055. * - The active serial input (usually USB)
  1056. * - The SD card file being actively printed
  1057. */
  1058. void get_available_commands() {
  1059. // if any immediate commands remain, don't get other commands yet
  1060. if (drain_injected_commands_P()) return;
  1061. get_serial_commands();
  1062. #if ENABLED(SDSUPPORT)
  1063. get_sdcard_commands();
  1064. #endif
  1065. }
  1066. /**
  1067. * Set target_extruder from the T parameter or the active_extruder
  1068. *
  1069. * Returns TRUE if the target is invalid
  1070. */
  1071. bool get_target_extruder_from_command(int code) {
  1072. if (parser.seen('T')) {
  1073. if (parser.value_byte() >= EXTRUDERS) {
  1074. SERIAL_ECHO_START;
  1075. SERIAL_CHAR('M');
  1076. SERIAL_ECHO(code);
  1077. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", parser.value_byte());
  1078. return true;
  1079. }
  1080. target_extruder = parser.value_byte();
  1081. }
  1082. else
  1083. target_extruder = active_extruder;
  1084. return false;
  1085. }
  1086. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1087. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1088. #endif
  1089. #if ENABLED(DUAL_X_CARRIAGE)
  1090. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1091. static float x_home_pos(const int extruder) {
  1092. if (extruder == 0)
  1093. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1094. else
  1095. /**
  1096. * In dual carriage mode the extruder offset provides an override of the
  1097. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1098. * This allows soft recalibration of the second extruder home position
  1099. * without firmware reflash (through the M218 command).
  1100. */
  1101. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1102. }
  1103. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1104. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1105. static bool active_extruder_parked = false; // used in mode 1 & 2
  1106. static float raised_parked_position[XYZE]; // used in mode 1
  1107. static millis_t delayed_move_time = 0; // used in mode 1
  1108. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1109. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1110. #endif // DUAL_X_CARRIAGE
  1111. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1112. /**
  1113. * Software endstops can be used to monitor the open end of
  1114. * an axis that has a hardware endstop on the other end. Or
  1115. * they can prevent axes from moving past endstops and grinding.
  1116. *
  1117. * To keep doing their job as the coordinate system changes,
  1118. * the software endstop positions must be refreshed to remain
  1119. * at the same positions relative to the machine.
  1120. */
  1121. void update_software_endstops(const AxisEnum axis) {
  1122. const float offs = 0.0
  1123. #if HAS_HOME_OFFSET
  1124. + home_offset[axis]
  1125. #endif
  1126. #if HAS_POSITION_SHIFT
  1127. + position_shift[axis]
  1128. #endif
  1129. ;
  1130. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1131. workspace_offset[axis] = offs;
  1132. #endif
  1133. #if ENABLED(DUAL_X_CARRIAGE)
  1134. if (axis == X_AXIS) {
  1135. // In Dual X mode hotend_offset[X] is T1's home position
  1136. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1137. if (active_extruder != 0) {
  1138. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1139. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1140. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1141. }
  1142. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1143. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1144. // but not so far to the right that T1 would move past the end
  1145. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1146. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1147. }
  1148. else {
  1149. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1150. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1151. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1152. }
  1153. }
  1154. #else
  1155. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1156. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1157. #endif
  1158. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1159. if (DEBUGGING(LEVELING)) {
  1160. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1161. #if HAS_HOME_OFFSET
  1162. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1163. #endif
  1164. #if HAS_POSITION_SHIFT
  1165. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1166. #endif
  1167. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1168. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1169. }
  1170. #endif
  1171. #if ENABLED(DELTA)
  1172. if (axis == Z_AXIS)
  1173. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1174. #endif
  1175. }
  1176. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1177. #if HAS_M206_COMMAND
  1178. /**
  1179. * Change the home offset for an axis, update the current
  1180. * position and the software endstops to retain the same
  1181. * relative distance to the new home.
  1182. *
  1183. * Since this changes the current_position, code should
  1184. * call sync_plan_position soon after this.
  1185. */
  1186. static void set_home_offset(const AxisEnum axis, const float v) {
  1187. current_position[axis] += v - home_offset[axis];
  1188. home_offset[axis] = v;
  1189. update_software_endstops(axis);
  1190. }
  1191. #endif // HAS_M206_COMMAND
  1192. /**
  1193. * Set an axis' current position to its home position (after homing).
  1194. *
  1195. * For Core and Cartesian robots this applies one-to-one when an
  1196. * individual axis has been homed.
  1197. *
  1198. * DELTA should wait until all homing is done before setting the XYZ
  1199. * current_position to home, because homing is a single operation.
  1200. * In the case where the axis positions are already known and previously
  1201. * homed, DELTA could home to X or Y individually by moving either one
  1202. * to the center. However, homing Z always homes XY and Z.
  1203. *
  1204. * SCARA should wait until all XY homing is done before setting the XY
  1205. * current_position to home, because neither X nor Y is at home until
  1206. * both are at home. Z can however be homed individually.
  1207. *
  1208. * Callers must sync the planner position after calling this!
  1209. */
  1210. static void set_axis_is_at_home(AxisEnum axis) {
  1211. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1212. if (DEBUGGING(LEVELING)) {
  1213. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1214. SERIAL_CHAR(')');
  1215. SERIAL_EOL;
  1216. }
  1217. #endif
  1218. axis_known_position[axis] = axis_homed[axis] = true;
  1219. #if HAS_POSITION_SHIFT
  1220. position_shift[axis] = 0;
  1221. update_software_endstops(axis);
  1222. #endif
  1223. #if ENABLED(DUAL_X_CARRIAGE)
  1224. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1225. current_position[X_AXIS] = x_home_pos(active_extruder);
  1226. return;
  1227. }
  1228. #endif
  1229. #if ENABLED(MORGAN_SCARA)
  1230. /**
  1231. * Morgan SCARA homes XY at the same time
  1232. */
  1233. if (axis == X_AXIS || axis == Y_AXIS) {
  1234. float homeposition[XYZ];
  1235. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1236. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1237. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1238. /**
  1239. * Get Home position SCARA arm angles using inverse kinematics,
  1240. * and calculate homing offset using forward kinematics
  1241. */
  1242. inverse_kinematics(homeposition);
  1243. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1244. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1245. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1246. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1247. /**
  1248. * SCARA home positions are based on configuration since the actual
  1249. * limits are determined by the inverse kinematic transform.
  1250. */
  1251. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1252. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1253. }
  1254. else
  1255. #endif
  1256. {
  1257. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1258. }
  1259. /**
  1260. * Z Probe Z Homing? Account for the probe's Z offset.
  1261. */
  1262. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1263. if (axis == Z_AXIS) {
  1264. #if HOMING_Z_WITH_PROBE
  1265. current_position[Z_AXIS] -= zprobe_zoffset;
  1266. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1267. if (DEBUGGING(LEVELING)) {
  1268. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1269. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1270. }
  1271. #endif
  1272. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1273. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1274. #endif
  1275. }
  1276. #endif
  1277. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1278. if (DEBUGGING(LEVELING)) {
  1279. #if HAS_HOME_OFFSET
  1280. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1281. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1282. #endif
  1283. DEBUG_POS("", current_position);
  1284. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1285. SERIAL_CHAR(')');
  1286. SERIAL_EOL;
  1287. }
  1288. #endif
  1289. }
  1290. /**
  1291. * Some planner shorthand inline functions
  1292. */
  1293. inline float get_homing_bump_feedrate(AxisEnum axis) {
  1294. int constexpr homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1295. int hbd = homing_bump_divisor[axis];
  1296. if (hbd < 1) {
  1297. hbd = 10;
  1298. SERIAL_ECHO_START;
  1299. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1300. }
  1301. return homing_feedrate_mm_s[axis] / hbd;
  1302. }
  1303. //
  1304. // line_to_current_position
  1305. // Move the planner to the current position from wherever it last moved
  1306. // (or from wherever it has been told it is located).
  1307. //
  1308. inline void line_to_current_position() {
  1309. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1310. }
  1311. //
  1312. // line_to_destination
  1313. // Move the planner, not necessarily synced with current_position
  1314. //
  1315. inline void line_to_destination(float fr_mm_s) {
  1316. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1317. }
  1318. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1319. inline void set_current_to_destination() { COPY(current_position, destination); }
  1320. inline void set_destination_to_current() { COPY(destination, current_position); }
  1321. #if IS_KINEMATIC
  1322. /**
  1323. * Calculate delta, start a line, and set current_position to destination
  1324. */
  1325. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1326. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1327. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1328. #endif
  1329. if ( current_position[X_AXIS] == destination[X_AXIS]
  1330. && current_position[Y_AXIS] == destination[Y_AXIS]
  1331. && current_position[Z_AXIS] == destination[Z_AXIS]
  1332. && current_position[E_AXIS] == destination[E_AXIS]
  1333. ) return;
  1334. refresh_cmd_timeout();
  1335. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1336. set_current_to_destination();
  1337. }
  1338. #endif // IS_KINEMATIC
  1339. /**
  1340. * Plan a move to (X, Y, Z) and set the current_position
  1341. * The final current_position may not be the one that was requested
  1342. */
  1343. void do_blocking_move_to(const float &x, const float &y, const float &z, const float &fr_mm_s /*=0.0*/) {
  1344. const float old_feedrate_mm_s = feedrate_mm_s;
  1345. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1346. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, x, y, z);
  1347. #endif
  1348. #if ENABLED(DELTA)
  1349. if (!position_is_reachable_xy(x, y)) return;
  1350. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1351. set_destination_to_current(); // sync destination at the start
  1352. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1353. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1354. #endif
  1355. // when in the danger zone
  1356. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1357. if (z > delta_clip_start_height) { // staying in the danger zone
  1358. destination[X_AXIS] = x; // move directly (uninterpolated)
  1359. destination[Y_AXIS] = y;
  1360. destination[Z_AXIS] = z;
  1361. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1362. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1363. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1364. #endif
  1365. return;
  1366. }
  1367. else {
  1368. destination[Z_AXIS] = delta_clip_start_height;
  1369. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1370. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1371. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1372. #endif
  1373. }
  1374. }
  1375. if (z > current_position[Z_AXIS]) { // raising?
  1376. destination[Z_AXIS] = z;
  1377. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1378. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1379. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1380. #endif
  1381. }
  1382. destination[X_AXIS] = x;
  1383. destination[Y_AXIS] = y;
  1384. prepare_move_to_destination(); // set_current_to_destination
  1385. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1386. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1387. #endif
  1388. if (z < current_position[Z_AXIS]) { // lowering?
  1389. destination[Z_AXIS] = z;
  1390. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1391. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1392. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1393. #endif
  1394. }
  1395. #elif IS_SCARA
  1396. if (!position_is_reachable_xy(x, y)) return;
  1397. set_destination_to_current();
  1398. // If Z needs to raise, do it before moving XY
  1399. if (destination[Z_AXIS] < z) {
  1400. destination[Z_AXIS] = z;
  1401. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1402. }
  1403. destination[X_AXIS] = x;
  1404. destination[Y_AXIS] = y;
  1405. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1406. // If Z needs to lower, do it after moving XY
  1407. if (destination[Z_AXIS] > z) {
  1408. destination[Z_AXIS] = z;
  1409. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1410. }
  1411. #else
  1412. // If Z needs to raise, do it before moving XY
  1413. if (current_position[Z_AXIS] < z) {
  1414. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1415. current_position[Z_AXIS] = z;
  1416. line_to_current_position();
  1417. }
  1418. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1419. current_position[X_AXIS] = x;
  1420. current_position[Y_AXIS] = y;
  1421. line_to_current_position();
  1422. // If Z needs to lower, do it after moving XY
  1423. if (current_position[Z_AXIS] > z) {
  1424. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1425. current_position[Z_AXIS] = z;
  1426. line_to_current_position();
  1427. }
  1428. #endif
  1429. stepper.synchronize();
  1430. feedrate_mm_s = old_feedrate_mm_s;
  1431. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1432. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1433. #endif
  1434. }
  1435. void do_blocking_move_to_x(const float &x, const float &fr_mm_s/*=0.0*/) {
  1436. do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1437. }
  1438. void do_blocking_move_to_z(const float &z, const float &fr_mm_s/*=0.0*/) {
  1439. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, fr_mm_s);
  1440. }
  1441. void do_blocking_move_to_xy(const float &x, const float &y, const float &fr_mm_s/*=0.0*/) {
  1442. do_blocking_move_to(x, y, current_position[Z_AXIS], fr_mm_s);
  1443. }
  1444. //
  1445. // Prepare to do endstop or probe moves
  1446. // with custom feedrates.
  1447. //
  1448. // - Save current feedrates
  1449. // - Reset the rate multiplier
  1450. // - Reset the command timeout
  1451. // - Enable the endstops (for endstop moves)
  1452. //
  1453. static void setup_for_endstop_or_probe_move() {
  1454. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1455. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1456. #endif
  1457. saved_feedrate_mm_s = feedrate_mm_s;
  1458. saved_feedrate_percentage = feedrate_percentage;
  1459. feedrate_percentage = 100;
  1460. refresh_cmd_timeout();
  1461. }
  1462. static void clean_up_after_endstop_or_probe_move() {
  1463. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1464. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1465. #endif
  1466. feedrate_mm_s = saved_feedrate_mm_s;
  1467. feedrate_percentage = saved_feedrate_percentage;
  1468. refresh_cmd_timeout();
  1469. }
  1470. #if HAS_BED_PROBE
  1471. /**
  1472. * Raise Z to a minimum height to make room for a probe to move
  1473. */
  1474. inline void do_probe_raise(float z_raise) {
  1475. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1476. if (DEBUGGING(LEVELING)) {
  1477. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1478. SERIAL_CHAR(')');
  1479. SERIAL_EOL;
  1480. }
  1481. #endif
  1482. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1483. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1484. #if ENABLED(DELTA)
  1485. z_dest -= home_offset[Z_AXIS];
  1486. #endif
  1487. if (z_dest > current_position[Z_AXIS])
  1488. do_blocking_move_to_z(z_dest);
  1489. }
  1490. #endif // HAS_BED_PROBE
  1491. #if HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE) || ENABLED(DELTA_AUTO_CALIBRATION)
  1492. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1493. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1494. const bool xx = x && !axis_known_position[X_AXIS],
  1495. yy = y && !axis_known_position[Y_AXIS],
  1496. zz = z && !axis_known_position[Z_AXIS];
  1497. #else
  1498. const bool xx = x && !axis_homed[X_AXIS],
  1499. yy = y && !axis_homed[Y_AXIS],
  1500. zz = z && !axis_homed[Z_AXIS];
  1501. #endif
  1502. if (xx || yy || zz) {
  1503. SERIAL_ECHO_START;
  1504. SERIAL_ECHOPGM(MSG_HOME " ");
  1505. if (xx) SERIAL_ECHOPGM(MSG_X);
  1506. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1507. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1508. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1509. #if ENABLED(ULTRA_LCD)
  1510. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1511. #endif
  1512. return true;
  1513. }
  1514. return false;
  1515. }
  1516. #endif
  1517. #if ENABLED(Z_PROBE_SLED)
  1518. #ifndef SLED_DOCKING_OFFSET
  1519. #define SLED_DOCKING_OFFSET 0
  1520. #endif
  1521. /**
  1522. * Method to dock/undock a sled designed by Charles Bell.
  1523. *
  1524. * stow[in] If false, move to MAX_X and engage the solenoid
  1525. * If true, move to MAX_X and release the solenoid
  1526. */
  1527. static void dock_sled(bool stow) {
  1528. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1529. if (DEBUGGING(LEVELING)) {
  1530. SERIAL_ECHOPAIR("dock_sled(", stow);
  1531. SERIAL_CHAR(')');
  1532. SERIAL_EOL;
  1533. }
  1534. #endif
  1535. // Dock sled a bit closer to ensure proper capturing
  1536. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1537. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1538. WRITE(SOL1_PIN, !stow); // switch solenoid
  1539. #endif
  1540. }
  1541. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1542. void run_deploy_moves_script() {
  1543. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_1_Z)
  1544. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1545. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1546. #endif
  1547. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1548. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1549. #endif
  1550. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1551. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1552. #endif
  1553. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1554. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1555. #endif
  1556. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1557. #endif
  1558. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_2_Z)
  1559. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1560. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1561. #endif
  1562. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1563. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1564. #endif
  1565. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1566. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1567. #endif
  1568. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1569. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1570. #endif
  1571. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1572. #endif
  1573. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_3_Z)
  1574. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1575. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1576. #endif
  1577. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1578. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1579. #endif
  1580. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1581. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1582. #endif
  1583. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1584. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1585. #endif
  1586. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1587. #endif
  1588. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_4_Z)
  1589. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1590. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1591. #endif
  1592. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1593. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1594. #endif
  1595. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1596. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1597. #endif
  1598. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1599. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1600. #endif
  1601. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1602. #endif
  1603. #if defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_X) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Y) || defined(Z_PROBE_ALLEN_KEY_DEPLOY_5_Z)
  1604. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1605. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1606. #endif
  1607. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1608. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1609. #endif
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1615. #endif
  1616. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1617. #endif
  1618. }
  1619. void run_stow_moves_script() {
  1620. #if defined(Z_PROBE_ALLEN_KEY_STOW_1_X) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_1_Z)
  1621. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1622. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1623. #endif
  1624. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1625. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1626. #endif
  1627. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1628. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1629. #endif
  1630. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1631. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1632. #endif
  1633. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1634. #endif
  1635. #if defined(Z_PROBE_ALLEN_KEY_STOW_2_X) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_2_Z)
  1636. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1637. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1638. #endif
  1639. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1640. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1641. #endif
  1642. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1643. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1646. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1647. #endif
  1648. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1649. #endif
  1650. #if defined(Z_PROBE_ALLEN_KEY_STOW_3_X) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_3_Z)
  1651. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1652. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1653. #endif
  1654. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1655. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1656. #endif
  1657. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1658. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1659. #endif
  1660. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1661. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1662. #endif
  1663. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1664. #endif
  1665. #if defined(Z_PROBE_ALLEN_KEY_STOW_4_X) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_4_Z)
  1666. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1667. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1668. #endif
  1669. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1670. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1671. #endif
  1672. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1673. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1674. #endif
  1675. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1676. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1677. #endif
  1678. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1679. #endif
  1680. #if defined(Z_PROBE_ALLEN_KEY_STOW_5_X) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Y) || defined(Z_PROBE_ALLEN_KEY_STOW_5_Z)
  1681. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1682. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1683. #endif
  1684. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1685. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1686. #endif
  1687. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1688. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1689. #endif
  1690. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1691. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1692. #endif
  1693. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1694. #endif
  1695. }
  1696. #endif
  1697. #if ENABLED(PROBING_FANS_OFF)
  1698. void fans_pause(const bool p) {
  1699. if (p != fans_paused) {
  1700. fans_paused = p;
  1701. if (p)
  1702. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1703. paused_fanSpeeds[x] = fanSpeeds[x];
  1704. fanSpeeds[x] = 0;
  1705. }
  1706. else
  1707. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1708. fanSpeeds[x] = paused_fanSpeeds[x];
  1709. }
  1710. }
  1711. #endif // PROBING_FANS_OFF
  1712. #if HAS_BED_PROBE
  1713. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1714. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1715. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1716. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1717. #else
  1718. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1719. #endif
  1720. #endif
  1721. #if QUIET_PROBING
  1722. void probing_pause(const bool p) {
  1723. #if ENABLED(PROBING_HEATERS_OFF)
  1724. thermalManager.pause(p);
  1725. #endif
  1726. #if ENABLED(PROBING_FANS_OFF)
  1727. fans_pause(p);
  1728. #endif
  1729. if (p) safe_delay(25);
  1730. }
  1731. #endif // QUIET_PROBING
  1732. #if ENABLED(BLTOUCH)
  1733. void bltouch_command(int angle) {
  1734. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1735. safe_delay(BLTOUCH_DELAY);
  1736. }
  1737. void set_bltouch_deployed(const bool deploy) {
  1738. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1739. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1740. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1741. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1742. safe_delay(1500); // Wait for internal self-test to complete.
  1743. // (Measured completion time was 0.65 seconds
  1744. // after reset, deploy, and stow sequence)
  1745. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1746. SERIAL_ERROR_START;
  1747. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1748. stop(); // punt!
  1749. }
  1750. }
  1751. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1752. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1753. if (DEBUGGING(LEVELING)) {
  1754. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1755. SERIAL_CHAR(')');
  1756. SERIAL_EOL;
  1757. }
  1758. #endif
  1759. }
  1760. #endif // BLTOUCH
  1761. // returns false for ok and true for failure
  1762. bool set_probe_deployed(bool deploy) {
  1763. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1764. if (DEBUGGING(LEVELING)) {
  1765. DEBUG_POS("set_probe_deployed", current_position);
  1766. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1767. }
  1768. #endif
  1769. if (endstops.z_probe_enabled == deploy) return false;
  1770. // Make room for probe
  1771. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1772. // When deploying make sure BLTOUCH is not already triggered
  1773. #if ENABLED(BLTOUCH)
  1774. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1775. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1776. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1777. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1778. safe_delay(1500); // wait for internal self test to complete
  1779. // measured completion time was 0.65 seconds
  1780. // after reset, deploy & stow sequence
  1781. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1782. SERIAL_ERROR_START;
  1783. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1784. stop(); // punt!
  1785. return true;
  1786. }
  1787. }
  1788. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1789. #if ENABLED(Z_PROBE_SLED)
  1790. #define _AUE_ARGS true, false, false
  1791. #else
  1792. #define _AUE_ARGS
  1793. #endif
  1794. if (axis_unhomed_error(_AUE_ARGS)) {
  1795. SERIAL_ERROR_START;
  1796. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1797. stop();
  1798. return true;
  1799. }
  1800. #endif
  1801. const float oldXpos = current_position[X_AXIS],
  1802. oldYpos = current_position[Y_AXIS];
  1803. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1804. // If endstop is already false, the Z probe is deployed
  1805. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1806. // Would a goto be less ugly?
  1807. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1808. // for a triggered when stowed manual probe.
  1809. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1810. // otherwise an Allen-Key probe can't be stowed.
  1811. #endif
  1812. #if ENABLED(SOLENOID_PROBE)
  1813. #if HAS_SOLENOID_1
  1814. WRITE(SOL1_PIN, deploy);
  1815. #endif
  1816. #elif ENABLED(Z_PROBE_SLED)
  1817. dock_sled(!deploy);
  1818. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1819. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1820. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1821. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1822. #endif
  1823. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1824. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1825. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1826. if (IsRunning()) {
  1827. SERIAL_ERROR_START;
  1828. SERIAL_ERRORLNPGM("Z-Probe failed");
  1829. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1830. }
  1831. stop();
  1832. return true;
  1833. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1834. #endif
  1835. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1836. endstops.enable_z_probe(deploy);
  1837. return false;
  1838. }
  1839. static void do_probe_move(float z, float fr_mm_m) {
  1840. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1841. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1842. #endif
  1843. // Deploy BLTouch at the start of any probe
  1844. #if ENABLED(BLTOUCH)
  1845. set_bltouch_deployed(true);
  1846. #endif
  1847. #if QUIET_PROBING
  1848. probing_pause(true);
  1849. #endif
  1850. // Move down until probe triggered
  1851. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1852. #if QUIET_PROBING
  1853. probing_pause(false);
  1854. #endif
  1855. // Retract BLTouch immediately after a probe
  1856. #if ENABLED(BLTOUCH)
  1857. set_bltouch_deployed(false);
  1858. #endif
  1859. // Clear endstop flags
  1860. endstops.hit_on_purpose();
  1861. // Get Z where the steppers were interrupted
  1862. set_current_from_steppers_for_axis(Z_AXIS);
  1863. // Tell the planner where we actually are
  1864. SYNC_PLAN_POSITION_KINEMATIC();
  1865. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1866. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1867. #endif
  1868. }
  1869. // Do a single Z probe and return with current_position[Z_AXIS]
  1870. // at the height where the probe triggered.
  1871. static float run_z_probe() {
  1872. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1873. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1874. #endif
  1875. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1876. refresh_cmd_timeout();
  1877. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1878. // Do a first probe at the fast speed
  1879. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1880. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1881. float first_probe_z = current_position[Z_AXIS];
  1882. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1883. #endif
  1884. // move up by the bump distance
  1885. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1886. #else
  1887. // If the nozzle is above the travel height then
  1888. // move down quickly before doing the slow probe
  1889. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1890. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1891. #if ENABLED(DELTA)
  1892. z -= home_offset[Z_AXIS];
  1893. #endif
  1894. if (z < current_position[Z_AXIS])
  1895. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1896. #endif
  1897. // move down slowly to find bed
  1898. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1899. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1900. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1901. #endif
  1902. // Debug: compare probe heights
  1903. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1904. if (DEBUGGING(LEVELING)) {
  1905. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1906. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1907. }
  1908. #endif
  1909. return current_position[Z_AXIS] + zprobe_zoffset;
  1910. }
  1911. /**
  1912. * - Move to the given XY
  1913. * - Deploy the probe, if not already deployed
  1914. * - Probe the bed, get the Z position
  1915. * - Depending on the 'stow' flag
  1916. * - Stow the probe, or
  1917. * - Raise to the BETWEEN height
  1918. * - Return the probed Z position
  1919. */
  1920. float probe_pt(const float &x, const float &y, const bool stow/*=true*/, const int verbose_level/*=1*/) {
  1921. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1922. if (DEBUGGING(LEVELING)) {
  1923. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1924. SERIAL_ECHOPAIR(", ", y);
  1925. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1926. SERIAL_ECHOLNPGM("stow)");
  1927. DEBUG_POS("", current_position);
  1928. }
  1929. #endif
  1930. if (!position_is_reachable_by_probe_xy(x, y)) return NAN;
  1931. const float old_feedrate_mm_s = feedrate_mm_s;
  1932. #if ENABLED(DELTA)
  1933. if (current_position[Z_AXIS] > delta_clip_start_height)
  1934. do_blocking_move_to_z(delta_clip_start_height);
  1935. #endif
  1936. // Ensure a minimum height before moving the probe
  1937. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1938. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1939. // Move the probe to the given XY
  1940. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1941. if (DEPLOY_PROBE()) return NAN;
  1942. const float measured_z = run_z_probe();
  1943. if (!stow)
  1944. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1945. else
  1946. if (STOW_PROBE()) return NAN;
  1947. if (verbose_level > 2) {
  1948. SERIAL_PROTOCOLPGM("Bed X: ");
  1949. SERIAL_PROTOCOL_F(x, 3);
  1950. SERIAL_PROTOCOLPGM(" Y: ");
  1951. SERIAL_PROTOCOL_F(y, 3);
  1952. SERIAL_PROTOCOLPGM(" Z: ");
  1953. SERIAL_PROTOCOL_F(measured_z, 3);
  1954. SERIAL_EOL;
  1955. }
  1956. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1957. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1958. #endif
  1959. feedrate_mm_s = old_feedrate_mm_s;
  1960. return measured_z;
  1961. }
  1962. #endif // HAS_BED_PROBE
  1963. #if HAS_LEVELING
  1964. bool leveling_is_valid() {
  1965. return
  1966. #if ENABLED(MESH_BED_LEVELING)
  1967. mbl.has_mesh()
  1968. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1969. !!bilinear_grid_spacing[X_AXIS]
  1970. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1971. true
  1972. #else // 3POINT, LINEAR
  1973. true
  1974. #endif
  1975. ;
  1976. }
  1977. bool leveling_is_active() {
  1978. return
  1979. #if ENABLED(MESH_BED_LEVELING)
  1980. mbl.active()
  1981. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  1982. ubl.state.active
  1983. #else
  1984. planner.abl_enabled
  1985. #endif
  1986. ;
  1987. }
  1988. /**
  1989. * Turn bed leveling on or off, fixing the current
  1990. * position as-needed.
  1991. *
  1992. * Disable: Current position = physical position
  1993. * Enable: Current position = "unleveled" physical position
  1994. */
  1995. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  1996. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1997. const bool can_change = (!enable || leveling_is_valid());
  1998. #else
  1999. constexpr bool can_change = true;
  2000. #endif
  2001. if (can_change && enable != leveling_is_active()) {
  2002. #if ENABLED(MESH_BED_LEVELING)
  2003. if (!enable)
  2004. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2005. const bool enabling = enable && leveling_is_valid();
  2006. mbl.set_active(enabling);
  2007. if (enabling) planner.unapply_leveling(current_position);
  2008. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2009. #if PLANNER_LEVELING
  2010. if (!enable) // leveling from on to off
  2011. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2012. else
  2013. planner.unapply_leveling(current_position);
  2014. #endif
  2015. ubl.state.active = enable;
  2016. #else // ABL
  2017. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2018. // Force bilinear_z_offset to re-calculate next time
  2019. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2020. (void)bilinear_z_offset(reset);
  2021. #endif
  2022. planner.abl_enabled = enable;
  2023. if (!enable)
  2024. set_current_from_steppers_for_axis(
  2025. #if ABL_PLANAR
  2026. ALL_AXES
  2027. #else
  2028. Z_AXIS
  2029. #endif
  2030. );
  2031. else
  2032. planner.unapply_leveling(current_position);
  2033. #endif
  2034. }
  2035. }
  2036. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2037. void set_z_fade_height(const float zfh) {
  2038. planner.z_fade_height = zfh;
  2039. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2040. if (leveling_is_active())
  2041. set_current_from_steppers_for_axis(
  2042. #if ABL_PLANAR
  2043. ALL_AXES
  2044. #else
  2045. Z_AXIS
  2046. #endif
  2047. );
  2048. }
  2049. #endif // LEVELING_FADE_HEIGHT
  2050. /**
  2051. * Reset calibration results to zero.
  2052. */
  2053. void reset_bed_level() {
  2054. set_bed_leveling_enabled(false);
  2055. #if ENABLED(MESH_BED_LEVELING)
  2056. if (leveling_is_valid()) {
  2057. mbl.reset();
  2058. mbl.set_has_mesh(false);
  2059. }
  2060. #else
  2061. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2062. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2063. #endif
  2064. #if ABL_PLANAR
  2065. planner.bed_level_matrix.set_to_identity();
  2066. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2067. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2068. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2069. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2070. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2071. z_values[x][y] = NAN;
  2072. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2073. ubl.reset();
  2074. #endif
  2075. #endif
  2076. }
  2077. #endif // HAS_LEVELING
  2078. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2079. /**
  2080. * Enable to produce output in JSON format suitable
  2081. * for SCAD or JavaScript mesh visualizers.
  2082. *
  2083. * Visualize meshes in OpenSCAD using the included script.
  2084. *
  2085. * buildroot/shared/scripts/MarlinMesh.scad
  2086. */
  2087. //#define SCAD_MESH_OUTPUT
  2088. /**
  2089. * Print calibration results for plotting or manual frame adjustment.
  2090. */
  2091. static void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, float (*fn)(const uint8_t, const uint8_t)) {
  2092. #ifndef SCAD_MESH_OUTPUT
  2093. for (uint8_t x = 0; x < sx; x++) {
  2094. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2095. SERIAL_PROTOCOLCHAR(' ');
  2096. SERIAL_PROTOCOL((int)x);
  2097. }
  2098. SERIAL_EOL;
  2099. #endif
  2100. #ifdef SCAD_MESH_OUTPUT
  2101. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2102. #endif
  2103. for (uint8_t y = 0; y < sy; y++) {
  2104. #ifdef SCAD_MESH_OUTPUT
  2105. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2106. #else
  2107. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2108. SERIAL_PROTOCOL((int)y);
  2109. #endif
  2110. for (uint8_t x = 0; x < sx; x++) {
  2111. SERIAL_PROTOCOLCHAR(' ');
  2112. const float offset = fn(x, y);
  2113. if (!isnan(offset)) {
  2114. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2115. SERIAL_PROTOCOL_F(offset, precision);
  2116. }
  2117. else {
  2118. #ifdef SCAD_MESH_OUTPUT
  2119. for (uint8_t i = 3; i < precision + 3; i++)
  2120. SERIAL_PROTOCOLCHAR(' ');
  2121. SERIAL_PROTOCOLPGM("NAN");
  2122. #else
  2123. for (uint8_t i = 0; i < precision + 3; i++)
  2124. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2125. #endif
  2126. }
  2127. #ifdef SCAD_MESH_OUTPUT
  2128. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2129. #endif
  2130. }
  2131. #ifdef SCAD_MESH_OUTPUT
  2132. SERIAL_PROTOCOLCHAR(' ');
  2133. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2134. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2135. #endif
  2136. SERIAL_EOL;
  2137. }
  2138. #ifdef SCAD_MESH_OUTPUT
  2139. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2140. #endif
  2141. SERIAL_EOL;
  2142. }
  2143. #endif
  2144. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2145. /**
  2146. * Extrapolate a single point from its neighbors
  2147. */
  2148. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2149. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2150. if (DEBUGGING(LEVELING)) {
  2151. SERIAL_ECHOPGM("Extrapolate [");
  2152. if (x < 10) SERIAL_CHAR(' ');
  2153. SERIAL_ECHO((int)x);
  2154. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2155. SERIAL_CHAR(' ');
  2156. if (y < 10) SERIAL_CHAR(' ');
  2157. SERIAL_ECHO((int)y);
  2158. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2159. SERIAL_CHAR(']');
  2160. }
  2161. #endif
  2162. if (!isnan(z_values[x][y])) {
  2163. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2164. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2165. #endif
  2166. return; // Don't overwrite good values.
  2167. }
  2168. SERIAL_EOL;
  2169. // Get X neighbors, Y neighbors, and XY neighbors
  2170. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2171. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2172. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2173. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2174. // Treat far unprobed points as zero, near as equal to far
  2175. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2176. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2177. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2178. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2179. // Take the average instead of the median
  2180. z_values[x][y] = (a + b + c) / 3.0;
  2181. // Median is robust (ignores outliers).
  2182. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2183. // : ((c < b) ? b : (a < c) ? a : c);
  2184. }
  2185. //Enable this if your SCARA uses 180° of total area
  2186. //#define EXTRAPOLATE_FROM_EDGE
  2187. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2188. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2189. #define HALF_IN_X
  2190. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2191. #define HALF_IN_Y
  2192. #endif
  2193. #endif
  2194. /**
  2195. * Fill in the unprobed points (corners of circular print surface)
  2196. * using linear extrapolation, away from the center.
  2197. */
  2198. static void extrapolate_unprobed_bed_level() {
  2199. #ifdef HALF_IN_X
  2200. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2201. #else
  2202. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2203. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2204. xlen = ctrx1;
  2205. #endif
  2206. #ifdef HALF_IN_Y
  2207. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2208. #else
  2209. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2210. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2211. ylen = ctry1;
  2212. #endif
  2213. for (uint8_t xo = 0; xo <= xlen; xo++)
  2214. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2215. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2216. #ifndef HALF_IN_X
  2217. const uint8_t x1 = ctrx1 - xo;
  2218. #endif
  2219. #ifndef HALF_IN_Y
  2220. const uint8_t y1 = ctry1 - yo;
  2221. #ifndef HALF_IN_X
  2222. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2223. #endif
  2224. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2225. #endif
  2226. #ifndef HALF_IN_X
  2227. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2228. #endif
  2229. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2230. }
  2231. }
  2232. static void print_bilinear_leveling_grid() {
  2233. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2234. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2235. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2236. );
  2237. }
  2238. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2239. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2240. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2241. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2242. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2243. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2244. int bilinear_grid_spacing_virt[2] = { 0 };
  2245. float bilinear_grid_factor_virt[2] = { 0 };
  2246. static void bed_level_virt_print() {
  2247. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2248. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2249. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2250. );
  2251. }
  2252. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2253. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2254. uint8_t ep = 0, ip = 1;
  2255. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2256. if (x) {
  2257. ep = GRID_MAX_POINTS_X - 1;
  2258. ip = GRID_MAX_POINTS_X - 2;
  2259. }
  2260. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2261. return LINEAR_EXTRAPOLATION(
  2262. z_values[ep][y - 1],
  2263. z_values[ip][y - 1]
  2264. );
  2265. else
  2266. return LINEAR_EXTRAPOLATION(
  2267. bed_level_virt_coord(ep + 1, y),
  2268. bed_level_virt_coord(ip + 1, y)
  2269. );
  2270. }
  2271. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2272. if (y) {
  2273. ep = GRID_MAX_POINTS_Y - 1;
  2274. ip = GRID_MAX_POINTS_Y - 2;
  2275. }
  2276. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2277. return LINEAR_EXTRAPOLATION(
  2278. z_values[x - 1][ep],
  2279. z_values[x - 1][ip]
  2280. );
  2281. else
  2282. return LINEAR_EXTRAPOLATION(
  2283. bed_level_virt_coord(x, ep + 1),
  2284. bed_level_virt_coord(x, ip + 1)
  2285. );
  2286. }
  2287. return z_values[x - 1][y - 1];
  2288. }
  2289. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2290. return (
  2291. p[i-1] * -t * sq(1 - t)
  2292. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2293. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2294. - p[i+2] * sq(t) * (1 - t)
  2295. ) * 0.5;
  2296. }
  2297. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2298. float row[4], column[4];
  2299. for (uint8_t i = 0; i < 4; i++) {
  2300. for (uint8_t j = 0; j < 4; j++) {
  2301. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2302. }
  2303. row[i] = bed_level_virt_cmr(column, 1, ty);
  2304. }
  2305. return bed_level_virt_cmr(row, 1, tx);
  2306. }
  2307. void bed_level_virt_interpolate() {
  2308. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2309. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2310. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2311. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2312. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2313. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2314. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2315. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2316. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2317. continue;
  2318. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2319. bed_level_virt_2cmr(
  2320. x + 1,
  2321. y + 1,
  2322. (float)tx / (BILINEAR_SUBDIVISIONS),
  2323. (float)ty / (BILINEAR_SUBDIVISIONS)
  2324. );
  2325. }
  2326. }
  2327. #endif // ABL_BILINEAR_SUBDIVISION
  2328. // Refresh after other values have been updated
  2329. void refresh_bed_level() {
  2330. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2331. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2332. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2333. bed_level_virt_interpolate();
  2334. #endif
  2335. }
  2336. #endif // AUTO_BED_LEVELING_BILINEAR
  2337. /**
  2338. * Home an individual linear axis
  2339. */
  2340. static void do_homing_move(const AxisEnum axis, float distance, float fr_mm_s=0.0) {
  2341. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2342. if (DEBUGGING(LEVELING)) {
  2343. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2344. SERIAL_ECHOPAIR(", ", distance);
  2345. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2346. SERIAL_CHAR(')');
  2347. SERIAL_EOL;
  2348. }
  2349. #endif
  2350. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2351. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2352. if (deploy_bltouch) set_bltouch_deployed(true);
  2353. #endif
  2354. #if QUIET_PROBING
  2355. if (axis == Z_AXIS) probing_pause(true);
  2356. #endif
  2357. // Tell the planner we're at Z=0
  2358. current_position[axis] = 0;
  2359. #if IS_SCARA
  2360. SYNC_PLAN_POSITION_KINEMATIC();
  2361. current_position[axis] = distance;
  2362. inverse_kinematics(current_position);
  2363. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[axis], active_extruder);
  2364. #else
  2365. sync_plan_position();
  2366. current_position[axis] = distance;
  2367. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[axis], active_extruder);
  2368. #endif
  2369. stepper.synchronize();
  2370. #if QUIET_PROBING
  2371. if (axis == Z_AXIS) probing_pause(false);
  2372. #endif
  2373. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2374. if (deploy_bltouch) set_bltouch_deployed(false);
  2375. #endif
  2376. endstops.hit_on_purpose();
  2377. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2378. if (DEBUGGING(LEVELING)) {
  2379. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2380. SERIAL_CHAR(')');
  2381. SERIAL_EOL;
  2382. }
  2383. #endif
  2384. }
  2385. /**
  2386. * TMC2130 specific sensorless homing using stallGuard2.
  2387. * stallGuard2 only works when in spreadCycle mode.
  2388. * spreadCycle and stealthChop are mutually exclusive.
  2389. */
  2390. #if ENABLED(SENSORLESS_HOMING)
  2391. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2392. #if ENABLED(STEALTHCHOP)
  2393. if (enable) {
  2394. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2395. st.stealthChop(0);
  2396. }
  2397. else {
  2398. st.coolstep_min_speed(0);
  2399. st.stealthChop(1);
  2400. }
  2401. #endif
  2402. st.diag1_stall(enable ? 1 : 0);
  2403. }
  2404. #endif
  2405. /**
  2406. * Home an individual "raw axis" to its endstop.
  2407. * This applies to XYZ on Cartesian and Core robots, and
  2408. * to the individual ABC steppers on DELTA and SCARA.
  2409. *
  2410. * At the end of the procedure the axis is marked as
  2411. * homed and the current position of that axis is updated.
  2412. * Kinematic robots should wait till all axes are homed
  2413. * before updating the current position.
  2414. */
  2415. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2416. static void homeaxis(const AxisEnum axis) {
  2417. #if IS_SCARA
  2418. // Only Z homing (with probe) is permitted
  2419. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2420. #else
  2421. #define CAN_HOME(A) \
  2422. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2423. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2424. #endif
  2425. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2426. if (DEBUGGING(LEVELING)) {
  2427. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2428. SERIAL_CHAR(')');
  2429. SERIAL_EOL;
  2430. }
  2431. #endif
  2432. const int axis_home_dir =
  2433. #if ENABLED(DUAL_X_CARRIAGE)
  2434. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2435. #endif
  2436. home_dir(axis);
  2437. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2438. #if HOMING_Z_WITH_PROBE
  2439. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2440. #endif
  2441. // Set a flag for Z motor locking
  2442. #if ENABLED(Z_DUAL_ENDSTOPS)
  2443. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2444. #endif
  2445. // Disable stealthChop if used. Enable diag1 pin on driver.
  2446. #if ENABLED(SENSORLESS_HOMING)
  2447. #if ENABLED(X_IS_TMC2130)
  2448. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2449. #endif
  2450. #if ENABLED(Y_IS_TMC2130)
  2451. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2452. #endif
  2453. #endif
  2454. // Fast move towards endstop until triggered
  2455. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2456. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2457. #endif
  2458. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2459. // When homing Z with probe respect probe clearance
  2460. const float bump = axis_home_dir * (
  2461. #if HOMING_Z_WITH_PROBE
  2462. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2463. #endif
  2464. home_bump_mm(axis)
  2465. );
  2466. // If a second homing move is configured...
  2467. if (bump) {
  2468. // Move away from the endstop by the axis HOME_BUMP_MM
  2469. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2470. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2471. #endif
  2472. do_homing_move(axis, -bump);
  2473. // Slow move towards endstop until triggered
  2474. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2475. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2476. #endif
  2477. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2478. }
  2479. #if ENABLED(Z_DUAL_ENDSTOPS)
  2480. if (axis == Z_AXIS) {
  2481. float adj = fabs(z_endstop_adj);
  2482. bool lockZ1;
  2483. if (axis_home_dir > 0) {
  2484. adj = -adj;
  2485. lockZ1 = (z_endstop_adj > 0);
  2486. }
  2487. else
  2488. lockZ1 = (z_endstop_adj < 0);
  2489. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2490. // Move to the adjusted endstop height
  2491. do_homing_move(axis, adj);
  2492. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2493. stepper.set_homing_flag(false);
  2494. } // Z_AXIS
  2495. #endif
  2496. #if IS_SCARA
  2497. set_axis_is_at_home(axis);
  2498. SYNC_PLAN_POSITION_KINEMATIC();
  2499. #elif ENABLED(DELTA)
  2500. // Delta has already moved all three towers up in G28
  2501. // so here it re-homes each tower in turn.
  2502. // Delta homing treats the axes as normal linear axes.
  2503. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2504. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2505. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2506. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2507. #endif
  2508. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2509. }
  2510. #else
  2511. // For cartesian/core machines,
  2512. // set the axis to its home position
  2513. set_axis_is_at_home(axis);
  2514. sync_plan_position();
  2515. destination[axis] = current_position[axis];
  2516. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2517. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2518. #endif
  2519. #endif
  2520. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2521. #if ENABLED(SENSORLESS_HOMING)
  2522. #if ENABLED(X_IS_TMC2130)
  2523. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2524. #endif
  2525. #if ENABLED(Y_IS_TMC2130)
  2526. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2527. #endif
  2528. #endif
  2529. // Put away the Z probe
  2530. #if HOMING_Z_WITH_PROBE
  2531. if (axis == Z_AXIS && STOW_PROBE()) return;
  2532. #endif
  2533. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2534. if (DEBUGGING(LEVELING)) {
  2535. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2536. SERIAL_CHAR(')');
  2537. SERIAL_EOL;
  2538. }
  2539. #endif
  2540. } // homeaxis()
  2541. #if ENABLED(FWRETRACT)
  2542. void retract(const bool retracting, const bool swapping = false) {
  2543. static float hop_height;
  2544. if (retracting == retracted[active_extruder]) return;
  2545. const float old_feedrate_mm_s = feedrate_mm_s;
  2546. set_destination_to_current();
  2547. if (retracting) {
  2548. feedrate_mm_s = retract_feedrate_mm_s;
  2549. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2550. sync_plan_position_e();
  2551. prepare_move_to_destination();
  2552. if (retract_zlift > 0.01) {
  2553. hop_height = current_position[Z_AXIS];
  2554. // Pretend current position is lower
  2555. current_position[Z_AXIS] -= retract_zlift;
  2556. SYNC_PLAN_POSITION_KINEMATIC();
  2557. // Raise up to the old current_position
  2558. prepare_move_to_destination();
  2559. }
  2560. }
  2561. else {
  2562. // If the height hasn't been lowered, undo the Z hop
  2563. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2564. // Pretend current position is higher. Z will lower on the next move
  2565. current_position[Z_AXIS] += retract_zlift;
  2566. SYNC_PLAN_POSITION_KINEMATIC();
  2567. // Lower Z
  2568. prepare_move_to_destination();
  2569. }
  2570. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2571. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2572. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2573. sync_plan_position_e();
  2574. // Recover E
  2575. prepare_move_to_destination();
  2576. }
  2577. feedrate_mm_s = old_feedrate_mm_s;
  2578. retracted[active_extruder] = retracting;
  2579. } // retract()
  2580. #endif // FWRETRACT
  2581. #if ENABLED(MIXING_EXTRUDER)
  2582. void normalize_mix() {
  2583. float mix_total = 0.0;
  2584. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2585. // Scale all values if they don't add up to ~1.0
  2586. if (!NEAR(mix_total, 1.0)) {
  2587. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2588. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2589. }
  2590. }
  2591. #if ENABLED(DIRECT_MIXING_IN_G1)
  2592. // Get mixing parameters from the GCode
  2593. // The total "must" be 1.0 (but it will be normalized)
  2594. // If no mix factors are given, the old mix is preserved
  2595. void gcode_get_mix() {
  2596. const char* mixing_codes = "ABCDHI";
  2597. byte mix_bits = 0;
  2598. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2599. if (parser.seen(mixing_codes[i])) {
  2600. SBI(mix_bits, i);
  2601. float v = parser.value_float();
  2602. NOLESS(v, 0.0);
  2603. mixing_factor[i] = RECIPROCAL(v);
  2604. }
  2605. }
  2606. // If any mixing factors were included, clear the rest
  2607. // If none were included, preserve the last mix
  2608. if (mix_bits) {
  2609. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2610. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2611. normalize_mix();
  2612. }
  2613. }
  2614. #endif
  2615. #endif
  2616. /**
  2617. * ***************************************************************************
  2618. * ***************************** G-CODE HANDLING *****************************
  2619. * ***************************************************************************
  2620. */
  2621. /**
  2622. * Set XYZE destination and feedrate from the current GCode command
  2623. *
  2624. * - Set destination from included axis codes
  2625. * - Set to current for missing axis codes
  2626. * - Set the feedrate, if included
  2627. */
  2628. void gcode_get_destination() {
  2629. LOOP_XYZE(i) {
  2630. if (parser.seen(axis_codes[i]))
  2631. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2632. else
  2633. destination[i] = current_position[i];
  2634. }
  2635. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  2636. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2637. #if ENABLED(PRINTCOUNTER)
  2638. if (!DEBUGGING(DRYRUN))
  2639. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2640. #endif
  2641. // Get ABCDHI mixing factors
  2642. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2643. gcode_get_mix();
  2644. #endif
  2645. }
  2646. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2647. /**
  2648. * Output a "busy" message at regular intervals
  2649. * while the machine is not accepting commands.
  2650. */
  2651. void host_keepalive() {
  2652. const millis_t ms = millis();
  2653. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2654. if (PENDING(ms, next_busy_signal_ms)) return;
  2655. switch (busy_state) {
  2656. case IN_HANDLER:
  2657. case IN_PROCESS:
  2658. SERIAL_ECHO_START;
  2659. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2660. break;
  2661. case PAUSED_FOR_USER:
  2662. SERIAL_ECHO_START;
  2663. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2664. break;
  2665. case PAUSED_FOR_INPUT:
  2666. SERIAL_ECHO_START;
  2667. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2668. break;
  2669. default:
  2670. break;
  2671. }
  2672. }
  2673. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2674. }
  2675. #endif // HOST_KEEPALIVE_FEATURE
  2676. /**************************************************
  2677. ***************** GCode Handlers *****************
  2678. **************************************************/
  2679. /**
  2680. * G0, G1: Coordinated movement of X Y Z E axes
  2681. */
  2682. inline void gcode_G0_G1(
  2683. #if IS_SCARA
  2684. bool fast_move=false
  2685. #endif
  2686. ) {
  2687. if (IsRunning()) {
  2688. gcode_get_destination(); // For X Y Z E F
  2689. #if ENABLED(FWRETRACT)
  2690. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2691. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2692. // Is this move an attempt to retract or recover?
  2693. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2694. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2695. sync_plan_position_e(); // AND from the planner
  2696. retract(!retracted[active_extruder]);
  2697. return;
  2698. }
  2699. }
  2700. #endif // FWRETRACT
  2701. #if IS_SCARA
  2702. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2703. #else
  2704. prepare_move_to_destination();
  2705. #endif
  2706. }
  2707. }
  2708. /**
  2709. * G2: Clockwise Arc
  2710. * G3: Counterclockwise Arc
  2711. *
  2712. * This command has two forms: IJ-form and R-form.
  2713. *
  2714. * - I specifies an X offset. J specifies a Y offset.
  2715. * At least one of the IJ parameters is required.
  2716. * X and Y can be omitted to do a complete circle.
  2717. * The given XY is not error-checked. The arc ends
  2718. * based on the angle of the destination.
  2719. * Mixing I or J with R will throw an error.
  2720. *
  2721. * - R specifies the radius. X or Y is required.
  2722. * Omitting both X and Y will throw an error.
  2723. * X or Y must differ from the current XY.
  2724. * Mixing R with I or J will throw an error.
  2725. *
  2726. * Examples:
  2727. *
  2728. * G2 I10 ; CW circle centered at X+10
  2729. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2730. */
  2731. #if ENABLED(ARC_SUPPORT)
  2732. inline void gcode_G2_G3(bool clockwise) {
  2733. if (IsRunning()) {
  2734. #if ENABLED(SF_ARC_FIX)
  2735. const bool relative_mode_backup = relative_mode;
  2736. relative_mode = true;
  2737. #endif
  2738. gcode_get_destination();
  2739. #if ENABLED(SF_ARC_FIX)
  2740. relative_mode = relative_mode_backup;
  2741. #endif
  2742. float arc_offset[2] = { 0.0, 0.0 };
  2743. if (parser.seen('R')) {
  2744. const float r = parser.value_linear_units(),
  2745. x1 = current_position[X_AXIS], y1 = current_position[Y_AXIS],
  2746. x2 = destination[X_AXIS], y2 = destination[Y_AXIS];
  2747. if (r && (x2 != x1 || y2 != y1)) {
  2748. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2749. dx = x2 - x1, dy = y2 - y1, // X and Y differences
  2750. d = HYPOT(dx, dy), // Linear distance between the points
  2751. h = sqrt(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2752. mx = (x1 + x2) * 0.5, my = (y1 + y2) * 0.5, // Point between the two points
  2753. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2754. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2755. arc_offset[X_AXIS] = cx - x1;
  2756. arc_offset[Y_AXIS] = cy - y1;
  2757. }
  2758. }
  2759. else {
  2760. if (parser.seen('I')) arc_offset[X_AXIS] = parser.value_linear_units();
  2761. if (parser.seen('J')) arc_offset[Y_AXIS] = parser.value_linear_units();
  2762. }
  2763. if (arc_offset[0] || arc_offset[1]) {
  2764. // Send an arc to the planner
  2765. plan_arc(destination, arc_offset, clockwise);
  2766. refresh_cmd_timeout();
  2767. }
  2768. else {
  2769. // Bad arguments
  2770. SERIAL_ERROR_START;
  2771. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2772. }
  2773. }
  2774. }
  2775. #endif
  2776. /**
  2777. * G4: Dwell S<seconds> or P<milliseconds>
  2778. */
  2779. inline void gcode_G4() {
  2780. millis_t dwell_ms = 0;
  2781. if (parser.seen('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2782. if (parser.seen('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2783. stepper.synchronize();
  2784. refresh_cmd_timeout();
  2785. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2786. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2787. while (PENDING(millis(), dwell_ms)) idle();
  2788. }
  2789. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2790. /**
  2791. * Parameters interpreted according to:
  2792. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2793. * However I, J omission is not supported at this point; all
  2794. * parameters can be omitted and default to zero.
  2795. */
  2796. /**
  2797. * G5: Cubic B-spline
  2798. */
  2799. inline void gcode_G5() {
  2800. if (IsRunning()) {
  2801. gcode_get_destination();
  2802. const float offset[] = {
  2803. parser.seen('I') ? parser.value_linear_units() : 0.0,
  2804. parser.seen('J') ? parser.value_linear_units() : 0.0,
  2805. parser.seen('P') ? parser.value_linear_units() : 0.0,
  2806. parser.seen('Q') ? parser.value_linear_units() : 0.0
  2807. };
  2808. plan_cubic_move(offset);
  2809. }
  2810. }
  2811. #endif // BEZIER_CURVE_SUPPORT
  2812. #if ENABLED(FWRETRACT)
  2813. /**
  2814. * G10 - Retract filament according to settings of M207
  2815. * G11 - Recover filament according to settings of M208
  2816. */
  2817. inline void gcode_G10_G11(bool doRetract=false) {
  2818. #if EXTRUDERS > 1
  2819. if (doRetract) {
  2820. retracted_swap[active_extruder] = (parser.seen('S') && parser.value_bool()); // checks for swap retract argument
  2821. }
  2822. #endif
  2823. retract(doRetract
  2824. #if EXTRUDERS > 1
  2825. , retracted_swap[active_extruder]
  2826. #endif
  2827. );
  2828. }
  2829. #endif // FWRETRACT
  2830. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2831. /**
  2832. * G12: Clean the nozzle
  2833. */
  2834. inline void gcode_G12() {
  2835. // Don't allow nozzle cleaning without homing first
  2836. if (axis_unhomed_error()) return;
  2837. const uint8_t pattern = parser.seen('P') ? parser.value_ushort() : 0,
  2838. strokes = parser.seen('S') ? parser.value_ushort() : NOZZLE_CLEAN_STROKES,
  2839. objects = parser.seen('T') ? parser.value_ushort() : NOZZLE_CLEAN_TRIANGLES;
  2840. const float radius = parser.seen('R') ? parser.value_float() : NOZZLE_CLEAN_CIRCLE_RADIUS;
  2841. Nozzle::clean(pattern, strokes, radius, objects);
  2842. }
  2843. #endif
  2844. #if ENABLED(INCH_MODE_SUPPORT)
  2845. /**
  2846. * G20: Set input mode to inches
  2847. */
  2848. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2849. /**
  2850. * G21: Set input mode to millimeters
  2851. */
  2852. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2853. #endif
  2854. #if ENABLED(NOZZLE_PARK_FEATURE)
  2855. /**
  2856. * G27: Park the nozzle
  2857. */
  2858. inline void gcode_G27() {
  2859. // Don't allow nozzle parking without homing first
  2860. if (axis_unhomed_error()) return;
  2861. Nozzle::park(parser.seen('P') ? parser.value_ushort() : 0);
  2862. }
  2863. #endif // NOZZLE_PARK_FEATURE
  2864. #if ENABLED(QUICK_HOME)
  2865. static void quick_home_xy() {
  2866. // Pretend the current position is 0,0
  2867. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2868. sync_plan_position();
  2869. const int x_axis_home_dir =
  2870. #if ENABLED(DUAL_X_CARRIAGE)
  2871. x_home_dir(active_extruder)
  2872. #else
  2873. home_dir(X_AXIS)
  2874. #endif
  2875. ;
  2876. const float mlx = max_length(X_AXIS),
  2877. mly = max_length(Y_AXIS),
  2878. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2879. fr_mm_s = min(homing_feedrate_mm_s[X_AXIS], homing_feedrate_mm_s[Y_AXIS]) * sqrt(sq(mlratio) + 1.0);
  2880. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2881. endstops.hit_on_purpose(); // clear endstop hit flags
  2882. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2883. }
  2884. #endif // QUICK_HOME
  2885. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2886. void log_machine_info() {
  2887. SERIAL_ECHOPGM("Machine Type: ");
  2888. #if ENABLED(DELTA)
  2889. SERIAL_ECHOLNPGM("Delta");
  2890. #elif IS_SCARA
  2891. SERIAL_ECHOLNPGM("SCARA");
  2892. #elif IS_CORE
  2893. SERIAL_ECHOLNPGM("Core");
  2894. #else
  2895. SERIAL_ECHOLNPGM("Cartesian");
  2896. #endif
  2897. SERIAL_ECHOPGM("Probe: ");
  2898. #if ENABLED(PROBE_MANUALLY)
  2899. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  2900. #elif ENABLED(FIX_MOUNTED_PROBE)
  2901. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  2902. #elif ENABLED(BLTOUCH)
  2903. SERIAL_ECHOLNPGM("BLTOUCH");
  2904. #elif HAS_Z_SERVO_ENDSTOP
  2905. SERIAL_ECHOLNPGM("SERVO PROBE");
  2906. #elif ENABLED(Z_PROBE_SLED)
  2907. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  2908. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2909. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  2910. #else
  2911. SERIAL_ECHOLNPGM("NONE");
  2912. #endif
  2913. #if HAS_BED_PROBE
  2914. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  2915. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  2916. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  2917. #if (X_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2918. SERIAL_ECHOPGM(" (Right");
  2919. #elif (X_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2920. SERIAL_ECHOPGM(" (Left");
  2921. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2922. SERIAL_ECHOPGM(" (Middle");
  2923. #else
  2924. SERIAL_ECHOPGM(" (Aligned With");
  2925. #endif
  2926. #if (Y_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2927. SERIAL_ECHOPGM("-Back");
  2928. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2929. SERIAL_ECHOPGM("-Front");
  2930. #elif (X_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2931. SERIAL_ECHOPGM("-Center");
  2932. #endif
  2933. if (zprobe_zoffset < 0)
  2934. SERIAL_ECHOPGM(" & Below");
  2935. else if (zprobe_zoffset > 0)
  2936. SERIAL_ECHOPGM(" & Above");
  2937. else
  2938. SERIAL_ECHOPGM(" & Same Z as");
  2939. SERIAL_ECHOLNPGM(" Nozzle)");
  2940. #endif
  2941. #if HAS_ABL
  2942. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  2943. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  2944. SERIAL_ECHOPGM("LINEAR");
  2945. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2946. SERIAL_ECHOPGM("BILINEAR");
  2947. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  2948. SERIAL_ECHOPGM("3POINT");
  2949. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2950. SERIAL_ECHOPGM("UBL");
  2951. #endif
  2952. if (leveling_is_active()) {
  2953. SERIAL_ECHOLNPGM(" (enabled)");
  2954. #if ABL_PLANAR
  2955. float diff[XYZ] = {
  2956. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  2957. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  2958. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  2959. };
  2960. SERIAL_ECHOPGM("ABL Adjustment X");
  2961. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  2962. SERIAL_ECHO(diff[X_AXIS]);
  2963. SERIAL_ECHOPGM(" Y");
  2964. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  2965. SERIAL_ECHO(diff[Y_AXIS]);
  2966. SERIAL_ECHOPGM(" Z");
  2967. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  2968. SERIAL_ECHO(diff[Z_AXIS]);
  2969. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2970. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  2971. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2972. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  2973. #endif
  2974. }
  2975. else
  2976. SERIAL_ECHOLNPGM(" (disabled)");
  2977. SERIAL_EOL;
  2978. #elif ENABLED(MESH_BED_LEVELING)
  2979. SERIAL_ECHOPGM("Mesh Bed Leveling");
  2980. if (leveling_is_active()) {
  2981. float lz = current_position[Z_AXIS];
  2982. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  2983. SERIAL_ECHOLNPGM(" (enabled)");
  2984. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  2985. }
  2986. else
  2987. SERIAL_ECHOPGM(" (disabled)");
  2988. SERIAL_EOL;
  2989. #endif // MESH_BED_LEVELING
  2990. }
  2991. #endif // DEBUG_LEVELING_FEATURE
  2992. #if ENABLED(DELTA)
  2993. /**
  2994. * A delta can only safely home all axes at the same time
  2995. * This is like quick_home_xy() but for 3 towers.
  2996. */
  2997. inline void home_delta() {
  2998. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2999. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3000. #endif
  3001. // Init the current position of all carriages to 0,0,0
  3002. ZERO(current_position);
  3003. sync_plan_position();
  3004. // Move all carriages together linearly until an endstop is hit.
  3005. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3006. feedrate_mm_s = homing_feedrate_mm_s[X_AXIS];
  3007. line_to_current_position();
  3008. stepper.synchronize();
  3009. endstops.hit_on_purpose(); // clear endstop hit flags
  3010. // At least one carriage has reached the top.
  3011. // Now re-home each carriage separately.
  3012. HOMEAXIS(A);
  3013. HOMEAXIS(B);
  3014. HOMEAXIS(C);
  3015. // Set all carriages to their home positions
  3016. // Do this here all at once for Delta, because
  3017. // XYZ isn't ABC. Applying this per-tower would
  3018. // give the impression that they are the same.
  3019. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3020. SYNC_PLAN_POSITION_KINEMATIC();
  3021. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3022. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3023. #endif
  3024. }
  3025. #endif // DELTA
  3026. #if ENABLED(Z_SAFE_HOMING)
  3027. inline void home_z_safely() {
  3028. // Disallow Z homing if X or Y are unknown
  3029. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3030. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3031. SERIAL_ECHO_START;
  3032. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3033. return;
  3034. }
  3035. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3036. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3037. #endif
  3038. SYNC_PLAN_POSITION_KINEMATIC();
  3039. /**
  3040. * Move the Z probe (or just the nozzle) to the safe homing point
  3041. */
  3042. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3043. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3044. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3045. #if HOMING_Z_WITH_PROBE
  3046. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3047. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3048. #endif
  3049. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3050. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3051. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3052. #endif
  3053. // This causes the carriage on Dual X to unpark
  3054. #if ENABLED(DUAL_X_CARRIAGE)
  3055. active_extruder_parked = false;
  3056. #endif
  3057. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3058. HOMEAXIS(Z);
  3059. }
  3060. else {
  3061. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3062. SERIAL_ECHO_START;
  3063. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3064. }
  3065. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3066. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3067. #endif
  3068. }
  3069. #endif // Z_SAFE_HOMING
  3070. #if ENABLED(PROBE_MANUALLY)
  3071. bool g29_in_progress = false;
  3072. #else
  3073. constexpr bool g29_in_progress = false;
  3074. #endif
  3075. /**
  3076. * G28: Home all axes according to settings
  3077. *
  3078. * Parameters
  3079. *
  3080. * None Home to all axes with no parameters.
  3081. * With QUICK_HOME enabled XY will home together, then Z.
  3082. *
  3083. * Cartesian parameters
  3084. *
  3085. * X Home to the X endstop
  3086. * Y Home to the Y endstop
  3087. * Z Home to the Z endstop
  3088. *
  3089. */
  3090. inline void gcode_G28(const bool always_home_all) {
  3091. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3092. if (DEBUGGING(LEVELING)) {
  3093. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3094. log_machine_info();
  3095. }
  3096. #endif
  3097. // Wait for planner moves to finish!
  3098. stepper.synchronize();
  3099. // Cancel the active G29 session
  3100. #if ENABLED(PROBE_MANUALLY)
  3101. g29_in_progress = false;
  3102. #endif
  3103. // Disable the leveling matrix before homing
  3104. #if HAS_LEVELING
  3105. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3106. const bool ubl_state_at_entry = leveling_is_active();
  3107. #endif
  3108. set_bed_leveling_enabled(false);
  3109. #endif
  3110. // Always home with tool 0 active
  3111. #if HOTENDS > 1
  3112. const uint8_t old_tool_index = active_extruder;
  3113. tool_change(0, 0, true);
  3114. #endif
  3115. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3116. extruder_duplication_enabled = false;
  3117. #endif
  3118. setup_for_endstop_or_probe_move();
  3119. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3120. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3121. #endif
  3122. endstops.enable(true); // Enable endstops for next homing move
  3123. #if ENABLED(DELTA)
  3124. home_delta();
  3125. #else // NOT DELTA
  3126. const bool homeX = always_home_all || parser.seen('X'),
  3127. homeY = always_home_all || parser.seen('Y'),
  3128. homeZ = always_home_all || parser.seen('Z'),
  3129. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3130. set_destination_to_current();
  3131. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3132. if (home_all || homeZ) {
  3133. HOMEAXIS(Z);
  3134. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3135. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3136. #endif
  3137. }
  3138. #else
  3139. if (home_all || homeX || homeY) {
  3140. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3141. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3142. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3143. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3144. if (DEBUGGING(LEVELING))
  3145. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3146. #endif
  3147. do_blocking_move_to_z(destination[Z_AXIS]);
  3148. }
  3149. }
  3150. #endif
  3151. #if ENABLED(QUICK_HOME)
  3152. if (home_all || (homeX && homeY)) quick_home_xy();
  3153. #endif
  3154. #if ENABLED(HOME_Y_BEFORE_X)
  3155. // Home Y
  3156. if (home_all || homeY) {
  3157. HOMEAXIS(Y);
  3158. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3159. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3160. #endif
  3161. }
  3162. #endif
  3163. // Home X
  3164. if (home_all || homeX) {
  3165. #if ENABLED(DUAL_X_CARRIAGE)
  3166. // Always home the 2nd (right) extruder first
  3167. active_extruder = 1;
  3168. HOMEAXIS(X);
  3169. // Remember this extruder's position for later tool change
  3170. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3171. // Home the 1st (left) extruder
  3172. active_extruder = 0;
  3173. HOMEAXIS(X);
  3174. // Consider the active extruder to be parked
  3175. COPY(raised_parked_position, current_position);
  3176. delayed_move_time = 0;
  3177. active_extruder_parked = true;
  3178. #else
  3179. HOMEAXIS(X);
  3180. #endif
  3181. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3182. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3183. #endif
  3184. }
  3185. #if DISABLED(HOME_Y_BEFORE_X)
  3186. // Home Y
  3187. if (home_all || homeY) {
  3188. HOMEAXIS(Y);
  3189. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3190. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3191. #endif
  3192. }
  3193. #endif
  3194. // Home Z last if homing towards the bed
  3195. #if Z_HOME_DIR < 0
  3196. if (home_all || homeZ) {
  3197. #if ENABLED(Z_SAFE_HOMING)
  3198. home_z_safely();
  3199. #else
  3200. HOMEAXIS(Z);
  3201. #endif
  3202. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3203. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3204. #endif
  3205. } // home_all || homeZ
  3206. #endif // Z_HOME_DIR < 0
  3207. SYNC_PLAN_POSITION_KINEMATIC();
  3208. #endif // !DELTA (gcode_G28)
  3209. endstops.not_homing();
  3210. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3211. // move to a height where we can use the full xy-area
  3212. do_blocking_move_to_z(delta_clip_start_height);
  3213. #endif
  3214. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3215. set_bed_leveling_enabled(ubl_state_at_entry);
  3216. #endif
  3217. clean_up_after_endstop_or_probe_move();
  3218. // Restore the active tool after homing
  3219. #if HOTENDS > 1
  3220. tool_change(old_tool_index, 0, true);
  3221. #endif
  3222. lcd_refresh();
  3223. report_current_position();
  3224. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3225. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3226. #endif
  3227. } // G28
  3228. void home_all_axes() { gcode_G28(true); }
  3229. #if HAS_PROBING_PROCEDURE
  3230. void out_of_range_error(const char* p_edge) {
  3231. SERIAL_PROTOCOLPGM("?Probe ");
  3232. serialprintPGM(p_edge);
  3233. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3234. }
  3235. #endif
  3236. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3237. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3238. extern bool lcd_wait_for_move;
  3239. #endif
  3240. inline void _manual_goto_xy(const float &x, const float &y) {
  3241. const float old_feedrate_mm_s = feedrate_mm_s;
  3242. #if MANUAL_PROBE_HEIGHT > 0
  3243. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3244. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3245. line_to_current_position();
  3246. #endif
  3247. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3248. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3249. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3250. line_to_current_position();
  3251. #if MANUAL_PROBE_HEIGHT > 0
  3252. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3253. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3254. line_to_current_position();
  3255. #endif
  3256. feedrate_mm_s = old_feedrate_mm_s;
  3257. stepper.synchronize();
  3258. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3259. lcd_wait_for_move = false;
  3260. #endif
  3261. }
  3262. #endif
  3263. #if ENABLED(MESH_BED_LEVELING)
  3264. // Save 130 bytes with non-duplication of PSTR
  3265. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3266. void mbl_mesh_report() {
  3267. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3268. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3269. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3270. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3271. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3272. );
  3273. }
  3274. void mesh_probing_done() {
  3275. mbl.set_has_mesh(true);
  3276. home_all_axes();
  3277. set_bed_leveling_enabled(true);
  3278. #if ENABLED(MESH_G28_REST_ORIGIN)
  3279. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3280. set_destination_to_current();
  3281. line_to_destination(homing_feedrate_mm_s[Z_AXIS]);
  3282. stepper.synchronize();
  3283. #endif
  3284. }
  3285. /**
  3286. * G29: Mesh-based Z probe, probes a grid and produces a
  3287. * mesh to compensate for variable bed height
  3288. *
  3289. * Parameters With MESH_BED_LEVELING:
  3290. *
  3291. * S0 Produce a mesh report
  3292. * S1 Start probing mesh points
  3293. * S2 Probe the next mesh point
  3294. * S3 Xn Yn Zn.nn Manually modify a single point
  3295. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3296. * S5 Reset and disable mesh
  3297. *
  3298. * The S0 report the points as below
  3299. *
  3300. * +----> X-axis 1-n
  3301. * |
  3302. * |
  3303. * v Y-axis 1-n
  3304. *
  3305. */
  3306. inline void gcode_G29() {
  3307. static int mbl_probe_index = -1;
  3308. #if HAS_SOFTWARE_ENDSTOPS
  3309. static bool enable_soft_endstops;
  3310. #endif
  3311. const MeshLevelingState state = parser.seen('S') ? (MeshLevelingState)parser.value_byte() : MeshReport;
  3312. if (!WITHIN(state, 0, 5)) {
  3313. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3314. return;
  3315. }
  3316. int8_t px, py;
  3317. switch (state) {
  3318. case MeshReport:
  3319. if (leveling_is_valid()) {
  3320. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3321. mbl_mesh_report();
  3322. }
  3323. else
  3324. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3325. break;
  3326. case MeshStart:
  3327. mbl.reset();
  3328. mbl_probe_index = 0;
  3329. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3330. break;
  3331. case MeshNext:
  3332. if (mbl_probe_index < 0) {
  3333. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3334. return;
  3335. }
  3336. // For each G29 S2...
  3337. if (mbl_probe_index == 0) {
  3338. #if HAS_SOFTWARE_ENDSTOPS
  3339. // For the initial G29 S2 save software endstop state
  3340. enable_soft_endstops = soft_endstops_enabled;
  3341. #endif
  3342. }
  3343. else {
  3344. // For G29 S2 after adjusting Z.
  3345. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3346. #if HAS_SOFTWARE_ENDSTOPS
  3347. soft_endstops_enabled = enable_soft_endstops;
  3348. #endif
  3349. }
  3350. // If there's another point to sample, move there with optional lift.
  3351. if (mbl_probe_index < GRID_MAX_POINTS) {
  3352. mbl.zigzag(mbl_probe_index, px, py);
  3353. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3354. #if HAS_SOFTWARE_ENDSTOPS
  3355. // Disable software endstops to allow manual adjustment
  3356. // If G29 is not completed, they will not be re-enabled
  3357. soft_endstops_enabled = false;
  3358. #endif
  3359. mbl_probe_index++;
  3360. }
  3361. else {
  3362. // One last "return to the bed" (as originally coded) at completion
  3363. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3364. line_to_current_position();
  3365. stepper.synchronize();
  3366. // After recording the last point, activate home and activate
  3367. mbl_probe_index = -1;
  3368. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3369. BUZZ(100, 659);
  3370. BUZZ(100, 698);
  3371. mesh_probing_done();
  3372. }
  3373. break;
  3374. case MeshSet:
  3375. if (parser.seen('X')) {
  3376. px = parser.value_int() - 1;
  3377. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3378. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3379. return;
  3380. }
  3381. }
  3382. else {
  3383. SERIAL_CHAR('X'); echo_not_entered();
  3384. return;
  3385. }
  3386. if (parser.seen('Y')) {
  3387. py = parser.value_int() - 1;
  3388. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3389. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3390. return;
  3391. }
  3392. }
  3393. else {
  3394. SERIAL_CHAR('Y'); echo_not_entered();
  3395. return;
  3396. }
  3397. if (parser.seen('Z')) {
  3398. mbl.z_values[px][py] = parser.value_linear_units();
  3399. }
  3400. else {
  3401. SERIAL_CHAR('Z'); echo_not_entered();
  3402. return;
  3403. }
  3404. break;
  3405. case MeshSetZOffset:
  3406. if (parser.seen('Z')) {
  3407. mbl.z_offset = parser.value_linear_units();
  3408. }
  3409. else {
  3410. SERIAL_CHAR('Z'); echo_not_entered();
  3411. return;
  3412. }
  3413. break;
  3414. case MeshReset:
  3415. reset_bed_level();
  3416. break;
  3417. } // switch(state)
  3418. report_current_position();
  3419. }
  3420. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3421. #if ABL_GRID
  3422. #if ENABLED(PROBE_Y_FIRST)
  3423. #define PR_OUTER_VAR xCount
  3424. #define PR_OUTER_END abl_grid_points_x
  3425. #define PR_INNER_VAR yCount
  3426. #define PR_INNER_END abl_grid_points_y
  3427. #else
  3428. #define PR_OUTER_VAR yCount
  3429. #define PR_OUTER_END abl_grid_points_y
  3430. #define PR_INNER_VAR xCount
  3431. #define PR_INNER_END abl_grid_points_x
  3432. #endif
  3433. #endif
  3434. /**
  3435. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3436. * Will fail if the printer has not been homed with G28.
  3437. *
  3438. * Enhanced G29 Auto Bed Leveling Probe Routine
  3439. *
  3440. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3441. * or alter the bed level data. Useful to check the topology
  3442. * after a first run of G29.
  3443. *
  3444. * J Jettison current bed leveling data
  3445. *
  3446. * V Set the verbose level (0-4). Example: "G29 V3"
  3447. *
  3448. * Parameters With LINEAR leveling only:
  3449. *
  3450. * P Set the size of the grid that will be probed (P x P points).
  3451. * Example: "G29 P4"
  3452. *
  3453. * X Set the X size of the grid that will be probed (X x Y points).
  3454. * Example: "G29 X7 Y5"
  3455. *
  3456. * Y Set the Y size of the grid that will be probed (X x Y points).
  3457. *
  3458. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3459. * This is useful for manual bed leveling and finding flaws in the bed (to
  3460. * assist with part placement).
  3461. * Not supported by non-linear delta printer bed leveling.
  3462. *
  3463. * Parameters With LINEAR and BILINEAR leveling only:
  3464. *
  3465. * S Set the XY travel speed between probe points (in units/min)
  3466. *
  3467. * F Set the Front limit of the probing grid
  3468. * B Set the Back limit of the probing grid
  3469. * L Set the Left limit of the probing grid
  3470. * R Set the Right limit of the probing grid
  3471. *
  3472. * Parameters with DEBUG_LEVELING_FEATURE only:
  3473. *
  3474. * C Make a totally fake grid with no actual probing.
  3475. * For use in testing when no probing is possible.
  3476. *
  3477. * Parameters with BILINEAR leveling only:
  3478. *
  3479. * Z Supply an additional Z probe offset
  3480. *
  3481. * Extra parameters with PROBE_MANUALLY:
  3482. *
  3483. * To do manual probing simply repeat G29 until the procedure is complete.
  3484. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3485. *
  3486. * Q Query leveling and G29 state
  3487. *
  3488. * A Abort current leveling procedure
  3489. *
  3490. * W Write a mesh point. (Ignored during leveling.)
  3491. * X Required X for mesh point
  3492. * Y Required Y for mesh point
  3493. * Z Required Z for mesh point
  3494. *
  3495. * Without PROBE_MANUALLY:
  3496. *
  3497. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3498. * Include "E" to engage/disengage the Z probe for each sample.
  3499. * There's no extra effect if you have a fixed Z probe.
  3500. *
  3501. */
  3502. inline void gcode_G29() {
  3503. // G29 Q is also available if debugging
  3504. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3505. const bool query = parser.seen('Q');
  3506. const uint8_t old_debug_flags = marlin_debug_flags;
  3507. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3508. if (DEBUGGING(LEVELING)) {
  3509. DEBUG_POS(">>> gcode_G29", current_position);
  3510. log_machine_info();
  3511. }
  3512. marlin_debug_flags = old_debug_flags;
  3513. #if DISABLED(PROBE_MANUALLY)
  3514. if (query) return;
  3515. #endif
  3516. #endif
  3517. #if ENABLED(PROBE_MANUALLY)
  3518. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q'), no_action = seenA || seenQ;
  3519. #endif
  3520. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3521. const bool faux = parser.seen('C') && parser.value_bool();
  3522. #elif ENABLED(PROBE_MANUALLY)
  3523. const bool faux = no_action;
  3524. #else
  3525. bool constexpr faux = false;
  3526. #endif
  3527. // Don't allow auto-leveling without homing first
  3528. if (axis_unhomed_error()) return;
  3529. // Define local vars 'static' for manual probing, 'auto' otherwise
  3530. #if ENABLED(PROBE_MANUALLY)
  3531. #define ABL_VAR static
  3532. #else
  3533. #define ABL_VAR
  3534. #endif
  3535. ABL_VAR int verbose_level;
  3536. ABL_VAR float xProbe, yProbe, measured_z;
  3537. ABL_VAR bool dryrun, abl_should_enable;
  3538. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3539. ABL_VAR int abl_probe_index;
  3540. #endif
  3541. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3542. ABL_VAR bool enable_soft_endstops = true;
  3543. #endif
  3544. #if ABL_GRID
  3545. #if ENABLED(PROBE_MANUALLY)
  3546. ABL_VAR uint8_t PR_OUTER_VAR;
  3547. ABL_VAR int8_t PR_INNER_VAR;
  3548. #endif
  3549. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3550. ABL_VAR float xGridSpacing, yGridSpacing;
  3551. #if ABL_PLANAR
  3552. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3553. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3554. ABL_VAR bool do_topography_map;
  3555. #else // 3-point
  3556. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3557. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3558. #endif
  3559. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3560. #if ABL_PLANAR
  3561. ABL_VAR int abl2;
  3562. #else // 3-point
  3563. int constexpr abl2 = GRID_MAX_POINTS;
  3564. #endif
  3565. #endif
  3566. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3567. ABL_VAR float zoffset;
  3568. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3569. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3570. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3571. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3572. mean;
  3573. #endif
  3574. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3575. // Probe at 3 arbitrary points
  3576. ABL_VAR vector_3 points[3] = {
  3577. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3578. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3579. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3580. };
  3581. #endif // AUTO_BED_LEVELING_3POINT
  3582. /**
  3583. * On the initial G29 fetch command parameters.
  3584. */
  3585. if (!g29_in_progress) {
  3586. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3587. abl_probe_index = -1;
  3588. #endif
  3589. abl_should_enable = leveling_is_active();
  3590. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3591. if (parser.seen('W')) {
  3592. if (!leveling_is_valid()) {
  3593. SERIAL_ERROR_START;
  3594. SERIAL_ERRORLNPGM("No bilinear grid");
  3595. return;
  3596. }
  3597. const float z = parser.seen('Z') && parser.has_value() ? parser.value_float() : NAN;
  3598. if (!isnan(z) || !WITHIN(z, -10, 10)) {
  3599. SERIAL_ERROR_START;
  3600. SERIAL_ERRORLNPGM("Bad Z value");
  3601. return;
  3602. }
  3603. const float x = parser.seen('X') && parser.has_value() ? parser.value_float() : NAN,
  3604. y = parser.seen('Y') && parser.has_value() ? parser.value_float() : NAN;
  3605. int8_t i = parser.seen('I') && parser.has_value() ? parser.value_byte() : -1,
  3606. j = parser.seen('J') && parser.has_value() ? parser.value_byte() : -1;
  3607. if (!isnan(x) && !isnan(y)) {
  3608. // Get nearest i / j from x / y
  3609. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3610. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3611. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3612. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3613. }
  3614. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3615. set_bed_leveling_enabled(false);
  3616. z_values[i][j] = z;
  3617. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3618. bed_level_virt_interpolate();
  3619. #endif
  3620. set_bed_leveling_enabled(abl_should_enable);
  3621. }
  3622. return;
  3623. } // parser.seen('W')
  3624. #endif
  3625. #if HAS_LEVELING
  3626. // Jettison bed leveling data
  3627. if (parser.seen('J')) {
  3628. reset_bed_level();
  3629. return;
  3630. }
  3631. #endif
  3632. verbose_level = parser.seen('V') && parser.has_value() ? parser.value_int() : 0;
  3633. if (!WITHIN(verbose_level, 0, 4)) {
  3634. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3635. return;
  3636. }
  3637. dryrun = (parser.seen('D') && parser.value_bool())
  3638. #if ENABLED(PROBE_MANUALLY)
  3639. || no_action
  3640. #endif
  3641. ;
  3642. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3643. do_topography_map = verbose_level > 2 || parser.seen('T');
  3644. // X and Y specify points in each direction, overriding the default
  3645. // These values may be saved with the completed mesh
  3646. abl_grid_points_x = parser.seen('X') ? parser.value_int() : GRID_MAX_POINTS_X;
  3647. abl_grid_points_y = parser.seen('Y') ? parser.value_int() : GRID_MAX_POINTS_Y;
  3648. if (parser.seen('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3649. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3650. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3651. return;
  3652. }
  3653. abl2 = abl_grid_points_x * abl_grid_points_y;
  3654. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3655. zoffset = parser.seen('Z') ? parser.value_linear_units() : 0;
  3656. #endif
  3657. #if ABL_GRID
  3658. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.seen('S') ? parser.value_linear_units() : XY_PROBE_SPEED);
  3659. left_probe_bed_position = parser.seen('L') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION);
  3660. right_probe_bed_position = parser.seen('R') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION);
  3661. front_probe_bed_position = parser.seen('F') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION);
  3662. back_probe_bed_position = parser.seen('B') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION);
  3663. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3664. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3665. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3666. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3667. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3668. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3669. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3670. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3671. if (left_out || right_out || front_out || back_out) {
  3672. if (left_out) {
  3673. out_of_range_error(PSTR("(L)eft"));
  3674. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3675. }
  3676. if (right_out) {
  3677. out_of_range_error(PSTR("(R)ight"));
  3678. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3679. }
  3680. if (front_out) {
  3681. out_of_range_error(PSTR("(F)ront"));
  3682. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3683. }
  3684. if (back_out) {
  3685. out_of_range_error(PSTR("(B)ack"));
  3686. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3687. }
  3688. return;
  3689. }
  3690. // probe at the points of a lattice grid
  3691. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3692. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3693. #endif // ABL_GRID
  3694. if (verbose_level > 0) {
  3695. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3696. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3697. }
  3698. stepper.synchronize();
  3699. // Disable auto bed leveling during G29
  3700. planner.abl_enabled = false;
  3701. if (!dryrun) {
  3702. // Re-orient the current position without leveling
  3703. // based on where the steppers are positioned.
  3704. set_current_from_steppers_for_axis(ALL_AXES);
  3705. // Sync the planner to where the steppers stopped
  3706. SYNC_PLAN_POSITION_KINEMATIC();
  3707. }
  3708. if (!faux) setup_for_endstop_or_probe_move();
  3709. //xProbe = yProbe = measured_z = 0;
  3710. #if HAS_BED_PROBE
  3711. // Deploy the probe. Probe will raise if needed.
  3712. if (DEPLOY_PROBE()) {
  3713. planner.abl_enabled = abl_should_enable;
  3714. return;
  3715. }
  3716. #endif
  3717. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3718. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3719. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3720. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3721. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3722. ) {
  3723. if (dryrun) {
  3724. // Before reset bed level, re-enable to correct the position
  3725. planner.abl_enabled = abl_should_enable;
  3726. }
  3727. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3728. reset_bed_level();
  3729. // Initialize a grid with the given dimensions
  3730. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3731. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3732. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3733. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3734. // Can't re-enable (on error) until the new grid is written
  3735. abl_should_enable = false;
  3736. }
  3737. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3738. mean = 0.0;
  3739. #endif // AUTO_BED_LEVELING_LINEAR
  3740. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3741. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3742. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3743. #endif
  3744. // Probe at 3 arbitrary points
  3745. points[0].z = points[1].z = points[2].z = 0;
  3746. #endif // AUTO_BED_LEVELING_3POINT
  3747. } // !g29_in_progress
  3748. #if ENABLED(PROBE_MANUALLY)
  3749. // For manual probing, get the next index to probe now.
  3750. // On the first probe this will be incremented to 0.
  3751. if (!no_action) {
  3752. ++abl_probe_index;
  3753. g29_in_progress = true;
  3754. }
  3755. // Abort current G29 procedure, go back to idle state
  3756. if (seenA && g29_in_progress) {
  3757. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3758. #if HAS_SOFTWARE_ENDSTOPS
  3759. soft_endstops_enabled = enable_soft_endstops;
  3760. #endif
  3761. planner.abl_enabled = abl_should_enable;
  3762. g29_in_progress = false;
  3763. #if ENABLED(LCD_BED_LEVELING)
  3764. lcd_wait_for_move = false;
  3765. #endif
  3766. }
  3767. // Query G29 status
  3768. if (verbose_level || seenQ) {
  3769. SERIAL_PROTOCOLPGM("Manual G29 ");
  3770. if (g29_in_progress) {
  3771. SERIAL_PROTOCOLPAIR("point ", min(abl_probe_index + 1, abl2));
  3772. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3773. }
  3774. else
  3775. SERIAL_PROTOCOLLNPGM("idle");
  3776. }
  3777. if (no_action) return;
  3778. if (abl_probe_index == 0) {
  3779. // For the initial G29 save software endstop state
  3780. #if HAS_SOFTWARE_ENDSTOPS
  3781. enable_soft_endstops = soft_endstops_enabled;
  3782. #endif
  3783. }
  3784. else {
  3785. // For G29 after adjusting Z.
  3786. // Save the previous Z before going to the next point
  3787. measured_z = current_position[Z_AXIS];
  3788. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3789. mean += measured_z;
  3790. eqnBVector[abl_probe_index] = measured_z;
  3791. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3792. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3793. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3794. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3795. z_values[xCount][yCount] = measured_z + zoffset;
  3796. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3797. if (DEBUGGING(LEVELING)) {
  3798. SERIAL_PROTOCOLPAIR("Save X", xCount);
  3799. SERIAL_PROTOCOLPAIR(" Y", yCount);
  3800. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  3801. }
  3802. #endif
  3803. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3804. points[i].z = measured_z;
  3805. #endif
  3806. }
  3807. //
  3808. // If there's another point to sample, move there with optional lift.
  3809. //
  3810. #if ABL_GRID
  3811. // Skip any unreachable points
  3812. while (abl_probe_index < abl2) {
  3813. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3814. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3815. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3816. // Probe in reverse order for every other row/column
  3817. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3818. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3819. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3820. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3821. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3822. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3823. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3824. indexIntoAB[xCount][yCount] = abl_probe_index;
  3825. #endif
  3826. // Keep looping till a reachable point is found
  3827. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3828. ++abl_probe_index;
  3829. }
  3830. // Is there a next point to move to?
  3831. if (abl_probe_index < abl2) {
  3832. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3833. #if HAS_SOFTWARE_ENDSTOPS
  3834. // Disable software endstops to allow manual adjustment
  3835. // If G29 is not completed, they will not be re-enabled
  3836. soft_endstops_enabled = false;
  3837. #endif
  3838. return;
  3839. }
  3840. else {
  3841. // Leveling done! Fall through to G29 finishing code below
  3842. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3843. // Re-enable software endstops, if needed
  3844. #if HAS_SOFTWARE_ENDSTOPS
  3845. soft_endstops_enabled = enable_soft_endstops;
  3846. #endif
  3847. }
  3848. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3849. // Probe at 3 arbitrary points
  3850. if (abl_probe_index < 3) {
  3851. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3852. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3853. #if HAS_SOFTWARE_ENDSTOPS
  3854. // Disable software endstops to allow manual adjustment
  3855. // If G29 is not completed, they will not be re-enabled
  3856. soft_endstops_enabled = false;
  3857. #endif
  3858. return;
  3859. }
  3860. else {
  3861. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3862. // Re-enable software endstops, if needed
  3863. #if HAS_SOFTWARE_ENDSTOPS
  3864. soft_endstops_enabled = enable_soft_endstops;
  3865. #endif
  3866. if (!dryrun) {
  3867. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3868. if (planeNormal.z < 0) {
  3869. planeNormal.x *= -1;
  3870. planeNormal.y *= -1;
  3871. planeNormal.z *= -1;
  3872. }
  3873. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3874. // Can't re-enable (on error) until the new grid is written
  3875. abl_should_enable = false;
  3876. }
  3877. }
  3878. #endif // AUTO_BED_LEVELING_3POINT
  3879. #else // !PROBE_MANUALLY
  3880. const bool stow_probe_after_each = parser.seen('E');
  3881. #if ABL_GRID
  3882. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3883. // Outer loop is Y with PROBE_Y_FIRST disabled
  3884. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  3885. int8_t inStart, inStop, inInc;
  3886. if (zig) { // away from origin
  3887. inStart = 0;
  3888. inStop = PR_INNER_END;
  3889. inInc = 1;
  3890. }
  3891. else { // towards origin
  3892. inStart = PR_INNER_END - 1;
  3893. inStop = -1;
  3894. inInc = -1;
  3895. }
  3896. zig ^= true; // zag
  3897. // Inner loop is Y with PROBE_Y_FIRST enabled
  3898. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  3899. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  3900. yBase = front_probe_bed_position + yGridSpacing * yCount;
  3901. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3902. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3903. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3904. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  3905. #endif
  3906. #if IS_KINEMATIC
  3907. // Avoid probing outside the round or hexagonal area
  3908. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  3909. #endif
  3910. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3911. if (isnan(measured_z)) {
  3912. planner.abl_enabled = abl_should_enable;
  3913. return;
  3914. }
  3915. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3916. mean += measured_z;
  3917. eqnBVector[abl_probe_index] = measured_z;
  3918. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3919. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3920. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3921. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3922. z_values[xCount][yCount] = measured_z + zoffset;
  3923. #endif
  3924. abl_should_enable = false;
  3925. idle();
  3926. } // inner
  3927. } // outer
  3928. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3929. // Probe at 3 arbitrary points
  3930. for (uint8_t i = 0; i < 3; ++i) {
  3931. // Retain the last probe position
  3932. xProbe = LOGICAL_X_POSITION(points[i].x);
  3933. yProbe = LOGICAL_Y_POSITION(points[i].y);
  3934. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3935. if (isnan(measured_z)) {
  3936. planner.abl_enabled = abl_should_enable;
  3937. return;
  3938. }
  3939. points[i].z = measured_z;
  3940. }
  3941. if (!dryrun) {
  3942. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3943. if (planeNormal.z < 0) {
  3944. planeNormal.x *= -1;
  3945. planeNormal.y *= -1;
  3946. planeNormal.z *= -1;
  3947. }
  3948. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3949. // Can't re-enable (on error) until the new grid is written
  3950. abl_should_enable = false;
  3951. }
  3952. #endif // AUTO_BED_LEVELING_3POINT
  3953. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  3954. if (STOW_PROBE()) {
  3955. planner.abl_enabled = abl_should_enable;
  3956. return;
  3957. }
  3958. #endif // !PROBE_MANUALLY
  3959. //
  3960. // G29 Finishing Code
  3961. //
  3962. // Unless this is a dry run, auto bed leveling will
  3963. // definitely be enabled after this point.
  3964. //
  3965. // If code above wants to continue leveling, it should
  3966. // return or loop before this point.
  3967. //
  3968. // Restore state after probing
  3969. if (!faux) clean_up_after_endstop_or_probe_move();
  3970. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3971. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  3972. #endif
  3973. #if ENABLED(PROBE_MANUALLY)
  3974. g29_in_progress = false;
  3975. #if ENABLED(LCD_BED_LEVELING)
  3976. lcd_wait_for_move = false;
  3977. #endif
  3978. #endif
  3979. // Calculate leveling, print reports, correct the position
  3980. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3981. if (!dryrun) extrapolate_unprobed_bed_level();
  3982. print_bilinear_leveling_grid();
  3983. refresh_bed_level();
  3984. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3985. bed_level_virt_print();
  3986. #endif
  3987. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3988. // For LINEAR leveling calculate matrix, print reports, correct the position
  3989. /**
  3990. * solve the plane equation ax + by + d = z
  3991. * A is the matrix with rows [x y 1] for all the probed points
  3992. * B is the vector of the Z positions
  3993. * the normal vector to the plane is formed by the coefficients of the
  3994. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  3995. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3996. */
  3997. float plane_equation_coefficients[3];
  3998. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  3999. mean /= abl2;
  4000. if (verbose_level) {
  4001. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4002. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4003. SERIAL_PROTOCOLPGM(" b: ");
  4004. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4005. SERIAL_PROTOCOLPGM(" d: ");
  4006. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4007. SERIAL_EOL;
  4008. if (verbose_level > 2) {
  4009. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4010. SERIAL_PROTOCOL_F(mean, 8);
  4011. SERIAL_EOL;
  4012. }
  4013. }
  4014. // Create the matrix but don't correct the position yet
  4015. if (!dryrun) {
  4016. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4017. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  4018. );
  4019. }
  4020. // Show the Topography map if enabled
  4021. if (do_topography_map) {
  4022. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4023. " +--- BACK --+\n"
  4024. " | |\n"
  4025. " L | (+) | R\n"
  4026. " E | | I\n"
  4027. " F | (-) N (+) | G\n"
  4028. " T | | H\n"
  4029. " | (-) | T\n"
  4030. " | |\n"
  4031. " O-- FRONT --+\n"
  4032. " (0,0)");
  4033. float min_diff = 999;
  4034. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4035. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4036. int ind = indexIntoAB[xx][yy];
  4037. float diff = eqnBVector[ind] - mean,
  4038. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4039. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4040. z_tmp = 0;
  4041. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4042. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4043. if (diff >= 0.0)
  4044. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4045. else
  4046. SERIAL_PROTOCOLCHAR(' ');
  4047. SERIAL_PROTOCOL_F(diff, 5);
  4048. } // xx
  4049. SERIAL_EOL;
  4050. } // yy
  4051. SERIAL_EOL;
  4052. if (verbose_level > 3) {
  4053. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4054. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4055. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4056. int ind = indexIntoAB[xx][yy];
  4057. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4058. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4059. z_tmp = 0;
  4060. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4061. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4062. if (diff >= 0.0)
  4063. SERIAL_PROTOCOLPGM(" +");
  4064. // Include + for column alignment
  4065. else
  4066. SERIAL_PROTOCOLCHAR(' ');
  4067. SERIAL_PROTOCOL_F(diff, 5);
  4068. } // xx
  4069. SERIAL_EOL;
  4070. } // yy
  4071. SERIAL_EOL;
  4072. }
  4073. } //do_topography_map
  4074. #endif // AUTO_BED_LEVELING_LINEAR
  4075. #if ABL_PLANAR
  4076. // For LINEAR and 3POINT leveling correct the current position
  4077. if (verbose_level > 0)
  4078. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4079. if (!dryrun) {
  4080. //
  4081. // Correct the current XYZ position based on the tilted plane.
  4082. //
  4083. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4084. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4085. #endif
  4086. float converted[XYZ];
  4087. COPY(converted, current_position);
  4088. planner.abl_enabled = true;
  4089. planner.unapply_leveling(converted); // use conversion machinery
  4090. planner.abl_enabled = false;
  4091. // Use the last measured distance to the bed, if possible
  4092. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4093. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4094. ) {
  4095. float simple_z = current_position[Z_AXIS] - measured_z;
  4096. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4097. if (DEBUGGING(LEVELING)) {
  4098. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4099. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4100. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4101. }
  4102. #endif
  4103. converted[Z_AXIS] = simple_z;
  4104. }
  4105. // The rotated XY and corrected Z are now current_position
  4106. COPY(current_position, converted);
  4107. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4108. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4109. #endif
  4110. }
  4111. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4112. if (!dryrun) {
  4113. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4114. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4115. #endif
  4116. // Unapply the offset because it is going to be immediately applied
  4117. // and cause compensation movement in Z
  4118. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4119. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4120. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4121. #endif
  4122. }
  4123. #endif // ABL_PLANAR
  4124. #ifdef Z_PROBE_END_SCRIPT
  4125. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4126. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4127. #endif
  4128. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4129. stepper.synchronize();
  4130. #endif
  4131. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4132. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4133. #endif
  4134. report_current_position();
  4135. KEEPALIVE_STATE(IN_HANDLER);
  4136. // Auto Bed Leveling is complete! Enable if possible.
  4137. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4138. if (planner.abl_enabled)
  4139. SYNC_PLAN_POSITION_KINEMATIC();
  4140. }
  4141. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4142. #if HAS_BED_PROBE
  4143. /**
  4144. * G30: Do a single Z probe at the current XY
  4145. *
  4146. * Parameters:
  4147. *
  4148. * X Probe X position (default current X)
  4149. * Y Probe Y position (default current Y)
  4150. * S0 Leave the probe deployed
  4151. */
  4152. inline void gcode_G30() {
  4153. const float xpos = parser.seen('X') ? parser.value_linear_units() : current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  4154. ypos = parser.seen('Y') ? parser.value_linear_units() : current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4155. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4156. // Disable leveling so the planner won't mess with us
  4157. #if HAS_LEVELING
  4158. set_bed_leveling_enabled(false);
  4159. #endif
  4160. setup_for_endstop_or_probe_move();
  4161. const float measured_z = probe_pt(xpos, ypos, !parser.seen('S') || parser.value_bool(), 1);
  4162. if (!isnan(measured_z)) {
  4163. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4164. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4165. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4166. }
  4167. clean_up_after_endstop_or_probe_move();
  4168. report_current_position();
  4169. }
  4170. #if ENABLED(Z_PROBE_SLED)
  4171. /**
  4172. * G31: Deploy the Z probe
  4173. */
  4174. inline void gcode_G31() { DEPLOY_PROBE(); }
  4175. /**
  4176. * G32: Stow the Z probe
  4177. */
  4178. inline void gcode_G32() { STOW_PROBE(); }
  4179. #endif // Z_PROBE_SLED
  4180. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4181. /**
  4182. * G33 - Delta '1-4-7-point' Auto-Calibration
  4183. * Calibrate height, endstops, delta radius, and tower angles.
  4184. *
  4185. * Parameters:
  4186. *
  4187. * Pn Number of probe points:
  4188. *
  4189. * P1 Probe center and set height only.
  4190. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4191. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4192. * P4-P7 Probe all positions at different locations and average them.
  4193. *
  4194. * T Don't calibrate tower angle corrections
  4195. *
  4196. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4197. *
  4198. * Vn Verbose level:
  4199. *
  4200. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4201. * V1 Report settings
  4202. * V2 Report settings and probe results
  4203. */
  4204. inline void gcode_G33() {
  4205. const int8_t probe_points = parser.seen('P') ? parser.value_int() : DELTA_CALIBRATION_DEFAULT_POINTS;
  4206. if (!WITHIN(probe_points, 1, 7)) {
  4207. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1 to 7).");
  4208. return;
  4209. }
  4210. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  4211. if (!WITHIN(verbose_level, 0, 2)) {
  4212. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4213. return;
  4214. }
  4215. const float calibration_precision = parser.seen('C') ? parser.value_float() : 0.0;
  4216. if (calibration_precision < 0) {
  4217. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4218. return;
  4219. }
  4220. const bool towers_set = !parser.seen('T'),
  4221. _1p_calibration = probe_points == 1,
  4222. _4p_calibration = probe_points == 2,
  4223. _4p_towers_points = _4p_calibration && towers_set,
  4224. _4p_opposite_points = _4p_calibration && !towers_set,
  4225. _7p_calibration = probe_points >= 3,
  4226. _7p_half_circle = probe_points == 3,
  4227. _7p_double_circle = probe_points == 5,
  4228. _7p_triple_circle = probe_points == 6,
  4229. _7p_quadruple_circle = probe_points == 7,
  4230. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4231. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4232. if (!_1p_calibration) { // test if the outer radius is reachable
  4233. const float circles = (_7p_quadruple_circle ? 1.5 :
  4234. _7p_triple_circle ? 1.0 :
  4235. _7p_double_circle ? 0.5 : 0),
  4236. radius = (1 + circles * 0.1) * delta_calibration_radius;
  4237. for (uint8_t axis = 1; axis < 13; ++axis) {
  4238. if (!position_is_reachable_by_probe_xy(cos(RADIANS(180 + 30 * axis)) * radius, sin(RADIANS(180 + 30 * axis)) * radius)) {
  4239. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4240. return;
  4241. }
  4242. }
  4243. }
  4244. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4245. stepper.synchronize();
  4246. #if HAS_LEVELING
  4247. reset_bed_level(); // After calibration bed-level data is no longer valid
  4248. #endif
  4249. #if HOTENDS > 1
  4250. const uint8_t old_tool_index = active_extruder;
  4251. tool_change(0, 0, true);
  4252. #endif
  4253. setup_for_endstop_or_probe_move();
  4254. endstops.enable(true);
  4255. home_delta();
  4256. endstops.not_homing();
  4257. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4258. float test_precision,
  4259. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4260. zero_std_dev_old = zero_std_dev,
  4261. e_old[XYZ] = {
  4262. endstop_adj[A_AXIS],
  4263. endstop_adj[B_AXIS],
  4264. endstop_adj[C_AXIS]
  4265. },
  4266. dr_old = delta_radius,
  4267. zh_old = home_offset[Z_AXIS],
  4268. alpha_old = delta_tower_angle_trim[A_AXIS],
  4269. beta_old = delta_tower_angle_trim[B_AXIS];
  4270. // print settings
  4271. SERIAL_PROTOCOLPGM("Checking... AC");
  4272. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4273. SERIAL_EOL;
  4274. LCD_MESSAGEPGM("Checking... AC"); // TODO: Make translatable string
  4275. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4276. if (!_1p_calibration) {
  4277. SERIAL_PROTOCOLPGM(" Ex:");
  4278. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4279. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4280. SERIAL_PROTOCOLPGM(" Ey:");
  4281. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4282. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4283. SERIAL_PROTOCOLPGM(" Ez:");
  4284. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4285. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4286. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4287. }
  4288. SERIAL_EOL;
  4289. if (_7p_calibration && towers_set) {
  4290. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4291. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4292. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4293. SERIAL_PROTOCOLPGM(" Ty:");
  4294. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4295. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4296. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4297. SERIAL_EOL;
  4298. }
  4299. #if ENABLED(Z_PROBE_SLED)
  4300. DEPLOY_PROBE();
  4301. #endif
  4302. int8_t iterations = 0;
  4303. home_offset[Z_AXIS] -= probe_pt(0.0, 0.0 , true, 1); // 1st probe to set height
  4304. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  4305. do {
  4306. float z_at_pt[13] = { 0.0 }, S1 = 0.0, S2 = 0.0;
  4307. int16_t N = 0;
  4308. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4309. iterations++;
  4310. // Probe the points
  4311. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4312. z_at_pt[0] += probe_pt(0.0, 0.0 , true, 1);
  4313. }
  4314. if (_7p_calibration) { // probe extra center points
  4315. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4316. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4317. z_at_pt[0] += probe_pt(cos(a) * r, sin(a) * r, true, 1); // TODO: Needs error handling
  4318. }
  4319. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4320. }
  4321. if (!_1p_calibration) { // probe the radius
  4322. bool zig_zag = true;
  4323. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4324. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4325. for (uint8_t axis = start; axis < 13; axis += step) {
  4326. const float offset_circles = _7p_quadruple_circle ? (zig_zag ? 1.5 : 1.0) :
  4327. _7p_triple_circle ? (zig_zag ? 1.0 : 0.5) :
  4328. _7p_double_circle ? (zig_zag ? 0.5 : 0.0) : 0;
  4329. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4330. const float a = RADIANS(180 + 30 * axis),
  4331. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4332. z_at_pt[axis] += probe_pt(cos(a) * r, sin(a) * r, true, 1); // TODO: Needs error handling
  4333. }
  4334. zig_zag = !zig_zag;
  4335. z_at_pt[axis] /= (2 * offset_circles + 1);
  4336. }
  4337. }
  4338. if (_7p_intermed_points) // average intermediates to tower and opposites
  4339. for (uint8_t axis = 1; axis <= 11; axis += 2)
  4340. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4341. S1 += z_at_pt[0];
  4342. S2 += sq(z_at_pt[0]);
  4343. N++;
  4344. if (!_1p_calibration) // std dev from zero plane
  4345. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4346. S1 += z_at_pt[axis];
  4347. S2 += sq(z_at_pt[axis]);
  4348. N++;
  4349. }
  4350. zero_std_dev_old = zero_std_dev;
  4351. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4352. if (iterations == 1) home_offset[Z_AXIS] = zh_old; // reset height after 1st probe change
  4353. // Solve matrices
  4354. if (zero_std_dev < test_precision && zero_std_dev > calibration_precision) {
  4355. COPY(e_old, endstop_adj);
  4356. dr_old = delta_radius;
  4357. zh_old = home_offset[Z_AXIS];
  4358. alpha_old = delta_tower_angle_trim[A_AXIS];
  4359. beta_old = delta_tower_angle_trim[B_AXIS];
  4360. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4361. const float r_diff = delta_radius - delta_calibration_radius,
  4362. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4363. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4364. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4365. #define ZP(N,I) ((N) * z_at_pt[I])
  4366. #define Z1000(I) ZP(1.00, I)
  4367. #define Z1050(I) ZP(h_factor, I)
  4368. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4369. #define Z0350(I) ZP(h_factor / 3.00, I)
  4370. #define Z0175(I) ZP(h_factor / 6.00, I)
  4371. #define Z2250(I) ZP(r_factor, I)
  4372. #define Z0750(I) ZP(r_factor / 3.00, I)
  4373. #define Z0375(I) ZP(r_factor / 6.00, I)
  4374. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4375. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4376. switch (probe_points) {
  4377. case 1:
  4378. test_precision = 0.00;
  4379. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4380. break;
  4381. case 2:
  4382. if (towers_set) {
  4383. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4384. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4385. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4386. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4387. }
  4388. else {
  4389. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4390. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4391. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4392. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4393. }
  4394. break;
  4395. default:
  4396. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4397. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4398. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4399. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4400. if (towers_set) {
  4401. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4402. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4403. }
  4404. break;
  4405. }
  4406. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4407. delta_radius += r_delta;
  4408. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4409. delta_tower_angle_trim[B_AXIS] += t_beta;
  4410. // adjust delta_height and endstops by the max amount
  4411. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4412. home_offset[Z_AXIS] -= z_temp;
  4413. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4414. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4415. }
  4416. else if (zero_std_dev >= test_precision) { // step one back
  4417. COPY(endstop_adj, e_old);
  4418. delta_radius = dr_old;
  4419. home_offset[Z_AXIS] = zh_old;
  4420. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4421. delta_tower_angle_trim[B_AXIS] = beta_old;
  4422. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4423. }
  4424. // print report
  4425. if (verbose_level != 1) {
  4426. SERIAL_PROTOCOLPGM(". c:");
  4427. if (z_at_pt[0] > 0) SERIAL_CHAR('+');
  4428. SERIAL_PROTOCOL_F(z_at_pt[0], 2);
  4429. if (_4p_towers_points || _7p_calibration) {
  4430. SERIAL_PROTOCOLPGM(" x:");
  4431. if (z_at_pt[1] >= 0) SERIAL_CHAR('+');
  4432. SERIAL_PROTOCOL_F(z_at_pt[1], 2);
  4433. SERIAL_PROTOCOLPGM(" y:");
  4434. if (z_at_pt[5] >= 0) SERIAL_CHAR('+');
  4435. SERIAL_PROTOCOL_F(z_at_pt[5], 2);
  4436. SERIAL_PROTOCOLPGM(" z:");
  4437. if (z_at_pt[9] >= 0) SERIAL_CHAR('+');
  4438. SERIAL_PROTOCOL_F(z_at_pt[9], 2);
  4439. }
  4440. if (!_4p_opposite_points) SERIAL_EOL;
  4441. if ((_4p_opposite_points) || _7p_calibration) {
  4442. if (_7p_calibration) {
  4443. SERIAL_CHAR('.');
  4444. SERIAL_PROTOCOL_SP(13);
  4445. }
  4446. SERIAL_PROTOCOLPGM(" yz:");
  4447. if (z_at_pt[7] >= 0) SERIAL_CHAR('+');
  4448. SERIAL_PROTOCOL_F(z_at_pt[7], 2);
  4449. SERIAL_PROTOCOLPGM(" zx:");
  4450. if (z_at_pt[11] >= 0) SERIAL_CHAR('+');
  4451. SERIAL_PROTOCOL_F(z_at_pt[11], 2);
  4452. SERIAL_PROTOCOLPGM(" xy:");
  4453. if (z_at_pt[3] >= 0) SERIAL_CHAR('+');
  4454. SERIAL_PROTOCOL_F(z_at_pt[3], 2);
  4455. SERIAL_EOL;
  4456. }
  4457. }
  4458. if (test_precision != 0.0) { // !forced end
  4459. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) { // end iterations
  4460. SERIAL_PROTOCOLPGM("Calibration OK");
  4461. SERIAL_PROTOCOL_SP(36);
  4462. if (zero_std_dev >= test_precision)
  4463. SERIAL_PROTOCOLPGM("rolling back.");
  4464. else {
  4465. SERIAL_PROTOCOLPGM("std dev:");
  4466. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4467. }
  4468. SERIAL_EOL;
  4469. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4470. }
  4471. else { // !end iterations
  4472. char mess[15] = "No convergence";
  4473. if (iterations < 31)
  4474. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4475. SERIAL_PROTOCOL(mess);
  4476. SERIAL_PROTOCOL_SP(36);
  4477. SERIAL_PROTOCOLPGM("std dev:");
  4478. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4479. SERIAL_EOL;
  4480. lcd_setstatus(mess);
  4481. }
  4482. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4483. if (!_1p_calibration) {
  4484. SERIAL_PROTOCOLPGM(" Ex:");
  4485. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4486. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4487. SERIAL_PROTOCOLPGM(" Ey:");
  4488. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4489. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4490. SERIAL_PROTOCOLPGM(" Ez:");
  4491. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4492. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4493. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4494. }
  4495. SERIAL_EOL;
  4496. if (_7p_calibration && towers_set) {
  4497. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4498. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4499. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4500. SERIAL_PROTOCOLPGM(" Ty:");
  4501. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4502. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4503. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4504. SERIAL_EOL;
  4505. }
  4506. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision)
  4507. serialprintPGM(save_message);
  4508. SERIAL_EOL;
  4509. }
  4510. else { // forced end
  4511. if (verbose_level == 0) {
  4512. SERIAL_PROTOCOLPGM("End DRY-RUN");
  4513. SERIAL_PROTOCOL_SP(39);
  4514. SERIAL_PROTOCOLPGM("std dev:");
  4515. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4516. SERIAL_EOL;
  4517. }
  4518. else {
  4519. SERIAL_PROTOCOLLNPGM("Calibration OK");
  4520. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4521. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4522. SERIAL_EOL;
  4523. serialprintPGM(save_message);
  4524. SERIAL_EOL;
  4525. }
  4526. }
  4527. endstops.enable(true);
  4528. home_delta();
  4529. endstops.not_homing();
  4530. }
  4531. while (zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31);
  4532. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4533. do_blocking_move_to_z(delta_clip_start_height);
  4534. #endif
  4535. clean_up_after_endstop_or_probe_move();
  4536. #if HOTENDS > 1
  4537. tool_change(old_tool_index, 0, true);
  4538. #endif
  4539. #if ENABLED(Z_PROBE_SLED)
  4540. RETRACT_PROBE();
  4541. #endif
  4542. }
  4543. #endif // DELTA_AUTO_CALIBRATION
  4544. #endif // HAS_BED_PROBE
  4545. #if ENABLED(G38_PROBE_TARGET)
  4546. static bool G38_run_probe() {
  4547. bool G38_pass_fail = false;
  4548. // Get direction of move and retract
  4549. float retract_mm[XYZ];
  4550. LOOP_XYZ(i) {
  4551. float dist = destination[i] - current_position[i];
  4552. retract_mm[i] = fabs(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4553. }
  4554. stepper.synchronize(); // wait until the machine is idle
  4555. // Move until destination reached or target hit
  4556. endstops.enable(true);
  4557. G38_move = true;
  4558. G38_endstop_hit = false;
  4559. prepare_move_to_destination();
  4560. stepper.synchronize();
  4561. G38_move = false;
  4562. endstops.hit_on_purpose();
  4563. set_current_from_steppers_for_axis(ALL_AXES);
  4564. SYNC_PLAN_POSITION_KINEMATIC();
  4565. if (G38_endstop_hit) {
  4566. G38_pass_fail = true;
  4567. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4568. // Move away by the retract distance
  4569. set_destination_to_current();
  4570. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4571. endstops.enable(false);
  4572. prepare_move_to_destination();
  4573. stepper.synchronize();
  4574. feedrate_mm_s /= 4;
  4575. // Bump the target more slowly
  4576. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4577. endstops.enable(true);
  4578. G38_move = true;
  4579. prepare_move_to_destination();
  4580. stepper.synchronize();
  4581. G38_move = false;
  4582. set_current_from_steppers_for_axis(ALL_AXES);
  4583. SYNC_PLAN_POSITION_KINEMATIC();
  4584. #endif
  4585. }
  4586. endstops.hit_on_purpose();
  4587. endstops.not_homing();
  4588. return G38_pass_fail;
  4589. }
  4590. /**
  4591. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4592. * G38.3 - probe toward workpiece, stop on contact
  4593. *
  4594. * Like G28 except uses Z min probe for all axes
  4595. */
  4596. inline void gcode_G38(bool is_38_2) {
  4597. // Get X Y Z E F
  4598. gcode_get_destination();
  4599. setup_for_endstop_or_probe_move();
  4600. // If any axis has enough movement, do the move
  4601. LOOP_XYZ(i)
  4602. if (fabs(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4603. if (!parser.seen('F')) feedrate_mm_s = homing_feedrate_mm_s[i];
  4604. // If G38.2 fails throw an error
  4605. if (!G38_run_probe() && is_38_2) {
  4606. SERIAL_ERROR_START;
  4607. SERIAL_ERRORLNPGM("Failed to reach target");
  4608. }
  4609. break;
  4610. }
  4611. clean_up_after_endstop_or_probe_move();
  4612. }
  4613. #endif // G38_PROBE_TARGET
  4614. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4615. /**
  4616. * G42: Move X & Y axes to mesh coordinates (I & J)
  4617. */
  4618. inline void gcode_G42() {
  4619. if (IsRunning()) {
  4620. const bool hasI = parser.seen('I');
  4621. const int8_t ix = parser.has_value() ? parser.value_int() : 0;
  4622. const bool hasJ = parser.seen('J');
  4623. const int8_t iy = parser.has_value() ? parser.value_int() : 0;
  4624. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4625. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4626. return;
  4627. }
  4628. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4629. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4630. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4631. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4632. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4633. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4634. #elif ENABLED(MESH_BED_LEVELING)
  4635. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4636. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4637. #endif
  4638. set_destination_to_current();
  4639. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4640. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4641. if (parser.seen('P') && parser.value_bool()) {
  4642. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4643. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4644. }
  4645. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  4646. feedrate_mm_s = MMM_TO_MMS(parser.value_linear_units());
  4647. // SCARA kinematic has "safe" XY raw moves
  4648. #if IS_SCARA
  4649. prepare_uninterpolated_move_to_destination();
  4650. #else
  4651. prepare_move_to_destination();
  4652. #endif
  4653. }
  4654. }
  4655. #endif // AUTO_BED_LEVELING_UBL
  4656. /**
  4657. * G92: Set current position to given X Y Z E
  4658. */
  4659. inline void gcode_G92() {
  4660. bool didXYZ = false,
  4661. didE = parser.seen('E');
  4662. if (!didE) stepper.synchronize();
  4663. LOOP_XYZE(i) {
  4664. if (parser.seen(axis_codes[i])) {
  4665. #if IS_SCARA
  4666. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4667. if (i != E_AXIS) didXYZ = true;
  4668. #else
  4669. #if HAS_POSITION_SHIFT
  4670. const float p = current_position[i];
  4671. #endif
  4672. float v = parser.value_axis_units((AxisEnum)i);
  4673. current_position[i] = v;
  4674. if (i != E_AXIS) {
  4675. didXYZ = true;
  4676. #if HAS_POSITION_SHIFT
  4677. position_shift[i] += v - p; // Offset the coordinate space
  4678. update_software_endstops((AxisEnum)i);
  4679. #endif
  4680. }
  4681. #endif
  4682. }
  4683. }
  4684. if (didXYZ)
  4685. SYNC_PLAN_POSITION_KINEMATIC();
  4686. else if (didE)
  4687. sync_plan_position_e();
  4688. report_current_position();
  4689. }
  4690. #if HAS_RESUME_CONTINUE
  4691. /**
  4692. * M0: Unconditional stop - Wait for user button press on LCD
  4693. * M1: Conditional stop - Wait for user button press on LCD
  4694. */
  4695. inline void gcode_M0_M1() {
  4696. const char * const args = parser.string_arg;
  4697. millis_t ms = 0;
  4698. bool hasP = false, hasS = false;
  4699. if (parser.seen('P')) {
  4700. ms = parser.value_millis(); // milliseconds to wait
  4701. hasP = ms > 0;
  4702. }
  4703. if (parser.seen('S')) {
  4704. ms = parser.value_millis_from_seconds(); // seconds to wait
  4705. hasS = ms > 0;
  4706. }
  4707. #if ENABLED(ULTIPANEL)
  4708. if (!hasP && !hasS && args && *args)
  4709. lcd_setstatus(args, true);
  4710. else {
  4711. LCD_MESSAGEPGM(MSG_USERWAIT);
  4712. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4713. dontExpireStatus();
  4714. #endif
  4715. }
  4716. #else
  4717. if (!hasP && !hasS && args && *args) {
  4718. SERIAL_ECHO_START;
  4719. SERIAL_ECHOLN(args);
  4720. }
  4721. #endif
  4722. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4723. wait_for_user = true;
  4724. stepper.synchronize();
  4725. refresh_cmd_timeout();
  4726. if (ms > 0) {
  4727. ms += previous_cmd_ms; // wait until this time for a click
  4728. while (PENDING(millis(), ms) && wait_for_user) idle();
  4729. }
  4730. else {
  4731. #if ENABLED(ULTIPANEL)
  4732. if (lcd_detected()) {
  4733. while (wait_for_user) idle();
  4734. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4735. }
  4736. #else
  4737. while (wait_for_user) idle();
  4738. #endif
  4739. }
  4740. wait_for_user = false;
  4741. KEEPALIVE_STATE(IN_HANDLER);
  4742. }
  4743. #endif // HAS_RESUME_CONTINUE
  4744. #if ENABLED(SPINDLE_LASER_ENABLE)
  4745. /**
  4746. * M3: Spindle Clockwise
  4747. * M4: Spindle Counter-clockwise
  4748. *
  4749. * S0 turns off spindle.
  4750. *
  4751. * If no speed PWM output is defined then M3/M4 just turns it on.
  4752. *
  4753. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4754. * Hardware PWM is required. ISRs are too slow.
  4755. *
  4756. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4757. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4758. *
  4759. * The system automatically sets WGM to Mode 1, so no special
  4760. * initialization is needed.
  4761. *
  4762. * WGM bits for timer 2 are automatically set by the system to
  4763. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4764. * No special initialization is needed.
  4765. *
  4766. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4767. * factors for timers 2, 3, 4, and 5 are acceptable.
  4768. *
  4769. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4770. * the spindle/laser during power-up or when connecting to the host
  4771. * (usually goes through a reset which sets all I/O pins to tri-state)
  4772. *
  4773. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4774. */
  4775. // Wait for spindle to come up to speed
  4776. inline void delay_for_power_up() {
  4777. refresh_cmd_timeout();
  4778. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4779. }
  4780. // Wait for spindle to stop turning
  4781. inline void delay_for_power_down() {
  4782. refresh_cmd_timeout();
  4783. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4784. }
  4785. /**
  4786. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4787. *
  4788. * it accepts inputs of 0-255
  4789. */
  4790. inline void ocr_val_mode() {
  4791. uint8_t spindle_laser_power = parser.value_byte();
  4792. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4793. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4794. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4795. }
  4796. inline void gcode_M3_M4(bool is_M3) {
  4797. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4798. #if SPINDLE_DIR_CHANGE
  4799. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4800. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4801. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4802. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4803. ) {
  4804. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4805. delay_for_power_down();
  4806. }
  4807. digitalWrite(SPINDLE_DIR_PIN, rotation_dir);
  4808. #endif
  4809. /**
  4810. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4811. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4812. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4813. */
  4814. #if ENABLED(SPINDLE_LASER_PWM)
  4815. if (parser.seen('O')) ocr_val_mode();
  4816. else {
  4817. const float spindle_laser_power = parser.seen('S') ? parser.value_float() : 0;
  4818. if (spindle_laser_power == 0) {
  4819. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4820. delay_for_power_down();
  4821. }
  4822. else {
  4823. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4824. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4825. if (spindle_laser_power <= SPEED_POWER_MIN)
  4826. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4827. if (spindle_laser_power >= SPEED_POWER_MAX)
  4828. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4829. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4830. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4831. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4832. delay_for_power_up();
  4833. }
  4834. }
  4835. #else
  4836. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4837. delay_for_power_up();
  4838. #endif
  4839. }
  4840. /**
  4841. * M5 turn off spindle
  4842. */
  4843. inline void gcode_M5() {
  4844. stepper.synchronize();
  4845. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4846. delay_for_power_down();
  4847. }
  4848. #endif // SPINDLE_LASER_ENABLE
  4849. /**
  4850. * M17: Enable power on all stepper motors
  4851. */
  4852. inline void gcode_M17() {
  4853. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4854. enable_all_steppers();
  4855. }
  4856. #if IS_KINEMATIC
  4857. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4858. #else
  4859. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4860. #endif
  4861. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4862. static float resume_position[XYZE];
  4863. static bool move_away_flag = false;
  4864. #if ENABLED(SDSUPPORT)
  4865. static bool sd_print_paused = false;
  4866. #endif
  4867. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4868. static millis_t next_buzz = 0;
  4869. static int8_t runout_beep = 0;
  4870. if (init) next_buzz = runout_beep = 0;
  4871. const millis_t ms = millis();
  4872. if (ELAPSED(ms, next_buzz)) {
  4873. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4874. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4875. BUZZ(300, 2000);
  4876. runout_beep++;
  4877. }
  4878. }
  4879. }
  4880. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  4881. const float &unload_length = 0 , int8_t max_beep_count = 0, bool show_lcd = false
  4882. ) {
  4883. if (move_away_flag) return false; // already paused
  4884. if (!DEBUGGING(DRYRUN) && thermalManager.tooColdToExtrude(active_extruder) && unload_length > 0) {
  4885. SERIAL_ERROR_START;
  4886. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4887. return false;
  4888. }
  4889. // Indicate that the printer is paused
  4890. move_away_flag = true;
  4891. // Pause the print job and timer
  4892. #if ENABLED(SDSUPPORT)
  4893. if (card.sdprinting) {
  4894. card.pauseSDPrint();
  4895. sd_print_paused = true;
  4896. }
  4897. #endif
  4898. print_job_timer.pause();
  4899. // Show initial message and wait for synchronize steppers
  4900. if (show_lcd) {
  4901. #if ENABLED(ULTIPANEL)
  4902. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  4903. #endif
  4904. }
  4905. stepper.synchronize();
  4906. // Save current position
  4907. COPY(resume_position, current_position);
  4908. set_destination_to_current();
  4909. // Initial retract before move to filament change position
  4910. destination[E_AXIS] += retract;
  4911. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  4912. // Lift Z axis
  4913. if (z_lift > 0) {
  4914. destination[Z_AXIS] += z_lift;
  4915. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  4916. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  4917. }
  4918. // Move XY axes to filament exchange position
  4919. destination[X_AXIS] = x_pos;
  4920. destination[Y_AXIS] = y_pos;
  4921. clamp_to_software_endstops(destination);
  4922. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  4923. stepper.synchronize();
  4924. if (unload_length != 0) {
  4925. if (show_lcd) {
  4926. #if ENABLED(ULTIPANEL)
  4927. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  4928. idle();
  4929. #endif
  4930. }
  4931. // Unload filament
  4932. destination[E_AXIS] += unload_length;
  4933. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  4934. stepper.synchronize();
  4935. if (show_lcd) {
  4936. #if ENABLED(ULTIPANEL)
  4937. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  4938. #endif
  4939. }
  4940. #if HAS_BUZZER
  4941. filament_change_beep(max_beep_count, true);
  4942. #endif
  4943. idle();
  4944. }
  4945. // Disable extruders steppers for manual filament changing
  4946. disable_e_steppers();
  4947. safe_delay(100);
  4948. // Start the heater idle timers
  4949. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  4950. HOTEND_LOOP()
  4951. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  4952. return true;
  4953. }
  4954. static void wait_for_filament_reload(int8_t max_beep_count = 0) {
  4955. bool nozzle_timed_out = false;
  4956. // Wait for filament insert by user and press button
  4957. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4958. wait_for_user = true; // LCD click or M108 will clear this
  4959. while (wait_for_user) {
  4960. #if HAS_BUZZER
  4961. filament_change_beep(max_beep_count);
  4962. #endif
  4963. if (!nozzle_timed_out)
  4964. HOTEND_LOOP()
  4965. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  4966. #if ENABLED(ULTIPANEL)
  4967. if (nozzle_timed_out)
  4968. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  4969. #endif
  4970. idle(true);
  4971. }
  4972. KEEPALIVE_STATE(IN_HANDLER);
  4973. }
  4974. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, int8_t max_beep_count = 0) {
  4975. bool nozzle_timed_out = false;
  4976. if (!move_away_flag) return;
  4977. // Re-enable the heaters if they timed out
  4978. HOTEND_LOOP() {
  4979. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  4980. thermalManager.reset_heater_idle_timer(e);
  4981. }
  4982. #if ENABLED(ULTIPANEL)
  4983. // Show "wait for heating"
  4984. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  4985. #endif
  4986. wait_for_heatup = true;
  4987. while (wait_for_heatup) {
  4988. idle();
  4989. wait_for_heatup = false;
  4990. HOTEND_LOOP() {
  4991. if (abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > 3) {
  4992. wait_for_heatup = true;
  4993. break;
  4994. }
  4995. }
  4996. }
  4997. #if HAS_BUZZER
  4998. filament_change_beep(max_beep_count, true);
  4999. #endif
  5000. if (load_length != 0) {
  5001. #if ENABLED(ULTIPANEL)
  5002. // Show "insert filament"
  5003. if (nozzle_timed_out)
  5004. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5005. #endif
  5006. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5007. wait_for_user = true; // LCD click or M108 will clear this
  5008. while (wait_for_user && nozzle_timed_out) {
  5009. #if HAS_BUZZER
  5010. filament_change_beep(max_beep_count);
  5011. #endif
  5012. idle(true);
  5013. }
  5014. KEEPALIVE_STATE(IN_HANDLER);
  5015. #if ENABLED(ULTIPANEL)
  5016. // Show "load" message
  5017. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5018. #endif
  5019. // Load filament
  5020. destination[E_AXIS] += load_length;
  5021. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5022. stepper.synchronize();
  5023. }
  5024. #if ENABLED(ULTIPANEL) && defined(ADVANCED_PAUSE_EXTRUDE_LENGTH) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5025. float extrude_length = initial_extrude_length;
  5026. do {
  5027. if (extrude_length > 0) {
  5028. // "Wait for filament extrude"
  5029. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5030. // Extrude filament to get into hotend
  5031. destination[E_AXIS] += extrude_length;
  5032. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5033. stepper.synchronize();
  5034. }
  5035. // Show "Extrude More" / "Resume" menu and wait for reply
  5036. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5037. wait_for_user = false;
  5038. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5039. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5040. KEEPALIVE_STATE(IN_HANDLER);
  5041. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5042. // Keep looping if "Extrude More" was selected
  5043. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5044. #endif
  5045. #if ENABLED(ULTIPANEL)
  5046. // "Wait for print to resume"
  5047. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5048. #endif
  5049. // Set extruder to saved position
  5050. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5051. planner.set_e_position_mm(current_position[E_AXIS]);
  5052. #if IS_KINEMATIC
  5053. // Move XYZ to starting position
  5054. planner.buffer_line_kinematic(resume_position, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5055. #else
  5056. // Move XY to starting position, then Z
  5057. destination[X_AXIS] = resume_position[X_AXIS];
  5058. destination[Y_AXIS] = resume_position[Y_AXIS];
  5059. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5060. destination[Z_AXIS] = resume_position[Z_AXIS];
  5061. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5062. #endif
  5063. stepper.synchronize();
  5064. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5065. filament_ran_out = false;
  5066. #endif
  5067. set_current_to_destination();
  5068. #if ENABLED(ULTIPANEL)
  5069. // Show status screen
  5070. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5071. #endif
  5072. #if ENABLED(SDSUPPORT)
  5073. if (sd_print_paused) {
  5074. card.startFileprint();
  5075. sd_print_paused = false;
  5076. }
  5077. #endif
  5078. move_away_flag = false;
  5079. }
  5080. #endif // ADVANCED_PAUSE_FEATURE
  5081. #if ENABLED(SDSUPPORT)
  5082. /**
  5083. * M20: List SD card to serial output
  5084. */
  5085. inline void gcode_M20() {
  5086. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5087. card.ls();
  5088. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5089. }
  5090. /**
  5091. * M21: Init SD Card
  5092. */
  5093. inline void gcode_M21() { card.initsd(); }
  5094. /**
  5095. * M22: Release SD Card
  5096. */
  5097. inline void gcode_M22() { card.release(); }
  5098. /**
  5099. * M23: Open a file
  5100. */
  5101. inline void gcode_M23() { card.openFile(parser.string_arg, true); }
  5102. /**
  5103. * M24: Start or Resume SD Print
  5104. */
  5105. inline void gcode_M24() {
  5106. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5107. resume_print();
  5108. #endif
  5109. card.startFileprint();
  5110. print_job_timer.start();
  5111. }
  5112. /**
  5113. * M25: Pause SD Print
  5114. */
  5115. inline void gcode_M25() {
  5116. card.pauseSDPrint();
  5117. print_job_timer.pause();
  5118. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5119. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5120. #endif
  5121. }
  5122. /**
  5123. * M26: Set SD Card file index
  5124. */
  5125. inline void gcode_M26() {
  5126. if (card.cardOK && parser.seen('S'))
  5127. card.setIndex(parser.value_long());
  5128. }
  5129. /**
  5130. * M27: Get SD Card status
  5131. */
  5132. inline void gcode_M27() { card.getStatus(); }
  5133. /**
  5134. * M28: Start SD Write
  5135. */
  5136. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5137. /**
  5138. * M29: Stop SD Write
  5139. * Processed in write to file routine above
  5140. */
  5141. inline void gcode_M29() {
  5142. // card.saving = false;
  5143. }
  5144. /**
  5145. * M30 <filename>: Delete SD Card file
  5146. */
  5147. inline void gcode_M30() {
  5148. if (card.cardOK) {
  5149. card.closefile();
  5150. card.removeFile(parser.string_arg);
  5151. }
  5152. }
  5153. #endif // SDSUPPORT
  5154. /**
  5155. * M31: Get the time since the start of SD Print (or last M109)
  5156. */
  5157. inline void gcode_M31() {
  5158. char buffer[21];
  5159. duration_t elapsed = print_job_timer.duration();
  5160. elapsed.toString(buffer);
  5161. lcd_setstatus(buffer);
  5162. SERIAL_ECHO_START;
  5163. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5164. }
  5165. #if ENABLED(SDSUPPORT)
  5166. /**
  5167. * M32: Select file and start SD Print
  5168. */
  5169. inline void gcode_M32() {
  5170. if (card.sdprinting)
  5171. stepper.synchronize();
  5172. char* namestartpos = parser.string_arg;
  5173. bool call_procedure = parser.seen('P');
  5174. if (card.cardOK) {
  5175. card.openFile(namestartpos, true, call_procedure);
  5176. if (parser.seen('S'))
  5177. card.setIndex(parser.value_long());
  5178. card.startFileprint();
  5179. // Procedure calls count as normal print time.
  5180. if (!call_procedure) print_job_timer.start();
  5181. }
  5182. }
  5183. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5184. /**
  5185. * M33: Get the long full path of a file or folder
  5186. *
  5187. * Parameters:
  5188. * <dospath> Case-insensitive DOS-style path to a file or folder
  5189. *
  5190. * Example:
  5191. * M33 miscel~1/armchair/armcha~1.gco
  5192. *
  5193. * Output:
  5194. * /Miscellaneous/Armchair/Armchair.gcode
  5195. */
  5196. inline void gcode_M33() {
  5197. card.printLongPath(parser.string_arg);
  5198. }
  5199. #endif
  5200. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5201. /**
  5202. * M34: Set SD Card Sorting Options
  5203. */
  5204. inline void gcode_M34() {
  5205. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5206. if (parser.seen('F')) {
  5207. int v = parser.value_long();
  5208. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5209. }
  5210. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5211. }
  5212. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5213. /**
  5214. * M928: Start SD Write
  5215. */
  5216. inline void gcode_M928() {
  5217. card.openLogFile(parser.string_arg);
  5218. }
  5219. #endif // SDSUPPORT
  5220. /**
  5221. * Sensitive pin test for M42, M226
  5222. */
  5223. static bool pin_is_protected(uint8_t pin) {
  5224. static const int sensitive_pins[] = SENSITIVE_PINS;
  5225. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5226. if (sensitive_pins[i] == pin) return true;
  5227. return false;
  5228. }
  5229. /**
  5230. * M42: Change pin status via GCode
  5231. *
  5232. * P<pin> Pin number (LED if omitted)
  5233. * S<byte> Pin status from 0 - 255
  5234. */
  5235. inline void gcode_M42() {
  5236. if (!parser.seen('S')) return;
  5237. int pin_status = parser.value_int();
  5238. if (!WITHIN(pin_status, 0, 255)) return;
  5239. int pin_number = parser.seen('P') ? parser.value_int() : LED_PIN;
  5240. if (pin_number < 0) return;
  5241. if (pin_is_protected(pin_number)) {
  5242. SERIAL_ERROR_START;
  5243. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5244. return;
  5245. }
  5246. pinMode(pin_number, OUTPUT);
  5247. digitalWrite(pin_number, pin_status);
  5248. analogWrite(pin_number, pin_status);
  5249. #if FAN_COUNT > 0
  5250. switch (pin_number) {
  5251. #if HAS_FAN0
  5252. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5253. #endif
  5254. #if HAS_FAN1
  5255. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5256. #endif
  5257. #if HAS_FAN2
  5258. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5259. #endif
  5260. }
  5261. #endif
  5262. }
  5263. #if ENABLED(PINS_DEBUGGING)
  5264. #include "pinsDebug.h"
  5265. inline void toggle_pins() {
  5266. const bool I_flag = parser.seen('I') && parser.value_bool();
  5267. const int repeat = parser.seen('R') ? parser.value_int() : 1,
  5268. start = parser.seen('S') ? parser.value_int() : 0,
  5269. end = parser.seen('E') ? parser.value_int() : NUM_DIGITAL_PINS - 1,
  5270. wait = parser.seen('W') ? parser.value_int() : 500;
  5271. for (uint8_t pin = start; pin <= end; pin++) {
  5272. if (!I_flag && pin_is_protected(pin)) {
  5273. SERIAL_ECHOPAIR("Sensitive Pin: ", pin);
  5274. SERIAL_ECHOLNPGM(" untouched.");
  5275. }
  5276. else {
  5277. SERIAL_ECHOPAIR("Pulsing Pin: ", pin);
  5278. pinMode(pin, OUTPUT);
  5279. for (int16_t j = 0; j < repeat; j++) {
  5280. digitalWrite(pin, 0);
  5281. safe_delay(wait);
  5282. digitalWrite(pin, 1);
  5283. safe_delay(wait);
  5284. digitalWrite(pin, 0);
  5285. safe_delay(wait);
  5286. }
  5287. }
  5288. SERIAL_CHAR('\n');
  5289. }
  5290. SERIAL_ECHOLNPGM("Done.");
  5291. } // toggle_pins
  5292. inline void servo_probe_test() {
  5293. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5294. SERIAL_ERROR_START;
  5295. SERIAL_ERRORLNPGM("SERVO not setup");
  5296. #elif !HAS_Z_SERVO_ENDSTOP
  5297. SERIAL_ERROR_START;
  5298. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5299. #else
  5300. const uint8_t probe_index = parser.seen('P') ? parser.value_byte() : Z_ENDSTOP_SERVO_NR;
  5301. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5302. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5303. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5304. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5305. bool probe_inverting;
  5306. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5307. #define PROBE_TEST_PIN Z_MIN_PIN
  5308. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5309. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5310. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5311. #if Z_MIN_ENDSTOP_INVERTING
  5312. SERIAL_PROTOCOLLNPGM("true");
  5313. #else
  5314. SERIAL_PROTOCOLLNPGM("false");
  5315. #endif
  5316. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5317. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5318. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5319. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5320. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5321. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5322. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5323. SERIAL_PROTOCOLLNPGM("true");
  5324. #else
  5325. SERIAL_PROTOCOLLNPGM("false");
  5326. #endif
  5327. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5328. #endif
  5329. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5330. pinMode(PROBE_TEST_PIN, INPUT_PULLUP);
  5331. bool deploy_state;
  5332. bool stow_state;
  5333. for (uint8_t i = 0; i < 4; i++) {
  5334. servo[probe_index].move(z_servo_angle[0]); //deploy
  5335. safe_delay(500);
  5336. deploy_state = digitalRead(PROBE_TEST_PIN);
  5337. servo[probe_index].move(z_servo_angle[1]); //stow
  5338. safe_delay(500);
  5339. stow_state = digitalRead(PROBE_TEST_PIN);
  5340. }
  5341. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5342. refresh_cmd_timeout();
  5343. if (deploy_state != stow_state) {
  5344. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5345. if (deploy_state) {
  5346. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5347. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5348. }
  5349. else {
  5350. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5351. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5352. }
  5353. #if ENABLED(BLTOUCH)
  5354. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5355. #endif
  5356. }
  5357. else { // measure active signal length
  5358. servo[probe_index].move(z_servo_angle[0]); // deploy
  5359. safe_delay(500);
  5360. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5361. uint16_t probe_counter = 0;
  5362. // Allow 30 seconds max for operator to trigger probe
  5363. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5364. safe_delay(2);
  5365. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5366. refresh_cmd_timeout();
  5367. if (deploy_state != digitalRead(PROBE_TEST_PIN)) { // probe triggered
  5368. for (probe_counter = 1; probe_counter < 50 && deploy_state != digitalRead(PROBE_TEST_PIN); ++probe_counter)
  5369. safe_delay(2);
  5370. if (probe_counter == 50)
  5371. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5372. else if (probe_counter >= 2)
  5373. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5374. else
  5375. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5376. servo[probe_index].move(z_servo_angle[1]); //stow
  5377. } // pulse detected
  5378. } // for loop waiting for trigger
  5379. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5380. } // measure active signal length
  5381. #endif
  5382. } // servo_probe_test
  5383. /**
  5384. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5385. *
  5386. * M43 - report name and state of pin(s)
  5387. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5388. * I Flag to ignore Marlin's pin protection.
  5389. *
  5390. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5391. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5392. * I Flag to ignore Marlin's pin protection.
  5393. *
  5394. * M43 E<bool> - Enable / disable background endstop monitoring
  5395. * - Machine continues to operate
  5396. * - Reports changes to endstops
  5397. * - Toggles LED when an endstop changes
  5398. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5399. *
  5400. * M43 T - Toggle pin(s) and report which pin is being toggled
  5401. * S<pin> - Start Pin number. If not given, will default to 0
  5402. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5403. * I - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5404. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5405. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5406. *
  5407. * M43 S - Servo probe test
  5408. * P<index> - Probe index (optional - defaults to 0
  5409. */
  5410. inline void gcode_M43() {
  5411. if (parser.seen('T')) { // must be first ot else it's "S" and "E" parameters will execute endstop or servo test
  5412. toggle_pins();
  5413. return;
  5414. }
  5415. // Enable or disable endstop monitoring
  5416. if (parser.seen('E')) {
  5417. endstop_monitor_flag = parser.value_bool();
  5418. SERIAL_PROTOCOLPGM("endstop monitor ");
  5419. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  5420. SERIAL_PROTOCOLLNPGM("abled");
  5421. return;
  5422. }
  5423. if (parser.seen('S')) {
  5424. servo_probe_test();
  5425. return;
  5426. }
  5427. // Get the range of pins to test or watch
  5428. const uint8_t first_pin = parser.seen('P') ? parser.value_byte() : 0,
  5429. last_pin = parser.seen('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5430. if (first_pin > last_pin) return;
  5431. const bool ignore_protection = parser.seen('I') && parser.value_bool();
  5432. // Watch until click, M108, or reset
  5433. if (parser.seen('W') && parser.value_bool()) {
  5434. SERIAL_PROTOCOLLNPGM("Watching pins");
  5435. byte pin_state[last_pin - first_pin + 1];
  5436. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5437. if (pin_is_protected(pin) && !ignore_protection) continue;
  5438. pinMode(pin, INPUT_PULLUP);
  5439. /*
  5440. if (IS_ANALOG(pin))
  5441. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5442. else
  5443. //*/
  5444. pin_state[pin - first_pin] = digitalRead(pin);
  5445. }
  5446. #if HAS_RESUME_CONTINUE
  5447. wait_for_user = true;
  5448. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5449. #endif
  5450. for (;;) {
  5451. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5452. if (pin_is_protected(pin)) continue;
  5453. const byte val =
  5454. /*
  5455. IS_ANALOG(pin)
  5456. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5457. :
  5458. //*/
  5459. digitalRead(pin);
  5460. if (val != pin_state[pin - first_pin]) {
  5461. report_pin_state(pin);
  5462. pin_state[pin - first_pin] = val;
  5463. }
  5464. }
  5465. #if HAS_RESUME_CONTINUE
  5466. if (!wait_for_user) {
  5467. KEEPALIVE_STATE(IN_HANDLER);
  5468. break;
  5469. }
  5470. #endif
  5471. safe_delay(500);
  5472. }
  5473. return;
  5474. }
  5475. // Report current state of selected pin(s)
  5476. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5477. report_pin_state_extended(pin, ignore_protection);
  5478. }
  5479. #endif // PINS_DEBUGGING
  5480. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5481. /**
  5482. * M48: Z probe repeatability measurement function.
  5483. *
  5484. * Usage:
  5485. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5486. * P = Number of sampled points (4-50, default 10)
  5487. * X = Sample X position
  5488. * Y = Sample Y position
  5489. * V = Verbose level (0-4, default=1)
  5490. * E = Engage Z probe for each reading
  5491. * L = Number of legs of movement before probe
  5492. * S = Schizoid (Or Star if you prefer)
  5493. *
  5494. * This function assumes the bed has been homed. Specifically, that a G28 command
  5495. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5496. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5497. * regenerated.
  5498. */
  5499. inline void gcode_M48() {
  5500. if (axis_unhomed_error()) return;
  5501. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  5502. if (!WITHIN(verbose_level, 0, 4)) {
  5503. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5504. return;
  5505. }
  5506. if (verbose_level > 0)
  5507. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5508. int8_t n_samples = parser.seen('P') ? parser.value_byte() : 10;
  5509. if (!WITHIN(n_samples, 4, 50)) {
  5510. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5511. return;
  5512. }
  5513. const bool stow_probe_after_each = parser.seen('E');
  5514. float X_current = current_position[X_AXIS],
  5515. Y_current = current_position[Y_AXIS];
  5516. const float X_probe_location = parser.seen('X') ? parser.value_linear_units() : X_current + X_PROBE_OFFSET_FROM_EXTRUDER,
  5517. Y_probe_location = parser.seen('Y') ? parser.value_linear_units() : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  5518. #if DISABLED(DELTA)
  5519. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5520. out_of_range_error(PSTR("X"));
  5521. return;
  5522. }
  5523. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5524. out_of_range_error(PSTR("Y"));
  5525. return;
  5526. }
  5527. #else
  5528. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5529. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5530. return;
  5531. }
  5532. #endif
  5533. bool seen_L = parser.seen('L');
  5534. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5535. if (n_legs > 15) {
  5536. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5537. return;
  5538. }
  5539. if (n_legs == 1) n_legs = 2;
  5540. bool schizoid_flag = parser.seen('S');
  5541. if (schizoid_flag && !seen_L) n_legs = 7;
  5542. /**
  5543. * Now get everything to the specified probe point So we can safely do a
  5544. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5545. * we don't want to use that as a starting point for each probe.
  5546. */
  5547. if (verbose_level > 2)
  5548. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5549. // Disable bed level correction in M48 because we want the raw data when we probe
  5550. #if HAS_LEVELING
  5551. const bool was_enabled = leveling_is_active();
  5552. set_bed_leveling_enabled(false);
  5553. #endif
  5554. setup_for_endstop_or_probe_move();
  5555. // Move to the first point, deploy, and probe
  5556. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5557. if (isnan(t)) return;
  5558. randomSeed(millis());
  5559. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5560. for (uint8_t n = 0; n < n_samples; n++) {
  5561. if (n_legs) {
  5562. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5563. float angle = random(0.0, 360.0),
  5564. radius = random(
  5565. #if ENABLED(DELTA)
  5566. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5567. #else
  5568. 5, X_MAX_LENGTH / 8
  5569. #endif
  5570. );
  5571. if (verbose_level > 3) {
  5572. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5573. SERIAL_ECHOPAIR(" angle: ", angle);
  5574. SERIAL_ECHOPGM(" Direction: ");
  5575. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5576. SERIAL_ECHOLNPGM("Clockwise");
  5577. }
  5578. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5579. double delta_angle;
  5580. if (schizoid_flag)
  5581. // The points of a 5 point star are 72 degrees apart. We need to
  5582. // skip a point and go to the next one on the star.
  5583. delta_angle = dir * 2.0 * 72.0;
  5584. else
  5585. // If we do this line, we are just trying to move further
  5586. // around the circle.
  5587. delta_angle = dir * (float) random(25, 45);
  5588. angle += delta_angle;
  5589. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5590. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5591. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5592. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5593. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5594. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5595. #if DISABLED(DELTA)
  5596. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5597. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5598. #else
  5599. // If we have gone out too far, we can do a simple fix and scale the numbers
  5600. // back in closer to the origin.
  5601. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5602. X_current *= 0.8;
  5603. Y_current *= 0.8;
  5604. if (verbose_level > 3) {
  5605. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5606. SERIAL_ECHOLNPAIR(", ", Y_current);
  5607. }
  5608. }
  5609. #endif
  5610. if (verbose_level > 3) {
  5611. SERIAL_PROTOCOLPGM("Going to:");
  5612. SERIAL_ECHOPAIR(" X", X_current);
  5613. SERIAL_ECHOPAIR(" Y", Y_current);
  5614. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5615. }
  5616. do_blocking_move_to_xy(X_current, Y_current);
  5617. } // n_legs loop
  5618. } // n_legs
  5619. // Probe a single point
  5620. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5621. /**
  5622. * Get the current mean for the data points we have so far
  5623. */
  5624. double sum = 0.0;
  5625. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5626. mean = sum / (n + 1);
  5627. NOMORE(min, sample_set[n]);
  5628. NOLESS(max, sample_set[n]);
  5629. /**
  5630. * Now, use that mean to calculate the standard deviation for the
  5631. * data points we have so far
  5632. */
  5633. sum = 0.0;
  5634. for (uint8_t j = 0; j <= n; j++)
  5635. sum += sq(sample_set[j] - mean);
  5636. sigma = sqrt(sum / (n + 1));
  5637. if (verbose_level > 0) {
  5638. if (verbose_level > 1) {
  5639. SERIAL_PROTOCOL(n + 1);
  5640. SERIAL_PROTOCOLPGM(" of ");
  5641. SERIAL_PROTOCOL((int)n_samples);
  5642. SERIAL_PROTOCOLPGM(": z: ");
  5643. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5644. if (verbose_level > 2) {
  5645. SERIAL_PROTOCOLPGM(" mean: ");
  5646. SERIAL_PROTOCOL_F(mean, 4);
  5647. SERIAL_PROTOCOLPGM(" sigma: ");
  5648. SERIAL_PROTOCOL_F(sigma, 6);
  5649. SERIAL_PROTOCOLPGM(" min: ");
  5650. SERIAL_PROTOCOL_F(min, 3);
  5651. SERIAL_PROTOCOLPGM(" max: ");
  5652. SERIAL_PROTOCOL_F(max, 3);
  5653. SERIAL_PROTOCOLPGM(" range: ");
  5654. SERIAL_PROTOCOL_F(max-min, 3);
  5655. }
  5656. SERIAL_EOL;
  5657. }
  5658. }
  5659. } // End of probe loop
  5660. if (STOW_PROBE()) return;
  5661. SERIAL_PROTOCOLPGM("Finished!");
  5662. SERIAL_EOL;
  5663. if (verbose_level > 0) {
  5664. SERIAL_PROTOCOLPGM("Mean: ");
  5665. SERIAL_PROTOCOL_F(mean, 6);
  5666. SERIAL_PROTOCOLPGM(" Min: ");
  5667. SERIAL_PROTOCOL_F(min, 3);
  5668. SERIAL_PROTOCOLPGM(" Max: ");
  5669. SERIAL_PROTOCOL_F(max, 3);
  5670. SERIAL_PROTOCOLPGM(" Range: ");
  5671. SERIAL_PROTOCOL_F(max-min, 3);
  5672. SERIAL_EOL;
  5673. }
  5674. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5675. SERIAL_PROTOCOL_F(sigma, 6);
  5676. SERIAL_EOL;
  5677. SERIAL_EOL;
  5678. clean_up_after_endstop_or_probe_move();
  5679. // Re-enable bed level correction if it had been on
  5680. #if HAS_LEVELING
  5681. set_bed_leveling_enabled(was_enabled);
  5682. #endif
  5683. report_current_position();
  5684. }
  5685. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5686. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5687. inline void gcode_M49() {
  5688. ubl.g26_debug_flag ^= true;
  5689. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5690. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5691. }
  5692. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5693. /**
  5694. * M75: Start print timer
  5695. */
  5696. inline void gcode_M75() { print_job_timer.start(); }
  5697. /**
  5698. * M76: Pause print timer
  5699. */
  5700. inline void gcode_M76() { print_job_timer.pause(); }
  5701. /**
  5702. * M77: Stop print timer
  5703. */
  5704. inline void gcode_M77() { print_job_timer.stop(); }
  5705. #if ENABLED(PRINTCOUNTER)
  5706. /**
  5707. * M78: Show print statistics
  5708. */
  5709. inline void gcode_M78() {
  5710. // "M78 S78" will reset the statistics
  5711. if (parser.seen('S') && parser.value_int() == 78)
  5712. print_job_timer.initStats();
  5713. else
  5714. print_job_timer.showStats();
  5715. }
  5716. #endif
  5717. /**
  5718. * M104: Set hot end temperature
  5719. */
  5720. inline void gcode_M104() {
  5721. if (get_target_extruder_from_command(104)) return;
  5722. if (DEBUGGING(DRYRUN)) return;
  5723. #if ENABLED(SINGLENOZZLE)
  5724. if (target_extruder != active_extruder) return;
  5725. #endif
  5726. if (parser.seen('S')) {
  5727. const int16_t temp = parser.value_celsius();
  5728. thermalManager.setTargetHotend(temp, target_extruder);
  5729. #if ENABLED(DUAL_X_CARRIAGE)
  5730. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5731. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5732. #endif
  5733. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5734. /**
  5735. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5736. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5737. * standby mode, for instance in a dual extruder setup, without affecting
  5738. * the running print timer.
  5739. */
  5740. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5741. print_job_timer.stop();
  5742. LCD_MESSAGEPGM(WELCOME_MSG);
  5743. }
  5744. #endif
  5745. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5746. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5747. }
  5748. #if ENABLED(AUTOTEMP)
  5749. planner.autotemp_M104_M109();
  5750. #endif
  5751. }
  5752. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5753. void print_heaterstates() {
  5754. #if HAS_TEMP_HOTEND
  5755. SERIAL_PROTOCOLPGM(" T:");
  5756. SERIAL_PROTOCOL(thermalManager.degHotend(target_extruder));
  5757. SERIAL_PROTOCOLPGM(" /");
  5758. SERIAL_PROTOCOL(thermalManager.degTargetHotend(target_extruder));
  5759. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5760. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawHotendTemp(target_extruder) / OVERSAMPLENR);
  5761. SERIAL_PROTOCOLCHAR(')');
  5762. #endif
  5763. #endif
  5764. #if HAS_TEMP_BED
  5765. SERIAL_PROTOCOLPGM(" B:");
  5766. SERIAL_PROTOCOL(thermalManager.degBed());
  5767. SERIAL_PROTOCOLPGM(" /");
  5768. SERIAL_PROTOCOL(thermalManager.degTargetBed());
  5769. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5770. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawBedTemp() / OVERSAMPLENR);
  5771. SERIAL_PROTOCOLCHAR(')');
  5772. #endif
  5773. #endif
  5774. #if HOTENDS > 1
  5775. HOTEND_LOOP() {
  5776. SERIAL_PROTOCOLPAIR(" T", e);
  5777. SERIAL_PROTOCOLCHAR(':');
  5778. SERIAL_PROTOCOL(thermalManager.degHotend(e));
  5779. SERIAL_PROTOCOLPGM(" /");
  5780. SERIAL_PROTOCOL(thermalManager.degTargetHotend(e));
  5781. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5782. SERIAL_PROTOCOLPAIR(" (", thermalManager.rawHotendTemp(e) / OVERSAMPLENR);
  5783. SERIAL_PROTOCOLCHAR(')');
  5784. #endif
  5785. }
  5786. #endif
  5787. SERIAL_PROTOCOLPGM(" @:");
  5788. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5789. #if HAS_TEMP_BED
  5790. SERIAL_PROTOCOLPGM(" B@:");
  5791. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5792. #endif
  5793. #if HOTENDS > 1
  5794. HOTEND_LOOP() {
  5795. SERIAL_PROTOCOLPAIR(" @", e);
  5796. SERIAL_PROTOCOLCHAR(':');
  5797. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5798. }
  5799. #endif
  5800. }
  5801. #endif
  5802. /**
  5803. * M105: Read hot end and bed temperature
  5804. */
  5805. inline void gcode_M105() {
  5806. if (get_target_extruder_from_command(105)) return;
  5807. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5808. SERIAL_PROTOCOLPGM(MSG_OK);
  5809. print_heaterstates();
  5810. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  5811. SERIAL_ERROR_START;
  5812. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  5813. #endif
  5814. SERIAL_EOL;
  5815. }
  5816. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  5817. static uint8_t auto_report_temp_interval;
  5818. static millis_t next_temp_report_ms;
  5819. /**
  5820. * M155: Set temperature auto-report interval. M155 S<seconds>
  5821. */
  5822. inline void gcode_M155() {
  5823. if (parser.seen('S')) {
  5824. auto_report_temp_interval = parser.value_byte();
  5825. NOMORE(auto_report_temp_interval, 60);
  5826. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5827. }
  5828. }
  5829. inline void auto_report_temperatures() {
  5830. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  5831. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5832. print_heaterstates();
  5833. SERIAL_EOL;
  5834. }
  5835. }
  5836. #endif // AUTO_REPORT_TEMPERATURES
  5837. #if FAN_COUNT > 0
  5838. /**
  5839. * M106: Set Fan Speed
  5840. *
  5841. * S<int> Speed between 0-255
  5842. * P<index> Fan index, if more than one fan
  5843. */
  5844. inline void gcode_M106() {
  5845. uint16_t s = parser.seen('S') ? parser.value_ushort() : 255,
  5846. p = parser.seen('P') ? parser.value_ushort() : 0;
  5847. NOMORE(s, 255);
  5848. if (p < FAN_COUNT) fanSpeeds[p] = s;
  5849. }
  5850. /**
  5851. * M107: Fan Off
  5852. */
  5853. inline void gcode_M107() {
  5854. uint16_t p = parser.seen('P') ? parser.value_ushort() : 0;
  5855. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  5856. }
  5857. #endif // FAN_COUNT > 0
  5858. #if DISABLED(EMERGENCY_PARSER)
  5859. /**
  5860. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  5861. */
  5862. inline void gcode_M108() { wait_for_heatup = false; }
  5863. /**
  5864. * M112: Emergency Stop
  5865. */
  5866. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  5867. /**
  5868. * M410: Quickstop - Abort all planned moves
  5869. *
  5870. * This will stop the carriages mid-move, so most likely they
  5871. * will be out of sync with the stepper position after this.
  5872. */
  5873. inline void gcode_M410() { quickstop_stepper(); }
  5874. #endif
  5875. /**
  5876. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  5877. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  5878. */
  5879. #ifndef MIN_COOLING_SLOPE_DEG
  5880. #define MIN_COOLING_SLOPE_DEG 1.50
  5881. #endif
  5882. #ifndef MIN_COOLING_SLOPE_TIME
  5883. #define MIN_COOLING_SLOPE_TIME 60
  5884. #endif
  5885. inline void gcode_M109() {
  5886. if (get_target_extruder_from_command(109)) return;
  5887. if (DEBUGGING(DRYRUN)) return;
  5888. #if ENABLED(SINGLENOZZLE)
  5889. if (target_extruder != active_extruder) return;
  5890. #endif
  5891. const bool no_wait_for_cooling = parser.seen('S');
  5892. if (no_wait_for_cooling || parser.seen('R')) {
  5893. const int16_t temp = parser.value_celsius();
  5894. thermalManager.setTargetHotend(temp, target_extruder);
  5895. #if ENABLED(DUAL_X_CARRIAGE)
  5896. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5897. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5898. #endif
  5899. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5900. /**
  5901. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  5902. * standby mode, (e.g., in a dual extruder setup) without affecting
  5903. * the running print timer.
  5904. */
  5905. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5906. print_job_timer.stop();
  5907. LCD_MESSAGEPGM(WELCOME_MSG);
  5908. }
  5909. else
  5910. print_job_timer.start();
  5911. #endif
  5912. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5913. }
  5914. else return;
  5915. #if ENABLED(AUTOTEMP)
  5916. planner.autotemp_M104_M109();
  5917. #endif
  5918. #if TEMP_RESIDENCY_TIME > 0
  5919. millis_t residency_start_ms = 0;
  5920. // Loop until the temperature has stabilized
  5921. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  5922. #else
  5923. // Loop until the temperature is very close target
  5924. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  5925. #endif
  5926. float target_temp = -1.0, old_temp = 9999.0;
  5927. bool wants_to_cool = false;
  5928. wait_for_heatup = true;
  5929. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  5930. KEEPALIVE_STATE(NOT_BUSY);
  5931. #if ENABLED(PRINTER_EVENT_LEDS)
  5932. const float start_temp = thermalManager.degHotend(target_extruder);
  5933. uint8_t old_blue = 0;
  5934. #endif
  5935. do {
  5936. // Target temperature might be changed during the loop
  5937. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  5938. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  5939. target_temp = thermalManager.degTargetHotend(target_extruder);
  5940. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  5941. if (no_wait_for_cooling && wants_to_cool) break;
  5942. }
  5943. now = millis();
  5944. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  5945. next_temp_ms = now + 1000UL;
  5946. print_heaterstates();
  5947. #if TEMP_RESIDENCY_TIME > 0
  5948. SERIAL_PROTOCOLPGM(" W:");
  5949. if (residency_start_ms) {
  5950. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  5951. SERIAL_PROTOCOLLN(rem);
  5952. }
  5953. else {
  5954. SERIAL_PROTOCOLLNPGM("?");
  5955. }
  5956. #else
  5957. SERIAL_EOL;
  5958. #endif
  5959. }
  5960. idle();
  5961. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  5962. const float temp = thermalManager.degHotend(target_extruder);
  5963. #if ENABLED(PRINTER_EVENT_LEDS)
  5964. // Gradually change LED strip from violet to red as nozzle heats up
  5965. if (!wants_to_cool) {
  5966. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  5967. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  5968. }
  5969. #endif
  5970. #if TEMP_RESIDENCY_TIME > 0
  5971. const float temp_diff = fabs(target_temp - temp);
  5972. if (!residency_start_ms) {
  5973. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  5974. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  5975. }
  5976. else if (temp_diff > TEMP_HYSTERESIS) {
  5977. // Restart the timer whenever the temperature falls outside the hysteresis.
  5978. residency_start_ms = now;
  5979. }
  5980. #endif
  5981. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  5982. if (wants_to_cool) {
  5983. // break after MIN_COOLING_SLOPE_TIME seconds
  5984. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  5985. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  5986. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  5987. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  5988. old_temp = temp;
  5989. }
  5990. }
  5991. } while (wait_for_heatup && TEMP_CONDITIONS);
  5992. if (wait_for_heatup) {
  5993. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  5994. #if ENABLED(PRINTER_EVENT_LEDS)
  5995. #if ENABLED(RGBW_LED)
  5996. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  5997. #else
  5998. set_led_color(255, 255, 255); // Set LEDs All On
  5999. #endif
  6000. #endif
  6001. }
  6002. KEEPALIVE_STATE(IN_HANDLER);
  6003. }
  6004. #if HAS_TEMP_BED
  6005. #ifndef MIN_COOLING_SLOPE_DEG_BED
  6006. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6007. #endif
  6008. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6009. #define MIN_COOLING_SLOPE_TIME_BED 60
  6010. #endif
  6011. /**
  6012. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6013. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6014. */
  6015. inline void gcode_M190() {
  6016. if (DEBUGGING(DRYRUN)) return;
  6017. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6018. const bool no_wait_for_cooling = parser.seen('S');
  6019. if (no_wait_for_cooling || parser.seen('R')) {
  6020. thermalManager.setTargetBed(parser.value_celsius());
  6021. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6022. if (parser.value_celsius() > BED_MINTEMP)
  6023. print_job_timer.start();
  6024. #endif
  6025. }
  6026. else return;
  6027. #if TEMP_BED_RESIDENCY_TIME > 0
  6028. millis_t residency_start_ms = 0;
  6029. // Loop until the temperature has stabilized
  6030. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6031. #else
  6032. // Loop until the temperature is very close target
  6033. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6034. #endif
  6035. float target_temp = -1.0, old_temp = 9999.0;
  6036. bool wants_to_cool = false;
  6037. wait_for_heatup = true;
  6038. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6039. KEEPALIVE_STATE(NOT_BUSY);
  6040. target_extruder = active_extruder; // for print_heaterstates
  6041. #if ENABLED(PRINTER_EVENT_LEDS)
  6042. const float start_temp = thermalManager.degBed();
  6043. uint8_t old_red = 255;
  6044. #endif
  6045. do {
  6046. // Target temperature might be changed during the loop
  6047. if (target_temp != thermalManager.degTargetBed()) {
  6048. wants_to_cool = thermalManager.isCoolingBed();
  6049. target_temp = thermalManager.degTargetBed();
  6050. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6051. if (no_wait_for_cooling && wants_to_cool) break;
  6052. }
  6053. now = millis();
  6054. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6055. next_temp_ms = now + 1000UL;
  6056. print_heaterstates();
  6057. #if TEMP_BED_RESIDENCY_TIME > 0
  6058. SERIAL_PROTOCOLPGM(" W:");
  6059. if (residency_start_ms) {
  6060. long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  6061. SERIAL_PROTOCOLLN(rem);
  6062. }
  6063. else {
  6064. SERIAL_PROTOCOLLNPGM("?");
  6065. }
  6066. #else
  6067. SERIAL_EOL;
  6068. #endif
  6069. }
  6070. idle();
  6071. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6072. const float temp = thermalManager.degBed();
  6073. #if ENABLED(PRINTER_EVENT_LEDS)
  6074. // Gradually change LED strip from blue to violet as bed heats up
  6075. if (!wants_to_cool) {
  6076. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6077. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6078. }
  6079. #endif
  6080. #if TEMP_BED_RESIDENCY_TIME > 0
  6081. const float temp_diff = fabs(target_temp - temp);
  6082. if (!residency_start_ms) {
  6083. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6084. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6085. }
  6086. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6087. // Restart the timer whenever the temperature falls outside the hysteresis.
  6088. residency_start_ms = now;
  6089. }
  6090. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6091. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6092. if (wants_to_cool) {
  6093. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6094. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6095. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6096. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6097. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6098. old_temp = temp;
  6099. }
  6100. }
  6101. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6102. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6103. KEEPALIVE_STATE(IN_HANDLER);
  6104. }
  6105. #endif // HAS_TEMP_BED
  6106. /**
  6107. * M110: Set Current Line Number
  6108. */
  6109. inline void gcode_M110() {
  6110. if (parser.seen('N')) gcode_LastN = parser.value_long();
  6111. }
  6112. /**
  6113. * M111: Set the debug level
  6114. */
  6115. inline void gcode_M111() {
  6116. marlin_debug_flags = parser.seen('S') ? parser.value_byte() : (uint8_t)DEBUG_NONE;
  6117. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6118. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6119. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6120. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6121. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6122. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6123. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6124. #endif
  6125. const static char* const debug_strings[] PROGMEM = {
  6126. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6127. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6128. , str_debug_32
  6129. #endif
  6130. };
  6131. SERIAL_ECHO_START;
  6132. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6133. if (marlin_debug_flags) {
  6134. uint8_t comma = 0;
  6135. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6136. if (TEST(marlin_debug_flags, i)) {
  6137. if (comma++) SERIAL_CHAR(',');
  6138. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6139. }
  6140. }
  6141. }
  6142. else {
  6143. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6144. }
  6145. SERIAL_EOL;
  6146. }
  6147. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6148. /**
  6149. * M113: Get or set Host Keepalive interval (0 to disable)
  6150. *
  6151. * S<seconds> Optional. Set the keepalive interval.
  6152. */
  6153. inline void gcode_M113() {
  6154. if (parser.seen('S')) {
  6155. host_keepalive_interval = parser.value_byte();
  6156. NOMORE(host_keepalive_interval, 60);
  6157. }
  6158. else {
  6159. SERIAL_ECHO_START;
  6160. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6161. }
  6162. }
  6163. #endif
  6164. #if ENABLED(BARICUDA)
  6165. #if HAS_HEATER_1
  6166. /**
  6167. * M126: Heater 1 valve open
  6168. */
  6169. inline void gcode_M126() { baricuda_valve_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6170. /**
  6171. * M127: Heater 1 valve close
  6172. */
  6173. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6174. #endif
  6175. #if HAS_HEATER_2
  6176. /**
  6177. * M128: Heater 2 valve open
  6178. */
  6179. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6180. /**
  6181. * M129: Heater 2 valve close
  6182. */
  6183. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6184. #endif
  6185. #endif // BARICUDA
  6186. /**
  6187. * M140: Set bed temperature
  6188. */
  6189. inline void gcode_M140() {
  6190. if (DEBUGGING(DRYRUN)) return;
  6191. if (parser.seen('S')) thermalManager.setTargetBed(parser.value_celsius());
  6192. }
  6193. #if ENABLED(ULTIPANEL)
  6194. /**
  6195. * M145: Set the heatup state for a material in the LCD menu
  6196. *
  6197. * S<material> (0=PLA, 1=ABS)
  6198. * H<hotend temp>
  6199. * B<bed temp>
  6200. * F<fan speed>
  6201. */
  6202. inline void gcode_M145() {
  6203. uint8_t material = parser.seen('S') ? (uint8_t)parser.value_int() : 0;
  6204. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6205. SERIAL_ERROR_START;
  6206. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6207. }
  6208. else {
  6209. int v;
  6210. if (parser.seen('H')) {
  6211. v = parser.value_int();
  6212. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6213. }
  6214. if (parser.seen('F')) {
  6215. v = parser.value_int();
  6216. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6217. }
  6218. #if TEMP_SENSOR_BED != 0
  6219. if (parser.seen('B')) {
  6220. v = parser.value_int();
  6221. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6222. }
  6223. #endif
  6224. }
  6225. }
  6226. #endif // ULTIPANEL
  6227. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6228. /**
  6229. * M149: Set temperature units
  6230. */
  6231. inline void gcode_M149() {
  6232. if (parser.seen('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6233. else if (parser.seen('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6234. else if (parser.seen('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6235. }
  6236. #endif
  6237. #if HAS_POWER_SWITCH
  6238. /**
  6239. * M80 : Turn on the Power Supply
  6240. * M80 S : Report the current state and exit
  6241. */
  6242. inline void gcode_M80() {
  6243. // S: Report the current power supply state and exit
  6244. if (parser.seen('S')) {
  6245. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6246. return;
  6247. }
  6248. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6249. /**
  6250. * If you have a switch on suicide pin, this is useful
  6251. * if you want to start another print with suicide feature after
  6252. * a print without suicide...
  6253. */
  6254. #if HAS_SUICIDE
  6255. OUT_WRITE(SUICIDE_PIN, HIGH);
  6256. #endif
  6257. #if ENABLED(HAVE_TMC2130)
  6258. delay(100);
  6259. tmc2130_init(); // Settings only stick when the driver has power
  6260. #endif
  6261. powersupply_on = true;
  6262. #if ENABLED(ULTIPANEL)
  6263. LCD_MESSAGEPGM(WELCOME_MSG);
  6264. #endif
  6265. }
  6266. #endif // HAS_POWER_SWITCH
  6267. /**
  6268. * M81: Turn off Power, including Power Supply, if there is one.
  6269. *
  6270. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6271. */
  6272. inline void gcode_M81() {
  6273. thermalManager.disable_all_heaters();
  6274. stepper.finish_and_disable();
  6275. #if FAN_COUNT > 0
  6276. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6277. #if ENABLED(PROBING_FANS_OFF)
  6278. fans_paused = false;
  6279. ZERO(paused_fanSpeeds);
  6280. #endif
  6281. #endif
  6282. safe_delay(1000); // Wait 1 second before switching off
  6283. #if HAS_SUICIDE
  6284. stepper.synchronize();
  6285. suicide();
  6286. #elif HAS_POWER_SWITCH
  6287. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6288. powersupply_on = false;
  6289. #endif
  6290. #if ENABLED(ULTIPANEL)
  6291. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6292. #endif
  6293. }
  6294. /**
  6295. * M82: Set E codes absolute (default)
  6296. */
  6297. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6298. /**
  6299. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6300. */
  6301. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6302. /**
  6303. * M18, M84: Disable stepper motors
  6304. */
  6305. inline void gcode_M18_M84() {
  6306. if (parser.seen('S')) {
  6307. stepper_inactive_time = parser.value_millis_from_seconds();
  6308. }
  6309. else {
  6310. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6311. if (all_axis) {
  6312. stepper.finish_and_disable();
  6313. }
  6314. else {
  6315. stepper.synchronize();
  6316. if (parser.seen('X')) disable_X();
  6317. if (parser.seen('Y')) disable_Y();
  6318. if (parser.seen('Z')) disable_Z();
  6319. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  6320. if (parser.seen('E')) disable_e_steppers();
  6321. #endif
  6322. }
  6323. }
  6324. }
  6325. /**
  6326. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6327. */
  6328. inline void gcode_M85() {
  6329. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6330. }
  6331. /**
  6332. * Multi-stepper support for M92, M201, M203
  6333. */
  6334. #if ENABLED(DISTINCT_E_FACTORS)
  6335. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6336. #define TARGET_EXTRUDER target_extruder
  6337. #else
  6338. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6339. #define TARGET_EXTRUDER 0
  6340. #endif
  6341. /**
  6342. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6343. * (Follows the same syntax as G92)
  6344. *
  6345. * With multiple extruders use T to specify which one.
  6346. */
  6347. inline void gcode_M92() {
  6348. GET_TARGET_EXTRUDER(92);
  6349. LOOP_XYZE(i) {
  6350. if (parser.seen(axis_codes[i])) {
  6351. if (i == E_AXIS) {
  6352. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6353. if (value < 20.0) {
  6354. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6355. planner.max_jerk[E_AXIS] *= factor;
  6356. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6357. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6358. }
  6359. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6360. }
  6361. else {
  6362. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6363. }
  6364. }
  6365. }
  6366. planner.refresh_positioning();
  6367. }
  6368. /**
  6369. * Output the current position to serial
  6370. */
  6371. static void report_current_position() {
  6372. SERIAL_PROTOCOLPGM("X:");
  6373. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6374. SERIAL_PROTOCOLPGM(" Y:");
  6375. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6376. SERIAL_PROTOCOLPGM(" Z:");
  6377. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6378. SERIAL_PROTOCOLPGM(" E:");
  6379. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6380. stepper.report_positions();
  6381. #if IS_SCARA
  6382. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6383. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6384. SERIAL_EOL;
  6385. #endif
  6386. }
  6387. /**
  6388. * M114: Output current position to serial port
  6389. */
  6390. inline void gcode_M114() { stepper.synchronize(); report_current_position(); }
  6391. /**
  6392. * M115: Capabilities string
  6393. */
  6394. inline void gcode_M115() {
  6395. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6396. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6397. // EEPROM (M500, M501)
  6398. #if ENABLED(EEPROM_SETTINGS)
  6399. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6400. #else
  6401. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6402. #endif
  6403. // AUTOREPORT_TEMP (M155)
  6404. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6405. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6406. #else
  6407. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6408. #endif
  6409. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6410. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6411. // AUTOLEVEL (G29)
  6412. #if HAS_ABL
  6413. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6414. #else
  6415. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6416. #endif
  6417. // Z_PROBE (G30)
  6418. #if HAS_BED_PROBE
  6419. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6420. #else
  6421. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6422. #endif
  6423. // MESH_REPORT (M420 V)
  6424. #if HAS_LEVELING
  6425. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6426. #else
  6427. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6428. #endif
  6429. // SOFTWARE_POWER (G30)
  6430. #if HAS_POWER_SWITCH
  6431. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6432. #else
  6433. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6434. #endif
  6435. // CASE LIGHTS (M355)
  6436. #if HAS_CASE_LIGHT
  6437. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6438. bool USEABLE_HARDWARE_PWM(uint8_t pin);
  6439. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  6440. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:1");
  6441. }
  6442. else
  6443. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6444. #else
  6445. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6446. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6447. #endif
  6448. // EMERGENCY_PARSER (M108, M112, M410)
  6449. #if ENABLED(EMERGENCY_PARSER)
  6450. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6451. #else
  6452. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6453. #endif
  6454. #endif // EXTENDED_CAPABILITIES_REPORT
  6455. }
  6456. /**
  6457. * M117: Set LCD Status Message
  6458. */
  6459. inline void gcode_M117() {
  6460. lcd_setstatus(parser.string_arg);
  6461. }
  6462. /**
  6463. * M119: Output endstop states to serial output
  6464. */
  6465. inline void gcode_M119() { endstops.M119(); }
  6466. /**
  6467. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6468. */
  6469. inline void gcode_M120() { endstops.enable_globally(true); }
  6470. /**
  6471. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6472. */
  6473. inline void gcode_M121() { endstops.enable_globally(false); }
  6474. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6475. /**
  6476. * M125: Store current position and move to filament change position.
  6477. * Called on pause (by M25) to prevent material leaking onto the
  6478. * object. On resume (M24) the head will be moved back and the
  6479. * print will resume.
  6480. *
  6481. * If Marlin is compiled without SD Card support, M125 can be
  6482. * used directly to pause the print and move to park position,
  6483. * resuming with a button click or M108.
  6484. *
  6485. * L = override retract length
  6486. * X = override X
  6487. * Y = override Y
  6488. * Z = override Z raise
  6489. */
  6490. inline void gcode_M125() {
  6491. // Initial retract before move to filament change position
  6492. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6493. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6494. - (PAUSE_PARK_RETRACT_LENGTH)
  6495. #endif
  6496. ;
  6497. // Lift Z axis
  6498. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  6499. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  6500. PAUSE_PARK_Z_ADD
  6501. #else
  6502. 0
  6503. #endif
  6504. ;
  6505. // Move XY axes to filament change position or given position
  6506. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  6507. #ifdef PAUSE_PARK_X_POS
  6508. + PAUSE_PARK_X_POS
  6509. #endif
  6510. ;
  6511. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  6512. #ifdef PAUSE_PARK_Y_POS
  6513. + PAUSE_PARK_Y_POS
  6514. #endif
  6515. ;
  6516. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6517. if (active_extruder > 0) {
  6518. if (!parser.seen('X')) x_pos += hotend_offset[X_AXIS][active_extruder];
  6519. if (!parser.seen('Y')) y_pos += hotend_offset[Y_AXIS][active_extruder];
  6520. }
  6521. #endif
  6522. const bool job_running = print_job_timer.isRunning();
  6523. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6524. #if DISABLED(SDSUPPORT)
  6525. // Wait for lcd click or M108
  6526. wait_for_filament_reload();
  6527. // Return to print position and continue
  6528. resume_print();
  6529. if (job_running) print_job_timer.start();
  6530. #endif
  6531. }
  6532. }
  6533. #endif // PARK_HEAD_ON_PAUSE
  6534. #if HAS_COLOR_LEDS
  6535. /**
  6536. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6537. *
  6538. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6539. *
  6540. * Examples:
  6541. *
  6542. * M150 R255 ; Turn LED red
  6543. * M150 R255 U127 ; Turn LED orange (PWM only)
  6544. * M150 ; Turn LED off
  6545. * M150 R U B ; Turn LED white
  6546. * M150 W ; Turn LED white using a white LED
  6547. *
  6548. */
  6549. inline void gcode_M150() {
  6550. set_led_color(
  6551. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6552. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6553. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6554. #if ENABLED(RGBW_LED)
  6555. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6556. #endif
  6557. );
  6558. }
  6559. #endif // BLINKM || RGB_LED
  6560. /**
  6561. * M200: Set filament diameter and set E axis units to cubic units
  6562. *
  6563. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6564. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6565. */
  6566. inline void gcode_M200() {
  6567. if (get_target_extruder_from_command(200)) return;
  6568. if (parser.seen('D')) {
  6569. // setting any extruder filament size disables volumetric on the assumption that
  6570. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6571. // for all extruders
  6572. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6573. if (volumetric_enabled) {
  6574. filament_size[target_extruder] = parser.value_linear_units();
  6575. // make sure all extruders have some sane value for the filament size
  6576. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6577. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6578. }
  6579. }
  6580. calculate_volumetric_multipliers();
  6581. }
  6582. /**
  6583. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6584. *
  6585. * With multiple extruders use T to specify which one.
  6586. */
  6587. inline void gcode_M201() {
  6588. GET_TARGET_EXTRUDER(201);
  6589. LOOP_XYZE(i) {
  6590. if (parser.seen(axis_codes[i])) {
  6591. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6592. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6593. }
  6594. }
  6595. // steps per sq second need to be updated to agree with the units per sq second (as they are what is used in the planner)
  6596. planner.reset_acceleration_rates();
  6597. }
  6598. #if 0 // Not used for Sprinter/grbl gen6
  6599. inline void gcode_M202() {
  6600. LOOP_XYZE(i) {
  6601. if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i];
  6602. }
  6603. }
  6604. #endif
  6605. /**
  6606. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6607. *
  6608. * With multiple extruders use T to specify which one.
  6609. */
  6610. inline void gcode_M203() {
  6611. GET_TARGET_EXTRUDER(203);
  6612. LOOP_XYZE(i)
  6613. if (parser.seen(axis_codes[i])) {
  6614. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6615. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6616. }
  6617. }
  6618. /**
  6619. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6620. *
  6621. * P = Printing moves
  6622. * R = Retract only (no X, Y, Z) moves
  6623. * T = Travel (non printing) moves
  6624. *
  6625. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6626. */
  6627. inline void gcode_M204() {
  6628. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6629. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6630. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6631. }
  6632. if (parser.seen('P')) {
  6633. planner.acceleration = parser.value_linear_units();
  6634. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6635. }
  6636. if (parser.seen('R')) {
  6637. planner.retract_acceleration = parser.value_linear_units();
  6638. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6639. }
  6640. if (parser.seen('T')) {
  6641. planner.travel_acceleration = parser.value_linear_units();
  6642. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6643. }
  6644. }
  6645. /**
  6646. * M205: Set Advanced Settings
  6647. *
  6648. * S = Min Feed Rate (units/s)
  6649. * T = Min Travel Feed Rate (units/s)
  6650. * B = Min Segment Time (µs)
  6651. * X = Max X Jerk (units/sec^2)
  6652. * Y = Max Y Jerk (units/sec^2)
  6653. * Z = Max Z Jerk (units/sec^2)
  6654. * E = Max E Jerk (units/sec^2)
  6655. */
  6656. inline void gcode_M205() {
  6657. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6658. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6659. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6660. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6661. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6662. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6663. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6664. }
  6665. #if HAS_M206_COMMAND
  6666. /**
  6667. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6668. *
  6669. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6670. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6671. * *** In the next 1.2 release, it will simply be disabled by default.
  6672. */
  6673. inline void gcode_M206() {
  6674. LOOP_XYZ(i)
  6675. if (parser.seen(axis_codes[i]))
  6676. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6677. #if ENABLED(MORGAN_SCARA)
  6678. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6679. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6680. #endif
  6681. SYNC_PLAN_POSITION_KINEMATIC();
  6682. report_current_position();
  6683. }
  6684. #endif // HAS_M206_COMMAND
  6685. #if ENABLED(DELTA)
  6686. /**
  6687. * M665: Set delta configurations
  6688. *
  6689. * H = delta height
  6690. * L = diagonal rod
  6691. * R = delta radius
  6692. * S = segments per second
  6693. * B = delta calibration radius
  6694. * X = Alpha (Tower 1) angle trim
  6695. * Y = Beta (Tower 2) angle trim
  6696. * Z = Rotate A and B by this angle
  6697. */
  6698. inline void gcode_M665() {
  6699. if (parser.seen('H')) {
  6700. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6701. current_position[Z_AXIS] += parser.value_linear_units() - DELTA_HEIGHT - home_offset[Z_AXIS];
  6702. update_software_endstops(Z_AXIS);
  6703. }
  6704. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6705. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6706. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6707. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6708. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6709. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6710. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6711. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6712. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6713. }
  6714. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6715. }
  6716. /**
  6717. * M666: Set delta endstop adjustment
  6718. */
  6719. inline void gcode_M666() {
  6720. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6721. if (DEBUGGING(LEVELING)) {
  6722. SERIAL_ECHOLNPGM(">>> gcode_M666");
  6723. }
  6724. #endif
  6725. LOOP_XYZ(i) {
  6726. if (parser.seen(axis_codes[i])) {
  6727. endstop_adj[i] = parser.value_linear_units();
  6728. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6729. if (DEBUGGING(LEVELING)) {
  6730. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  6731. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  6732. }
  6733. #endif
  6734. }
  6735. }
  6736. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6737. if (DEBUGGING(LEVELING)) {
  6738. SERIAL_ECHOLNPGM("<<< gcode_M666");
  6739. }
  6740. #endif
  6741. // normalize endstops so all are <=0; set the residue to delta height
  6742. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  6743. home_offset[Z_AXIS] -= z_temp;
  6744. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  6745. }
  6746. #elif IS_SCARA
  6747. /**
  6748. * M665: Set SCARA settings
  6749. *
  6750. * Parameters:
  6751. *
  6752. * S[segments-per-second] - Segments-per-second
  6753. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  6754. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  6755. *
  6756. * A, P, and X are all aliases for the shoulder angle
  6757. * B, T, and Y are all aliases for the elbow angle
  6758. */
  6759. inline void gcode_M665() {
  6760. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6761. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  6762. const uint8_t sumAPX = hasA + hasP + hasX;
  6763. if (sumAPX == 1)
  6764. home_offset[A_AXIS] = parser.value_float();
  6765. else if (sumAPX > 1) {
  6766. SERIAL_ERROR_START;
  6767. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  6768. return;
  6769. }
  6770. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  6771. const uint8_t sumBTY = hasB + hasT + hasY;
  6772. if (sumBTY == 1)
  6773. home_offset[B_AXIS] = parser.value_float();
  6774. else if (sumBTY > 1) {
  6775. SERIAL_ERROR_START;
  6776. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  6777. return;
  6778. }
  6779. }
  6780. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  6781. /**
  6782. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  6783. */
  6784. inline void gcode_M666() {
  6785. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  6786. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  6787. }
  6788. #endif // !DELTA && Z_DUAL_ENDSTOPS
  6789. #if ENABLED(FWRETRACT)
  6790. /**
  6791. * M207: Set firmware retraction values
  6792. *
  6793. * S[+units] retract_length
  6794. * W[+units] retract_length_swap (multi-extruder)
  6795. * F[units/min] retract_feedrate_mm_s
  6796. * Z[units] retract_zlift
  6797. */
  6798. inline void gcode_M207() {
  6799. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  6800. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6801. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  6802. #if EXTRUDERS > 1
  6803. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  6804. #endif
  6805. }
  6806. /**
  6807. * M208: Set firmware un-retraction values
  6808. *
  6809. * S[+units] retract_recover_length (in addition to M207 S*)
  6810. * W[+units] retract_recover_length_swap (multi-extruder)
  6811. * F[units/min] retract_recover_feedrate_mm_s
  6812. */
  6813. inline void gcode_M208() {
  6814. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  6815. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6816. #if EXTRUDERS > 1
  6817. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  6818. #endif
  6819. }
  6820. /**
  6821. * M209: Enable automatic retract (M209 S1)
  6822. * For slicers that don't support G10/11, reversed extrude-only
  6823. * moves will be classified as retraction.
  6824. */
  6825. inline void gcode_M209() {
  6826. if (parser.seen('S')) {
  6827. autoretract_enabled = parser.value_bool();
  6828. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  6829. }
  6830. }
  6831. #endif // FWRETRACT
  6832. /**
  6833. * M211: Enable, Disable, and/or Report software endstops
  6834. *
  6835. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  6836. */
  6837. inline void gcode_M211() {
  6838. SERIAL_ECHO_START;
  6839. #if HAS_SOFTWARE_ENDSTOPS
  6840. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  6841. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  6842. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  6843. #else
  6844. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  6845. SERIAL_ECHOPGM(MSG_OFF);
  6846. #endif
  6847. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  6848. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  6849. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  6850. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  6851. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  6852. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  6853. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  6854. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  6855. }
  6856. #if HOTENDS > 1
  6857. /**
  6858. * M218 - set hotend offset (in linear units)
  6859. *
  6860. * T<tool>
  6861. * X<xoffset>
  6862. * Y<yoffset>
  6863. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  6864. */
  6865. inline void gcode_M218() {
  6866. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  6867. if (parser.seen('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  6868. if (parser.seen('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  6869. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  6870. if (parser.seen('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  6871. #endif
  6872. SERIAL_ECHO_START;
  6873. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  6874. HOTEND_LOOP() {
  6875. SERIAL_CHAR(' ');
  6876. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  6877. SERIAL_CHAR(',');
  6878. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  6879. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  6880. SERIAL_CHAR(',');
  6881. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  6882. #endif
  6883. }
  6884. SERIAL_EOL;
  6885. }
  6886. #endif // HOTENDS > 1
  6887. /**
  6888. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  6889. */
  6890. inline void gcode_M220() {
  6891. if (parser.seen('S')) feedrate_percentage = parser.value_int();
  6892. }
  6893. /**
  6894. * M221: Set extrusion percentage (M221 T0 S95)
  6895. */
  6896. inline void gcode_M221() {
  6897. if (get_target_extruder_from_command(221)) return;
  6898. if (parser.seen('S'))
  6899. flow_percentage[target_extruder] = parser.value_int();
  6900. }
  6901. /**
  6902. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  6903. */
  6904. inline void gcode_M226() {
  6905. if (parser.seen('P')) {
  6906. int pin_number = parser.value_int(),
  6907. pin_state = parser.seen('S') ? parser.value_int() : -1; // required pin state - default is inverted
  6908. if (pin_state >= -1 && pin_state <= 1 && pin_number > -1 && !pin_is_protected(pin_number)) {
  6909. int target = LOW;
  6910. stepper.synchronize();
  6911. pinMode(pin_number, INPUT);
  6912. switch (pin_state) {
  6913. case 1:
  6914. target = HIGH;
  6915. break;
  6916. case 0:
  6917. target = LOW;
  6918. break;
  6919. case -1:
  6920. target = !digitalRead(pin_number);
  6921. break;
  6922. }
  6923. while (digitalRead(pin_number) != target) idle();
  6924. } // pin_state -1 0 1 && pin_number > -1
  6925. } // parser.seen('P')
  6926. }
  6927. #if ENABLED(EXPERIMENTAL_I2CBUS)
  6928. /**
  6929. * M260: Send data to a I2C slave device
  6930. *
  6931. * This is a PoC, the formating and arguments for the GCODE will
  6932. * change to be more compatible, the current proposal is:
  6933. *
  6934. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  6935. *
  6936. * M260 B<byte-1 value in base 10>
  6937. * M260 B<byte-2 value in base 10>
  6938. * M260 B<byte-3 value in base 10>
  6939. *
  6940. * M260 S1 ; Send the buffered data and reset the buffer
  6941. * M260 R1 ; Reset the buffer without sending data
  6942. *
  6943. */
  6944. inline void gcode_M260() {
  6945. // Set the target address
  6946. if (parser.seen('A')) i2c.address(parser.value_byte());
  6947. // Add a new byte to the buffer
  6948. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  6949. // Flush the buffer to the bus
  6950. if (parser.seen('S')) i2c.send();
  6951. // Reset and rewind the buffer
  6952. else if (parser.seen('R')) i2c.reset();
  6953. }
  6954. /**
  6955. * M261: Request X bytes from I2C slave device
  6956. *
  6957. * Usage: M261 A<slave device address base 10> B<number of bytes>
  6958. */
  6959. inline void gcode_M261() {
  6960. if (parser.seen('A')) i2c.address(parser.value_byte());
  6961. uint8_t bytes = parser.seen('B') ? parser.value_byte() : 1;
  6962. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  6963. i2c.relay(bytes);
  6964. }
  6965. else {
  6966. SERIAL_ERROR_START;
  6967. SERIAL_ERRORLN("Bad i2c request");
  6968. }
  6969. }
  6970. #endif // EXPERIMENTAL_I2CBUS
  6971. #if HAS_SERVOS
  6972. /**
  6973. * M280: Get or set servo position. P<index> [S<angle>]
  6974. */
  6975. inline void gcode_M280() {
  6976. if (!parser.seen('P')) return;
  6977. int servo_index = parser.value_int();
  6978. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  6979. if (parser.seen('S'))
  6980. MOVE_SERVO(servo_index, parser.value_int());
  6981. else {
  6982. SERIAL_ECHO_START;
  6983. SERIAL_ECHOPAIR(" Servo ", servo_index);
  6984. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  6985. }
  6986. }
  6987. else {
  6988. SERIAL_ERROR_START;
  6989. SERIAL_ECHOPAIR("Servo ", servo_index);
  6990. SERIAL_ECHOLNPGM(" out of range");
  6991. }
  6992. }
  6993. #endif // HAS_SERVOS
  6994. #if HAS_BUZZER
  6995. /**
  6996. * M300: Play beep sound S<frequency Hz> P<duration ms>
  6997. */
  6998. inline void gcode_M300() {
  6999. uint16_t const frequency = parser.seen('S') ? parser.value_ushort() : 260;
  7000. uint16_t duration = parser.seen('P') ? parser.value_ushort() : 1000;
  7001. // Limits the tone duration to 0-5 seconds.
  7002. NOMORE(duration, 5000);
  7003. BUZZ(duration, frequency);
  7004. }
  7005. #endif // HAS_BUZZER
  7006. #if ENABLED(PIDTEMP)
  7007. /**
  7008. * M301: Set PID parameters P I D (and optionally C, L)
  7009. *
  7010. * P[float] Kp term
  7011. * I[float] Ki term (unscaled)
  7012. * D[float] Kd term (unscaled)
  7013. *
  7014. * With PID_EXTRUSION_SCALING:
  7015. *
  7016. * C[float] Kc term
  7017. * L[float] LPQ length
  7018. */
  7019. inline void gcode_M301() {
  7020. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7021. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7022. int e = parser.seen('E') ? parser.value_int() : 0; // extruder being updated
  7023. if (e < HOTENDS) { // catch bad input value
  7024. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7025. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7026. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7027. #if ENABLED(PID_EXTRUSION_SCALING)
  7028. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7029. if (parser.seen('L')) lpq_len = parser.value_float();
  7030. NOMORE(lpq_len, LPQ_MAX_LEN);
  7031. #endif
  7032. thermalManager.updatePID();
  7033. SERIAL_ECHO_START;
  7034. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7035. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7036. #endif // PID_PARAMS_PER_HOTEND
  7037. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7038. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7039. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7040. #if ENABLED(PID_EXTRUSION_SCALING)
  7041. //Kc does not have scaling applied above, or in resetting defaults
  7042. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7043. #endif
  7044. SERIAL_EOL;
  7045. }
  7046. else {
  7047. SERIAL_ERROR_START;
  7048. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7049. }
  7050. }
  7051. #endif // PIDTEMP
  7052. #if ENABLED(PIDTEMPBED)
  7053. inline void gcode_M304() {
  7054. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7055. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7056. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7057. thermalManager.updatePID();
  7058. SERIAL_ECHO_START;
  7059. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7060. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7061. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7062. }
  7063. #endif // PIDTEMPBED
  7064. #if defined(CHDK) || HAS_PHOTOGRAPH
  7065. /**
  7066. * M240: Trigger a camera by emulating a Canon RC-1
  7067. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7068. */
  7069. inline void gcode_M240() {
  7070. #ifdef CHDK
  7071. OUT_WRITE(CHDK, HIGH);
  7072. chdkHigh = millis();
  7073. chdkActive = true;
  7074. #elif HAS_PHOTOGRAPH
  7075. const uint8_t NUM_PULSES = 16;
  7076. const float PULSE_LENGTH = 0.01524;
  7077. for (int i = 0; i < NUM_PULSES; i++) {
  7078. WRITE(PHOTOGRAPH_PIN, HIGH);
  7079. _delay_ms(PULSE_LENGTH);
  7080. WRITE(PHOTOGRAPH_PIN, LOW);
  7081. _delay_ms(PULSE_LENGTH);
  7082. }
  7083. delay(7.33);
  7084. for (int i = 0; i < NUM_PULSES; i++) {
  7085. WRITE(PHOTOGRAPH_PIN, HIGH);
  7086. _delay_ms(PULSE_LENGTH);
  7087. WRITE(PHOTOGRAPH_PIN, LOW);
  7088. _delay_ms(PULSE_LENGTH);
  7089. }
  7090. #endif // !CHDK && HAS_PHOTOGRAPH
  7091. }
  7092. #endif // CHDK || PHOTOGRAPH_PIN
  7093. #if HAS_LCD_CONTRAST
  7094. /**
  7095. * M250: Read and optionally set the LCD contrast
  7096. */
  7097. inline void gcode_M250() {
  7098. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7099. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7100. SERIAL_PROTOCOL(lcd_contrast);
  7101. SERIAL_EOL;
  7102. }
  7103. #endif // HAS_LCD_CONTRAST
  7104. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7105. /**
  7106. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7107. *
  7108. * S<temperature> sets the minimum extrude temperature
  7109. * P<bool> enables (1) or disables (0) cold extrusion
  7110. *
  7111. * Examples:
  7112. *
  7113. * M302 ; report current cold extrusion state
  7114. * M302 P0 ; enable cold extrusion checking
  7115. * M302 P1 ; disables cold extrusion checking
  7116. * M302 S0 ; always allow extrusion (disables checking)
  7117. * M302 S170 ; only allow extrusion above 170
  7118. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7119. */
  7120. inline void gcode_M302() {
  7121. bool seen_S = parser.seen('S');
  7122. if (seen_S) {
  7123. thermalManager.extrude_min_temp = parser.value_celsius();
  7124. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7125. }
  7126. if (parser.seen('P'))
  7127. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7128. else if (!seen_S) {
  7129. // Report current state
  7130. SERIAL_ECHO_START;
  7131. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7132. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7133. SERIAL_ECHOLNPGM("C)");
  7134. }
  7135. }
  7136. #endif // PREVENT_COLD_EXTRUSION
  7137. /**
  7138. * M303: PID relay autotune
  7139. *
  7140. * S<temperature> sets the target temperature. (default 150C)
  7141. * E<extruder> (-1 for the bed) (default 0)
  7142. * C<cycles>
  7143. * U<bool> with a non-zero value will apply the result to current settings
  7144. */
  7145. inline void gcode_M303() {
  7146. #if HAS_PID_HEATING
  7147. const int e = parser.seen('E') ? parser.value_int() : 0,
  7148. c = parser.seen('C') ? parser.value_int() : 5;
  7149. const bool u = parser.seen('U') && parser.value_bool();
  7150. int16_t temp = parser.seen('S') ? parser.value_celsius() : (e < 0 ? 70 : 150);
  7151. if (WITHIN(e, 0, HOTENDS - 1))
  7152. target_extruder = e;
  7153. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  7154. thermalManager.PID_autotune(temp, e, c, u);
  7155. KEEPALIVE_STATE(IN_HANDLER);
  7156. #else
  7157. SERIAL_ERROR_START;
  7158. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7159. #endif
  7160. }
  7161. #if ENABLED(MORGAN_SCARA)
  7162. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7163. if (IsRunning()) {
  7164. forward_kinematics_SCARA(delta_a, delta_b);
  7165. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7166. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7167. destination[Z_AXIS] = current_position[Z_AXIS];
  7168. prepare_move_to_destination();
  7169. return true;
  7170. }
  7171. return false;
  7172. }
  7173. /**
  7174. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7175. */
  7176. inline bool gcode_M360() {
  7177. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7178. return SCARA_move_to_cal(0, 120);
  7179. }
  7180. /**
  7181. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7182. */
  7183. inline bool gcode_M361() {
  7184. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7185. return SCARA_move_to_cal(90, 130);
  7186. }
  7187. /**
  7188. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7189. */
  7190. inline bool gcode_M362() {
  7191. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7192. return SCARA_move_to_cal(60, 180);
  7193. }
  7194. /**
  7195. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7196. */
  7197. inline bool gcode_M363() {
  7198. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7199. return SCARA_move_to_cal(50, 90);
  7200. }
  7201. /**
  7202. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7203. */
  7204. inline bool gcode_M364() {
  7205. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7206. return SCARA_move_to_cal(45, 135);
  7207. }
  7208. #endif // SCARA
  7209. #if ENABLED(EXT_SOLENOID)
  7210. void enable_solenoid(const uint8_t num) {
  7211. switch (num) {
  7212. case 0:
  7213. OUT_WRITE(SOL0_PIN, HIGH);
  7214. break;
  7215. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7216. case 1:
  7217. OUT_WRITE(SOL1_PIN, HIGH);
  7218. break;
  7219. #endif
  7220. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7221. case 2:
  7222. OUT_WRITE(SOL2_PIN, HIGH);
  7223. break;
  7224. #endif
  7225. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7226. case 3:
  7227. OUT_WRITE(SOL3_PIN, HIGH);
  7228. break;
  7229. #endif
  7230. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7231. case 4:
  7232. OUT_WRITE(SOL4_PIN, HIGH);
  7233. break;
  7234. #endif
  7235. default:
  7236. SERIAL_ECHO_START;
  7237. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7238. break;
  7239. }
  7240. }
  7241. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7242. void disable_all_solenoids() {
  7243. OUT_WRITE(SOL0_PIN, LOW);
  7244. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7245. OUT_WRITE(SOL1_PIN, LOW);
  7246. #endif
  7247. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7248. OUT_WRITE(SOL2_PIN, LOW);
  7249. #endif
  7250. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7251. OUT_WRITE(SOL3_PIN, LOW);
  7252. #endif
  7253. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7254. OUT_WRITE(SOL4_PIN, LOW);
  7255. #endif
  7256. }
  7257. /**
  7258. * M380: Enable solenoid on the active extruder
  7259. */
  7260. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7261. /**
  7262. * M381: Disable all solenoids
  7263. */
  7264. inline void gcode_M381() { disable_all_solenoids(); }
  7265. #endif // EXT_SOLENOID
  7266. /**
  7267. * M400: Finish all moves
  7268. */
  7269. inline void gcode_M400() { stepper.synchronize(); }
  7270. #if HAS_BED_PROBE
  7271. /**
  7272. * M401: Engage Z Servo endstop if available
  7273. */
  7274. inline void gcode_M401() { DEPLOY_PROBE(); }
  7275. /**
  7276. * M402: Retract Z Servo endstop if enabled
  7277. */
  7278. inline void gcode_M402() { STOW_PROBE(); }
  7279. #endif // HAS_BED_PROBE
  7280. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7281. /**
  7282. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7283. */
  7284. inline void gcode_M404() {
  7285. if (parser.seen('W')) {
  7286. filament_width_nominal = parser.value_linear_units();
  7287. }
  7288. else {
  7289. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7290. SERIAL_PROTOCOLLN(filament_width_nominal);
  7291. }
  7292. }
  7293. /**
  7294. * M405: Turn on filament sensor for control
  7295. */
  7296. inline void gcode_M405() {
  7297. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  7298. // everything else, it uses parser.value_int() instead of parser.value_linear_units().
  7299. if (parser.seen('D')) meas_delay_cm = parser.value_int();
  7300. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7301. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7302. const int temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7303. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7304. measurement_delay[i] = temp_ratio;
  7305. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7306. }
  7307. filament_sensor = true;
  7308. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7309. //SERIAL_PROTOCOL(filament_width_meas);
  7310. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7311. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7312. }
  7313. /**
  7314. * M406: Turn off filament sensor for control
  7315. */
  7316. inline void gcode_M406() { filament_sensor = false; }
  7317. /**
  7318. * M407: Get measured filament diameter on serial output
  7319. */
  7320. inline void gcode_M407() {
  7321. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7322. SERIAL_PROTOCOLLN(filament_width_meas);
  7323. }
  7324. #endif // FILAMENT_WIDTH_SENSOR
  7325. void quickstop_stepper() {
  7326. stepper.quick_stop();
  7327. stepper.synchronize();
  7328. set_current_from_steppers_for_axis(ALL_AXES);
  7329. SYNC_PLAN_POSITION_KINEMATIC();
  7330. }
  7331. #if HAS_LEVELING
  7332. /**
  7333. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7334. *
  7335. * S[bool] Turns leveling on or off
  7336. * Z[height] Sets the Z fade height (0 or none to disable)
  7337. * V[bool] Verbose - Print the leveling grid
  7338. *
  7339. * With AUTO_BED_LEVELING_UBL only:
  7340. *
  7341. * L[index] Load UBL mesh from index (0 is default)
  7342. */
  7343. inline void gcode_M420() {
  7344. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7345. // L to load a mesh from the EEPROM
  7346. if (parser.seen('L')) {
  7347. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7348. const int16_t a = settings.calc_num_meshes();
  7349. if (!a) {
  7350. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7351. return;
  7352. }
  7353. if (!WITHIN(storage_slot, 0, a - 1)) {
  7354. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7355. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7356. return;
  7357. }
  7358. settings.load_mesh(storage_slot);
  7359. ubl.state.storage_slot = storage_slot;
  7360. }
  7361. #endif // AUTO_BED_LEVELING_UBL
  7362. // V to print the matrix or mesh
  7363. if (parser.seen('V')) {
  7364. #if ABL_PLANAR
  7365. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7366. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7367. if (leveling_is_valid()) {
  7368. print_bilinear_leveling_grid();
  7369. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7370. bed_level_virt_print();
  7371. #endif
  7372. }
  7373. #elif ENABLED(MESH_BED_LEVELING)
  7374. if (leveling_is_valid()) {
  7375. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7376. mbl_mesh_report();
  7377. }
  7378. #endif
  7379. }
  7380. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7381. // L to load a mesh from the EEPROM
  7382. if (parser.seen('L') || parser.seen('V')) {
  7383. ubl.display_map(0); // Currently only supports one map type
  7384. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7385. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7386. }
  7387. #endif
  7388. bool to_enable = false;
  7389. if (parser.seen('S')) {
  7390. to_enable = parser.value_bool();
  7391. set_bed_leveling_enabled(to_enable);
  7392. }
  7393. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7394. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7395. #endif
  7396. const bool new_status = leveling_is_active();
  7397. if (to_enable && !new_status) {
  7398. SERIAL_ERROR_START;
  7399. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7400. }
  7401. SERIAL_ECHO_START;
  7402. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7403. }
  7404. #endif
  7405. #if ENABLED(MESH_BED_LEVELING)
  7406. /**
  7407. * M421: Set a single Mesh Bed Leveling Z coordinate
  7408. *
  7409. * Usage:
  7410. * M421 X<linear> Y<linear> Z<linear>
  7411. * M421 X<linear> Y<linear> Q<offset>
  7412. * M421 I<xindex> J<yindex> Z<linear>
  7413. * M421 I<xindex> J<yindex> Q<offset>
  7414. */
  7415. inline void gcode_M421() {
  7416. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7417. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7418. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7419. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7420. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7421. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7422. SERIAL_ERROR_START;
  7423. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7424. }
  7425. else if (ix < 0 || iy < 0) {
  7426. SERIAL_ERROR_START;
  7427. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7428. }
  7429. else
  7430. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7431. }
  7432. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7433. /**
  7434. * M421: Set a single Mesh Bed Leveling Z coordinate
  7435. *
  7436. * Usage:
  7437. * M421 I<xindex> J<yindex> Z<linear>
  7438. * M421 I<xindex> J<yindex> Q<offset>
  7439. */
  7440. inline void gcode_M421() {
  7441. const bool hasI = parser.seen('I');
  7442. const int8_t ix = hasI ? parser.value_int() : -1;
  7443. const bool hasJ = parser.seen('J');
  7444. const int8_t iy = hasJ ? parser.value_int() : -1;
  7445. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7446. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  7447. SERIAL_ERROR_START;
  7448. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7449. }
  7450. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7451. SERIAL_ERROR_START;
  7452. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7453. }
  7454. else {
  7455. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7456. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7457. bed_level_virt_interpolate();
  7458. #endif
  7459. }
  7460. }
  7461. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7462. /**
  7463. * M421: Set a single Mesh Bed Leveling Z coordinate
  7464. *
  7465. * Usage:
  7466. * M421 I<xindex> J<yindex> Z<linear>
  7467. * M421 I<xindex> J<yindex> Q<offset>
  7468. * M421 C Z<linear>
  7469. * M421 C Q<offset>
  7470. */
  7471. inline void gcode_M421() {
  7472. const bool hasC = parser.seen('C'), hasI = parser.seen('I');
  7473. int8_t ix = hasI ? parser.value_int() : -1;
  7474. const bool hasJ = parser.seen('J');
  7475. int8_t iy = hasJ ? parser.value_int() : -1;
  7476. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7477. if (hasC) {
  7478. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL, false);
  7479. ix = location.x_index;
  7480. iy = location.y_index;
  7481. }
  7482. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7483. SERIAL_ERROR_START;
  7484. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7485. }
  7486. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7487. SERIAL_ERROR_START;
  7488. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7489. }
  7490. else
  7491. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7492. }
  7493. #endif // AUTO_BED_LEVELING_UBL
  7494. #if HAS_M206_COMMAND
  7495. /**
  7496. * M428: Set home_offset based on the distance between the
  7497. * current_position and the nearest "reference point."
  7498. * If an axis is past center its endstop position
  7499. * is the reference-point. Otherwise it uses 0. This allows
  7500. * the Z offset to be set near the bed when using a max endstop.
  7501. *
  7502. * M428 can't be used more than 2cm away from 0 or an endstop.
  7503. *
  7504. * Use M206 to set these values directly.
  7505. */
  7506. inline void gcode_M428() {
  7507. bool err = false;
  7508. LOOP_XYZ(i) {
  7509. if (axis_homed[i]) {
  7510. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7511. diff = base - RAW_POSITION(current_position[i], i);
  7512. if (WITHIN(diff, -20, 20)) {
  7513. set_home_offset((AxisEnum)i, diff);
  7514. }
  7515. else {
  7516. SERIAL_ERROR_START;
  7517. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7518. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7519. BUZZ(200, 40);
  7520. err = true;
  7521. break;
  7522. }
  7523. }
  7524. }
  7525. if (!err) {
  7526. SYNC_PLAN_POSITION_KINEMATIC();
  7527. report_current_position();
  7528. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7529. BUZZ(100, 659);
  7530. BUZZ(100, 698);
  7531. }
  7532. }
  7533. #endif // HAS_M206_COMMAND
  7534. /**
  7535. * M500: Store settings in EEPROM
  7536. */
  7537. inline void gcode_M500() {
  7538. (void)settings.save();
  7539. }
  7540. /**
  7541. * M501: Read settings from EEPROM
  7542. */
  7543. inline void gcode_M501() {
  7544. (void)settings.load();
  7545. }
  7546. /**
  7547. * M502: Revert to default settings
  7548. */
  7549. inline void gcode_M502() {
  7550. (void)settings.reset();
  7551. }
  7552. /**
  7553. * M503: print settings currently in memory
  7554. */
  7555. inline void gcode_M503() {
  7556. (void)settings.report(parser.seen('S') && !parser.value_bool());
  7557. }
  7558. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7559. /**
  7560. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7561. */
  7562. inline void gcode_M540() {
  7563. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7564. }
  7565. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7566. #if HAS_BED_PROBE
  7567. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7568. static float last_zoffset = NAN;
  7569. if (!isnan(last_zoffset)) {
  7570. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7571. const float diff = zprobe_zoffset - last_zoffset;
  7572. #endif
  7573. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7574. // Correct bilinear grid for new probe offset
  7575. if (diff) {
  7576. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7577. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7578. z_values[x][y] -= diff;
  7579. }
  7580. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7581. bed_level_virt_interpolate();
  7582. #endif
  7583. #endif
  7584. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7585. if (!no_babystep && leveling_is_active())
  7586. thermalManager.babystep_axis(Z_AXIS, -lround(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7587. #else
  7588. UNUSED(no_babystep);
  7589. #endif
  7590. #if ENABLED(DELTA) // correct the delta_height
  7591. home_offset[Z_AXIS] -= diff;
  7592. #endif
  7593. }
  7594. last_zoffset = zprobe_zoffset;
  7595. }
  7596. inline void gcode_M851() {
  7597. SERIAL_ECHO_START;
  7598. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7599. if (parser.seen('Z')) {
  7600. const float value = parser.value_linear_units();
  7601. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7602. zprobe_zoffset = value;
  7603. refresh_zprobe_zoffset();
  7604. SERIAL_ECHO(zprobe_zoffset);
  7605. }
  7606. else
  7607. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7608. }
  7609. else
  7610. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7611. SERIAL_EOL;
  7612. }
  7613. #endif // HAS_BED_PROBE
  7614. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7615. /**
  7616. * M600: Pause for filament change
  7617. *
  7618. * E[distance] - Retract the filament this far (negative value)
  7619. * Z[distance] - Move the Z axis by this distance
  7620. * X[position] - Move to this X position, with Y
  7621. * Y[position] - Move to this Y position, with X
  7622. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7623. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7624. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7625. *
  7626. * Default values are used for omitted arguments.
  7627. *
  7628. */
  7629. inline void gcode_M600() {
  7630. // Initial retract before move to filament change position
  7631. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7632. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7633. - (PAUSE_PARK_RETRACT_LENGTH)
  7634. #endif
  7635. ;
  7636. // Lift Z axis
  7637. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  7638. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7639. PAUSE_PARK_Z_ADD
  7640. #else
  7641. 0
  7642. #endif
  7643. ;
  7644. // Move XY axes to filament exchange position
  7645. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  7646. #ifdef PAUSE_PARK_X_POS
  7647. + PAUSE_PARK_X_POS
  7648. #endif
  7649. ;
  7650. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  7651. #ifdef PAUSE_PARK_Y_POS
  7652. + PAUSE_PARK_Y_POS
  7653. #endif
  7654. ;
  7655. // Unload filament
  7656. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7657. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7658. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7659. #endif
  7660. ;
  7661. // Load filament
  7662. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7663. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7664. + FILAMENT_CHANGE_LOAD_LENGTH
  7665. #endif
  7666. ;
  7667. const int beep_count = parser.seen('B') ? parser.value_int() :
  7668. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7669. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7670. #else
  7671. -1
  7672. #endif
  7673. ;
  7674. const bool job_running = print_job_timer.isRunning();
  7675. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7676. wait_for_filament_reload(beep_count);
  7677. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7678. }
  7679. // Resume the print job timer if it was running
  7680. if (job_running) print_job_timer.start();
  7681. }
  7682. #endif // ADVANCED_PAUSE_FEATURE
  7683. #if ENABLED(DUAL_X_CARRIAGE)
  7684. /**
  7685. * M605: Set dual x-carriage movement mode
  7686. *
  7687. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  7688. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  7689. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  7690. * units x-offset and an optional differential hotend temperature of
  7691. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  7692. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  7693. *
  7694. * Note: the X axis should be homed after changing dual x-carriage mode.
  7695. */
  7696. inline void gcode_M605() {
  7697. stepper.synchronize();
  7698. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  7699. switch (dual_x_carriage_mode) {
  7700. case DXC_FULL_CONTROL_MODE:
  7701. case DXC_AUTO_PARK_MODE:
  7702. break;
  7703. case DXC_DUPLICATION_MODE:
  7704. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  7705. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  7706. SERIAL_ECHO_START;
  7707. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7708. SERIAL_CHAR(' ');
  7709. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  7710. SERIAL_CHAR(',');
  7711. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  7712. SERIAL_CHAR(' ');
  7713. SERIAL_ECHO(duplicate_extruder_x_offset);
  7714. SERIAL_CHAR(',');
  7715. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  7716. break;
  7717. default:
  7718. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  7719. break;
  7720. }
  7721. active_extruder_parked = false;
  7722. extruder_duplication_enabled = false;
  7723. delayed_move_time = 0;
  7724. }
  7725. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  7726. inline void gcode_M605() {
  7727. stepper.synchronize();
  7728. extruder_duplication_enabled = parser.seen('S') && parser.value_int() == (int)DXC_DUPLICATION_MODE;
  7729. SERIAL_ECHO_START;
  7730. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  7731. }
  7732. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  7733. #if ENABLED(LIN_ADVANCE)
  7734. /**
  7735. * M900: Set and/or Get advance K factor and WH/D ratio
  7736. *
  7737. * K<factor> Set advance K factor
  7738. * R<ratio> Set ratio directly (overrides WH/D)
  7739. * W<width> H<height> D<diam> Set ratio from WH/D
  7740. */
  7741. inline void gcode_M900() {
  7742. stepper.synchronize();
  7743. const float newK = parser.seen('K') ? parser.value_float() : -1;
  7744. if (newK >= 0) planner.extruder_advance_k = newK;
  7745. float newR = parser.seen('R') ? parser.value_float() : -1;
  7746. if (newR < 0) {
  7747. const float newD = parser.seen('D') ? parser.value_float() : -1,
  7748. newW = parser.seen('W') ? parser.value_float() : -1,
  7749. newH = parser.seen('H') ? parser.value_float() : -1;
  7750. if (newD >= 0 && newW >= 0 && newH >= 0)
  7751. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  7752. }
  7753. if (newR >= 0) planner.advance_ed_ratio = newR;
  7754. SERIAL_ECHO_START;
  7755. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  7756. SERIAL_ECHOPGM(" E/D=");
  7757. const float ratio = planner.advance_ed_ratio;
  7758. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  7759. SERIAL_EOL;
  7760. }
  7761. #endif // LIN_ADVANCE
  7762. #if ENABLED(HAVE_TMC2130)
  7763. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  7764. SERIAL_CHAR(name);
  7765. SERIAL_ECHOPGM(" axis driver current: ");
  7766. SERIAL_ECHOLN(st.getCurrent());
  7767. }
  7768. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  7769. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  7770. tmc2130_get_current(st, name);
  7771. }
  7772. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  7773. SERIAL_CHAR(name);
  7774. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  7775. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  7776. SERIAL_EOL;
  7777. }
  7778. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  7779. st.clear_otpw();
  7780. SERIAL_CHAR(name);
  7781. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  7782. }
  7783. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  7784. SERIAL_CHAR(name);
  7785. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  7786. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  7787. }
  7788. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  7789. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  7790. tmc2130_get_pwmthrs(st, name, spmm);
  7791. }
  7792. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  7793. SERIAL_CHAR(name);
  7794. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  7795. SERIAL_ECHOLN(st.sgt());
  7796. }
  7797. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  7798. st.sgt(sgt_val);
  7799. tmc2130_get_sgt(st, name);
  7800. }
  7801. /**
  7802. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  7803. * Report driver currents when no axis specified
  7804. *
  7805. * S1: Enable automatic current control
  7806. * S0: Disable
  7807. */
  7808. inline void gcode_M906() {
  7809. uint16_t values[XYZE];
  7810. LOOP_XYZE(i)
  7811. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  7812. #if ENABLED(X_IS_TMC2130)
  7813. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  7814. else tmc2130_get_current(stepperX, 'X');
  7815. #endif
  7816. #if ENABLED(Y_IS_TMC2130)
  7817. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  7818. else tmc2130_get_current(stepperY, 'Y');
  7819. #endif
  7820. #if ENABLED(Z_IS_TMC2130)
  7821. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  7822. else tmc2130_get_current(stepperZ, 'Z');
  7823. #endif
  7824. #if ENABLED(E0_IS_TMC2130)
  7825. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  7826. else tmc2130_get_current(stepperE0, 'E');
  7827. #endif
  7828. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  7829. if (parser.seen('S')) auto_current_control = parser.value_bool();
  7830. #endif
  7831. }
  7832. /**
  7833. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  7834. * The flag is held by the library and persist until manually cleared by M912
  7835. */
  7836. inline void gcode_M911() {
  7837. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  7838. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  7839. #if ENABLED(X_IS_TMC2130)
  7840. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  7841. #endif
  7842. #if ENABLED(Y_IS_TMC2130)
  7843. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  7844. #endif
  7845. #if ENABLED(Z_IS_TMC2130)
  7846. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  7847. #endif
  7848. #if ENABLED(E0_IS_TMC2130)
  7849. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  7850. #endif
  7851. }
  7852. /**
  7853. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  7854. */
  7855. inline void gcode_M912() {
  7856. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  7857. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  7858. #if ENABLED(X_IS_TMC2130)
  7859. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  7860. #endif
  7861. #if ENABLED(Y_IS_TMC2130)
  7862. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  7863. #endif
  7864. #if ENABLED(Z_IS_TMC2130)
  7865. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  7866. #endif
  7867. #if ENABLED(E0_IS_TMC2130)
  7868. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  7869. #endif
  7870. }
  7871. /**
  7872. * M913: Set HYBRID_THRESHOLD speed.
  7873. */
  7874. #if ENABLED(HYBRID_THRESHOLD)
  7875. inline void gcode_M913() {
  7876. uint16_t values[XYZE];
  7877. LOOP_XYZE(i)
  7878. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  7879. #if ENABLED(X_IS_TMC2130)
  7880. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  7881. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  7882. #endif
  7883. #if ENABLED(Y_IS_TMC2130)
  7884. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  7885. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  7886. #endif
  7887. #if ENABLED(Z_IS_TMC2130)
  7888. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  7889. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  7890. #endif
  7891. #if ENABLED(E0_IS_TMC2130)
  7892. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  7893. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  7894. #endif
  7895. }
  7896. #endif // HYBRID_THRESHOLD
  7897. /**
  7898. * M914: Set SENSORLESS_HOMING sensitivity.
  7899. */
  7900. #if ENABLED(SENSORLESS_HOMING)
  7901. inline void gcode_M914() {
  7902. #if ENABLED(X_IS_TMC2130)
  7903. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  7904. else tmc2130_get_sgt(stepperX, 'X');
  7905. #endif
  7906. #if ENABLED(Y_IS_TMC2130)
  7907. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  7908. else tmc2130_get_sgt(stepperY, 'Y');
  7909. #endif
  7910. }
  7911. #endif // SENSORLESS_HOMING
  7912. #endif // HAVE_TMC2130
  7913. /**
  7914. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  7915. */
  7916. inline void gcode_M907() {
  7917. #if HAS_DIGIPOTSS
  7918. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  7919. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  7920. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  7921. #elif HAS_MOTOR_CURRENT_PWM
  7922. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  7923. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  7924. #endif
  7925. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  7926. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  7927. #endif
  7928. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  7929. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  7930. #endif
  7931. #endif
  7932. #if ENABLED(DIGIPOT_I2C)
  7933. // this one uses actual amps in floating point
  7934. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  7935. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  7936. for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float());
  7937. #endif
  7938. #if ENABLED(DAC_STEPPER_CURRENT)
  7939. if (parser.seen('S')) {
  7940. const float dac_percent = parser.value_float();
  7941. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  7942. }
  7943. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  7944. #endif
  7945. }
  7946. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  7947. /**
  7948. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  7949. */
  7950. inline void gcode_M908() {
  7951. #if HAS_DIGIPOTSS
  7952. stepper.digitalPotWrite(
  7953. parser.seen('P') ? parser.value_int() : 0,
  7954. parser.seen('S') ? parser.value_int() : 0
  7955. );
  7956. #endif
  7957. #ifdef DAC_STEPPER_CURRENT
  7958. dac_current_raw(
  7959. parser.seen('P') ? parser.value_byte() : -1,
  7960. parser.seen('S') ? parser.value_ushort() : 0
  7961. );
  7962. #endif
  7963. }
  7964. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  7965. inline void gcode_M909() { dac_print_values(); }
  7966. inline void gcode_M910() { dac_commit_eeprom(); }
  7967. #endif
  7968. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  7969. #if HAS_MICROSTEPS
  7970. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  7971. inline void gcode_M350() {
  7972. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  7973. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  7974. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  7975. stepper.microstep_readings();
  7976. }
  7977. /**
  7978. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  7979. * S# determines MS1 or MS2, X# sets the pin high/low.
  7980. */
  7981. inline void gcode_M351() {
  7982. if (parser.seen('S')) switch (parser.value_byte()) {
  7983. case 1:
  7984. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  7985. if (parser.seen('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  7986. break;
  7987. case 2:
  7988. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  7989. if (parser.seen('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  7990. break;
  7991. }
  7992. stepper.microstep_readings();
  7993. }
  7994. #endif // HAS_MICROSTEPS
  7995. #if HAS_CASE_LIGHT
  7996. #ifndef INVERT_CASE_LIGHT
  7997. #define INVERT_CASE_LIGHT false
  7998. #endif
  7999. int case_light_brightness; // LCD routine wants INT
  8000. bool case_light_on;
  8001. void update_case_light() {
  8002. pinMode(CASE_LIGHT_PIN, OUTPUT); // digitalWrite doesn't set the port mode
  8003. uint8_t case_light_bright = (uint8_t)case_light_brightness;
  8004. if (case_light_on) {
  8005. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  8006. analogWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? 255 - case_light_brightness : case_light_brightness );
  8007. }
  8008. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? LOW : HIGH );
  8009. }
  8010. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? HIGH : LOW);
  8011. }
  8012. #endif // HAS_CASE_LIGHT
  8013. /**
  8014. * M355: Turn case light on/off and set brightness
  8015. *
  8016. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  8017. *
  8018. * S<bool> Set case light on/off
  8019. *
  8020. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  8021. *
  8022. * M355 P200 S0 turns off the light & sets the brightness level
  8023. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  8024. */
  8025. inline void gcode_M355() {
  8026. #if HAS_CASE_LIGHT
  8027. uint8_t args = 0;
  8028. if (parser.seen('P')) ++args, case_light_brightness = parser.value_byte();
  8029. if (parser.seen('S')) ++args, case_light_on = parser.value_bool();
  8030. if (args) update_case_light();
  8031. // always report case light status
  8032. SERIAL_ECHO_START;
  8033. if (!case_light_on) {
  8034. SERIAL_ECHOLN("Case light: off");
  8035. }
  8036. else {
  8037. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLN("Case light: on");
  8038. else SERIAL_ECHOLNPAIR("Case light: ", case_light_brightness);
  8039. }
  8040. #else
  8041. SERIAL_ERROR_START;
  8042. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8043. #endif // HAS_CASE_LIGHT
  8044. }
  8045. #if ENABLED(MIXING_EXTRUDER)
  8046. /**
  8047. * M163: Set a single mix factor for a mixing extruder
  8048. * This is called "weight" by some systems.
  8049. *
  8050. * S[index] The channel index to set
  8051. * P[float] The mix value
  8052. *
  8053. */
  8054. inline void gcode_M163() {
  8055. const int mix_index = parser.seen('S') ? parser.value_int() : 0;
  8056. if (mix_index < MIXING_STEPPERS) {
  8057. float mix_value = parser.seen('P') ? parser.value_float() : 0.0;
  8058. NOLESS(mix_value, 0.0);
  8059. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8060. }
  8061. }
  8062. #if MIXING_VIRTUAL_TOOLS > 1
  8063. /**
  8064. * M164: Store the current mix factors as a virtual tool.
  8065. *
  8066. * S[index] The virtual tool to store
  8067. *
  8068. */
  8069. inline void gcode_M164() {
  8070. const int tool_index = parser.seen('S') ? parser.value_int() : 0;
  8071. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8072. normalize_mix();
  8073. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8074. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8075. }
  8076. }
  8077. #endif
  8078. #if ENABLED(DIRECT_MIXING_IN_G1)
  8079. /**
  8080. * M165: Set multiple mix factors for a mixing extruder.
  8081. * Factors that are left out will be set to 0.
  8082. * All factors together must add up to 1.0.
  8083. *
  8084. * A[factor] Mix factor for extruder stepper 1
  8085. * B[factor] Mix factor for extruder stepper 2
  8086. * C[factor] Mix factor for extruder stepper 3
  8087. * D[factor] Mix factor for extruder stepper 4
  8088. * H[factor] Mix factor for extruder stepper 5
  8089. * I[factor] Mix factor for extruder stepper 6
  8090. *
  8091. */
  8092. inline void gcode_M165() { gcode_get_mix(); }
  8093. #endif
  8094. #endif // MIXING_EXTRUDER
  8095. /**
  8096. * M999: Restart after being stopped
  8097. *
  8098. * Default behaviour is to flush the serial buffer and request
  8099. * a resend to the host starting on the last N line received.
  8100. *
  8101. * Sending "M999 S1" will resume printing without flushing the
  8102. * existing command buffer.
  8103. *
  8104. */
  8105. inline void gcode_M999() {
  8106. Running = true;
  8107. lcd_reset_alert_level();
  8108. if (parser.seen('S') && parser.value_bool()) return;
  8109. // gcode_LastN = Stopped_gcode_LastN;
  8110. FlushSerialRequestResend();
  8111. }
  8112. #if ENABLED(SWITCHING_EXTRUDER)
  8113. inline void move_extruder_servo(uint8_t e) {
  8114. const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8115. MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]);
  8116. safe_delay(500);
  8117. }
  8118. #endif
  8119. #if ENABLED(SWITCHING_NOZZLE)
  8120. inline void move_nozzle_servo(uint8_t e) {
  8121. const int angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8122. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8123. safe_delay(500);
  8124. }
  8125. #endif
  8126. inline void invalid_extruder_error(const uint8_t &e) {
  8127. SERIAL_ECHO_START;
  8128. SERIAL_CHAR('T');
  8129. SERIAL_ECHO_F(e, DEC);
  8130. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8131. }
  8132. /**
  8133. * Perform a tool-change, which may result in moving the
  8134. * previous tool out of the way and the new tool into place.
  8135. */
  8136. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8137. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8138. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8139. return invalid_extruder_error(tmp_extruder);
  8140. // T0-Tnnn: Switch virtual tool by changing the mix
  8141. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8142. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8143. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8144. #if HOTENDS > 1
  8145. if (tmp_extruder >= EXTRUDERS)
  8146. return invalid_extruder_error(tmp_extruder);
  8147. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8148. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8149. if (tmp_extruder != active_extruder) {
  8150. if (!no_move && axis_unhomed_error()) {
  8151. SERIAL_ECHOLNPGM("No move on toolchange");
  8152. no_move = true;
  8153. }
  8154. // Save current position to destination, for use later
  8155. set_destination_to_current();
  8156. #if ENABLED(DUAL_X_CARRIAGE)
  8157. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8158. if (DEBUGGING(LEVELING)) {
  8159. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8160. switch (dual_x_carriage_mode) {
  8161. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8162. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8163. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8164. }
  8165. }
  8166. #endif
  8167. const float xhome = x_home_pos(active_extruder);
  8168. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8169. && IsRunning()
  8170. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8171. ) {
  8172. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8173. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8174. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8175. #endif
  8176. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8177. if (DEBUGGING(LEVELING)) {
  8178. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8179. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8180. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8181. }
  8182. #endif
  8183. // Park old head: 1) raise 2) move to park position 3) lower
  8184. for (uint8_t i = 0; i < 3; i++)
  8185. planner.buffer_line(
  8186. i == 0 ? current_position[X_AXIS] : xhome,
  8187. current_position[Y_AXIS],
  8188. i == 2 ? current_position[Z_AXIS] : raised_z,
  8189. current_position[E_AXIS],
  8190. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8191. active_extruder
  8192. );
  8193. stepper.synchronize();
  8194. }
  8195. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8196. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8197. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8198. // Activate the new extruder
  8199. active_extruder = tmp_extruder;
  8200. // This function resets the max/min values - the current position may be overwritten below.
  8201. set_axis_is_at_home(X_AXIS);
  8202. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8203. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8204. #endif
  8205. // Only when auto-parking are carriages safe to move
  8206. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8207. switch (dual_x_carriage_mode) {
  8208. case DXC_FULL_CONTROL_MODE:
  8209. // New current position is the position of the activated extruder
  8210. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8211. // Save the inactive extruder's position (from the old current_position)
  8212. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8213. break;
  8214. case DXC_AUTO_PARK_MODE:
  8215. // record raised toolhead position for use by unpark
  8216. COPY(raised_parked_position, current_position);
  8217. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8218. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8219. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8220. #endif
  8221. active_extruder_parked = true;
  8222. delayed_move_time = 0;
  8223. break;
  8224. case DXC_DUPLICATION_MODE:
  8225. // If the new extruder is the left one, set it "parked"
  8226. // This triggers the second extruder to move into the duplication position
  8227. active_extruder_parked = (active_extruder == 0);
  8228. if (active_extruder_parked)
  8229. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8230. else
  8231. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8232. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8233. extruder_duplication_enabled = false;
  8234. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8235. if (DEBUGGING(LEVELING)) {
  8236. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8237. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8238. }
  8239. #endif
  8240. break;
  8241. }
  8242. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8243. if (DEBUGGING(LEVELING)) {
  8244. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8245. DEBUG_POS("New extruder (parked)", current_position);
  8246. }
  8247. #endif
  8248. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8249. #else // !DUAL_X_CARRIAGE
  8250. #if ENABLED(SWITCHING_NOZZLE)
  8251. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8252. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8253. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8254. // Always raise by some amount (destination copied from current_position earlier)
  8255. current_position[Z_AXIS] += z_raise;
  8256. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8257. stepper.synchronize();
  8258. move_nozzle_servo(active_extruder);
  8259. #endif
  8260. #if ENABLED(SWITCHING_EXTRUDER)
  8261. #if !(ENABLED(SWITCHING_NOZZLE) && (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR))
  8262. stepper.synchronize();
  8263. move_extruder_servo(active_extruder);
  8264. #endif
  8265. #endif
  8266. /**
  8267. * Set current_position to the position of the new nozzle.
  8268. * Offsets are based on linear distance, so we need to get
  8269. * the resulting position in coordinate space.
  8270. *
  8271. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8272. * - With mesh leveling, update Z for the new position
  8273. * - Otherwise, just use the raw linear distance
  8274. *
  8275. * Software endstops are altered here too. Consider a case where:
  8276. * E0 at X=0 ... E1 at X=10
  8277. * When we switch to E1 now X=10, but E1 can't move left.
  8278. * To express this we apply the change in XY to the software endstops.
  8279. * E1 can move farther right than E0, so the right limit is extended.
  8280. *
  8281. * Note that we don't adjust the Z software endstops. Why not?
  8282. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8283. * because the bed is 1mm lower at the new position. As long as
  8284. * the first nozzle is out of the way, the carriage should be
  8285. * allowed to move 1mm lower. This technically "breaks" the
  8286. * Z software endstop. But this is technically correct (and
  8287. * there is no viable alternative).
  8288. */
  8289. #if ABL_PLANAR
  8290. // Offset extruder, make sure to apply the bed level rotation matrix
  8291. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8292. hotend_offset[Y_AXIS][tmp_extruder],
  8293. 0),
  8294. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8295. hotend_offset[Y_AXIS][active_extruder],
  8296. 0),
  8297. offset_vec = tmp_offset_vec - act_offset_vec;
  8298. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8299. if (DEBUGGING(LEVELING)) {
  8300. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8301. act_offset_vec.debug(PSTR("act_offset_vec"));
  8302. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8303. }
  8304. #endif
  8305. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8306. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8307. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8308. #endif
  8309. // Adjustments to the current position
  8310. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8311. current_position[Z_AXIS] += offset_vec.z;
  8312. #else // !ABL_PLANAR
  8313. const float xydiff[2] = {
  8314. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8315. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8316. };
  8317. #if ENABLED(MESH_BED_LEVELING)
  8318. if (leveling_is_active()) {
  8319. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8320. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8321. #endif
  8322. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8323. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8324. z1 = current_position[Z_AXIS], z2 = z1;
  8325. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8326. planner.apply_leveling(x2, y2, z2);
  8327. current_position[Z_AXIS] += z2 - z1;
  8328. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8329. if (DEBUGGING(LEVELING))
  8330. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8331. #endif
  8332. }
  8333. #endif // MESH_BED_LEVELING
  8334. #endif // !HAS_ABL
  8335. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8336. if (DEBUGGING(LEVELING)) {
  8337. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8338. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8339. SERIAL_ECHOLNPGM(" }");
  8340. }
  8341. #endif
  8342. // The newly-selected extruder XY is actually at...
  8343. current_position[X_AXIS] += xydiff[X_AXIS];
  8344. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8345. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8346. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8347. #if HAS_POSITION_SHIFT
  8348. position_shift[i] += xydiff[i];
  8349. #endif
  8350. update_software_endstops((AxisEnum)i);
  8351. }
  8352. #endif
  8353. // Set the new active extruder
  8354. active_extruder = tmp_extruder;
  8355. #endif // !DUAL_X_CARRIAGE
  8356. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8357. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8358. #endif
  8359. // Tell the planner the new "current position"
  8360. SYNC_PLAN_POSITION_KINEMATIC();
  8361. // Move to the "old position" (move the extruder into place)
  8362. if (!no_move && IsRunning()) {
  8363. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8364. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8365. #endif
  8366. prepare_move_to_destination();
  8367. }
  8368. #if ENABLED(SWITCHING_NOZZLE)
  8369. // Move back down, if needed. (Including when the new tool is higher.)
  8370. if (z_raise != z_diff) {
  8371. destination[Z_AXIS] += z_diff;
  8372. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8373. prepare_move_to_destination();
  8374. }
  8375. #endif
  8376. } // (tmp_extruder != active_extruder)
  8377. stepper.synchronize();
  8378. #if ENABLED(EXT_SOLENOID)
  8379. disable_all_solenoids();
  8380. enable_solenoid_on_active_extruder();
  8381. #endif // EXT_SOLENOID
  8382. feedrate_mm_s = old_feedrate_mm_s;
  8383. #else // HOTENDS <= 1
  8384. // Set the new active extruder
  8385. active_extruder = tmp_extruder;
  8386. UNUSED(fr_mm_s);
  8387. UNUSED(no_move);
  8388. #if ENABLED(SWITCHING_EXTRUDER)
  8389. stepper.synchronize();
  8390. move_extruder_servo(active_extruder);
  8391. #endif
  8392. #endif // HOTENDS <= 1
  8393. SERIAL_ECHO_START;
  8394. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8395. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8396. }
  8397. /**
  8398. * T0-T3: Switch tool, usually switching extruders
  8399. *
  8400. * F[units/min] Set the movement feedrate
  8401. * S1 Don't move the tool in XY after change
  8402. */
  8403. inline void gcode_T(uint8_t tmp_extruder) {
  8404. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8405. if (DEBUGGING(LEVELING)) {
  8406. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8407. SERIAL_CHAR(')');
  8408. SERIAL_EOL;
  8409. DEBUG_POS("BEFORE", current_position);
  8410. }
  8411. #endif
  8412. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8413. tool_change(tmp_extruder);
  8414. #elif HOTENDS > 1
  8415. tool_change(
  8416. tmp_extruder,
  8417. parser.seen('F') ? MMM_TO_MMS(parser.value_linear_units()) : 0.0,
  8418. (tmp_extruder == active_extruder) || (parser.seen('S') && parser.value_bool())
  8419. );
  8420. #endif
  8421. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8422. if (DEBUGGING(LEVELING)) {
  8423. DEBUG_POS("AFTER", current_position);
  8424. SERIAL_ECHOLNPGM("<<< gcode_T");
  8425. }
  8426. #endif
  8427. }
  8428. /**
  8429. * Process a single command and dispatch it to its handler
  8430. * This is called from the main loop()
  8431. */
  8432. void process_next_command() {
  8433. char * const current_command = command_queue[cmd_queue_index_r];
  8434. if (DEBUGGING(ECHO)) {
  8435. SERIAL_ECHO_START;
  8436. SERIAL_ECHOLN(current_command);
  8437. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8438. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8439. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8440. #endif
  8441. }
  8442. KEEPALIVE_STATE(IN_HANDLER);
  8443. // Parse the next command in the queue
  8444. parser.parse(current_command);
  8445. // Handle a known G, M, or T
  8446. switch (parser.command_letter) {
  8447. case 'G': switch (parser.codenum) {
  8448. // G0, G1
  8449. case 0:
  8450. case 1:
  8451. #if IS_SCARA
  8452. gcode_G0_G1(parser.codenum == 0);
  8453. #else
  8454. gcode_G0_G1();
  8455. #endif
  8456. break;
  8457. // G2, G3
  8458. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8459. case 2: // G2 - CW ARC
  8460. case 3: // G3 - CCW ARC
  8461. gcode_G2_G3(parser.codenum == 2);
  8462. break;
  8463. #endif
  8464. // G4 Dwell
  8465. case 4:
  8466. gcode_G4();
  8467. break;
  8468. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8469. // G5
  8470. case 5: // G5 - Cubic B_spline
  8471. gcode_G5();
  8472. break;
  8473. #endif // BEZIER_CURVE_SUPPORT
  8474. #if ENABLED(FWRETRACT)
  8475. case 10: // G10: retract
  8476. case 11: // G11: retract_recover
  8477. gcode_G10_G11(parser.codenum == 10);
  8478. break;
  8479. #endif // FWRETRACT
  8480. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8481. case 12:
  8482. gcode_G12(); // G12: Nozzle Clean
  8483. break;
  8484. #endif // NOZZLE_CLEAN_FEATURE
  8485. #if ENABLED(INCH_MODE_SUPPORT)
  8486. case 20: //G20: Inch Mode
  8487. gcode_G20();
  8488. break;
  8489. case 21: //G21: MM Mode
  8490. gcode_G21();
  8491. break;
  8492. #endif // INCH_MODE_SUPPORT
  8493. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8494. case 26: // G26: Mesh Validation Pattern generation
  8495. gcode_G26();
  8496. break;
  8497. #endif // AUTO_BED_LEVELING_UBL
  8498. #if ENABLED(NOZZLE_PARK_FEATURE)
  8499. case 27: // G27: Nozzle Park
  8500. gcode_G27();
  8501. break;
  8502. #endif // NOZZLE_PARK_FEATURE
  8503. case 28: // G28: Home all axes, one at a time
  8504. gcode_G28(false);
  8505. break;
  8506. #if HAS_LEVELING
  8507. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8508. // or provides access to the UBL System if enabled.
  8509. gcode_G29();
  8510. break;
  8511. #endif // HAS_LEVELING
  8512. #if HAS_BED_PROBE
  8513. case 30: // G30 Single Z probe
  8514. gcode_G30();
  8515. break;
  8516. #if ENABLED(Z_PROBE_SLED)
  8517. case 31: // G31: dock the sled
  8518. gcode_G31();
  8519. break;
  8520. case 32: // G32: undock the sled
  8521. gcode_G32();
  8522. break;
  8523. #endif // Z_PROBE_SLED
  8524. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8525. case 33: // G33: Delta Auto-Calibration
  8526. gcode_G33();
  8527. break;
  8528. #endif // DELTA_AUTO_CALIBRATION
  8529. #endif // HAS_BED_PROBE
  8530. #if ENABLED(G38_PROBE_TARGET)
  8531. case 38: // G38.2 & G38.3
  8532. if (subcode == 2 || subcode == 3)
  8533. gcode_G38(subcode == 2);
  8534. break;
  8535. #endif
  8536. case 90: // G90
  8537. relative_mode = false;
  8538. break;
  8539. case 91: // G91
  8540. relative_mode = true;
  8541. break;
  8542. case 92: // G92
  8543. gcode_G92();
  8544. break;
  8545. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8546. case 42:
  8547. gcode_G42();
  8548. break;
  8549. #endif
  8550. #if ENABLED(DEBUG_GCODE_PARSER)
  8551. case 800:
  8552. parser.debug(); // GCode Parser Test for G
  8553. break;
  8554. #endif
  8555. }
  8556. break;
  8557. case 'M': switch (parser.codenum) {
  8558. #if HAS_RESUME_CONTINUE
  8559. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8560. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8561. gcode_M0_M1();
  8562. break;
  8563. #endif // ULTIPANEL
  8564. #if ENABLED(SPINDLE_LASER_ENABLE)
  8565. case 3:
  8566. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8567. break; // synchronizes with movement commands
  8568. case 4:
  8569. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8570. break; // synchronizes with movement commands
  8571. case 5:
  8572. gcode_M5(); // M5 - turn spindle/laser off
  8573. break; // synchronizes with movement commands
  8574. #endif
  8575. case 17: // M17: Enable all stepper motors
  8576. gcode_M17();
  8577. break;
  8578. #if ENABLED(SDSUPPORT)
  8579. case 20: // M20: list SD card
  8580. gcode_M20(); break;
  8581. case 21: // M21: init SD card
  8582. gcode_M21(); break;
  8583. case 22: // M22: release SD card
  8584. gcode_M22(); break;
  8585. case 23: // M23: Select file
  8586. gcode_M23(); break;
  8587. case 24: // M24: Start SD print
  8588. gcode_M24(); break;
  8589. case 25: // M25: Pause SD print
  8590. gcode_M25(); break;
  8591. case 26: // M26: Set SD index
  8592. gcode_M26(); break;
  8593. case 27: // M27: Get SD status
  8594. gcode_M27(); break;
  8595. case 28: // M28: Start SD write
  8596. gcode_M28(); break;
  8597. case 29: // M29: Stop SD write
  8598. gcode_M29(); break;
  8599. case 30: // M30 <filename> Delete File
  8600. gcode_M30(); break;
  8601. case 32: // M32: Select file and start SD print
  8602. gcode_M32(); break;
  8603. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8604. case 33: // M33: Get the long full path to a file or folder
  8605. gcode_M33(); break;
  8606. #endif
  8607. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8608. case 34: //M34 - Set SD card sorting options
  8609. gcode_M34(); break;
  8610. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8611. case 928: // M928: Start SD write
  8612. gcode_M928(); break;
  8613. #endif // SDSUPPORT
  8614. case 31: // M31: Report time since the start of SD print or last M109
  8615. gcode_M31(); break;
  8616. case 42: // M42: Change pin state
  8617. gcode_M42(); break;
  8618. #if ENABLED(PINS_DEBUGGING)
  8619. case 43: // M43: Read pin state
  8620. gcode_M43(); break;
  8621. #endif
  8622. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8623. case 48: // M48: Z probe repeatability test
  8624. gcode_M48();
  8625. break;
  8626. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8627. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8628. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8629. gcode_M49();
  8630. break;
  8631. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8632. case 75: // M75: Start print timer
  8633. gcode_M75(); break;
  8634. case 76: // M76: Pause print timer
  8635. gcode_M76(); break;
  8636. case 77: // M77: Stop print timer
  8637. gcode_M77(); break;
  8638. #if ENABLED(PRINTCOUNTER)
  8639. case 78: // M78: Show print statistics
  8640. gcode_M78(); break;
  8641. #endif
  8642. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8643. case 100: // M100: Free Memory Report
  8644. gcode_M100();
  8645. break;
  8646. #endif
  8647. case 104: // M104: Set hot end temperature
  8648. gcode_M104();
  8649. break;
  8650. case 110: // M110: Set Current Line Number
  8651. gcode_M110();
  8652. break;
  8653. case 111: // M111: Set debug level
  8654. gcode_M111();
  8655. break;
  8656. #if DISABLED(EMERGENCY_PARSER)
  8657. case 108: // M108: Cancel Waiting
  8658. gcode_M108();
  8659. break;
  8660. case 112: // M112: Emergency Stop
  8661. gcode_M112();
  8662. break;
  8663. case 410: // M410 quickstop - Abort all the planned moves.
  8664. gcode_M410();
  8665. break;
  8666. #endif
  8667. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  8668. case 113: // M113: Set Host Keepalive interval
  8669. gcode_M113();
  8670. break;
  8671. #endif
  8672. case 140: // M140: Set bed temperature
  8673. gcode_M140();
  8674. break;
  8675. case 105: // M105: Report current temperature
  8676. gcode_M105();
  8677. KEEPALIVE_STATE(NOT_BUSY);
  8678. return; // "ok" already printed
  8679. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8680. case 155: // M155: Set temperature auto-report interval
  8681. gcode_M155();
  8682. break;
  8683. #endif
  8684. case 109: // M109: Wait for hotend temperature to reach target
  8685. gcode_M109();
  8686. break;
  8687. #if HAS_TEMP_BED
  8688. case 190: // M190: Wait for bed temperature to reach target
  8689. gcode_M190();
  8690. break;
  8691. #endif // HAS_TEMP_BED
  8692. #if FAN_COUNT > 0
  8693. case 106: // M106: Fan On
  8694. gcode_M106();
  8695. break;
  8696. case 107: // M107: Fan Off
  8697. gcode_M107();
  8698. break;
  8699. #endif // FAN_COUNT > 0
  8700. #if ENABLED(PARK_HEAD_ON_PAUSE)
  8701. case 125: // M125: Store current position and move to filament change position
  8702. gcode_M125(); break;
  8703. #endif
  8704. #if ENABLED(BARICUDA)
  8705. // PWM for HEATER_1_PIN
  8706. #if HAS_HEATER_1
  8707. case 126: // M126: valve open
  8708. gcode_M126();
  8709. break;
  8710. case 127: // M127: valve closed
  8711. gcode_M127();
  8712. break;
  8713. #endif // HAS_HEATER_1
  8714. // PWM for HEATER_2_PIN
  8715. #if HAS_HEATER_2
  8716. case 128: // M128: valve open
  8717. gcode_M128();
  8718. break;
  8719. case 129: // M129: valve closed
  8720. gcode_M129();
  8721. break;
  8722. #endif // HAS_HEATER_2
  8723. #endif // BARICUDA
  8724. #if HAS_POWER_SWITCH
  8725. case 80: // M80: Turn on Power Supply
  8726. gcode_M80();
  8727. break;
  8728. #endif // HAS_POWER_SWITCH
  8729. case 81: // M81: Turn off Power, including Power Supply, if possible
  8730. gcode_M81();
  8731. break;
  8732. case 82: // M82: Set E axis normal mode (same as other axes)
  8733. gcode_M82();
  8734. break;
  8735. case 83: // M83: Set E axis relative mode
  8736. gcode_M83();
  8737. break;
  8738. case 18: // M18 => M84
  8739. case 84: // M84: Disable all steppers or set timeout
  8740. gcode_M18_M84();
  8741. break;
  8742. case 85: // M85: Set inactivity stepper shutdown timeout
  8743. gcode_M85();
  8744. break;
  8745. case 92: // M92: Set the steps-per-unit for one or more axes
  8746. gcode_M92();
  8747. break;
  8748. case 114: // M114: Report current position
  8749. gcode_M114();
  8750. break;
  8751. case 115: // M115: Report capabilities
  8752. gcode_M115();
  8753. break;
  8754. case 117: // M117: Set LCD message text, if possible
  8755. gcode_M117();
  8756. break;
  8757. case 119: // M119: Report endstop states
  8758. gcode_M119();
  8759. break;
  8760. case 120: // M120: Enable endstops
  8761. gcode_M120();
  8762. break;
  8763. case 121: // M121: Disable endstops
  8764. gcode_M121();
  8765. break;
  8766. #if ENABLED(ULTIPANEL)
  8767. case 145: // M145: Set material heatup parameters
  8768. gcode_M145();
  8769. break;
  8770. #endif
  8771. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  8772. case 149: // M149: Set temperature units
  8773. gcode_M149();
  8774. break;
  8775. #endif
  8776. #if HAS_COLOR_LEDS
  8777. case 150: // M150: Set Status LED Color
  8778. gcode_M150();
  8779. break;
  8780. #endif // BLINKM
  8781. #if ENABLED(MIXING_EXTRUDER)
  8782. case 163: // M163: Set a component weight for mixing extruder
  8783. gcode_M163();
  8784. break;
  8785. #if MIXING_VIRTUAL_TOOLS > 1
  8786. case 164: // M164: Save current mix as a virtual extruder
  8787. gcode_M164();
  8788. break;
  8789. #endif
  8790. #if ENABLED(DIRECT_MIXING_IN_G1)
  8791. case 165: // M165: Set multiple mix weights
  8792. gcode_M165();
  8793. break;
  8794. #endif
  8795. #endif
  8796. case 200: // M200: Set filament diameter, E to cubic units
  8797. gcode_M200();
  8798. break;
  8799. case 201: // M201: Set max acceleration for print moves (units/s^2)
  8800. gcode_M201();
  8801. break;
  8802. #if 0 // Not used for Sprinter/grbl gen6
  8803. case 202: // M202
  8804. gcode_M202();
  8805. break;
  8806. #endif
  8807. case 203: // M203: Set max feedrate (units/sec)
  8808. gcode_M203();
  8809. break;
  8810. case 204: // M204: Set acceleration
  8811. gcode_M204();
  8812. break;
  8813. case 205: //M205: Set advanced settings
  8814. gcode_M205();
  8815. break;
  8816. #if HAS_M206_COMMAND
  8817. case 206: // M206: Set home offsets
  8818. gcode_M206();
  8819. break;
  8820. #endif
  8821. #if ENABLED(DELTA)
  8822. case 665: // M665: Set delta configurations
  8823. gcode_M665();
  8824. break;
  8825. #endif
  8826. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  8827. case 666: // M666: Set delta or dual endstop adjustment
  8828. gcode_M666();
  8829. break;
  8830. #endif
  8831. #if ENABLED(FWRETRACT)
  8832. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  8833. gcode_M207();
  8834. break;
  8835. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  8836. gcode_M208();
  8837. break;
  8838. case 209: // M209: Turn Automatic Retract Detection on/off
  8839. gcode_M209();
  8840. break;
  8841. #endif // FWRETRACT
  8842. case 211: // M211: Enable, Disable, and/or Report software endstops
  8843. gcode_M211();
  8844. break;
  8845. #if HOTENDS > 1
  8846. case 218: // M218: Set a tool offset
  8847. gcode_M218();
  8848. break;
  8849. #endif
  8850. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  8851. gcode_M220();
  8852. break;
  8853. case 221: // M221: Set Flow Percentage
  8854. gcode_M221();
  8855. break;
  8856. case 226: // M226: Wait until a pin reaches a state
  8857. gcode_M226();
  8858. break;
  8859. #if HAS_SERVOS
  8860. case 280: // M280: Set servo position absolute
  8861. gcode_M280();
  8862. break;
  8863. #endif // HAS_SERVOS
  8864. #if HAS_BUZZER
  8865. case 300: // M300: Play beep tone
  8866. gcode_M300();
  8867. break;
  8868. #endif // HAS_BUZZER
  8869. #if ENABLED(PIDTEMP)
  8870. case 301: // M301: Set hotend PID parameters
  8871. gcode_M301();
  8872. break;
  8873. #endif // PIDTEMP
  8874. #if ENABLED(PIDTEMPBED)
  8875. case 304: // M304: Set bed PID parameters
  8876. gcode_M304();
  8877. break;
  8878. #endif // PIDTEMPBED
  8879. #if defined(CHDK) || HAS_PHOTOGRAPH
  8880. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  8881. gcode_M240();
  8882. break;
  8883. #endif // CHDK || PHOTOGRAPH_PIN
  8884. #if HAS_LCD_CONTRAST
  8885. case 250: // M250: Set LCD contrast
  8886. gcode_M250();
  8887. break;
  8888. #endif // HAS_LCD_CONTRAST
  8889. #if ENABLED(EXPERIMENTAL_I2CBUS)
  8890. case 260: // M260: Send data to an i2c slave
  8891. gcode_M260();
  8892. break;
  8893. case 261: // M261: Request data from an i2c slave
  8894. gcode_M261();
  8895. break;
  8896. #endif // EXPERIMENTAL_I2CBUS
  8897. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8898. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  8899. gcode_M302();
  8900. break;
  8901. #endif // PREVENT_COLD_EXTRUSION
  8902. case 303: // M303: PID autotune
  8903. gcode_M303();
  8904. break;
  8905. #if ENABLED(MORGAN_SCARA)
  8906. case 360: // M360: SCARA Theta pos1
  8907. if (gcode_M360()) return;
  8908. break;
  8909. case 361: // M361: SCARA Theta pos2
  8910. if (gcode_M361()) return;
  8911. break;
  8912. case 362: // M362: SCARA Psi pos1
  8913. if (gcode_M362()) return;
  8914. break;
  8915. case 363: // M363: SCARA Psi pos2
  8916. if (gcode_M363()) return;
  8917. break;
  8918. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  8919. if (gcode_M364()) return;
  8920. break;
  8921. #endif // SCARA
  8922. case 400: // M400: Finish all moves
  8923. gcode_M400();
  8924. break;
  8925. #if HAS_BED_PROBE
  8926. case 401: // M401: Deploy probe
  8927. gcode_M401();
  8928. break;
  8929. case 402: // M402: Stow probe
  8930. gcode_M402();
  8931. break;
  8932. #endif // HAS_BED_PROBE
  8933. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  8934. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  8935. gcode_M404();
  8936. break;
  8937. case 405: // M405: Turn on filament sensor for control
  8938. gcode_M405();
  8939. break;
  8940. case 406: // M406: Turn off filament sensor for control
  8941. gcode_M406();
  8942. break;
  8943. case 407: // M407: Display measured filament diameter
  8944. gcode_M407();
  8945. break;
  8946. #endif // FILAMENT_WIDTH_SENSOR
  8947. #if HAS_LEVELING
  8948. case 420: // M420: Enable/Disable Bed Leveling
  8949. gcode_M420();
  8950. break;
  8951. #endif
  8952. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  8953. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  8954. gcode_M421();
  8955. break;
  8956. #endif
  8957. #if HAS_M206_COMMAND
  8958. case 428: // M428: Apply current_position to home_offset
  8959. gcode_M428();
  8960. break;
  8961. #endif
  8962. case 500: // M500: Store settings in EEPROM
  8963. gcode_M500();
  8964. break;
  8965. case 501: // M501: Read settings from EEPROM
  8966. gcode_M501();
  8967. break;
  8968. case 502: // M502: Revert to default settings
  8969. gcode_M502();
  8970. break;
  8971. case 503: // M503: print settings currently in memory
  8972. gcode_M503();
  8973. break;
  8974. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  8975. case 540: // M540: Set abort on endstop hit for SD printing
  8976. gcode_M540();
  8977. break;
  8978. #endif
  8979. #if HAS_BED_PROBE
  8980. case 851: // M851: Set Z Probe Z Offset
  8981. gcode_M851();
  8982. break;
  8983. #endif // HAS_BED_PROBE
  8984. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  8985. case 600: // M600: Pause for filament change
  8986. gcode_M600();
  8987. break;
  8988. #endif // ADVANCED_PAUSE_FEATURE
  8989. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  8990. case 605: // M605: Set Dual X Carriage movement mode
  8991. gcode_M605();
  8992. break;
  8993. #endif // DUAL_X_CARRIAGE
  8994. #if ENABLED(LIN_ADVANCE)
  8995. case 900: // M900: Set advance K factor.
  8996. gcode_M900();
  8997. break;
  8998. #endif
  8999. #if ENABLED(HAVE_TMC2130)
  9000. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9001. gcode_M906();
  9002. break;
  9003. #endif
  9004. case 907: // M907: Set digital trimpot motor current using axis codes.
  9005. gcode_M907();
  9006. break;
  9007. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  9008. case 908: // M908: Control digital trimpot directly.
  9009. gcode_M908();
  9010. break;
  9011. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  9012. case 909: // M909: Print digipot/DAC current value
  9013. gcode_M909();
  9014. break;
  9015. case 910: // M910: Commit digipot/DAC value to external EEPROM
  9016. gcode_M910();
  9017. break;
  9018. #endif
  9019. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  9020. #if ENABLED(HAVE_TMC2130)
  9021. case 911: // M911: Report TMC2130 prewarn triggered flags
  9022. gcode_M911();
  9023. break;
  9024. case 912: // M911: Clear TMC2130 prewarn triggered flags
  9025. gcode_M912();
  9026. break;
  9027. #if ENABLED(HYBRID_THRESHOLD)
  9028. case 913: // M913: Set HYBRID_THRESHOLD speed.
  9029. gcode_M913();
  9030. break;
  9031. #endif
  9032. #if ENABLED(SENSORLESS_HOMING)
  9033. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  9034. gcode_M914();
  9035. break;
  9036. #endif
  9037. #endif
  9038. #if HAS_MICROSTEPS
  9039. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9040. gcode_M350();
  9041. break;
  9042. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9043. gcode_M351();
  9044. break;
  9045. #endif // HAS_MICROSTEPS
  9046. case 355: // M355 set case light brightness
  9047. gcode_M355();
  9048. break;
  9049. #if ENABLED(DEBUG_GCODE_PARSER)
  9050. case 800:
  9051. parser.debug(); // GCode Parser Test for M
  9052. break;
  9053. #endif
  9054. case 999: // M999: Restart after being Stopped
  9055. gcode_M999();
  9056. break;
  9057. }
  9058. break;
  9059. case 'T':
  9060. gcode_T(parser.codenum);
  9061. break;
  9062. default: parser.unknown_command_error();
  9063. }
  9064. KEEPALIVE_STATE(NOT_BUSY);
  9065. ok_to_send();
  9066. }
  9067. /**
  9068. * Send a "Resend: nnn" message to the host to
  9069. * indicate that a command needs to be re-sent.
  9070. */
  9071. void FlushSerialRequestResend() {
  9072. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9073. MYSERIAL.flush();
  9074. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9075. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9076. ok_to_send();
  9077. }
  9078. /**
  9079. * Send an "ok" message to the host, indicating
  9080. * that a command was successfully processed.
  9081. *
  9082. * If ADVANCED_OK is enabled also include:
  9083. * N<int> Line number of the command, if any
  9084. * P<int> Planner space remaining
  9085. * B<int> Block queue space remaining
  9086. */
  9087. void ok_to_send() {
  9088. refresh_cmd_timeout();
  9089. if (!send_ok[cmd_queue_index_r]) return;
  9090. SERIAL_PROTOCOLPGM(MSG_OK);
  9091. #if ENABLED(ADVANCED_OK)
  9092. char* p = command_queue[cmd_queue_index_r];
  9093. if (*p == 'N') {
  9094. SERIAL_PROTOCOL(' ');
  9095. SERIAL_ECHO(*p++);
  9096. while (NUMERIC_SIGNED(*p))
  9097. SERIAL_ECHO(*p++);
  9098. }
  9099. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9100. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9101. #endif
  9102. SERIAL_EOL;
  9103. }
  9104. #if HAS_SOFTWARE_ENDSTOPS
  9105. /**
  9106. * Constrain the given coordinates to the software endstops.
  9107. */
  9108. void clamp_to_software_endstops(float target[XYZ]) {
  9109. if (!soft_endstops_enabled) return;
  9110. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9111. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9112. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9113. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9114. #endif
  9115. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9116. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9117. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9118. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9119. #endif
  9120. }
  9121. #endif
  9122. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9123. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9124. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9125. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9126. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9127. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9128. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9129. #else
  9130. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9131. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9132. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9133. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9134. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9135. #endif
  9136. // Get the Z adjustment for non-linear bed leveling
  9137. float bilinear_z_offset(const float logical[XYZ]) {
  9138. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9139. last_x = -999.999, last_y = -999.999;
  9140. // Whole units for the grid line indices. Constrained within bounds.
  9141. static int8_t gridx, gridy, nextx, nexty,
  9142. last_gridx = -99, last_gridy = -99;
  9143. // XY relative to the probed area
  9144. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9145. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9146. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9147. // Keep using the last grid box
  9148. #define FAR_EDGE_OR_BOX 2
  9149. #else
  9150. // Just use the grid far edge
  9151. #define FAR_EDGE_OR_BOX 1
  9152. #endif
  9153. if (last_x != x) {
  9154. last_x = x;
  9155. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9156. const float gx = constrain(floor(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9157. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9158. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9159. // Beyond the grid maintain height at grid edges
  9160. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9161. #endif
  9162. gridx = gx;
  9163. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9164. }
  9165. if (last_y != y || last_gridx != gridx) {
  9166. if (last_y != y) {
  9167. last_y = y;
  9168. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9169. const float gy = constrain(floor(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9170. ratio_y -= gy;
  9171. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9172. // Beyond the grid maintain height at grid edges
  9173. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9174. #endif
  9175. gridy = gy;
  9176. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9177. }
  9178. if (last_gridx != gridx || last_gridy != gridy) {
  9179. last_gridx = gridx;
  9180. last_gridy = gridy;
  9181. // Z at the box corners
  9182. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9183. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9184. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9185. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9186. }
  9187. // Bilinear interpolate. Needed since y or gridx has changed.
  9188. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9189. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9190. D = R - L;
  9191. }
  9192. const float offset = L + ratio_x * D; // the offset almost always changes
  9193. /*
  9194. static float last_offset = 0;
  9195. if (fabs(last_offset - offset) > 0.2) {
  9196. SERIAL_ECHOPGM("Sudden Shift at ");
  9197. SERIAL_ECHOPAIR("x=", x);
  9198. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9199. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9200. SERIAL_ECHOPAIR(" y=", y);
  9201. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9202. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9203. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9204. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9205. SERIAL_ECHOPAIR(" z1=", z1);
  9206. SERIAL_ECHOPAIR(" z2=", z2);
  9207. SERIAL_ECHOPAIR(" z3=", z3);
  9208. SERIAL_ECHOLNPAIR(" z4=", z4);
  9209. SERIAL_ECHOPAIR(" L=", L);
  9210. SERIAL_ECHOPAIR(" R=", R);
  9211. SERIAL_ECHOLNPAIR(" offset=", offset);
  9212. }
  9213. last_offset = offset;
  9214. //*/
  9215. return offset;
  9216. }
  9217. #endif // AUTO_BED_LEVELING_BILINEAR
  9218. #if ENABLED(DELTA)
  9219. /**
  9220. * Recalculate factors used for delta kinematics whenever
  9221. * settings have been changed (e.g., by M665).
  9222. */
  9223. void recalc_delta_settings(float radius, float diagonal_rod) {
  9224. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9225. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9226. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9227. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9228. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9229. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9230. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9231. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9232. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9233. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9234. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9235. }
  9236. #if ENABLED(DELTA_FAST_SQRT)
  9237. /**
  9238. * Fast inverse sqrt from Quake III Arena
  9239. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9240. */
  9241. float Q_rsqrt(float number) {
  9242. long i;
  9243. float x2, y;
  9244. const float threehalfs = 1.5f;
  9245. x2 = number * 0.5f;
  9246. y = number;
  9247. i = * ( long * ) &y; // evil floating point bit level hacking
  9248. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9249. y = * ( float * ) &i;
  9250. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9251. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9252. return y;
  9253. }
  9254. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9255. #else
  9256. #define _SQRT(n) sqrt(n)
  9257. #endif
  9258. /**
  9259. * Delta Inverse Kinematics
  9260. *
  9261. * Calculate the tower positions for a given logical
  9262. * position, storing the result in the delta[] array.
  9263. *
  9264. * This is an expensive calculation, requiring 3 square
  9265. * roots per segmented linear move, and strains the limits
  9266. * of a Mega2560 with a Graphical Display.
  9267. *
  9268. * Suggested optimizations include:
  9269. *
  9270. * - Disable the home_offset (M206) and/or position_shift (G92)
  9271. * features to remove up to 12 float additions.
  9272. *
  9273. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9274. * (see above)
  9275. */
  9276. // Macro to obtain the Z position of an individual tower
  9277. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9278. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9279. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9280. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9281. ) \
  9282. )
  9283. #define DELTA_RAW_IK() do { \
  9284. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9285. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9286. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9287. } while(0)
  9288. #define DELTA_LOGICAL_IK() do { \
  9289. const float raw[XYZ] = { \
  9290. RAW_X_POSITION(logical[X_AXIS]), \
  9291. RAW_Y_POSITION(logical[Y_AXIS]), \
  9292. RAW_Z_POSITION(logical[Z_AXIS]) \
  9293. }; \
  9294. DELTA_RAW_IK(); \
  9295. } while(0)
  9296. #define DELTA_DEBUG() do { \
  9297. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9298. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9299. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9300. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9301. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9302. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9303. } while(0)
  9304. void inverse_kinematics(const float logical[XYZ]) {
  9305. DELTA_LOGICAL_IK();
  9306. // DELTA_DEBUG();
  9307. }
  9308. /**
  9309. * Calculate the highest Z position where the
  9310. * effector has the full range of XY motion.
  9311. */
  9312. float delta_safe_distance_from_top() {
  9313. float cartesian[XYZ] = {
  9314. LOGICAL_X_POSITION(0),
  9315. LOGICAL_Y_POSITION(0),
  9316. LOGICAL_Z_POSITION(0)
  9317. };
  9318. inverse_kinematics(cartesian);
  9319. float distance = delta[A_AXIS];
  9320. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9321. inverse_kinematics(cartesian);
  9322. return abs(distance - delta[A_AXIS]);
  9323. }
  9324. /**
  9325. * Delta Forward Kinematics
  9326. *
  9327. * See the Wikipedia article "Trilateration"
  9328. * https://en.wikipedia.org/wiki/Trilateration
  9329. *
  9330. * Establish a new coordinate system in the plane of the
  9331. * three carriage points. This system has its origin at
  9332. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9333. * plane with a Z component of zero.
  9334. * We will define unit vectors in this coordinate system
  9335. * in our original coordinate system. Then when we calculate
  9336. * the Xnew, Ynew and Znew values, we can translate back into
  9337. * the original system by moving along those unit vectors
  9338. * by the corresponding values.
  9339. *
  9340. * Variable names matched to Marlin, c-version, and avoid the
  9341. * use of any vector library.
  9342. *
  9343. * by Andreas Hardtung 2016-06-07
  9344. * based on a Java function from "Delta Robot Kinematics V3"
  9345. * by Steve Graves
  9346. *
  9347. * The result is stored in the cartes[] array.
  9348. */
  9349. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9350. // Create a vector in old coordinates along x axis of new coordinate
  9351. float p12[3] = { delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z2 - z1 };
  9352. // Get the Magnitude of vector.
  9353. float d = sqrt( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9354. // Create unit vector by dividing by magnitude.
  9355. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9356. // Get the vector from the origin of the new system to the third point.
  9357. float p13[3] = { delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z3 - z1 };
  9358. // Use the dot product to find the component of this vector on the X axis.
  9359. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9360. // Create a vector along the x axis that represents the x component of p13.
  9361. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9362. // Subtract the X component from the original vector leaving only Y. We use the
  9363. // variable that will be the unit vector after we scale it.
  9364. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9365. // The magnitude of Y component
  9366. float j = sqrt( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9367. // Convert to a unit vector
  9368. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9369. // The cross product of the unit x and y is the unit z
  9370. // float[] ez = vectorCrossProd(ex, ey);
  9371. float ez[3] = {
  9372. ex[1] * ey[2] - ex[2] * ey[1],
  9373. ex[2] * ey[0] - ex[0] * ey[2],
  9374. ex[0] * ey[1] - ex[1] * ey[0]
  9375. };
  9376. // We now have the d, i and j values defined in Wikipedia.
  9377. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9378. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9379. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9380. Znew = sqrt(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9381. // Start from the origin of the old coordinates and add vectors in the
  9382. // old coords that represent the Xnew, Ynew and Znew to find the point
  9383. // in the old system.
  9384. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9385. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9386. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9387. }
  9388. void forward_kinematics_DELTA(float point[ABC]) {
  9389. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9390. }
  9391. #endif // DELTA
  9392. /**
  9393. * Get the stepper positions in the cartes[] array.
  9394. * Forward kinematics are applied for DELTA and SCARA.
  9395. *
  9396. * The result is in the current coordinate space with
  9397. * leveling applied. The coordinates need to be run through
  9398. * unapply_leveling to obtain the "ideal" coordinates
  9399. * suitable for current_position, etc.
  9400. */
  9401. void get_cartesian_from_steppers() {
  9402. #if ENABLED(DELTA)
  9403. forward_kinematics_DELTA(
  9404. stepper.get_axis_position_mm(A_AXIS),
  9405. stepper.get_axis_position_mm(B_AXIS),
  9406. stepper.get_axis_position_mm(C_AXIS)
  9407. );
  9408. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9409. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9410. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9411. #elif IS_SCARA
  9412. forward_kinematics_SCARA(
  9413. stepper.get_axis_position_degrees(A_AXIS),
  9414. stepper.get_axis_position_degrees(B_AXIS)
  9415. );
  9416. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9417. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9418. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9419. #else
  9420. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9421. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9422. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9423. #endif
  9424. }
  9425. /**
  9426. * Set the current_position for an axis based on
  9427. * the stepper positions, removing any leveling that
  9428. * may have been applied.
  9429. */
  9430. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9431. get_cartesian_from_steppers();
  9432. #if PLANNER_LEVELING
  9433. planner.unapply_leveling(cartes);
  9434. #endif
  9435. if (axis == ALL_AXES)
  9436. COPY(current_position, cartes);
  9437. else
  9438. current_position[axis] = cartes[axis];
  9439. }
  9440. #if ENABLED(MESH_BED_LEVELING)
  9441. /**
  9442. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9443. * splitting the move where it crosses mesh borders.
  9444. */
  9445. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9446. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9447. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9448. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9449. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9450. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9451. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9452. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9453. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9454. if (cx1 == cx2 && cy1 == cy2) {
  9455. // Start and end on same mesh square
  9456. line_to_destination(fr_mm_s);
  9457. set_current_to_destination();
  9458. return;
  9459. }
  9460. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9461. float normalized_dist, end[XYZE];
  9462. // Split at the left/front border of the right/top square
  9463. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9464. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9465. COPY(end, destination);
  9466. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9467. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9468. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9469. CBI(x_splits, gcx);
  9470. }
  9471. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9472. COPY(end, destination);
  9473. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9474. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9475. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9476. CBI(y_splits, gcy);
  9477. }
  9478. else {
  9479. // Already split on a border
  9480. line_to_destination(fr_mm_s);
  9481. set_current_to_destination();
  9482. return;
  9483. }
  9484. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9485. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9486. // Do the split and look for more borders
  9487. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9488. // Restore destination from stack
  9489. COPY(destination, end);
  9490. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9491. }
  9492. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9493. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9494. /**
  9495. * Prepare a bilinear-leveled linear move on Cartesian,
  9496. * splitting the move where it crosses grid borders.
  9497. */
  9498. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9499. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9500. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9501. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9502. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9503. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9504. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9505. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9506. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9507. if (cx1 == cx2 && cy1 == cy2) {
  9508. // Start and end on same mesh square
  9509. line_to_destination(fr_mm_s);
  9510. set_current_to_destination();
  9511. return;
  9512. }
  9513. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9514. float normalized_dist, end[XYZE];
  9515. // Split at the left/front border of the right/top square
  9516. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9517. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9518. COPY(end, destination);
  9519. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9520. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9521. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9522. CBI(x_splits, gcx);
  9523. }
  9524. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9525. COPY(end, destination);
  9526. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9527. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9528. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9529. CBI(y_splits, gcy);
  9530. }
  9531. else {
  9532. // Already split on a border
  9533. line_to_destination(fr_mm_s);
  9534. set_current_to_destination();
  9535. return;
  9536. }
  9537. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9538. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9539. // Do the split and look for more borders
  9540. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9541. // Restore destination from stack
  9542. COPY(destination, end);
  9543. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9544. }
  9545. #endif // AUTO_BED_LEVELING_BILINEAR
  9546. #if IS_KINEMATIC && !UBL_DELTA
  9547. /**
  9548. * Prepare a linear move in a DELTA or SCARA setup.
  9549. *
  9550. * This calls planner.buffer_line several times, adding
  9551. * small incremental moves for DELTA or SCARA.
  9552. */
  9553. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9554. // Get the top feedrate of the move in the XY plane
  9555. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9556. // If the move is only in Z/E don't split up the move
  9557. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9558. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9559. return false;
  9560. }
  9561. // Fail if attempting move outside printable radius
  9562. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9563. // Get the cartesian distances moved in XYZE
  9564. const float difference[XYZE] = {
  9565. ltarget[X_AXIS] - current_position[X_AXIS],
  9566. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9567. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9568. ltarget[E_AXIS] - current_position[E_AXIS]
  9569. };
  9570. // Get the linear distance in XYZ
  9571. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9572. // If the move is very short, check the E move distance
  9573. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = abs(difference[E_AXIS]);
  9574. // No E move either? Game over.
  9575. if (UNEAR_ZERO(cartesian_mm)) return true;
  9576. // Minimum number of seconds to move the given distance
  9577. const float seconds = cartesian_mm / _feedrate_mm_s;
  9578. // The number of segments-per-second times the duration
  9579. // gives the number of segments
  9580. uint16_t segments = delta_segments_per_second * seconds;
  9581. // For SCARA minimum segment size is 0.25mm
  9582. #if IS_SCARA
  9583. NOMORE(segments, cartesian_mm * 4);
  9584. #endif
  9585. // At least one segment is required
  9586. NOLESS(segments, 1);
  9587. // The approximate length of each segment
  9588. const float inv_segments = 1.0 / float(segments),
  9589. segment_distance[XYZE] = {
  9590. difference[X_AXIS] * inv_segments,
  9591. difference[Y_AXIS] * inv_segments,
  9592. difference[Z_AXIS] * inv_segments,
  9593. difference[E_AXIS] * inv_segments
  9594. };
  9595. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9596. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9597. // SERIAL_ECHOLNPAIR(" segments=", segments);
  9598. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9599. // SCARA needs to scale the feed rate from mm/s to degrees/s
  9600. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  9601. feed_factor = inv_segment_length * _feedrate_mm_s;
  9602. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  9603. oldB = stepper.get_axis_position_degrees(B_AXIS);
  9604. #endif
  9605. // Get the logical current position as starting point
  9606. float logical[XYZE];
  9607. COPY(logical, current_position);
  9608. // Drop one segment so the last move is to the exact target.
  9609. // If there's only 1 segment, loops will be skipped entirely.
  9610. --segments;
  9611. // Calculate and execute the segments
  9612. for (uint16_t s = segments + 1; --s;) {
  9613. LOOP_XYZE(i) logical[i] += segment_distance[i];
  9614. #if ENABLED(DELTA)
  9615. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  9616. #else
  9617. inverse_kinematics(logical);
  9618. #endif
  9619. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  9620. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9621. // For SCARA scale the feed rate from mm/s to degrees/s
  9622. // Use ratio between the length of the move and the larger angle change
  9623. const float adiff = abs(delta[A_AXIS] - oldA),
  9624. bdiff = abs(delta[B_AXIS] - oldB);
  9625. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9626. oldA = delta[A_AXIS];
  9627. oldB = delta[B_AXIS];
  9628. #else
  9629. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  9630. #endif
  9631. }
  9632. // Since segment_distance is only approximate,
  9633. // the final move must be to the exact destination.
  9634. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9635. // For SCARA scale the feed rate from mm/s to degrees/s
  9636. // With segments > 1 length is 1 segment, otherwise total length
  9637. inverse_kinematics(ltarget);
  9638. ADJUST_DELTA(ltarget);
  9639. const float adiff = abs(delta[A_AXIS] - oldA),
  9640. bdiff = abs(delta[B_AXIS] - oldB);
  9641. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9642. #else
  9643. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9644. #endif
  9645. return false;
  9646. }
  9647. #else // !IS_KINEMATIC || UBL_DELTA
  9648. /**
  9649. * Prepare a linear move in a Cartesian setup.
  9650. * If Mesh Bed Leveling is enabled, perform a mesh move.
  9651. *
  9652. * Returns true if the caller didn't update current_position.
  9653. */
  9654. inline bool prepare_move_to_destination_cartesian() {
  9655. #if ENABLED(AUTO_BED_LEVELING_UBL)
  9656. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9657. if (ubl.state.active) { // direct use of ubl.state.active for speed
  9658. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  9659. return true;
  9660. }
  9661. else
  9662. line_to_destination(fr_scaled);
  9663. #else
  9664. // Do not use feedrate_percentage for E or Z only moves
  9665. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  9666. line_to_destination();
  9667. else {
  9668. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9669. #if ENABLED(MESH_BED_LEVELING)
  9670. if (mbl.active()) { // direct used of mbl.active() for speed
  9671. mesh_line_to_destination(fr_scaled);
  9672. return true;
  9673. }
  9674. else
  9675. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9676. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  9677. bilinear_line_to_destination(fr_scaled);
  9678. return true;
  9679. }
  9680. else
  9681. #endif
  9682. line_to_destination(fr_scaled);
  9683. }
  9684. #endif
  9685. return false;
  9686. }
  9687. #endif // !IS_KINEMATIC || UBL_DELTA
  9688. #if ENABLED(DUAL_X_CARRIAGE)
  9689. /**
  9690. * Prepare a linear move in a dual X axis setup
  9691. */
  9692. inline bool prepare_move_to_destination_dualx() {
  9693. if (active_extruder_parked) {
  9694. switch (dual_x_carriage_mode) {
  9695. case DXC_FULL_CONTROL_MODE:
  9696. break;
  9697. case DXC_AUTO_PARK_MODE:
  9698. if (current_position[E_AXIS] == destination[E_AXIS]) {
  9699. // This is a travel move (with no extrusion)
  9700. // Skip it, but keep track of the current position
  9701. // (so it can be used as the start of the next non-travel move)
  9702. if (delayed_move_time != 0xFFFFFFFFUL) {
  9703. set_current_to_destination();
  9704. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  9705. delayed_move_time = millis();
  9706. return true;
  9707. }
  9708. }
  9709. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  9710. for (uint8_t i = 0; i < 3; i++)
  9711. planner.buffer_line(
  9712. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  9713. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  9714. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  9715. current_position[E_AXIS],
  9716. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  9717. active_extruder
  9718. );
  9719. delayed_move_time = 0;
  9720. active_extruder_parked = false;
  9721. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9722. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  9723. #endif
  9724. break;
  9725. case DXC_DUPLICATION_MODE:
  9726. if (active_extruder == 0) {
  9727. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9728. if (DEBUGGING(LEVELING)) {
  9729. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  9730. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  9731. }
  9732. #endif
  9733. // move duplicate extruder into correct duplication position.
  9734. planner.set_position_mm(
  9735. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  9736. current_position[Y_AXIS],
  9737. current_position[Z_AXIS],
  9738. current_position[E_AXIS]
  9739. );
  9740. planner.buffer_line(
  9741. current_position[X_AXIS] + duplicate_extruder_x_offset,
  9742. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  9743. planner.max_feedrate_mm_s[X_AXIS], 1
  9744. );
  9745. SYNC_PLAN_POSITION_KINEMATIC();
  9746. stepper.synchronize();
  9747. extruder_duplication_enabled = true;
  9748. active_extruder_parked = false;
  9749. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9750. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  9751. #endif
  9752. }
  9753. else {
  9754. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9755. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  9756. #endif
  9757. }
  9758. break;
  9759. }
  9760. }
  9761. return false;
  9762. }
  9763. #endif // DUAL_X_CARRIAGE
  9764. /**
  9765. * Prepare a single move and get ready for the next one
  9766. *
  9767. * This may result in several calls to planner.buffer_line to
  9768. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  9769. */
  9770. void prepare_move_to_destination() {
  9771. clamp_to_software_endstops(destination);
  9772. refresh_cmd_timeout();
  9773. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9774. if (!DEBUGGING(DRYRUN)) {
  9775. if (destination[E_AXIS] != current_position[E_AXIS]) {
  9776. if (thermalManager.tooColdToExtrude(active_extruder)) {
  9777. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9778. SERIAL_ECHO_START;
  9779. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  9780. }
  9781. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9782. if (labs(destination[E_AXIS] - current_position[E_AXIS]) > EXTRUDE_MAXLENGTH) {
  9783. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9784. SERIAL_ECHO_START;
  9785. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  9786. }
  9787. #endif
  9788. }
  9789. }
  9790. #endif
  9791. if (
  9792. #if IS_KINEMATIC
  9793. #if UBL_DELTA
  9794. ubl.prepare_linear_move_to(destination, feedrate_mm_s)
  9795. #else
  9796. prepare_kinematic_move_to(destination)
  9797. #endif
  9798. #elif ENABLED(DUAL_X_CARRIAGE)
  9799. prepare_move_to_destination_dualx()
  9800. #elif UBL_DELTA // will work for CARTESIAN too (smaller segments follow mesh more closely)
  9801. ubl.prepare_linear_move_to(destination, feedrate_mm_s)
  9802. #else
  9803. prepare_move_to_destination_cartesian()
  9804. #endif
  9805. ) return;
  9806. set_current_to_destination();
  9807. }
  9808. #if ENABLED(ARC_SUPPORT)
  9809. /**
  9810. * Plan an arc in 2 dimensions
  9811. *
  9812. * The arc is approximated by generating many small linear segments.
  9813. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  9814. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  9815. * larger segments will tend to be more efficient. Your slicer should have
  9816. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  9817. */
  9818. void plan_arc(
  9819. float logical[XYZE], // Destination position
  9820. float *offset, // Center of rotation relative to current_position
  9821. uint8_t clockwise // Clockwise?
  9822. ) {
  9823. float r_X = -offset[X_AXIS], // Radius vector from center to current location
  9824. r_Y = -offset[Y_AXIS];
  9825. const float radius = HYPOT(r_X, r_Y),
  9826. center_X = current_position[X_AXIS] - r_X,
  9827. center_Y = current_position[Y_AXIS] - r_Y,
  9828. rt_X = logical[X_AXIS] - center_X,
  9829. rt_Y = logical[Y_AXIS] - center_Y,
  9830. linear_travel = logical[Z_AXIS] - current_position[Z_AXIS],
  9831. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  9832. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  9833. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  9834. if (angular_travel < 0) angular_travel += RADIANS(360);
  9835. if (clockwise) angular_travel -= RADIANS(360);
  9836. // Make a circle if the angular rotation is 0
  9837. if (angular_travel == 0 && current_position[X_AXIS] == logical[X_AXIS] && current_position[Y_AXIS] == logical[Y_AXIS])
  9838. angular_travel += RADIANS(360);
  9839. const float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel));
  9840. if (mm_of_travel < 0.001) return;
  9841. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  9842. if (segments == 0) segments = 1;
  9843. /**
  9844. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  9845. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  9846. * r_T = [cos(phi) -sin(phi);
  9847. * sin(phi) cos(phi)] * r ;
  9848. *
  9849. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  9850. * defined from the circle center to the initial position. Each line segment is formed by successive
  9851. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  9852. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  9853. * all double numbers are single precision on the Arduino. (True double precision will not have
  9854. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  9855. * tool precision in some cases. Therefore, arc path correction is implemented.
  9856. *
  9857. * Small angle approximation may be used to reduce computation overhead further. This approximation
  9858. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  9859. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  9860. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  9861. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  9862. * issue for CNC machines with the single precision Arduino calculations.
  9863. *
  9864. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  9865. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  9866. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  9867. * This is important when there are successive arc motions.
  9868. */
  9869. // Vector rotation matrix values
  9870. float arc_target[XYZE];
  9871. const float theta_per_segment = angular_travel / segments,
  9872. linear_per_segment = linear_travel / segments,
  9873. extruder_per_segment = extruder_travel / segments,
  9874. sin_T = theta_per_segment,
  9875. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  9876. // Initialize the linear axis
  9877. arc_target[Z_AXIS] = current_position[Z_AXIS];
  9878. // Initialize the extruder axis
  9879. arc_target[E_AXIS] = current_position[E_AXIS];
  9880. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  9881. millis_t next_idle_ms = millis() + 200UL;
  9882. int8_t count = 0;
  9883. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  9884. thermalManager.manage_heater();
  9885. if (ELAPSED(millis(), next_idle_ms)) {
  9886. next_idle_ms = millis() + 200UL;
  9887. idle();
  9888. }
  9889. if (++count < N_ARC_CORRECTION) {
  9890. // Apply vector rotation matrix to previous r_X / 1
  9891. const float r_new_Y = r_X * sin_T + r_Y * cos_T;
  9892. r_X = r_X * cos_T - r_Y * sin_T;
  9893. r_Y = r_new_Y;
  9894. }
  9895. else {
  9896. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  9897. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  9898. // To reduce stuttering, the sin and cos could be computed at different times.
  9899. // For now, compute both at the same time.
  9900. const float cos_Ti = cos(i * theta_per_segment),
  9901. sin_Ti = sin(i * theta_per_segment);
  9902. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  9903. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  9904. count = 0;
  9905. }
  9906. // Update arc_target location
  9907. arc_target[X_AXIS] = center_X + r_X;
  9908. arc_target[Y_AXIS] = center_Y + r_Y;
  9909. arc_target[Z_AXIS] += linear_per_segment;
  9910. arc_target[E_AXIS] += extruder_per_segment;
  9911. clamp_to_software_endstops(arc_target);
  9912. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  9913. }
  9914. // Ensure last segment arrives at target location.
  9915. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  9916. // As far as the parser is concerned, the position is now == target. In reality the
  9917. // motion control system might still be processing the action and the real tool position
  9918. // in any intermediate location.
  9919. set_current_to_destination();
  9920. }
  9921. #endif
  9922. #if ENABLED(BEZIER_CURVE_SUPPORT)
  9923. void plan_cubic_move(const float offset[4]) {
  9924. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  9925. // As far as the parser is concerned, the position is now == destination. In reality the
  9926. // motion control system might still be processing the action and the real tool position
  9927. // in any intermediate location.
  9928. set_current_to_destination();
  9929. }
  9930. #endif // BEZIER_CURVE_SUPPORT
  9931. #if ENABLED(USE_CONTROLLER_FAN)
  9932. void controllerFan() {
  9933. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  9934. nextMotorCheck = 0; // Last time the state was checked
  9935. const millis_t ms = millis();
  9936. if (ELAPSED(ms, nextMotorCheck)) {
  9937. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  9938. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_amount_bed > 0
  9939. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  9940. #if E_STEPPERS > 1
  9941. || E1_ENABLE_READ == E_ENABLE_ON
  9942. #if HAS_X2_ENABLE
  9943. || X2_ENABLE_READ == X_ENABLE_ON
  9944. #endif
  9945. #if E_STEPPERS > 2
  9946. || E2_ENABLE_READ == E_ENABLE_ON
  9947. #if E_STEPPERS > 3
  9948. || E3_ENABLE_READ == E_ENABLE_ON
  9949. #if E_STEPPERS > 4
  9950. || E4_ENABLE_READ == E_ENABLE_ON
  9951. #endif // E_STEPPERS > 4
  9952. #endif // E_STEPPERS > 3
  9953. #endif // E_STEPPERS > 2
  9954. #endif // E_STEPPERS > 1
  9955. ) {
  9956. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  9957. }
  9958. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  9959. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  9960. // allows digital or PWM fan output to be used (see M42 handling)
  9961. WRITE(CONTROLLER_FAN_PIN, speed);
  9962. analogWrite(CONTROLLER_FAN_PIN, speed);
  9963. }
  9964. }
  9965. #endif // USE_CONTROLLER_FAN
  9966. #if ENABLED(MORGAN_SCARA)
  9967. /**
  9968. * Morgan SCARA Forward Kinematics. Results in cartes[].
  9969. * Maths and first version by QHARLEY.
  9970. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  9971. */
  9972. void forward_kinematics_SCARA(const float &a, const float &b) {
  9973. float a_sin = sin(RADIANS(a)) * L1,
  9974. a_cos = cos(RADIANS(a)) * L1,
  9975. b_sin = sin(RADIANS(b)) * L2,
  9976. b_cos = cos(RADIANS(b)) * L2;
  9977. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  9978. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  9979. /*
  9980. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  9981. SERIAL_ECHOPAIR(" b=", b);
  9982. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  9983. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  9984. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  9985. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  9986. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  9987. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  9988. //*/
  9989. }
  9990. /**
  9991. * Morgan SCARA Inverse Kinematics. Results in delta[].
  9992. *
  9993. * See http://forums.reprap.org/read.php?185,283327
  9994. *
  9995. * Maths and first version by QHARLEY.
  9996. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  9997. */
  9998. void inverse_kinematics(const float logical[XYZ]) {
  9999. static float C2, S2, SK1, SK2, THETA, PSI;
  10000. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  10001. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  10002. if (L1 == L2)
  10003. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  10004. else
  10005. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  10006. S2 = sqrt(sq(C2) - 1);
  10007. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  10008. SK1 = L1 + L2 * C2;
  10009. // Rotated Arm2 gives the distance from Arm1 to Arm2
  10010. SK2 = L2 * S2;
  10011. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  10012. THETA = atan2(SK1, SK2) - atan2(sx, sy);
  10013. // Angle of Arm2
  10014. PSI = atan2(S2, C2);
  10015. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  10016. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  10017. delta[C_AXIS] = logical[Z_AXIS];
  10018. /*
  10019. DEBUG_POS("SCARA IK", logical);
  10020. DEBUG_POS("SCARA IK", delta);
  10021. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  10022. SERIAL_ECHOPAIR(",", sy);
  10023. SERIAL_ECHOPAIR(" C2=", C2);
  10024. SERIAL_ECHOPAIR(" S2=", S2);
  10025. SERIAL_ECHOPAIR(" Theta=", THETA);
  10026. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  10027. //*/
  10028. }
  10029. #endif // MORGAN_SCARA
  10030. #if ENABLED(TEMP_STAT_LEDS)
  10031. static bool red_led = false;
  10032. static millis_t next_status_led_update_ms = 0;
  10033. void handle_status_leds(void) {
  10034. if (ELAPSED(millis(), next_status_led_update_ms)) {
  10035. next_status_led_update_ms += 500; // Update every 0.5s
  10036. float max_temp = 0.0;
  10037. #if HAS_TEMP_BED
  10038. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10039. #endif
  10040. HOTEND_LOOP()
  10041. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10042. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10043. if (new_led != red_led) {
  10044. red_led = new_led;
  10045. #if PIN_EXISTS(STAT_LED_RED)
  10046. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10047. #if PIN_EXISTS(STAT_LED_BLUE)
  10048. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10049. #endif
  10050. #else
  10051. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10052. #endif
  10053. }
  10054. }
  10055. }
  10056. #endif
  10057. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10058. void handle_filament_runout() {
  10059. if (!filament_ran_out) {
  10060. filament_ran_out = true;
  10061. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10062. stepper.synchronize();
  10063. }
  10064. }
  10065. #endif // FILAMENT_RUNOUT_SENSOR
  10066. #if ENABLED(FAST_PWM_FAN)
  10067. void setPwmFrequency(uint8_t pin, int val) {
  10068. val &= 0x07;
  10069. switch (digitalPinToTimer(pin)) {
  10070. #ifdef TCCR0A
  10071. case TIMER0A:
  10072. case TIMER0B:
  10073. //_SET_CS(0, val);
  10074. break;
  10075. #endif
  10076. #ifdef TCCR1A
  10077. case TIMER1A:
  10078. case TIMER1B:
  10079. //_SET_CS(1, val);
  10080. break;
  10081. #endif
  10082. #ifdef TCCR2
  10083. case TIMER2:
  10084. case TIMER2:
  10085. _SET_CS(2, val);
  10086. break;
  10087. #endif
  10088. #ifdef TCCR2A
  10089. case TIMER2A:
  10090. case TIMER2B:
  10091. _SET_CS(2, val);
  10092. break;
  10093. #endif
  10094. #ifdef TCCR3A
  10095. case TIMER3A:
  10096. case TIMER3B:
  10097. case TIMER3C:
  10098. _SET_CS(3, val);
  10099. break;
  10100. #endif
  10101. #ifdef TCCR4A
  10102. case TIMER4A:
  10103. case TIMER4B:
  10104. case TIMER4C:
  10105. _SET_CS(4, val);
  10106. break;
  10107. #endif
  10108. #ifdef TCCR5A
  10109. case TIMER5A:
  10110. case TIMER5B:
  10111. case TIMER5C:
  10112. _SET_CS(5, val);
  10113. break;
  10114. #endif
  10115. }
  10116. }
  10117. #endif // FAST_PWM_FAN
  10118. float calculate_volumetric_multiplier(float diameter) {
  10119. if (!volumetric_enabled || diameter == 0) return 1.0;
  10120. return 1.0 / (M_PI * sq(diameter * 0.5));
  10121. }
  10122. void calculate_volumetric_multipliers() {
  10123. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10124. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10125. }
  10126. void enable_all_steppers() {
  10127. enable_X();
  10128. enable_Y();
  10129. enable_Z();
  10130. enable_E0();
  10131. enable_E1();
  10132. enable_E2();
  10133. enable_E3();
  10134. enable_E4();
  10135. }
  10136. void disable_e_steppers() {
  10137. disable_E0();
  10138. disable_E1();
  10139. disable_E2();
  10140. disable_E3();
  10141. disable_E4();
  10142. }
  10143. void disable_all_steppers() {
  10144. disable_X();
  10145. disable_Y();
  10146. disable_Z();
  10147. disable_e_steppers();
  10148. }
  10149. #if ENABLED(HAVE_TMC2130)
  10150. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10151. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10152. const bool is_otpw = st.checkOT();
  10153. // Report if a warning was triggered
  10154. static bool previous_otpw = false;
  10155. if (is_otpw && !previous_otpw) {
  10156. char timestamp[10];
  10157. duration_t elapsed = print_job_timer.duration();
  10158. const bool has_days = (elapsed.value > 60*60*24L);
  10159. (void)elapsed.toDigital(timestamp, has_days);
  10160. SERIAL_ECHO(timestamp);
  10161. SERIAL_ECHO(": ");
  10162. SERIAL_ECHO(axisID);
  10163. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10164. }
  10165. previous_otpw = is_otpw;
  10166. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10167. // Return if user has not enabled current control start with M906 S1.
  10168. if (!auto_current_control) return;
  10169. /**
  10170. * Decrease current if is_otpw is true.
  10171. * Bail out if driver is disabled.
  10172. * Increase current if OTPW has not been triggered yet.
  10173. */
  10174. uint16_t current = st.getCurrent();
  10175. if (is_otpw) {
  10176. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10177. #if ENABLED(REPORT_CURRENT_CHANGE)
  10178. SERIAL_ECHO(axisID);
  10179. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10180. #endif
  10181. }
  10182. else if (!st.isEnabled())
  10183. return;
  10184. else if (!is_otpw && !st.getOTPW()) {
  10185. current += CURRENT_STEP;
  10186. if (current <= AUTO_ADJUST_MAX) {
  10187. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10188. #if ENABLED(REPORT_CURRENT_CHANGE)
  10189. SERIAL_ECHO(axisID);
  10190. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10191. #endif
  10192. }
  10193. }
  10194. SERIAL_EOL;
  10195. #endif
  10196. }
  10197. void checkOverTemp() {
  10198. static millis_t next_cOT = 0;
  10199. if (ELAPSED(millis(), next_cOT)) {
  10200. next_cOT = millis() + 5000;
  10201. #if ENABLED(X_IS_TMC2130)
  10202. automatic_current_control(stepperX, "X");
  10203. #endif
  10204. #if ENABLED(Y_IS_TMC2130)
  10205. automatic_current_control(stepperY, "Y");
  10206. #endif
  10207. #if ENABLED(Z_IS_TMC2130)
  10208. automatic_current_control(stepperZ, "Z");
  10209. #endif
  10210. #if ENABLED(X2_IS_TMC2130)
  10211. automatic_current_control(stepperX2, "X2");
  10212. #endif
  10213. #if ENABLED(Y2_IS_TMC2130)
  10214. automatic_current_control(stepperY2, "Y2");
  10215. #endif
  10216. #if ENABLED(Z2_IS_TMC2130)
  10217. automatic_current_control(stepperZ2, "Z2");
  10218. #endif
  10219. #if ENABLED(E0_IS_TMC2130)
  10220. automatic_current_control(stepperE0, "E0");
  10221. #endif
  10222. #if ENABLED(E1_IS_TMC2130)
  10223. automatic_current_control(stepperE1, "E1");
  10224. #endif
  10225. #if ENABLED(E2_IS_TMC2130)
  10226. automatic_current_control(stepperE2, "E2");
  10227. #endif
  10228. #if ENABLED(E3_IS_TMC2130)
  10229. automatic_current_control(stepperE3, "E3");
  10230. #endif
  10231. #if ENABLED(E4_IS_TMC2130)
  10232. automatic_current_control(stepperE4, "E4");
  10233. #endif
  10234. #if ENABLED(E4_IS_TMC2130)
  10235. automatic_current_control(stepperE4);
  10236. #endif
  10237. }
  10238. }
  10239. #endif // HAVE_TMC2130
  10240. /**
  10241. * Manage several activities:
  10242. * - Check for Filament Runout
  10243. * - Keep the command buffer full
  10244. * - Check for maximum inactive time between commands
  10245. * - Check for maximum inactive time between stepper commands
  10246. * - Check if pin CHDK needs to go LOW
  10247. * - Check for KILL button held down
  10248. * - Check for HOME button held down
  10249. * - Check if cooling fan needs to be switched on
  10250. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10251. */
  10252. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10253. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10254. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10255. handle_filament_runout();
  10256. #endif
  10257. if (commands_in_queue < BUFSIZE) get_available_commands();
  10258. const millis_t ms = millis();
  10259. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10260. SERIAL_ERROR_START;
  10261. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10262. kill(PSTR(MSG_KILLED));
  10263. }
  10264. // Prevent steppers timing-out in the middle of M600
  10265. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10266. #define MOVE_AWAY_TEST !move_away_flag
  10267. #else
  10268. #define MOVE_AWAY_TEST true
  10269. #endif
  10270. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10271. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10272. #if ENABLED(DISABLE_INACTIVE_X)
  10273. disable_X();
  10274. #endif
  10275. #if ENABLED(DISABLE_INACTIVE_Y)
  10276. disable_Y();
  10277. #endif
  10278. #if ENABLED(DISABLE_INACTIVE_Z)
  10279. disable_Z();
  10280. #endif
  10281. #if ENABLED(DISABLE_INACTIVE_E)
  10282. disable_e_steppers();
  10283. #endif
  10284. }
  10285. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10286. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10287. chdkActive = false;
  10288. WRITE(CHDK, LOW);
  10289. }
  10290. #endif
  10291. #if HAS_KILL
  10292. // Check if the kill button was pressed and wait just in case it was an accidental
  10293. // key kill key press
  10294. // -------------------------------------------------------------------------------
  10295. static int killCount = 0; // make the inactivity button a bit less responsive
  10296. const int KILL_DELAY = 750;
  10297. if (!READ(KILL_PIN))
  10298. killCount++;
  10299. else if (killCount > 0)
  10300. killCount--;
  10301. // Exceeded threshold and we can confirm that it was not accidental
  10302. // KILL the machine
  10303. // ----------------------------------------------------------------
  10304. if (killCount >= KILL_DELAY) {
  10305. SERIAL_ERROR_START;
  10306. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10307. kill(PSTR(MSG_KILLED));
  10308. }
  10309. #endif
  10310. #if HAS_HOME
  10311. // Check to see if we have to home, use poor man's debouncer
  10312. // ---------------------------------------------------------
  10313. static int homeDebounceCount = 0; // poor man's debouncing count
  10314. const int HOME_DEBOUNCE_DELAY = 2500;
  10315. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10316. if (!homeDebounceCount) {
  10317. enqueue_and_echo_commands_P(PSTR("G28"));
  10318. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10319. }
  10320. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10321. homeDebounceCount++;
  10322. else
  10323. homeDebounceCount = 0;
  10324. }
  10325. #endif
  10326. #if ENABLED(USE_CONTROLLER_FAN)
  10327. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10328. #endif
  10329. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10330. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10331. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10332. bool oldstatus;
  10333. #if ENABLED(SWITCHING_EXTRUDER)
  10334. oldstatus = E0_ENABLE_READ;
  10335. enable_E0();
  10336. #else // !SWITCHING_EXTRUDER
  10337. switch (active_extruder) {
  10338. case 0: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10339. #if E_STEPPERS > 1
  10340. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10341. #if E_STEPPERS > 2
  10342. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10343. #if E_STEPPERS > 3
  10344. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10345. #if E_STEPPERS > 4
  10346. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10347. #endif // E_STEPPERS > 4
  10348. #endif // E_STEPPERS > 3
  10349. #endif // E_STEPPERS > 2
  10350. #endif // E_STEPPERS > 1
  10351. }
  10352. #endif // !SWITCHING_EXTRUDER
  10353. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10354. const float olde = current_position[E_AXIS];
  10355. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10356. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10357. current_position[E_AXIS] = olde;
  10358. planner.set_e_position_mm(olde);
  10359. stepper.synchronize();
  10360. #if ENABLED(SWITCHING_EXTRUDER)
  10361. E0_ENABLE_WRITE(oldstatus);
  10362. #else
  10363. switch (active_extruder) {
  10364. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10365. #if E_STEPPERS > 1
  10366. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10367. #if E_STEPPERS > 2
  10368. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10369. #if E_STEPPERS > 3
  10370. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10371. #if E_STEPPERS > 4
  10372. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10373. #endif // E_STEPPERS > 4
  10374. #endif // E_STEPPERS > 3
  10375. #endif // E_STEPPERS > 2
  10376. #endif // E_STEPPERS > 1
  10377. }
  10378. #endif // !SWITCHING_EXTRUDER
  10379. }
  10380. #endif // EXTRUDER_RUNOUT_PREVENT
  10381. #if ENABLED(DUAL_X_CARRIAGE)
  10382. // handle delayed move timeout
  10383. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10384. // travel moves have been received so enact them
  10385. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10386. set_destination_to_current();
  10387. prepare_move_to_destination();
  10388. }
  10389. #endif
  10390. #if ENABLED(TEMP_STAT_LEDS)
  10391. handle_status_leds();
  10392. #endif
  10393. #if ENABLED(HAVE_TMC2130)
  10394. checkOverTemp();
  10395. #endif
  10396. planner.check_axes_activity();
  10397. }
  10398. /**
  10399. * Standard idle routine keeps the machine alive
  10400. */
  10401. void idle(
  10402. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10403. bool no_stepper_sleep/*=false*/
  10404. #endif
  10405. ) {
  10406. lcd_update();
  10407. host_keepalive();
  10408. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10409. auto_report_temperatures();
  10410. #endif
  10411. manage_inactivity(
  10412. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10413. no_stepper_sleep
  10414. #endif
  10415. );
  10416. thermalManager.manage_heater();
  10417. #if ENABLED(PRINTCOUNTER)
  10418. print_job_timer.tick();
  10419. #endif
  10420. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10421. buzzer.tick();
  10422. #endif
  10423. }
  10424. /**
  10425. * Kill all activity and lock the machine.
  10426. * After this the machine will need to be reset.
  10427. */
  10428. void kill(const char* lcd_msg) {
  10429. SERIAL_ERROR_START;
  10430. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10431. thermalManager.disable_all_heaters();
  10432. disable_all_steppers();
  10433. #if ENABLED(ULTRA_LCD)
  10434. kill_screen(lcd_msg);
  10435. #else
  10436. UNUSED(lcd_msg);
  10437. #endif
  10438. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10439. cli(); // Stop interrupts
  10440. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10441. thermalManager.disable_all_heaters(); //turn off heaters again
  10442. #if HAS_POWER_SWITCH
  10443. SET_INPUT(PS_ON_PIN);
  10444. #endif
  10445. suicide();
  10446. while (1) {
  10447. #if ENABLED(USE_WATCHDOG)
  10448. watchdog_reset();
  10449. #endif
  10450. } // Wait for reset
  10451. }
  10452. /**
  10453. * Turn off heaters and stop the print in progress
  10454. * After a stop the machine may be resumed with M999
  10455. */
  10456. void stop() {
  10457. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10458. #if ENABLED(PROBING_FANS_OFF)
  10459. if (fans_paused) fans_pause(false); // put things back the way they were
  10460. #endif
  10461. if (IsRunning()) {
  10462. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10463. SERIAL_ERROR_START;
  10464. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10465. LCD_MESSAGEPGM(MSG_STOPPED);
  10466. safe_delay(350); // allow enough time for messages to get out before stopping
  10467. Running = false;
  10468. }
  10469. }
  10470. /**
  10471. * Marlin entry-point: Set up before the program loop
  10472. * - Set up the kill pin, filament runout, power hold
  10473. * - Start the serial port
  10474. * - Print startup messages and diagnostics
  10475. * - Get EEPROM or default settings
  10476. * - Initialize managers for:
  10477. * • temperature
  10478. * • planner
  10479. * • watchdog
  10480. * • stepper
  10481. * • photo pin
  10482. * • servos
  10483. * • LCD controller
  10484. * • Digipot I2C
  10485. * • Z probe sled
  10486. * • status LEDs
  10487. */
  10488. void setup() {
  10489. #ifdef DISABLE_JTAG
  10490. // Disable JTAG on AT90USB chips to free up pins for IO
  10491. MCUCR = 0x80;
  10492. MCUCR = 0x80;
  10493. #endif
  10494. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10495. setup_filrunoutpin();
  10496. #endif
  10497. setup_killpin();
  10498. setup_powerhold();
  10499. #if HAS_STEPPER_RESET
  10500. disableStepperDrivers();
  10501. #endif
  10502. MYSERIAL.begin(BAUDRATE);
  10503. SERIAL_PROTOCOLLNPGM("start");
  10504. SERIAL_ECHO_START;
  10505. // Check startup - does nothing if bootloader sets MCUSR to 0
  10506. byte mcu = MCUSR;
  10507. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10508. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10509. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10510. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10511. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10512. MCUSR = 0;
  10513. SERIAL_ECHOPGM(MSG_MARLIN);
  10514. SERIAL_CHAR(' ');
  10515. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10516. SERIAL_EOL;
  10517. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10518. SERIAL_ECHO_START;
  10519. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10520. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10521. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10522. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10523. #endif
  10524. SERIAL_ECHO_START;
  10525. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10526. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10527. // Send "ok" after commands by default
  10528. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10529. // Load data from EEPROM if available (or use defaults)
  10530. // This also updates variables in the planner, elsewhere
  10531. (void)settings.load();
  10532. #if HAS_M206_COMMAND
  10533. // Initialize current position based on home_offset
  10534. COPY(current_position, home_offset);
  10535. #else
  10536. ZERO(current_position);
  10537. #endif
  10538. // Vital to init stepper/planner equivalent for current_position
  10539. SYNC_PLAN_POSITION_KINEMATIC();
  10540. thermalManager.init(); // Initialize temperature loop
  10541. #if ENABLED(USE_WATCHDOG)
  10542. watchdog_init();
  10543. #endif
  10544. stepper.init(); // Initialize stepper, this enables interrupts!
  10545. servo_init();
  10546. #if HAS_PHOTOGRAPH
  10547. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10548. #endif
  10549. #if HAS_CASE_LIGHT
  10550. case_light_on = CASE_LIGHT_DEFAULT_ON;
  10551. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  10552. update_case_light();
  10553. #endif
  10554. #if ENABLED(SPINDLE_LASER_ENABLE)
  10555. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10556. #if SPINDLE_DIR_CHANGE
  10557. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10558. #endif
  10559. #if ENABLED(SPINDLE_LASER_PWM)
  10560. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10561. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10562. #endif
  10563. #endif
  10564. #if HAS_BED_PROBE
  10565. endstops.enable_z_probe(false);
  10566. #endif
  10567. #if ENABLED(USE_CONTROLLER_FAN)
  10568. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  10569. #endif
  10570. #if HAS_STEPPER_RESET
  10571. enableStepperDrivers();
  10572. #endif
  10573. #if ENABLED(DIGIPOT_I2C)
  10574. digipot_i2c_init();
  10575. #endif
  10576. #if ENABLED(DAC_STEPPER_CURRENT)
  10577. dac_init();
  10578. #endif
  10579. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  10580. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  10581. #endif
  10582. setup_homepin();
  10583. #if PIN_EXISTS(STAT_LED_RED)
  10584. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  10585. #endif
  10586. #if PIN_EXISTS(STAT_LED_BLUE)
  10587. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  10588. #endif
  10589. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  10590. SET_OUTPUT(RGB_LED_R_PIN);
  10591. SET_OUTPUT(RGB_LED_G_PIN);
  10592. SET_OUTPUT(RGB_LED_B_PIN);
  10593. #if ENABLED(RGBW_LED)
  10594. SET_OUTPUT(RGB_LED_W_PIN);
  10595. #endif
  10596. #endif
  10597. lcd_init();
  10598. #if ENABLED(SHOW_BOOTSCREEN)
  10599. #if ENABLED(DOGLCD)
  10600. safe_delay(BOOTSCREEN_TIMEOUT);
  10601. #elif ENABLED(ULTRA_LCD)
  10602. bootscreen();
  10603. #if DISABLED(SDSUPPORT)
  10604. lcd_init();
  10605. #endif
  10606. #endif
  10607. #endif
  10608. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10609. // Initialize mixing to 100% color 1
  10610. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10611. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  10612. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  10613. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10614. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  10615. #endif
  10616. #if ENABLED(BLTOUCH)
  10617. // Make sure any BLTouch error condition is cleared
  10618. bltouch_command(BLTOUCH_RESET);
  10619. set_bltouch_deployed(true);
  10620. set_bltouch_deployed(false);
  10621. #endif
  10622. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  10623. i2c.onReceive(i2c_on_receive);
  10624. i2c.onRequest(i2c_on_request);
  10625. #endif
  10626. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  10627. setup_endstop_interrupts();
  10628. #endif
  10629. }
  10630. /**
  10631. * The main Marlin program loop
  10632. *
  10633. * - Save or log commands to SD
  10634. * - Process available commands (if not saving)
  10635. * - Call heater manager
  10636. * - Call inactivity manager
  10637. * - Call endstop manager
  10638. * - Call LCD update
  10639. */
  10640. void loop() {
  10641. if (commands_in_queue < BUFSIZE) get_available_commands();
  10642. #if ENABLED(SDSUPPORT)
  10643. card.checkautostart(false);
  10644. #endif
  10645. if (commands_in_queue) {
  10646. #if ENABLED(SDSUPPORT)
  10647. if (card.saving) {
  10648. char* command = command_queue[cmd_queue_index_r];
  10649. if (strstr_P(command, PSTR("M29"))) {
  10650. // M29 closes the file
  10651. card.closefile();
  10652. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  10653. ok_to_send();
  10654. }
  10655. else {
  10656. // Write the string from the read buffer to SD
  10657. card.write_command(command);
  10658. if (card.logging)
  10659. process_next_command(); // The card is saving because it's logging
  10660. else
  10661. ok_to_send();
  10662. }
  10663. }
  10664. else
  10665. process_next_command();
  10666. #else
  10667. process_next_command();
  10668. #endif // SDSUPPORT
  10669. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  10670. if (commands_in_queue) {
  10671. --commands_in_queue;
  10672. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  10673. }
  10674. }
  10675. endstops.report_state();
  10676. idle();
  10677. }