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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * 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. * It has preliminary support for Matthew Roberts advance algorithm
  30. * - http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  31. */
  32. /**
  33. * -----------------
  34. * G-Codes in Marlin
  35. * -----------------
  36. *
  37. * Helpful G-code references:
  38. * - http://linuxcnc.org/handbook/gcode/g-code.html
  39. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  40. *
  41. * Help to document Marlin's G-codes online:
  42. * - http://reprap.org/wiki/G-code
  43. * - https://github.com/MarlinFirmware/MarlinDocumentation
  44. *
  45. * -----------------
  46. *
  47. * "G" Codes
  48. *
  49. * G0 -> G1
  50. * G1 - Coordinated Movement X Y Z E
  51. * G2 - CW ARC
  52. * G3 - CCW ARC
  53. * G4 - Dwell S<seconds> or P<milliseconds>
  54. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  55. * G10 - Retract filament according to settings of M207
  56. * G11 - Retract recover filament according to settings of M208
  57. * G12 - Clean tool
  58. * G20 - Set input units to inches
  59. * G21 - Set input units to millimeters
  60. * G28 - Home one or more axes
  61. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  62. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  63. * G31 - Dock sled (Z_PROBE_SLED only)
  64. * G32 - Undock sled (Z_PROBE_SLED only)
  65. * G38 - Probe target - similar to G28 except it uses the Z_MIN endstop for all three axes
  66. * G90 - Use Absolute Coordinates
  67. * G91 - Use Relative Coordinates
  68. * G92 - Set current position to coordinates given
  69. *
  70. * "M" Codes
  71. *
  72. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  73. * M1 - Same as M0
  74. * M17 - Enable/Power all stepper motors
  75. * M18 - Disable all stepper motors; same as M84
  76. * M20 - List SD card. (Requires SDSUPPORT)
  77. * M21 - Init SD card. (Requires SDSUPPORT)
  78. * M22 - Release SD card. (Requires SDSUPPORT)
  79. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  80. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  81. * M25 - Pause SD print. (Requires SDSUPPORT)
  82. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  83. * M27 - Report SD print status. (Requires SDSUPPORT)
  84. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  85. * M29 - Stop SD write. (Requires SDSUPPORT)
  86. * M30 - Delete file from SD: "M30 /path/file.gco"
  87. * M31 - Report time since last M109 or SD card start to serial.
  88. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  89. * Use P to run other files as sub-programs: "M32 P !filename#"
  90. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  91. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  92. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  93. * M43 - Monitor pins & report changes - report active pins
  94. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  95. * M75 - Start the print job timer.
  96. * M76 - Pause the print job timer.
  97. * M77 - Stop the print job timer.
  98. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  99. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY)
  100. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY)
  101. * M82 - Set E codes absolute (default).
  102. * M83 - Set E codes relative while in Absolute (G90) mode.
  103. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  104. * duration after which steppers should turn off. S0 disables the timeout.
  105. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  106. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  107. * M104 - Set extruder target temp.
  108. * M105 - Report current temperatures.
  109. * M106 - Fan on.
  110. * M107 - Fan off.
  111. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  112. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  113. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  114. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  115. * M110 - Set the current line number. (Used by host printing)
  116. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  117. * M112 - Emergency stop.
  118. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  119. * M114 - Report current position.
  120. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  121. * M117 - Display a message on the controller screen. (Requires an LCD)
  122. * M119 - Report endstops status.
  123. * M120 - Enable endstops detection.
  124. * M121 - Disable endstops detection.
  125. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  126. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  127. * M128 - EtoP Open. (Requires BARICUDA)
  128. * M129 - EtoP Closed. (Requires BARICUDA)
  129. * M140 - Set bed target temp. S<temp>
  130. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  131. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  132. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM or RGB_LED)
  133. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  134. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  135. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  136. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  137. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  138. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  139. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  140. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  141. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  142. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  143. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  144. * M205 - Set advanced settings. Current units apply:
  145. S<print> T<travel> minimum speeds
  146. B<minimum segment time>
  147. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  148. * M206 - Set additional homing offset.
  149. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  150. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  151. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  152. Every normal extrude-only move will be classified as retract depending on the direction.
  153. * M211 - Enable, Disable, and/or Report software endstops: S<0|1>
  154. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  155. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  156. * M221 - Set Flow Percentage: "M221 S<percent>"
  157. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  158. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  159. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  160. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  161. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  162. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  163. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  164. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  165. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  166. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  167. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  168. * M355 - Turn the Case Light on/off and set its brightness. (Requires CASE_LIGHT_PIN)
  169. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  170. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  171. * M400 - Finish all moves.
  172. * M401 - Lower Z probe. (Requires a probe)
  173. * M402 - Raise Z probe. (Requires a probe)
  174. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  175. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  176. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  177. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  178. * M410 - Quickstop. Abort all planned moves.
  179. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  180. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING)
  181. * M428 - Set the home_offset based on the current_position. Nearest edge applies.
  182. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  183. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  184. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  185. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  186. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  187. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires FILAMENT_CHANGE_FEATURE)
  188. * M665 - Set delta configurations: "M665 L<diagonal rod> R<delta radius> S<segments/s>" (Requires DELTA)
  189. * M666 - Set delta endstop adjustment. (Requires DELTA)
  190. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  191. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  192. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  193. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  194. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  195. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  196. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  197. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  198. *
  199. * ************ SCARA Specific - This can change to suit future G-code regulations
  200. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  201. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  202. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  203. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  204. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  205. * ************* SCARA End ***************
  206. *
  207. * ************ Custom codes - This can change to suit future G-code regulations
  208. * M100 - Watch Free Memory (For Debugging). (Requires M100_FREE_MEMORY_WATCHER)
  209. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  210. * M999 - Restart after being stopped by error
  211. *
  212. * "T" Codes
  213. *
  214. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  215. *
  216. */
  217. #include "Marlin.h"
  218. #include "ultralcd.h"
  219. #include "planner.h"
  220. #include "stepper.h"
  221. #include "endstops.h"
  222. #include "temperature.h"
  223. #include "cardreader.h"
  224. #include "configuration_store.h"
  225. #include "language.h"
  226. #include "pins_arduino.h"
  227. #include "math.h"
  228. #include "nozzle.h"
  229. #include "duration_t.h"
  230. #include "types.h"
  231. #if HAS_ABL
  232. #include "vector_3.h"
  233. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  234. #include "qr_solve.h"
  235. #endif
  236. #elif ENABLED(MESH_BED_LEVELING)
  237. #include "mesh_bed_leveling.h"
  238. #endif
  239. #if ENABLED(BEZIER_CURVE_SUPPORT)
  240. #include "planner_bezier.h"
  241. #endif
  242. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  243. #include "buzzer.h"
  244. #endif
  245. #if ENABLED(USE_WATCHDOG)
  246. #include "watchdog.h"
  247. #endif
  248. #if ENABLED(BLINKM)
  249. #include "blinkm.h"
  250. #include "Wire.h"
  251. #endif
  252. #if HAS_SERVOS
  253. #include "servo.h"
  254. #endif
  255. #if HAS_DIGIPOTSS
  256. #include <SPI.h>
  257. #endif
  258. #if ENABLED(DAC_STEPPER_CURRENT)
  259. #include "stepper_dac.h"
  260. #endif
  261. #if ENABLED(EXPERIMENTAL_I2CBUS)
  262. #include "twibus.h"
  263. #endif
  264. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  265. #include "endstop_interrupts.h"
  266. #endif
  267. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  268. void gcode_M100();
  269. #endif
  270. #if ENABLED(SDSUPPORT)
  271. CardReader card;
  272. #endif
  273. #if ENABLED(EXPERIMENTAL_I2CBUS)
  274. TWIBus i2c;
  275. #endif
  276. #if ENABLED(G38_PROBE_TARGET)
  277. bool G38_move = false,
  278. G38_endstop_hit = false;
  279. #endif
  280. bool Running = true;
  281. uint8_t marlin_debug_flags = DEBUG_NONE;
  282. /**
  283. * Cartesian Current Position
  284. * Used to track the logical position as moves are queued.
  285. * Used by 'line_to_current_position' to do a move after changing it.
  286. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  287. */
  288. float current_position[XYZE] = { 0.0 };
  289. /**
  290. * Cartesian Destination
  291. * A temporary position, usually applied to 'current_position'.
  292. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  293. * 'line_to_destination' sets 'current_position' to 'destination'.
  294. */
  295. static float destination[XYZE] = { 0.0 };
  296. /**
  297. * axis_homed
  298. * Flags that each linear axis was homed.
  299. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  300. *
  301. * axis_known_position
  302. * Flags that the position is known in each linear axis. Set when homed.
  303. * Cleared whenever a stepper powers off, potentially losing its position.
  304. */
  305. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  306. /**
  307. * GCode line number handling. Hosts may opt to include line numbers when
  308. * sending commands to Marlin, and lines will be checked for sequentiality.
  309. * M110 S<int> sets the current line number.
  310. */
  311. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  312. /**
  313. * GCode Command Queue
  314. * A simple ring buffer of BUFSIZE command strings.
  315. *
  316. * Commands are copied into this buffer by the command injectors
  317. * (immediate, serial, sd card) and they are processed sequentially by
  318. * the main loop. The process_next_command function parses the next
  319. * command and hands off execution to individual handler functions.
  320. */
  321. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  322. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  323. cmd_queue_index_w = 0, // Ring buffer write position
  324. commands_in_queue = 0; // Count of commands in the queue
  325. /**
  326. * Current GCode Command
  327. * When a GCode handler is running, these will be set
  328. */
  329. static char *current_command, // The command currently being executed
  330. *current_command_args, // The address where arguments begin
  331. *seen_pointer; // Set by code_seen(), used by the code_value functions
  332. /**
  333. * Next Injected Command pointer. NULL if no commands are being injected.
  334. * Used by Marlin internally to ensure that commands initiated from within
  335. * are enqueued ahead of any pending serial or sd card commands.
  336. */
  337. static const char *injected_commands_P = NULL;
  338. #if ENABLED(INCH_MODE_SUPPORT)
  339. float linear_unit_factor = 1.0, volumetric_unit_factor = 1.0;
  340. #endif
  341. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  342. TempUnit input_temp_units = TEMPUNIT_C;
  343. #endif
  344. /**
  345. * Feed rates are often configured with mm/m
  346. * but the planner and stepper like mm/s units.
  347. */
  348. float constexpr homing_feedrate_mm_s[] = {
  349. #if ENABLED(DELTA)
  350. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  351. #else
  352. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  353. #endif
  354. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  355. };
  356. static float feedrate_mm_s = MMM_TO_MMS(1500.0), saved_feedrate_mm_s;
  357. int feedrate_percentage = 100, saved_feedrate_percentage,
  358. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  359. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  360. volumetric_enabled = false;
  361. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  362. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  363. // The distance that XYZ has been offset by G92. Reset by G28.
  364. float position_shift[XYZ] = { 0 };
  365. // This offset is added to the configured home position.
  366. // Set by M206, M428, or menu item. Saved to EEPROM.
  367. float home_offset[XYZ] = { 0 };
  368. // Software Endstops are based on the configured limits.
  369. #if ENABLED(min_software_endstops) || ENABLED(max_software_endstops)
  370. bool soft_endstops_enabled = true;
  371. #endif
  372. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  373. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  374. #if FAN_COUNT > 0
  375. int fanSpeeds[FAN_COUNT] = { 0 };
  376. #endif
  377. // The active extruder (tool). Set with T<extruder> command.
  378. uint8_t active_extruder = 0;
  379. // Relative Mode. Enable with G91, disable with G90.
  380. static bool relative_mode = false;
  381. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  382. volatile bool wait_for_heatup = true;
  383. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  384. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  385. volatile bool wait_for_user = false;
  386. #endif
  387. const char errormagic[] PROGMEM = "Error:";
  388. const char echomagic[] PROGMEM = "echo:";
  389. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  390. // Number of characters read in the current line of serial input
  391. static int serial_count = 0;
  392. // Inactivity shutdown
  393. millis_t previous_cmd_ms = 0;
  394. static millis_t max_inactive_time = 0;
  395. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  396. // Print Job Timer
  397. #if ENABLED(PRINTCOUNTER)
  398. PrintCounter print_job_timer = PrintCounter();
  399. #else
  400. Stopwatch print_job_timer = Stopwatch();
  401. #endif
  402. // Buzzer - I2C on the LCD or a BEEPER_PIN
  403. #if ENABLED(LCD_USE_I2C_BUZZER)
  404. #define BUZZ(d,f) lcd_buzz(d, f)
  405. #elif PIN_EXISTS(BEEPER)
  406. Buzzer buzzer;
  407. #define BUZZ(d,f) buzzer.tone(d, f)
  408. #else
  409. #define BUZZ(d,f) NOOP
  410. #endif
  411. static uint8_t target_extruder;
  412. #if HAS_BED_PROBE
  413. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  414. #endif
  415. #define PLANNER_XY_FEEDRATE() (min(planner.max_feedrate_mm_s[X_AXIS], planner.max_feedrate_mm_s[Y_AXIS]))
  416. #if HAS_ABL
  417. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  418. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  419. #elif defined(XY_PROBE_SPEED)
  420. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  421. #else
  422. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  423. #endif
  424. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  425. #if ENABLED(DELTA)
  426. #define ADJUST_DELTA(V) \
  427. if (planner.abl_enabled) { \
  428. const float zadj = bilinear_z_offset(V); \
  429. delta[A_AXIS] += zadj; \
  430. delta[B_AXIS] += zadj; \
  431. delta[C_AXIS] += zadj; \
  432. }
  433. #else
  434. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  435. #endif
  436. #elif IS_KINEMATIC
  437. #define ADJUST_DELTA(V) NOOP
  438. #endif
  439. #if ENABLED(Z_DUAL_ENDSTOPS)
  440. float z_endstop_adj = 0;
  441. #endif
  442. // Extruder offsets
  443. #if HOTENDS > 1
  444. float hotend_offset[XYZ][HOTENDS];
  445. #endif
  446. #if HAS_Z_SERVO_ENDSTOP
  447. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  448. #endif
  449. #if ENABLED(BARICUDA)
  450. int baricuda_valve_pressure = 0;
  451. int baricuda_e_to_p_pressure = 0;
  452. #endif
  453. #if ENABLED(FWRETRACT)
  454. bool autoretract_enabled = false;
  455. bool retracted[EXTRUDERS] = { false };
  456. bool retracted_swap[EXTRUDERS] = { false };
  457. float retract_length = RETRACT_LENGTH;
  458. float retract_length_swap = RETRACT_LENGTH_SWAP;
  459. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  460. float retract_zlift = RETRACT_ZLIFT;
  461. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  462. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  463. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  464. #endif // FWRETRACT
  465. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  466. bool powersupply =
  467. #if ENABLED(PS_DEFAULT_OFF)
  468. false
  469. #else
  470. true
  471. #endif
  472. ;
  473. #endif
  474. #if ENABLED(ULTIPANEL) && HAS_CASE_LIGHT
  475. bool case_light_on =
  476. #if ENABLED(CASE_LIGHT_DEFAULT_ON)
  477. true
  478. #else
  479. false
  480. #endif
  481. ;
  482. #endif
  483. #if ENABLED(DELTA)
  484. #define SIN_60 0.8660254037844386
  485. #define COS_60 0.5
  486. float delta[ABC],
  487. endstop_adj[ABC] = { 0 };
  488. // these are the default values, can be overriden with M665
  489. float delta_radius = DELTA_RADIUS,
  490. delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1), // front left tower
  491. delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1),
  492. delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2), // front right tower
  493. delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2),
  494. delta_tower3_x = 0, // back middle tower
  495. delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3),
  496. delta_diagonal_rod = DELTA_DIAGONAL_ROD,
  497. delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1,
  498. delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2,
  499. delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3,
  500. delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1),
  501. delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2),
  502. delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3),
  503. delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND,
  504. delta_clip_start_height = Z_MAX_POS;
  505. float delta_safe_distance_from_top();
  506. #else
  507. static bool home_all_axis = true;
  508. #endif
  509. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  510. int bilinear_grid_spacing[2] = { 0 }, bilinear_start[2] = { 0 };
  511. float bed_level_grid[ABL_GRID_POINTS_X][ABL_GRID_POINTS_Y];
  512. #endif
  513. #if IS_SCARA
  514. // Float constants for SCARA calculations
  515. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  516. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  517. L2_2 = sq(float(L2));
  518. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  519. delta[ABC];
  520. #endif
  521. float cartes[XYZ] = { 0 };
  522. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  523. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  524. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404
  525. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  526. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  527. int filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  528. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  529. #endif
  530. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  531. static bool filament_ran_out = false;
  532. #endif
  533. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  534. FilamentChangeMenuResponse filament_change_menu_response;
  535. #endif
  536. #if ENABLED(MIXING_EXTRUDER)
  537. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  538. #if MIXING_VIRTUAL_TOOLS > 1
  539. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  540. #endif
  541. #endif
  542. static bool send_ok[BUFSIZE];
  543. #if HAS_SERVOS
  544. Servo servo[NUM_SERVOS];
  545. #define MOVE_SERVO(I, P) servo[I].move(P)
  546. #if HAS_Z_SERVO_ENDSTOP
  547. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  548. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  549. #endif
  550. #endif
  551. #ifdef CHDK
  552. millis_t chdkHigh = 0;
  553. boolean chdkActive = false;
  554. #endif
  555. #if ENABLED(PID_EXTRUSION_SCALING)
  556. int lpq_len = 20;
  557. #endif
  558. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  559. static MarlinBusyState busy_state = NOT_BUSY;
  560. static millis_t next_busy_signal_ms = 0;
  561. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  562. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  563. #else
  564. #define host_keepalive() ;
  565. #define KEEPALIVE_STATE(n) ;
  566. #endif // HOST_KEEPALIVE_FEATURE
  567. #define DEFINE_PGM_READ_ANY(type, reader) \
  568. static inline type pgm_read_any(const type *p) \
  569. { return pgm_read_##reader##_near(p); }
  570. DEFINE_PGM_READ_ANY(float, float)
  571. DEFINE_PGM_READ_ANY(signed char, byte)
  572. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  573. static const PROGMEM type array##_P[XYZ] = \
  574. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  575. static inline type array(int axis) \
  576. { return pgm_read_any(&array##_P[axis]); }
  577. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS)
  578. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS)
  579. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS)
  580. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH)
  581. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM)
  582. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR)
  583. /**
  584. * ***************************************************************************
  585. * ******************************** FUNCTIONS ********************************
  586. * ***************************************************************************
  587. */
  588. void stop();
  589. void get_available_commands();
  590. void process_next_command();
  591. void prepare_move_to_destination();
  592. void get_cartesian_from_steppers();
  593. void set_current_from_steppers_for_axis(const AxisEnum axis);
  594. #if ENABLED(ARC_SUPPORT)
  595. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  596. #endif
  597. #if ENABLED(BEZIER_CURVE_SUPPORT)
  598. void plan_cubic_move(const float offset[4]);
  599. #endif
  600. void serial_echopair_P(const char* s_P, const char *v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  601. void serial_echopair_P(const char* s_P, char v) { serialprintPGM(s_P); SERIAL_CHAR(v); }
  602. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  603. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  604. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  605. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  606. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  607. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  608. static void report_current_position();
  609. #if ENABLED(DEBUG_LEVELING_FEATURE)
  610. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  611. serialprintPGM(prefix);
  612. SERIAL_ECHOPAIR("(", x);
  613. SERIAL_ECHOPAIR(", ", y);
  614. SERIAL_ECHOPAIR(", ", z);
  615. SERIAL_ECHOPGM(")");
  616. if (suffix) serialprintPGM(suffix);
  617. else SERIAL_EOL;
  618. }
  619. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  620. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  621. }
  622. #if HAS_ABL
  623. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  624. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  625. }
  626. #endif
  627. #define DEBUG_POS(SUFFIX,VAR) do { \
  628. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  629. #endif
  630. /**
  631. * sync_plan_position
  632. *
  633. * Set the planner/stepper positions directly from current_position with
  634. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  635. */
  636. inline void sync_plan_position() {
  637. #if ENABLED(DEBUG_LEVELING_FEATURE)
  638. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  639. #endif
  640. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  641. }
  642. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  643. #if IS_KINEMATIC
  644. inline void sync_plan_position_kinematic() {
  645. #if ENABLED(DEBUG_LEVELING_FEATURE)
  646. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  647. #endif
  648. planner.set_position_mm_kinematic(current_position);
  649. }
  650. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  651. #else
  652. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  653. #endif
  654. #if ENABLED(SDSUPPORT)
  655. #include "SdFatUtil.h"
  656. int freeMemory() { return SdFatUtil::FreeRam(); }
  657. #else
  658. extern "C" {
  659. extern unsigned int __bss_end;
  660. extern unsigned int __heap_start;
  661. extern void* __brkval;
  662. int freeMemory() {
  663. int free_memory;
  664. if ((int)__brkval == 0)
  665. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  666. else
  667. free_memory = ((int)&free_memory) - ((int)__brkval);
  668. return free_memory;
  669. }
  670. }
  671. #endif //!SDSUPPORT
  672. #if ENABLED(DIGIPOT_I2C)
  673. extern void digipot_i2c_set_current(int channel, float current);
  674. extern void digipot_i2c_init();
  675. #endif
  676. /**
  677. * Inject the next "immediate" command, when possible.
  678. * Return true if any immediate commands remain to inject.
  679. */
  680. static bool drain_injected_commands_P() {
  681. if (injected_commands_P != NULL) {
  682. size_t i = 0;
  683. char c, cmd[30];
  684. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  685. cmd[sizeof(cmd) - 1] = '\0';
  686. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  687. cmd[i] = '\0';
  688. if (enqueue_and_echo_command(cmd)) { // success?
  689. if (c) // newline char?
  690. injected_commands_P += i + 1; // advance to the next command
  691. else
  692. injected_commands_P = NULL; // nul char? no more commands
  693. }
  694. }
  695. return (injected_commands_P != NULL); // return whether any more remain
  696. }
  697. /**
  698. * Record one or many commands to run from program memory.
  699. * Aborts the current queue, if any.
  700. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  701. */
  702. void enqueue_and_echo_commands_P(const char* pgcode) {
  703. injected_commands_P = pgcode;
  704. drain_injected_commands_P(); // first command executed asap (when possible)
  705. }
  706. void clear_command_queue() {
  707. cmd_queue_index_r = cmd_queue_index_w;
  708. commands_in_queue = 0;
  709. }
  710. /**
  711. * Once a new command is in the ring buffer, call this to commit it
  712. */
  713. inline void _commit_command(bool say_ok) {
  714. send_ok[cmd_queue_index_w] = say_ok;
  715. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  716. commands_in_queue++;
  717. }
  718. /**
  719. * Copy a command directly into the main command buffer, from RAM.
  720. * Returns true if successfully adds the command
  721. */
  722. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  723. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  724. strcpy(command_queue[cmd_queue_index_w], cmd);
  725. _commit_command(say_ok);
  726. return true;
  727. }
  728. void enqueue_and_echo_command_now(const char* cmd) {
  729. while (!enqueue_and_echo_command(cmd)) idle();
  730. }
  731. /**
  732. * Enqueue with Serial Echo
  733. */
  734. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  735. if (_enqueuecommand(cmd, say_ok)) {
  736. SERIAL_ECHO_START;
  737. SERIAL_ECHOPAIR(MSG_Enqueueing, cmd);
  738. SERIAL_CHAR('"');
  739. SERIAL_EOL;
  740. return true;
  741. }
  742. return false;
  743. }
  744. void setup_killpin() {
  745. #if HAS_KILL
  746. SET_INPUT(KILL_PIN);
  747. WRITE(KILL_PIN, HIGH);
  748. #endif
  749. }
  750. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  751. void setup_filrunoutpin() {
  752. SET_INPUT(FIL_RUNOUT_PIN);
  753. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  754. WRITE(FIL_RUNOUT_PIN, HIGH);
  755. #endif
  756. }
  757. #endif
  758. // Set home pin
  759. void setup_homepin(void) {
  760. #if HAS_HOME
  761. SET_INPUT(HOME_PIN);
  762. WRITE(HOME_PIN, HIGH);
  763. #endif
  764. }
  765. void setup_powerhold() {
  766. #if HAS_SUICIDE
  767. OUT_WRITE(SUICIDE_PIN, HIGH);
  768. #endif
  769. #if HAS_POWER_SWITCH
  770. #if ENABLED(PS_DEFAULT_OFF)
  771. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  772. #else
  773. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  774. #endif
  775. #endif
  776. }
  777. void suicide() {
  778. #if HAS_SUICIDE
  779. OUT_WRITE(SUICIDE_PIN, LOW);
  780. #endif
  781. }
  782. void servo_init() {
  783. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  784. servo[0].attach(SERVO0_PIN);
  785. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  786. #endif
  787. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  788. servo[1].attach(SERVO1_PIN);
  789. servo[1].detach();
  790. #endif
  791. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  792. servo[2].attach(SERVO2_PIN);
  793. servo[2].detach();
  794. #endif
  795. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  796. servo[3].attach(SERVO3_PIN);
  797. servo[3].detach();
  798. #endif
  799. #if HAS_Z_SERVO_ENDSTOP
  800. /**
  801. * Set position of Z Servo Endstop
  802. *
  803. * The servo might be deployed and positioned too low to stow
  804. * when starting up the machine or rebooting the board.
  805. * There's no way to know where the nozzle is positioned until
  806. * homing has been done - no homing with z-probe without init!
  807. *
  808. */
  809. STOW_Z_SERVO();
  810. #endif
  811. }
  812. /**
  813. * Stepper Reset (RigidBoard, et.al.)
  814. */
  815. #if HAS_STEPPER_RESET
  816. void disableStepperDrivers() {
  817. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  818. }
  819. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  820. #endif
  821. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  822. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  823. i2c.receive(bytes);
  824. }
  825. void i2c_on_request() { // just send dummy data for now
  826. i2c.reply("Hello World!\n");
  827. }
  828. #endif
  829. void gcode_line_error(const char* err, bool doFlush = true) {
  830. SERIAL_ERROR_START;
  831. serialprintPGM(err);
  832. SERIAL_ERRORLN(gcode_LastN);
  833. //Serial.println(gcode_N);
  834. if (doFlush) FlushSerialRequestResend();
  835. serial_count = 0;
  836. }
  837. inline void get_serial_commands() {
  838. static char serial_line_buffer[MAX_CMD_SIZE];
  839. static boolean serial_comment_mode = false;
  840. // If the command buffer is empty for too long,
  841. // send "wait" to indicate Marlin is still waiting.
  842. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  843. static millis_t last_command_time = 0;
  844. millis_t ms = millis();
  845. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  846. SERIAL_ECHOLNPGM(MSG_WAIT);
  847. last_command_time = ms;
  848. }
  849. #endif
  850. /**
  851. * Loop while serial characters are incoming and the queue is not full
  852. */
  853. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  854. char serial_char = MYSERIAL.read();
  855. /**
  856. * If the character ends the line
  857. */
  858. if (serial_char == '\n' || serial_char == '\r') {
  859. serial_comment_mode = false; // end of line == end of comment
  860. if (!serial_count) continue; // skip empty lines
  861. serial_line_buffer[serial_count] = 0; // terminate string
  862. serial_count = 0; //reset buffer
  863. char* command = serial_line_buffer;
  864. while (*command == ' ') command++; // skip any leading spaces
  865. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  866. char* apos = strchr(command, '*');
  867. if (npos) {
  868. boolean M110 = strstr_P(command, PSTR("M110")) != NULL;
  869. if (M110) {
  870. char* n2pos = strchr(command + 4, 'N');
  871. if (n2pos) npos = n2pos;
  872. }
  873. gcode_N = strtol(npos + 1, NULL, 10);
  874. if (gcode_N != gcode_LastN + 1 && !M110) {
  875. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  876. return;
  877. }
  878. if (apos) {
  879. byte checksum = 0, count = 0;
  880. while (command[count] != '*') checksum ^= command[count++];
  881. if (strtol(apos + 1, NULL, 10) != checksum) {
  882. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  883. return;
  884. }
  885. // if no errors, continue parsing
  886. }
  887. else {
  888. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  889. return;
  890. }
  891. gcode_LastN = gcode_N;
  892. // if no errors, continue parsing
  893. }
  894. else if (apos) { // No '*' without 'N'
  895. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  896. return;
  897. }
  898. // Movement commands alert when stopped
  899. if (IsStopped()) {
  900. char* gpos = strchr(command, 'G');
  901. if (gpos) {
  902. int codenum = strtol(gpos + 1, NULL, 10);
  903. switch (codenum) {
  904. case 0:
  905. case 1:
  906. case 2:
  907. case 3:
  908. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  909. LCD_MESSAGEPGM(MSG_STOPPED);
  910. break;
  911. }
  912. }
  913. }
  914. #if DISABLED(EMERGENCY_PARSER)
  915. // If command was e-stop process now
  916. if (strcmp(command, "M108") == 0) {
  917. wait_for_heatup = false;
  918. #if ENABLED(ULTIPANEL)
  919. wait_for_user = false;
  920. #endif
  921. }
  922. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  923. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  924. #endif
  925. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  926. last_command_time = ms;
  927. #endif
  928. // Add the command to the queue
  929. _enqueuecommand(serial_line_buffer, true);
  930. }
  931. else if (serial_count >= MAX_CMD_SIZE - 1) {
  932. // Keep fetching, but ignore normal characters beyond the max length
  933. // The command will be injected when EOL is reached
  934. }
  935. else if (serial_char == '\\') { // Handle escapes
  936. if (MYSERIAL.available() > 0) {
  937. // if we have one more character, copy it over
  938. serial_char = MYSERIAL.read();
  939. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  940. }
  941. // otherwise do nothing
  942. }
  943. else { // it's not a newline, carriage return or escape char
  944. if (serial_char == ';') serial_comment_mode = true;
  945. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  946. }
  947. } // queue has space, serial has data
  948. }
  949. #if ENABLED(SDSUPPORT)
  950. inline void get_sdcard_commands() {
  951. static bool stop_buffering = false,
  952. sd_comment_mode = false;
  953. if (!card.sdprinting) return;
  954. /**
  955. * '#' stops reading from SD to the buffer prematurely, so procedural
  956. * macro calls are possible. If it occurs, stop_buffering is triggered
  957. * and the buffer is run dry; this character _can_ occur in serial com
  958. * due to checksums, however, no checksums are used in SD printing.
  959. */
  960. if (commands_in_queue == 0) stop_buffering = false;
  961. uint16_t sd_count = 0;
  962. bool card_eof = card.eof();
  963. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  964. int16_t n = card.get();
  965. char sd_char = (char)n;
  966. card_eof = card.eof();
  967. if (card_eof || n == -1
  968. || sd_char == '\n' || sd_char == '\r'
  969. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  970. ) {
  971. if (card_eof) {
  972. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  973. card.printingHasFinished();
  974. card.checkautostart(true);
  975. }
  976. else if (n == -1) {
  977. SERIAL_ERROR_START;
  978. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  979. }
  980. if (sd_char == '#') stop_buffering = true;
  981. sd_comment_mode = false; //for new command
  982. if (!sd_count) continue; //skip empty lines
  983. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  984. sd_count = 0; //clear buffer
  985. _commit_command(false);
  986. }
  987. else if (sd_count >= MAX_CMD_SIZE - 1) {
  988. /**
  989. * Keep fetching, but ignore normal characters beyond the max length
  990. * The command will be injected when EOL is reached
  991. */
  992. }
  993. else {
  994. if (sd_char == ';') sd_comment_mode = true;
  995. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  996. }
  997. }
  998. }
  999. #endif // SDSUPPORT
  1000. /**
  1001. * Add to the circular command queue the next command from:
  1002. * - The command-injection queue (injected_commands_P)
  1003. * - The active serial input (usually USB)
  1004. * - The SD card file being actively printed
  1005. */
  1006. void get_available_commands() {
  1007. // if any immediate commands remain, don't get other commands yet
  1008. if (drain_injected_commands_P()) return;
  1009. get_serial_commands();
  1010. #if ENABLED(SDSUPPORT)
  1011. get_sdcard_commands();
  1012. #endif
  1013. }
  1014. inline bool code_has_value() {
  1015. int i = 1;
  1016. char c = seen_pointer[i];
  1017. while (c == ' ') c = seen_pointer[++i];
  1018. if (c == '-' || c == '+') c = seen_pointer[++i];
  1019. if (c == '.') c = seen_pointer[++i];
  1020. return NUMERIC(c);
  1021. }
  1022. inline float code_value_float() {
  1023. float ret;
  1024. char* e = strchr(seen_pointer, 'E');
  1025. if (e) {
  1026. *e = 0;
  1027. ret = strtod(seen_pointer + 1, NULL);
  1028. *e = 'E';
  1029. }
  1030. else
  1031. ret = strtod(seen_pointer + 1, NULL);
  1032. return ret;
  1033. }
  1034. inline unsigned long code_value_ulong() { return strtoul(seen_pointer + 1, NULL, 10); }
  1035. inline long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  1036. inline int code_value_int() { return (int)strtol(seen_pointer + 1, NULL, 10); }
  1037. inline uint16_t code_value_ushort() { return (uint16_t)strtoul(seen_pointer + 1, NULL, 10); }
  1038. inline uint8_t code_value_byte() { return (uint8_t)(constrain(strtol(seen_pointer + 1, NULL, 10), 0, 255)); }
  1039. inline bool code_value_bool() { return !code_has_value() || code_value_byte() > 0; }
  1040. #if ENABLED(INCH_MODE_SUPPORT)
  1041. inline void set_input_linear_units(LinearUnit units) {
  1042. switch (units) {
  1043. case LINEARUNIT_INCH:
  1044. linear_unit_factor = 25.4;
  1045. break;
  1046. case LINEARUNIT_MM:
  1047. default:
  1048. linear_unit_factor = 1.0;
  1049. break;
  1050. }
  1051. volumetric_unit_factor = pow(linear_unit_factor, 3.0);
  1052. }
  1053. inline float axis_unit_factor(int axis) {
  1054. return (axis >= E_AXIS && volumetric_enabled ? volumetric_unit_factor : linear_unit_factor);
  1055. }
  1056. inline float code_value_linear_units() { return code_value_float() * linear_unit_factor; }
  1057. inline float code_value_axis_units(int axis) { return code_value_float() * axis_unit_factor(axis); }
  1058. inline float code_value_per_axis_unit(int axis) { return code_value_float() / axis_unit_factor(axis); }
  1059. #else
  1060. inline float code_value_linear_units() { return code_value_float(); }
  1061. inline float code_value_axis_units(int axis) { UNUSED(axis); return code_value_float(); }
  1062. inline float code_value_per_axis_unit(int axis) { UNUSED(axis); return code_value_float(); }
  1063. #endif
  1064. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  1065. inline void set_input_temp_units(TempUnit units) { input_temp_units = units; }
  1066. float code_value_temp_abs() {
  1067. switch (input_temp_units) {
  1068. case TEMPUNIT_C:
  1069. return code_value_float();
  1070. case TEMPUNIT_F:
  1071. return (code_value_float() - 32) * 0.5555555556;
  1072. case TEMPUNIT_K:
  1073. return code_value_float() - 272.15;
  1074. default:
  1075. return code_value_float();
  1076. }
  1077. }
  1078. float code_value_temp_diff() {
  1079. switch (input_temp_units) {
  1080. case TEMPUNIT_C:
  1081. case TEMPUNIT_K:
  1082. return code_value_float();
  1083. case TEMPUNIT_F:
  1084. return code_value_float() * 0.5555555556;
  1085. default:
  1086. return code_value_float();
  1087. }
  1088. }
  1089. #else
  1090. float code_value_temp_abs() { return code_value_float(); }
  1091. float code_value_temp_diff() { return code_value_float(); }
  1092. #endif
  1093. FORCE_INLINE millis_t code_value_millis() { return code_value_ulong(); }
  1094. inline millis_t code_value_millis_from_seconds() { return code_value_float() * 1000; }
  1095. bool code_seen(char code) {
  1096. seen_pointer = strchr(current_command_args, code);
  1097. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  1098. }
  1099. /**
  1100. * Set target_extruder from the T parameter or the active_extruder
  1101. *
  1102. * Returns TRUE if the target is invalid
  1103. */
  1104. bool get_target_extruder_from_command(int code) {
  1105. if (code_seen('T')) {
  1106. if (code_value_byte() >= EXTRUDERS) {
  1107. SERIAL_ECHO_START;
  1108. SERIAL_CHAR('M');
  1109. SERIAL_ECHO(code);
  1110. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", code_value_byte());
  1111. return true;
  1112. }
  1113. target_extruder = code_value_byte();
  1114. }
  1115. else
  1116. target_extruder = active_extruder;
  1117. return false;
  1118. }
  1119. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1120. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1121. #endif
  1122. #if ENABLED(DUAL_X_CARRIAGE)
  1123. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1124. static float x_home_pos(const int extruder) {
  1125. if (extruder == 0)
  1126. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1127. else
  1128. /**
  1129. * In dual carriage mode the extruder offset provides an override of the
  1130. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1131. * This allows soft recalibration of the second extruder home position
  1132. * without firmware reflash (through the M218 command).
  1133. */
  1134. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1135. }
  1136. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1137. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1138. static bool active_extruder_parked = false; // used in mode 1 & 2
  1139. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  1140. static millis_t delayed_move_time = 0; // used in mode 1
  1141. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1142. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  1143. #endif // DUAL_X_CARRIAGE
  1144. /**
  1145. * Software endstops can be used to monitor the open end of
  1146. * an axis that has a hardware endstop on the other end. Or
  1147. * they can prevent axes from moving past endstops and grinding.
  1148. *
  1149. * To keep doing their job as the coordinate system changes,
  1150. * the software endstop positions must be refreshed to remain
  1151. * at the same positions relative to the machine.
  1152. */
  1153. void update_software_endstops(AxisEnum axis) {
  1154. float offs = LOGICAL_POSITION(0, axis);
  1155. #if ENABLED(DUAL_X_CARRIAGE)
  1156. if (axis == X_AXIS) {
  1157. // In Dual X mode hotend_offset[X] is T1's home position
  1158. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1159. if (active_extruder != 0) {
  1160. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1161. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1162. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1163. }
  1164. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1165. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1166. // but not so far to the right that T1 would move past the end
  1167. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1168. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1169. }
  1170. else {
  1171. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1172. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1173. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1174. }
  1175. }
  1176. #else
  1177. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1178. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1179. #endif
  1180. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1181. if (DEBUGGING(LEVELING)) {
  1182. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1183. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1184. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1185. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1186. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1187. }
  1188. #endif
  1189. #if ENABLED(DELTA)
  1190. if (axis == Z_AXIS)
  1191. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1192. #endif
  1193. }
  1194. /**
  1195. * Change the home offset for an axis, update the current
  1196. * position and the software endstops to retain the same
  1197. * relative distance to the new home.
  1198. *
  1199. * Since this changes the current_position, code should
  1200. * call sync_plan_position soon after this.
  1201. */
  1202. static void set_home_offset(AxisEnum axis, float v) {
  1203. current_position[axis] += v - home_offset[axis];
  1204. home_offset[axis] = v;
  1205. update_software_endstops(axis);
  1206. }
  1207. /**
  1208. * Set an axis' current position to its home position (after homing).
  1209. *
  1210. * For Core and Cartesian robots this applies one-to-one when an
  1211. * individual axis has been homed.
  1212. *
  1213. * DELTA should wait until all homing is done before setting the XYZ
  1214. * current_position to home, because homing is a single operation.
  1215. * In the case where the axis positions are already known and previously
  1216. * homed, DELTA could home to X or Y individually by moving either one
  1217. * to the center. However, homing Z always homes XY and Z.
  1218. *
  1219. * SCARA should wait until all XY homing is done before setting the XY
  1220. * current_position to home, because neither X nor Y is at home until
  1221. * both are at home. Z can however be homed individually.
  1222. *
  1223. * Callers must sync the planner position after calling this!
  1224. */
  1225. static void set_axis_is_at_home(AxisEnum axis) {
  1226. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1227. if (DEBUGGING(LEVELING)) {
  1228. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1229. SERIAL_CHAR(')');
  1230. SERIAL_EOL;
  1231. }
  1232. #endif
  1233. axis_known_position[axis] = axis_homed[axis] = true;
  1234. position_shift[axis] = 0;
  1235. update_software_endstops(axis);
  1236. #if ENABLED(DUAL_X_CARRIAGE)
  1237. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1238. current_position[X_AXIS] = x_home_pos(active_extruder);
  1239. return;
  1240. }
  1241. #endif
  1242. #if ENABLED(MORGAN_SCARA)
  1243. /**
  1244. * Morgan SCARA homes XY at the same time
  1245. */
  1246. if (axis == X_AXIS || axis == Y_AXIS) {
  1247. float homeposition[XYZ];
  1248. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1249. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1250. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1251. /**
  1252. * Get Home position SCARA arm angles using inverse kinematics,
  1253. * and calculate homing offset using forward kinematics
  1254. */
  1255. inverse_kinematics(homeposition);
  1256. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1257. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1258. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1259. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1260. /**
  1261. * SCARA home positions are based on configuration since the actual
  1262. * limits are determined by the inverse kinematic transform.
  1263. */
  1264. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1265. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1266. }
  1267. else
  1268. #endif
  1269. {
  1270. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1271. }
  1272. /**
  1273. * Z Probe Z Homing? Account for the probe's Z offset.
  1274. */
  1275. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1276. if (axis == Z_AXIS) {
  1277. #if HOMING_Z_WITH_PROBE
  1278. current_position[Z_AXIS] -= zprobe_zoffset;
  1279. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1280. if (DEBUGGING(LEVELING)) {
  1281. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1282. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1283. }
  1284. #endif
  1285. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1286. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1287. #endif
  1288. }
  1289. #endif
  1290. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1291. if (DEBUGGING(LEVELING)) {
  1292. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1293. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1294. DEBUG_POS("", current_position);
  1295. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1296. SERIAL_CHAR(')');
  1297. SERIAL_EOL;
  1298. }
  1299. #endif
  1300. }
  1301. /**
  1302. * Some planner shorthand inline functions
  1303. */
  1304. inline float get_homing_bump_feedrate(AxisEnum axis) {
  1305. int constexpr homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1306. int hbd = homing_bump_divisor[axis];
  1307. if (hbd < 1) {
  1308. hbd = 10;
  1309. SERIAL_ECHO_START;
  1310. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1311. }
  1312. return homing_feedrate_mm_s[axis] / hbd;
  1313. }
  1314. //
  1315. // line_to_current_position
  1316. // Move the planner to the current position from wherever it last moved
  1317. // (or from wherever it has been told it is located).
  1318. //
  1319. inline void line_to_current_position() {
  1320. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1321. }
  1322. //
  1323. // line_to_destination
  1324. // Move the planner, not necessarily synced with current_position
  1325. //
  1326. inline void line_to_destination(float fr_mm_s) {
  1327. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1328. }
  1329. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1330. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1331. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1332. #if IS_KINEMATIC
  1333. /**
  1334. * Calculate delta, start a line, and set current_position to destination
  1335. */
  1336. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1337. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1338. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1339. #endif
  1340. if ( current_position[X_AXIS] == destination[X_AXIS]
  1341. && current_position[Y_AXIS] == destination[Y_AXIS]
  1342. && current_position[Z_AXIS] == destination[Z_AXIS]
  1343. && current_position[E_AXIS] == destination[E_AXIS]
  1344. ) return;
  1345. refresh_cmd_timeout();
  1346. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1347. set_current_to_destination();
  1348. }
  1349. #endif // IS_KINEMATIC
  1350. /**
  1351. * Plan a move to (X, Y, Z) and set the current_position
  1352. * The final current_position may not be the one that was requested
  1353. */
  1354. void do_blocking_move_to(const float &x, const float &y, const float &z, const float &fr_mm_s /*=0.0*/) {
  1355. float old_feedrate_mm_s = feedrate_mm_s;
  1356. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1357. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, x, y, z);
  1358. #endif
  1359. #if ENABLED(DELTA)
  1360. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1361. set_destination_to_current(); // sync destination at the start
  1362. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1363. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1364. #endif
  1365. // when in the danger zone
  1366. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1367. if (z > delta_clip_start_height) { // staying in the danger zone
  1368. destination[X_AXIS] = x; // move directly (uninterpolated)
  1369. destination[Y_AXIS] = y;
  1370. destination[Z_AXIS] = z;
  1371. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1372. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1373. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1374. #endif
  1375. return;
  1376. }
  1377. else {
  1378. destination[Z_AXIS] = delta_clip_start_height;
  1379. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1380. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1381. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1382. #endif
  1383. }
  1384. }
  1385. if (z > current_position[Z_AXIS]) { // raising?
  1386. destination[Z_AXIS] = z;
  1387. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1388. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1389. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1390. #endif
  1391. }
  1392. destination[X_AXIS] = x;
  1393. destination[Y_AXIS] = y;
  1394. prepare_move_to_destination(); // set_current_to_destination
  1395. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1396. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1397. #endif
  1398. if (z < current_position[Z_AXIS]) { // lowering?
  1399. destination[Z_AXIS] = z;
  1400. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1401. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1402. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1403. #endif
  1404. }
  1405. #elif IS_SCARA
  1406. set_destination_to_current();
  1407. // If Z needs to raise, do it before moving XY
  1408. if (destination[Z_AXIS] < z) {
  1409. destination[Z_AXIS] = z;
  1410. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1411. }
  1412. destination[X_AXIS] = x;
  1413. destination[Y_AXIS] = y;
  1414. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1415. // If Z needs to lower, do it after moving XY
  1416. if (destination[Z_AXIS] > z) {
  1417. destination[Z_AXIS] = z;
  1418. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1419. }
  1420. #else
  1421. // If Z needs to raise, do it before moving XY
  1422. if (current_position[Z_AXIS] < z) {
  1423. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1424. current_position[Z_AXIS] = z;
  1425. line_to_current_position();
  1426. }
  1427. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1428. current_position[X_AXIS] = x;
  1429. current_position[Y_AXIS] = y;
  1430. line_to_current_position();
  1431. // If Z needs to lower, do it after moving XY
  1432. if (current_position[Z_AXIS] > z) {
  1433. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1434. current_position[Z_AXIS] = z;
  1435. line_to_current_position();
  1436. }
  1437. #endif
  1438. stepper.synchronize();
  1439. feedrate_mm_s = old_feedrate_mm_s;
  1440. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1441. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1442. #endif
  1443. }
  1444. void do_blocking_move_to_x(const float &x, const float &fr_mm_s/*=0.0*/) {
  1445. do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1446. }
  1447. void do_blocking_move_to_z(const float &z, const float &fr_mm_s/*=0.0*/) {
  1448. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, fr_mm_s);
  1449. }
  1450. void do_blocking_move_to_xy(const float &x, const float &y, const float &fr_mm_s/*=0.0*/) {
  1451. do_blocking_move_to(x, y, current_position[Z_AXIS], fr_mm_s);
  1452. }
  1453. //
  1454. // Prepare to do endstop or probe moves
  1455. // with custom feedrates.
  1456. //
  1457. // - Save current feedrates
  1458. // - Reset the rate multiplier
  1459. // - Reset the command timeout
  1460. // - Enable the endstops (for endstop moves)
  1461. //
  1462. static void setup_for_endstop_or_probe_move() {
  1463. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1464. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1465. #endif
  1466. saved_feedrate_mm_s = feedrate_mm_s;
  1467. saved_feedrate_percentage = feedrate_percentage;
  1468. feedrate_percentage = 100;
  1469. refresh_cmd_timeout();
  1470. }
  1471. static void clean_up_after_endstop_or_probe_move() {
  1472. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1473. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1474. #endif
  1475. feedrate_mm_s = saved_feedrate_mm_s;
  1476. feedrate_percentage = saved_feedrate_percentage;
  1477. refresh_cmd_timeout();
  1478. }
  1479. #if HAS_BED_PROBE
  1480. /**
  1481. * Raise Z to a minimum height to make room for a probe to move
  1482. */
  1483. inline void do_probe_raise(float z_raise) {
  1484. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1485. if (DEBUGGING(LEVELING)) {
  1486. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1487. SERIAL_CHAR(')');
  1488. SERIAL_EOL;
  1489. }
  1490. #endif
  1491. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1492. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1493. if (z_dest > current_position[Z_AXIS])
  1494. do_blocking_move_to_z(z_dest);
  1495. }
  1496. #endif //HAS_BED_PROBE
  1497. #if ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE)
  1498. static bool axis_unhomed_error(const bool x, const bool y, const bool z) {
  1499. const bool xx = x && !axis_homed[X_AXIS],
  1500. yy = y && !axis_homed[Y_AXIS],
  1501. zz = z && !axis_homed[Z_AXIS];
  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. char message[3 * (LCD_WIDTH) + 1] = ""; // worst case is kana.utf with up to 3*LCD_WIDTH+1
  1511. strcat_P(message, PSTR(MSG_HOME " "));
  1512. if (xx) strcat_P(message, PSTR(MSG_X));
  1513. if (yy) strcat_P(message, PSTR(MSG_Y));
  1514. if (zz) strcat_P(message, PSTR(MSG_Z));
  1515. strcat_P(message, PSTR(" " MSG_FIRST));
  1516. lcd_setstatus(message);
  1517. #endif
  1518. return true;
  1519. }
  1520. return false;
  1521. }
  1522. #endif
  1523. #if ENABLED(Z_PROBE_SLED)
  1524. #ifndef SLED_DOCKING_OFFSET
  1525. #define SLED_DOCKING_OFFSET 0
  1526. #endif
  1527. /**
  1528. * Method to dock/undock a sled designed by Charles Bell.
  1529. *
  1530. * stow[in] If false, move to MAX_X and engage the solenoid
  1531. * If true, move to MAX_X and release the solenoid
  1532. */
  1533. static void dock_sled(bool stow) {
  1534. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1535. if (DEBUGGING(LEVELING)) {
  1536. SERIAL_ECHOPAIR("dock_sled(", stow);
  1537. SERIAL_CHAR(')');
  1538. SERIAL_EOL;
  1539. }
  1540. #endif
  1541. // Dock sled a bit closer to ensure proper capturing
  1542. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1543. #if PIN_EXISTS(SLED)
  1544. digitalWrite(SLED_PIN, !stow); // switch solenoid
  1545. #endif
  1546. }
  1547. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1548. void run_deploy_moves_script() {
  1549. #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)
  1550. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1551. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1552. #endif
  1553. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1554. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1555. #endif
  1556. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1557. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1558. #endif
  1559. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1560. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1561. #endif
  1562. 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));
  1563. #endif
  1564. #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)
  1565. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1566. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1567. #endif
  1568. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1569. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1570. #endif
  1571. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1572. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1573. #endif
  1574. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1575. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1576. #endif
  1577. 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));
  1578. #endif
  1579. #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)
  1580. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1581. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1582. #endif
  1583. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1584. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1585. #endif
  1586. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1587. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1588. #endif
  1589. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1590. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1591. #endif
  1592. 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));
  1593. #endif
  1594. #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)
  1595. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1596. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1597. #endif
  1598. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1599. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1600. #endif
  1601. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1602. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1603. #endif
  1604. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1605. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1606. #endif
  1607. 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));
  1608. #endif
  1609. #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)
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1615. #endif
  1616. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1617. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1618. #endif
  1619. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1620. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1621. #endif
  1622. 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));
  1623. #endif
  1624. }
  1625. void run_stow_moves_script() {
  1626. #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)
  1627. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1628. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1629. #endif
  1630. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1631. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1632. #endif
  1633. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1634. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1635. #endif
  1636. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1637. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1638. #endif
  1639. 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));
  1640. #endif
  1641. #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)
  1642. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1643. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1646. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1647. #endif
  1648. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1649. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1650. #endif
  1651. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1652. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1653. #endif
  1654. 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));
  1655. #endif
  1656. #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)
  1657. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1658. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1659. #endif
  1660. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1661. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1662. #endif
  1663. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1664. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1665. #endif
  1666. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1667. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1668. #endif
  1669. 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));
  1670. #endif
  1671. #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)
  1672. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1673. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1674. #endif
  1675. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1676. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1677. #endif
  1678. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1679. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1680. #endif
  1681. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1682. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1683. #endif
  1684. 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));
  1685. #endif
  1686. #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)
  1687. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1688. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1689. #endif
  1690. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1691. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1692. #endif
  1693. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1694. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1695. #endif
  1696. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1697. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1698. #endif
  1699. 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));
  1700. #endif
  1701. }
  1702. #endif
  1703. #if HAS_BED_PROBE
  1704. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1705. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1706. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1707. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1708. #else
  1709. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1710. #endif
  1711. #endif
  1712. #define DEPLOY_PROBE() set_probe_deployed(true)
  1713. #define STOW_PROBE() set_probe_deployed(false)
  1714. #if ENABLED(BLTOUCH)
  1715. FORCE_INLINE void set_bltouch_deployed(const bool &deploy) {
  1716. servo[Z_ENDSTOP_SERVO_NR].move(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1717. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1718. if (DEBUGGING(LEVELING)) {
  1719. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1720. SERIAL_CHAR(')');
  1721. SERIAL_EOL;
  1722. }
  1723. #endif
  1724. }
  1725. #endif
  1726. // returns false for ok and true for failure
  1727. static bool set_probe_deployed(bool deploy) {
  1728. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1729. if (DEBUGGING(LEVELING)) {
  1730. DEBUG_POS("set_probe_deployed", current_position);
  1731. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1732. }
  1733. #endif
  1734. if (endstops.z_probe_enabled == deploy) return false;
  1735. // Make room for probe
  1736. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1737. // When deploying make sure BLTOUCH is not already triggered
  1738. #if ENABLED(BLTOUCH)
  1739. if (deploy && TEST_BLTOUCH()) { stop(); return true; }
  1740. #elif ENABLED(Z_PROBE_SLED)
  1741. if (axis_unhomed_error(true, false, false)) { stop(); return true; }
  1742. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1743. if (axis_unhomed_error(true, true, true )) { stop(); return true; }
  1744. #endif
  1745. float oldXpos = current_position[X_AXIS],
  1746. oldYpos = current_position[Y_AXIS];
  1747. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1748. // If endstop is already false, the Z probe is deployed
  1749. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1750. // Would a goto be less ugly?
  1751. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1752. // for a triggered when stowed manual probe.
  1753. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1754. // otherwise an Allen-Key probe can't be stowed.
  1755. #endif
  1756. #if ENABLED(Z_PROBE_SLED)
  1757. dock_sled(!deploy);
  1758. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1759. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1760. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1761. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1762. #endif
  1763. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1764. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1765. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1766. if (IsRunning()) {
  1767. SERIAL_ERROR_START;
  1768. SERIAL_ERRORLNPGM("Z-Probe failed");
  1769. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1770. }
  1771. stop();
  1772. return true;
  1773. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1774. #endif
  1775. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1776. endstops.enable_z_probe(deploy);
  1777. return false;
  1778. }
  1779. static void do_probe_move(float z, float fr_mm_m) {
  1780. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1781. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1782. #endif
  1783. // Deploy BLTouch at the start of any probe
  1784. #if ENABLED(BLTOUCH)
  1785. set_bltouch_deployed(true);
  1786. #endif
  1787. // Move down until probe triggered
  1788. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1789. // Retract BLTouch immediately after a probe
  1790. #if ENABLED(BLTOUCH)
  1791. set_bltouch_deployed(false);
  1792. #endif
  1793. // Clear endstop flags
  1794. endstops.hit_on_purpose();
  1795. // Get Z where the steppers were interrupted
  1796. set_current_from_steppers_for_axis(Z_AXIS);
  1797. // Tell the planner where we actually are
  1798. SYNC_PLAN_POSITION_KINEMATIC();
  1799. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1800. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1801. #endif
  1802. }
  1803. // Do a single Z probe and return with current_position[Z_AXIS]
  1804. // at the height where the probe triggered.
  1805. static float run_z_probe() {
  1806. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1807. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1808. #endif
  1809. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1810. refresh_cmd_timeout();
  1811. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1812. // Do a first probe at the fast speed
  1813. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1814. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1815. float first_probe_z = current_position[Z_AXIS];
  1816. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1817. #endif
  1818. // move up by the bump distance
  1819. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1820. #else
  1821. // If the nozzle is above the travel height then
  1822. // move down quickly before doing the slow probe
  1823. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1824. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1825. if (z < current_position[Z_AXIS])
  1826. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1827. #endif
  1828. // move down slowly to find bed
  1829. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1830. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1831. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1832. #endif
  1833. // Debug: compare probe heights
  1834. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1835. if (DEBUGGING(LEVELING)) {
  1836. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1837. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1838. }
  1839. #endif
  1840. return current_position[Z_AXIS];
  1841. }
  1842. //
  1843. // - Move to the given XY
  1844. // - Deploy the probe, if not already deployed
  1845. // - Probe the bed, get the Z position
  1846. // - Depending on the 'stow' flag
  1847. // - Stow the probe, or
  1848. // - Raise to the BETWEEN height
  1849. // - Return the probed Z position
  1850. //
  1851. static float probe_pt(const float &x, const float &y, bool stow = true, int verbose_level = 1) {
  1852. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1853. if (DEBUGGING(LEVELING)) {
  1854. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1855. SERIAL_ECHOPAIR(", ", y);
  1856. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1857. SERIAL_ECHOLNPGM("stow)");
  1858. DEBUG_POS("", current_position);
  1859. }
  1860. #endif
  1861. float old_feedrate_mm_s = feedrate_mm_s;
  1862. #if ENABLED(DELTA)
  1863. if (current_position[Z_AXIS] > delta_clip_start_height)
  1864. do_blocking_move_to_z(delta_clip_start_height);
  1865. #endif
  1866. // Ensure a minimum height before moving the probe
  1867. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1868. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1869. // Move the probe to the given XY
  1870. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1871. if (DEPLOY_PROBE()) return NAN;
  1872. float measured_z = run_z_probe();
  1873. if (!stow)
  1874. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1875. else
  1876. if (STOW_PROBE()) return NAN;
  1877. if (verbose_level > 2) {
  1878. SERIAL_PROTOCOLPGM("Bed X: ");
  1879. SERIAL_PROTOCOL_F(x, 3);
  1880. SERIAL_PROTOCOLPGM(" Y: ");
  1881. SERIAL_PROTOCOL_F(y, 3);
  1882. SERIAL_PROTOCOLPGM(" Z: ");
  1883. SERIAL_PROTOCOL_F(measured_z, 3);
  1884. SERIAL_EOL;
  1885. }
  1886. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1887. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1888. #endif
  1889. feedrate_mm_s = old_feedrate_mm_s;
  1890. return measured_z;
  1891. }
  1892. #endif // HAS_BED_PROBE
  1893. #if PLANNER_LEVELING
  1894. /**
  1895. * Turn bed leveling on or off, fixing the current
  1896. * position as-needed.
  1897. *
  1898. * Disable: Current position = physical position
  1899. * Enable: Current position = "unleveled" physical position
  1900. */
  1901. void set_bed_leveling_enabled(bool enable=true) {
  1902. #if ENABLED(MESH_BED_LEVELING)
  1903. if (enable != mbl.active()) {
  1904. if (!enable)
  1905. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  1906. mbl.set_active(enable && mbl.has_mesh());
  1907. if (enable) planner.unapply_leveling(current_position);
  1908. }
  1909. #elif HAS_ABL
  1910. if (enable != planner.abl_enabled) {
  1911. planner.abl_enabled = enable;
  1912. if (!enable)
  1913. set_current_from_steppers_for_axis(
  1914. #if ABL_PLANAR
  1915. ALL_AXES
  1916. #else
  1917. Z_AXIS
  1918. #endif
  1919. );
  1920. else
  1921. planner.unapply_leveling(current_position);
  1922. }
  1923. #endif
  1924. }
  1925. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1926. void set_z_fade_height(const float zfh) {
  1927. planner.z_fade_height = zfh;
  1928. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  1929. if (
  1930. #if ENABLED(MESH_BED_LEVELING)
  1931. mbl.active()
  1932. #else
  1933. planner.abl_enabled
  1934. #endif
  1935. ) {
  1936. set_current_from_steppers_for_axis(
  1937. #if ABL_PLANAR
  1938. ALL_AXES
  1939. #else
  1940. Z_AXIS
  1941. #endif
  1942. );
  1943. }
  1944. }
  1945. #endif // LEVELING_FADE_HEIGHT
  1946. /**
  1947. * Reset calibration results to zero.
  1948. */
  1949. void reset_bed_level() {
  1950. #if ENABLED(MESH_BED_LEVELING)
  1951. if (mbl.has_mesh()) {
  1952. set_bed_leveling_enabled(false);
  1953. mbl.reset();
  1954. mbl.set_has_mesh(false);
  1955. }
  1956. #else
  1957. planner.abl_enabled = false;
  1958. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1959. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  1960. #endif
  1961. #if ABL_PLANAR
  1962. planner.bed_level_matrix.set_to_identity();
  1963. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1964. for (uint8_t x = 0; x < ABL_GRID_POINTS_X; x++)
  1965. for (uint8_t y = 0; y < ABL_GRID_POINTS_Y; y++)
  1966. bed_level_grid[x][y] = 1000.0;
  1967. #endif
  1968. #endif
  1969. }
  1970. #endif // PLANNER_LEVELING
  1971. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1972. /**
  1973. * Extrapolate a single point from its neighbors
  1974. */
  1975. static void extrapolate_one_point(uint8_t x, uint8_t y, int8_t xdir, int8_t ydir) {
  1976. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1977. if (DEBUGGING(LEVELING)) {
  1978. SERIAL_ECHOPGM("Extrapolate [");
  1979. if (x < 10) SERIAL_CHAR(' ');
  1980. SERIAL_ECHO((int)x);
  1981. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  1982. SERIAL_CHAR(' ');
  1983. if (y < 10) SERIAL_CHAR(' ');
  1984. SERIAL_ECHO((int)y);
  1985. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  1986. SERIAL_CHAR(']');
  1987. }
  1988. #endif
  1989. if (bed_level_grid[x][y] < 999.0) {
  1990. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1991. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  1992. #endif
  1993. return; // Don't overwrite good values.
  1994. }
  1995. SERIAL_EOL;
  1996. // Get X neighbors, Y neighbors, and XY neighbors
  1997. float a1 = bed_level_grid[x + xdir][y], a2 = bed_level_grid[x + xdir * 2][y],
  1998. b1 = bed_level_grid[x][y + ydir], b2 = bed_level_grid[x][y + ydir * 2],
  1999. c1 = bed_level_grid[x + xdir][y + ydir], c2 = bed_level_grid[x + xdir * 2][y + ydir * 2];
  2000. // Treat far unprobed points as zero, near as equal to far
  2001. if (a2 > 999.0) a2 = 0.0; if (a1 > 999.0) a1 = a2;
  2002. if (b2 > 999.0) b2 = 0.0; if (b1 > 999.0) b1 = b2;
  2003. if (c2 > 999.0) c2 = 0.0; if (c1 > 999.0) c1 = c2;
  2004. float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2005. // Take the average intstead of the median
  2006. bed_level_grid[x][y] = (a + b + c) / 3.0;
  2007. // Median is robust (ignores outliers).
  2008. // bed_level_grid[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2009. // : ((c < b) ? b : (a < c) ? a : c);
  2010. }
  2011. //Enable this if your SCARA uses 180° of total area
  2012. //#define EXTRAPOLATE_FROM_EDGE
  2013. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2014. #if ABL_GRID_POINTS_X < ABL_GRID_POINTS_Y
  2015. #define HALF_IN_X
  2016. #elif ABL_GRID_POINTS_Y < ABL_GRID_POINTS_X
  2017. #define HALF_IN_Y
  2018. #endif
  2019. #endif
  2020. /**
  2021. * Fill in the unprobed points (corners of circular print surface)
  2022. * using linear extrapolation, away from the center.
  2023. */
  2024. static void extrapolate_unprobed_bed_level() {
  2025. #ifdef HALF_IN_X
  2026. const uint8_t ctrx2 = 0, xlen = ABL_GRID_POINTS_X - 1;
  2027. #else
  2028. const uint8_t ctrx1 = (ABL_GRID_POINTS_X - 1) / 2, // left-of-center
  2029. ctrx2 = ABL_GRID_POINTS_X / 2, // right-of-center
  2030. xlen = ctrx1;
  2031. #endif
  2032. #ifdef HALF_IN_Y
  2033. const uint8_t ctry2 = 0, ylen = ABL_GRID_POINTS_Y - 1;
  2034. #else
  2035. const uint8_t ctry1 = (ABL_GRID_POINTS_Y - 1) / 2, // top-of-center
  2036. ctry2 = ABL_GRID_POINTS_Y / 2, // bottom-of-center
  2037. ylen = ctry1;
  2038. #endif
  2039. for (uint8_t xo = 0; xo <= xlen; xo++)
  2040. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2041. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2042. #ifndef HALF_IN_X
  2043. uint8_t x1 = ctrx1 - xo;
  2044. #endif
  2045. #ifndef HALF_IN_Y
  2046. uint8_t y1 = ctry1 - yo;
  2047. #ifndef HALF_IN_X
  2048. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2049. #endif
  2050. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2051. #endif
  2052. #ifndef HALF_IN_X
  2053. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2054. #endif
  2055. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2056. }
  2057. }
  2058. /**
  2059. * Print calibration results for plotting or manual frame adjustment.
  2060. */
  2061. static void print_bed_level() {
  2062. SERIAL_ECHOPGM("Bilinear Leveling Grid:\n ");
  2063. for (uint8_t x = 0; x < ABL_GRID_POINTS_X; x++) {
  2064. SERIAL_PROTOCOLPGM(" ");
  2065. if (x < 10) SERIAL_PROTOCOLCHAR(' ');
  2066. SERIAL_PROTOCOL((int)x);
  2067. }
  2068. SERIAL_EOL;
  2069. for (uint8_t y = 0; y < ABL_GRID_POINTS_Y; y++) {
  2070. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2071. SERIAL_PROTOCOL((int)y);
  2072. for (uint8_t x = 0; x < ABL_GRID_POINTS_X; x++) {
  2073. SERIAL_PROTOCOLCHAR(' ');
  2074. float offset = bed_level_grid[x][y];
  2075. if (offset < 999.0) {
  2076. if (offset > 0) SERIAL_CHAR('+');
  2077. SERIAL_PROTOCOL_F(offset, 2);
  2078. }
  2079. else
  2080. SERIAL_PROTOCOLPGM(" ====");
  2081. }
  2082. SERIAL_EOL;
  2083. }
  2084. SERIAL_EOL;
  2085. }
  2086. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2087. #define ABL_GRID_POINTS_VIRT_X (ABL_GRID_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2088. #define ABL_GRID_POINTS_VIRT_Y (ABL_GRID_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2089. float bed_level_grid_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2090. float bed_level_grid_virt_temp[ABL_GRID_POINTS_X + 2][ABL_GRID_POINTS_Y + 2]; //temporary for calculation (maybe dynamical?)
  2091. int bilinear_grid_spacing_virt[2] = { 0 };
  2092. static void bed_level_virt_print() {
  2093. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2094. for (uint8_t x = 0; x < ABL_GRID_POINTS_VIRT_X; x++) {
  2095. SERIAL_PROTOCOLPGM(" ");
  2096. if (x < 10) SERIAL_PROTOCOLCHAR(' ');
  2097. SERIAL_PROTOCOL((int)x);
  2098. }
  2099. SERIAL_EOL;
  2100. for (uint8_t y = 0; y < ABL_GRID_POINTS_VIRT_Y; y++) {
  2101. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2102. SERIAL_PROTOCOL((int)y);
  2103. for (uint8_t x = 0; x < ABL_GRID_POINTS_VIRT_X; x++) {
  2104. SERIAL_PROTOCOLCHAR(' ');
  2105. float offset = bed_level_grid_virt[x][y];
  2106. if (offset < 999.0) {
  2107. if (offset > 0) SERIAL_CHAR('+');
  2108. SERIAL_PROTOCOL_F(offset, 5);
  2109. }
  2110. else
  2111. SERIAL_PROTOCOLPGM(" ====");
  2112. }
  2113. SERIAL_EOL;
  2114. }
  2115. SERIAL_EOL;
  2116. }
  2117. #define LINEAR_EXTRAPOLATION(E, I) (E * 2 - I)
  2118. static void bed_level_virt_prepare() {
  2119. for (uint8_t y = 1; y <= ABL_GRID_POINTS_Y; y++) {
  2120. for (uint8_t x = 1; x <= ABL_GRID_POINTS_X; x++)
  2121. bed_level_grid_virt_temp[x][y] = bed_level_grid[x - 1][y - 1];
  2122. bed_level_grid_virt_temp[0][y] = LINEAR_EXTRAPOLATION(
  2123. bed_level_grid_virt_temp[1][y],
  2124. bed_level_grid_virt_temp[2][y]
  2125. );
  2126. bed_level_grid_virt_temp[(ABL_GRID_POINTS_X + 2) - 1][y] =
  2127. LINEAR_EXTRAPOLATION(
  2128. bed_level_grid_virt_temp[(ABL_GRID_POINTS_X + 2) - 2][y],
  2129. bed_level_grid_virt_temp[(ABL_GRID_POINTS_X + 2) - 3][y]
  2130. );
  2131. }
  2132. for (uint8_t x = 0; x < ABL_GRID_POINTS_X + 2; x++) {
  2133. bed_level_grid_virt_temp[x][0] = LINEAR_EXTRAPOLATION(
  2134. bed_level_grid_virt_temp[x][1],
  2135. bed_level_grid_virt_temp[x][2]
  2136. );
  2137. bed_level_grid_virt_temp[x][(ABL_GRID_POINTS_Y + 2) - 1] =
  2138. LINEAR_EXTRAPOLATION(
  2139. bed_level_grid_virt_temp[x][(ABL_GRID_POINTS_Y + 2) - 2],
  2140. bed_level_grid_virt_temp[x][(ABL_GRID_POINTS_Y + 2) - 3]
  2141. );
  2142. }
  2143. }
  2144. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2145. return (
  2146. p[i-1] * -t * sq(1 - t)
  2147. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2148. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2149. - p[i+2] * sq(t) * (1 - t)
  2150. ) * 0.5;
  2151. }
  2152. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2153. float row[4], column[4];
  2154. for (uint8_t i = 0; i < 4; i++) {
  2155. for (uint8_t j = 0; j < 4; j++) // can be memcopy or through memory access
  2156. column[j] = bed_level_grid_virt_temp[i + x - 1][j + y - 1];
  2157. row[i] = bed_level_virt_cmr(column, 1, ty);
  2158. }
  2159. return bed_level_virt_cmr(row, 1, tx);
  2160. }
  2161. static void bed_level_virt_interpolate() {
  2162. for (uint8_t y = 0; y < ABL_GRID_POINTS_Y; y++)
  2163. for (uint8_t x = 0; x < ABL_GRID_POINTS_X; x++)
  2164. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2165. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2166. if ((ty && y == ABL_GRID_POINTS_Y - 1) || (tx && x == ABL_GRID_POINTS_X - 1))
  2167. continue;
  2168. bed_level_grid_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2169. bed_level_virt_2cmr(
  2170. x + 1,
  2171. y + 1,
  2172. (float)tx / (BILINEAR_SUBDIVISIONS),
  2173. (float)ty / (BILINEAR_SUBDIVISIONS)
  2174. );
  2175. }
  2176. }
  2177. #endif // ABL_BILINEAR_SUBDIVISION
  2178. #endif // AUTO_BED_LEVELING_BILINEAR
  2179. /**
  2180. * Home an individual linear axis
  2181. */
  2182. static void do_homing_move(const AxisEnum axis, float distance, float fr_mm_s=0.0) {
  2183. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2184. if (DEBUGGING(LEVELING)) {
  2185. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2186. SERIAL_ECHOPAIR(", ", distance);
  2187. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2188. SERIAL_CHAR(')');
  2189. SERIAL_EOL;
  2190. }
  2191. #endif
  2192. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2193. bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2194. if (deploy_bltouch) set_bltouch_deployed(true);
  2195. #endif
  2196. // Tell the planner we're at Z=0
  2197. current_position[axis] = 0;
  2198. #if IS_SCARA
  2199. SYNC_PLAN_POSITION_KINEMATIC();
  2200. current_position[axis] = distance;
  2201. inverse_kinematics(current_position);
  2202. 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);
  2203. #else
  2204. sync_plan_position();
  2205. current_position[axis] = distance;
  2206. 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);
  2207. #endif
  2208. stepper.synchronize();
  2209. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2210. if (deploy_bltouch) set_bltouch_deployed(false);
  2211. #endif
  2212. endstops.hit_on_purpose();
  2213. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2214. if (DEBUGGING(LEVELING)) {
  2215. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2216. SERIAL_CHAR(')');
  2217. SERIAL_EOL;
  2218. }
  2219. #endif
  2220. }
  2221. /**
  2222. * Home an individual "raw axis" to its endstop.
  2223. * This applies to XYZ on Cartesian and Core robots, and
  2224. * to the individual ABC steppers on DELTA and SCARA.
  2225. *
  2226. * At the end of the procedure the axis is marked as
  2227. * homed and the current position of that axis is updated.
  2228. * Kinematic robots should wait till all axes are homed
  2229. * before updating the current position.
  2230. */
  2231. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2232. static void homeaxis(AxisEnum axis) {
  2233. #if IS_SCARA
  2234. // Only Z homing (with probe) is permitted
  2235. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2236. #else
  2237. #define CAN_HOME(A) \
  2238. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2239. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2240. #endif
  2241. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2242. if (DEBUGGING(LEVELING)) {
  2243. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2244. SERIAL_CHAR(')');
  2245. SERIAL_EOL;
  2246. }
  2247. #endif
  2248. int axis_home_dir =
  2249. #if ENABLED(DUAL_X_CARRIAGE)
  2250. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2251. #endif
  2252. home_dir(axis);
  2253. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2254. #if HOMING_Z_WITH_PROBE
  2255. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2256. #endif
  2257. // Set a flag for Z motor locking
  2258. #if ENABLED(Z_DUAL_ENDSTOPS)
  2259. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2260. #endif
  2261. // Fast move towards endstop until triggered
  2262. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2263. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2264. #endif
  2265. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2266. // When homing Z with probe respect probe clearance
  2267. const float bump = axis_home_dir * (
  2268. #if HOMING_Z_WITH_PROBE
  2269. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2270. #endif
  2271. home_bump_mm(axis)
  2272. );
  2273. // If a second homing move is configured...
  2274. if (bump) {
  2275. // Move away from the endstop by the axis HOME_BUMP_MM
  2276. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2277. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2278. #endif
  2279. do_homing_move(axis, -bump);
  2280. // Slow move towards endstop until triggered
  2281. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2282. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2283. #endif
  2284. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2285. }
  2286. #if ENABLED(Z_DUAL_ENDSTOPS)
  2287. if (axis == Z_AXIS) {
  2288. float adj = fabs(z_endstop_adj);
  2289. bool lockZ1;
  2290. if (axis_home_dir > 0) {
  2291. adj = -adj;
  2292. lockZ1 = (z_endstop_adj > 0);
  2293. }
  2294. else
  2295. lockZ1 = (z_endstop_adj < 0);
  2296. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2297. // Move to the adjusted endstop height
  2298. do_homing_move(axis, adj);
  2299. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2300. stepper.set_homing_flag(false);
  2301. } // Z_AXIS
  2302. #endif
  2303. #if IS_SCARA
  2304. set_axis_is_at_home(axis);
  2305. SYNC_PLAN_POSITION_KINEMATIC();
  2306. #elif ENABLED(DELTA)
  2307. // Delta has already moved all three towers up in G28
  2308. // so here it re-homes each tower in turn.
  2309. // Delta homing treats the axes as normal linear axes.
  2310. // retrace by the amount specified in endstop_adj
  2311. if (endstop_adj[axis] * Z_HOME_DIR < 0) {
  2312. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2313. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2314. #endif
  2315. do_homing_move(axis, endstop_adj[axis]);
  2316. }
  2317. #else
  2318. // For cartesian/core machines,
  2319. // set the axis to its home position
  2320. set_axis_is_at_home(axis);
  2321. sync_plan_position();
  2322. destination[axis] = current_position[axis];
  2323. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2324. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2325. #endif
  2326. #endif
  2327. // Put away the Z probe
  2328. #if HOMING_Z_WITH_PROBE
  2329. if (axis == Z_AXIS && STOW_PROBE()) return;
  2330. #endif
  2331. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2332. if (DEBUGGING(LEVELING)) {
  2333. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2334. SERIAL_CHAR(')');
  2335. SERIAL_EOL;
  2336. }
  2337. #endif
  2338. } // homeaxis()
  2339. #if ENABLED(FWRETRACT)
  2340. void retract(bool retracting, bool swapping = false) {
  2341. if (retracting == retracted[active_extruder]) return;
  2342. float old_feedrate_mm_s = feedrate_mm_s;
  2343. set_destination_to_current();
  2344. if (retracting) {
  2345. feedrate_mm_s = retract_feedrate_mm_s;
  2346. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2347. sync_plan_position_e();
  2348. prepare_move_to_destination();
  2349. if (retract_zlift > 0.01) {
  2350. current_position[Z_AXIS] -= retract_zlift;
  2351. SYNC_PLAN_POSITION_KINEMATIC();
  2352. prepare_move_to_destination();
  2353. }
  2354. }
  2355. else {
  2356. if (retract_zlift > 0.01) {
  2357. current_position[Z_AXIS] += retract_zlift;
  2358. SYNC_PLAN_POSITION_KINEMATIC();
  2359. }
  2360. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2361. float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2362. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2363. sync_plan_position_e();
  2364. prepare_move_to_destination();
  2365. }
  2366. feedrate_mm_s = old_feedrate_mm_s;
  2367. retracted[active_extruder] = retracting;
  2368. } // retract()
  2369. #endif // FWRETRACT
  2370. #if ENABLED(MIXING_EXTRUDER)
  2371. void normalize_mix() {
  2372. float mix_total = 0.0;
  2373. for (int i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2374. // Scale all values if they don't add up to ~1.0
  2375. if (!NEAR(mix_total, 1.0)) {
  2376. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2377. for (int i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2378. }
  2379. }
  2380. #if ENABLED(DIRECT_MIXING_IN_G1)
  2381. // Get mixing parameters from the GCode
  2382. // The total "must" be 1.0 (but it will be normalized)
  2383. // If no mix factors are given, the old mix is preserved
  2384. void gcode_get_mix() {
  2385. const char* mixing_codes = "ABCDHI";
  2386. byte mix_bits = 0;
  2387. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2388. if (code_seen(mixing_codes[i])) {
  2389. SBI(mix_bits, i);
  2390. float v = code_value_float();
  2391. NOLESS(v, 0.0);
  2392. mixing_factor[i] = RECIPROCAL(v);
  2393. }
  2394. }
  2395. // If any mixing factors were included, clear the rest
  2396. // If none were included, preserve the last mix
  2397. if (mix_bits) {
  2398. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2399. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2400. normalize_mix();
  2401. }
  2402. }
  2403. #endif
  2404. #endif
  2405. /**
  2406. * ***************************************************************************
  2407. * ***************************** G-CODE HANDLING *****************************
  2408. * ***************************************************************************
  2409. */
  2410. /**
  2411. * Set XYZE destination and feedrate from the current GCode command
  2412. *
  2413. * - Set destination from included axis codes
  2414. * - Set to current for missing axis codes
  2415. * - Set the feedrate, if included
  2416. */
  2417. void gcode_get_destination() {
  2418. LOOP_XYZE(i) {
  2419. if (code_seen(axis_codes[i]))
  2420. destination[i] = code_value_axis_units(i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2421. else
  2422. destination[i] = current_position[i];
  2423. }
  2424. if (code_seen('F') && code_value_linear_units() > 0.0)
  2425. feedrate_mm_s = MMM_TO_MMS(code_value_linear_units());
  2426. #if ENABLED(PRINTCOUNTER)
  2427. if (!DEBUGGING(DRYRUN))
  2428. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2429. #endif
  2430. // Get ABCDHI mixing factors
  2431. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2432. gcode_get_mix();
  2433. #endif
  2434. }
  2435. void unknown_command_error() {
  2436. SERIAL_ECHO_START;
  2437. SERIAL_ECHOPAIR(MSG_UNKNOWN_COMMAND, current_command);
  2438. SERIAL_CHAR('"');
  2439. SERIAL_EOL;
  2440. }
  2441. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2442. /**
  2443. * Output a "busy" message at regular intervals
  2444. * while the machine is not accepting commands.
  2445. */
  2446. void host_keepalive() {
  2447. millis_t ms = millis();
  2448. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2449. if (PENDING(ms, next_busy_signal_ms)) return;
  2450. switch (busy_state) {
  2451. case IN_HANDLER:
  2452. case IN_PROCESS:
  2453. SERIAL_ECHO_START;
  2454. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2455. break;
  2456. case PAUSED_FOR_USER:
  2457. SERIAL_ECHO_START;
  2458. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2459. break;
  2460. case PAUSED_FOR_INPUT:
  2461. SERIAL_ECHO_START;
  2462. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2463. break;
  2464. default:
  2465. break;
  2466. }
  2467. }
  2468. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2469. }
  2470. #endif //HOST_KEEPALIVE_FEATURE
  2471. bool position_is_reachable(float target[XYZ]
  2472. #if HAS_BED_PROBE
  2473. , bool by_probe=false
  2474. #endif
  2475. ) {
  2476. float dx = RAW_X_POSITION(target[X_AXIS]),
  2477. dy = RAW_Y_POSITION(target[Y_AXIS]);
  2478. #if HAS_BED_PROBE
  2479. if (by_probe) {
  2480. dx -= X_PROBE_OFFSET_FROM_EXTRUDER;
  2481. dy -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  2482. }
  2483. #endif
  2484. #if IS_SCARA
  2485. #if MIDDLE_DEAD_ZONE_R > 0
  2486. const float R2 = HYPOT2(dx - SCARA_OFFSET_X, dy - SCARA_OFFSET_Y);
  2487. return R2 >= sq(float(MIDDLE_DEAD_ZONE_R)) && R2 <= sq(L1 + L2);
  2488. #else
  2489. return HYPOT2(dx - SCARA_OFFSET_X, dy - SCARA_OFFSET_Y) <= sq(L1 + L2);
  2490. #endif
  2491. #elif ENABLED(DELTA)
  2492. return HYPOT2(dx, dy) <= sq(DELTA_PRINTABLE_RADIUS);
  2493. #else
  2494. const float dz = RAW_Z_POSITION(target[Z_AXIS]);
  2495. return dx >= X_MIN_POS - 0.0001 && dx <= X_MAX_POS + 0.0001
  2496. && dy >= Y_MIN_POS - 0.0001 && dy <= Y_MAX_POS + 0.0001
  2497. && dz >= Z_MIN_POS - 0.0001 && dz <= Z_MAX_POS + 0.0001;
  2498. #endif
  2499. }
  2500. /**************************************************
  2501. ***************** GCode Handlers *****************
  2502. **************************************************/
  2503. /**
  2504. * G0, G1: Coordinated movement of X Y Z E axes
  2505. */
  2506. inline void gcode_G0_G1(
  2507. #if IS_SCARA
  2508. bool fast_move=false
  2509. #endif
  2510. ) {
  2511. if (IsRunning()) {
  2512. gcode_get_destination(); // For X Y Z E F
  2513. #if ENABLED(FWRETRACT)
  2514. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  2515. float echange = destination[E_AXIS] - current_position[E_AXIS];
  2516. // Is this move an attempt to retract or recover?
  2517. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2518. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2519. sync_plan_position_e(); // AND from the planner
  2520. retract(!retracted[active_extruder]);
  2521. return;
  2522. }
  2523. }
  2524. #endif //FWRETRACT
  2525. #if IS_SCARA
  2526. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2527. #else
  2528. prepare_move_to_destination();
  2529. #endif
  2530. }
  2531. }
  2532. /**
  2533. * G2: Clockwise Arc
  2534. * G3: Counterclockwise Arc
  2535. *
  2536. * This command has two forms: IJ-form and R-form.
  2537. *
  2538. * - I specifies an X offset. J specifies a Y offset.
  2539. * At least one of the IJ parameters is required.
  2540. * X and Y can be omitted to do a complete circle.
  2541. * The given XY is not error-checked. The arc ends
  2542. * based on the angle of the destination.
  2543. * Mixing I or J with R will throw an error.
  2544. *
  2545. * - R specifies the radius. X or Y is required.
  2546. * Omitting both X and Y will throw an error.
  2547. * X or Y must differ from the current XY.
  2548. * Mixing R with I or J will throw an error.
  2549. *
  2550. * Examples:
  2551. *
  2552. * G2 I10 ; CW circle centered at X+10
  2553. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2554. */
  2555. #if ENABLED(ARC_SUPPORT)
  2556. inline void gcode_G2_G3(bool clockwise) {
  2557. if (IsRunning()) {
  2558. #if ENABLED(SF_ARC_FIX)
  2559. bool relative_mode_backup = relative_mode;
  2560. relative_mode = true;
  2561. #endif
  2562. gcode_get_destination();
  2563. #if ENABLED(SF_ARC_FIX)
  2564. relative_mode = relative_mode_backup;
  2565. #endif
  2566. float arc_offset[2] = { 0.0, 0.0 };
  2567. if (code_seen('R')) {
  2568. const float r = code_value_axis_units(X_AXIS),
  2569. x1 = current_position[X_AXIS], y1 = current_position[Y_AXIS],
  2570. x2 = destination[X_AXIS], y2 = destination[Y_AXIS];
  2571. if (r && (x2 != x1 || y2 != y1)) {
  2572. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2573. dx = x2 - x1, dy = y2 - y1, // X and Y differences
  2574. d = HYPOT(dx, dy), // Linear distance between the points
  2575. h = sqrt(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2576. mx = (x1 + x2) * 0.5, my = (y1 + y2) * 0.5, // Point between the two points
  2577. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2578. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2579. arc_offset[X_AXIS] = cx - x1;
  2580. arc_offset[Y_AXIS] = cy - y1;
  2581. }
  2582. }
  2583. else {
  2584. if (code_seen('I')) arc_offset[X_AXIS] = code_value_axis_units(X_AXIS);
  2585. if (code_seen('J')) arc_offset[Y_AXIS] = code_value_axis_units(Y_AXIS);
  2586. }
  2587. if (arc_offset[0] || arc_offset[1]) {
  2588. // Send an arc to the planner
  2589. plan_arc(destination, arc_offset, clockwise);
  2590. refresh_cmd_timeout();
  2591. }
  2592. else {
  2593. // Bad arguments
  2594. SERIAL_ERROR_START;
  2595. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2596. }
  2597. }
  2598. }
  2599. #endif
  2600. /**
  2601. * G4: Dwell S<seconds> or P<milliseconds>
  2602. */
  2603. inline void gcode_G4() {
  2604. millis_t dwell_ms = 0;
  2605. if (code_seen('P')) dwell_ms = code_value_millis(); // milliseconds to wait
  2606. if (code_seen('S')) dwell_ms = code_value_millis_from_seconds(); // seconds to wait
  2607. stepper.synchronize();
  2608. refresh_cmd_timeout();
  2609. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2610. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2611. while (PENDING(millis(), dwell_ms)) idle();
  2612. }
  2613. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2614. /**
  2615. * Parameters interpreted according to:
  2616. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2617. * However I, J omission is not supported at this point; all
  2618. * parameters can be omitted and default to zero.
  2619. */
  2620. /**
  2621. * G5: Cubic B-spline
  2622. */
  2623. inline void gcode_G5() {
  2624. if (IsRunning()) {
  2625. gcode_get_destination();
  2626. float offset[] = {
  2627. code_seen('I') ? code_value_axis_units(X_AXIS) : 0.0,
  2628. code_seen('J') ? code_value_axis_units(Y_AXIS) : 0.0,
  2629. code_seen('P') ? code_value_axis_units(X_AXIS) : 0.0,
  2630. code_seen('Q') ? code_value_axis_units(Y_AXIS) : 0.0
  2631. };
  2632. plan_cubic_move(offset);
  2633. }
  2634. }
  2635. #endif // BEZIER_CURVE_SUPPORT
  2636. #if ENABLED(FWRETRACT)
  2637. /**
  2638. * G10 - Retract filament according to settings of M207
  2639. * G11 - Recover filament according to settings of M208
  2640. */
  2641. inline void gcode_G10_G11(bool doRetract=false) {
  2642. #if EXTRUDERS > 1
  2643. if (doRetract) {
  2644. retracted_swap[active_extruder] = (code_seen('S') && code_value_bool()); // checks for swap retract argument
  2645. }
  2646. #endif
  2647. retract(doRetract
  2648. #if EXTRUDERS > 1
  2649. , retracted_swap[active_extruder]
  2650. #endif
  2651. );
  2652. }
  2653. #endif //FWRETRACT
  2654. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2655. /**
  2656. * G12: Clean the nozzle
  2657. */
  2658. inline void gcode_G12() {
  2659. // Don't allow nozzle cleaning without homing first
  2660. if (axis_unhomed_error(true, true, true)) { return; }
  2661. uint8_t const pattern = code_seen('P') ? code_value_ushort() : 0;
  2662. uint8_t const strokes = code_seen('S') ? code_value_ushort() : NOZZLE_CLEAN_STROKES;
  2663. uint8_t const objects = code_seen('T') ? code_value_ushort() : 3;
  2664. Nozzle::clean(pattern, strokes, objects);
  2665. }
  2666. #endif
  2667. #if ENABLED(INCH_MODE_SUPPORT)
  2668. /**
  2669. * G20: Set input mode to inches
  2670. */
  2671. inline void gcode_G20() { set_input_linear_units(LINEARUNIT_INCH); }
  2672. /**
  2673. * G21: Set input mode to millimeters
  2674. */
  2675. inline void gcode_G21() { set_input_linear_units(LINEARUNIT_MM); }
  2676. #endif
  2677. #if ENABLED(NOZZLE_PARK_FEATURE)
  2678. /**
  2679. * G27: Park the nozzle
  2680. */
  2681. inline void gcode_G27() {
  2682. // Don't allow nozzle parking without homing first
  2683. if (axis_unhomed_error(true, true, true)) { return; }
  2684. uint8_t const z_action = code_seen('P') ? code_value_ushort() : 0;
  2685. Nozzle::park(z_action);
  2686. }
  2687. #endif // NOZZLE_PARK_FEATURE
  2688. #if ENABLED(QUICK_HOME)
  2689. static void quick_home_xy() {
  2690. // Pretend the current position is 0,0
  2691. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2692. sync_plan_position();
  2693. int x_axis_home_dir =
  2694. #if ENABLED(DUAL_X_CARRIAGE)
  2695. x_home_dir(active_extruder)
  2696. #else
  2697. home_dir(X_AXIS)
  2698. #endif
  2699. ;
  2700. float mlx = max_length(X_AXIS),
  2701. mly = max_length(Y_AXIS),
  2702. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2703. fr_mm_s = min(homing_feedrate_mm_s[X_AXIS], homing_feedrate_mm_s[Y_AXIS]) * sqrt(sq(mlratio) + 1.0);
  2704. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2705. endstops.hit_on_purpose(); // clear endstop hit flags
  2706. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2707. }
  2708. #endif // QUICK_HOME
  2709. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2710. void log_machine_info() {
  2711. SERIAL_ECHOPGM("Machine Type: ");
  2712. #if ENABLED(DELTA)
  2713. SERIAL_ECHOLNPGM("Delta");
  2714. #elif IS_SCARA
  2715. SERIAL_ECHOLNPGM("SCARA");
  2716. #elif IS_CORE
  2717. SERIAL_ECHOLNPGM("Core");
  2718. #else
  2719. SERIAL_ECHOLNPGM("Cartesian");
  2720. #endif
  2721. SERIAL_ECHOPGM("Probe: ");
  2722. #if ENABLED(FIX_MOUNTED_PROBE)
  2723. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  2724. #elif ENABLED(BLTOUCH)
  2725. SERIAL_ECHOLNPGM("BLTOUCH");
  2726. #elif HAS_Z_SERVO_ENDSTOP
  2727. SERIAL_ECHOLNPGM("SERVO PROBE");
  2728. #elif ENABLED(Z_PROBE_SLED)
  2729. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  2730. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2731. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  2732. #else
  2733. SERIAL_ECHOLNPGM("NONE");
  2734. #endif
  2735. #if HAS_BED_PROBE
  2736. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  2737. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  2738. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  2739. #if (X_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2740. SERIAL_ECHOPGM(" (Right");
  2741. #elif (X_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2742. SERIAL_ECHOPGM(" (Left");
  2743. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2744. SERIAL_ECHOPGM(" (Middle");
  2745. #else
  2746. SERIAL_ECHOPGM(" (Aligned With");
  2747. #endif
  2748. #if (Y_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2749. SERIAL_ECHOPGM("-Back");
  2750. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2751. SERIAL_ECHOPGM("-Front");
  2752. #elif (X_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2753. SERIAL_ECHOPGM("-Center");
  2754. #endif
  2755. if (zprobe_zoffset < 0)
  2756. SERIAL_ECHOPGM(" & Below");
  2757. else if (zprobe_zoffset > 0)
  2758. SERIAL_ECHOPGM(" & Above");
  2759. else
  2760. SERIAL_ECHOPGM(" & Same Z as");
  2761. SERIAL_ECHOLNPGM(" Nozzle)");
  2762. #endif
  2763. #if HAS_ABL
  2764. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  2765. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  2766. SERIAL_ECHOPGM("LINEAR");
  2767. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2768. SERIAL_ECHOPGM("BILINEAR");
  2769. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  2770. SERIAL_ECHOPGM("3POINT");
  2771. #endif
  2772. if (planner.abl_enabled) {
  2773. SERIAL_ECHOLNPGM(" (enabled)");
  2774. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT)
  2775. float diff[XYZ] = {
  2776. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  2777. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  2778. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  2779. };
  2780. SERIAL_ECHOPGM("ABL Adjustment X");
  2781. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  2782. SERIAL_ECHO(diff[X_AXIS]);
  2783. SERIAL_ECHOPGM(" Y");
  2784. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  2785. SERIAL_ECHO(diff[Y_AXIS]);
  2786. SERIAL_ECHOPGM(" Z");
  2787. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  2788. SERIAL_ECHO(diff[Z_AXIS]);
  2789. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2790. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  2791. #endif
  2792. }
  2793. SERIAL_EOL;
  2794. #elif ENABLED(MESH_BED_LEVELING)
  2795. SERIAL_ECHOPGM("Mesh Bed Leveling");
  2796. if (mbl.active()) {
  2797. float lz = current_position[Z_AXIS];
  2798. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  2799. SERIAL_ECHOLNPGM(" (enabled)");
  2800. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  2801. }
  2802. SERIAL_EOL;
  2803. #endif
  2804. }
  2805. #endif // DEBUG_LEVELING_FEATURE
  2806. #if ENABLED(DELTA)
  2807. /**
  2808. * A delta can only safely home all axes at the same time
  2809. * This is like quick_home_xy() but for 3 towers.
  2810. */
  2811. inline void home_delta() {
  2812. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2813. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  2814. #endif
  2815. // Init the current position of all carriages to 0,0,0
  2816. ZERO(current_position);
  2817. sync_plan_position();
  2818. // Move all carriages together linearly until an endstop is hit.
  2819. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  2820. feedrate_mm_s = homing_feedrate_mm_s[X_AXIS];
  2821. line_to_current_position();
  2822. stepper.synchronize();
  2823. endstops.hit_on_purpose(); // clear endstop hit flags
  2824. // At least one carriage has reached the top.
  2825. // Now re-home each carriage separately.
  2826. HOMEAXIS(A);
  2827. HOMEAXIS(B);
  2828. HOMEAXIS(C);
  2829. // Set all carriages to their home positions
  2830. // Do this here all at once for Delta, because
  2831. // XYZ isn't ABC. Applying this per-tower would
  2832. // give the impression that they are the same.
  2833. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  2834. SYNC_PLAN_POSITION_KINEMATIC();
  2835. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2836. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  2837. #endif
  2838. }
  2839. #endif // DELTA
  2840. #if ENABLED(Z_SAFE_HOMING)
  2841. inline void home_z_safely() {
  2842. // Disallow Z homing if X or Y are unknown
  2843. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  2844. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  2845. SERIAL_ECHO_START;
  2846. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  2847. return;
  2848. }
  2849. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2850. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  2851. #endif
  2852. SYNC_PLAN_POSITION_KINEMATIC();
  2853. /**
  2854. * Move the Z probe (or just the nozzle) to the safe homing point
  2855. */
  2856. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  2857. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  2858. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  2859. if (position_is_reachable(
  2860. destination
  2861. #if HOMING_Z_WITH_PROBE
  2862. , true
  2863. #endif
  2864. )
  2865. ) {
  2866. #if HOMING_Z_WITH_PROBE
  2867. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  2868. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  2869. #endif
  2870. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2871. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  2872. #endif
  2873. // This causes the carriage on Dual X to unpark
  2874. #if ENABLED(DUAL_X_CARRIAGE)
  2875. active_extruder_parked = false;
  2876. #endif
  2877. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  2878. HOMEAXIS(Z);
  2879. }
  2880. else {
  2881. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2882. SERIAL_ECHO_START;
  2883. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2884. }
  2885. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2886. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2887. #endif
  2888. }
  2889. #endif // Z_SAFE_HOMING
  2890. /**
  2891. * G28: Home all axes according to settings
  2892. *
  2893. * Parameters
  2894. *
  2895. * None Home to all axes with no parameters.
  2896. * With QUICK_HOME enabled XY will home together, then Z.
  2897. *
  2898. * Cartesian parameters
  2899. *
  2900. * X Home to the X endstop
  2901. * Y Home to the Y endstop
  2902. * Z Home to the Z endstop
  2903. *
  2904. */
  2905. inline void gcode_G28() {
  2906. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2907. if (DEBUGGING(LEVELING)) {
  2908. SERIAL_ECHOLNPGM(">>> gcode_G28");
  2909. log_machine_info();
  2910. }
  2911. #endif
  2912. // Wait for planner moves to finish!
  2913. stepper.synchronize();
  2914. // For auto bed leveling, clear the level matrix
  2915. #if HAS_ABL
  2916. reset_bed_level();
  2917. #endif
  2918. // Always home with tool 0 active
  2919. #if HOTENDS > 1
  2920. uint8_t old_tool_index = active_extruder;
  2921. tool_change(0, 0, true);
  2922. #endif
  2923. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  2924. extruder_duplication_enabled = false;
  2925. #endif
  2926. /**
  2927. * For mesh bed leveling deactivate the mesh calculations, will be turned
  2928. * on again when homing all axis
  2929. */
  2930. #if ENABLED(MESH_BED_LEVELING)
  2931. float pre_home_z = MESH_HOME_SEARCH_Z;
  2932. if (mbl.active()) {
  2933. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2934. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL was active");
  2935. #endif
  2936. // Use known Z position if already homed
  2937. if (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) {
  2938. set_bed_leveling_enabled(false);
  2939. pre_home_z = current_position[Z_AXIS];
  2940. }
  2941. else {
  2942. mbl.set_active(false);
  2943. current_position[Z_AXIS] = pre_home_z;
  2944. }
  2945. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2946. if (DEBUGGING(LEVELING)) DEBUG_POS("Set Z to pre_home_z", current_position);
  2947. #endif
  2948. }
  2949. #endif
  2950. setup_for_endstop_or_probe_move();
  2951. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2952. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  2953. #endif
  2954. endstops.enable(true); // Enable endstops for next homing move
  2955. #if ENABLED(DELTA)
  2956. home_delta();
  2957. #else // NOT DELTA
  2958. bool homeX = code_seen('X'), homeY = code_seen('Y'), homeZ = code_seen('Z');
  2959. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  2960. set_destination_to_current();
  2961. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2962. if (home_all_axis || homeZ) {
  2963. HOMEAXIS(Z);
  2964. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2965. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  2966. #endif
  2967. }
  2968. #else
  2969. if (home_all_axis || homeX || homeY) {
  2970. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2971. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  2972. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  2973. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2974. if (DEBUGGING(LEVELING))
  2975. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  2976. #endif
  2977. do_blocking_move_to_z(destination[Z_AXIS]);
  2978. }
  2979. }
  2980. #endif
  2981. #if ENABLED(QUICK_HOME)
  2982. if (home_all_axis || (homeX && homeY)) quick_home_xy();
  2983. #endif
  2984. #if ENABLED(HOME_Y_BEFORE_X)
  2985. // Home Y
  2986. if (home_all_axis || homeY) {
  2987. HOMEAXIS(Y);
  2988. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2989. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  2990. #endif
  2991. }
  2992. #endif
  2993. // Home X
  2994. if (home_all_axis || homeX) {
  2995. #if ENABLED(DUAL_X_CARRIAGE)
  2996. // Always home the 2nd (right) extruder first
  2997. active_extruder = 1;
  2998. HOMEAXIS(X);
  2999. // Remember this extruder's position for later tool change
  3000. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3001. // Home the 1st (left) extruder
  3002. active_extruder = 0;
  3003. HOMEAXIS(X);
  3004. // Consider the active extruder to be parked
  3005. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  3006. delayed_move_time = 0;
  3007. active_extruder_parked = true;
  3008. #else
  3009. HOMEAXIS(X);
  3010. #endif
  3011. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3012. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3013. #endif
  3014. }
  3015. #if DISABLED(HOME_Y_BEFORE_X)
  3016. // Home Y
  3017. if (home_all_axis || homeY) {
  3018. HOMEAXIS(Y);
  3019. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3020. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3021. #endif
  3022. }
  3023. #endif
  3024. // Home Z last if homing towards the bed
  3025. #if Z_HOME_DIR < 0
  3026. if (home_all_axis || homeZ) {
  3027. #if ENABLED(Z_SAFE_HOMING)
  3028. home_z_safely();
  3029. #else
  3030. HOMEAXIS(Z);
  3031. #endif
  3032. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3033. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all_axis || homeZ) > final", current_position);
  3034. #endif
  3035. } // home_all_axis || homeZ
  3036. #endif // Z_HOME_DIR < 0
  3037. SYNC_PLAN_POSITION_KINEMATIC();
  3038. #endif // !DELTA (gcode_G28)
  3039. endstops.not_homing();
  3040. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3041. // move to a height where we can use the full xy-area
  3042. do_blocking_move_to_z(delta_clip_start_height);
  3043. #endif
  3044. // Enable mesh leveling again
  3045. #if ENABLED(MESH_BED_LEVELING)
  3046. if (mbl.has_mesh()) {
  3047. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3048. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL has mesh");
  3049. #endif
  3050. if (home_all_axis || (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && homeZ)) {
  3051. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3052. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("MBL Z homing");
  3053. #endif
  3054. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  3055. #if Z_HOME_DIR > 0
  3056. + Z_MAX_POS
  3057. #endif
  3058. ;
  3059. SYNC_PLAN_POSITION_KINEMATIC();
  3060. mbl.set_active(true);
  3061. #if ENABLED(MESH_G28_REST_ORIGIN)
  3062. current_position[Z_AXIS] = 0.0;
  3063. set_destination_to_current();
  3064. line_to_destination(homing_feedrate_mm_s[Z_AXIS]);
  3065. stepper.synchronize();
  3066. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3067. if (DEBUGGING(LEVELING)) DEBUG_POS("MBL Rest Origin", current_position);
  3068. #endif
  3069. #else
  3070. planner.unapply_leveling(current_position);
  3071. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3072. if (DEBUGGING(LEVELING)) DEBUG_POS("MBL adjusted MESH_HOME_SEARCH_Z", current_position);
  3073. #endif
  3074. #endif
  3075. }
  3076. else if ((axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) && (homeX || homeY)) {
  3077. current_position[Z_AXIS] = pre_home_z;
  3078. SYNC_PLAN_POSITION_KINEMATIC();
  3079. mbl.set_active(true);
  3080. planner.unapply_leveling(current_position);
  3081. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3082. if (DEBUGGING(LEVELING)) DEBUG_POS("MBL Home X or Y", current_position);
  3083. #endif
  3084. }
  3085. }
  3086. #endif
  3087. clean_up_after_endstop_or_probe_move();
  3088. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3089. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3090. #endif
  3091. // Restore the active tool after homing
  3092. #if HOTENDS > 1
  3093. tool_change(old_tool_index, 0, true);
  3094. #endif
  3095. report_current_position();
  3096. }
  3097. #if HAS_PROBING_PROCEDURE
  3098. void out_of_range_error(const char* p_edge) {
  3099. SERIAL_PROTOCOLPGM("?Probe ");
  3100. serialprintPGM(p_edge);
  3101. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3102. }
  3103. #endif
  3104. #if ENABLED(MESH_BED_LEVELING)
  3105. inline void _mbl_goto_xy(float x, float y) {
  3106. float old_feedrate_mm_s = feedrate_mm_s;
  3107. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3108. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  3109. #if Z_CLEARANCE_BETWEEN_PROBES > Z_HOMING_HEIGHT
  3110. + Z_CLEARANCE_BETWEEN_PROBES
  3111. #elif Z_HOMING_HEIGHT > 0
  3112. + Z_HOMING_HEIGHT
  3113. #endif
  3114. ;
  3115. line_to_current_position();
  3116. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3117. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3118. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3119. line_to_current_position();
  3120. #if Z_CLEARANCE_BETWEEN_PROBES > 0 || Z_HOMING_HEIGHT > 0
  3121. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3122. current_position[Z_AXIS] = LOGICAL_Z_POSITION(MESH_HOME_SEARCH_Z);
  3123. line_to_current_position();
  3124. #endif
  3125. feedrate_mm_s = old_feedrate_mm_s;
  3126. stepper.synchronize();
  3127. }
  3128. // Save 130 bytes with non-duplication of PSTR
  3129. void say_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3130. /**
  3131. * G29: Mesh-based Z probe, probes a grid and produces a
  3132. * mesh to compensate for variable bed height
  3133. *
  3134. * Parameters With MESH_BED_LEVELING:
  3135. *
  3136. * S0 Produce a mesh report
  3137. * S1 Start probing mesh points
  3138. * S2 Probe the next mesh point
  3139. * S3 Xn Yn Zn.nn Manually modify a single point
  3140. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3141. * S5 Reset and disable mesh
  3142. *
  3143. * The S0 report the points as below
  3144. *
  3145. * +----> X-axis 1-n
  3146. * |
  3147. * |
  3148. * v Y-axis 1-n
  3149. *
  3150. */
  3151. inline void gcode_G29() {
  3152. static int probe_point = -1;
  3153. MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_byte() : MeshReport;
  3154. if (state < 0 || state > 5) {
  3155. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3156. return;
  3157. }
  3158. int8_t px, py;
  3159. switch (state) {
  3160. case MeshReport:
  3161. if (mbl.has_mesh()) {
  3162. SERIAL_PROTOCOLPAIR("State: ", mbl.active() ? MSG_ON : MSG_OFF);
  3163. SERIAL_PROTOCOLLNPGM("\nNum X,Y: " STRINGIFY(MESH_NUM_X_POINTS) "," STRINGIFY(MESH_NUM_Y_POINTS));
  3164. SERIAL_PROTOCOLLNPGM("Z search height: " STRINGIFY(MESH_HOME_SEARCH_Z));
  3165. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3166. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3167. for (py = 0; py < MESH_NUM_Y_POINTS; py++) {
  3168. for (px = 0; px < MESH_NUM_X_POINTS; px++) {
  3169. SERIAL_PROTOCOLPGM(" ");
  3170. SERIAL_PROTOCOL_F(mbl.z_values[py][px], 5);
  3171. }
  3172. SERIAL_EOL;
  3173. }
  3174. }
  3175. else
  3176. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  3177. break;
  3178. case MeshStart:
  3179. mbl.reset();
  3180. probe_point = 0;
  3181. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3182. break;
  3183. case MeshNext:
  3184. if (probe_point < 0) {
  3185. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3186. return;
  3187. }
  3188. // For each G29 S2...
  3189. if (probe_point == 0) {
  3190. // For the initial G29 S2 make Z a positive value (e.g., 4.0)
  3191. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  3192. #if Z_HOME_DIR > 0
  3193. + Z_MAX_POS
  3194. #endif
  3195. ;
  3196. SYNC_PLAN_POSITION_KINEMATIC();
  3197. }
  3198. else {
  3199. // For G29 S2 after adjusting Z.
  3200. mbl.set_zigzag_z(probe_point - 1, current_position[Z_AXIS]);
  3201. }
  3202. // If there's another point to sample, move there with optional lift.
  3203. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  3204. mbl.zigzag(probe_point, px, py);
  3205. _mbl_goto_xy(mbl.get_probe_x(px), mbl.get_probe_y(py));
  3206. probe_point++;
  3207. }
  3208. else {
  3209. // One last "return to the bed" (as originally coded) at completion
  3210. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  3211. #if Z_CLEARANCE_BETWEEN_PROBES > Z_HOMING_HEIGHT
  3212. + Z_CLEARANCE_BETWEEN_PROBES
  3213. #elif Z_HOMING_HEIGHT > 0
  3214. + Z_HOMING_HEIGHT
  3215. #endif
  3216. ;
  3217. line_to_current_position();
  3218. stepper.synchronize();
  3219. // After recording the last point, activate the mbl and home
  3220. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3221. probe_point = -1;
  3222. mbl.set_has_mesh(true);
  3223. enqueue_and_echo_commands_P(PSTR("G28"));
  3224. }
  3225. break;
  3226. case MeshSet:
  3227. if (code_seen('X')) {
  3228. px = code_value_int() - 1;
  3229. if (px < 0 || px >= MESH_NUM_X_POINTS) {
  3230. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").");
  3231. return;
  3232. }
  3233. }
  3234. else {
  3235. SERIAL_CHAR('X'); say_not_entered();
  3236. return;
  3237. }
  3238. if (code_seen('Y')) {
  3239. py = code_value_int() - 1;
  3240. if (py < 0 || py >= MESH_NUM_Y_POINTS) {
  3241. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").");
  3242. return;
  3243. }
  3244. }
  3245. else {
  3246. SERIAL_CHAR('Y'); say_not_entered();
  3247. return;
  3248. }
  3249. if (code_seen('Z')) {
  3250. mbl.z_values[py][px] = code_value_axis_units(Z_AXIS);
  3251. }
  3252. else {
  3253. SERIAL_CHAR('Z'); say_not_entered();
  3254. return;
  3255. }
  3256. break;
  3257. case MeshSetZOffset:
  3258. if (code_seen('Z')) {
  3259. mbl.z_offset = code_value_axis_units(Z_AXIS);
  3260. }
  3261. else {
  3262. SERIAL_CHAR('Z'); say_not_entered();
  3263. return;
  3264. }
  3265. break;
  3266. case MeshReset:
  3267. if (mbl.active()) {
  3268. current_position[Z_AXIS] -= MESH_HOME_SEARCH_Z;
  3269. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  3270. mbl.reset();
  3271. SYNC_PLAN_POSITION_KINEMATIC();
  3272. }
  3273. else
  3274. mbl.reset();
  3275. } // switch(state)
  3276. report_current_position();
  3277. }
  3278. #elif HAS_ABL
  3279. /**
  3280. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3281. * Will fail if the printer has not been homed with G28.
  3282. *
  3283. * Enhanced G29 Auto Bed Leveling Probe Routine
  3284. *
  3285. * Parameters With ABL_GRID:
  3286. *
  3287. * P Set the size of the grid that will be probed (P x P points).
  3288. * Not supported by non-linear delta printer bed leveling.
  3289. * Example: "G29 P4"
  3290. *
  3291. * S Set the XY travel speed between probe points (in units/min)
  3292. *
  3293. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3294. * or clean the rotation Matrix. Useful to check the topology
  3295. * after a first run of G29.
  3296. *
  3297. * V Set the verbose level (0-4). Example: "G29 V3"
  3298. *
  3299. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3300. * This is useful for manual bed leveling and finding flaws in the bed (to
  3301. * assist with part placement).
  3302. * Not supported by non-linear delta printer bed leveling.
  3303. *
  3304. * F Set the Front limit of the probing grid
  3305. * B Set the Back limit of the probing grid
  3306. * L Set the Left limit of the probing grid
  3307. * R Set the Right limit of the probing grid
  3308. *
  3309. * Global Parameters:
  3310. *
  3311. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  3312. * Include "E" to engage/disengage the Z probe for each sample.
  3313. * There's no extra effect if you have a fixed Z probe.
  3314. * Usage: "G29 E" or "G29 e"
  3315. *
  3316. */
  3317. inline void gcode_G29() {
  3318. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3319. bool query = code_seen('Q');
  3320. uint8_t old_debug_flags = marlin_debug_flags;
  3321. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3322. if (DEBUGGING(LEVELING)) {
  3323. DEBUG_POS(">>> gcode_G29", current_position);
  3324. log_machine_info();
  3325. }
  3326. marlin_debug_flags = old_debug_flags;
  3327. if (query) return;
  3328. #endif
  3329. // Don't allow auto-leveling without homing first
  3330. if (axis_unhomed_error(true, true, true)) return;
  3331. int verbose_level = code_seen('V') ? code_value_int() : 1;
  3332. if (verbose_level < 0 || verbose_level > 4) {
  3333. SERIAL_PROTOCOLLNPGM("?(V)erbose Level is implausible (0-4).");
  3334. return;
  3335. }
  3336. bool dryrun = code_seen('D'),
  3337. stow_probe_after_each = code_seen('E');
  3338. #if ABL_GRID
  3339. if (verbose_level > 0) {
  3340. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3341. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3342. }
  3343. #if ABL_PLANAR
  3344. bool do_topography_map = verbose_level > 2 || code_seen('T');
  3345. // X and Y specify points in each direction, overriding the default
  3346. // These values may be saved with the completed mesh
  3347. int abl_grid_points_x = code_seen('X') ? code_value_int() : ABL_GRID_POINTS_X,
  3348. abl_grid_points_y = code_seen('Y') ? code_value_int() : ABL_GRID_POINTS_Y;
  3349. if (code_seen('P')) abl_grid_points_x = abl_grid_points_y = code_value_int();
  3350. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3351. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3352. return;
  3353. }
  3354. #else
  3355. const int abl_grid_points_x = ABL_GRID_POINTS_X, abl_grid_points_y = ABL_GRID_POINTS_Y;
  3356. #endif
  3357. xy_probe_feedrate_mm_s = MMM_TO_MMS(code_seen('S') ? code_value_linear_units() : XY_PROBE_SPEED);
  3358. int left_probe_bed_position = code_seen('L') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION),
  3359. right_probe_bed_position = code_seen('R') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION),
  3360. front_probe_bed_position = code_seen('F') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION),
  3361. back_probe_bed_position = code_seen('B') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION);
  3362. bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3363. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3364. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3365. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3366. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3367. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3368. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3369. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3370. if (left_out || right_out || front_out || back_out) {
  3371. if (left_out) {
  3372. out_of_range_error(PSTR("(L)eft"));
  3373. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3374. }
  3375. if (right_out) {
  3376. out_of_range_error(PSTR("(R)ight"));
  3377. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3378. }
  3379. if (front_out) {
  3380. out_of_range_error(PSTR("(F)ront"));
  3381. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3382. }
  3383. if (back_out) {
  3384. out_of_range_error(PSTR("(B)ack"));
  3385. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3386. }
  3387. return;
  3388. }
  3389. #endif // ABL_GRID
  3390. stepper.synchronize();
  3391. // Disable auto bed leveling during G29
  3392. bool abl_should_enable = planner.abl_enabled;
  3393. planner.abl_enabled = false;
  3394. if (!dryrun) {
  3395. // Re-orient the current position without leveling
  3396. // based on where the steppers are positioned.
  3397. set_current_from_steppers_for_axis(ALL_AXES);
  3398. // Sync the planner to where the steppers stopped
  3399. SYNC_PLAN_POSITION_KINEMATIC();
  3400. }
  3401. setup_for_endstop_or_probe_move();
  3402. // Deploy the probe. Probe will raise if needed.
  3403. if (DEPLOY_PROBE()) {
  3404. planner.abl_enabled = abl_should_enable;
  3405. return;
  3406. }
  3407. float xProbe = 0, yProbe = 0, measured_z = 0;
  3408. #if ABL_GRID
  3409. // probe at the points of a lattice grid
  3410. const float xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1),
  3411. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3412. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3413. float zoffset = zprobe_zoffset;
  3414. if (code_seen('Z')) zoffset += code_value_axis_units(Z_AXIS);
  3415. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3416. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3417. || left_probe_bed_position != bilinear_start[X_AXIS]
  3418. || front_probe_bed_position != bilinear_start[Y_AXIS]
  3419. ) {
  3420. reset_bed_level();
  3421. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3422. bilinear_grid_spacing_virt[X_AXIS] = xGridSpacing / (BILINEAR_SUBDIVISIONS);
  3423. bilinear_grid_spacing_virt[Y_AXIS] = yGridSpacing / (BILINEAR_SUBDIVISIONS);
  3424. #endif
  3425. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3426. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3427. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3428. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3429. // Can't re-enable (on error) until the new grid is written
  3430. abl_should_enable = false;
  3431. }
  3432. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3433. /**
  3434. * solve the plane equation ax + by + d = z
  3435. * A is the matrix with rows [x y 1] for all the probed points
  3436. * B is the vector of the Z positions
  3437. * the normal vector to the plane is formed by the coefficients of the
  3438. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  3439. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3440. */
  3441. int abl2 = abl_grid_points_x * abl_grid_points_y,
  3442. indexIntoAB[abl_grid_points_x][abl_grid_points_y],
  3443. probePointCounter = -1;
  3444. float eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  3445. eqnBVector[abl2], // "B" vector of Z points
  3446. mean = 0.0;
  3447. #endif // AUTO_BED_LEVELING_LINEAR
  3448. #if ENABLED(PROBE_Y_FIRST)
  3449. #define PR_OUTER_VAR xCount
  3450. #define PR_OUTER_END abl_grid_points_x
  3451. #define PR_INNER_VAR yCount
  3452. #define PR_INNER_END abl_grid_points_y
  3453. #else
  3454. #define PR_OUTER_VAR yCount
  3455. #define PR_OUTER_END abl_grid_points_y
  3456. #define PR_INNER_VAR xCount
  3457. #define PR_INNER_END abl_grid_points_x
  3458. #endif
  3459. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3460. // Outer loop is Y with PROBE_Y_FIRST disabled
  3461. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  3462. int8_t inStart, inStop, inInc;
  3463. if (zig) { // away from origin
  3464. inStart = 0;
  3465. inStop = PR_INNER_END;
  3466. inInc = 1;
  3467. }
  3468. else { // towards origin
  3469. inStart = PR_INNER_END - 1;
  3470. inStop = -1;
  3471. inInc = -1;
  3472. }
  3473. zig = !zig; // zag
  3474. // Inner loop is Y with PROBE_Y_FIRST enabled
  3475. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  3476. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  3477. yBase = front_probe_bed_position + yGridSpacing * yCount;
  3478. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3479. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3480. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3481. indexIntoAB[xCount][yCount] = ++probePointCounter;
  3482. #endif
  3483. #if IS_KINEMATIC
  3484. // Avoid probing outside the round or hexagonal area
  3485. float pos[XYZ] = { xProbe, yProbe, 0 };
  3486. if (!position_is_reachable(pos, true)) continue;
  3487. #endif
  3488. measured_z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3489. if (measured_z == NAN) {
  3490. planner.abl_enabled = abl_should_enable;
  3491. return;
  3492. }
  3493. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3494. mean += measured_z;
  3495. eqnBVector[probePointCounter] = measured_z;
  3496. eqnAMatrix[probePointCounter + 0 * abl2] = xProbe;
  3497. eqnAMatrix[probePointCounter + 1 * abl2] = yProbe;
  3498. eqnAMatrix[probePointCounter + 2 * abl2] = 1;
  3499. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3500. bed_level_grid[xCount][yCount] = measured_z + zoffset;
  3501. #endif
  3502. idle();
  3503. } //xProbe
  3504. } //yProbe
  3505. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3506. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3507. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3508. #endif
  3509. // Probe at 3 arbitrary points
  3510. vector_3 points[3] = {
  3511. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3512. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3513. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3514. };
  3515. for (uint8_t i = 0; i < 3; ++i) {
  3516. // Retain the last probe position
  3517. xProbe = LOGICAL_X_POSITION(points[i].x);
  3518. yProbe = LOGICAL_Y_POSITION(points[i].y);
  3519. measured_z = points[i].z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3520. }
  3521. if (measured_z == NAN) {
  3522. planner.abl_enabled = abl_should_enable;
  3523. return;
  3524. }
  3525. if (!dryrun) {
  3526. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3527. if (planeNormal.z < 0) {
  3528. planeNormal.x *= -1;
  3529. planeNormal.y *= -1;
  3530. planeNormal.z *= -1;
  3531. }
  3532. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3533. // Can't re-enable (on error) until the new grid is written
  3534. abl_should_enable = false;
  3535. }
  3536. #endif // AUTO_BED_LEVELING_3POINT
  3537. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  3538. if (STOW_PROBE()) {
  3539. planner.abl_enabled = abl_should_enable;
  3540. return;
  3541. }
  3542. //
  3543. // Unless this is a dry run, auto bed leveling will
  3544. // definitely be enabled after this point
  3545. //
  3546. // Restore state after probing
  3547. clean_up_after_endstop_or_probe_move();
  3548. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3549. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  3550. #endif
  3551. // Calculate leveling, print reports, correct the position
  3552. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3553. if (!dryrun) extrapolate_unprobed_bed_level();
  3554. print_bed_level();
  3555. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3556. bed_level_virt_prepare();
  3557. bed_level_virt_interpolate();
  3558. bed_level_virt_print();
  3559. #endif
  3560. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3561. // For LINEAR leveling calculate matrix, print reports, correct the position
  3562. // solve lsq problem
  3563. float plane_equation_coefficients[3];
  3564. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  3565. mean /= abl2;
  3566. if (verbose_level) {
  3567. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3568. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  3569. SERIAL_PROTOCOLPGM(" b: ");
  3570. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  3571. SERIAL_PROTOCOLPGM(" d: ");
  3572. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  3573. SERIAL_EOL;
  3574. if (verbose_level > 2) {
  3575. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  3576. SERIAL_PROTOCOL_F(mean, 8);
  3577. SERIAL_EOL;
  3578. }
  3579. }
  3580. // Create the matrix but don't correct the position yet
  3581. if (!dryrun) {
  3582. planner.bed_level_matrix = matrix_3x3::create_look_at(
  3583. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  3584. );
  3585. }
  3586. // Show the Topography map if enabled
  3587. if (do_topography_map) {
  3588. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  3589. " +--- BACK --+\n"
  3590. " | |\n"
  3591. " L | (+) | R\n"
  3592. " E | | I\n"
  3593. " F | (-) N (+) | G\n"
  3594. " T | | H\n"
  3595. " | (-) | T\n"
  3596. " | |\n"
  3597. " O-- FRONT --+\n"
  3598. " (0,0)");
  3599. float min_diff = 999;
  3600. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  3601. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  3602. int ind = indexIntoAB[xx][yy];
  3603. float diff = eqnBVector[ind] - mean,
  3604. x_tmp = eqnAMatrix[ind + 0 * abl2],
  3605. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3606. z_tmp = 0;
  3607. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3608. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  3609. if (diff >= 0.0)
  3610. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  3611. else
  3612. SERIAL_PROTOCOLCHAR(' ');
  3613. SERIAL_PROTOCOL_F(diff, 5);
  3614. } // xx
  3615. SERIAL_EOL;
  3616. } // yy
  3617. SERIAL_EOL;
  3618. if (verbose_level > 3) {
  3619. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  3620. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  3621. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  3622. int ind = indexIntoAB[xx][yy];
  3623. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  3624. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3625. z_tmp = 0;
  3626. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3627. float diff = eqnBVector[ind] - z_tmp - min_diff;
  3628. if (diff >= 0.0)
  3629. SERIAL_PROTOCOLPGM(" +");
  3630. // Include + for column alignment
  3631. else
  3632. SERIAL_PROTOCOLCHAR(' ');
  3633. SERIAL_PROTOCOL_F(diff, 5);
  3634. } // xx
  3635. SERIAL_EOL;
  3636. } // yy
  3637. SERIAL_EOL;
  3638. }
  3639. } //do_topography_map
  3640. #endif // AUTO_BED_LEVELING_LINEAR
  3641. #if ABL_PLANAR
  3642. // For LINEAR and 3POINT leveling correct the current position
  3643. if (verbose_level > 0)
  3644. planner.bed_level_matrix.debug("\n\nBed Level Correction Matrix:");
  3645. if (!dryrun) {
  3646. //
  3647. // Correct the current XYZ position based on the tilted plane.
  3648. //
  3649. // 1. Get the distance from the current position to the reference point.
  3650. float x_dist = RAW_CURRENT_POSITION(X_AXIS) - X_TILT_FULCRUM,
  3651. y_dist = RAW_CURRENT_POSITION(Y_AXIS) - Y_TILT_FULCRUM,
  3652. z_real = current_position[Z_AXIS],
  3653. z_zero = 0;
  3654. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3655. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  3656. #endif
  3657. matrix_3x3 inverse = matrix_3x3::transpose(planner.bed_level_matrix);
  3658. // 2. Apply the inverse matrix to the distance
  3659. // from the reference point to X, Y, and zero.
  3660. apply_rotation_xyz(inverse, x_dist, y_dist, z_zero);
  3661. // 3. Get the matrix-based corrected Z.
  3662. // (Even if not used, get it for comparison.)
  3663. float new_z = z_real + z_zero;
  3664. // 4. Use the last measured distance to the bed, if possible
  3665. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  3666. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  3667. ) {
  3668. float simple_z = z_real - (measured_z - (-zprobe_zoffset));
  3669. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3670. if (DEBUGGING(LEVELING)) {
  3671. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  3672. SERIAL_ECHOPAIR(" Matrix:", new_z);
  3673. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - new_z);
  3674. }
  3675. #endif
  3676. new_z = simple_z;
  3677. }
  3678. // 5. The rotated XY and corrected Z are now current_position
  3679. current_position[X_AXIS] = LOGICAL_X_POSITION(x_dist) + X_TILT_FULCRUM;
  3680. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y_dist) + Y_TILT_FULCRUM;
  3681. current_position[Z_AXIS] = new_z;
  3682. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3683. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  3684. #endif
  3685. }
  3686. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3687. if (!dryrun) {
  3688. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3689. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  3690. #endif
  3691. // Unapply the offset because it is going to be immediately applied
  3692. // and cause compensation movement in Z
  3693. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  3694. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3695. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  3696. #endif
  3697. }
  3698. #endif // ABL_PLANAR
  3699. #ifdef Z_PROBE_END_SCRIPT
  3700. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3701. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  3702. #endif
  3703. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  3704. stepper.synchronize();
  3705. #endif
  3706. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3707. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  3708. #endif
  3709. report_current_position();
  3710. KEEPALIVE_STATE(IN_HANDLER);
  3711. // Auto Bed Leveling is complete! Enable if possible.
  3712. planner.abl_enabled = dryrun ? abl_should_enable : true;
  3713. if (planner.abl_enabled)
  3714. SYNC_PLAN_POSITION_KINEMATIC();
  3715. }
  3716. #endif // HAS_ABL
  3717. #if HAS_BED_PROBE
  3718. /**
  3719. * G30: Do a single Z probe at the current XY
  3720. * Usage:
  3721. * G30 <X#> <Y#> <S#>
  3722. * X = Probe X position (default=current probe position)
  3723. * Y = Probe Y position (default=current probe position)
  3724. * S = Stows the probe if 1 (default=1)
  3725. */
  3726. inline void gcode_G30() {
  3727. float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  3728. Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3729. float pos[XYZ] = { X_probe_location, Y_probe_location, LOGICAL_Z_POSITION(0) };
  3730. if (!position_is_reachable(pos, true)) return;
  3731. bool stow = code_seen('S') ? code_value_bool() : true;
  3732. // Disable leveling so the planner won't mess with us
  3733. #if PLANNER_LEVELING
  3734. set_bed_leveling_enabled(false);
  3735. #endif
  3736. setup_for_endstop_or_probe_move();
  3737. float measured_z = probe_pt(X_probe_location, Y_probe_location, stow, 1);
  3738. SERIAL_PROTOCOLPGM("Bed X: ");
  3739. SERIAL_PROTOCOL(X_probe_location + 0.0001);
  3740. SERIAL_PROTOCOLPGM(" Y: ");
  3741. SERIAL_PROTOCOL(Y_probe_location + 0.0001);
  3742. SERIAL_PROTOCOLPGM(" Z: ");
  3743. SERIAL_PROTOCOLLN(measured_z + 0.0001);
  3744. clean_up_after_endstop_or_probe_move();
  3745. report_current_position();
  3746. }
  3747. #if ENABLED(Z_PROBE_SLED)
  3748. /**
  3749. * G31: Deploy the Z probe
  3750. */
  3751. inline void gcode_G31() { DEPLOY_PROBE(); }
  3752. /**
  3753. * G32: Stow the Z probe
  3754. */
  3755. inline void gcode_G32() { STOW_PROBE(); }
  3756. #endif // Z_PROBE_SLED
  3757. #endif // HAS_BED_PROBE
  3758. #if ENABLED(G38_PROBE_TARGET)
  3759. static bool G38_run_probe() {
  3760. bool G38_pass_fail = false;
  3761. // Get direction of move and retract
  3762. float retract_mm[XYZ];
  3763. LOOP_XYZ(i) {
  3764. float dist = destination[i] - current_position[i];
  3765. retract_mm[i] = fabs(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  3766. }
  3767. stepper.synchronize(); // wait until the machine is idle
  3768. // Move until destination reached or target hit
  3769. endstops.enable(true);
  3770. G38_move = true;
  3771. G38_endstop_hit = false;
  3772. prepare_move_to_destination();
  3773. stepper.synchronize();
  3774. G38_move = false;
  3775. endstops.hit_on_purpose();
  3776. set_current_from_steppers_for_axis(ALL_AXES);
  3777. SYNC_PLAN_POSITION_KINEMATIC();
  3778. // Only do remaining moves if target was hit
  3779. if (G38_endstop_hit) {
  3780. G38_pass_fail = true;
  3781. // Move away by the retract distance
  3782. set_destination_to_current();
  3783. LOOP_XYZ(i) destination[i] += retract_mm[i];
  3784. endstops.enable(false);
  3785. prepare_move_to_destination();
  3786. stepper.synchronize();
  3787. feedrate_mm_s /= 4;
  3788. // Bump the target more slowly
  3789. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  3790. endstops.enable(true);
  3791. G38_move = true;
  3792. prepare_move_to_destination();
  3793. stepper.synchronize();
  3794. G38_move = false;
  3795. set_current_from_steppers_for_axis(ALL_AXES);
  3796. SYNC_PLAN_POSITION_KINEMATIC();
  3797. }
  3798. endstops.hit_on_purpose();
  3799. endstops.not_homing();
  3800. return G38_pass_fail;
  3801. }
  3802. /**
  3803. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  3804. * G38.3 - probe toward workpiece, stop on contact
  3805. *
  3806. * Like G28 except uses Z min endstop for all axes
  3807. */
  3808. inline void gcode_G38(bool is_38_2) {
  3809. // Get X Y Z E F
  3810. gcode_get_destination();
  3811. setup_for_endstop_or_probe_move();
  3812. // If any axis has enough movement, do the move
  3813. LOOP_XYZ(i)
  3814. if (fabs(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  3815. if (!code_seen('F')) feedrate_mm_s = homing_feedrate_mm_s[i];
  3816. // If G38.2 fails throw an error
  3817. if (!G38_run_probe() && is_38_2) {
  3818. SERIAL_ERROR_START;
  3819. SERIAL_ERRORLNPGM("Failed to reach target");
  3820. }
  3821. break;
  3822. }
  3823. clean_up_after_endstop_or_probe_move();
  3824. }
  3825. #endif // G38_PROBE_TARGET
  3826. /**
  3827. * G92: Set current position to given X Y Z E
  3828. */
  3829. inline void gcode_G92() {
  3830. bool didXYZ = false,
  3831. didE = code_seen('E');
  3832. if (!didE) stepper.synchronize();
  3833. LOOP_XYZE(i) {
  3834. if (code_seen(axis_codes[i])) {
  3835. #if IS_SCARA
  3836. current_position[i] = code_value_axis_units(i);
  3837. if (i != E_AXIS) didXYZ = true;
  3838. #else
  3839. float p = current_position[i],
  3840. v = code_value_axis_units(i);
  3841. current_position[i] = v;
  3842. if (i != E_AXIS) {
  3843. didXYZ = true;
  3844. position_shift[i] += v - p; // Offset the coordinate space
  3845. update_software_endstops((AxisEnum)i);
  3846. }
  3847. #endif
  3848. }
  3849. }
  3850. if (didXYZ)
  3851. SYNC_PLAN_POSITION_KINEMATIC();
  3852. else if (didE)
  3853. sync_plan_position_e();
  3854. report_current_position();
  3855. }
  3856. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  3857. /**
  3858. * M0: Unconditional stop - Wait for user button press on LCD
  3859. * M1: Conditional stop - Wait for user button press on LCD
  3860. */
  3861. inline void gcode_M0_M1() {
  3862. char* args = current_command_args;
  3863. millis_t codenum = 0;
  3864. bool hasP = false, hasS = false;
  3865. if (code_seen('P')) {
  3866. codenum = code_value_millis(); // milliseconds to wait
  3867. hasP = codenum > 0;
  3868. }
  3869. if (code_seen('S')) {
  3870. codenum = code_value_millis_from_seconds(); // seconds to wait
  3871. hasS = codenum > 0;
  3872. }
  3873. #if ENABLED(ULTIPANEL)
  3874. if (!hasP && !hasS && *args != '\0')
  3875. lcd_setstatus(args, true);
  3876. else {
  3877. LCD_MESSAGEPGM(MSG_USERWAIT);
  3878. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  3879. dontExpireStatus();
  3880. #endif
  3881. }
  3882. #else
  3883. if (!hasP && !hasS && *args != '\0') {
  3884. SERIAL_ECHO_START;
  3885. SERIAL_ECHOLN(args);
  3886. }
  3887. #endif
  3888. wait_for_user = true;
  3889. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3890. stepper.synchronize();
  3891. refresh_cmd_timeout();
  3892. if (codenum > 0) {
  3893. codenum += previous_cmd_ms; // wait until this time for a click
  3894. while (PENDING(millis(), codenum) && wait_for_user) idle();
  3895. }
  3896. else {
  3897. #if ENABLED(ULTIPANEL)
  3898. if (lcd_detected()) {
  3899. while (wait_for_user) idle();
  3900. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  3901. }
  3902. #else
  3903. while (wait_for_user) idle();
  3904. #endif
  3905. }
  3906. wait_for_user = false;
  3907. KEEPALIVE_STATE(IN_HANDLER);
  3908. }
  3909. #endif // EMERGENCY_PARSER || ULTIPANEL
  3910. /**
  3911. * M17: Enable power on all stepper motors
  3912. */
  3913. inline void gcode_M17() {
  3914. LCD_MESSAGEPGM(MSG_NO_MOVE);
  3915. enable_all_steppers();
  3916. }
  3917. #if ENABLED(SDSUPPORT)
  3918. /**
  3919. * M20: List SD card to serial output
  3920. */
  3921. inline void gcode_M20() {
  3922. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  3923. card.ls();
  3924. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  3925. }
  3926. /**
  3927. * M21: Init SD Card
  3928. */
  3929. inline void gcode_M21() { card.initsd(); }
  3930. /**
  3931. * M22: Release SD Card
  3932. */
  3933. inline void gcode_M22() { card.release(); }
  3934. /**
  3935. * M23: Open a file
  3936. */
  3937. inline void gcode_M23() { card.openFile(current_command_args, true); }
  3938. /**
  3939. * M24: Start SD Print
  3940. */
  3941. inline void gcode_M24() {
  3942. card.startFileprint();
  3943. print_job_timer.start();
  3944. }
  3945. /**
  3946. * M25: Pause SD Print
  3947. */
  3948. inline void gcode_M25() { card.pauseSDPrint(); }
  3949. /**
  3950. * M26: Set SD Card file index
  3951. */
  3952. inline void gcode_M26() {
  3953. if (card.cardOK && code_seen('S'))
  3954. card.setIndex(code_value_long());
  3955. }
  3956. /**
  3957. * M27: Get SD Card status
  3958. */
  3959. inline void gcode_M27() { card.getStatus(); }
  3960. /**
  3961. * M28: Start SD Write
  3962. */
  3963. inline void gcode_M28() { card.openFile(current_command_args, false); }
  3964. /**
  3965. * M29: Stop SD Write
  3966. * Processed in write to file routine above
  3967. */
  3968. inline void gcode_M29() {
  3969. // card.saving = false;
  3970. }
  3971. /**
  3972. * M30 <filename>: Delete SD Card file
  3973. */
  3974. inline void gcode_M30() {
  3975. if (card.cardOK) {
  3976. card.closefile();
  3977. card.removeFile(current_command_args);
  3978. }
  3979. }
  3980. #endif // SDSUPPORT
  3981. /**
  3982. * M31: Get the time since the start of SD Print (or last M109)
  3983. */
  3984. inline void gcode_M31() {
  3985. char buffer[21];
  3986. duration_t elapsed = print_job_timer.duration();
  3987. elapsed.toString(buffer);
  3988. lcd_setstatus(buffer);
  3989. SERIAL_ECHO_START;
  3990. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  3991. #if ENABLED(AUTOTEMP)
  3992. thermalManager.autotempShutdown();
  3993. #endif
  3994. }
  3995. #if ENABLED(SDSUPPORT)
  3996. /**
  3997. * M32: Select file and start SD Print
  3998. */
  3999. inline void gcode_M32() {
  4000. if (card.sdprinting)
  4001. stepper.synchronize();
  4002. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  4003. if (!namestartpos)
  4004. namestartpos = current_command_args; // Default name position, 4 letters after the M
  4005. else
  4006. namestartpos++; //to skip the '!'
  4007. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  4008. if (card.cardOK) {
  4009. card.openFile(namestartpos, true, call_procedure);
  4010. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  4011. card.setIndex(code_value_long());
  4012. card.startFileprint();
  4013. // Procedure calls count as normal print time.
  4014. if (!call_procedure) print_job_timer.start();
  4015. }
  4016. }
  4017. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  4018. /**
  4019. * M33: Get the long full path of a file or folder
  4020. *
  4021. * Parameters:
  4022. * <dospath> Case-insensitive DOS-style path to a file or folder
  4023. *
  4024. * Example:
  4025. * M33 miscel~1/armchair/armcha~1.gco
  4026. *
  4027. * Output:
  4028. * /Miscellaneous/Armchair/Armchair.gcode
  4029. */
  4030. inline void gcode_M33() {
  4031. card.printLongPath(current_command_args);
  4032. }
  4033. #endif
  4034. /**
  4035. * M928: Start SD Write
  4036. */
  4037. inline void gcode_M928() {
  4038. card.openLogFile(current_command_args);
  4039. }
  4040. #endif // SDSUPPORT
  4041. /**
  4042. * Sensitive pin test for M42, M226
  4043. */
  4044. static bool pin_is_protected(uint8_t pin) {
  4045. static const int sensitive_pins[] = SENSITIVE_PINS;
  4046. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  4047. if (sensitive_pins[i] == pin) return true;
  4048. return false;
  4049. }
  4050. /**
  4051. * M42: Change pin status via GCode
  4052. *
  4053. * P<pin> Pin number (LED if omitted)
  4054. * S<byte> Pin status from 0 - 255
  4055. */
  4056. inline void gcode_M42() {
  4057. if (!code_seen('S')) return;
  4058. int pin_status = code_value_int();
  4059. if (pin_status < 0 || pin_status > 255) return;
  4060. int pin_number = code_seen('P') ? code_value_int() : LED_PIN;
  4061. if (pin_number < 0) return;
  4062. if (pin_is_protected(pin_number)) {
  4063. SERIAL_ERROR_START;
  4064. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  4065. return;
  4066. }
  4067. pinMode(pin_number, OUTPUT);
  4068. digitalWrite(pin_number, pin_status);
  4069. analogWrite(pin_number, pin_status);
  4070. #if FAN_COUNT > 0
  4071. switch (pin_number) {
  4072. #if HAS_FAN0
  4073. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  4074. #endif
  4075. #if HAS_FAN1
  4076. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  4077. #endif
  4078. #if HAS_FAN2
  4079. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  4080. #endif
  4081. }
  4082. #endif
  4083. }
  4084. #if ENABLED(PINS_DEBUGGING)
  4085. #include "pinsDebug.h"
  4086. /**
  4087. * M43: Pin report and debug
  4088. *
  4089. * E<bool> Enable / disable background endstop monitoring
  4090. * - Machine continues to operate
  4091. * - Reports changes to endstops
  4092. * - Toggles LED when an endstop changes
  4093. *
  4094. * or
  4095. *
  4096. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  4097. * W<bool> Watch pins -reporting changes- until reset, click, or M108.
  4098. * I<bool> Flag to ignore Marlin's pin protection.
  4099. *
  4100. */
  4101. inline void gcode_M43() {
  4102. // Enable or disable endstop monitoring
  4103. if (code_seen('E')) {
  4104. endstop_monitor_flag = code_value_bool();
  4105. SERIAL_PROTOCOLPGM("endstop monitor ");
  4106. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  4107. SERIAL_PROTOCOLLNPGM("abled");
  4108. return;
  4109. }
  4110. // Get the range of pins to test or watch
  4111. int first_pin = 0, last_pin = NUM_DIGITAL_PINS - 1;
  4112. if (code_seen('P')) {
  4113. first_pin = last_pin = code_value_byte();
  4114. if (first_pin > NUM_DIGITAL_PINS - 1) return;
  4115. }
  4116. bool ignore_protection = code_seen('I') ? code_value_bool() : false;
  4117. // Watch until click, M108, or reset
  4118. if (code_seen('W') && code_value_bool()) { // watch digital pins
  4119. byte pin_state[last_pin - first_pin + 1];
  4120. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  4121. if (pin_is_protected(pin) && !ignore_protection) continue;
  4122. pinMode(pin, INPUT_PULLUP);
  4123. // if (IS_ANALOG(pin))
  4124. // pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  4125. // else
  4126. pin_state[pin - first_pin] = digitalRead(pin);
  4127. }
  4128. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  4129. wait_for_user = true;
  4130. #endif
  4131. for(;;) {
  4132. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  4133. if (pin_is_protected(pin)) continue;
  4134. byte val;
  4135. // if (IS_ANALOG(pin))
  4136. // val = analogRead(pin - analogInputToDigitalPin(0)); // int16_t val
  4137. // else
  4138. val = digitalRead(pin);
  4139. if (val != pin_state[pin - first_pin]) {
  4140. report_pin_state(pin);
  4141. pin_state[pin - first_pin] = val;
  4142. }
  4143. }
  4144. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  4145. if (!wait_for_user) break;
  4146. #endif
  4147. safe_delay(500);
  4148. }
  4149. return;
  4150. }
  4151. // Report current state of selected pin(s)
  4152. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  4153. report_pin_state_extended(pin, ignore_protection);
  4154. }
  4155. #endif // PINS_DEBUGGING
  4156. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  4157. /**
  4158. * M48: Z probe repeatability measurement function.
  4159. *
  4160. * Usage:
  4161. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  4162. * P = Number of sampled points (4-50, default 10)
  4163. * X = Sample X position
  4164. * Y = Sample Y position
  4165. * V = Verbose level (0-4, default=1)
  4166. * E = Engage Z probe for each reading
  4167. * L = Number of legs of movement before probe
  4168. * S = Schizoid (Or Star if you prefer)
  4169. *
  4170. * This function assumes the bed has been homed. Specifically, that a G28 command
  4171. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  4172. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4173. * regenerated.
  4174. */
  4175. inline void gcode_M48() {
  4176. if (axis_unhomed_error(true, true, true)) return;
  4177. int8_t verbose_level = code_seen('V') ? code_value_byte() : 1;
  4178. if (verbose_level < 0 || verbose_level > 4) {
  4179. SERIAL_PROTOCOLLNPGM("?Verbose Level not plausible (0-4).");
  4180. return;
  4181. }
  4182. if (verbose_level > 0)
  4183. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  4184. int8_t n_samples = code_seen('P') ? code_value_byte() : 10;
  4185. if (n_samples < 4 || n_samples > 50) {
  4186. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  4187. return;
  4188. }
  4189. float X_current = current_position[X_AXIS],
  4190. Y_current = current_position[Y_AXIS];
  4191. bool stow_probe_after_each = code_seen('E');
  4192. float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : X_current + X_PROBE_OFFSET_FROM_EXTRUDER;
  4193. #if DISABLED(DELTA)
  4194. if (X_probe_location < LOGICAL_X_POSITION(MIN_PROBE_X) || X_probe_location > LOGICAL_X_POSITION(MAX_PROBE_X)) {
  4195. out_of_range_error(PSTR("X"));
  4196. return;
  4197. }
  4198. #endif
  4199. float Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4200. #if DISABLED(DELTA)
  4201. if (Y_probe_location < LOGICAL_Y_POSITION(MIN_PROBE_Y) || Y_probe_location > LOGICAL_Y_POSITION(MAX_PROBE_Y)) {
  4202. out_of_range_error(PSTR("Y"));
  4203. return;
  4204. }
  4205. #else
  4206. float pos[XYZ] = { X_probe_location, Y_probe_location, 0 };
  4207. if (!position_is_reachable(pos, true)) {
  4208. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  4209. return;
  4210. }
  4211. #endif
  4212. bool seen_L = code_seen('L');
  4213. uint8_t n_legs = seen_L ? code_value_byte() : 0;
  4214. if (n_legs > 15) {
  4215. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  4216. return;
  4217. }
  4218. if (n_legs == 1) n_legs = 2;
  4219. bool schizoid_flag = code_seen('S');
  4220. if (schizoid_flag && !seen_L) n_legs = 7;
  4221. /**
  4222. * Now get everything to the specified probe point So we can safely do a
  4223. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  4224. * we don't want to use that as a starting point for each probe.
  4225. */
  4226. if (verbose_level > 2)
  4227. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  4228. // Disable bed level correction in M48 because we want the raw data when we probe
  4229. #if HAS_ABL
  4230. reset_bed_level();
  4231. #endif
  4232. setup_for_endstop_or_probe_move();
  4233. // Move to the first point, deploy, and probe
  4234. probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  4235. randomSeed(millis());
  4236. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  4237. for (uint8_t n = 0; n < n_samples; n++) {
  4238. if (n_legs) {
  4239. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  4240. float angle = random(0.0, 360.0),
  4241. radius = random(
  4242. #if ENABLED(DELTA)
  4243. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  4244. #else
  4245. 5, X_MAX_LENGTH / 8
  4246. #endif
  4247. );
  4248. if (verbose_level > 3) {
  4249. SERIAL_ECHOPAIR("Starting radius: ", radius);
  4250. SERIAL_ECHOPAIR(" angle: ", angle);
  4251. SERIAL_ECHOPGM(" Direction: ");
  4252. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  4253. SERIAL_ECHOLNPGM("Clockwise");
  4254. }
  4255. for (uint8_t l = 0; l < n_legs - 1; l++) {
  4256. double delta_angle;
  4257. if (schizoid_flag)
  4258. // The points of a 5 point star are 72 degrees apart. We need to
  4259. // skip a point and go to the next one on the star.
  4260. delta_angle = dir * 2.0 * 72.0;
  4261. else
  4262. // If we do this line, we are just trying to move further
  4263. // around the circle.
  4264. delta_angle = dir * (float) random(25, 45);
  4265. angle += delta_angle;
  4266. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  4267. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  4268. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  4269. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  4270. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  4271. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  4272. #if DISABLED(DELTA)
  4273. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  4274. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  4275. #else
  4276. // If we have gone out too far, we can do a simple fix and scale the numbers
  4277. // back in closer to the origin.
  4278. while (HYPOT(X_current, Y_current) > DELTA_PROBEABLE_RADIUS) {
  4279. X_current /= 1.25;
  4280. Y_current /= 1.25;
  4281. if (verbose_level > 3) {
  4282. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  4283. SERIAL_ECHOLNPAIR(", ", Y_current);
  4284. }
  4285. }
  4286. #endif
  4287. if (verbose_level > 3) {
  4288. SERIAL_PROTOCOLPGM("Going to:");
  4289. SERIAL_ECHOPAIR(" X", X_current);
  4290. SERIAL_ECHOPAIR(" Y", Y_current);
  4291. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  4292. }
  4293. do_blocking_move_to_xy(X_current, Y_current);
  4294. } // n_legs loop
  4295. } // n_legs
  4296. // Probe a single point
  4297. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  4298. /**
  4299. * Get the current mean for the data points we have so far
  4300. */
  4301. double sum = 0.0;
  4302. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  4303. mean = sum / (n + 1);
  4304. NOMORE(min, sample_set[n]);
  4305. NOLESS(max, sample_set[n]);
  4306. /**
  4307. * Now, use that mean to calculate the standard deviation for the
  4308. * data points we have so far
  4309. */
  4310. sum = 0.0;
  4311. for (uint8_t j = 0; j <= n; j++)
  4312. sum += sq(sample_set[j] - mean);
  4313. sigma = sqrt(sum / (n + 1));
  4314. if (verbose_level > 0) {
  4315. if (verbose_level > 1) {
  4316. SERIAL_PROTOCOL(n + 1);
  4317. SERIAL_PROTOCOLPGM(" of ");
  4318. SERIAL_PROTOCOL((int)n_samples);
  4319. SERIAL_PROTOCOLPGM(": z: ");
  4320. SERIAL_PROTOCOL_F(sample_set[n], 3);
  4321. if (verbose_level > 2) {
  4322. SERIAL_PROTOCOLPGM(" mean: ");
  4323. SERIAL_PROTOCOL_F(mean, 4);
  4324. SERIAL_PROTOCOLPGM(" sigma: ");
  4325. SERIAL_PROTOCOL_F(sigma, 6);
  4326. SERIAL_PROTOCOLPGM(" min: ");
  4327. SERIAL_PROTOCOL_F(min, 3);
  4328. SERIAL_PROTOCOLPGM(" max: ");
  4329. SERIAL_PROTOCOL_F(max, 3);
  4330. SERIAL_PROTOCOLPGM(" range: ");
  4331. SERIAL_PROTOCOL_F(max-min, 3);
  4332. }
  4333. }
  4334. SERIAL_EOL;
  4335. }
  4336. } // End of probe loop
  4337. if (STOW_PROBE()) return;
  4338. SERIAL_PROTOCOLPGM("Finished!");
  4339. SERIAL_EOL;
  4340. if (verbose_level > 0) {
  4341. SERIAL_PROTOCOLPGM("Mean: ");
  4342. SERIAL_PROTOCOL_F(mean, 6);
  4343. SERIAL_PROTOCOLPGM(" Min: ");
  4344. SERIAL_PROTOCOL_F(min, 3);
  4345. SERIAL_PROTOCOLPGM(" Max: ");
  4346. SERIAL_PROTOCOL_F(max, 3);
  4347. SERIAL_PROTOCOLPGM(" Range: ");
  4348. SERIAL_PROTOCOL_F(max-min, 3);
  4349. SERIAL_EOL;
  4350. }
  4351. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  4352. SERIAL_PROTOCOL_F(sigma, 6);
  4353. SERIAL_EOL;
  4354. SERIAL_EOL;
  4355. clean_up_after_endstop_or_probe_move();
  4356. report_current_position();
  4357. }
  4358. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  4359. /**
  4360. * M75: Start print timer
  4361. */
  4362. inline void gcode_M75() { print_job_timer.start(); }
  4363. /**
  4364. * M76: Pause print timer
  4365. */
  4366. inline void gcode_M76() { print_job_timer.pause(); }
  4367. /**
  4368. * M77: Stop print timer
  4369. */
  4370. inline void gcode_M77() { print_job_timer.stop(); }
  4371. #if ENABLED(PRINTCOUNTER)
  4372. /**
  4373. * M78: Show print statistics
  4374. */
  4375. inline void gcode_M78() {
  4376. // "M78 S78" will reset the statistics
  4377. if (code_seen('S') && code_value_int() == 78)
  4378. print_job_timer.initStats();
  4379. else
  4380. print_job_timer.showStats();
  4381. }
  4382. #endif
  4383. /**
  4384. * M104: Set hot end temperature
  4385. */
  4386. inline void gcode_M104() {
  4387. if (get_target_extruder_from_command(104)) return;
  4388. if (DEBUGGING(DRYRUN)) return;
  4389. #if ENABLED(SINGLENOZZLE)
  4390. if (target_extruder != active_extruder) return;
  4391. #endif
  4392. if (code_seen('S')) {
  4393. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  4394. #if ENABLED(DUAL_X_CARRIAGE)
  4395. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  4396. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  4397. #endif
  4398. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4399. /**
  4400. * Stop the timer at the end of print, starting is managed by
  4401. * 'heat and wait' M109.
  4402. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  4403. * stand by mode, for instance in a dual extruder setup, without affecting
  4404. * the running print timer.
  4405. */
  4406. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  4407. print_job_timer.stop();
  4408. LCD_MESSAGEPGM(WELCOME_MSG);
  4409. }
  4410. #endif
  4411. if (code_value_temp_abs() > thermalManager.degHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING);
  4412. }
  4413. #if ENABLED(AUTOTEMP)
  4414. planner.autotemp_M104_M109();
  4415. #endif
  4416. }
  4417. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  4418. void print_heaterstates() {
  4419. #if HAS_TEMP_HOTEND
  4420. SERIAL_PROTOCOLPGM(" T:");
  4421. SERIAL_PROTOCOL_F(thermalManager.degHotend(target_extruder), 1);
  4422. SERIAL_PROTOCOLPGM(" /");
  4423. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(target_extruder), 1);
  4424. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4425. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[target_extruder] / OVERSAMPLENR);
  4426. SERIAL_CHAR(')');
  4427. #endif
  4428. #endif
  4429. #if HAS_TEMP_BED
  4430. SERIAL_PROTOCOLPGM(" B:");
  4431. SERIAL_PROTOCOL_F(thermalManager.degBed(), 1);
  4432. SERIAL_PROTOCOLPGM(" /");
  4433. SERIAL_PROTOCOL_F(thermalManager.degTargetBed(), 1);
  4434. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4435. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_bed_raw / OVERSAMPLENR);
  4436. SERIAL_CHAR(')');
  4437. #endif
  4438. #endif
  4439. #if HOTENDS > 1
  4440. HOTEND_LOOP() {
  4441. SERIAL_PROTOCOLPAIR(" T", e);
  4442. SERIAL_PROTOCOLCHAR(':');
  4443. SERIAL_PROTOCOL_F(thermalManager.degHotend(e), 1);
  4444. SERIAL_PROTOCOLPGM(" /");
  4445. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(e), 1);
  4446. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4447. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[e] / OVERSAMPLENR);
  4448. SERIAL_CHAR(')');
  4449. #endif
  4450. }
  4451. #endif
  4452. SERIAL_PROTOCOLPGM(" @:");
  4453. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  4454. #if HAS_TEMP_BED
  4455. SERIAL_PROTOCOLPGM(" B@:");
  4456. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  4457. #endif
  4458. #if HOTENDS > 1
  4459. HOTEND_LOOP() {
  4460. SERIAL_PROTOCOLPAIR(" @", e);
  4461. SERIAL_PROTOCOLCHAR(':');
  4462. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  4463. }
  4464. #endif
  4465. }
  4466. #endif
  4467. /**
  4468. * M105: Read hot end and bed temperature
  4469. */
  4470. inline void gcode_M105() {
  4471. if (get_target_extruder_from_command(105)) return;
  4472. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  4473. SERIAL_PROTOCOLPGM(MSG_OK);
  4474. print_heaterstates();
  4475. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  4476. SERIAL_ERROR_START;
  4477. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  4478. #endif
  4479. SERIAL_EOL;
  4480. }
  4481. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  4482. static uint8_t auto_report_temp_interval;
  4483. static millis_t next_temp_report_ms;
  4484. /**
  4485. * M155: Set temperature auto-report interval. M155 S<seconds>
  4486. */
  4487. inline void gcode_M155() {
  4488. if (code_seen('S')) {
  4489. auto_report_temp_interval = code_value_byte();
  4490. NOMORE(auto_report_temp_interval, 60);
  4491. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  4492. }
  4493. }
  4494. inline void auto_report_temperatures() {
  4495. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  4496. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  4497. print_heaterstates();
  4498. SERIAL_EOL;
  4499. }
  4500. }
  4501. #endif // AUTO_REPORT_TEMPERATURES
  4502. #if FAN_COUNT > 0
  4503. /**
  4504. * M106: Set Fan Speed
  4505. *
  4506. * S<int> Speed between 0-255
  4507. * P<index> Fan index, if more than one fan
  4508. */
  4509. inline void gcode_M106() {
  4510. uint16_t s = code_seen('S') ? code_value_ushort() : 255,
  4511. p = code_seen('P') ? code_value_ushort() : 0;
  4512. NOMORE(s, 255);
  4513. if (p < FAN_COUNT) fanSpeeds[p] = s;
  4514. }
  4515. /**
  4516. * M107: Fan Off
  4517. */
  4518. inline void gcode_M107() {
  4519. uint16_t p = code_seen('P') ? code_value_ushort() : 0;
  4520. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  4521. }
  4522. #endif // FAN_COUNT > 0
  4523. #if DISABLED(EMERGENCY_PARSER)
  4524. /**
  4525. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  4526. */
  4527. inline void gcode_M108() { wait_for_heatup = false; }
  4528. /**
  4529. * M112: Emergency Stop
  4530. */
  4531. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  4532. /**
  4533. * M410: Quickstop - Abort all planned moves
  4534. *
  4535. * This will stop the carriages mid-move, so most likely they
  4536. * will be out of sync with the stepper position after this.
  4537. */
  4538. inline void gcode_M410() { quickstop_stepper(); }
  4539. #endif
  4540. #ifndef MIN_COOLING_SLOPE_DEG
  4541. #define MIN_COOLING_SLOPE_DEG 1.50
  4542. #endif
  4543. #ifndef MIN_COOLING_SLOPE_TIME
  4544. #define MIN_COOLING_SLOPE_TIME 60
  4545. #endif
  4546. /**
  4547. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  4548. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  4549. */
  4550. inline void gcode_M109() {
  4551. if (get_target_extruder_from_command(109)) return;
  4552. if (DEBUGGING(DRYRUN)) return;
  4553. #if ENABLED(SINGLENOZZLE)
  4554. if (target_extruder != active_extruder) return;
  4555. #endif
  4556. bool no_wait_for_cooling = code_seen('S');
  4557. if (no_wait_for_cooling || code_seen('R')) {
  4558. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  4559. #if ENABLED(DUAL_X_CARRIAGE)
  4560. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  4561. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  4562. #endif
  4563. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4564. /**
  4565. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  4566. * stand by mode, for instance in a dual extruder setup, without affecting
  4567. * the running print timer.
  4568. */
  4569. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  4570. print_job_timer.stop();
  4571. LCD_MESSAGEPGM(WELCOME_MSG);
  4572. }
  4573. /**
  4574. * We do not check if the timer is already running because this check will
  4575. * be done for us inside the Stopwatch::start() method thus a running timer
  4576. * will not restart.
  4577. */
  4578. else print_job_timer.start();
  4579. #endif
  4580. if (thermalManager.isHeatingHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING);
  4581. }
  4582. #if ENABLED(AUTOTEMP)
  4583. planner.autotemp_M104_M109();
  4584. #endif
  4585. #if TEMP_RESIDENCY_TIME > 0
  4586. millis_t residency_start_ms = 0;
  4587. // Loop until the temperature has stabilized
  4588. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  4589. #else
  4590. // Loop until the temperature is very close target
  4591. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  4592. #endif //TEMP_RESIDENCY_TIME > 0
  4593. float theTarget = -1.0, old_temp = 9999.0;
  4594. bool wants_to_cool = false;
  4595. wait_for_heatup = true;
  4596. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  4597. KEEPALIVE_STATE(NOT_BUSY);
  4598. do {
  4599. // Target temperature might be changed during the loop
  4600. if (theTarget != thermalManager.degTargetHotend(target_extruder)) {
  4601. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  4602. theTarget = thermalManager.degTargetHotend(target_extruder);
  4603. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  4604. if (no_wait_for_cooling && wants_to_cool) break;
  4605. }
  4606. now = millis();
  4607. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  4608. next_temp_ms = now + 1000UL;
  4609. print_heaterstates();
  4610. #if TEMP_RESIDENCY_TIME > 0
  4611. SERIAL_PROTOCOLPGM(" W:");
  4612. if (residency_start_ms) {
  4613. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  4614. SERIAL_PROTOCOLLN(rem);
  4615. }
  4616. else {
  4617. SERIAL_PROTOCOLLNPGM("?");
  4618. }
  4619. #else
  4620. SERIAL_EOL;
  4621. #endif
  4622. }
  4623. idle();
  4624. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  4625. float temp = thermalManager.degHotend(target_extruder);
  4626. #if TEMP_RESIDENCY_TIME > 0
  4627. float temp_diff = fabs(theTarget - temp);
  4628. if (!residency_start_ms) {
  4629. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  4630. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  4631. }
  4632. else if (temp_diff > TEMP_HYSTERESIS) {
  4633. // Restart the timer whenever the temperature falls outside the hysteresis.
  4634. residency_start_ms = now;
  4635. }
  4636. #endif //TEMP_RESIDENCY_TIME > 0
  4637. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  4638. if (wants_to_cool) {
  4639. // break after MIN_COOLING_SLOPE_TIME seconds
  4640. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  4641. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  4642. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  4643. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  4644. old_temp = temp;
  4645. }
  4646. }
  4647. } while (wait_for_heatup && TEMP_CONDITIONS);
  4648. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  4649. KEEPALIVE_STATE(IN_HANDLER);
  4650. }
  4651. #if HAS_TEMP_BED
  4652. #ifndef MIN_COOLING_SLOPE_DEG_BED
  4653. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  4654. #endif
  4655. #ifndef MIN_COOLING_SLOPE_TIME_BED
  4656. #define MIN_COOLING_SLOPE_TIME_BED 60
  4657. #endif
  4658. /**
  4659. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  4660. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  4661. */
  4662. inline void gcode_M190() {
  4663. if (DEBUGGING(DRYRUN)) return;
  4664. LCD_MESSAGEPGM(MSG_BED_HEATING);
  4665. bool no_wait_for_cooling = code_seen('S');
  4666. if (no_wait_for_cooling || code_seen('R')) {
  4667. thermalManager.setTargetBed(code_value_temp_abs());
  4668. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4669. if (code_value_temp_abs() > BED_MINTEMP) {
  4670. /**
  4671. * We start the timer when 'heating and waiting' command arrives, LCD
  4672. * functions never wait. Cooling down managed by extruders.
  4673. *
  4674. * We do not check if the timer is already running because this check will
  4675. * be done for us inside the Stopwatch::start() method thus a running timer
  4676. * will not restart.
  4677. */
  4678. print_job_timer.start();
  4679. }
  4680. #endif
  4681. }
  4682. #if TEMP_BED_RESIDENCY_TIME > 0
  4683. millis_t residency_start_ms = 0;
  4684. // Loop until the temperature has stabilized
  4685. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  4686. #else
  4687. // Loop until the temperature is very close target
  4688. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  4689. #endif //TEMP_BED_RESIDENCY_TIME > 0
  4690. float theTarget = -1.0, old_temp = 9999.0;
  4691. bool wants_to_cool = false;
  4692. wait_for_heatup = true;
  4693. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  4694. KEEPALIVE_STATE(NOT_BUSY);
  4695. target_extruder = active_extruder; // for print_heaterstates
  4696. do {
  4697. // Target temperature might be changed during the loop
  4698. if (theTarget != thermalManager.degTargetBed()) {
  4699. wants_to_cool = thermalManager.isCoolingBed();
  4700. theTarget = thermalManager.degTargetBed();
  4701. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  4702. if (no_wait_for_cooling && wants_to_cool) break;
  4703. }
  4704. now = millis();
  4705. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  4706. next_temp_ms = now + 1000UL;
  4707. print_heaterstates();
  4708. #if TEMP_BED_RESIDENCY_TIME > 0
  4709. SERIAL_PROTOCOLPGM(" W:");
  4710. if (residency_start_ms) {
  4711. long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  4712. SERIAL_PROTOCOLLN(rem);
  4713. }
  4714. else {
  4715. SERIAL_PROTOCOLLNPGM("?");
  4716. }
  4717. #else
  4718. SERIAL_EOL;
  4719. #endif
  4720. }
  4721. idle();
  4722. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  4723. float temp = thermalManager.degBed();
  4724. #if TEMP_BED_RESIDENCY_TIME > 0
  4725. float temp_diff = fabs(theTarget - temp);
  4726. if (!residency_start_ms) {
  4727. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  4728. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  4729. }
  4730. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  4731. // Restart the timer whenever the temperature falls outside the hysteresis.
  4732. residency_start_ms = now;
  4733. }
  4734. #endif //TEMP_BED_RESIDENCY_TIME > 0
  4735. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  4736. if (wants_to_cool) {
  4737. // break after MIN_COOLING_SLOPE_TIME_BED seconds
  4738. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  4739. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  4740. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  4741. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  4742. old_temp = temp;
  4743. }
  4744. }
  4745. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  4746. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  4747. KEEPALIVE_STATE(IN_HANDLER);
  4748. }
  4749. #endif // HAS_TEMP_BED
  4750. /**
  4751. * M110: Set Current Line Number
  4752. */
  4753. inline void gcode_M110() {
  4754. if (code_seen('N')) gcode_N = code_value_long();
  4755. }
  4756. /**
  4757. * M111: Set the debug level
  4758. */
  4759. inline void gcode_M111() {
  4760. marlin_debug_flags = code_seen('S') ? code_value_byte() : (uint8_t) DEBUG_NONE;
  4761. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  4762. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  4763. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  4764. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  4765. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  4766. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4767. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  4768. #endif
  4769. const static char* const debug_strings[] PROGMEM = {
  4770. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16,
  4771. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4772. str_debug_32
  4773. #endif
  4774. };
  4775. SERIAL_ECHO_START;
  4776. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  4777. if (marlin_debug_flags) {
  4778. uint8_t comma = 0;
  4779. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  4780. if (TEST(marlin_debug_flags, i)) {
  4781. if (comma++) SERIAL_CHAR(',');
  4782. serialprintPGM((char*)pgm_read_word(&(debug_strings[i])));
  4783. }
  4784. }
  4785. }
  4786. else {
  4787. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  4788. }
  4789. SERIAL_EOL;
  4790. }
  4791. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  4792. /**
  4793. * M113: Get or set Host Keepalive interval (0 to disable)
  4794. *
  4795. * S<seconds> Optional. Set the keepalive interval.
  4796. */
  4797. inline void gcode_M113() {
  4798. if (code_seen('S')) {
  4799. host_keepalive_interval = code_value_byte();
  4800. NOMORE(host_keepalive_interval, 60);
  4801. }
  4802. else {
  4803. SERIAL_ECHO_START;
  4804. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  4805. }
  4806. }
  4807. #endif
  4808. #if ENABLED(BARICUDA)
  4809. #if HAS_HEATER_1
  4810. /**
  4811. * M126: Heater 1 valve open
  4812. */
  4813. inline void gcode_M126() { baricuda_valve_pressure = code_seen('S') ? code_value_byte() : 255; }
  4814. /**
  4815. * M127: Heater 1 valve close
  4816. */
  4817. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  4818. #endif
  4819. #if HAS_HEATER_2
  4820. /**
  4821. * M128: Heater 2 valve open
  4822. */
  4823. inline void gcode_M128() { baricuda_e_to_p_pressure = code_seen('S') ? code_value_byte() : 255; }
  4824. /**
  4825. * M129: Heater 2 valve close
  4826. */
  4827. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  4828. #endif
  4829. #endif //BARICUDA
  4830. /**
  4831. * M140: Set bed temperature
  4832. */
  4833. inline void gcode_M140() {
  4834. if (DEBUGGING(DRYRUN)) return;
  4835. if (code_seen('S')) thermalManager.setTargetBed(code_value_temp_abs());
  4836. }
  4837. #if ENABLED(ULTIPANEL)
  4838. /**
  4839. * M145: Set the heatup state for a material in the LCD menu
  4840. * S<material> (0=PLA, 1=ABS)
  4841. * H<hotend temp>
  4842. * B<bed temp>
  4843. * F<fan speed>
  4844. */
  4845. inline void gcode_M145() {
  4846. uint8_t material = code_seen('S') ? (uint8_t)code_value_int() : 0;
  4847. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  4848. SERIAL_ERROR_START;
  4849. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  4850. }
  4851. else {
  4852. int v;
  4853. if (code_seen('H')) {
  4854. v = code_value_int();
  4855. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  4856. }
  4857. if (code_seen('F')) {
  4858. v = code_value_int();
  4859. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  4860. }
  4861. #if TEMP_SENSOR_BED != 0
  4862. if (code_seen('B')) {
  4863. v = code_value_int();
  4864. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  4865. }
  4866. #endif
  4867. }
  4868. }
  4869. #endif // ULTIPANEL
  4870. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  4871. /**
  4872. * M149: Set temperature units
  4873. */
  4874. inline void gcode_M149() {
  4875. if (code_seen('C')) set_input_temp_units(TEMPUNIT_C);
  4876. else if (code_seen('K')) set_input_temp_units(TEMPUNIT_K);
  4877. else if (code_seen('F')) set_input_temp_units(TEMPUNIT_F);
  4878. }
  4879. #endif
  4880. #if HAS_POWER_SWITCH
  4881. /**
  4882. * M80: Turn on Power Supply
  4883. */
  4884. inline void gcode_M80() {
  4885. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  4886. /**
  4887. * If you have a switch on suicide pin, this is useful
  4888. * if you want to start another print with suicide feature after
  4889. * a print without suicide...
  4890. */
  4891. #if HAS_SUICIDE
  4892. OUT_WRITE(SUICIDE_PIN, HIGH);
  4893. #endif
  4894. #if ENABLED(ULTIPANEL)
  4895. powersupply = true;
  4896. LCD_MESSAGEPGM(WELCOME_MSG);
  4897. lcd_update();
  4898. #endif
  4899. }
  4900. #endif // HAS_POWER_SWITCH
  4901. /**
  4902. * M81: Turn off Power, including Power Supply, if there is one.
  4903. *
  4904. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  4905. */
  4906. inline void gcode_M81() {
  4907. thermalManager.disable_all_heaters();
  4908. stepper.finish_and_disable();
  4909. #if FAN_COUNT > 0
  4910. #if FAN_COUNT > 1
  4911. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  4912. #else
  4913. fanSpeeds[0] = 0;
  4914. #endif
  4915. #endif
  4916. delay(1000); // Wait 1 second before switching off
  4917. #if HAS_SUICIDE
  4918. stepper.synchronize();
  4919. suicide();
  4920. #elif HAS_POWER_SWITCH
  4921. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  4922. #endif
  4923. #if ENABLED(ULTIPANEL)
  4924. #if HAS_POWER_SWITCH
  4925. powersupply = false;
  4926. #endif
  4927. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  4928. lcd_update();
  4929. #endif
  4930. }
  4931. /**
  4932. * M82: Set E codes absolute (default)
  4933. */
  4934. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  4935. /**
  4936. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  4937. */
  4938. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  4939. /**
  4940. * M18, M84: Disable all stepper motors
  4941. */
  4942. inline void gcode_M18_M84() {
  4943. if (code_seen('S')) {
  4944. stepper_inactive_time = code_value_millis_from_seconds();
  4945. }
  4946. else {
  4947. bool all_axis = !((code_seen('X')) || (code_seen('Y')) || (code_seen('Z')) || (code_seen('E')));
  4948. if (all_axis) {
  4949. stepper.finish_and_disable();
  4950. }
  4951. else {
  4952. stepper.synchronize();
  4953. if (code_seen('X')) disable_x();
  4954. if (code_seen('Y')) disable_y();
  4955. if (code_seen('Z')) disable_z();
  4956. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  4957. if (code_seen('E')) {
  4958. disable_e0();
  4959. disable_e1();
  4960. disable_e2();
  4961. disable_e3();
  4962. }
  4963. #endif
  4964. }
  4965. }
  4966. }
  4967. /**
  4968. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  4969. */
  4970. inline void gcode_M85() {
  4971. if (code_seen('S')) max_inactive_time = code_value_millis_from_seconds();
  4972. }
  4973. /**
  4974. * Multi-stepper support for M92, M201, M203
  4975. */
  4976. #if ENABLED(DISTINCT_E_FACTORS)
  4977. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  4978. #define TARGET_EXTRUDER target_extruder
  4979. #else
  4980. #define GET_TARGET_EXTRUDER(CMD) NOOP
  4981. #define TARGET_EXTRUDER 0
  4982. #endif
  4983. /**
  4984. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  4985. * (Follows the same syntax as G92)
  4986. *
  4987. * With multiple extruders use T to specify which one.
  4988. */
  4989. inline void gcode_M92() {
  4990. GET_TARGET_EXTRUDER(92);
  4991. LOOP_XYZE(i) {
  4992. if (code_seen(axis_codes[i])) {
  4993. if (i == E_AXIS) {
  4994. float value = code_value_per_axis_unit(E_AXIS + TARGET_EXTRUDER);
  4995. if (value < 20.0) {
  4996. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  4997. planner.max_jerk[E_AXIS] *= factor;
  4998. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  4999. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  5000. }
  5001. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  5002. }
  5003. else {
  5004. planner.axis_steps_per_mm[i] = code_value_per_axis_unit(i);
  5005. }
  5006. }
  5007. }
  5008. planner.refresh_positioning();
  5009. }
  5010. /**
  5011. * Output the current position to serial
  5012. */
  5013. static void report_current_position() {
  5014. SERIAL_PROTOCOLPGM("X:");
  5015. SERIAL_PROTOCOL(current_position[X_AXIS]);
  5016. SERIAL_PROTOCOLPGM(" Y:");
  5017. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  5018. SERIAL_PROTOCOLPGM(" Z:");
  5019. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  5020. SERIAL_PROTOCOLPGM(" E:");
  5021. SERIAL_PROTOCOL(current_position[E_AXIS]);
  5022. stepper.report_positions();
  5023. #if IS_SCARA
  5024. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  5025. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  5026. SERIAL_EOL;
  5027. #endif
  5028. }
  5029. /**
  5030. * M114: Output current position to serial port
  5031. */
  5032. inline void gcode_M114() { report_current_position(); }
  5033. /**
  5034. * M115: Capabilities string
  5035. */
  5036. inline void gcode_M115() {
  5037. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  5038. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  5039. // EEPROM (M500, M501)
  5040. #if ENABLED(EEPROM_SETTINGS)
  5041. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  5042. #else
  5043. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  5044. #endif
  5045. // AUTOREPORT_TEMP (M155)
  5046. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  5047. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  5048. #else
  5049. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  5050. #endif
  5051. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  5052. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  5053. // AUTOLEVEL (G29)
  5054. #if HAS_ABL
  5055. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  5056. #else
  5057. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  5058. #endif
  5059. // Z_PROBE (G30)
  5060. #if HAS_BED_PROBE
  5061. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  5062. #else
  5063. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  5064. #endif
  5065. // SOFTWARE_POWER (G30)
  5066. #if HAS_POWER_SWITCH
  5067. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  5068. #else
  5069. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  5070. #endif
  5071. // TOGGLE_LIGHTS (M355)
  5072. #if HAS_CASE_LIGHT
  5073. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  5074. #else
  5075. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  5076. #endif
  5077. // EMERGENCY_PARSER (M108, M112, M410)
  5078. #if ENABLED(EMERGENCY_PARSER)
  5079. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  5080. #else
  5081. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  5082. #endif
  5083. #endif // EXTENDED_CAPABILITIES_REPORT
  5084. }
  5085. /**
  5086. * M117: Set LCD Status Message
  5087. */
  5088. inline void gcode_M117() {
  5089. lcd_setstatus(current_command_args);
  5090. }
  5091. /**
  5092. * M119: Output endstop states to serial output
  5093. */
  5094. inline void gcode_M119() { endstops.M119(); }
  5095. /**
  5096. * M120: Enable endstops and set non-homing endstop state to "enabled"
  5097. */
  5098. inline void gcode_M120() { endstops.enable_globally(true); }
  5099. /**
  5100. * M121: Disable endstops and set non-homing endstop state to "disabled"
  5101. */
  5102. inline void gcode_M121() { endstops.enable_globally(false); }
  5103. #if ENABLED(HAVE_TMC2130DRIVER)
  5104. /**
  5105. * M122: Output Trinamic TMC2130 status to serial output. Very bad formatting.
  5106. */
  5107. static void tmc2130_report(Trinamic_TMC2130 &stepr, const char *name) {
  5108. stepr.read_STAT();
  5109. SERIAL_PROTOCOL(name);
  5110. SERIAL_PROTOCOL(": ");
  5111. stepr.isReset() ? SERIAL_PROTOCOLPGM("RESET ") : SERIAL_PROTOCOLPGM("----- ");
  5112. stepr.isError() ? SERIAL_PROTOCOLPGM("ERROR ") : SERIAL_PROTOCOLPGM("----- ");
  5113. stepr.isStallguard() ? SERIAL_PROTOCOLPGM("SLGRD ") : SERIAL_PROTOCOLPGM("----- ");
  5114. stepr.isStandstill() ? SERIAL_PROTOCOLPGM("STILL ") : SERIAL_PROTOCOLPGM("----- ");
  5115. SERIAL_PROTOCOLLN(stepr.debug());
  5116. }
  5117. inline void gcode_M122() {
  5118. SERIAL_PROTOCOLLNPGM("Reporting TMC2130 status");
  5119. #if ENABLED(X_IS_TMC2130)
  5120. tmc2130_report(stepperX, "X");
  5121. #endif
  5122. #if ENABLED(X2_IS_TMC2130)
  5123. tmc2130_report(stepperX2, "X2");
  5124. #endif
  5125. #if ENABLED(Y_IS_TMC2130)
  5126. tmc2130_report(stepperY, "Y");
  5127. #endif
  5128. #if ENABLED(Y2_IS_TMC2130)
  5129. tmc2130_report(stepperY2, "Y2");
  5130. #endif
  5131. #if ENABLED(Z_IS_TMC2130)
  5132. tmc2130_report(stepperZ, "Z");
  5133. #endif
  5134. #if ENABLED(Z2_IS_TMC2130)
  5135. tmc2130_report(stepperZ2, "Z2");
  5136. #endif
  5137. #if ENABLED(E0_IS_TMC2130)
  5138. tmc2130_report(stepperE0, "E0");
  5139. #endif
  5140. #if ENABLED(E1_IS_TMC2130)
  5141. tmc2130_report(stepperE1, "E1");
  5142. #endif
  5143. #if ENABLED(E2_IS_TMC2130)
  5144. tmc2130_report(stepperE2, "E2");
  5145. #endif
  5146. #if ENABLED(E3_IS_TMC2130)
  5147. tmc2130_report(stepperE3, "E3");
  5148. #endif
  5149. }
  5150. #endif // HAVE_TMC2130DRIVER
  5151. #if ENABLED(BLINKM) || ENABLED(RGB_LED)
  5152. void set_led_color(const uint8_t r, const uint8_t g, const uint8_t b) {
  5153. #if ENABLED(BLINKM)
  5154. // This variant uses i2c to send the RGB components to the device.
  5155. SendColors(r, g, b);
  5156. #else
  5157. // This variant uses 3 separate pins for the RGB components.
  5158. // If the pins can do PWM then their intensity will be set.
  5159. digitalWrite(RGB_LED_R_PIN, r ? HIGH : LOW);
  5160. digitalWrite(RGB_LED_G_PIN, g ? HIGH : LOW);
  5161. digitalWrite(RGB_LED_B_PIN, b ? HIGH : LOW);
  5162. analogWrite(RGB_LED_R_PIN, r);
  5163. analogWrite(RGB_LED_G_PIN, g);
  5164. analogWrite(RGB_LED_B_PIN, b);
  5165. #endif
  5166. }
  5167. /**
  5168. * M150: Set Status LED Color - Use R-U-B for R-G-B
  5169. *
  5170. * Always sets all 3 components. If a component is left out, set to 0.
  5171. *
  5172. * Examples:
  5173. *
  5174. * M150 R255 ; Turn LED red
  5175. * M150 R255 U127 ; Turn LED orange (PWM only)
  5176. * M150 ; Turn LED off
  5177. * M150 R U B ; Turn LED white
  5178. *
  5179. */
  5180. inline void gcode_M150() {
  5181. set_led_color(
  5182. code_seen('R') ? (code_has_value() ? code_value_byte() : 255) : 0,
  5183. code_seen('U') ? (code_has_value() ? code_value_byte() : 255) : 0,
  5184. code_seen('B') ? (code_has_value() ? code_value_byte() : 255) : 0
  5185. );
  5186. }
  5187. #endif // BLINKM || RGB_LED
  5188. /**
  5189. * M200: Set filament diameter and set E axis units to cubic units
  5190. *
  5191. * T<extruder> - Optional extruder number. Current extruder if omitted.
  5192. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  5193. */
  5194. inline void gcode_M200() {
  5195. if (get_target_extruder_from_command(200)) return;
  5196. if (code_seen('D')) {
  5197. // setting any extruder filament size disables volumetric on the assumption that
  5198. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5199. // for all extruders
  5200. volumetric_enabled = (code_value_linear_units() != 0.0);
  5201. if (volumetric_enabled) {
  5202. filament_size[target_extruder] = code_value_linear_units();
  5203. // make sure all extruders have some sane value for the filament size
  5204. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  5205. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  5206. }
  5207. }
  5208. else {
  5209. //reserved for setting filament diameter via UFID or filament measuring device
  5210. return;
  5211. }
  5212. calculate_volumetric_multipliers();
  5213. }
  5214. /**
  5215. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  5216. *
  5217. * With multiple extruders use T to specify which one.
  5218. */
  5219. inline void gcode_M201() {
  5220. GET_TARGET_EXTRUDER(201);
  5221. LOOP_XYZE(i) {
  5222. if (code_seen(axis_codes[i])) {
  5223. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  5224. planner.max_acceleration_mm_per_s2[a] = code_value_axis_units(a);
  5225. }
  5226. }
  5227. // 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)
  5228. planner.reset_acceleration_rates();
  5229. }
  5230. #if 0 // Not used for Sprinter/grbl gen6
  5231. inline void gcode_M202() {
  5232. LOOP_XYZE(i) {
  5233. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value_axis_units(i) * planner.axis_steps_per_mm[i];
  5234. }
  5235. }
  5236. #endif
  5237. /**
  5238. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  5239. *
  5240. * With multiple extruders use T to specify which one.
  5241. */
  5242. inline void gcode_M203() {
  5243. GET_TARGET_EXTRUDER(203);
  5244. LOOP_XYZE(i)
  5245. if (code_seen(axis_codes[i])) {
  5246. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  5247. planner.max_feedrate_mm_s[a] = code_value_axis_units(a);
  5248. }
  5249. }
  5250. /**
  5251. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  5252. *
  5253. * P = Printing moves
  5254. * R = Retract only (no X, Y, Z) moves
  5255. * T = Travel (non printing) moves
  5256. *
  5257. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  5258. */
  5259. inline void gcode_M204() {
  5260. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  5261. planner.travel_acceleration = planner.acceleration = code_value_linear_units();
  5262. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  5263. }
  5264. if (code_seen('P')) {
  5265. planner.acceleration = code_value_linear_units();
  5266. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  5267. }
  5268. if (code_seen('R')) {
  5269. planner.retract_acceleration = code_value_linear_units();
  5270. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  5271. }
  5272. if (code_seen('T')) {
  5273. planner.travel_acceleration = code_value_linear_units();
  5274. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  5275. }
  5276. }
  5277. /**
  5278. * M205: Set Advanced Settings
  5279. *
  5280. * S = Min Feed Rate (units/s)
  5281. * T = Min Travel Feed Rate (units/s)
  5282. * B = Min Segment Time (µs)
  5283. * X = Max X Jerk (units/sec^2)
  5284. * Y = Max Y Jerk (units/sec^2)
  5285. * Z = Max Z Jerk (units/sec^2)
  5286. * E = Max E Jerk (units/sec^2)
  5287. */
  5288. inline void gcode_M205() {
  5289. if (code_seen('S')) planner.min_feedrate_mm_s = code_value_linear_units();
  5290. if (code_seen('T')) planner.min_travel_feedrate_mm_s = code_value_linear_units();
  5291. if (code_seen('B')) planner.min_segment_time = code_value_millis();
  5292. if (code_seen('X')) planner.max_jerk[X_AXIS] = code_value_axis_units(X_AXIS);
  5293. if (code_seen('Y')) planner.max_jerk[Y_AXIS] = code_value_axis_units(Y_AXIS);
  5294. if (code_seen('Z')) planner.max_jerk[Z_AXIS] = code_value_axis_units(Z_AXIS);
  5295. if (code_seen('E')) planner.max_jerk[E_AXIS] = code_value_axis_units(E_AXIS);
  5296. }
  5297. /**
  5298. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  5299. */
  5300. inline void gcode_M206() {
  5301. LOOP_XYZ(i)
  5302. if (code_seen(axis_codes[i]))
  5303. set_home_offset((AxisEnum)i, code_value_axis_units(i));
  5304. #if ENABLED(MORGAN_SCARA)
  5305. if (code_seen('T')) set_home_offset(A_AXIS, code_value_axis_units(A_AXIS)); // Theta
  5306. if (code_seen('P')) set_home_offset(B_AXIS, code_value_axis_units(B_AXIS)); // Psi
  5307. #endif
  5308. SYNC_PLAN_POSITION_KINEMATIC();
  5309. report_current_position();
  5310. }
  5311. #if ENABLED(DELTA)
  5312. /**
  5313. * M665: Set delta configurations
  5314. *
  5315. * L = diagonal rod
  5316. * R = delta radius
  5317. * S = segments per second
  5318. * A = Alpha (Tower 1) diagonal rod trim
  5319. * B = Beta (Tower 2) diagonal rod trim
  5320. * C = Gamma (Tower 3) diagonal rod trim
  5321. */
  5322. inline void gcode_M665() {
  5323. if (code_seen('L')) delta_diagonal_rod = code_value_linear_units();
  5324. if (code_seen('R')) delta_radius = code_value_linear_units();
  5325. if (code_seen('S')) delta_segments_per_second = code_value_float();
  5326. if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value_linear_units();
  5327. if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value_linear_units();
  5328. if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value_linear_units();
  5329. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  5330. }
  5331. /**
  5332. * M666: Set delta endstop adjustment
  5333. */
  5334. inline void gcode_M666() {
  5335. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5336. if (DEBUGGING(LEVELING)) {
  5337. SERIAL_ECHOLNPGM(">>> gcode_M666");
  5338. }
  5339. #endif
  5340. LOOP_XYZ(i) {
  5341. if (code_seen(axis_codes[i])) {
  5342. endstop_adj[i] = code_value_axis_units(i);
  5343. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5344. if (DEBUGGING(LEVELING)) {
  5345. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  5346. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  5347. }
  5348. #endif
  5349. }
  5350. }
  5351. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5352. if (DEBUGGING(LEVELING)) {
  5353. SERIAL_ECHOLNPGM("<<< gcode_M666");
  5354. }
  5355. #endif
  5356. }
  5357. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  5358. /**
  5359. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  5360. */
  5361. inline void gcode_M666() {
  5362. if (code_seen('Z')) z_endstop_adj = code_value_axis_units(Z_AXIS);
  5363. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  5364. }
  5365. #endif // !DELTA && Z_DUAL_ENDSTOPS
  5366. #if ENABLED(FWRETRACT)
  5367. /**
  5368. * M207: Set firmware retraction values
  5369. *
  5370. * S[+units] retract_length
  5371. * W[+units] retract_length_swap (multi-extruder)
  5372. * F[units/min] retract_feedrate_mm_s
  5373. * Z[units] retract_zlift
  5374. */
  5375. inline void gcode_M207() {
  5376. if (code_seen('S')) retract_length = code_value_axis_units(E_AXIS);
  5377. if (code_seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS));
  5378. if (code_seen('Z')) retract_zlift = code_value_axis_units(Z_AXIS);
  5379. #if EXTRUDERS > 1
  5380. if (code_seen('W')) retract_length_swap = code_value_axis_units(E_AXIS);
  5381. #endif
  5382. }
  5383. /**
  5384. * M208: Set firmware un-retraction values
  5385. *
  5386. * S[+units] retract_recover_length (in addition to M207 S*)
  5387. * W[+units] retract_recover_length_swap (multi-extruder)
  5388. * F[units/min] retract_recover_feedrate_mm_s
  5389. */
  5390. inline void gcode_M208() {
  5391. if (code_seen('S')) retract_recover_length = code_value_axis_units(E_AXIS);
  5392. if (code_seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS));
  5393. #if EXTRUDERS > 1
  5394. if (code_seen('W')) retract_recover_length_swap = code_value_axis_units(E_AXIS);
  5395. #endif
  5396. }
  5397. /**
  5398. * M209: Enable automatic retract (M209 S1)
  5399. * For slicers that don't support G10/11, reversed extrude-only
  5400. * moves will be classified as retraction.
  5401. */
  5402. inline void gcode_M209() {
  5403. if (code_seen('S')) {
  5404. autoretract_enabled = code_value_bool();
  5405. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  5406. }
  5407. }
  5408. #endif // FWRETRACT
  5409. /**
  5410. * M211: Enable, Disable, and/or Report software endstops
  5411. *
  5412. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  5413. */
  5414. inline void gcode_M211() {
  5415. SERIAL_ECHO_START;
  5416. #if ENABLED(min_software_endstops) || ENABLED(max_software_endstops)
  5417. if (code_seen('S')) soft_endstops_enabled = code_value_bool();
  5418. #endif
  5419. #if ENABLED(min_software_endstops) || ENABLED(max_software_endstops)
  5420. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  5421. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  5422. #else
  5423. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  5424. SERIAL_ECHOPGM(MSG_OFF);
  5425. #endif
  5426. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  5427. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  5428. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  5429. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  5430. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  5431. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  5432. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  5433. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  5434. }
  5435. #if HOTENDS > 1
  5436. /**
  5437. * M218 - set hotend offset (in linear units)
  5438. *
  5439. * T<tool>
  5440. * X<xoffset>
  5441. * Y<yoffset>
  5442. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_EXTRUDER
  5443. */
  5444. inline void gcode_M218() {
  5445. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  5446. if (code_seen('X')) hotend_offset[X_AXIS][target_extruder] = code_value_axis_units(X_AXIS);
  5447. if (code_seen('Y')) hotend_offset[Y_AXIS][target_extruder] = code_value_axis_units(Y_AXIS);
  5448. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER)
  5449. if (code_seen('Z')) hotend_offset[Z_AXIS][target_extruder] = code_value_axis_units(Z_AXIS);
  5450. #endif
  5451. SERIAL_ECHO_START;
  5452. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  5453. HOTEND_LOOP() {
  5454. SERIAL_CHAR(' ');
  5455. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  5456. SERIAL_CHAR(',');
  5457. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  5458. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER)
  5459. SERIAL_CHAR(',');
  5460. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  5461. #endif
  5462. }
  5463. SERIAL_EOL;
  5464. }
  5465. #endif // HOTENDS > 1
  5466. /**
  5467. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  5468. */
  5469. inline void gcode_M220() {
  5470. if (code_seen('S')) feedrate_percentage = code_value_int();
  5471. }
  5472. /**
  5473. * M221: Set extrusion percentage (M221 T0 S95)
  5474. */
  5475. inline void gcode_M221() {
  5476. if (get_target_extruder_from_command(221)) return;
  5477. if (code_seen('S'))
  5478. flow_percentage[target_extruder] = code_value_int();
  5479. }
  5480. /**
  5481. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  5482. */
  5483. inline void gcode_M226() {
  5484. if (code_seen('P')) {
  5485. int pin_number = code_value_int(),
  5486. pin_state = code_seen('S') ? code_value_int() : -1; // required pin state - default is inverted
  5487. if (pin_state >= -1 && pin_state <= 1 && pin_number > -1 && !pin_is_protected(pin_number)) {
  5488. int target = LOW;
  5489. stepper.synchronize();
  5490. pinMode(pin_number, INPUT);
  5491. switch (pin_state) {
  5492. case 1:
  5493. target = HIGH;
  5494. break;
  5495. case 0:
  5496. target = LOW;
  5497. break;
  5498. case -1:
  5499. target = !digitalRead(pin_number);
  5500. break;
  5501. }
  5502. while (digitalRead(pin_number) != target) idle();
  5503. } // pin_state -1 0 1 && pin_number > -1
  5504. } // code_seen('P')
  5505. }
  5506. #if ENABLED(EXPERIMENTAL_I2CBUS)
  5507. /**
  5508. * M260: Send data to a I2C slave device
  5509. *
  5510. * This is a PoC, the formating and arguments for the GCODE will
  5511. * change to be more compatible, the current proposal is:
  5512. *
  5513. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  5514. *
  5515. * M260 B<byte-1 value in base 10>
  5516. * M260 B<byte-2 value in base 10>
  5517. * M260 B<byte-3 value in base 10>
  5518. *
  5519. * M260 S1 ; Send the buffered data and reset the buffer
  5520. * M260 R1 ; Reset the buffer without sending data
  5521. *
  5522. */
  5523. inline void gcode_M260() {
  5524. // Set the target address
  5525. if (code_seen('A')) i2c.address(code_value_byte());
  5526. // Add a new byte to the buffer
  5527. if (code_seen('B')) i2c.addbyte(code_value_byte());
  5528. // Flush the buffer to the bus
  5529. if (code_seen('S')) i2c.send();
  5530. // Reset and rewind the buffer
  5531. else if (code_seen('R')) i2c.reset();
  5532. }
  5533. /**
  5534. * M261: Request X bytes from I2C slave device
  5535. *
  5536. * Usage: M261 A<slave device address base 10> B<number of bytes>
  5537. */
  5538. inline void gcode_M261() {
  5539. if (code_seen('A')) i2c.address(code_value_byte());
  5540. uint8_t bytes = code_seen('B') ? code_value_byte() : 1;
  5541. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  5542. i2c.relay(bytes);
  5543. }
  5544. else {
  5545. SERIAL_ERROR_START;
  5546. SERIAL_ERRORLN("Bad i2c request");
  5547. }
  5548. }
  5549. #endif // EXPERIMENTAL_I2CBUS
  5550. #if HAS_SERVOS
  5551. /**
  5552. * M280: Get or set servo position. P<index> [S<angle>]
  5553. */
  5554. inline void gcode_M280() {
  5555. if (!code_seen('P')) return;
  5556. int servo_index = code_value_int();
  5557. if (servo_index >= 0 && servo_index < NUM_SERVOS) {
  5558. if (code_seen('S'))
  5559. MOVE_SERVO(servo_index, code_value_int());
  5560. else {
  5561. SERIAL_ECHO_START;
  5562. SERIAL_ECHOPAIR(" Servo ", servo_index);
  5563. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  5564. }
  5565. }
  5566. else {
  5567. SERIAL_ERROR_START;
  5568. SERIAL_ECHOPAIR("Servo ", servo_index);
  5569. SERIAL_ECHOLNPGM(" out of range");
  5570. }
  5571. }
  5572. #endif // HAS_SERVOS
  5573. #if HAS_BUZZER
  5574. /**
  5575. * M300: Play beep sound S<frequency Hz> P<duration ms>
  5576. */
  5577. inline void gcode_M300() {
  5578. uint16_t const frequency = code_seen('S') ? code_value_ushort() : 260;
  5579. uint16_t duration = code_seen('P') ? code_value_ushort() : 1000;
  5580. // Limits the tone duration to 0-5 seconds.
  5581. NOMORE(duration, 5000);
  5582. BUZZ(duration, frequency);
  5583. }
  5584. #endif // HAS_BUZZER
  5585. #if ENABLED(PIDTEMP)
  5586. /**
  5587. * M301: Set PID parameters P I D (and optionally C, L)
  5588. *
  5589. * P[float] Kp term
  5590. * I[float] Ki term (unscaled)
  5591. * D[float] Kd term (unscaled)
  5592. *
  5593. * With PID_EXTRUSION_SCALING:
  5594. *
  5595. * C[float] Kc term
  5596. * L[float] LPQ length
  5597. */
  5598. inline void gcode_M301() {
  5599. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  5600. // default behaviour (omitting E parameter) is to update for extruder 0 only
  5601. int e = code_seen('E') ? code_value_int() : 0; // extruder being updated
  5602. if (e < HOTENDS) { // catch bad input value
  5603. if (code_seen('P')) PID_PARAM(Kp, e) = code_value_float();
  5604. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value_float());
  5605. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value_float());
  5606. #if ENABLED(PID_EXTRUSION_SCALING)
  5607. if (code_seen('C')) PID_PARAM(Kc, e) = code_value_float();
  5608. if (code_seen('L')) lpq_len = code_value_float();
  5609. NOMORE(lpq_len, LPQ_MAX_LEN);
  5610. #endif
  5611. thermalManager.updatePID();
  5612. SERIAL_ECHO_START;
  5613. #if ENABLED(PID_PARAMS_PER_HOTEND)
  5614. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  5615. #endif // PID_PARAMS_PER_HOTEND
  5616. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  5617. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  5618. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  5619. #if ENABLED(PID_EXTRUSION_SCALING)
  5620. //Kc does not have scaling applied above, or in resetting defaults
  5621. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  5622. #endif
  5623. SERIAL_EOL;
  5624. }
  5625. else {
  5626. SERIAL_ERROR_START;
  5627. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  5628. }
  5629. }
  5630. #endif // PIDTEMP
  5631. #if ENABLED(PIDTEMPBED)
  5632. inline void gcode_M304() {
  5633. if (code_seen('P')) thermalManager.bedKp = code_value_float();
  5634. if (code_seen('I')) thermalManager.bedKi = scalePID_i(code_value_float());
  5635. if (code_seen('D')) thermalManager.bedKd = scalePID_d(code_value_float());
  5636. thermalManager.updatePID();
  5637. SERIAL_ECHO_START;
  5638. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  5639. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  5640. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  5641. }
  5642. #endif // PIDTEMPBED
  5643. #if defined(CHDK) || HAS_PHOTOGRAPH
  5644. /**
  5645. * M240: Trigger a camera by emulating a Canon RC-1
  5646. * See http://www.doc-diy.net/photo/rc-1_hacked/
  5647. */
  5648. inline void gcode_M240() {
  5649. #ifdef CHDK
  5650. OUT_WRITE(CHDK, HIGH);
  5651. chdkHigh = millis();
  5652. chdkActive = true;
  5653. #elif HAS_PHOTOGRAPH
  5654. const uint8_t NUM_PULSES = 16;
  5655. const float PULSE_LENGTH = 0.01524;
  5656. for (int i = 0; i < NUM_PULSES; i++) {
  5657. WRITE(PHOTOGRAPH_PIN, HIGH);
  5658. _delay_ms(PULSE_LENGTH);
  5659. WRITE(PHOTOGRAPH_PIN, LOW);
  5660. _delay_ms(PULSE_LENGTH);
  5661. }
  5662. delay(7.33);
  5663. for (int i = 0; i < NUM_PULSES; i++) {
  5664. WRITE(PHOTOGRAPH_PIN, HIGH);
  5665. _delay_ms(PULSE_LENGTH);
  5666. WRITE(PHOTOGRAPH_PIN, LOW);
  5667. _delay_ms(PULSE_LENGTH);
  5668. }
  5669. #endif // !CHDK && HAS_PHOTOGRAPH
  5670. }
  5671. #endif // CHDK || PHOTOGRAPH_PIN
  5672. #if HAS_LCD_CONTRAST
  5673. /**
  5674. * M250: Read and optionally set the LCD contrast
  5675. */
  5676. inline void gcode_M250() {
  5677. if (code_seen('C')) set_lcd_contrast(code_value_int());
  5678. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  5679. SERIAL_PROTOCOL(lcd_contrast);
  5680. SERIAL_EOL;
  5681. }
  5682. #endif // HAS_LCD_CONTRAST
  5683. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5684. /**
  5685. * M302: Allow cold extrudes, or set the minimum extrude temperature
  5686. *
  5687. * S<temperature> sets the minimum extrude temperature
  5688. * P<bool> enables (1) or disables (0) cold extrusion
  5689. *
  5690. * Examples:
  5691. *
  5692. * M302 ; report current cold extrusion state
  5693. * M302 P0 ; enable cold extrusion checking
  5694. * M302 P1 ; disables cold extrusion checking
  5695. * M302 S0 ; always allow extrusion (disables checking)
  5696. * M302 S170 ; only allow extrusion above 170
  5697. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  5698. */
  5699. inline void gcode_M302() {
  5700. bool seen_S = code_seen('S');
  5701. if (seen_S) {
  5702. thermalManager.extrude_min_temp = code_value_temp_abs();
  5703. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  5704. }
  5705. if (code_seen('P'))
  5706. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || code_value_bool();
  5707. else if (!seen_S) {
  5708. // Report current state
  5709. SERIAL_ECHO_START;
  5710. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  5711. SERIAL_ECHOPAIR("abled (min temp ", int(thermalManager.extrude_min_temp + 0.5));
  5712. SERIAL_ECHOLNPGM("C)");
  5713. }
  5714. }
  5715. #endif // PREVENT_COLD_EXTRUSION
  5716. /**
  5717. * M303: PID relay autotune
  5718. *
  5719. * S<temperature> sets the target temperature. (default 150C)
  5720. * E<extruder> (-1 for the bed) (default 0)
  5721. * C<cycles>
  5722. * U<bool> with a non-zero value will apply the result to current settings
  5723. */
  5724. inline void gcode_M303() {
  5725. #if HAS_PID_HEATING
  5726. int e = code_seen('E') ? code_value_int() : 0;
  5727. int c = code_seen('C') ? code_value_int() : 5;
  5728. bool u = code_seen('U') && code_value_bool();
  5729. float temp = code_seen('S') ? code_value_temp_abs() : (e < 0 ? 70.0 : 150.0);
  5730. if (e >= 0 && e < HOTENDS)
  5731. target_extruder = e;
  5732. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  5733. thermalManager.PID_autotune(temp, e, c, u);
  5734. KEEPALIVE_STATE(IN_HANDLER);
  5735. #else
  5736. SERIAL_ERROR_START;
  5737. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  5738. #endif
  5739. }
  5740. #if ENABLED(MORGAN_SCARA)
  5741. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  5742. if (IsRunning()) {
  5743. forward_kinematics_SCARA(delta_a, delta_b);
  5744. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  5745. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  5746. destination[Z_AXIS] = current_position[Z_AXIS];
  5747. prepare_move_to_destination();
  5748. return true;
  5749. }
  5750. return false;
  5751. }
  5752. /**
  5753. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  5754. */
  5755. inline bool gcode_M360() {
  5756. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  5757. return SCARA_move_to_cal(0, 120);
  5758. }
  5759. /**
  5760. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  5761. */
  5762. inline bool gcode_M361() {
  5763. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  5764. return SCARA_move_to_cal(90, 130);
  5765. }
  5766. /**
  5767. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  5768. */
  5769. inline bool gcode_M362() {
  5770. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  5771. return SCARA_move_to_cal(60, 180);
  5772. }
  5773. /**
  5774. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  5775. */
  5776. inline bool gcode_M363() {
  5777. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  5778. return SCARA_move_to_cal(50, 90);
  5779. }
  5780. /**
  5781. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  5782. */
  5783. inline bool gcode_M364() {
  5784. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  5785. return SCARA_move_to_cal(45, 135);
  5786. }
  5787. #endif // SCARA
  5788. #if ENABLED(EXT_SOLENOID)
  5789. void enable_solenoid(uint8_t num) {
  5790. switch (num) {
  5791. case 0:
  5792. OUT_WRITE(SOL0_PIN, HIGH);
  5793. break;
  5794. #if HAS_SOLENOID_1
  5795. case 1:
  5796. OUT_WRITE(SOL1_PIN, HIGH);
  5797. break;
  5798. #endif
  5799. #if HAS_SOLENOID_2
  5800. case 2:
  5801. OUT_WRITE(SOL2_PIN, HIGH);
  5802. break;
  5803. #endif
  5804. #if HAS_SOLENOID_3
  5805. case 3:
  5806. OUT_WRITE(SOL3_PIN, HIGH);
  5807. break;
  5808. #endif
  5809. default:
  5810. SERIAL_ECHO_START;
  5811. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  5812. break;
  5813. }
  5814. }
  5815. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  5816. void disable_all_solenoids() {
  5817. OUT_WRITE(SOL0_PIN, LOW);
  5818. OUT_WRITE(SOL1_PIN, LOW);
  5819. OUT_WRITE(SOL2_PIN, LOW);
  5820. OUT_WRITE(SOL3_PIN, LOW);
  5821. }
  5822. /**
  5823. * M380: Enable solenoid on the active extruder
  5824. */
  5825. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  5826. /**
  5827. * M381: Disable all solenoids
  5828. */
  5829. inline void gcode_M381() { disable_all_solenoids(); }
  5830. #endif // EXT_SOLENOID
  5831. /**
  5832. * M400: Finish all moves
  5833. */
  5834. inline void gcode_M400() { stepper.synchronize(); }
  5835. #if HAS_BED_PROBE
  5836. /**
  5837. * M401: Engage Z Servo endstop if available
  5838. */
  5839. inline void gcode_M401() { DEPLOY_PROBE(); }
  5840. /**
  5841. * M402: Retract Z Servo endstop if enabled
  5842. */
  5843. inline void gcode_M402() { STOW_PROBE(); }
  5844. #endif // HAS_BED_PROBE
  5845. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  5846. /**
  5847. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  5848. */
  5849. inline void gcode_M404() {
  5850. if (code_seen('W')) {
  5851. filament_width_nominal = code_value_linear_units();
  5852. }
  5853. else {
  5854. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  5855. SERIAL_PROTOCOLLN(filament_width_nominal);
  5856. }
  5857. }
  5858. /**
  5859. * M405: Turn on filament sensor for control
  5860. */
  5861. inline void gcode_M405() {
  5862. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  5863. // everything else, it uses code_value_int() instead of code_value_linear_units().
  5864. if (code_seen('D')) meas_delay_cm = code_value_int();
  5865. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  5866. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  5867. int temp_ratio = thermalManager.widthFil_to_size_ratio();
  5868. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  5869. measurement_delay[i] = temp_ratio - 100; // Subtract 100 to scale within a signed byte
  5870. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  5871. }
  5872. filament_sensor = true;
  5873. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5874. //SERIAL_PROTOCOL(filament_width_meas);
  5875. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  5876. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  5877. }
  5878. /**
  5879. * M406: Turn off filament sensor for control
  5880. */
  5881. inline void gcode_M406() { filament_sensor = false; }
  5882. /**
  5883. * M407: Get measured filament diameter on serial output
  5884. */
  5885. inline void gcode_M407() {
  5886. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5887. SERIAL_PROTOCOLLN(filament_width_meas);
  5888. }
  5889. #endif // FILAMENT_WIDTH_SENSOR
  5890. void quickstop_stepper() {
  5891. stepper.quick_stop();
  5892. stepper.synchronize();
  5893. set_current_from_steppers_for_axis(ALL_AXES);
  5894. SYNC_PLAN_POSITION_KINEMATIC();
  5895. }
  5896. #if PLANNER_LEVELING
  5897. /**
  5898. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  5899. *
  5900. * S[bool] Turns leveling on or off
  5901. * Z[height] Sets the Z fade height (0 or none to disable)
  5902. */
  5903. inline void gcode_M420() {
  5904. if (code_seen('S')) set_bed_leveling_enabled(code_value_bool());
  5905. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  5906. if (code_seen('Z')) set_z_fade_height(code_value_linear_units());
  5907. #endif
  5908. }
  5909. #endif
  5910. #if ENABLED(MESH_BED_LEVELING)
  5911. /**
  5912. * M421: Set a single Mesh Bed Leveling Z coordinate
  5913. * Use either 'M421 X<linear> Y<linear> Z<linear>' or 'M421 I<xindex> J<yindex> Z<linear>'
  5914. */
  5915. inline void gcode_M421() {
  5916. int8_t px = 0, py = 0;
  5917. float z = 0;
  5918. bool hasX, hasY, hasZ, hasI, hasJ;
  5919. if ((hasX = code_seen('X'))) px = mbl.probe_index_x(code_value_axis_units(X_AXIS));
  5920. if ((hasY = code_seen('Y'))) py = mbl.probe_index_y(code_value_axis_units(Y_AXIS));
  5921. if ((hasI = code_seen('I'))) px = code_value_axis_units(X_AXIS);
  5922. if ((hasJ = code_seen('J'))) py = code_value_axis_units(Y_AXIS);
  5923. if ((hasZ = code_seen('Z'))) z = code_value_axis_units(Z_AXIS);
  5924. if (hasX && hasY && hasZ) {
  5925. if (px >= 0 && py >= 0)
  5926. mbl.set_z(px, py, z);
  5927. else {
  5928. SERIAL_ERROR_START;
  5929. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5930. }
  5931. }
  5932. else if (hasI && hasJ && hasZ) {
  5933. if (px >= 0 && px < MESH_NUM_X_POINTS && py >= 0 && py < MESH_NUM_Y_POINTS)
  5934. mbl.set_z(px, py, z);
  5935. else {
  5936. SERIAL_ERROR_START;
  5937. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5938. }
  5939. }
  5940. else {
  5941. SERIAL_ERROR_START;
  5942. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  5943. }
  5944. }
  5945. #endif
  5946. /**
  5947. * M428: Set home_offset based on the distance between the
  5948. * current_position and the nearest "reference point."
  5949. * If an axis is past center its endstop position
  5950. * is the reference-point. Otherwise it uses 0. This allows
  5951. * the Z offset to be set near the bed when using a max endstop.
  5952. *
  5953. * M428 can't be used more than 2cm away from 0 or an endstop.
  5954. *
  5955. * Use M206 to set these values directly.
  5956. */
  5957. inline void gcode_M428() {
  5958. bool err = false;
  5959. LOOP_XYZ(i) {
  5960. if (axis_homed[i]) {
  5961. float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  5962. diff = current_position[i] - LOGICAL_POSITION(base, i);
  5963. if (diff > -20 && diff < 20) {
  5964. set_home_offset((AxisEnum)i, home_offset[i] - diff);
  5965. }
  5966. else {
  5967. SERIAL_ERROR_START;
  5968. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  5969. LCD_ALERTMESSAGEPGM("Err: Too far!");
  5970. BUZZ(200, 40);
  5971. err = true;
  5972. break;
  5973. }
  5974. }
  5975. }
  5976. if (!err) {
  5977. SYNC_PLAN_POSITION_KINEMATIC();
  5978. report_current_position();
  5979. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  5980. BUZZ(200, 659);
  5981. BUZZ(200, 698);
  5982. }
  5983. }
  5984. /**
  5985. * M500: Store settings in EEPROM
  5986. */
  5987. inline void gcode_M500() {
  5988. Config_StoreSettings();
  5989. }
  5990. /**
  5991. * M501: Read settings from EEPROM
  5992. */
  5993. inline void gcode_M501() {
  5994. Config_RetrieveSettings();
  5995. }
  5996. /**
  5997. * M502: Revert to default settings
  5998. */
  5999. inline void gcode_M502() {
  6000. Config_ResetDefault();
  6001. }
  6002. /**
  6003. * M503: print settings currently in memory
  6004. */
  6005. inline void gcode_M503() {
  6006. Config_PrintSettings(code_seen('S') && !code_value_bool());
  6007. }
  6008. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  6009. /**
  6010. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  6011. */
  6012. inline void gcode_M540() {
  6013. if (code_seen('S')) stepper.abort_on_endstop_hit = code_value_bool();
  6014. }
  6015. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6016. #if HAS_BED_PROBE
  6017. inline void gcode_M851() {
  6018. SERIAL_ECHO_START;
  6019. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  6020. SERIAL_CHAR(' ');
  6021. if (code_seen('Z')) {
  6022. float value = code_value_axis_units(Z_AXIS);
  6023. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  6024. zprobe_zoffset = value;
  6025. SERIAL_ECHO(zprobe_zoffset);
  6026. }
  6027. else {
  6028. SERIAL_ECHOPAIR(MSG_Z_MIN, Z_PROBE_OFFSET_RANGE_MIN);
  6029. SERIAL_CHAR(' ');
  6030. SERIAL_ECHOPAIR(MSG_Z_MAX, Z_PROBE_OFFSET_RANGE_MAX);
  6031. }
  6032. }
  6033. else {
  6034. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  6035. }
  6036. SERIAL_EOL;
  6037. }
  6038. #endif // HAS_BED_PROBE
  6039. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  6040. /**
  6041. * M600: Pause for filament change
  6042. *
  6043. * E[distance] - Retract the filament this far (negative value)
  6044. * Z[distance] - Move the Z axis by this distance
  6045. * X[position] - Move to this X position, with Y
  6046. * Y[position] - Move to this Y position, with X
  6047. * L[distance] - Retract distance for removal (manual reload)
  6048. *
  6049. * Default values are used for omitted arguments.
  6050. *
  6051. */
  6052. inline void gcode_M600() {
  6053. if (thermalManager.tooColdToExtrude(active_extruder)) {
  6054. SERIAL_ERROR_START;
  6055. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  6056. return;
  6057. }
  6058. // Show initial message and wait for synchronize steppers
  6059. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INIT);
  6060. stepper.synchronize();
  6061. float lastpos[NUM_AXIS];
  6062. // Save current position of all axes
  6063. LOOP_XYZE(i)
  6064. lastpos[i] = destination[i] = current_position[i];
  6065. // Define runplan for move axes
  6066. #if IS_KINEMATIC
  6067. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder);
  6068. #else
  6069. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S);
  6070. #endif
  6071. KEEPALIVE_STATE(IN_HANDLER);
  6072. // Initial retract before move to filament change position
  6073. if (code_seen('E')) destination[E_AXIS] += code_value_axis_units(E_AXIS);
  6074. #if defined(FILAMENT_CHANGE_RETRACT_LENGTH) && FILAMENT_CHANGE_RETRACT_LENGTH > 0
  6075. else destination[E_AXIS] -= FILAMENT_CHANGE_RETRACT_LENGTH;
  6076. #endif
  6077. RUNPLAN(FILAMENT_CHANGE_RETRACT_FEEDRATE);
  6078. // Lift Z axis
  6079. float z_lift = code_seen('Z') ? code_value_axis_units(Z_AXIS) :
  6080. #if defined(FILAMENT_CHANGE_Z_ADD) && FILAMENT_CHANGE_Z_ADD > 0
  6081. FILAMENT_CHANGE_Z_ADD
  6082. #else
  6083. 0
  6084. #endif
  6085. ;
  6086. if (z_lift > 0) {
  6087. destination[Z_AXIS] += z_lift;
  6088. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  6089. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  6090. }
  6091. // Move XY axes to filament exchange position
  6092. if (code_seen('X')) destination[X_AXIS] = code_value_axis_units(X_AXIS);
  6093. #ifdef FILAMENT_CHANGE_X_POS
  6094. else destination[X_AXIS] = FILAMENT_CHANGE_X_POS;
  6095. #endif
  6096. if (code_seen('Y')) destination[Y_AXIS] = code_value_axis_units(Y_AXIS);
  6097. #ifdef FILAMENT_CHANGE_Y_POS
  6098. else destination[Y_AXIS] = FILAMENT_CHANGE_Y_POS;
  6099. #endif
  6100. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  6101. stepper.synchronize();
  6102. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_UNLOAD);
  6103. // Unload filament
  6104. if (code_seen('L')) destination[E_AXIS] += code_value_axis_units(E_AXIS);
  6105. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  6106. else destination[E_AXIS] -= FILAMENT_CHANGE_UNLOAD_LENGTH;
  6107. #endif
  6108. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  6109. // Synchronize steppers and then disable extruders steppers for manual filament changing
  6110. stepper.synchronize();
  6111. disable_e0();
  6112. disable_e1();
  6113. disable_e2();
  6114. disable_e3();
  6115. delay(100);
  6116. #if HAS_BUZZER
  6117. millis_t next_buzz = 0;
  6118. #endif
  6119. // Wait for filament insert by user and press button
  6120. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INSERT);
  6121. // LCD click or M108 will clear this
  6122. wait_for_user = true;
  6123. while (wait_for_user) {
  6124. #if HAS_BUZZER
  6125. millis_t ms = millis();
  6126. if (ms >= next_buzz) {
  6127. BUZZ(300, 2000);
  6128. next_buzz = ms + 2500; // Beep every 2.5s while waiting
  6129. }
  6130. #endif
  6131. idle(true);
  6132. }
  6133. // Show load message
  6134. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_LOAD);
  6135. // Load filament
  6136. if (code_seen('L')) destination[E_AXIS] -= code_value_axis_units(E_AXIS);
  6137. #if defined(FILAMENT_CHANGE_LOAD_LENGTH) && FILAMENT_CHANGE_LOAD_LENGTH > 0
  6138. else destination[E_AXIS] += FILAMENT_CHANGE_LOAD_LENGTH;
  6139. #endif
  6140. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  6141. stepper.synchronize();
  6142. #if defined(FILAMENT_CHANGE_EXTRUDE_LENGTH) && FILAMENT_CHANGE_EXTRUDE_LENGTH > 0
  6143. do {
  6144. // Extrude filament to get into hotend
  6145. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_EXTRUDE);
  6146. destination[E_AXIS] += FILAMENT_CHANGE_EXTRUDE_LENGTH;
  6147. RUNPLAN(FILAMENT_CHANGE_EXTRUDE_FEEDRATE);
  6148. stepper.synchronize();
  6149. // Ask user if more filament should be extruded
  6150. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6151. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_OPTION);
  6152. while (filament_change_menu_response == FILAMENT_CHANGE_RESPONSE_WAIT_FOR) idle(true);
  6153. KEEPALIVE_STATE(IN_HANDLER);
  6154. } while (filament_change_menu_response != FILAMENT_CHANGE_RESPONSE_RESUME_PRINT);
  6155. #endif
  6156. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_RESUME);
  6157. KEEPALIVE_STATE(IN_HANDLER);
  6158. // Set extruder to saved position
  6159. destination[E_AXIS] = current_position[E_AXIS] = lastpos[E_AXIS];
  6160. planner.set_e_position_mm(current_position[E_AXIS]);
  6161. #if IS_KINEMATIC
  6162. // Move XYZ to starting position
  6163. planner.buffer_line_kinematic(lastpos, FILAMENT_CHANGE_XY_FEEDRATE, active_extruder);
  6164. #else
  6165. // Move XY to starting position, then Z
  6166. destination[X_AXIS] = lastpos[X_AXIS];
  6167. destination[Y_AXIS] = lastpos[Y_AXIS];
  6168. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  6169. destination[Z_AXIS] = lastpos[Z_AXIS];
  6170. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  6171. #endif
  6172. stepper.synchronize();
  6173. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6174. filament_ran_out = false;
  6175. #endif
  6176. // Show status screen
  6177. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_STATUS);
  6178. }
  6179. #endif // FILAMENT_CHANGE_FEATURE
  6180. #if ENABLED(DUAL_X_CARRIAGE)
  6181. /**
  6182. * M605: Set dual x-carriage movement mode
  6183. *
  6184. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  6185. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  6186. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  6187. * units x-offset and an optional differential hotend temperature of
  6188. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  6189. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  6190. *
  6191. * Note: the X axis should be homed after changing dual x-carriage mode.
  6192. */
  6193. inline void gcode_M605() {
  6194. stepper.synchronize();
  6195. if (code_seen('S')) dual_x_carriage_mode = (DualXMode)code_value_byte();
  6196. switch (dual_x_carriage_mode) {
  6197. case DXC_FULL_CONTROL_MODE:
  6198. case DXC_AUTO_PARK_MODE:
  6199. break;
  6200. case DXC_DUPLICATION_MODE:
  6201. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value_axis_units(X_AXIS), X2_MIN_POS - x_home_pos(0));
  6202. if (code_seen('R')) duplicate_extruder_temp_offset = code_value_temp_diff();
  6203. SERIAL_ECHO_START;
  6204. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  6205. SERIAL_CHAR(' ');
  6206. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  6207. SERIAL_CHAR(',');
  6208. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  6209. SERIAL_CHAR(' ');
  6210. SERIAL_ECHO(duplicate_extruder_x_offset);
  6211. SERIAL_CHAR(',');
  6212. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  6213. break;
  6214. default:
  6215. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  6216. break;
  6217. }
  6218. active_extruder_parked = false;
  6219. extruder_duplication_enabled = false;
  6220. delayed_move_time = 0;
  6221. }
  6222. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  6223. inline void gcode_M605() {
  6224. stepper.synchronize();
  6225. extruder_duplication_enabled = code_seen('S') && code_value_int() == 2;
  6226. SERIAL_ECHO_START;
  6227. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  6228. }
  6229. #endif // M605
  6230. #if ENABLED(LIN_ADVANCE)
  6231. /**
  6232. * M905: Set advance factor
  6233. */
  6234. inline void gcode_M905() {
  6235. stepper.synchronize();
  6236. planner.advance_M905(code_seen('K') ? code_value_float() : -1.0);
  6237. }
  6238. #endif
  6239. /**
  6240. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  6241. */
  6242. inline void gcode_M907() {
  6243. #if HAS_DIGIPOTSS
  6244. LOOP_XYZE(i)
  6245. if (code_seen(axis_codes[i])) stepper.digipot_current(i, code_value_int());
  6246. if (code_seen('B')) stepper.digipot_current(4, code_value_int());
  6247. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.digipot_current(i, code_value_int());
  6248. #elif HAS_MOTOR_CURRENT_PWM
  6249. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  6250. if (code_seen('X')) stepper.digipot_current(0, code_value_int());
  6251. #endif
  6252. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  6253. if (code_seen('Z')) stepper.digipot_current(1, code_value_int());
  6254. #endif
  6255. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  6256. if (code_seen('E')) stepper.digipot_current(2, code_value_int());
  6257. #endif
  6258. #endif
  6259. #if ENABLED(DIGIPOT_I2C)
  6260. // this one uses actual amps in floating point
  6261. LOOP_XYZE(i) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value_float());
  6262. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  6263. for (int i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (code_seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, code_value_float());
  6264. #endif
  6265. #if ENABLED(DAC_STEPPER_CURRENT)
  6266. if (code_seen('S')) {
  6267. float dac_percent = code_value_float();
  6268. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  6269. }
  6270. LOOP_XYZE(i) if (code_seen(axis_codes[i])) dac_current_percent(i, code_value_float());
  6271. #endif
  6272. }
  6273. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  6274. /**
  6275. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  6276. */
  6277. inline void gcode_M908() {
  6278. #if HAS_DIGIPOTSS
  6279. stepper.digitalPotWrite(
  6280. code_seen('P') ? code_value_int() : 0,
  6281. code_seen('S') ? code_value_int() : 0
  6282. );
  6283. #endif
  6284. #ifdef DAC_STEPPER_CURRENT
  6285. dac_current_raw(
  6286. code_seen('P') ? code_value_byte() : -1,
  6287. code_seen('S') ? code_value_ushort() : 0
  6288. );
  6289. #endif
  6290. }
  6291. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  6292. inline void gcode_M909() { dac_print_values(); }
  6293. inline void gcode_M910() { dac_commit_eeprom(); }
  6294. #endif
  6295. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  6296. #if HAS_MICROSTEPS
  6297. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6298. inline void gcode_M350() {
  6299. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, code_value_byte());
  6300. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_mode(i, code_value_byte());
  6301. if (code_seen('B')) stepper.microstep_mode(4, code_value_byte());
  6302. stepper.microstep_readings();
  6303. }
  6304. /**
  6305. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  6306. * S# determines MS1 or MS2, X# sets the pin high/low.
  6307. */
  6308. inline void gcode_M351() {
  6309. if (code_seen('S')) switch (code_value_byte()) {
  6310. case 1:
  6311. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, code_value_byte(), -1);
  6312. if (code_seen('B')) stepper.microstep_ms(4, code_value_byte(), -1);
  6313. break;
  6314. case 2:
  6315. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, -1, code_value_byte());
  6316. if (code_seen('B')) stepper.microstep_ms(4, -1, code_value_byte());
  6317. break;
  6318. }
  6319. stepper.microstep_readings();
  6320. }
  6321. #endif // HAS_MICROSTEPS
  6322. #if HAS_CASE_LIGHT
  6323. uint8_t case_light_brightness = 255;
  6324. void update_case_light() {
  6325. digitalWrite(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? HIGH : LOW);
  6326. analogWrite(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? case_light_brightness : 0);
  6327. }
  6328. /**
  6329. * M355: Turn case lights on/off and set brightness
  6330. *
  6331. * S<bool> Turn case light on or off
  6332. * P<byte> Set case light brightness (PWM pin required)
  6333. */
  6334. inline void gcode_M355() {
  6335. if (code_seen('P')) case_light_brightness = code_value_byte();
  6336. if (code_seen('S')) case_light_on = code_value_bool();
  6337. update_case_light();
  6338. SERIAL_ECHO_START;
  6339. SERIAL_ECHOPGM("Case lights ");
  6340. case_light_on ? SERIAL_ECHOLNPGM("on") : SERIAL_ECHOLNPGM("off");
  6341. }
  6342. #endif // HAS_CASE_LIGHT
  6343. #if ENABLED(MIXING_EXTRUDER)
  6344. /**
  6345. * M163: Set a single mix factor for a mixing extruder
  6346. * This is called "weight" by some systems.
  6347. *
  6348. * S[index] The channel index to set
  6349. * P[float] The mix value
  6350. *
  6351. */
  6352. inline void gcode_M163() {
  6353. int mix_index = code_seen('S') ? code_value_int() : 0;
  6354. if (mix_index < MIXING_STEPPERS) {
  6355. float mix_value = code_seen('P') ? code_value_float() : 0.0;
  6356. NOLESS(mix_value, 0.0);
  6357. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  6358. }
  6359. }
  6360. #if MIXING_VIRTUAL_TOOLS > 1
  6361. /**
  6362. * M164: Store the current mix factors as a virtual tool.
  6363. *
  6364. * S[index] The virtual tool to store
  6365. *
  6366. */
  6367. inline void gcode_M164() {
  6368. int tool_index = code_seen('S') ? code_value_int() : 0;
  6369. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  6370. normalize_mix();
  6371. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  6372. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  6373. }
  6374. }
  6375. #endif
  6376. #if ENABLED(DIRECT_MIXING_IN_G1)
  6377. /**
  6378. * M165: Set multiple mix factors for a mixing extruder.
  6379. * Factors that are left out will be set to 0.
  6380. * All factors together must add up to 1.0.
  6381. *
  6382. * A[factor] Mix factor for extruder stepper 1
  6383. * B[factor] Mix factor for extruder stepper 2
  6384. * C[factor] Mix factor for extruder stepper 3
  6385. * D[factor] Mix factor for extruder stepper 4
  6386. * H[factor] Mix factor for extruder stepper 5
  6387. * I[factor] Mix factor for extruder stepper 6
  6388. *
  6389. */
  6390. inline void gcode_M165() { gcode_get_mix(); }
  6391. #endif
  6392. #endif // MIXING_EXTRUDER
  6393. /**
  6394. * M999: Restart after being stopped
  6395. *
  6396. * Default behaviour is to flush the serial buffer and request
  6397. * a resend to the host starting on the last N line received.
  6398. *
  6399. * Sending "M999 S1" will resume printing without flushing the
  6400. * existing command buffer.
  6401. *
  6402. */
  6403. inline void gcode_M999() {
  6404. Running = true;
  6405. lcd_reset_alert_level();
  6406. if (code_seen('S') && code_value_bool()) return;
  6407. // gcode_LastN = Stopped_gcode_LastN;
  6408. FlushSerialRequestResend();
  6409. }
  6410. #if ENABLED(SWITCHING_EXTRUDER)
  6411. inline void move_extruder_servo(uint8_t e) {
  6412. const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  6413. MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]);
  6414. }
  6415. #endif
  6416. inline void invalid_extruder_error(const uint8_t &e) {
  6417. SERIAL_ECHO_START;
  6418. SERIAL_CHAR('T');
  6419. SERIAL_PROTOCOL_F(e, DEC);
  6420. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  6421. }
  6422. /**
  6423. * Perform a tool-change, which may result in moving the
  6424. * previous tool out of the way and the new tool into place.
  6425. */
  6426. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  6427. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  6428. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  6429. return invalid_extruder_error(tmp_extruder);
  6430. // T0-Tnnn: Switch virtual tool by changing the mix
  6431. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  6432. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  6433. #else //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  6434. #if HOTENDS > 1
  6435. if (tmp_extruder >= EXTRUDERS)
  6436. return invalid_extruder_error(tmp_extruder);
  6437. float old_feedrate_mm_s = feedrate_mm_s;
  6438. feedrate_mm_s = fr_mm_s > 0.0 ? (old_feedrate_mm_s = fr_mm_s) : XY_PROBE_FEEDRATE_MM_S;
  6439. if (tmp_extruder != active_extruder) {
  6440. if (!no_move && axis_unhomed_error(true, true, true)) {
  6441. SERIAL_ECHOLNPGM("No move on toolchange");
  6442. no_move = true;
  6443. }
  6444. // Save current position to destination, for use later
  6445. set_destination_to_current();
  6446. #if ENABLED(DUAL_X_CARRIAGE)
  6447. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6448. if (DEBUGGING(LEVELING)) {
  6449. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  6450. switch (dual_x_carriage_mode) {
  6451. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  6452. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  6453. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  6454. }
  6455. }
  6456. #endif
  6457. const float xhome = x_home_pos(active_extruder);
  6458. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  6459. && IsRunning()
  6460. && (delayed_move_time || current_position[X_AXIS] != xhome)
  6461. ) {
  6462. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  6463. #if ENABLED(max_software_endstops)
  6464. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  6465. #endif
  6466. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6467. if (DEBUGGING(LEVELING)) {
  6468. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  6469. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  6470. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  6471. }
  6472. #endif
  6473. // Park old head: 1) raise 2) move to park position 3) lower
  6474. for (uint8_t i = 0; i < 3; i++)
  6475. planner.buffer_line(
  6476. i == 0 ? current_position[X_AXIS] : xhome,
  6477. current_position[Y_AXIS],
  6478. i == 2 ? current_position[Z_AXIS] : raised_z,
  6479. current_position[E_AXIS],
  6480. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  6481. active_extruder
  6482. );
  6483. stepper.synchronize();
  6484. }
  6485. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  6486. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  6487. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  6488. // Activate the new extruder
  6489. active_extruder = tmp_extruder;
  6490. // This function resets the max/min values - the current position may be overwritten below.
  6491. set_axis_is_at_home(X_AXIS);
  6492. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6493. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  6494. #endif
  6495. // Only when auto-parking are carriages safe to move
  6496. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  6497. switch (dual_x_carriage_mode) {
  6498. case DXC_FULL_CONTROL_MODE:
  6499. // New current position is the position of the activated extruder
  6500. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  6501. // Save the inactive extruder's position (from the old current_position)
  6502. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  6503. break;
  6504. case DXC_AUTO_PARK_MODE:
  6505. // record raised toolhead position for use by unpark
  6506. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  6507. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  6508. #if ENABLED(max_software_endstops)
  6509. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  6510. #endif
  6511. active_extruder_parked = true;
  6512. delayed_move_time = 0;
  6513. break;
  6514. case DXC_DUPLICATION_MODE:
  6515. // If the new extruder is the left one, set it "parked"
  6516. // This triggers the second extruder to move into the duplication position
  6517. active_extruder_parked = (active_extruder == 0);
  6518. if (active_extruder_parked)
  6519. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  6520. else
  6521. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  6522. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  6523. extruder_duplication_enabled = false;
  6524. break;
  6525. }
  6526. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6527. if (DEBUGGING(LEVELING)) {
  6528. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  6529. DEBUG_POS("New extruder (parked)", current_position);
  6530. }
  6531. #endif
  6532. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  6533. #else // !DUAL_X_CARRIAGE
  6534. #if ENABLED(SWITCHING_EXTRUDER)
  6535. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  6536. float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  6537. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  6538. // Always raise by some amount (destination copied from current_position earlier)
  6539. destination[Z_AXIS] += z_raise;
  6540. planner.buffer_line_kinematic(destination, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  6541. stepper.synchronize();
  6542. move_extruder_servo(active_extruder);
  6543. delay(500);
  6544. // Move back down, if needed
  6545. if (z_raise != z_diff) {
  6546. destination[Z_AXIS] = current_position[Z_AXIS] + z_diff;
  6547. planner.buffer_line_kinematic(destination, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  6548. stepper.synchronize();
  6549. }
  6550. #endif
  6551. /**
  6552. * Set current_position to the position of the new nozzle.
  6553. * Offsets are based on linear distance, so we need to get
  6554. * the resulting position in coordinate space.
  6555. *
  6556. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  6557. * - With mesh leveling, update Z for the new position
  6558. * - Otherwise, just use the raw linear distance
  6559. *
  6560. * Software endstops are altered here too. Consider a case where:
  6561. * E0 at X=0 ... E1 at X=10
  6562. * When we switch to E1 now X=10, but E1 can't move left.
  6563. * To express this we apply the change in XY to the software endstops.
  6564. * E1 can move farther right than E0, so the right limit is extended.
  6565. *
  6566. * Note that we don't adjust the Z software endstops. Why not?
  6567. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  6568. * because the bed is 1mm lower at the new position. As long as
  6569. * the first nozzle is out of the way, the carriage should be
  6570. * allowed to move 1mm lower. This technically "breaks" the
  6571. * Z software endstop. But this is technically correct (and
  6572. * there is no viable alternative).
  6573. */
  6574. #if ABL_PLANAR
  6575. // Offset extruder, make sure to apply the bed level rotation matrix
  6576. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  6577. hotend_offset[Y_AXIS][tmp_extruder],
  6578. 0),
  6579. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  6580. hotend_offset[Y_AXIS][active_extruder],
  6581. 0),
  6582. offset_vec = tmp_offset_vec - act_offset_vec;
  6583. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6584. if (DEBUGGING(LEVELING)) {
  6585. tmp_offset_vec.debug("tmp_offset_vec");
  6586. act_offset_vec.debug("act_offset_vec");
  6587. offset_vec.debug("offset_vec (BEFORE)");
  6588. }
  6589. #endif
  6590. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  6591. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6592. if (DEBUGGING(LEVELING)) offset_vec.debug("offset_vec (AFTER)");
  6593. #endif
  6594. // Adjustments to the current position
  6595. float xydiff[2] = { offset_vec.x, offset_vec.y };
  6596. current_position[Z_AXIS] += offset_vec.z;
  6597. #else // !ABL_PLANAR
  6598. float xydiff[2] = {
  6599. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  6600. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  6601. };
  6602. #if ENABLED(MESH_BED_LEVELING)
  6603. if (mbl.active()) {
  6604. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6605. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  6606. #endif
  6607. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  6608. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  6609. z1 = current_position[Z_AXIS], z2 = z1;
  6610. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  6611. planner.apply_leveling(x2, y2, z2);
  6612. current_position[Z_AXIS] += z2 - z1;
  6613. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6614. if (DEBUGGING(LEVELING))
  6615. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  6616. #endif
  6617. }
  6618. #endif // MESH_BED_LEVELING
  6619. #endif // !HAS_ABL
  6620. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6621. if (DEBUGGING(LEVELING)) {
  6622. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  6623. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  6624. SERIAL_ECHOLNPGM(" }");
  6625. }
  6626. #endif
  6627. // The newly-selected extruder XY is actually at...
  6628. current_position[X_AXIS] += xydiff[X_AXIS];
  6629. current_position[Y_AXIS] += xydiff[Y_AXIS];
  6630. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  6631. position_shift[i] += xydiff[i];
  6632. update_software_endstops((AxisEnum)i);
  6633. }
  6634. // Set the new active extruder
  6635. active_extruder = tmp_extruder;
  6636. #endif // !DUAL_X_CARRIAGE
  6637. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6638. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  6639. #endif
  6640. // Tell the planner the new "current position"
  6641. SYNC_PLAN_POSITION_KINEMATIC();
  6642. // Move to the "old position" (move the extruder into place)
  6643. if (!no_move && IsRunning()) {
  6644. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6645. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  6646. #endif
  6647. prepare_move_to_destination();
  6648. }
  6649. } // (tmp_extruder != active_extruder)
  6650. stepper.synchronize();
  6651. #if ENABLED(EXT_SOLENOID)
  6652. disable_all_solenoids();
  6653. enable_solenoid_on_active_extruder();
  6654. #endif // EXT_SOLENOID
  6655. feedrate_mm_s = old_feedrate_mm_s;
  6656. #else // HOTENDS <= 1
  6657. // Set the new active extruder
  6658. active_extruder = tmp_extruder;
  6659. UNUSED(fr_mm_s);
  6660. UNUSED(no_move);
  6661. #endif // HOTENDS <= 1
  6662. SERIAL_ECHO_START;
  6663. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  6664. #endif //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  6665. }
  6666. /**
  6667. * T0-T3: Switch tool, usually switching extruders
  6668. *
  6669. * F[units/min] Set the movement feedrate
  6670. * S1 Don't move the tool in XY after change
  6671. */
  6672. inline void gcode_T(uint8_t tmp_extruder) {
  6673. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6674. if (DEBUGGING(LEVELING)) {
  6675. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  6676. SERIAL_CHAR(')');
  6677. SERIAL_EOL;
  6678. DEBUG_POS("BEFORE", current_position);
  6679. }
  6680. #endif
  6681. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  6682. tool_change(tmp_extruder);
  6683. #elif HOTENDS > 1
  6684. tool_change(
  6685. tmp_extruder,
  6686. code_seen('F') ? MMM_TO_MMS(code_value_axis_units(X_AXIS)) : 0.0,
  6687. (tmp_extruder == active_extruder) || (code_seen('S') && code_value_bool())
  6688. );
  6689. #endif
  6690. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6691. if (DEBUGGING(LEVELING)) {
  6692. DEBUG_POS("AFTER", current_position);
  6693. SERIAL_ECHOLNPGM("<<< gcode_T");
  6694. }
  6695. #endif
  6696. }
  6697. /**
  6698. * Process a single command and dispatch it to its handler
  6699. * This is called from the main loop()
  6700. */
  6701. void process_next_command() {
  6702. current_command = command_queue[cmd_queue_index_r];
  6703. if (DEBUGGING(ECHO)) {
  6704. SERIAL_ECHO_START;
  6705. SERIAL_ECHOLN(current_command);
  6706. }
  6707. // Sanitize the current command:
  6708. // - Skip leading spaces
  6709. // - Bypass N[-0-9][0-9]*[ ]*
  6710. // - Overwrite * with nul to mark the end
  6711. while (*current_command == ' ') ++current_command;
  6712. if (*current_command == 'N' && NUMERIC_SIGNED(current_command[1])) {
  6713. current_command += 2; // skip N[-0-9]
  6714. while (NUMERIC(*current_command)) ++current_command; // skip [0-9]*
  6715. while (*current_command == ' ') ++current_command; // skip [ ]*
  6716. }
  6717. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  6718. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  6719. char *cmd_ptr = current_command;
  6720. // Get the command code, which must be G, M, or T
  6721. char command_code = *cmd_ptr++;
  6722. // Skip spaces to get the numeric part
  6723. while (*cmd_ptr == ' ') cmd_ptr++;
  6724. // Allow for decimal point in command
  6725. #if ENABLED(G38_PROBE_TARGET)
  6726. uint8_t subcode = 0;
  6727. #endif
  6728. uint16_t codenum = 0; // define ahead of goto
  6729. // Bail early if there's no code
  6730. bool code_is_good = NUMERIC(*cmd_ptr);
  6731. if (!code_is_good) goto ExitUnknownCommand;
  6732. // Get and skip the code number
  6733. do {
  6734. codenum = (codenum * 10) + (*cmd_ptr - '0');
  6735. cmd_ptr++;
  6736. } while (NUMERIC(*cmd_ptr));
  6737. // Allow for decimal point in command
  6738. #if ENABLED(G38_PROBE_TARGET)
  6739. if (*cmd_ptr == '.') {
  6740. cmd_ptr++;
  6741. while (NUMERIC(*cmd_ptr))
  6742. subcode = (subcode * 10) + (*cmd_ptr++ - '0');
  6743. }
  6744. #endif
  6745. // Skip all spaces to get to the first argument, or nul
  6746. while (*cmd_ptr == ' ') cmd_ptr++;
  6747. // The command's arguments (if any) start here, for sure!
  6748. current_command_args = cmd_ptr;
  6749. KEEPALIVE_STATE(IN_HANDLER);
  6750. // Handle a known G, M, or T
  6751. switch (command_code) {
  6752. case 'G': switch (codenum) {
  6753. // G0, G1
  6754. case 0:
  6755. case 1:
  6756. #if IS_SCARA
  6757. gcode_G0_G1(codenum == 0);
  6758. #else
  6759. gcode_G0_G1();
  6760. #endif
  6761. break;
  6762. // G2, G3
  6763. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  6764. case 2: // G2 - CW ARC
  6765. case 3: // G3 - CCW ARC
  6766. gcode_G2_G3(codenum == 2);
  6767. break;
  6768. #endif
  6769. // G4 Dwell
  6770. case 4:
  6771. gcode_G4();
  6772. break;
  6773. #if ENABLED(BEZIER_CURVE_SUPPORT)
  6774. // G5
  6775. case 5: // G5 - Cubic B_spline
  6776. gcode_G5();
  6777. break;
  6778. #endif // BEZIER_CURVE_SUPPORT
  6779. #if ENABLED(FWRETRACT)
  6780. case 10: // G10: retract
  6781. case 11: // G11: retract_recover
  6782. gcode_G10_G11(codenum == 10);
  6783. break;
  6784. #endif // FWRETRACT
  6785. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  6786. case 12:
  6787. gcode_G12(); // G12: Nozzle Clean
  6788. break;
  6789. #endif // NOZZLE_CLEAN_FEATURE
  6790. #if ENABLED(INCH_MODE_SUPPORT)
  6791. case 20: //G20: Inch Mode
  6792. gcode_G20();
  6793. break;
  6794. case 21: //G21: MM Mode
  6795. gcode_G21();
  6796. break;
  6797. #endif // INCH_MODE_SUPPORT
  6798. #if ENABLED(NOZZLE_PARK_FEATURE)
  6799. case 27: // G27: Nozzle Park
  6800. gcode_G27();
  6801. break;
  6802. #endif // NOZZLE_PARK_FEATURE
  6803. case 28: // G28: Home all axes, one at a time
  6804. gcode_G28();
  6805. break;
  6806. #if PLANNER_LEVELING
  6807. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points.
  6808. gcode_G29();
  6809. break;
  6810. #endif // PLANNER_LEVELING
  6811. #if HAS_BED_PROBE
  6812. case 30: // G30 Single Z probe
  6813. gcode_G30();
  6814. break;
  6815. #if ENABLED(Z_PROBE_SLED)
  6816. case 31: // G31: dock the sled
  6817. gcode_G31();
  6818. break;
  6819. case 32: // G32: undock the sled
  6820. gcode_G32();
  6821. break;
  6822. #endif // Z_PROBE_SLED
  6823. #endif // HAS_BED_PROBE
  6824. #if ENABLED(G38_PROBE_TARGET)
  6825. case 38: // G38.2 & G38.3
  6826. if (subcode == 2 || subcode == 3)
  6827. gcode_G38(subcode == 2);
  6828. break;
  6829. #endif
  6830. case 90: // G90
  6831. relative_mode = false;
  6832. break;
  6833. case 91: // G91
  6834. relative_mode = true;
  6835. break;
  6836. case 92: // G92
  6837. gcode_G92();
  6838. break;
  6839. }
  6840. break;
  6841. case 'M': switch (codenum) {
  6842. #if ENABLED(ULTIPANEL) || ENABLED(EMERGENCY_PARSER)
  6843. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  6844. case 1: // M1: Conditional stop - Wait for user button press on LCD
  6845. gcode_M0_M1();
  6846. break;
  6847. #endif // ULTIPANEL
  6848. case 17: // M17: Enable all stepper motors
  6849. gcode_M17();
  6850. break;
  6851. #if ENABLED(SDSUPPORT)
  6852. case 20: // M20: list SD card
  6853. gcode_M20(); break;
  6854. case 21: // M21: init SD card
  6855. gcode_M21(); break;
  6856. case 22: // M22: release SD card
  6857. gcode_M22(); break;
  6858. case 23: // M23: Select file
  6859. gcode_M23(); break;
  6860. case 24: // M24: Start SD print
  6861. gcode_M24(); break;
  6862. case 25: // M25: Pause SD print
  6863. gcode_M25(); break;
  6864. case 26: // M26: Set SD index
  6865. gcode_M26(); break;
  6866. case 27: // M27: Get SD status
  6867. gcode_M27(); break;
  6868. case 28: // M28: Start SD write
  6869. gcode_M28(); break;
  6870. case 29: // M29: Stop SD write
  6871. gcode_M29(); break;
  6872. case 30: // M30 <filename> Delete File
  6873. gcode_M30(); break;
  6874. case 32: // M32: Select file and start SD print
  6875. gcode_M32(); break;
  6876. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  6877. case 33: // M33: Get the long full path to a file or folder
  6878. gcode_M33(); break;
  6879. #endif
  6880. case 928: // M928: Start SD write
  6881. gcode_M928(); break;
  6882. #endif //SDSUPPORT
  6883. case 31: // M31: Report time since the start of SD print or last M109
  6884. gcode_M31(); break;
  6885. case 42: // M42: Change pin state
  6886. gcode_M42(); break;
  6887. #if ENABLED(PINS_DEBUGGING)
  6888. case 43: // M43: Read pin state
  6889. gcode_M43(); break;
  6890. #endif
  6891. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  6892. case 48: // M48: Z probe repeatability test
  6893. gcode_M48();
  6894. break;
  6895. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  6896. case 75: // M75: Start print timer
  6897. gcode_M75(); break;
  6898. case 76: // M76: Pause print timer
  6899. gcode_M76(); break;
  6900. case 77: // M77: Stop print timer
  6901. gcode_M77(); break;
  6902. #if ENABLED(PRINTCOUNTER)
  6903. case 78: // M78: Show print statistics
  6904. gcode_M78(); break;
  6905. #endif
  6906. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  6907. case 100: // M100: Free Memory Report
  6908. gcode_M100();
  6909. break;
  6910. #endif
  6911. case 104: // M104: Set hot end temperature
  6912. gcode_M104();
  6913. break;
  6914. case 110: // M110: Set Current Line Number
  6915. gcode_M110();
  6916. break;
  6917. case 111: // M111: Set debug level
  6918. gcode_M111();
  6919. break;
  6920. #if DISABLED(EMERGENCY_PARSER)
  6921. case 108: // M108: Cancel Waiting
  6922. gcode_M108();
  6923. break;
  6924. case 112: // M112: Emergency Stop
  6925. gcode_M112();
  6926. break;
  6927. case 410: // M410 quickstop - Abort all the planned moves.
  6928. gcode_M410();
  6929. break;
  6930. #endif
  6931. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6932. case 113: // M113: Set Host Keepalive interval
  6933. gcode_M113();
  6934. break;
  6935. #endif
  6936. case 140: // M140: Set bed temperature
  6937. gcode_M140();
  6938. break;
  6939. case 105: // M105: Report current temperature
  6940. gcode_M105();
  6941. KEEPALIVE_STATE(NOT_BUSY);
  6942. return; // "ok" already printed
  6943. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  6944. case 155: // M155: Set temperature auto-report interval
  6945. gcode_M155();
  6946. break;
  6947. #endif
  6948. case 109: // M109: Wait for hotend temperature to reach target
  6949. gcode_M109();
  6950. break;
  6951. #if HAS_TEMP_BED
  6952. case 190: // M190: Wait for bed temperature to reach target
  6953. gcode_M190();
  6954. break;
  6955. #endif // HAS_TEMP_BED
  6956. #if FAN_COUNT > 0
  6957. case 106: // M106: Fan On
  6958. gcode_M106();
  6959. break;
  6960. case 107: // M107: Fan Off
  6961. gcode_M107();
  6962. break;
  6963. #endif // FAN_COUNT > 0
  6964. #if ENABLED(BARICUDA)
  6965. // PWM for HEATER_1_PIN
  6966. #if HAS_HEATER_1
  6967. case 126: // M126: valve open
  6968. gcode_M126();
  6969. break;
  6970. case 127: // M127: valve closed
  6971. gcode_M127();
  6972. break;
  6973. #endif // HAS_HEATER_1
  6974. // PWM for HEATER_2_PIN
  6975. #if HAS_HEATER_2
  6976. case 128: // M128: valve open
  6977. gcode_M128();
  6978. break;
  6979. case 129: // M129: valve closed
  6980. gcode_M129();
  6981. break;
  6982. #endif // HAS_HEATER_2
  6983. #endif // BARICUDA
  6984. #if HAS_POWER_SWITCH
  6985. case 80: // M80: Turn on Power Supply
  6986. gcode_M80();
  6987. break;
  6988. #endif // HAS_POWER_SWITCH
  6989. case 81: // M81: Turn off Power, including Power Supply, if possible
  6990. gcode_M81();
  6991. break;
  6992. case 82: // M83: Set E axis normal mode (same as other axes)
  6993. gcode_M82();
  6994. break;
  6995. case 83: // M83: Set E axis relative mode
  6996. gcode_M83();
  6997. break;
  6998. case 18: // M18 => M84
  6999. case 84: // M84: Disable all steppers or set timeout
  7000. gcode_M18_M84();
  7001. break;
  7002. case 85: // M85: Set inactivity stepper shutdown timeout
  7003. gcode_M85();
  7004. break;
  7005. case 92: // M92: Set the steps-per-unit for one or more axes
  7006. gcode_M92();
  7007. break;
  7008. case 114: // M114: Report current position
  7009. gcode_M114();
  7010. break;
  7011. case 115: // M115: Report capabilities
  7012. gcode_M115();
  7013. break;
  7014. case 117: // M117: Set LCD message text, if possible
  7015. gcode_M117();
  7016. break;
  7017. case 119: // M119: Report endstop states
  7018. gcode_M119();
  7019. break;
  7020. case 120: // M120: Enable endstops
  7021. gcode_M120();
  7022. break;
  7023. case 121: // M121: Disable endstops
  7024. gcode_M121();
  7025. break;
  7026. #if ENABLED(HAVE_TMC2130DRIVER)
  7027. case 122: // M122: Diagnose, used to debug TMC2130
  7028. gcode_M122();
  7029. break;
  7030. #endif
  7031. #if ENABLED(ULTIPANEL)
  7032. case 145: // M145: Set material heatup parameters
  7033. gcode_M145();
  7034. break;
  7035. #endif
  7036. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  7037. case 149: // M149: Set temperature units
  7038. gcode_M149();
  7039. break;
  7040. #endif
  7041. #if ENABLED(BLINKM) || ENABLED(RGB_LED)
  7042. case 150: // M150: Set Status LED Color
  7043. gcode_M150();
  7044. break;
  7045. #endif // BLINKM
  7046. #if ENABLED(MIXING_EXTRUDER)
  7047. case 163: // M163: Set a component weight for mixing extruder
  7048. gcode_M163();
  7049. break;
  7050. #if MIXING_VIRTUAL_TOOLS > 1
  7051. case 164: // M164: Save current mix as a virtual extruder
  7052. gcode_M164();
  7053. break;
  7054. #endif
  7055. #if ENABLED(DIRECT_MIXING_IN_G1)
  7056. case 165: // M165: Set multiple mix weights
  7057. gcode_M165();
  7058. break;
  7059. #endif
  7060. #endif
  7061. case 200: // M200: Set filament diameter, E to cubic units
  7062. gcode_M200();
  7063. break;
  7064. case 201: // M201: Set max acceleration for print moves (units/s^2)
  7065. gcode_M201();
  7066. break;
  7067. #if 0 // Not used for Sprinter/grbl gen6
  7068. case 202: // M202
  7069. gcode_M202();
  7070. break;
  7071. #endif
  7072. case 203: // M203: Set max feedrate (units/sec)
  7073. gcode_M203();
  7074. break;
  7075. case 204: // M204: Set acceleration
  7076. gcode_M204();
  7077. break;
  7078. case 205: //M205: Set advanced settings
  7079. gcode_M205();
  7080. break;
  7081. case 206: // M206: Set home offsets
  7082. gcode_M206();
  7083. break;
  7084. #if ENABLED(DELTA)
  7085. case 665: // M665: Set delta configurations
  7086. gcode_M665();
  7087. break;
  7088. #endif
  7089. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  7090. case 666: // M666: Set delta or dual endstop adjustment
  7091. gcode_M666();
  7092. break;
  7093. #endif
  7094. #if ENABLED(FWRETRACT)
  7095. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  7096. gcode_M207();
  7097. break;
  7098. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  7099. gcode_M208();
  7100. break;
  7101. case 209: // M209: Turn Automatic Retract Detection on/off
  7102. gcode_M209();
  7103. break;
  7104. #endif // FWRETRACT
  7105. case 211: // M211: Enable, Disable, and/or Report software endstops
  7106. gcode_M211();
  7107. break;
  7108. #if HOTENDS > 1
  7109. case 218: // M218: Set a tool offset
  7110. gcode_M218();
  7111. break;
  7112. #endif
  7113. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  7114. gcode_M220();
  7115. break;
  7116. case 221: // M221: Set Flow Percentage
  7117. gcode_M221();
  7118. break;
  7119. case 226: // M226: Wait until a pin reaches a state
  7120. gcode_M226();
  7121. break;
  7122. #if HAS_SERVOS
  7123. case 280: // M280: Set servo position absolute
  7124. gcode_M280();
  7125. break;
  7126. #endif // HAS_SERVOS
  7127. #if HAS_BUZZER
  7128. case 300: // M300: Play beep tone
  7129. gcode_M300();
  7130. break;
  7131. #endif // HAS_BUZZER
  7132. #if ENABLED(PIDTEMP)
  7133. case 301: // M301: Set hotend PID parameters
  7134. gcode_M301();
  7135. break;
  7136. #endif // PIDTEMP
  7137. #if ENABLED(PIDTEMPBED)
  7138. case 304: // M304: Set bed PID parameters
  7139. gcode_M304();
  7140. break;
  7141. #endif // PIDTEMPBED
  7142. #if defined(CHDK) || HAS_PHOTOGRAPH
  7143. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  7144. gcode_M240();
  7145. break;
  7146. #endif // CHDK || PHOTOGRAPH_PIN
  7147. #if HAS_LCD_CONTRAST
  7148. case 250: // M250: Set LCD contrast
  7149. gcode_M250();
  7150. break;
  7151. #endif // HAS_LCD_CONTRAST
  7152. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7153. case 260: // M260: Send data to an i2c slave
  7154. gcode_M260();
  7155. break;
  7156. case 261: // M261: Request data from an i2c slave
  7157. gcode_M261();
  7158. break;
  7159. #endif // EXPERIMENTAL_I2CBUS
  7160. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7161. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  7162. gcode_M302();
  7163. break;
  7164. #endif // PREVENT_COLD_EXTRUSION
  7165. case 303: // M303: PID autotune
  7166. gcode_M303();
  7167. break;
  7168. #if ENABLED(MORGAN_SCARA)
  7169. case 360: // M360: SCARA Theta pos1
  7170. if (gcode_M360()) return;
  7171. break;
  7172. case 361: // M361: SCARA Theta pos2
  7173. if (gcode_M361()) return;
  7174. break;
  7175. case 362: // M362: SCARA Psi pos1
  7176. if (gcode_M362()) return;
  7177. break;
  7178. case 363: // M363: SCARA Psi pos2
  7179. if (gcode_M363()) return;
  7180. break;
  7181. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  7182. if (gcode_M364()) return;
  7183. break;
  7184. #endif // SCARA
  7185. case 400: // M400: Finish all moves
  7186. gcode_M400();
  7187. break;
  7188. #if HAS_BED_PROBE
  7189. case 401: // M401: Deploy probe
  7190. gcode_M401();
  7191. break;
  7192. case 402: // M402: Stow probe
  7193. gcode_M402();
  7194. break;
  7195. #endif // HAS_BED_PROBE
  7196. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7197. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  7198. gcode_M404();
  7199. break;
  7200. case 405: // M405: Turn on filament sensor for control
  7201. gcode_M405();
  7202. break;
  7203. case 406: // M406: Turn off filament sensor for control
  7204. gcode_M406();
  7205. break;
  7206. case 407: // M407: Display measured filament diameter
  7207. gcode_M407();
  7208. break;
  7209. #endif // ENABLED(FILAMENT_WIDTH_SENSOR)
  7210. #if PLANNER_LEVELING
  7211. case 420: // M420: Enable/Disable Bed Leveling
  7212. gcode_M420();
  7213. break;
  7214. #endif
  7215. #if ENABLED(MESH_BED_LEVELING)
  7216. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  7217. gcode_M421();
  7218. break;
  7219. #endif
  7220. case 428: // M428: Apply current_position to home_offset
  7221. gcode_M428();
  7222. break;
  7223. case 500: // M500: Store settings in EEPROM
  7224. gcode_M500();
  7225. break;
  7226. case 501: // M501: Read settings from EEPROM
  7227. gcode_M501();
  7228. break;
  7229. case 502: // M502: Revert to default settings
  7230. gcode_M502();
  7231. break;
  7232. case 503: // M503: print settings currently in memory
  7233. gcode_M503();
  7234. break;
  7235. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7236. case 540: // M540: Set abort on endstop hit for SD printing
  7237. gcode_M540();
  7238. break;
  7239. #endif
  7240. #if HAS_BED_PROBE
  7241. case 851: // M851: Set Z Probe Z Offset
  7242. gcode_M851();
  7243. break;
  7244. #endif // HAS_BED_PROBE
  7245. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  7246. case 600: // M600: Pause for filament change
  7247. gcode_M600();
  7248. break;
  7249. #endif // FILAMENT_CHANGE_FEATURE
  7250. #if ENABLED(DUAL_X_CARRIAGE)
  7251. case 605: // M605: Set Dual X Carriage movement mode
  7252. gcode_M605();
  7253. break;
  7254. #endif // DUAL_X_CARRIAGE
  7255. #if ENABLED(LIN_ADVANCE)
  7256. case 905: // M905: Set advance K factor.
  7257. gcode_M905();
  7258. break;
  7259. #endif
  7260. case 907: // M907: Set digital trimpot motor current using axis codes.
  7261. gcode_M907();
  7262. break;
  7263. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  7264. case 908: // M908: Control digital trimpot directly.
  7265. gcode_M908();
  7266. break;
  7267. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  7268. case 909: // M909: Print digipot/DAC current value
  7269. gcode_M909();
  7270. break;
  7271. case 910: // M910: Commit digipot/DAC value to external EEPROM
  7272. gcode_M910();
  7273. break;
  7274. #endif
  7275. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  7276. #if HAS_MICROSTEPS
  7277. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  7278. gcode_M350();
  7279. break;
  7280. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  7281. gcode_M351();
  7282. break;
  7283. #endif // HAS_MICROSTEPS
  7284. #if HAS_CASE_LIGHT
  7285. case 355: // M355 Turn case lights on/off
  7286. gcode_M355();
  7287. break;
  7288. #endif // HAS_CASE_LIGHT
  7289. case 999: // M999: Restart after being Stopped
  7290. gcode_M999();
  7291. break;
  7292. }
  7293. break;
  7294. case 'T':
  7295. gcode_T(codenum);
  7296. break;
  7297. default: code_is_good = false;
  7298. }
  7299. KEEPALIVE_STATE(NOT_BUSY);
  7300. ExitUnknownCommand:
  7301. // Still unknown command? Throw an error
  7302. if (!code_is_good) unknown_command_error();
  7303. ok_to_send();
  7304. }
  7305. /**
  7306. * Send a "Resend: nnn" message to the host to
  7307. * indicate that a command needs to be re-sent.
  7308. */
  7309. void FlushSerialRequestResend() {
  7310. //char command_queue[cmd_queue_index_r][100]="Resend:";
  7311. MYSERIAL.flush();
  7312. SERIAL_PROTOCOLPGM(MSG_RESEND);
  7313. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  7314. ok_to_send();
  7315. }
  7316. /**
  7317. * Send an "ok" message to the host, indicating
  7318. * that a command was successfully processed.
  7319. *
  7320. * If ADVANCED_OK is enabled also include:
  7321. * N<int> Line number of the command, if any
  7322. * P<int> Planner space remaining
  7323. * B<int> Block queue space remaining
  7324. */
  7325. void ok_to_send() {
  7326. refresh_cmd_timeout();
  7327. if (!send_ok[cmd_queue_index_r]) return;
  7328. SERIAL_PROTOCOLPGM(MSG_OK);
  7329. #if ENABLED(ADVANCED_OK)
  7330. char* p = command_queue[cmd_queue_index_r];
  7331. if (*p == 'N') {
  7332. SERIAL_PROTOCOL(' ');
  7333. SERIAL_ECHO(*p++);
  7334. while (NUMERIC_SIGNED(*p))
  7335. SERIAL_ECHO(*p++);
  7336. }
  7337. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  7338. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  7339. #endif
  7340. SERIAL_EOL;
  7341. }
  7342. #if ENABLED(min_software_endstops) || ENABLED(max_software_endstops)
  7343. /**
  7344. * Constrain the given coordinates to the software endstops.
  7345. */
  7346. void clamp_to_software_endstops(float target[XYZ]) {
  7347. #if ENABLED(min_software_endstops)
  7348. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  7349. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  7350. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  7351. #endif
  7352. #if ENABLED(max_software_endstops)
  7353. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  7354. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  7355. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  7356. #endif
  7357. }
  7358. #endif
  7359. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7360. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7361. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  7362. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  7363. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  7364. #define ABL_BG_GRID(X,Y) bed_level_grid_virt[X][Y]
  7365. #else
  7366. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  7367. #define ABL_BG_POINTS_X ABL_GRID_POINTS_X
  7368. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_Y
  7369. #define ABL_BG_GRID(X,Y) bed_level_grid[X][Y]
  7370. #endif
  7371. // Get the Z adjustment for non-linear bed leveling
  7372. float bilinear_z_offset(float cartesian[XYZ]) {
  7373. // XY relative to the probed area
  7374. const float x = RAW_X_POSITION(cartesian[X_AXIS]) - bilinear_start[X_AXIS],
  7375. y = RAW_Y_POSITION(cartesian[Y_AXIS]) - bilinear_start[Y_AXIS];
  7376. // Convert to grid box units
  7377. float ratio_x = x / ABL_BG_SPACING(X_AXIS),
  7378. ratio_y = y / ABL_BG_SPACING(Y_AXIS);
  7379. // Whole units for the grid line indices. Constrained within bounds.
  7380. const int gridx = constrain(floor(ratio_x), 0, ABL_BG_POINTS_X - 1),
  7381. gridy = constrain(floor(ratio_y), 0, ABL_BG_POINTS_Y - 1),
  7382. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1),
  7383. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  7384. // Subtract whole to get the ratio within the grid box
  7385. ratio_x -= gridx; ratio_y -= gridy;
  7386. // Never less than 0.0. (Over 1.0 is fine due to previous contraints.)
  7387. NOLESS(ratio_x, 0); NOLESS(ratio_y, 0);
  7388. // Z at the box corners
  7389. const float z1 = ABL_BG_GRID(gridx, gridy), // left-front
  7390. z2 = ABL_BG_GRID(gridx, nexty), // left-back
  7391. z3 = ABL_BG_GRID(nextx, gridy), // right-front
  7392. z4 = ABL_BG_GRID(nextx, nexty), // right-back
  7393. // Bilinear interpolate
  7394. L = z1 + (z2 - z1) * ratio_y, // Linear interp. LF -> LB
  7395. R = z3 + (z4 - z3) * ratio_y, // Linear interp. RF -> RB
  7396. offset = L + ratio_x * (R - L);
  7397. /*
  7398. static float last_offset = 0;
  7399. if (fabs(last_offset - offset) > 0.2) {
  7400. SERIAL_ECHOPGM("Sudden Shift at ");
  7401. SERIAL_ECHOPAIR("x=", x);
  7402. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  7403. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  7404. SERIAL_ECHOPAIR(" y=", y);
  7405. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  7406. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  7407. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  7408. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  7409. SERIAL_ECHOPAIR(" z1=", z1);
  7410. SERIAL_ECHOPAIR(" z2=", z2);
  7411. SERIAL_ECHOPAIR(" z3=", z3);
  7412. SERIAL_ECHOLNPAIR(" z4=", z4);
  7413. SERIAL_ECHOPAIR(" L=", L);
  7414. SERIAL_ECHOPAIR(" R=", R);
  7415. SERIAL_ECHOLNPAIR(" offset=", offset);
  7416. }
  7417. last_offset = offset;
  7418. //*/
  7419. return offset;
  7420. }
  7421. #endif // AUTO_BED_LEVELING_BILINEAR
  7422. #if ENABLED(DELTA)
  7423. /**
  7424. * Recalculate factors used for delta kinematics whenever
  7425. * settings have been changed (e.g., by M665).
  7426. */
  7427. void recalc_delta_settings(float radius, float diagonal_rod) {
  7428. delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  7429. delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1);
  7430. delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  7431. delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2);
  7432. delta_tower3_x = 0.0; // back middle tower
  7433. delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3);
  7434. delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1);
  7435. delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2);
  7436. delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3);
  7437. }
  7438. #if ENABLED(DELTA_FAST_SQRT)
  7439. /**
  7440. * Fast inverse sqrt from Quake III Arena
  7441. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  7442. */
  7443. float Q_rsqrt(float number) {
  7444. long i;
  7445. float x2, y;
  7446. const float threehalfs = 1.5f;
  7447. x2 = number * 0.5f;
  7448. y = number;
  7449. i = * ( long * ) &y; // evil floating point bit level hacking
  7450. i = 0x5f3759df - ( i >> 1 ); // what the f***?
  7451. y = * ( float * ) &i;
  7452. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  7453. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  7454. return y;
  7455. }
  7456. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  7457. #else
  7458. #define _SQRT(n) sqrt(n)
  7459. #endif
  7460. /**
  7461. * Delta Inverse Kinematics
  7462. *
  7463. * Calculate the tower positions for a given logical
  7464. * position, storing the result in the delta[] array.
  7465. *
  7466. * This is an expensive calculation, requiring 3 square
  7467. * roots per segmented linear move, and strains the limits
  7468. * of a Mega2560 with a Graphical Display.
  7469. *
  7470. * Suggested optimizations include:
  7471. *
  7472. * - Disable the home_offset (M206) and/or position_shift (G92)
  7473. * features to remove up to 12 float additions.
  7474. *
  7475. * - Use a fast-inverse-sqrt function and add the reciprocal.
  7476. * (see above)
  7477. */
  7478. // Macro to obtain the Z position of an individual tower
  7479. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  7480. delta_diagonal_rod_2_tower_##T - HYPOT2( \
  7481. delta_tower##T##_x - raw[X_AXIS], \
  7482. delta_tower##T##_y - raw[Y_AXIS] \
  7483. ) \
  7484. )
  7485. #define DELTA_RAW_IK() do { \
  7486. delta[A_AXIS] = DELTA_Z(1); \
  7487. delta[B_AXIS] = DELTA_Z(2); \
  7488. delta[C_AXIS] = DELTA_Z(3); \
  7489. } while(0)
  7490. #define DELTA_LOGICAL_IK() do { \
  7491. const float raw[XYZ] = { \
  7492. RAW_X_POSITION(logical[X_AXIS]), \
  7493. RAW_Y_POSITION(logical[Y_AXIS]), \
  7494. RAW_Z_POSITION(logical[Z_AXIS]) \
  7495. }; \
  7496. DELTA_RAW_IK(); \
  7497. } while(0)
  7498. #define DELTA_DEBUG() do { \
  7499. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  7500. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  7501. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  7502. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  7503. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  7504. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  7505. } while(0)
  7506. void inverse_kinematics(const float logical[XYZ]) {
  7507. DELTA_LOGICAL_IK();
  7508. // DELTA_DEBUG();
  7509. }
  7510. /**
  7511. * Calculate the highest Z position where the
  7512. * effector has the full range of XY motion.
  7513. */
  7514. float delta_safe_distance_from_top() {
  7515. float cartesian[XYZ] = {
  7516. LOGICAL_X_POSITION(0),
  7517. LOGICAL_Y_POSITION(0),
  7518. LOGICAL_Z_POSITION(0)
  7519. };
  7520. inverse_kinematics(cartesian);
  7521. float distance = delta[A_AXIS];
  7522. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  7523. inverse_kinematics(cartesian);
  7524. return abs(distance - delta[A_AXIS]);
  7525. }
  7526. /**
  7527. * Delta Forward Kinematics
  7528. *
  7529. * See the Wikipedia article "Trilateration"
  7530. * https://en.wikipedia.org/wiki/Trilateration
  7531. *
  7532. * Establish a new coordinate system in the plane of the
  7533. * three carriage points. This system has its origin at
  7534. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  7535. * plane with a Z component of zero.
  7536. * We will define unit vectors in this coordinate system
  7537. * in our original coordinate system. Then when we calculate
  7538. * the Xnew, Ynew and Znew values, we can translate back into
  7539. * the original system by moving along those unit vectors
  7540. * by the corresponding values.
  7541. *
  7542. * Variable names matched to Marlin, c-version, and avoid the
  7543. * use of any vector library.
  7544. *
  7545. * by Andreas Hardtung 2016-06-07
  7546. * based on a Java function from "Delta Robot Kinematics V3"
  7547. * by Steve Graves
  7548. *
  7549. * The result is stored in the cartes[] array.
  7550. */
  7551. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  7552. // Create a vector in old coordinates along x axis of new coordinate
  7553. float p12[3] = { delta_tower2_x - delta_tower1_x, delta_tower2_y - delta_tower1_y, z2 - z1 };
  7554. // Get the Magnitude of vector.
  7555. float d = sqrt( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  7556. // Create unit vector by dividing by magnitude.
  7557. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  7558. // Get the vector from the origin of the new system to the third point.
  7559. float p13[3] = { delta_tower3_x - delta_tower1_x, delta_tower3_y - delta_tower1_y, z3 - z1 };
  7560. // Use the dot product to find the component of this vector on the X axis.
  7561. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  7562. // Create a vector along the x axis that represents the x component of p13.
  7563. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  7564. // Subtract the X component from the original vector leaving only Y. We use the
  7565. // variable that will be the unit vector after we scale it.
  7566. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  7567. // The magnitude of Y component
  7568. float j = sqrt( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  7569. // Convert to a unit vector
  7570. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  7571. // The cross product of the unit x and y is the unit z
  7572. // float[] ez = vectorCrossProd(ex, ey);
  7573. float ez[3] = {
  7574. ex[1] * ey[2] - ex[2] * ey[1],
  7575. ex[2] * ey[0] - ex[0] * ey[2],
  7576. ex[0] * ey[1] - ex[1] * ey[0]
  7577. };
  7578. // We now have the d, i and j values defined in Wikipedia.
  7579. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  7580. float Xnew = (delta_diagonal_rod_2_tower_1 - delta_diagonal_rod_2_tower_2 + sq(d)) / (d * 2),
  7581. Ynew = ((delta_diagonal_rod_2_tower_1 - delta_diagonal_rod_2_tower_3 + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  7582. Znew = sqrt(delta_diagonal_rod_2_tower_1 - HYPOT2(Xnew, Ynew));
  7583. // Start from the origin of the old coordinates and add vectors in the
  7584. // old coords that represent the Xnew, Ynew and Znew to find the point
  7585. // in the old system.
  7586. cartes[X_AXIS] = delta_tower1_x + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  7587. cartes[Y_AXIS] = delta_tower1_y + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  7588. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  7589. }
  7590. void forward_kinematics_DELTA(float point[ABC]) {
  7591. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  7592. }
  7593. #endif // DELTA
  7594. /**
  7595. * Get the stepper positions in the cartes[] array.
  7596. * Forward kinematics are applied for DELTA and SCARA.
  7597. *
  7598. * The result is in the current coordinate space with
  7599. * leveling applied. The coordinates need to be run through
  7600. * unapply_leveling to obtain the "ideal" coordinates
  7601. * suitable for current_position, etc.
  7602. */
  7603. void get_cartesian_from_steppers() {
  7604. #if ENABLED(DELTA)
  7605. forward_kinematics_DELTA(
  7606. stepper.get_axis_position_mm(A_AXIS),
  7607. stepper.get_axis_position_mm(B_AXIS),
  7608. stepper.get_axis_position_mm(C_AXIS)
  7609. );
  7610. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  7611. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  7612. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  7613. #elif IS_SCARA
  7614. forward_kinematics_SCARA(
  7615. stepper.get_axis_position_degrees(A_AXIS),
  7616. stepper.get_axis_position_degrees(B_AXIS)
  7617. );
  7618. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  7619. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  7620. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  7621. #else
  7622. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  7623. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  7624. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  7625. #endif
  7626. }
  7627. /**
  7628. * Set the current_position for an axis based on
  7629. * the stepper positions, removing any leveling that
  7630. * may have been applied.
  7631. */
  7632. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  7633. get_cartesian_from_steppers();
  7634. #if PLANNER_LEVELING
  7635. planner.unapply_leveling(cartes);
  7636. #endif
  7637. if (axis == ALL_AXES)
  7638. memcpy(current_position, cartes, sizeof(cartes));
  7639. else
  7640. current_position[axis] = cartes[axis];
  7641. }
  7642. #if ENABLED(MESH_BED_LEVELING)
  7643. /**
  7644. * Prepare a mesh-leveled linear move in a Cartesian setup,
  7645. * splitting the move where it crosses mesh borders.
  7646. */
  7647. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  7648. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X_AXIS)),
  7649. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y_AXIS)),
  7650. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  7651. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  7652. NOMORE(cx1, MESH_NUM_X_POINTS - 2);
  7653. NOMORE(cy1, MESH_NUM_Y_POINTS - 2);
  7654. NOMORE(cx2, MESH_NUM_X_POINTS - 2);
  7655. NOMORE(cy2, MESH_NUM_Y_POINTS - 2);
  7656. if (cx1 == cx2 && cy1 == cy2) {
  7657. // Start and end on same mesh square
  7658. line_to_destination(fr_mm_s);
  7659. set_current_to_destination();
  7660. return;
  7661. }
  7662. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  7663. float normalized_dist, end[XYZE];
  7664. // Split at the left/front border of the right/top square
  7665. int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  7666. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  7667. memcpy(end, destination, sizeof(end));
  7668. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.get_probe_x(gcx));
  7669. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  7670. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  7671. CBI(x_splits, gcx);
  7672. }
  7673. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  7674. memcpy(end, destination, sizeof(end));
  7675. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.get_probe_y(gcy));
  7676. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  7677. destination[X_AXIS] = MBL_SEGMENT_END(X);
  7678. CBI(y_splits, gcy);
  7679. }
  7680. else {
  7681. // Already split on a border
  7682. line_to_destination(fr_mm_s);
  7683. set_current_to_destination();
  7684. return;
  7685. }
  7686. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  7687. destination[E_AXIS] = MBL_SEGMENT_END(E);
  7688. // Do the split and look for more borders
  7689. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  7690. // Restore destination from stack
  7691. memcpy(destination, end, sizeof(end));
  7692. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  7693. }
  7694. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  7695. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) / ABL_BG_SPACING(A##_AXIS))
  7696. /**
  7697. * Prepare a bilinear-leveled linear move on Cartesian,
  7698. * splitting the move where it crosses grid borders.
  7699. */
  7700. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  7701. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  7702. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  7703. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  7704. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  7705. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  7706. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  7707. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  7708. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  7709. if (cx1 == cx2 && cy1 == cy2) {
  7710. // Start and end on same mesh square
  7711. line_to_destination(fr_mm_s);
  7712. set_current_to_destination();
  7713. return;
  7714. }
  7715. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  7716. float normalized_dist, end[XYZE];
  7717. // Split at the left/front border of the right/top square
  7718. int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  7719. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  7720. memcpy(end, destination, sizeof(end));
  7721. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  7722. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  7723. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  7724. CBI(x_splits, gcx);
  7725. }
  7726. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  7727. memcpy(end, destination, sizeof(end));
  7728. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  7729. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  7730. destination[X_AXIS] = LINE_SEGMENT_END(X);
  7731. CBI(y_splits, gcy);
  7732. }
  7733. else {
  7734. // Already split on a border
  7735. line_to_destination(fr_mm_s);
  7736. set_current_to_destination();
  7737. return;
  7738. }
  7739. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  7740. destination[E_AXIS] = LINE_SEGMENT_END(E);
  7741. // Do the split and look for more borders
  7742. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  7743. // Restore destination from stack
  7744. memcpy(destination, end, sizeof(end));
  7745. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  7746. }
  7747. #endif // AUTO_BED_LEVELING_BILINEAR
  7748. #if IS_KINEMATIC
  7749. /**
  7750. * Prepare a linear move in a DELTA or SCARA setup.
  7751. *
  7752. * This calls planner.buffer_line several times, adding
  7753. * small incremental moves for DELTA or SCARA.
  7754. */
  7755. inline bool prepare_kinematic_move_to(float ltarget[NUM_AXIS]) {
  7756. // Get the top feedrate of the move in the XY plane
  7757. float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  7758. // If the move is only in Z/E don't split up the move
  7759. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  7760. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  7761. return true;
  7762. }
  7763. // Get the cartesian distances moved in XYZE
  7764. float difference[NUM_AXIS];
  7765. LOOP_XYZE(i) difference[i] = ltarget[i] - current_position[i];
  7766. // Get the linear distance in XYZ
  7767. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  7768. // If the move is very short, check the E move distance
  7769. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = abs(difference[E_AXIS]);
  7770. // No E move either? Game over.
  7771. if (UNEAR_ZERO(cartesian_mm)) return false;
  7772. // Minimum number of seconds to move the given distance
  7773. float seconds = cartesian_mm / _feedrate_mm_s;
  7774. // The number of segments-per-second times the duration
  7775. // gives the number of segments
  7776. uint16_t segments = delta_segments_per_second * seconds;
  7777. // For SCARA minimum segment size is 0.5mm
  7778. #if IS_SCARA
  7779. NOMORE(segments, cartesian_mm * 2);
  7780. #endif
  7781. // At least one segment is required
  7782. NOLESS(segments, 1);
  7783. // The approximate length of each segment
  7784. float segment_distance[XYZE] = {
  7785. difference[X_AXIS] / segments,
  7786. difference[Y_AXIS] / segments,
  7787. difference[Z_AXIS] / segments,
  7788. difference[E_AXIS] / segments
  7789. };
  7790. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  7791. // SERIAL_ECHOPAIR(" seconds=", seconds);
  7792. // SERIAL_ECHOLNPAIR(" segments=", segments);
  7793. // Drop one segment so the last move is to the exact target.
  7794. // If there's only 1 segment, loops will be skipped entirely.
  7795. --segments;
  7796. // Using "raw" coordinates saves 6 float subtractions
  7797. // per segment, saving valuable CPU cycles
  7798. #if ENABLED(USE_RAW_KINEMATICS)
  7799. // Get the raw current position as starting point
  7800. float raw[XYZE] = {
  7801. RAW_CURRENT_POSITION(X_AXIS),
  7802. RAW_CURRENT_POSITION(Y_AXIS),
  7803. RAW_CURRENT_POSITION(Z_AXIS),
  7804. current_position[E_AXIS]
  7805. };
  7806. #define DELTA_VAR raw
  7807. // Delta can inline its kinematics
  7808. #if ENABLED(DELTA)
  7809. #define DELTA_IK() DELTA_RAW_IK()
  7810. #else
  7811. #define DELTA_IK() inverse_kinematics(raw)
  7812. #endif
  7813. #else
  7814. // Get the logical current position as starting point
  7815. float logical[XYZE];
  7816. memcpy(logical, current_position, sizeof(logical));
  7817. #define DELTA_VAR logical
  7818. // Delta can inline its kinematics
  7819. #if ENABLED(DELTA)
  7820. #define DELTA_IK() DELTA_LOGICAL_IK()
  7821. #else
  7822. #define DELTA_IK() inverse_kinematics(logical)
  7823. #endif
  7824. #endif
  7825. #if ENABLED(USE_DELTA_IK_INTERPOLATION)
  7826. // Only interpolate XYZ. Advance E normally.
  7827. #define DELTA_NEXT(ADDEND) LOOP_XYZ(i) DELTA_VAR[i] += ADDEND;
  7828. // Get the starting delta if interpolation is possible
  7829. if (segments >= 2) {
  7830. DELTA_IK();
  7831. ADJUST_DELTA(DELTA_VAR); // Adjust Z if bed leveling is enabled
  7832. }
  7833. // Loop using decrement
  7834. for (uint16_t s = segments + 1; --s;) {
  7835. // Are there at least 2 moves left?
  7836. if (s >= 2) {
  7837. // Save the previous delta for interpolation
  7838. float prev_delta[ABC] = { delta[A_AXIS], delta[B_AXIS], delta[C_AXIS] };
  7839. // Get the delta 2 segments ahead (rather than the next)
  7840. DELTA_NEXT(segment_distance[i] + segment_distance[i]);
  7841. // Advance E normally
  7842. DELTA_VAR[E_AXIS] += segment_distance[E_AXIS];
  7843. // Get the exact delta for the move after this
  7844. DELTA_IK();
  7845. ADJUST_DELTA(DELTA_VAR); // Adjust Z if bed leveling is enabled
  7846. // Move to the interpolated delta position first
  7847. planner.buffer_line(
  7848. (prev_delta[A_AXIS] + delta[A_AXIS]) * 0.5,
  7849. (prev_delta[B_AXIS] + delta[B_AXIS]) * 0.5,
  7850. (prev_delta[C_AXIS] + delta[C_AXIS]) * 0.5,
  7851. DELTA_VAR[E_AXIS], _feedrate_mm_s, active_extruder
  7852. );
  7853. // Advance E once more for the next move
  7854. DELTA_VAR[E_AXIS] += segment_distance[E_AXIS];
  7855. // Do an extra decrement of the loop
  7856. --s;
  7857. }
  7858. else {
  7859. // Get the last segment delta. (Used when segments is odd)
  7860. DELTA_NEXT(segment_distance[i]);
  7861. DELTA_VAR[E_AXIS] += segment_distance[E_AXIS];
  7862. DELTA_IK();
  7863. ADJUST_DELTA(DELTA_VAR); // Adjust Z if bed leveling is enabled
  7864. }
  7865. // Move to the non-interpolated position
  7866. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], DELTA_VAR[E_AXIS], _feedrate_mm_s, active_extruder);
  7867. }
  7868. #else
  7869. #define DELTA_NEXT(ADDEND) LOOP_XYZE(i) DELTA_VAR[i] += ADDEND;
  7870. // For non-interpolated delta calculate every segment
  7871. for (uint16_t s = segments + 1; --s;) {
  7872. DELTA_NEXT(segment_distance[i]);
  7873. planner.buffer_line_kinematic(DELTA_VAR, _feedrate_mm_s, active_extruder);
  7874. }
  7875. #endif
  7876. // Since segment_distance is only approximate,
  7877. // the final move must be to the exact destination.
  7878. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  7879. return true;
  7880. }
  7881. #else // !IS_KINEMATIC
  7882. /**
  7883. * Prepare a linear move in a Cartesian setup.
  7884. * If Mesh Bed Leveling is enabled, perform a mesh move.
  7885. */
  7886. inline bool prepare_move_to_destination_cartesian() {
  7887. // Do not use feedrate_percentage for E or Z only moves
  7888. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  7889. line_to_destination();
  7890. }
  7891. else {
  7892. #if ENABLED(MESH_BED_LEVELING)
  7893. if (mbl.active()) {
  7894. mesh_line_to_destination(MMS_SCALED(feedrate_mm_s));
  7895. return false;
  7896. }
  7897. else
  7898. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7899. if (planner.abl_enabled) {
  7900. bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s));
  7901. return false;
  7902. }
  7903. else
  7904. #endif
  7905. line_to_destination(MMS_SCALED(feedrate_mm_s));
  7906. }
  7907. return true;
  7908. }
  7909. #endif // !IS_KINEMATIC
  7910. #if ENABLED(DUAL_X_CARRIAGE)
  7911. /**
  7912. * Prepare a linear move in a dual X axis setup
  7913. */
  7914. inline bool prepare_move_to_destination_dualx() {
  7915. if (active_extruder_parked) {
  7916. switch (dual_x_carriage_mode) {
  7917. case DXC_FULL_CONTROL_MODE:
  7918. break;
  7919. case DXC_AUTO_PARK_MODE:
  7920. if (current_position[E_AXIS] == destination[E_AXIS]) {
  7921. // This is a travel move (with no extrusion)
  7922. // Skip it, but keep track of the current position
  7923. // (so it can be used as the start of the next non-travel move)
  7924. if (delayed_move_time != 0xFFFFFFFFUL) {
  7925. set_current_to_destination();
  7926. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  7927. delayed_move_time = millis();
  7928. return false;
  7929. }
  7930. }
  7931. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  7932. for (uint8_t i = 0; i < 3; i++)
  7933. planner.buffer_line(
  7934. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  7935. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  7936. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  7937. current_position[E_AXIS],
  7938. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  7939. active_extruder
  7940. );
  7941. delayed_move_time = 0;
  7942. active_extruder_parked = false;
  7943. break;
  7944. case DXC_DUPLICATION_MODE:
  7945. if (active_extruder == 0) {
  7946. // move duplicate extruder into correct duplication position.
  7947. planner.set_position_mm(
  7948. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  7949. current_position[Y_AXIS],
  7950. current_position[Z_AXIS],
  7951. current_position[E_AXIS]
  7952. );
  7953. planner.buffer_line(
  7954. current_position[X_AXIS] + duplicate_extruder_x_offset,
  7955. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  7956. planner.max_feedrate_mm_s[X_AXIS], 1
  7957. );
  7958. SYNC_PLAN_POSITION_KINEMATIC();
  7959. stepper.synchronize();
  7960. extruder_duplication_enabled = true;
  7961. active_extruder_parked = false;
  7962. }
  7963. break;
  7964. }
  7965. }
  7966. return true;
  7967. }
  7968. #endif // DUAL_X_CARRIAGE
  7969. /**
  7970. * Prepare a single move and get ready for the next one
  7971. *
  7972. * This may result in several calls to planner.buffer_line to
  7973. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  7974. */
  7975. void prepare_move_to_destination() {
  7976. clamp_to_software_endstops(destination);
  7977. refresh_cmd_timeout();
  7978. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7979. if (!DEBUGGING(DRYRUN)) {
  7980. if (destination[E_AXIS] != current_position[E_AXIS]) {
  7981. if (thermalManager.tooColdToExtrude(active_extruder)) {
  7982. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  7983. SERIAL_ECHO_START;
  7984. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  7985. }
  7986. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  7987. if (labs(destination[E_AXIS] - current_position[E_AXIS]) > EXTRUDE_MAXLENGTH) {
  7988. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  7989. SERIAL_ECHO_START;
  7990. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  7991. }
  7992. #endif
  7993. }
  7994. }
  7995. #endif
  7996. #if IS_KINEMATIC
  7997. if (!prepare_kinematic_move_to(destination)) return;
  7998. #else
  7999. #if ENABLED(DUAL_X_CARRIAGE)
  8000. if (!prepare_move_to_destination_dualx()) return;
  8001. #endif
  8002. if (!prepare_move_to_destination_cartesian()) return;
  8003. #endif
  8004. set_current_to_destination();
  8005. }
  8006. #if ENABLED(ARC_SUPPORT)
  8007. /**
  8008. * Plan an arc in 2 dimensions
  8009. *
  8010. * The arc is approximated by generating many small linear segments.
  8011. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  8012. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  8013. * larger segments will tend to be more efficient. Your slicer should have
  8014. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  8015. */
  8016. void plan_arc(
  8017. float logical[NUM_AXIS], // Destination position
  8018. float* offset, // Center of rotation relative to current_position
  8019. uint8_t clockwise // Clockwise?
  8020. ) {
  8021. float radius = HYPOT(offset[X_AXIS], offset[Y_AXIS]),
  8022. center_X = current_position[X_AXIS] + offset[X_AXIS],
  8023. center_Y = current_position[Y_AXIS] + offset[Y_AXIS],
  8024. linear_travel = logical[Z_AXIS] - current_position[Z_AXIS],
  8025. extruder_travel = logical[E_AXIS] - current_position[E_AXIS],
  8026. r_X = -offset[X_AXIS], // Radius vector from center to current location
  8027. r_Y = -offset[Y_AXIS],
  8028. rt_X = logical[X_AXIS] - center_X,
  8029. rt_Y = logical[Y_AXIS] - center_Y;
  8030. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  8031. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  8032. if (angular_travel < 0) angular_travel += RADIANS(360);
  8033. if (clockwise) angular_travel -= RADIANS(360);
  8034. // Make a circle if the angular rotation is 0
  8035. if (angular_travel == 0 && current_position[X_AXIS] == logical[X_AXIS] && current_position[Y_AXIS] == logical[Y_AXIS])
  8036. angular_travel += RADIANS(360);
  8037. float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel));
  8038. if (mm_of_travel < 0.001) return;
  8039. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  8040. if (segments == 0) segments = 1;
  8041. /**
  8042. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  8043. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  8044. * r_T = [cos(phi) -sin(phi);
  8045. * sin(phi) cos(phi)] * r ;
  8046. *
  8047. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  8048. * defined from the circle center to the initial position. Each line segment is formed by successive
  8049. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  8050. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  8051. * all double numbers are single precision on the Arduino. (True double precision will not have
  8052. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  8053. * tool precision in some cases. Therefore, arc path correction is implemented.
  8054. *
  8055. * Small angle approximation may be used to reduce computation overhead further. This approximation
  8056. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  8057. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  8058. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  8059. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  8060. * issue for CNC machines with the single precision Arduino calculations.
  8061. *
  8062. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  8063. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  8064. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  8065. * This is important when there are successive arc motions.
  8066. */
  8067. // Vector rotation matrix values
  8068. float arc_target[XYZE],
  8069. theta_per_segment = angular_travel / segments,
  8070. linear_per_segment = linear_travel / segments,
  8071. extruder_per_segment = extruder_travel / segments,
  8072. sin_T = theta_per_segment,
  8073. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  8074. // Initialize the linear axis
  8075. arc_target[Z_AXIS] = current_position[Z_AXIS];
  8076. // Initialize the extruder axis
  8077. arc_target[E_AXIS] = current_position[E_AXIS];
  8078. float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  8079. millis_t next_idle_ms = millis() + 200UL;
  8080. int8_t count = 0;
  8081. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  8082. thermalManager.manage_heater();
  8083. if (ELAPSED(millis(), next_idle_ms)) {
  8084. next_idle_ms = millis() + 200UL;
  8085. idle();
  8086. }
  8087. if (++count < N_ARC_CORRECTION) {
  8088. // Apply vector rotation matrix to previous r_X / 1
  8089. float r_new_Y = r_X * sin_T + r_Y * cos_T;
  8090. r_X = r_X * cos_T - r_Y * sin_T;
  8091. r_Y = r_new_Y;
  8092. }
  8093. else {
  8094. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  8095. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  8096. // To reduce stuttering, the sin and cos could be computed at different times.
  8097. // For now, compute both at the same time.
  8098. float cos_Ti = cos(i * theta_per_segment),
  8099. sin_Ti = sin(i * theta_per_segment);
  8100. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  8101. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  8102. count = 0;
  8103. }
  8104. // Update arc_target location
  8105. arc_target[X_AXIS] = center_X + r_X;
  8106. arc_target[Y_AXIS] = center_Y + r_Y;
  8107. arc_target[Z_AXIS] += linear_per_segment;
  8108. arc_target[E_AXIS] += extruder_per_segment;
  8109. clamp_to_software_endstops(arc_target);
  8110. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  8111. }
  8112. // Ensure last segment arrives at target location.
  8113. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  8114. // As far as the parser is concerned, the position is now == target. In reality the
  8115. // motion control system might still be processing the action and the real tool position
  8116. // in any intermediate location.
  8117. set_current_to_destination();
  8118. }
  8119. #endif
  8120. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8121. void plan_cubic_move(const float offset[4]) {
  8122. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  8123. // As far as the parser is concerned, the position is now == destination. In reality the
  8124. // motion control system might still be processing the action and the real tool position
  8125. // in any intermediate location.
  8126. set_current_to_destination();
  8127. }
  8128. #endif // BEZIER_CURVE_SUPPORT
  8129. #if HAS_CONTROLLERFAN
  8130. void controllerFan() {
  8131. static millis_t lastMotorOn = 0; // Last time a motor was turned on
  8132. static millis_t nextMotorCheck = 0; // Last time the state was checked
  8133. millis_t ms = millis();
  8134. if (ELAPSED(ms, nextMotorCheck)) {
  8135. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  8136. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_bed > 0
  8137. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  8138. #if E_STEPPERS > 1
  8139. || E1_ENABLE_READ == E_ENABLE_ON
  8140. #if HAS_X2_ENABLE
  8141. || X2_ENABLE_READ == X_ENABLE_ON
  8142. #endif
  8143. #if E_STEPPERS > 2
  8144. || E2_ENABLE_READ == E_ENABLE_ON
  8145. #if E_STEPPERS > 3
  8146. || E3_ENABLE_READ == E_ENABLE_ON
  8147. #endif
  8148. #endif
  8149. #endif
  8150. ) {
  8151. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  8152. }
  8153. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  8154. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  8155. // allows digital or PWM fan output to be used (see M42 handling)
  8156. digitalWrite(CONTROLLERFAN_PIN, speed);
  8157. analogWrite(CONTROLLERFAN_PIN, speed);
  8158. }
  8159. }
  8160. #endif // HAS_CONTROLLERFAN
  8161. #if ENABLED(MORGAN_SCARA)
  8162. /**
  8163. * Morgan SCARA Forward Kinematics. Results in cartes[].
  8164. * Maths and first version by QHARLEY.
  8165. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  8166. */
  8167. void forward_kinematics_SCARA(const float &a, const float &b) {
  8168. float a_sin = sin(RADIANS(a)) * L1,
  8169. a_cos = cos(RADIANS(a)) * L1,
  8170. b_sin = sin(RADIANS(b)) * L2,
  8171. b_cos = cos(RADIANS(b)) * L2;
  8172. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  8173. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  8174. /*
  8175. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  8176. SERIAL_ECHOPAIR(" b=", b);
  8177. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  8178. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  8179. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  8180. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  8181. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  8182. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  8183. //*/
  8184. }
  8185. /**
  8186. * Morgan SCARA Inverse Kinematics. Results in delta[].
  8187. *
  8188. * See http://forums.reprap.org/read.php?185,283327
  8189. *
  8190. * Maths and first version by QHARLEY.
  8191. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  8192. */
  8193. void inverse_kinematics(const float logical[XYZ]) {
  8194. static float C2, S2, SK1, SK2, THETA, PSI;
  8195. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  8196. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  8197. if (L1 == L2)
  8198. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  8199. else
  8200. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  8201. S2 = sqrt(sq(C2) - 1);
  8202. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  8203. SK1 = L1 + L2 * C2;
  8204. // Rotated Arm2 gives the distance from Arm1 to Arm2
  8205. SK2 = L2 * S2;
  8206. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  8207. THETA = atan2(SK1, SK2) - atan2(sx, sy);
  8208. // Angle of Arm2
  8209. PSI = atan2(S2, C2);
  8210. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  8211. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  8212. delta[C_AXIS] = logical[Z_AXIS];
  8213. /*
  8214. DEBUG_POS("SCARA IK", logical);
  8215. DEBUG_POS("SCARA IK", delta);
  8216. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  8217. SERIAL_ECHOPAIR(",", sy);
  8218. SERIAL_ECHOPAIR(" C2=", C2);
  8219. SERIAL_ECHOPAIR(" S2=", S2);
  8220. SERIAL_ECHOPAIR(" Theta=", THETA);
  8221. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  8222. //*/
  8223. }
  8224. #endif // MORGAN_SCARA
  8225. #if ENABLED(TEMP_STAT_LEDS)
  8226. static bool red_led = false;
  8227. static millis_t next_status_led_update_ms = 0;
  8228. void handle_status_leds(void) {
  8229. if (ELAPSED(millis(), next_status_led_update_ms)) {
  8230. next_status_led_update_ms += 500; // Update every 0.5s
  8231. float max_temp = 0.0;
  8232. #if HAS_TEMP_BED
  8233. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  8234. #endif
  8235. HOTEND_LOOP() {
  8236. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  8237. }
  8238. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  8239. if (new_led != red_led) {
  8240. red_led = new_led;
  8241. #if PIN_EXISTS(STAT_LED_RED)
  8242. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  8243. #if PIN_EXISTS(STAT_LED_BLUE)
  8244. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  8245. #endif
  8246. #else
  8247. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  8248. #endif
  8249. }
  8250. }
  8251. }
  8252. #endif
  8253. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8254. void handle_filament_runout() {
  8255. if (!filament_ran_out) {
  8256. filament_ran_out = true;
  8257. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  8258. stepper.synchronize();
  8259. }
  8260. }
  8261. #endif // FILAMENT_RUNOUT_SENSOR
  8262. #if ENABLED(FAST_PWM_FAN)
  8263. void setPwmFrequency(uint8_t pin, int val) {
  8264. val &= 0x07;
  8265. switch (digitalPinToTimer(pin)) {
  8266. #if defined(TCCR0A)
  8267. case TIMER0A:
  8268. case TIMER0B:
  8269. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8270. // TCCR0B |= val;
  8271. break;
  8272. #endif
  8273. #if defined(TCCR1A)
  8274. case TIMER1A:
  8275. case TIMER1B:
  8276. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8277. // TCCR1B |= val;
  8278. break;
  8279. #endif
  8280. #if defined(TCCR2)
  8281. case TIMER2:
  8282. case TIMER2:
  8283. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8284. TCCR2 |= val;
  8285. break;
  8286. #endif
  8287. #if defined(TCCR2A)
  8288. case TIMER2A:
  8289. case TIMER2B:
  8290. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8291. TCCR2B |= val;
  8292. break;
  8293. #endif
  8294. #if defined(TCCR3A)
  8295. case TIMER3A:
  8296. case TIMER3B:
  8297. case TIMER3C:
  8298. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8299. TCCR3B |= val;
  8300. break;
  8301. #endif
  8302. #if defined(TCCR4A)
  8303. case TIMER4A:
  8304. case TIMER4B:
  8305. case TIMER4C:
  8306. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8307. TCCR4B |= val;
  8308. break;
  8309. #endif
  8310. #if defined(TCCR5A)
  8311. case TIMER5A:
  8312. case TIMER5B:
  8313. case TIMER5C:
  8314. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8315. TCCR5B |= val;
  8316. break;
  8317. #endif
  8318. }
  8319. }
  8320. #endif // FAST_PWM_FAN
  8321. float calculate_volumetric_multiplier(float diameter) {
  8322. if (!volumetric_enabled || diameter == 0) return 1.0;
  8323. return 1.0 / (M_PI * diameter * 0.5 * diameter * 0.5);
  8324. }
  8325. void calculate_volumetric_multipliers() {
  8326. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  8327. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  8328. }
  8329. void enable_all_steppers() {
  8330. enable_x();
  8331. enable_y();
  8332. enable_z();
  8333. enable_e0();
  8334. enable_e1();
  8335. enable_e2();
  8336. enable_e3();
  8337. }
  8338. void disable_all_steppers() {
  8339. disable_x();
  8340. disable_y();
  8341. disable_z();
  8342. disable_e0();
  8343. disable_e1();
  8344. disable_e2();
  8345. disable_e3();
  8346. }
  8347. /**
  8348. * Manage several activities:
  8349. * - Check for Filament Runout
  8350. * - Keep the command buffer full
  8351. * - Check for maximum inactive time between commands
  8352. * - Check for maximum inactive time between stepper commands
  8353. * - Check if pin CHDK needs to go LOW
  8354. * - Check for KILL button held down
  8355. * - Check for HOME button held down
  8356. * - Check if cooling fan needs to be switched on
  8357. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  8358. */
  8359. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  8360. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8361. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  8362. handle_filament_runout();
  8363. #endif
  8364. if (commands_in_queue < BUFSIZE) get_available_commands();
  8365. millis_t ms = millis();
  8366. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) kill(PSTR(MSG_KILLED));
  8367. if (stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  8368. && !ignore_stepper_queue && !planner.blocks_queued()) {
  8369. #if ENABLED(DISABLE_INACTIVE_X)
  8370. disable_x();
  8371. #endif
  8372. #if ENABLED(DISABLE_INACTIVE_Y)
  8373. disable_y();
  8374. #endif
  8375. #if ENABLED(DISABLE_INACTIVE_Z)
  8376. disable_z();
  8377. #endif
  8378. #if ENABLED(DISABLE_INACTIVE_E)
  8379. disable_e0();
  8380. disable_e1();
  8381. disable_e2();
  8382. disable_e3();
  8383. #endif
  8384. }
  8385. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  8386. if (chdkActive && PENDING(ms, chdkHigh + CHDK_DELAY)) {
  8387. chdkActive = false;
  8388. WRITE(CHDK, LOW);
  8389. }
  8390. #endif
  8391. #if HAS_KILL
  8392. // Check if the kill button was pressed and wait just in case it was an accidental
  8393. // key kill key press
  8394. // -------------------------------------------------------------------------------
  8395. static int killCount = 0; // make the inactivity button a bit less responsive
  8396. const int KILL_DELAY = 750;
  8397. if (!READ(KILL_PIN))
  8398. killCount++;
  8399. else if (killCount > 0)
  8400. killCount--;
  8401. // Exceeded threshold and we can confirm that it was not accidental
  8402. // KILL the machine
  8403. // ----------------------------------------------------------------
  8404. if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED));
  8405. #endif
  8406. #if HAS_HOME
  8407. // Check to see if we have to home, use poor man's debouncer
  8408. // ---------------------------------------------------------
  8409. static int homeDebounceCount = 0; // poor man's debouncing count
  8410. const int HOME_DEBOUNCE_DELAY = 2500;
  8411. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  8412. if (!homeDebounceCount) {
  8413. enqueue_and_echo_commands_P(PSTR("G28"));
  8414. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  8415. }
  8416. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  8417. homeDebounceCount++;
  8418. else
  8419. homeDebounceCount = 0;
  8420. }
  8421. #endif
  8422. #if HAS_CONTROLLERFAN
  8423. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  8424. #endif
  8425. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  8426. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  8427. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  8428. bool oldstatus;
  8429. #if ENABLED(SWITCHING_EXTRUDER)
  8430. oldstatus = E0_ENABLE_READ;
  8431. enable_e0();
  8432. #else // !SWITCHING_EXTRUDER
  8433. switch (active_extruder) {
  8434. case 0:
  8435. oldstatus = E0_ENABLE_READ;
  8436. enable_e0();
  8437. break;
  8438. #if E_STEPPERS > 1
  8439. case 1:
  8440. oldstatus = E1_ENABLE_READ;
  8441. enable_e1();
  8442. break;
  8443. #if E_STEPPERS > 2
  8444. case 2:
  8445. oldstatus = E2_ENABLE_READ;
  8446. enable_e2();
  8447. break;
  8448. #if E_STEPPERS > 3
  8449. case 3:
  8450. oldstatus = E3_ENABLE_READ;
  8451. enable_e3();
  8452. break;
  8453. #endif
  8454. #endif
  8455. #endif
  8456. }
  8457. #endif // !SWITCHING_EXTRUDER
  8458. previous_cmd_ms = ms; // refresh_cmd_timeout()
  8459. #if IS_KINEMATIC
  8460. inverse_kinematics(current_position);
  8461. ADJUST_DELTA(current_position);
  8462. planner.buffer_line(
  8463. delta[A_AXIS], delta[B_AXIS], delta[C_AXIS],
  8464. current_position[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE,
  8465. MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder
  8466. );
  8467. #else
  8468. planner.buffer_line(
  8469. current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  8470. current_position[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE,
  8471. MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder
  8472. );
  8473. #endif
  8474. stepper.synchronize();
  8475. planner.set_e_position_mm(current_position[E_AXIS]);
  8476. #if ENABLED(SWITCHING_EXTRUDER)
  8477. E0_ENABLE_WRITE(oldstatus);
  8478. #else
  8479. switch (active_extruder) {
  8480. case 0:
  8481. E0_ENABLE_WRITE(oldstatus);
  8482. break;
  8483. #if E_STEPPERS > 1
  8484. case 1:
  8485. E1_ENABLE_WRITE(oldstatus);
  8486. break;
  8487. #if E_STEPPERS > 2
  8488. case 2:
  8489. E2_ENABLE_WRITE(oldstatus);
  8490. break;
  8491. #if E_STEPPERS > 3
  8492. case 3:
  8493. E3_ENABLE_WRITE(oldstatus);
  8494. break;
  8495. #endif
  8496. #endif
  8497. #endif
  8498. }
  8499. #endif // !SWITCHING_EXTRUDER
  8500. }
  8501. #endif // EXTRUDER_RUNOUT_PREVENT
  8502. #if ENABLED(DUAL_X_CARRIAGE)
  8503. // handle delayed move timeout
  8504. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  8505. // travel moves have been received so enact them
  8506. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  8507. set_destination_to_current();
  8508. prepare_move_to_destination();
  8509. }
  8510. #endif
  8511. #if ENABLED(TEMP_STAT_LEDS)
  8512. handle_status_leds();
  8513. #endif
  8514. planner.check_axes_activity();
  8515. }
  8516. /**
  8517. * Standard idle routine keeps the machine alive
  8518. */
  8519. void idle(
  8520. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  8521. bool no_stepper_sleep/*=false*/
  8522. #endif
  8523. ) {
  8524. lcd_update();
  8525. host_keepalive();
  8526. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8527. auto_report_temperatures();
  8528. #endif
  8529. manage_inactivity(
  8530. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  8531. no_stepper_sleep
  8532. #endif
  8533. );
  8534. thermalManager.manage_heater();
  8535. #if ENABLED(PRINTCOUNTER)
  8536. print_job_timer.tick();
  8537. #endif
  8538. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  8539. buzzer.tick();
  8540. #endif
  8541. }
  8542. /**
  8543. * Kill all activity and lock the machine.
  8544. * After this the machine will need to be reset.
  8545. */
  8546. void kill(const char* lcd_msg) {
  8547. SERIAL_ERROR_START;
  8548. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  8549. #if ENABLED(ULTRA_LCD)
  8550. kill_screen(lcd_msg);
  8551. #else
  8552. UNUSED(lcd_msg);
  8553. #endif
  8554. delay(500); // Wait a short time
  8555. cli(); // Stop interrupts
  8556. thermalManager.disable_all_heaters();
  8557. disable_all_steppers();
  8558. #if HAS_POWER_SWITCH
  8559. SET_INPUT(PS_ON_PIN);
  8560. #endif
  8561. suicide();
  8562. while (1) {
  8563. #if ENABLED(USE_WATCHDOG)
  8564. watchdog_reset();
  8565. #endif
  8566. } // Wait for reset
  8567. }
  8568. /**
  8569. * Turn off heaters and stop the print in progress
  8570. * After a stop the machine may be resumed with M999
  8571. */
  8572. void stop() {
  8573. thermalManager.disable_all_heaters();
  8574. if (IsRunning()) {
  8575. Running = false;
  8576. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  8577. SERIAL_ERROR_START;
  8578. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  8579. LCD_MESSAGEPGM(MSG_STOPPED);
  8580. }
  8581. }
  8582. /**
  8583. * Marlin entry-point: Set up before the program loop
  8584. * - Set up the kill pin, filament runout, power hold
  8585. * - Start the serial port
  8586. * - Print startup messages and diagnostics
  8587. * - Get EEPROM or default settings
  8588. * - Initialize managers for:
  8589. * • temperature
  8590. * • planner
  8591. * • watchdog
  8592. * • stepper
  8593. * • photo pin
  8594. * • servos
  8595. * • LCD controller
  8596. * • Digipot I2C
  8597. * • Z probe sled
  8598. * • status LEDs
  8599. */
  8600. void setup() {
  8601. #ifdef DISABLE_JTAG
  8602. // Disable JTAG on AT90USB chips to free up pins for IO
  8603. MCUCR = 0x80;
  8604. MCUCR = 0x80;
  8605. #endif
  8606. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8607. setup_filrunoutpin();
  8608. #endif
  8609. setup_killpin();
  8610. setup_powerhold();
  8611. #if HAS_STEPPER_RESET
  8612. disableStepperDrivers();
  8613. #endif
  8614. MYSERIAL.begin(BAUDRATE);
  8615. SERIAL_PROTOCOLLNPGM("start");
  8616. SERIAL_ECHO_START;
  8617. // Check startup - does nothing if bootloader sets MCUSR to 0
  8618. byte mcu = MCUSR;
  8619. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  8620. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  8621. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  8622. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  8623. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  8624. MCUSR = 0;
  8625. SERIAL_ECHOPGM(MSG_MARLIN);
  8626. SERIAL_CHAR(' ');
  8627. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  8628. SERIAL_EOL;
  8629. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  8630. SERIAL_ECHO_START;
  8631. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  8632. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  8633. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  8634. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  8635. #endif
  8636. SERIAL_ECHO_START;
  8637. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  8638. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  8639. // Send "ok" after commands by default
  8640. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  8641. // Load data from EEPROM if available (or use defaults)
  8642. // This also updates variables in the planner, elsewhere
  8643. Config_RetrieveSettings();
  8644. // Initialize current position based on home_offset
  8645. memcpy(current_position, home_offset, sizeof(home_offset));
  8646. // Vital to init stepper/planner equivalent for current_position
  8647. SYNC_PLAN_POSITION_KINEMATIC();
  8648. thermalManager.init(); // Initialize temperature loop
  8649. #if ENABLED(USE_WATCHDOG)
  8650. watchdog_init();
  8651. #endif
  8652. stepper.init(); // Initialize stepper, this enables interrupts!
  8653. servo_init();
  8654. #if HAS_PHOTOGRAPH
  8655. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  8656. #endif
  8657. #if HAS_CASE_LIGHT
  8658. update_case_light();
  8659. #endif
  8660. #if HAS_BED_PROBE
  8661. endstops.enable_z_probe(false);
  8662. #endif
  8663. #if HAS_CONTROLLERFAN
  8664. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  8665. #endif
  8666. #if HAS_STEPPER_RESET
  8667. enableStepperDrivers();
  8668. #endif
  8669. #if ENABLED(DIGIPOT_I2C)
  8670. digipot_i2c_init();
  8671. #endif
  8672. #if ENABLED(DAC_STEPPER_CURRENT)
  8673. dac_init();
  8674. #endif
  8675. #if ENABLED(Z_PROBE_SLED) && PIN_EXISTS(SLED)
  8676. OUT_WRITE(SLED_PIN, LOW); // turn it off
  8677. #endif // Z_PROBE_SLED
  8678. setup_homepin();
  8679. #if PIN_EXISTS(STAT_LED_RED)
  8680. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  8681. #endif
  8682. #if PIN_EXISTS(STAT_LED_BLUE)
  8683. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  8684. #endif
  8685. #if ENABLED(RGB_LED)
  8686. pinMode(RGB_LED_R_PIN, OUTPUT);
  8687. pinMode(RGB_LED_G_PIN, OUTPUT);
  8688. pinMode(RGB_LED_B_PIN, OUTPUT);
  8689. #endif
  8690. lcd_init();
  8691. #if ENABLED(SHOW_BOOTSCREEN)
  8692. #if ENABLED(DOGLCD)
  8693. safe_delay(BOOTSCREEN_TIMEOUT);
  8694. #elif ENABLED(ULTRA_LCD)
  8695. bootscreen();
  8696. #if DISABLED(SDSUPPORT)
  8697. lcd_init();
  8698. #endif
  8699. #endif
  8700. #endif
  8701. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8702. // Initialize mixing to 100% color 1
  8703. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8704. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  8705. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  8706. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8707. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  8708. #endif
  8709. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  8710. i2c.onReceive(i2c_on_receive);
  8711. i2c.onRequest(i2c_on_request);
  8712. #endif
  8713. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  8714. setup_endstop_interrupts();
  8715. #endif
  8716. }
  8717. /**
  8718. * The main Marlin program loop
  8719. *
  8720. * - Save or log commands to SD
  8721. * - Process available commands (if not saving)
  8722. * - Call heater manager
  8723. * - Call inactivity manager
  8724. * - Call endstop manager
  8725. * - Call LCD update
  8726. */
  8727. void loop() {
  8728. if (commands_in_queue < BUFSIZE) get_available_commands();
  8729. #if ENABLED(SDSUPPORT)
  8730. card.checkautostart(false);
  8731. #endif
  8732. if (commands_in_queue) {
  8733. #if ENABLED(SDSUPPORT)
  8734. if (card.saving) {
  8735. char* command = command_queue[cmd_queue_index_r];
  8736. if (strstr_P(command, PSTR("M29"))) {
  8737. // M29 closes the file
  8738. card.closefile();
  8739. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  8740. ok_to_send();
  8741. }
  8742. else {
  8743. // Write the string from the read buffer to SD
  8744. card.write_command(command);
  8745. if (card.logging)
  8746. process_next_command(); // The card is saving because it's logging
  8747. else
  8748. ok_to_send();
  8749. }
  8750. }
  8751. else
  8752. process_next_command();
  8753. #else
  8754. process_next_command();
  8755. #endif // SDSUPPORT
  8756. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  8757. if (commands_in_queue) {
  8758. --commands_in_queue;
  8759. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  8760. }
  8761. }
  8762. endstops.report_state();
  8763. idle();
  8764. }