My Marlin configs for Fabrikator Mini and CTC i3 Pro B
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Marlin_main.cpp 266KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474
  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. *
  24. * About Marlin
  25. *
  26. * This firmware is a mashup between Sprinter and grbl.
  27. * - https://github.com/kliment/Sprinter
  28. * - https://github.com/simen/grbl/tree
  29. *
  30. * It has preliminary support for Matthew Roberts advance algorithm
  31. * - http://reprap.org/pipermail/reprap-dev/2011-May/003323.html
  32. */
  33. #include "Marlin.h"
  34. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  35. #include "vector_3.h"
  36. #if ENABLED(AUTO_BED_LEVELING_GRID)
  37. #include "qr_solve.h"
  38. #endif
  39. #endif // AUTO_BED_LEVELING_FEATURE
  40. #if ENABLED(MESH_BED_LEVELING)
  41. #include "mesh_bed_leveling.h"
  42. #endif
  43. #if ENABLED(BEZIER_CURVE_SUPPORT)
  44. #include "planner_bezier.h"
  45. #endif
  46. #include "ultralcd.h"
  47. #include "planner.h"
  48. #include "stepper.h"
  49. #include "endstops.h"
  50. #include "temperature.h"
  51. #include "cardreader.h"
  52. #include "configuration_store.h"
  53. #include "language.h"
  54. #include "pins_arduino.h"
  55. #include "math.h"
  56. #if ENABLED(USE_WATCHDOG)
  57. #include "watchdog.h"
  58. #endif
  59. #if ENABLED(BLINKM)
  60. #include "blinkm.h"
  61. #include "Wire.h"
  62. #endif
  63. #if HAS_SERVOS
  64. #include "servo.h"
  65. #endif
  66. #if HAS_DIGIPOTSS
  67. #include <SPI.h>
  68. #endif
  69. #if ENABLED(DAC_STEPPER_CURRENT)
  70. #include "stepper_dac.h"
  71. #endif
  72. #if ENABLED(EXPERIMENTAL_I2CBUS)
  73. #include "twibus.h"
  74. #endif
  75. /**
  76. * Look here for descriptions of G-codes:
  77. * - http://linuxcnc.org/handbook/gcode/g-code.html
  78. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  79. *
  80. * Help us document these G-codes online:
  81. * - https://github.com/MarlinFirmware/Marlin/wiki/G-Code-in-Marlin
  82. * - http://reprap.org/wiki/G-code
  83. *
  84. * -----------------
  85. * Implemented Codes
  86. * -----------------
  87. *
  88. * "G" Codes
  89. *
  90. * G0 -> G1
  91. * G1 - Coordinated Movement X Y Z E
  92. * G2 - CW ARC
  93. * G3 - CCW ARC
  94. * G4 - Dwell S<seconds> or P<milliseconds>
  95. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  96. * G10 - Retract filament according to settings of M207
  97. * G11 - Retract recover filament according to settings of M208
  98. * G12 - Clean tool
  99. * G20 - Set input units to inches
  100. * G21 - Set input units to millimeters
  101. * G28 - Home one or more axes
  102. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  103. * G30 - Single Z probe, probes bed at current XY location.
  104. * G31 - Dock sled (Z_PROBE_SLED only)
  105. * G32 - Undock sled (Z_PROBE_SLED only)
  106. * G90 - Use Absolute Coordinates
  107. * G91 - Use Relative Coordinates
  108. * G92 - Set current position to coordinates given
  109. *
  110. * "M" Codes
  111. *
  112. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  113. * M1 - Same as M0
  114. * M17 - Enable/Power all stepper motors
  115. * M18 - Disable all stepper motors; same as M84
  116. * M20 - List SD card
  117. * M21 - Init SD card
  118. * M22 - Release SD card
  119. * M23 - Select SD file (M23 filename.g)
  120. * M24 - Start/resume SD print
  121. * M25 - Pause SD print
  122. * M26 - Set SD position in bytes (M26 S12345)
  123. * M27 - Report SD print status
  124. * M28 - Start SD write (M28 filename.g)
  125. * M29 - Stop SD write
  126. * M30 - Delete file from SD (M30 filename.g)
  127. * M31 - Output time since last M109 or SD card start to serial
  128. * M32 - Select file and start SD print (Can be used _while_ printing from SD card files):
  129. * syntax "M32 /path/filename#", or "M32 S<startpos bytes> !filename#"
  130. * Call gcode file : "M32 P !filename#" and return to caller file after finishing (similar to #include).
  131. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  132. * M33 - Get the longname version of a path
  133. * M42 - Change pin status via gcode Use M42 Px Sy to set pin x to value y, when omitting Px the onboard led will be used.
  134. * M48 - Measure Z_Probe repeatability. M48 [P # of points] [X position] [Y position] [V_erboseness #] [E_ngage Probe] [L # of legs of travel]
  135. * M75 - Start the print job timer
  136. * M76 - Pause the print job timer
  137. * M77 - Stop the print job timer
  138. * M78 - Show statistical information about the print jobs
  139. * M80 - Turn on Power Supply
  140. * M81 - Turn off Power Supply
  141. * M82 - Set E codes absolute (default)
  142. * M83 - Set E codes relative while in Absolute Coordinates (G90) mode
  143. * M84 - Disable steppers until next move,
  144. * or use S<seconds> to specify an inactivity timeout, after which the steppers will be disabled. S0 to disable the timeout.
  145. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  146. * M92 - Set planner.axis_steps_per_mm - same syntax as G92
  147. * M104 - Set extruder target temp
  148. * M105 - Read current temp
  149. * M106 - Fan on
  150. * M107 - Fan off
  151. * M108 - Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  152. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  153. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  154. * IF AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  155. * M110 - Set the current line number
  156. * M111 - Set debug flags with S<mask>. See flag bits defined in Marlin.h.
  157. * M112 - Emergency stop
  158. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages
  159. * M114 - Output current position to serial port
  160. * M115 - Capabilities string
  161. * M117 - Display a message on the controller screen
  162. * M119 - Output Endstop status to serial port
  163. * M120 - Enable endstop detection
  164. * M121 - Disable endstop detection
  165. * M126 - Solenoid Air Valve Open (BariCUDA support by jmil)
  166. * M127 - Solenoid Air Valve Closed (BariCUDA vent to atmospheric pressure by jmil)
  167. * M128 - EtoP Open (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  168. * M129 - EtoP Closed (BariCUDA EtoP = electricity to air pressure transducer by jmil)
  169. * M140 - Set bed target temp
  170. * M145 - Set the heatup state H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  171. * M149 - Set temperature units
  172. * M150 - Set BlinkM Color Output R: Red<0-255> U(!): Green<0-255> B: Blue<0-255> over i2c, G for green does not work.
  173. * M190 - Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  174. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  175. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  176. * M201 - Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  177. * M202 - Set max acceleration in units/s^2 for travel moves (M202 X1000 Y1000) Unused in Marlin!!
  178. * M203 - Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  179. * M204 - Set default acceleration: P for Printing moves, R for Retract only (no X, Y, Z) moves and T for Travel (non printing) moves (ex. M204 P800 T3000 R9000) in units/sec^2
  180. * M205 - Set advanced settings. Current units apply:
  181. S<print> T<travel> minimum speeds
  182. B<minimum segment time>
  183. X<max xy jerk>, Z<max Z jerk>, E<max E jerk>
  184. * M206 - Set additional homing offset
  185. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>
  186. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>
  187. * M209 - Turn Automatic Retract Detection on/off: S<bool> (For slicers that don't support G10/11).
  188. Every normal extrude-only move will be classified as retract depending on the direction.
  189. * M218 - Set a tool offset: T<index> X<offset> Y<offset>
  190. * M220 - Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  191. * M221 - Set Flow Percentage: S<percent>
  192. * M226 - Wait until the specified pin reaches the state required: P<pin number> S<pin state>
  193. * M240 - Trigger a camera to take a photograph
  194. * M250 - Set LCD contrast C<contrast value> (value 0..63)
  195. * M280 - Set servo position absolute. P: servo index, S: angle or microseconds
  196. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  197. * M301 - Set PID parameters P I and D
  198. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>.
  199. * M303 - PID relay autotune S<temperature> sets the target temperature. (default target temperature = 150C)
  200. * M304 - Set bed PID parameters P I and D
  201. * M380 - Activate solenoid on active extruder
  202. * M381 - Disable all solenoids
  203. * M400 - Finish all moves
  204. * M401 - Lower Z probe if present
  205. * M402 - Raise Z probe if present
  206. * M404 - Display or set the Nominal Filament Width: [ N<diameter> ]
  207. * M405 - Enable Filament Sensor extrusion control. Optional delay between sensor and extruder: D<cm>
  208. * M406 - Disable Filament Sensor extrusion control
  209. * M407 - Display measured filament diameter in millimeters
  210. * M410 - Quickstop. Abort all the planned moves
  211. * M420 - Enable/Disable Mesh Leveling (with current values) S1=enable S0=disable
  212. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units>
  213. * M428 - Set the home_offset logically based on the current_position
  214. * M500 - Store parameters in EEPROM
  215. * M501 - Read parameters from EEPROM (if you need reset them after you changed them temporarily).
  216. * M502 - Revert to the default "factory settings". You still need to store them in EEPROM afterwards if you want to.
  217. * M503 - Print the current settings (from memory not from EEPROM). Use S0 to leave off headings.
  218. * M540 - Use S[0|1] to enable or disable the stop SD card print on endstop hit (requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  219. * M600 - Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  220. * M665 - Set delta configurations: L<diagonal rod> R<delta radius> S<segments/s>
  221. * M666 - Set delta endstop adjustment
  222. * M605 - Set dual x-carriage movement mode: S<mode> [ X<duplication x-offset> R<duplication temp offset> ]
  223. * M851 - Set Z probe's Z offset in current units. (Negative values apply to probes that extend below the nozzle.)
  224. * M907 - Set digital trimpot motor current using axis codes.
  225. * M908 - Control digital trimpot directly.
  226. * M909 - DAC_STEPPER_CURRENT: Print digipot/DAC current value
  227. * M910 - DAC_STEPPER_CURRENT: Commit digipot/DAC value to external EEPROM via I2C
  228. * M350 - Set microstepping mode.
  229. * M351 - Toggle MS1 MS2 pins directly.
  230. *
  231. * ************ SCARA Specific - This can change to suit future G-code regulations
  232. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  233. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  234. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  235. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  236. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  237. * M365 - SCARA calibration: Scaling factor, X, Y, Z axis
  238. * ************* SCARA End ***************
  239. *
  240. * ************ Custom codes - This can change to suit future G-code regulations
  241. * M100 - Watch Free Memory (For Debugging Only)
  242. * M928 - Start SD logging (M928 filename.g) - ended by M29
  243. * M999 - Restart after being stopped by error
  244. *
  245. * "T" Codes
  246. *
  247. * T0-T3 - Select a tool by index (usually an extruder) [ F<units/min> ]
  248. *
  249. */
  250. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  251. void gcode_M100();
  252. #endif
  253. #if ENABLED(SDSUPPORT)
  254. CardReader card;
  255. #endif
  256. #if ENABLED(EXPERIMENTAL_I2CBUS)
  257. TWIBus i2c;
  258. #endif
  259. bool Running = true;
  260. uint8_t marlin_debug_flags = DEBUG_NONE;
  261. static float feedrate = 1500.0, saved_feedrate;
  262. float current_position[NUM_AXIS] = { 0.0 };
  263. static float destination[NUM_AXIS] = { 0.0 };
  264. bool axis_known_position[3] = { false };
  265. bool axis_homed[3] = { false };
  266. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  267. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  268. static char* current_command, *current_command_args;
  269. static uint8_t cmd_queue_index_r = 0,
  270. cmd_queue_index_w = 0,
  271. commands_in_queue = 0;
  272. #if ENABLED(INCH_MODE_SUPPORT)
  273. float linear_unit_factor = 1.0;
  274. float volumetric_unit_factor = 1.0;
  275. #endif
  276. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  277. TempUnit input_temp_units = TEMPUNIT_C;
  278. #endif
  279. const float homing_feedrate[] = HOMING_FEEDRATE;
  280. bool axis_relative_modes[] = AXIS_RELATIVE_MODES;
  281. int feedrate_multiplier = 100; //100->1 200->2
  282. int saved_feedrate_multiplier;
  283. int extruder_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  284. bool volumetric_enabled = false;
  285. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA);
  286. float volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  287. // The distance that XYZ has been offset by G92. Reset by G28.
  288. float position_shift[3] = { 0 };
  289. // This offset is added to the configured home position.
  290. // Set by M206, M428, or menu item. Saved to EEPROM.
  291. float home_offset[3] = { 0 };
  292. #define RAW_POSITION(POS, AXIS) (POS - home_offset[AXIS] - position_shift[AXIS])
  293. #define RAW_CURRENT_POSITION(AXIS) (RAW_POSITION(current_position[AXIS], AXIS))
  294. // Software Endstops. Default to configured limits.
  295. float sw_endstop_min[3] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS };
  296. float sw_endstop_max[3] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  297. #if ENABLED(DELTA)
  298. float delta_clip_start_height = Z_MAX_POS;
  299. #endif
  300. #if FAN_COUNT > 0
  301. int fanSpeeds[FAN_COUNT] = { 0 };
  302. #endif
  303. // The active extruder (tool). Set with T<extruder> command.
  304. uint8_t active_extruder = 0;
  305. // Relative Mode. Enable with G91, disable with G90.
  306. static bool relative_mode = false;
  307. volatile bool wait_for_heatup = true;
  308. const char errormagic[] PROGMEM = "Error:";
  309. const char echomagic[] PROGMEM = "echo:";
  310. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  311. static int serial_count = 0;
  312. // GCode parameter pointer used by code_seen(), code_value_float(), etc.
  313. static char* seen_pointer;
  314. // Next Immediate GCode Command pointer. NULL if none.
  315. const char* queued_commands_P = NULL;
  316. const int sensitive_pins[] = SENSITIVE_PINS; ///< Sensitive pin list for M42
  317. // Inactivity shutdown
  318. millis_t previous_cmd_ms = 0;
  319. static millis_t max_inactive_time = 0;
  320. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  321. // Print Job Timer
  322. #if ENABLED(PRINTCOUNTER)
  323. PrintCounter print_job_timer = PrintCounter();
  324. #else
  325. Stopwatch print_job_timer = Stopwatch();
  326. #endif
  327. // Buzzer
  328. #if HAS_BUZZER
  329. #if ENABLED(SPEAKER)
  330. Speaker buzzer;
  331. #else
  332. Buzzer buzzer;
  333. #endif
  334. #endif
  335. static uint8_t target_extruder;
  336. #if HAS_BED_PROBE
  337. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  338. #endif
  339. #define PLANNER_XY_FEEDRATE() (min(planner.max_feedrate[X_AXIS], planner.max_feedrate[Y_AXIS]))
  340. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  341. int xy_probe_speed = XY_PROBE_SPEED;
  342. bool bed_leveling_in_progress = false;
  343. #define XY_PROBE_FEEDRATE xy_probe_speed
  344. #elif defined(XY_PROBE_SPEED)
  345. #define XY_PROBE_FEEDRATE XY_PROBE_SPEED
  346. #else
  347. #define XY_PROBE_FEEDRATE (PLANNER_XY_FEEDRATE() * 60)
  348. #endif
  349. #if ENABLED(Z_DUAL_ENDSTOPS) && DISABLED(DELTA)
  350. float z_endstop_adj = 0;
  351. #endif
  352. // Extruder offsets
  353. #if HOTENDS > 1
  354. #ifndef HOTEND_OFFSET_X
  355. #define HOTEND_OFFSET_X { 0 } // X offsets for each extruder
  356. #endif
  357. #ifndef HOTEND_OFFSET_Y
  358. #define HOTEND_OFFSET_Y { 0 } // Y offsets for each extruder
  359. #endif
  360. float hotend_offset[][HOTENDS] = {
  361. HOTEND_OFFSET_X,
  362. HOTEND_OFFSET_Y
  363. #if ENABLED(DUAL_X_CARRIAGE)
  364. , { 0 } // Z offsets for each extruder
  365. #endif
  366. };
  367. #endif
  368. #if HAS_Z_SERVO_ENDSTOP
  369. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  370. #endif
  371. #if ENABLED(BARICUDA)
  372. int baricuda_valve_pressure = 0;
  373. int baricuda_e_to_p_pressure = 0;
  374. #endif
  375. #if ENABLED(FWRETRACT)
  376. bool autoretract_enabled = false;
  377. bool retracted[EXTRUDERS] = { false };
  378. bool retracted_swap[EXTRUDERS] = { false };
  379. float retract_length = RETRACT_LENGTH;
  380. float retract_length_swap = RETRACT_LENGTH_SWAP;
  381. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  382. float retract_zlift = RETRACT_ZLIFT;
  383. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  384. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  385. float retract_recover_feedrate = RETRACT_RECOVER_FEEDRATE;
  386. #endif // FWRETRACT
  387. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  388. bool powersupply =
  389. #if ENABLED(PS_DEFAULT_OFF)
  390. false
  391. #else
  392. true
  393. #endif
  394. ;
  395. #endif
  396. #if ENABLED(DELTA)
  397. #define TOWER_1 X_AXIS
  398. #define TOWER_2 Y_AXIS
  399. #define TOWER_3 Z_AXIS
  400. float delta[3] = { 0 };
  401. #define SIN_60 0.8660254037844386
  402. #define COS_60 0.5
  403. float endstop_adj[3] = { 0 };
  404. // these are the default values, can be overriden with M665
  405. float delta_radius = DELTA_RADIUS;
  406. float delta_tower1_x = -SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  407. float delta_tower1_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1);
  408. float delta_tower2_x = SIN_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  409. float delta_tower2_y = -COS_60 * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2);
  410. float delta_tower3_x = 0; // back middle tower
  411. float delta_tower3_y = (delta_radius + DELTA_RADIUS_TRIM_TOWER_3);
  412. float delta_diagonal_rod = DELTA_DIAGONAL_ROD;
  413. float delta_diagonal_rod_trim_tower_1 = DELTA_DIAGONAL_ROD_TRIM_TOWER_1;
  414. float delta_diagonal_rod_trim_tower_2 = DELTA_DIAGONAL_ROD_TRIM_TOWER_2;
  415. float delta_diagonal_rod_trim_tower_3 = DELTA_DIAGONAL_ROD_TRIM_TOWER_3;
  416. float delta_diagonal_rod_2_tower_1 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_1);
  417. float delta_diagonal_rod_2_tower_2 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_2);
  418. float delta_diagonal_rod_2_tower_3 = sq(delta_diagonal_rod + delta_diagonal_rod_trim_tower_3);
  419. //float delta_diagonal_rod_2 = sq(delta_diagonal_rod);
  420. float delta_segments_per_second = DELTA_SEGMENTS_PER_SECOND;
  421. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  422. int delta_grid_spacing[2] = { 0, 0 };
  423. float bed_level[AUTO_BED_LEVELING_GRID_POINTS][AUTO_BED_LEVELING_GRID_POINTS];
  424. #endif
  425. #else
  426. static bool home_all_axis = true;
  427. #endif
  428. #if ENABLED(SCARA)
  429. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND;
  430. static float delta[3] = { 0 };
  431. float axis_scaling[3] = { 1, 1, 1 }; // Build size scaling, default to 1
  432. #endif
  433. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  434. //Variables for Filament Sensor input
  435. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA; //Set nominal filament width, can be changed with M404
  436. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  437. float filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; //Stores the measured filament diameter
  438. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; //ring buffer to delay measurement store extruder factor after subtracting 100
  439. int filwidth_delay_index1 = 0; //index into ring buffer
  440. int filwidth_delay_index2 = -1; //index into ring buffer - set to -1 on startup to indicate ring buffer needs to be initialized
  441. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  442. #endif
  443. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  444. static bool filament_ran_out = false;
  445. #endif
  446. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  447. FilamentChangeMenuResponse filament_change_menu_response;
  448. #endif
  449. static bool send_ok[BUFSIZE];
  450. #if HAS_SERVOS
  451. Servo servo[NUM_SERVOS];
  452. #define MOVE_SERVO(I, P) servo[I].move(P)
  453. #if HAS_Z_SERVO_ENDSTOP
  454. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  455. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  456. #endif
  457. #endif
  458. #ifdef CHDK
  459. millis_t chdkHigh = 0;
  460. boolean chdkActive = false;
  461. #endif
  462. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  463. int lpq_len = 20;
  464. #endif
  465. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  466. // States for managing Marlin and host communication
  467. // Marlin sends messages if blocked or busy
  468. enum MarlinBusyState {
  469. NOT_BUSY, // Not in a handler
  470. IN_HANDLER, // Processing a GCode
  471. IN_PROCESS, // Known to be blocking command input (as in G29)
  472. PAUSED_FOR_USER, // Blocking pending any input
  473. PAUSED_FOR_INPUT // Blocking pending text input (concept)
  474. };
  475. static MarlinBusyState busy_state = NOT_BUSY;
  476. static millis_t next_busy_signal_ms = 0;
  477. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  478. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  479. #else
  480. #define host_keepalive() ;
  481. #define KEEPALIVE_STATE(n) ;
  482. #endif // HOST_KEEPALIVE_FEATURE
  483. /**
  484. * ***************************************************************************
  485. * ******************************** FUNCTIONS ********************************
  486. * ***************************************************************************
  487. */
  488. void stop();
  489. void get_available_commands();
  490. void process_next_command();
  491. void prepare_move_to_destination();
  492. #if ENABLED(ARC_SUPPORT)
  493. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  494. #endif
  495. #if ENABLED(BEZIER_CURVE_SUPPORT)
  496. void plan_cubic_move(const float offset[4]);
  497. #endif
  498. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  499. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  500. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  501. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  502. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  503. static void report_current_position();
  504. #if ENABLED(DEBUG_LEVELING_FEATURE)
  505. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  506. serialprintPGM(prefix);
  507. SERIAL_ECHOPAIR("(", x);
  508. SERIAL_ECHOPAIR(", ", y);
  509. SERIAL_ECHOPAIR(", ", z);
  510. SERIAL_ECHOPGM(")");
  511. if (suffix) serialprintPGM(suffix);
  512. else SERIAL_EOL;
  513. }
  514. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  515. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  516. }
  517. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  518. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  519. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  520. }
  521. #endif
  522. #define DEBUG_POS(SUFFIX,VAR) do { \
  523. print_xyz(PSTR(STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  524. #endif
  525. #if ENABLED(DELTA) || ENABLED(SCARA)
  526. inline void sync_plan_position_delta() {
  527. #if ENABLED(DEBUG_LEVELING_FEATURE)
  528. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_delta", current_position);
  529. #endif
  530. calculate_delta(current_position);
  531. planner.set_position_mm(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], current_position[E_AXIS]);
  532. }
  533. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_delta()
  534. #else
  535. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  536. #endif
  537. #if ENABLED(SDSUPPORT)
  538. #include "SdFatUtil.h"
  539. int freeMemory() { return SdFatUtil::FreeRam(); }
  540. #else
  541. extern "C" {
  542. extern unsigned int __bss_end;
  543. extern unsigned int __heap_start;
  544. extern void* __brkval;
  545. int freeMemory() {
  546. int free_memory;
  547. if ((int)__brkval == 0)
  548. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  549. else
  550. free_memory = ((int)&free_memory) - ((int)__brkval);
  551. return free_memory;
  552. }
  553. }
  554. #endif //!SDSUPPORT
  555. #if ENABLED(DIGIPOT_I2C)
  556. extern void digipot_i2c_set_current(int channel, float current);
  557. extern void digipot_i2c_init();
  558. #endif
  559. /**
  560. * Inject the next "immediate" command, when possible.
  561. * Return true if any immediate commands remain to inject.
  562. */
  563. static bool drain_queued_commands_P() {
  564. if (queued_commands_P != NULL) {
  565. size_t i = 0;
  566. char c, cmd[30];
  567. strncpy_P(cmd, queued_commands_P, sizeof(cmd) - 1);
  568. cmd[sizeof(cmd) - 1] = '\0';
  569. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  570. cmd[i] = '\0';
  571. if (enqueue_and_echo_command(cmd)) { // success?
  572. if (c) // newline char?
  573. queued_commands_P += i + 1; // advance to the next command
  574. else
  575. queued_commands_P = NULL; // nul char? no more commands
  576. }
  577. }
  578. return (queued_commands_P != NULL); // return whether any more remain
  579. }
  580. /**
  581. * Record one or many commands to run from program memory.
  582. * Aborts the current queue, if any.
  583. * Note: drain_queued_commands_P() must be called repeatedly to drain the commands afterwards
  584. */
  585. void enqueue_and_echo_commands_P(const char* pgcode) {
  586. queued_commands_P = pgcode;
  587. drain_queued_commands_P(); // first command executed asap (when possible)
  588. }
  589. void clear_command_queue() {
  590. cmd_queue_index_r = cmd_queue_index_w;
  591. commands_in_queue = 0;
  592. }
  593. /**
  594. * Once a new command is in the ring buffer, call this to commit it
  595. */
  596. inline void _commit_command(bool say_ok) {
  597. send_ok[cmd_queue_index_w] = say_ok;
  598. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  599. commands_in_queue++;
  600. }
  601. /**
  602. * Copy a command directly into the main command buffer, from RAM.
  603. * Returns true if successfully adds the command
  604. */
  605. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  606. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  607. strcpy(command_queue[cmd_queue_index_w], cmd);
  608. _commit_command(say_ok);
  609. return true;
  610. }
  611. void enqueue_and_echo_command_now(const char* cmd) {
  612. while (!enqueue_and_echo_command(cmd)) idle();
  613. }
  614. /**
  615. * Enqueue with Serial Echo
  616. */
  617. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  618. if (_enqueuecommand(cmd, say_ok)) {
  619. SERIAL_ECHO_START;
  620. SERIAL_ECHOPGM(MSG_Enqueueing);
  621. SERIAL_ECHO(cmd);
  622. SERIAL_ECHOLNPGM("\"");
  623. return true;
  624. }
  625. return false;
  626. }
  627. void setup_killpin() {
  628. #if HAS_KILL
  629. SET_INPUT(KILL_PIN);
  630. WRITE(KILL_PIN, HIGH);
  631. #endif
  632. }
  633. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  634. void setup_filrunoutpin() {
  635. pinMode(FIL_RUNOUT_PIN, INPUT);
  636. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  637. WRITE(FIL_RUNOUT_PIN, HIGH);
  638. #endif
  639. }
  640. #endif
  641. // Set home pin
  642. void setup_homepin(void) {
  643. #if HAS_HOME
  644. SET_INPUT(HOME_PIN);
  645. WRITE(HOME_PIN, HIGH);
  646. #endif
  647. }
  648. void setup_photpin() {
  649. #if HAS_PHOTOGRAPH
  650. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  651. #endif
  652. }
  653. void setup_powerhold() {
  654. #if HAS_SUICIDE
  655. OUT_WRITE(SUICIDE_PIN, HIGH);
  656. #endif
  657. #if HAS_POWER_SWITCH
  658. #if ENABLED(PS_DEFAULT_OFF)
  659. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  660. #else
  661. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  662. #endif
  663. #endif
  664. }
  665. void suicide() {
  666. #if HAS_SUICIDE
  667. OUT_WRITE(SUICIDE_PIN, LOW);
  668. #endif
  669. }
  670. void servo_init() {
  671. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  672. servo[0].attach(SERVO0_PIN);
  673. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  674. #endif
  675. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  676. servo[1].attach(SERVO1_PIN);
  677. servo[1].detach();
  678. #endif
  679. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  680. servo[2].attach(SERVO2_PIN);
  681. servo[2].detach();
  682. #endif
  683. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  684. servo[3].attach(SERVO3_PIN);
  685. servo[3].detach();
  686. #endif
  687. #if HAS_Z_SERVO_ENDSTOP
  688. /**
  689. * Set position of Z Servo Endstop
  690. *
  691. * The servo might be deployed and positioned too low to stow
  692. * when starting up the machine or rebooting the board.
  693. * There's no way to know where the nozzle is positioned until
  694. * homing has been done - no homing with z-probe without init!
  695. *
  696. */
  697. STOW_Z_SERVO();
  698. #endif
  699. #if HAS_BED_PROBE
  700. endstops.enable_z_probe(false);
  701. #endif
  702. }
  703. /**
  704. * Stepper Reset (RigidBoard, et.al.)
  705. */
  706. #if HAS_STEPPER_RESET
  707. void disableStepperDrivers() {
  708. pinMode(STEPPER_RESET_PIN, OUTPUT);
  709. digitalWrite(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  710. }
  711. void enableStepperDrivers() { pinMode(STEPPER_RESET_PIN, INPUT); } // set to input, which allows it to be pulled high by pullups
  712. #endif
  713. /**
  714. * Marlin entry-point: Set up before the program loop
  715. * - Set up the kill pin, filament runout, power hold
  716. * - Start the serial port
  717. * - Print startup messages and diagnostics
  718. * - Get EEPROM or default settings
  719. * - Initialize managers for:
  720. * • temperature
  721. * • planner
  722. * • watchdog
  723. * • stepper
  724. * • photo pin
  725. * • servos
  726. * • LCD controller
  727. * • Digipot I2C
  728. * • Z probe sled
  729. * • status LEDs
  730. */
  731. void setup() {
  732. #ifdef DISABLE_JTAG
  733. // Disable JTAG on AT90USB chips to free up pins for IO
  734. MCUCR = 0x80;
  735. MCUCR = 0x80;
  736. #endif
  737. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  738. setup_filrunoutpin();
  739. #endif
  740. setup_killpin();
  741. setup_powerhold();
  742. #if HAS_STEPPER_RESET
  743. disableStepperDrivers();
  744. #endif
  745. MYSERIAL.begin(BAUDRATE);
  746. SERIAL_PROTOCOLLNPGM("start");
  747. SERIAL_ECHO_START;
  748. // Check startup - does nothing if bootloader sets MCUSR to 0
  749. byte mcu = MCUSR;
  750. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  751. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  752. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  753. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  754. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  755. MCUSR = 0;
  756. SERIAL_ECHOPGM(MSG_MARLIN);
  757. SERIAL_ECHOLNPGM(" " SHORT_BUILD_VERSION);
  758. #ifdef STRING_DISTRIBUTION_DATE
  759. #ifdef STRING_CONFIG_H_AUTHOR
  760. SERIAL_ECHO_START;
  761. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  762. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  763. SERIAL_ECHOPGM(MSG_AUTHOR);
  764. SERIAL_ECHOLNPGM(STRING_CONFIG_H_AUTHOR);
  765. SERIAL_ECHOPGM("Compiled: ");
  766. SERIAL_ECHOLNPGM(__DATE__);
  767. #endif // STRING_CONFIG_H_AUTHOR
  768. #endif // STRING_DISTRIBUTION_DATE
  769. SERIAL_ECHO_START;
  770. SERIAL_ECHOPGM(MSG_FREE_MEMORY);
  771. SERIAL_ECHO(freeMemory());
  772. SERIAL_ECHOPGM(MSG_PLANNER_BUFFER_BYTES);
  773. SERIAL_ECHOLN((int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  774. // Send "ok" after commands by default
  775. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  776. // loads data from EEPROM if available else uses defaults (and resets step acceleration rate)
  777. Config_RetrieveSettings();
  778. // Initialize current position based on home_offset
  779. memcpy(current_position, home_offset, sizeof(home_offset));
  780. #if ENABLED(DELTA) || ENABLED(SCARA)
  781. // Vital to init kinematic equivalent for X0 Y0 Z0
  782. SYNC_PLAN_POSITION_KINEMATIC();
  783. #endif
  784. thermalManager.init(); // Initialize temperature loop
  785. #if ENABLED(USE_WATCHDOG)
  786. watchdog_init();
  787. #endif
  788. stepper.init(); // Initialize stepper, this enables interrupts!
  789. setup_photpin();
  790. servo_init();
  791. #if HAS_CONTROLLERFAN
  792. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  793. #endif
  794. #if HAS_STEPPER_RESET
  795. enableStepperDrivers();
  796. #endif
  797. #if ENABLED(DIGIPOT_I2C)
  798. digipot_i2c_init();
  799. #endif
  800. #if ENABLED(DAC_STEPPER_CURRENT)
  801. dac_init();
  802. #endif
  803. #if ENABLED(Z_PROBE_SLED)
  804. pinMode(SLED_PIN, OUTPUT);
  805. digitalWrite(SLED_PIN, LOW); // turn it off
  806. #endif // Z_PROBE_SLED
  807. setup_homepin();
  808. #ifdef STAT_LED_RED
  809. pinMode(STAT_LED_RED, OUTPUT);
  810. digitalWrite(STAT_LED_RED, LOW); // turn it off
  811. #endif
  812. #ifdef STAT_LED_BLUE
  813. pinMode(STAT_LED_BLUE, OUTPUT);
  814. digitalWrite(STAT_LED_BLUE, LOW); // turn it off
  815. #endif
  816. lcd_init();
  817. #if ENABLED(SHOW_BOOTSCREEN)
  818. #if ENABLED(DOGLCD)
  819. delay(1000);
  820. #elif ENABLED(ULTRA_LCD)
  821. bootscreen();
  822. lcd_init();
  823. #endif
  824. #endif
  825. }
  826. /**
  827. * The main Marlin program loop
  828. *
  829. * - Save or log commands to SD
  830. * - Process available commands (if not saving)
  831. * - Call heater manager
  832. * - Call inactivity manager
  833. * - Call endstop manager
  834. * - Call LCD update
  835. */
  836. void loop() {
  837. if (commands_in_queue < BUFSIZE) get_available_commands();
  838. #if ENABLED(SDSUPPORT)
  839. card.checkautostart(false);
  840. #endif
  841. if (commands_in_queue) {
  842. #if ENABLED(SDSUPPORT)
  843. if (card.saving) {
  844. char* command = command_queue[cmd_queue_index_r];
  845. if (strstr_P(command, PSTR("M29"))) {
  846. // M29 closes the file
  847. card.closefile();
  848. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  849. ok_to_send();
  850. }
  851. else {
  852. // Write the string from the read buffer to SD
  853. card.write_command(command);
  854. if (card.logging)
  855. process_next_command(); // The card is saving because it's logging
  856. else
  857. ok_to_send();
  858. }
  859. }
  860. else
  861. process_next_command();
  862. #else
  863. process_next_command();
  864. #endif // SDSUPPORT
  865. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  866. if (commands_in_queue) {
  867. --commands_in_queue;
  868. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  869. }
  870. }
  871. endstops.report_state();
  872. idle();
  873. }
  874. void gcode_line_error(const char* err, bool doFlush = true) {
  875. SERIAL_ERROR_START;
  876. serialprintPGM(err);
  877. SERIAL_ERRORLN(gcode_LastN);
  878. //Serial.println(gcode_N);
  879. if (doFlush) FlushSerialRequestResend();
  880. serial_count = 0;
  881. }
  882. inline void get_serial_commands() {
  883. static char serial_line_buffer[MAX_CMD_SIZE];
  884. static boolean serial_comment_mode = false;
  885. // If the command buffer is empty for too long,
  886. // send "wait" to indicate Marlin is still waiting.
  887. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  888. static millis_t last_command_time = 0;
  889. millis_t ms = millis();
  890. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  891. SERIAL_ECHOLNPGM(MSG_WAIT);
  892. last_command_time = ms;
  893. }
  894. #endif
  895. /**
  896. * Loop while serial characters are incoming and the queue is not full
  897. */
  898. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  899. char serial_char = MYSERIAL.read();
  900. /**
  901. * If the character ends the line
  902. */
  903. if (serial_char == '\n' || serial_char == '\r') {
  904. serial_comment_mode = false; // end of line == end of comment
  905. if (!serial_count) continue; // skip empty lines
  906. serial_line_buffer[serial_count] = 0; // terminate string
  907. serial_count = 0; //reset buffer
  908. char* command = serial_line_buffer;
  909. while (*command == ' ') command++; // skip any leading spaces
  910. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  911. char* apos = strchr(command, '*');
  912. if (npos) {
  913. boolean M110 = strstr_P(command, PSTR("M110")) != NULL;
  914. if (M110) {
  915. char* n2pos = strchr(command + 4, 'N');
  916. if (n2pos) npos = n2pos;
  917. }
  918. gcode_N = strtol(npos + 1, NULL, 10);
  919. if (gcode_N != gcode_LastN + 1 && !M110) {
  920. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  921. return;
  922. }
  923. if (apos) {
  924. byte checksum = 0, count = 0;
  925. while (command[count] != '*') checksum ^= command[count++];
  926. if (strtol(apos + 1, NULL, 10) != checksum) {
  927. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  928. return;
  929. }
  930. // if no errors, continue parsing
  931. }
  932. else {
  933. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  934. return;
  935. }
  936. gcode_LastN = gcode_N;
  937. // if no errors, continue parsing
  938. }
  939. else if (apos) { // No '*' without 'N'
  940. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  941. return;
  942. }
  943. // Movement commands alert when stopped
  944. if (IsStopped()) {
  945. char* gpos = strchr(command, 'G');
  946. if (gpos) {
  947. int codenum = strtol(gpos + 1, NULL, 10);
  948. switch (codenum) {
  949. case 0:
  950. case 1:
  951. case 2:
  952. case 3:
  953. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  954. LCD_MESSAGEPGM(MSG_STOPPED);
  955. break;
  956. }
  957. }
  958. }
  959. #if DISABLED(EMERGENCY_PARSER)
  960. // If command was e-stop process now
  961. if (strcmp(command, "M108") == 0) wait_for_heatup = false;
  962. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  963. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  964. #endif
  965. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  966. last_command_time = ms;
  967. #endif
  968. // Add the command to the queue
  969. _enqueuecommand(serial_line_buffer, true);
  970. }
  971. else if (serial_count >= MAX_CMD_SIZE - 1) {
  972. // Keep fetching, but ignore normal characters beyond the max length
  973. // The command will be injected when EOL is reached
  974. }
  975. else if (serial_char == '\\') { // Handle escapes
  976. if (MYSERIAL.available() > 0) {
  977. // if we have one more character, copy it over
  978. serial_char = MYSERIAL.read();
  979. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  980. }
  981. // otherwise do nothing
  982. }
  983. else { // it's not a newline, carriage return or escape char
  984. if (serial_char == ';') serial_comment_mode = true;
  985. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  986. }
  987. } // queue has space, serial has data
  988. }
  989. #if ENABLED(SDSUPPORT)
  990. inline void get_sdcard_commands() {
  991. static bool stop_buffering = false,
  992. sd_comment_mode = false;
  993. if (!card.sdprinting) return;
  994. /**
  995. * '#' stops reading from SD to the buffer prematurely, so procedural
  996. * macro calls are possible. If it occurs, stop_buffering is triggered
  997. * and the buffer is run dry; this character _can_ occur in serial com
  998. * due to checksums, however, no checksums are used in SD printing.
  999. */
  1000. if (commands_in_queue == 0) stop_buffering = false;
  1001. uint16_t sd_count = 0;
  1002. bool card_eof = card.eof();
  1003. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1004. int16_t n = card.get();
  1005. char sd_char = (char)n;
  1006. card_eof = card.eof();
  1007. if (card_eof || n == -1
  1008. || sd_char == '\n' || sd_char == '\r'
  1009. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1010. ) {
  1011. if (card_eof) {
  1012. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1013. card.printingHasFinished();
  1014. card.checkautostart(true);
  1015. }
  1016. else if (n == -1) {
  1017. SERIAL_ERROR_START;
  1018. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1019. }
  1020. if (sd_char == '#') stop_buffering = true;
  1021. sd_comment_mode = false; //for new command
  1022. if (!sd_count) continue; //skip empty lines
  1023. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  1024. sd_count = 0; //clear buffer
  1025. _commit_command(false);
  1026. }
  1027. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1028. /**
  1029. * Keep fetching, but ignore normal characters beyond the max length
  1030. * The command will be injected when EOL is reached
  1031. */
  1032. }
  1033. else {
  1034. if (sd_char == ';') sd_comment_mode = true;
  1035. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1036. }
  1037. }
  1038. }
  1039. #endif // SDSUPPORT
  1040. /**
  1041. * Add to the circular command queue the next command from:
  1042. * - The command-injection queue (queued_commands_P)
  1043. * - The active serial input (usually USB)
  1044. * - The SD card file being actively printed
  1045. */
  1046. void get_available_commands() {
  1047. // if any immediate commands remain, don't get other commands yet
  1048. if (drain_queued_commands_P()) return;
  1049. get_serial_commands();
  1050. #if ENABLED(SDSUPPORT)
  1051. get_sdcard_commands();
  1052. #endif
  1053. }
  1054. inline bool code_has_value() {
  1055. int i = 1;
  1056. char c = seen_pointer[i];
  1057. while (c == ' ') c = seen_pointer[++i];
  1058. if (c == '-' || c == '+') c = seen_pointer[++i];
  1059. if (c == '.') c = seen_pointer[++i];
  1060. return NUMERIC(c);
  1061. }
  1062. inline float code_value_float() {
  1063. float ret;
  1064. char* e = strchr(seen_pointer, 'E');
  1065. if (e) {
  1066. *e = 0;
  1067. ret = strtod(seen_pointer + 1, NULL);
  1068. *e = 'E';
  1069. }
  1070. else
  1071. ret = strtod(seen_pointer + 1, NULL);
  1072. return ret;
  1073. }
  1074. inline unsigned long code_value_ulong() { return strtoul(seen_pointer + 1, NULL, 10); }
  1075. inline long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  1076. inline int code_value_int() { return (int)strtol(seen_pointer + 1, NULL, 10); }
  1077. inline uint16_t code_value_ushort() { return (uint16_t)strtoul(seen_pointer + 1, NULL, 10); }
  1078. inline uint8_t code_value_byte() { return (uint8_t)(constrain(strtol(seen_pointer + 1, NULL, 10), 0, 255)); }
  1079. inline bool code_value_bool() { return code_value_byte() > 0; }
  1080. #if ENABLED(INCH_MODE_SUPPORT)
  1081. inline void set_input_linear_units(LinearUnit units) {
  1082. switch (units) {
  1083. case LINEARUNIT_INCH:
  1084. linear_unit_factor = 25.4;
  1085. break;
  1086. case LINEARUNIT_MM:
  1087. default:
  1088. linear_unit_factor = 1.0;
  1089. break;
  1090. }
  1091. volumetric_unit_factor = pow(linear_unit_factor, 3.0);
  1092. }
  1093. inline float axis_unit_factor(int axis) {
  1094. return (axis == E_AXIS && volumetric_enabled ? volumetric_unit_factor : linear_unit_factor);
  1095. }
  1096. inline float code_value_linear_units() { return code_value_float() * linear_unit_factor; }
  1097. inline float code_value_axis_units(int axis) { return code_value_float() * axis_unit_factor(axis); }
  1098. inline float code_value_per_axis_unit(int axis) { return code_value_float() / axis_unit_factor(axis); }
  1099. #else
  1100. inline float code_value_linear_units() { return code_value_float(); }
  1101. inline float code_value_axis_units(int axis) { UNUSED(axis); return code_value_float(); }
  1102. inline float code_value_per_axis_unit(int axis) { UNUSED(axis); return code_value_float(); }
  1103. #endif
  1104. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  1105. inline void set_input_temp_units(TempUnit units) { input_temp_units = units; }
  1106. float code_value_temp_abs() {
  1107. switch (input_temp_units) {
  1108. case TEMPUNIT_C:
  1109. return code_value_float();
  1110. case TEMPUNIT_F:
  1111. return (code_value_float() - 32) / 1.8;
  1112. case TEMPUNIT_K:
  1113. return code_value_float() - 272.15;
  1114. default:
  1115. return code_value_float();
  1116. }
  1117. }
  1118. float code_value_temp_diff() {
  1119. switch (input_temp_units) {
  1120. case TEMPUNIT_C:
  1121. case TEMPUNIT_K:
  1122. return code_value_float();
  1123. case TEMPUNIT_F:
  1124. return code_value_float() / 1.8;
  1125. default:
  1126. return code_value_float();
  1127. }
  1128. }
  1129. #else
  1130. float code_value_temp_abs() { return code_value_float(); }
  1131. float code_value_temp_diff() { return code_value_float(); }
  1132. #endif
  1133. FORCE_INLINE millis_t code_value_millis() { return code_value_ulong(); }
  1134. inline millis_t code_value_millis_from_seconds() { return code_value_float() * 1000; }
  1135. bool code_seen(char code) {
  1136. seen_pointer = strchr(current_command_args, code);
  1137. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  1138. }
  1139. /**
  1140. * Set target_extruder from the T parameter or the active_extruder
  1141. *
  1142. * Returns TRUE if the target is invalid
  1143. */
  1144. bool get_target_extruder_from_command(int code) {
  1145. if (code_seen('T')) {
  1146. if (code_value_byte() >= EXTRUDERS) {
  1147. SERIAL_ECHO_START;
  1148. SERIAL_CHAR('M');
  1149. SERIAL_ECHO(code);
  1150. SERIAL_ECHOPAIR(" " MSG_INVALID_EXTRUDER " ", code_value_byte());
  1151. SERIAL_EOL;
  1152. return true;
  1153. }
  1154. target_extruder = code_value_byte();
  1155. }
  1156. else
  1157. target_extruder = active_extruder;
  1158. return false;
  1159. }
  1160. #define DEFINE_PGM_READ_ANY(type, reader) \
  1161. static inline type pgm_read_any(const type *p) \
  1162. { return pgm_read_##reader##_near(p); }
  1163. DEFINE_PGM_READ_ANY(float, float);
  1164. DEFINE_PGM_READ_ANY(signed char, byte);
  1165. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  1166. static const PROGMEM type array##_P[3] = \
  1167. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  1168. static inline type array(int axis) \
  1169. { return pgm_read_any(&array##_P[axis]); }
  1170. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  1171. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  1172. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  1173. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  1174. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  1175. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  1176. #if ENABLED(DUAL_X_CARRIAGE)
  1177. #define DXC_FULL_CONTROL_MODE 0
  1178. #define DXC_AUTO_PARK_MODE 1
  1179. #define DXC_DUPLICATION_MODE 2
  1180. static int dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1181. static float x_home_pos(int extruder) {
  1182. if (extruder == 0)
  1183. return base_home_pos(X_AXIS) + home_offset[X_AXIS];
  1184. else
  1185. /**
  1186. * In dual carriage mode the extruder offset provides an override of the
  1187. * second X-carriage offset when homed - otherwise X2_HOME_POS is used.
  1188. * This allow soft recalibration of the second extruder offset position
  1189. * without firmware reflash (through the M218 command).
  1190. */
  1191. return (hotend_offset[X_AXIS][1] > 0) ? hotend_offset[X_AXIS][1] : X2_HOME_POS;
  1192. }
  1193. static int x_home_dir(int extruder) {
  1194. return (extruder == 0) ? X_HOME_DIR : X2_HOME_DIR;
  1195. }
  1196. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1197. static bool active_extruder_parked = false; // used in mode 1 & 2
  1198. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  1199. static millis_t delayed_move_time = 0; // used in mode 1
  1200. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1201. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  1202. bool extruder_duplication_enabled = false; // used in mode 2
  1203. #endif //DUAL_X_CARRIAGE
  1204. /**
  1205. * Software endstops can be used to monitor the open end of
  1206. * an axis that has a hardware endstop on the other end. Or
  1207. * they can prevent axes from moving past endstops and grinding.
  1208. *
  1209. * To keep doing their job as the coordinate system changes,
  1210. * the software endstop positions must be refreshed to remain
  1211. * at the same positions relative to the machine.
  1212. */
  1213. static void update_software_endstops(AxisEnum axis) {
  1214. float offs = home_offset[axis] + position_shift[axis];
  1215. #if ENABLED(DUAL_X_CARRIAGE)
  1216. if (axis == X_AXIS) {
  1217. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1218. if (active_extruder != 0) {
  1219. sw_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1220. sw_endstop_max[X_AXIS] = dual_max_x + offs;
  1221. return;
  1222. }
  1223. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1224. sw_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1225. sw_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1226. return;
  1227. }
  1228. }
  1229. else
  1230. #endif
  1231. {
  1232. sw_endstop_min[axis] = base_min_pos(axis) + offs;
  1233. sw_endstop_max[axis] = base_max_pos(axis) + offs;
  1234. }
  1235. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1236. if (DEBUGGING(LEVELING)) {
  1237. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1238. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1239. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1240. SERIAL_ECHOPAIR("\n sw_endstop_min = ", sw_endstop_min[axis]);
  1241. SERIAL_ECHOPAIR("\n sw_endstop_max = ", sw_endstop_max[axis]);
  1242. SERIAL_EOL;
  1243. }
  1244. #endif
  1245. #if ENABLED(DELTA)
  1246. if (axis == Z_AXIS) {
  1247. delta_clip_start_height = sw_endstop_max[axis] - delta_safe_distance_from_top();
  1248. }
  1249. #endif
  1250. }
  1251. /**
  1252. * Change the home offset for an axis, update the current
  1253. * position and the software endstops to retain the same
  1254. * relative distance to the new home.
  1255. *
  1256. * Since this changes the current_position, code should
  1257. * call sync_plan_position soon after this.
  1258. */
  1259. static void set_home_offset(AxisEnum axis, float v) {
  1260. current_position[axis] += v - home_offset[axis];
  1261. home_offset[axis] = v;
  1262. update_software_endstops(axis);
  1263. }
  1264. static void set_axis_is_at_home(AxisEnum axis) {
  1265. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1266. if (DEBUGGING(LEVELING)) {
  1267. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis);
  1268. SERIAL_ECHOLNPGM(")");
  1269. }
  1270. #endif
  1271. position_shift[axis] = 0;
  1272. #if ENABLED(DUAL_X_CARRIAGE)
  1273. if (axis == X_AXIS && (active_extruder != 0 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1274. if (active_extruder != 0)
  1275. current_position[X_AXIS] = x_home_pos(active_extruder);
  1276. else
  1277. current_position[X_AXIS] = base_home_pos(X_AXIS) + home_offset[X_AXIS];
  1278. update_software_endstops(X_AXIS);
  1279. return;
  1280. }
  1281. #endif
  1282. #if ENABLED(SCARA)
  1283. if (axis == X_AXIS || axis == Y_AXIS) {
  1284. float homeposition[3];
  1285. for (int i = 0; i < 3; i++) homeposition[i] = base_home_pos(i);
  1286. // SERIAL_ECHOPGM("homeposition[x]= "); SERIAL_ECHO(homeposition[0]);
  1287. // SERIAL_ECHOPGM("homeposition[y]= "); SERIAL_ECHOLN(homeposition[1]);
  1288. /**
  1289. * Works out real Homeposition angles using inverse kinematics,
  1290. * and calculates homing offset using forward kinematics
  1291. */
  1292. calculate_delta(homeposition);
  1293. // SERIAL_ECHOPGM("base Theta= "); SERIAL_ECHO(delta[X_AXIS]);
  1294. // SERIAL_ECHOPGM(" base Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  1295. for (int i = 0; i < 2; i++) delta[i] -= home_offset[i];
  1296. // SERIAL_ECHOPGM("addhome X="); SERIAL_ECHO(home_offset[X_AXIS]);
  1297. // SERIAL_ECHOPGM(" addhome Y="); SERIAL_ECHO(home_offset[Y_AXIS]);
  1298. // SERIAL_ECHOPGM(" addhome Theta="); SERIAL_ECHO(delta[X_AXIS]);
  1299. // SERIAL_ECHOPGM(" addhome Psi+Theta="); SERIAL_ECHOLN(delta[Y_AXIS]);
  1300. calculate_SCARA_forward_Transform(delta);
  1301. // SERIAL_ECHOPGM("Delta X="); SERIAL_ECHO(delta[X_AXIS]);
  1302. // SERIAL_ECHOPGM(" Delta Y="); SERIAL_ECHOLN(delta[Y_AXIS]);
  1303. current_position[axis] = delta[axis];
  1304. /**
  1305. * SCARA home positions are based on configuration since the actual
  1306. * limits are determined by the inverse kinematic transform.
  1307. */
  1308. sw_endstop_min[axis] = base_min_pos(axis); // + (delta[axis] - base_home_pos(axis));
  1309. sw_endstop_max[axis] = base_max_pos(axis); // + (delta[axis] - base_home_pos(axis));
  1310. }
  1311. else
  1312. #endif
  1313. {
  1314. current_position[axis] = base_home_pos(axis) + home_offset[axis];
  1315. update_software_endstops(axis);
  1316. #if HAS_BED_PROBE && Z_HOME_DIR < 0 && DISABLED(Z_MIN_PROBE_ENDSTOP)
  1317. if (axis == Z_AXIS) {
  1318. current_position[Z_AXIS] -= zprobe_zoffset;
  1319. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1320. if (DEBUGGING(LEVELING)) {
  1321. SERIAL_ECHOPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1322. SERIAL_EOL;
  1323. }
  1324. #endif
  1325. }
  1326. #endif
  1327. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1328. if (DEBUGGING(LEVELING)) {
  1329. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1330. SERIAL_ECHOPAIR("] = ", home_offset[axis]);
  1331. SERIAL_EOL;
  1332. DEBUG_POS("", current_position);
  1333. }
  1334. #endif
  1335. }
  1336. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1337. if (DEBUGGING(LEVELING)) {
  1338. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis);
  1339. SERIAL_ECHOLNPGM(")");
  1340. }
  1341. #endif
  1342. }
  1343. /**
  1344. * Some planner shorthand inline functions
  1345. */
  1346. inline void set_homing_bump_feedrate(AxisEnum axis) {
  1347. const int homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1348. int hbd = homing_bump_divisor[axis];
  1349. if (hbd < 1) {
  1350. hbd = 10;
  1351. SERIAL_ECHO_START;
  1352. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1353. }
  1354. feedrate = homing_feedrate[axis] / hbd;
  1355. }
  1356. //
  1357. // line_to_current_position
  1358. // Move the planner to the current position from wherever it last moved
  1359. // (or from wherever it has been told it is located).
  1360. //
  1361. inline void line_to_current_position() {
  1362. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate / 60, active_extruder);
  1363. }
  1364. inline void line_to_z(float zPosition) {
  1365. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], zPosition, current_position[E_AXIS], feedrate / 60, active_extruder);
  1366. }
  1367. //
  1368. // line_to_destination
  1369. // Move the planner, not necessarily synced with current_position
  1370. //
  1371. inline void line_to_destination(float mm_m) {
  1372. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], mm_m / 60, active_extruder);
  1373. }
  1374. inline void line_to_destination() { line_to_destination(feedrate); }
  1375. /**
  1376. * sync_plan_position
  1377. * Set planner / stepper positions to the cartesian current_position.
  1378. * The stepper code translates these coordinates into step units.
  1379. * Allows translation between steps and millimeters for cartesian & core robots
  1380. */
  1381. inline void sync_plan_position() {
  1382. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1383. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  1384. #endif
  1385. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  1386. }
  1387. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  1388. inline void set_current_to_destination() { memcpy(current_position, destination, sizeof(current_position)); }
  1389. inline void set_destination_to_current() { memcpy(destination, current_position, sizeof(destination)); }
  1390. #if ENABLED(DELTA)
  1391. /**
  1392. * Calculate delta, start a line, and set current_position to destination
  1393. */
  1394. void prepare_move_to_destination_raw() {
  1395. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1396. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_move_to_destination_raw", destination);
  1397. #endif
  1398. refresh_cmd_timeout();
  1399. calculate_delta(destination);
  1400. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  1401. set_current_to_destination();
  1402. }
  1403. #endif
  1404. /**
  1405. * Plan a move to (X, Y, Z) and set the current_position
  1406. * The final current_position may not be the one that was requested
  1407. */
  1408. static void do_blocking_move_to(float x, float y, float z, float feed_rate = 0.0) {
  1409. float old_feedrate = feedrate;
  1410. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1411. if (DEBUGGING(LEVELING)) print_xyz(PSTR("do_blocking_move_to"), NULL, x, y, z);
  1412. #endif
  1413. #if ENABLED(DELTA)
  1414. feedrate = (feed_rate != 0.0) ? feed_rate : XY_PROBE_FEEDRATE;
  1415. destination[X_AXIS] = x;
  1416. destination[Y_AXIS] = y;
  1417. destination[Z_AXIS] = z;
  1418. if (x == current_position[X_AXIS] && y == current_position[Y_AXIS])
  1419. prepare_move_to_destination_raw(); // this will also set_current_to_destination
  1420. else
  1421. prepare_move_to_destination(); // this will also set_current_to_destination
  1422. #else
  1423. // If Z needs to raise, do it before moving XY
  1424. if (current_position[Z_AXIS] < z) {
  1425. feedrate = (feed_rate != 0.0) ? feed_rate : homing_feedrate[Z_AXIS];
  1426. current_position[Z_AXIS] = z;
  1427. line_to_current_position();
  1428. }
  1429. feedrate = (feed_rate != 0.0) ? feed_rate : XY_PROBE_FEEDRATE;
  1430. current_position[X_AXIS] = x;
  1431. current_position[Y_AXIS] = y;
  1432. line_to_current_position();
  1433. // If Z needs to lower, do it after moving XY
  1434. if (current_position[Z_AXIS] > z) {
  1435. feedrate = (feed_rate != 0.0) ? feed_rate : homing_feedrate[Z_AXIS];
  1436. current_position[Z_AXIS] = z;
  1437. line_to_current_position();
  1438. }
  1439. #endif
  1440. stepper.synchronize();
  1441. feedrate = old_feedrate;
  1442. }
  1443. inline void do_blocking_move_to_x(float x, float feed_rate = 0.0) {
  1444. do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], feed_rate);
  1445. }
  1446. inline void do_blocking_move_to_y(float y) {
  1447. do_blocking_move_to(current_position[X_AXIS], y, current_position[Z_AXIS]);
  1448. }
  1449. inline void do_blocking_move_to_xy(float x, float y, float feed_rate = 0.0) {
  1450. do_blocking_move_to(x, y, current_position[Z_AXIS], feed_rate);
  1451. }
  1452. inline void do_blocking_move_to_z(float z, float feed_rate = 0.0) {
  1453. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, feed_rate);
  1454. }
  1455. //
  1456. // Prepare to do endstop or probe moves
  1457. // with custom feedrates.
  1458. //
  1459. // - Save current feedrates
  1460. // - Reset the rate multiplier
  1461. // - Reset the command timeout
  1462. // - Enable the endstops (for endstop moves)
  1463. //
  1464. static void setup_for_endstop_or_probe_move() {
  1465. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1466. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1467. #endif
  1468. saved_feedrate = feedrate;
  1469. saved_feedrate_multiplier = feedrate_multiplier;
  1470. feedrate_multiplier = 100;
  1471. refresh_cmd_timeout();
  1472. }
  1473. static void clean_up_after_endstop_or_probe_move() {
  1474. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1475. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1476. #endif
  1477. feedrate = saved_feedrate;
  1478. feedrate_multiplier = saved_feedrate_multiplier;
  1479. refresh_cmd_timeout();
  1480. }
  1481. #if HAS_BED_PROBE
  1482. /**
  1483. * Raise Z to a minimum height to make room for a probe to move
  1484. */
  1485. inline void do_probe_raise(float z_raise) {
  1486. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1487. if (DEBUGGING(LEVELING)) {
  1488. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1489. SERIAL_ECHOLNPGM(")");
  1490. }
  1491. #endif
  1492. float z_dest = home_offset[Z_AXIS] + z_raise;
  1493. if (zprobe_zoffset < 0)
  1494. z_dest -= zprobe_zoffset;
  1495. if (z_dest > current_position[Z_AXIS])
  1496. do_blocking_move_to_z(z_dest);
  1497. }
  1498. #endif //HAS_BED_PROBE
  1499. #if ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || ENABLED(Z_SAFE_HOMING) || HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE)
  1500. static bool axis_unhomed_error(const bool x, const bool y, const bool z) {
  1501. const bool xx = x && !axis_homed[X_AXIS],
  1502. yy = y && !axis_homed[Y_AXIS],
  1503. zz = z && !axis_homed[Z_AXIS];
  1504. if (xx || yy || zz) {
  1505. SERIAL_ECHO_START;
  1506. SERIAL_ECHOPGM(MSG_HOME " ");
  1507. if (xx) SERIAL_ECHOPGM(MSG_X);
  1508. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1509. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1510. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1511. #if ENABLED(ULTRA_LCD)
  1512. char message[3 * (LCD_WIDTH) + 1] = ""; // worst case is kana.utf with up to 3*LCD_WIDTH+1
  1513. strcat_P(message, PSTR(MSG_HOME " "));
  1514. if (xx) strcat_P(message, PSTR(MSG_X));
  1515. if (yy) strcat_P(message, PSTR(MSG_Y));
  1516. if (zz) strcat_P(message, PSTR(MSG_Z));
  1517. strcat_P(message, PSTR(" " MSG_FIRST));
  1518. lcd_setstatus(message);
  1519. #endif
  1520. return true;
  1521. }
  1522. return false;
  1523. }
  1524. #endif
  1525. #if ENABLED(Z_PROBE_SLED)
  1526. #ifndef SLED_DOCKING_OFFSET
  1527. #define SLED_DOCKING_OFFSET 0
  1528. #endif
  1529. /**
  1530. * Method to dock/undock a sled designed by Charles Bell.
  1531. *
  1532. * stow[in] If false, move to MAX_X and engage the solenoid
  1533. * If true, move to MAX_X and release the solenoid
  1534. */
  1535. static void dock_sled(bool stow) {
  1536. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1537. if (DEBUGGING(LEVELING)) {
  1538. SERIAL_ECHOPAIR("dock_sled(", stow);
  1539. SERIAL_ECHOLNPGM(")");
  1540. }
  1541. #endif
  1542. // Dock sled a bit closer to ensure proper capturing
  1543. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1544. digitalWrite(SLED_PIN, !stow); // switch solenoid
  1545. }
  1546. #endif // Z_PROBE_SLED
  1547. #if 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, 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, 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, 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, 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, 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, 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, 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, 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, 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, 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. // returns false for ok and true for failure
  1715. static bool set_probe_deployed(bool deploy) {
  1716. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1717. if (DEBUGGING(LEVELING)) {
  1718. DEBUG_POS("set_probe_deployed", current_position);
  1719. SERIAL_ECHOPAIR("deploy: ", deploy);
  1720. }
  1721. #endif
  1722. if (endstops.z_probe_enabled == deploy) return false;
  1723. // Make room for probe
  1724. do_probe_raise(_Z_RAISE_PROBE_DEPLOY_STOW);
  1725. #if ENABLED(Z_PROBE_SLED)
  1726. if (axis_unhomed_error(true, false, false)) { stop(); return true; }
  1727. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1728. if (axis_unhomed_error(true, true, true )) { stop(); return true; }
  1729. #endif
  1730. float oldXpos = current_position[X_AXIS]; // save x position
  1731. float oldYpos = current_position[Y_AXIS]; // save y position
  1732. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1733. // If endstop is already false, the Z probe is deployed
  1734. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1735. // Would a goto be less ugly?
  1736. //while (!_TRIGGERED_WHEN_STOWED_TEST) { idle(); // would offer the opportunity
  1737. // for a triggered when stowed manual probe.
  1738. #endif
  1739. #if ENABLED(Z_PROBE_SLED)
  1740. dock_sled(!deploy);
  1741. #elif HAS_Z_SERVO_ENDSTOP
  1742. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[((deploy) ? 0 : 1)]);
  1743. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1744. if (!deploy) run_stow_moves_script();
  1745. else run_deploy_moves_script();
  1746. #else
  1747. // Nothing to be done. Just enable_z_probe below...
  1748. #endif
  1749. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1750. }; // opened before the probe specific actions
  1751. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) {
  1752. if (IsRunning()) {
  1753. SERIAL_ERROR_START;
  1754. SERIAL_ERRORLNPGM("Z-Probe failed");
  1755. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1756. }
  1757. stop();
  1758. return true;
  1759. }
  1760. #endif
  1761. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1762. endstops.enable_z_probe( deploy );
  1763. return false;
  1764. }
  1765. // Do a single Z probe and return with current_position[Z_AXIS]
  1766. // at the height where the probe triggered.
  1767. static float run_z_probe() {
  1768. float old_feedrate = feedrate;
  1769. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1770. refresh_cmd_timeout();
  1771. #if ENABLED(DELTA)
  1772. float start_z = current_position[Z_AXIS];
  1773. long start_steps = stepper.position(Z_AXIS);
  1774. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1775. if (DEBUGGING(LEVELING)) DEBUG_POS("run_z_probe (DELTA) 1", current_position);
  1776. #endif
  1777. // move down slowly until you find the bed
  1778. feedrate = homing_feedrate[Z_AXIS] / 4;
  1779. destination[Z_AXIS] = -10;
  1780. prepare_move_to_destination_raw(); // this will also set_current_to_destination
  1781. stepper.synchronize();
  1782. endstops.hit_on_purpose(); // clear endstop hit flags
  1783. /**
  1784. * We have to let the planner know where we are right now as it
  1785. * is not where we said to go.
  1786. */
  1787. long stop_steps = stepper.position(Z_AXIS);
  1788. float mm = start_z - float(start_steps - stop_steps) / planner.axis_steps_per_mm[Z_AXIS];
  1789. current_position[Z_AXIS] = mm;
  1790. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1791. if (DEBUGGING(LEVELING)) DEBUG_POS("run_z_probe (DELTA) 2", current_position);
  1792. #endif
  1793. #else // !DELTA
  1794. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1795. planner.bed_level_matrix.set_to_identity();
  1796. #endif
  1797. feedrate = homing_feedrate[Z_AXIS];
  1798. // Move down until the Z probe (or endstop?) is triggered
  1799. float zPosition = -(Z_MAX_LENGTH + 10);
  1800. line_to_z(zPosition);
  1801. stepper.synchronize();
  1802. // Tell the planner where we ended up - Get this from the stepper handler
  1803. zPosition = stepper.get_axis_position_mm(Z_AXIS);
  1804. planner.set_position_mm(
  1805. current_position[X_AXIS], current_position[Y_AXIS], zPosition,
  1806. current_position[E_AXIS]
  1807. );
  1808. // move up the retract distance
  1809. zPosition += home_bump_mm(Z_AXIS);
  1810. line_to_z(zPosition);
  1811. stepper.synchronize();
  1812. endstops.hit_on_purpose(); // clear endstop hit flags
  1813. // move back down slowly to find bed
  1814. set_homing_bump_feedrate(Z_AXIS);
  1815. zPosition -= home_bump_mm(Z_AXIS) * 2;
  1816. line_to_z(zPosition);
  1817. stepper.synchronize();
  1818. endstops.hit_on_purpose(); // clear endstop hit flags
  1819. // Get the current stepper position after bumping an endstop
  1820. current_position[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  1821. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1822. if (DEBUGGING(LEVELING)) DEBUG_POS("run_z_probe", current_position);
  1823. #endif
  1824. #endif // !DELTA
  1825. SYNC_PLAN_POSITION_KINEMATIC();
  1826. feedrate = old_feedrate;
  1827. return current_position[Z_AXIS];
  1828. }
  1829. //
  1830. // - Move to the given XY
  1831. // - Deploy the probe, if not already deployed
  1832. // - Probe the bed, get the Z position
  1833. // - Depending on the 'stow' flag
  1834. // - Stow the probe, or
  1835. // - Raise to the BETWEEN height
  1836. // - Return the probed Z position
  1837. //
  1838. static float probe_pt(float x, float y, bool stow = true, int verbose_level = 1) {
  1839. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1840. if (DEBUGGING(LEVELING)) {
  1841. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1842. SERIAL_ECHOPAIR(", ", y);
  1843. SERIAL_ECHOPAIR(", ", stow ? "stow" : "no stow");
  1844. SERIAL_ECHOLNPGM(")");
  1845. DEBUG_POS("", current_position);
  1846. }
  1847. #endif
  1848. float old_feedrate = feedrate;
  1849. // Ensure a minimum height before moving the probe
  1850. do_probe_raise(Z_RAISE_BETWEEN_PROBINGS);
  1851. // Move to the XY where we shall probe
  1852. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1853. if (DEBUGGING(LEVELING)) {
  1854. SERIAL_ECHOPAIR("> do_blocking_move_to_xy(", x - (X_PROBE_OFFSET_FROM_EXTRUDER));
  1855. SERIAL_ECHOPAIR(", ", y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1856. SERIAL_ECHOLNPGM(")");
  1857. }
  1858. #endif
  1859. feedrate = XY_PROBE_FEEDRATE;
  1860. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1861. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1862. if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> ");
  1863. #endif
  1864. if (DEPLOY_PROBE()) return NAN;
  1865. float measured_z = run_z_probe();
  1866. if (stow) {
  1867. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1868. if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> ");
  1869. #endif
  1870. if (STOW_PROBE()) return NAN;
  1871. }
  1872. else {
  1873. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1874. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> do_probe_raise");
  1875. #endif
  1876. do_probe_raise(Z_RAISE_BETWEEN_PROBINGS);
  1877. }
  1878. if (verbose_level > 2) {
  1879. SERIAL_PROTOCOLPGM("Bed X: ");
  1880. SERIAL_PROTOCOL_F(x, 3);
  1881. SERIAL_PROTOCOLPGM(" Y: ");
  1882. SERIAL_PROTOCOL_F(y, 3);
  1883. SERIAL_PROTOCOLPGM(" Z: ");
  1884. SERIAL_PROTOCOL_F(measured_z, 3);
  1885. SERIAL_EOL;
  1886. }
  1887. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1888. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1889. #endif
  1890. feedrate = old_feedrate;
  1891. return measured_z;
  1892. }
  1893. #endif // HAS_BED_PROBE
  1894. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  1895. #if ENABLED(AUTO_BED_LEVELING_GRID)
  1896. #if DISABLED(DELTA)
  1897. static void set_bed_level_equation_lsq(double* plane_equation_coefficients) {
  1898. //planner.bed_level_matrix.debug("bed level before");
  1899. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1900. planner.bed_level_matrix.set_to_identity();
  1901. if (DEBUGGING(LEVELING)) {
  1902. vector_3 uncorrected_position = planner.adjusted_position();
  1903. DEBUG_POS(">>> set_bed_level_equation_lsq", uncorrected_position);
  1904. DEBUG_POS(">>> set_bed_level_equation_lsq", current_position);
  1905. }
  1906. #endif
  1907. vector_3 planeNormal = vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1);
  1908. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1909. vector_3 corrected_position = planner.adjusted_position();
  1910. current_position[X_AXIS] = corrected_position.x;
  1911. current_position[Y_AXIS] = corrected_position.y;
  1912. current_position[Z_AXIS] = corrected_position.z;
  1913. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1914. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< set_bed_level_equation_lsq", corrected_position);
  1915. #endif
  1916. SYNC_PLAN_POSITION_KINEMATIC();
  1917. }
  1918. #endif // !DELTA
  1919. #else // !AUTO_BED_LEVELING_GRID
  1920. static void set_bed_level_equation_3pts(float z_at_pt_1, float z_at_pt_2, float z_at_pt_3) {
  1921. planner.bed_level_matrix.set_to_identity();
  1922. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1923. if (DEBUGGING(LEVELING)) {
  1924. vector_3 uncorrected_position = planner.adjusted_position();
  1925. DEBUG_POS("set_bed_level_equation_3pts", uncorrected_position);
  1926. }
  1927. #endif
  1928. vector_3 pt1 = vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, z_at_pt_1);
  1929. vector_3 pt2 = vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, z_at_pt_2);
  1930. vector_3 pt3 = vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, z_at_pt_3);
  1931. vector_3 planeNormal = vector_3::cross(pt1 - pt2, pt3 - pt2).get_normal();
  1932. if (planeNormal.z < 0) {
  1933. planeNormal.x = -planeNormal.x;
  1934. planeNormal.y = -planeNormal.y;
  1935. planeNormal.z = -planeNormal.z;
  1936. }
  1937. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  1938. vector_3 corrected_position = planner.adjusted_position();
  1939. current_position[X_AXIS] = corrected_position.x;
  1940. current_position[Y_AXIS] = corrected_position.y;
  1941. current_position[Z_AXIS] = corrected_position.z;
  1942. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1943. if (DEBUGGING(LEVELING)) DEBUG_POS("set_bed_level_equation_3pts", corrected_position);
  1944. #endif
  1945. SYNC_PLAN_POSITION_KINEMATIC();
  1946. }
  1947. #endif // !AUTO_BED_LEVELING_GRID
  1948. #if ENABLED(DELTA)
  1949. /**
  1950. * All DELTA leveling in the Marlin uses NONLINEAR_BED_LEVELING
  1951. */
  1952. static void extrapolate_one_point(int x, int y, int xdir, int ydir) {
  1953. if (bed_level[x][y] != 0.0) {
  1954. return; // Don't overwrite good values.
  1955. }
  1956. float a = 2 * bed_level[x + xdir][y] - bed_level[x + xdir * 2][y]; // Left to right.
  1957. float b = 2 * bed_level[x][y + ydir] - bed_level[x][y + ydir * 2]; // Front to back.
  1958. float c = 2 * bed_level[x + xdir][y + ydir] - bed_level[x + xdir * 2][y + ydir * 2]; // Diagonal.
  1959. float median = c; // Median is robust (ignores outliers).
  1960. if (a < b) {
  1961. if (b < c) median = b;
  1962. if (c < a) median = a;
  1963. }
  1964. else { // b <= a
  1965. if (c < b) median = b;
  1966. if (a < c) median = a;
  1967. }
  1968. bed_level[x][y] = median;
  1969. }
  1970. /**
  1971. * Fill in the unprobed points (corners of circular print surface)
  1972. * using linear extrapolation, away from the center.
  1973. */
  1974. static void extrapolate_unprobed_bed_level() {
  1975. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  1976. for (int y = 0; y <= half; y++) {
  1977. for (int x = 0; x <= half; x++) {
  1978. if (x + y < 3) continue;
  1979. extrapolate_one_point(half - x, half - y, x > 1 ? +1 : 0, y > 1 ? +1 : 0);
  1980. extrapolate_one_point(half + x, half - y, x > 1 ? -1 : 0, y > 1 ? +1 : 0);
  1981. extrapolate_one_point(half - x, half + y, x > 1 ? +1 : 0, y > 1 ? -1 : 0);
  1982. extrapolate_one_point(half + x, half + y, x > 1 ? -1 : 0, y > 1 ? -1 : 0);
  1983. }
  1984. }
  1985. }
  1986. /**
  1987. * Print calibration results for plotting or manual frame adjustment.
  1988. */
  1989. static void print_bed_level() {
  1990. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  1991. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  1992. SERIAL_PROTOCOL_F(bed_level[x][y], 2);
  1993. SERIAL_PROTOCOLCHAR(' ');
  1994. }
  1995. SERIAL_EOL;
  1996. }
  1997. }
  1998. /**
  1999. * Reset calibration results to zero.
  2000. */
  2001. void reset_bed_level() {
  2002. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2003. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2004. #endif
  2005. for (int y = 0; y < AUTO_BED_LEVELING_GRID_POINTS; y++) {
  2006. for (int x = 0; x < AUTO_BED_LEVELING_GRID_POINTS; x++) {
  2007. bed_level[x][y] = 0.0;
  2008. }
  2009. }
  2010. }
  2011. #endif // DELTA
  2012. #endif // AUTO_BED_LEVELING_FEATURE
  2013. /**
  2014. * Home an individual axis
  2015. */
  2016. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2017. static void homeaxis(AxisEnum axis) {
  2018. #define HOMEAXIS_DO(LETTER) \
  2019. ((LETTER##_MIN_PIN > -1 && LETTER##_HOME_DIR==-1) || (LETTER##_MAX_PIN > -1 && LETTER##_HOME_DIR==1))
  2020. if (!(axis == X_AXIS ? HOMEAXIS_DO(X) : axis == Y_AXIS ? HOMEAXIS_DO(Y) : axis == Z_AXIS ? HOMEAXIS_DO(Z) : 0)) return;
  2021. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2022. if (DEBUGGING(LEVELING)) {
  2023. SERIAL_ECHOPAIR(">>> homeaxis(", axis);
  2024. SERIAL_ECHOLNPGM(")");
  2025. }
  2026. #endif
  2027. int axis_home_dir =
  2028. #if ENABLED(DUAL_X_CARRIAGE)
  2029. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2030. #endif
  2031. home_dir(axis);
  2032. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2033. #if HAS_BED_PROBE && DISABLED(Z_MIN_PROBE_ENDSTOP)
  2034. if (axis == Z_AXIS && axis_home_dir < 0) {
  2035. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2036. if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> ");
  2037. #endif
  2038. if (DEPLOY_PROBE()) return;
  2039. }
  2040. #endif
  2041. // Set the axis position as setup for the move
  2042. current_position[axis] = 0;
  2043. sync_plan_position();
  2044. // Set a flag for Z motor locking
  2045. #if ENABLED(Z_DUAL_ENDSTOPS)
  2046. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2047. #endif
  2048. // Move towards the endstop until an endstop is triggered
  2049. destination[axis] = 1.5 * max_length(axis) * axis_home_dir;
  2050. feedrate = homing_feedrate[axis];
  2051. line_to_destination();
  2052. stepper.synchronize();
  2053. // Set the axis position as setup for the move
  2054. current_position[axis] = 0;
  2055. sync_plan_position();
  2056. // Move away from the endstop by the axis HOME_BUMP_MM
  2057. destination[axis] = -home_bump_mm(axis) * axis_home_dir;
  2058. line_to_destination();
  2059. stepper.synchronize();
  2060. // Slow down the feedrate for the next move
  2061. set_homing_bump_feedrate(axis);
  2062. // Move slowly towards the endstop until triggered
  2063. destination[axis] = 2 * home_bump_mm(axis) * axis_home_dir;
  2064. line_to_destination();
  2065. stepper.synchronize();
  2066. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2067. if (DEBUGGING(LEVELING)) DEBUG_POS("> TRIGGER ENDSTOP", current_position);
  2068. #endif
  2069. #if ENABLED(Z_DUAL_ENDSTOPS)
  2070. if (axis == Z_AXIS) {
  2071. float adj = fabs(z_endstop_adj);
  2072. bool lockZ1;
  2073. if (axis_home_dir > 0) {
  2074. adj = -adj;
  2075. lockZ1 = (z_endstop_adj > 0);
  2076. }
  2077. else
  2078. lockZ1 = (z_endstop_adj < 0);
  2079. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2080. sync_plan_position();
  2081. // Move to the adjusted endstop height
  2082. feedrate = homing_feedrate[axis];
  2083. destination[Z_AXIS] = adj;
  2084. line_to_destination();
  2085. stepper.synchronize();
  2086. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2087. stepper.set_homing_flag(false);
  2088. } // Z_AXIS
  2089. #endif
  2090. #if ENABLED(DELTA)
  2091. // retrace by the amount specified in endstop_adj
  2092. if (endstop_adj[axis] * axis_home_dir < 0) {
  2093. sync_plan_position();
  2094. destination[axis] = endstop_adj[axis];
  2095. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2096. if (DEBUGGING(LEVELING)) {
  2097. SERIAL_ECHOPAIR("> endstop_adj = ", endstop_adj[axis]);
  2098. DEBUG_POS("", destination);
  2099. }
  2100. #endif
  2101. line_to_destination();
  2102. stepper.synchronize();
  2103. }
  2104. #endif
  2105. // Set the axis position to its home position (plus home offsets)
  2106. set_axis_is_at_home(axis);
  2107. SYNC_PLAN_POSITION_KINEMATIC();
  2108. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2109. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2110. #endif
  2111. destination[axis] = current_position[axis];
  2112. endstops.hit_on_purpose(); // clear endstop hit flags
  2113. axis_known_position[axis] = true;
  2114. axis_homed[axis] = true;
  2115. // Put away the Z probe
  2116. #if HAS_BED_PROBE && DISABLED(Z_MIN_PROBE_ENDSTOP)
  2117. if (axis == Z_AXIS && axis_home_dir < 0) {
  2118. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2119. if (DEBUGGING(LEVELING)) SERIAL_ECHOPGM("> ");
  2120. #endif
  2121. if (STOW_PROBE()) return;
  2122. }
  2123. #endif
  2124. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2125. if (DEBUGGING(LEVELING)) {
  2126. SERIAL_ECHOPAIR("<<< homeaxis(", axis);
  2127. SERIAL_ECHOLNPGM(")");
  2128. }
  2129. #endif
  2130. }
  2131. #if ENABLED(FWRETRACT)
  2132. void retract(bool retracting, bool swapping = false) {
  2133. if (retracting == retracted[active_extruder]) return;
  2134. float old_feedrate = feedrate;
  2135. set_destination_to_current();
  2136. if (retracting) {
  2137. feedrate = retract_feedrate_mm_s * 60;
  2138. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2139. sync_plan_position_e();
  2140. prepare_move_to_destination();
  2141. if (retract_zlift > 0.01) {
  2142. current_position[Z_AXIS] -= retract_zlift;
  2143. SYNC_PLAN_POSITION_KINEMATIC();
  2144. prepare_move_to_destination();
  2145. }
  2146. }
  2147. else {
  2148. if (retract_zlift > 0.01) {
  2149. current_position[Z_AXIS] += retract_zlift;
  2150. SYNC_PLAN_POSITION_KINEMATIC();
  2151. }
  2152. feedrate = retract_recover_feedrate * 60;
  2153. float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2154. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2155. sync_plan_position_e();
  2156. prepare_move_to_destination();
  2157. }
  2158. feedrate = old_feedrate;
  2159. retracted[active_extruder] = retracting;
  2160. } // retract()
  2161. #endif // FWRETRACT
  2162. /**
  2163. * ***************************************************************************
  2164. * ***************************** G-CODE HANDLING *****************************
  2165. * ***************************************************************************
  2166. */
  2167. /**
  2168. * Set XYZE destination and feedrate from the current GCode command
  2169. *
  2170. * - Set destination from included axis codes
  2171. * - Set to current for missing axis codes
  2172. * - Set the feedrate, if included
  2173. */
  2174. void gcode_get_destination() {
  2175. for (int i = 0; i < NUM_AXIS; i++) {
  2176. if (code_seen(axis_codes[i]))
  2177. destination[i] = code_value_axis_units(i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2178. else
  2179. destination[i] = current_position[i];
  2180. }
  2181. if (code_seen('F') && code_value_linear_units() > 0.0)
  2182. feedrate = code_value_linear_units();
  2183. }
  2184. void unknown_command_error() {
  2185. SERIAL_ECHO_START;
  2186. SERIAL_ECHOPGM(MSG_UNKNOWN_COMMAND);
  2187. SERIAL_ECHO(current_command);
  2188. SERIAL_ECHOLNPGM("\"");
  2189. }
  2190. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2191. /**
  2192. * Output a "busy" message at regular intervals
  2193. * while the machine is not accepting commands.
  2194. */
  2195. void host_keepalive() {
  2196. millis_t ms = millis();
  2197. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2198. if (PENDING(ms, next_busy_signal_ms)) return;
  2199. switch (busy_state) {
  2200. case IN_HANDLER:
  2201. case IN_PROCESS:
  2202. SERIAL_ECHO_START;
  2203. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2204. break;
  2205. case PAUSED_FOR_USER:
  2206. SERIAL_ECHO_START;
  2207. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2208. break;
  2209. case PAUSED_FOR_INPUT:
  2210. SERIAL_ECHO_START;
  2211. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2212. break;
  2213. default:
  2214. break;
  2215. }
  2216. }
  2217. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2218. }
  2219. #endif //HOST_KEEPALIVE_FEATURE
  2220. /**
  2221. * G0, G1: Coordinated movement of X Y Z E axes
  2222. */
  2223. inline void gcode_G0_G1() {
  2224. if (IsRunning()) {
  2225. gcode_get_destination(); // For X Y Z E F
  2226. #if ENABLED(FWRETRACT)
  2227. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  2228. float echange = destination[E_AXIS] - current_position[E_AXIS];
  2229. // Is this move an attempt to retract or recover?
  2230. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2231. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2232. sync_plan_position_e(); // AND from the planner
  2233. retract(!retracted[active_extruder]);
  2234. return;
  2235. }
  2236. }
  2237. #endif //FWRETRACT
  2238. prepare_move_to_destination();
  2239. }
  2240. }
  2241. /**
  2242. * G2: Clockwise Arc
  2243. * G3: Counterclockwise Arc
  2244. */
  2245. #if ENABLED(ARC_SUPPORT)
  2246. inline void gcode_G2_G3(bool clockwise) {
  2247. if (IsRunning()) {
  2248. #if ENABLED(SF_ARC_FIX)
  2249. bool relative_mode_backup = relative_mode;
  2250. relative_mode = true;
  2251. #endif
  2252. gcode_get_destination();
  2253. #if ENABLED(SF_ARC_FIX)
  2254. relative_mode = relative_mode_backup;
  2255. #endif
  2256. // Center of arc as offset from current_position
  2257. float arc_offset[2] = {
  2258. code_seen('I') ? code_value_axis_units(X_AXIS) : 0,
  2259. code_seen('J') ? code_value_axis_units(Y_AXIS) : 0
  2260. };
  2261. // Send an arc to the planner
  2262. plan_arc(destination, arc_offset, clockwise);
  2263. refresh_cmd_timeout();
  2264. }
  2265. }
  2266. #endif
  2267. /**
  2268. * G4: Dwell S<seconds> or P<milliseconds>
  2269. */
  2270. inline void gcode_G4() {
  2271. millis_t codenum = 0;
  2272. if (code_seen('P')) codenum = code_value_millis(); // milliseconds to wait
  2273. if (code_seen('S')) codenum = code_value_millis_from_seconds(); // seconds to wait
  2274. stepper.synchronize();
  2275. refresh_cmd_timeout();
  2276. codenum += previous_cmd_ms; // keep track of when we started waiting
  2277. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2278. while (PENDING(millis(), codenum)) idle();
  2279. }
  2280. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2281. /**
  2282. * Parameters interpreted according to:
  2283. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2284. * However I, J omission is not supported at this point; all
  2285. * parameters can be omitted and default to zero.
  2286. */
  2287. /**
  2288. * G5: Cubic B-spline
  2289. */
  2290. inline void gcode_G5() {
  2291. if (IsRunning()) {
  2292. gcode_get_destination();
  2293. float offset[] = {
  2294. code_seen('I') ? code_value_axis_units(X_AXIS) : 0.0,
  2295. code_seen('J') ? code_value_axis_units(Y_AXIS) : 0.0,
  2296. code_seen('P') ? code_value_axis_units(X_AXIS) : 0.0,
  2297. code_seen('Q') ? code_value_axis_units(Y_AXIS) : 0.0
  2298. };
  2299. plan_cubic_move(offset);
  2300. }
  2301. }
  2302. #endif // BEZIER_CURVE_SUPPORT
  2303. #if ENABLED(FWRETRACT)
  2304. /**
  2305. * G10 - Retract filament according to settings of M207
  2306. * G11 - Recover filament according to settings of M208
  2307. */
  2308. inline void gcode_G10_G11(bool doRetract=false) {
  2309. #if EXTRUDERS > 1
  2310. if (doRetract) {
  2311. retracted_swap[active_extruder] = (code_seen('S') && code_value_bool()); // checks for swap retract argument
  2312. }
  2313. #endif
  2314. retract(doRetract
  2315. #if EXTRUDERS > 1
  2316. , retracted_swap[active_extruder]
  2317. #endif
  2318. );
  2319. }
  2320. #endif //FWRETRACT
  2321. #if ENABLED(NOZZLE_CLEAN_FEATURE) && ENABLED(AUTO_BED_LEVELING_FEATURE)
  2322. #include "nozzle.h"
  2323. inline void gcode_G12() {
  2324. // Don't allow nozzle cleaning without homing first
  2325. if (axis_unhomed_error(true, true, true)) { return; }
  2326. uint8_t const pattern = code_seen('P') ? code_value_ushort() : 0;
  2327. uint8_t const strokes = code_seen('S') ? code_value_ushort() : NOZZLE_CLEAN_STROKES;
  2328. uint8_t const objects = code_seen('T') ? code_value_ushort() : 3;
  2329. Nozzle::clean(pattern, strokes, objects);
  2330. }
  2331. #endif
  2332. #if ENABLED(INCH_MODE_SUPPORT)
  2333. /**
  2334. * G20: Set input mode to inches
  2335. */
  2336. inline void gcode_G20() {
  2337. set_input_linear_units(LINEARUNIT_INCH);
  2338. }
  2339. /**
  2340. * G21: Set input mode to millimeters
  2341. */
  2342. inline void gcode_G21() {
  2343. set_input_linear_units(LINEARUNIT_MM);
  2344. }
  2345. #endif
  2346. #if ENABLED(QUICK_HOME)
  2347. static void quick_home_xy() {
  2348. current_position[X_AXIS] = current_position[Y_AXIS] = 0;
  2349. #if ENABLED(DUAL_X_CARRIAGE)
  2350. int x_axis_home_dir = x_home_dir(active_extruder);
  2351. extruder_duplication_enabled = false;
  2352. #else
  2353. int x_axis_home_dir = home_dir(X_AXIS);
  2354. #endif
  2355. float mlx = max_length(X_AXIS), mly = max_length(Y_AXIS),
  2356. mlratio = mlx > mly ? mly / mlx : mlx / mly;
  2357. destination[X_AXIS] = 1.5 * mlx * x_axis_home_dir;
  2358. destination[Y_AXIS] = 1.5 * mly * home_dir(Y_AXIS);
  2359. feedrate = min(homing_feedrate[X_AXIS], homing_feedrate[Y_AXIS]) * sqrt(mlratio * mlratio + 1);
  2360. line_to_destination();
  2361. stepper.synchronize();
  2362. endstops.hit_on_purpose(); // clear endstop hit flags
  2363. destination[X_AXIS] = destination[Y_AXIS] = 0;
  2364. }
  2365. #endif // QUICK_HOME
  2366. /**
  2367. * G28: Home all axes according to settings
  2368. *
  2369. * Parameters
  2370. *
  2371. * None Home to all axes with no parameters.
  2372. * With QUICK_HOME enabled XY will home together, then Z.
  2373. *
  2374. * Cartesian parameters
  2375. *
  2376. * X Home to the X endstop
  2377. * Y Home to the Y endstop
  2378. * Z Home to the Z endstop
  2379. *
  2380. */
  2381. inline void gcode_G28() {
  2382. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2383. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(">>> gcode_G28");
  2384. #endif
  2385. // Wait for planner moves to finish!
  2386. stepper.synchronize();
  2387. // For auto bed leveling, clear the level matrix
  2388. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  2389. planner.bed_level_matrix.set_to_identity();
  2390. #if ENABLED(DELTA)
  2391. reset_bed_level();
  2392. #endif
  2393. #endif
  2394. /**
  2395. * For mesh bed leveling deactivate the mesh calculations, will be turned
  2396. * on again when homing all axis
  2397. */
  2398. #if ENABLED(MESH_BED_LEVELING)
  2399. float pre_home_z = MESH_HOME_SEARCH_Z;
  2400. if (mbl.active()) {
  2401. // Save known Z position if already homed
  2402. if (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) {
  2403. pre_home_z = current_position[Z_AXIS];
  2404. pre_home_z += mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS));
  2405. }
  2406. mbl.set_active(false);
  2407. current_position[Z_AXIS] = pre_home_z;
  2408. }
  2409. #endif
  2410. setup_for_endstop_or_probe_move();
  2411. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2412. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  2413. #endif
  2414. endstops.enable(true); // Enable endstops for next homing move
  2415. #if ENABLED(DELTA)
  2416. /**
  2417. * A delta can only safely home all axes at the same time
  2418. */
  2419. // Pretend the current position is 0,0,0
  2420. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = 0;
  2421. sync_plan_position();
  2422. // Move all carriages up together until the first endstop is hit.
  2423. for (int i = X_AXIS; i <= Z_AXIS; i++) destination[i] = 3 * (Z_MAX_LENGTH);
  2424. feedrate = 1.732 * homing_feedrate[X_AXIS];
  2425. line_to_destination();
  2426. stepper.synchronize();
  2427. endstops.hit_on_purpose(); // clear endstop hit flags
  2428. // Destination reached
  2429. for (int i = X_AXIS; i <= Z_AXIS; i++) current_position[i] = destination[i];
  2430. // take care of back off and rehome now we are all at the top
  2431. HOMEAXIS(X);
  2432. HOMEAXIS(Y);
  2433. HOMEAXIS(Z);
  2434. SYNC_PLAN_POSITION_KINEMATIC();
  2435. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2436. if (DEBUGGING(LEVELING)) DEBUG_POS("(DELTA)", current_position);
  2437. #endif
  2438. #else // NOT DELTA
  2439. bool homeX = code_seen('X'), homeY = code_seen('Y'), homeZ = code_seen('Z');
  2440. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  2441. set_destination_to_current();
  2442. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2443. if (home_all_axis || homeZ) {
  2444. HOMEAXIS(Z);
  2445. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2446. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  2447. #endif
  2448. }
  2449. #else
  2450. if (home_all_axis || homeX || homeY) {
  2451. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2452. destination[Z_AXIS] = home_offset[Z_AXIS] + MIN_Z_HEIGHT_FOR_HOMING;
  2453. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  2454. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2455. if (DEBUGGING(LEVELING)) {
  2456. SERIAL_ECHOPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  2457. SERIAL_EOL;
  2458. }
  2459. #endif
  2460. do_blocking_move_to_z(destination[Z_AXIS]);
  2461. }
  2462. }
  2463. #endif
  2464. #if ENABLED(QUICK_HOME)
  2465. if (home_all_axis || (homeX && homeY)) quick_home_xy();
  2466. #endif
  2467. #if ENABLED(HOME_Y_BEFORE_X)
  2468. // Home Y
  2469. if (home_all_axis || homeY) {
  2470. HOMEAXIS(Y);
  2471. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2472. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  2473. #endif
  2474. }
  2475. #endif
  2476. // Home X
  2477. if (home_all_axis || homeX) {
  2478. #if ENABLED(DUAL_X_CARRIAGE)
  2479. int tmp_extruder = active_extruder;
  2480. extruder_duplication_enabled = false;
  2481. active_extruder = !active_extruder;
  2482. HOMEAXIS(X);
  2483. inactive_extruder_x_pos = current_position[X_AXIS];
  2484. active_extruder = tmp_extruder;
  2485. HOMEAXIS(X);
  2486. // reset state used by the different modes
  2487. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  2488. delayed_move_time = 0;
  2489. active_extruder_parked = true;
  2490. #else
  2491. HOMEAXIS(X);
  2492. #endif
  2493. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2494. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  2495. #endif
  2496. }
  2497. #if DISABLED(HOME_Y_BEFORE_X)
  2498. // Home Y
  2499. if (home_all_axis || homeY) {
  2500. HOMEAXIS(Y);
  2501. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2502. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  2503. #endif
  2504. }
  2505. #endif
  2506. // Home Z last if homing towards the bed
  2507. #if Z_HOME_DIR < 0
  2508. if (home_all_axis || homeZ) {
  2509. #if ENABLED(Z_SAFE_HOMING)
  2510. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2511. if (DEBUGGING(LEVELING)) {
  2512. SERIAL_ECHOLNPGM("> Z_SAFE_HOMING >>>");
  2513. }
  2514. #endif
  2515. if (home_all_axis) {
  2516. /**
  2517. * At this point we already have Z at MIN_Z_HEIGHT_FOR_HOMING height
  2518. * No need to move Z any more as this height should already be safe
  2519. * enough to reach Z_SAFE_HOMING XY positions.
  2520. * Just make sure the planner is in sync.
  2521. */
  2522. SYNC_PLAN_POSITION_KINEMATIC();
  2523. /**
  2524. * Set the Z probe (or just the nozzle) destination to the safe
  2525. * homing point
  2526. */
  2527. destination[X_AXIS] = round(Z_SAFE_HOMING_X_POINT - (X_PROBE_OFFSET_FROM_EXTRUDER));
  2528. destination[Y_AXIS] = round(Z_SAFE_HOMING_Y_POINT - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  2529. destination[Z_AXIS] = current_position[Z_AXIS]; //z is already at the right height
  2530. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2531. if (DEBUGGING(LEVELING)) {
  2532. DEBUG_POS("> Z_SAFE_HOMING > home_all_axis", current_position);
  2533. DEBUG_POS("> Z_SAFE_HOMING > home_all_axis", destination);
  2534. }
  2535. #endif
  2536. // Move in the XY plane
  2537. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  2538. }
  2539. // Let's see if X and Y are homed
  2540. if (axis_unhomed_error(true, true, false)) return;
  2541. /**
  2542. * Make sure the Z probe is within the physical limits
  2543. * NOTE: This doesn't necessarily ensure the Z probe is also
  2544. * within the bed!
  2545. */
  2546. float cpx = current_position[X_AXIS], cpy = current_position[Y_AXIS];
  2547. if ( cpx >= X_MIN_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2548. && cpx <= X_MAX_POS - (X_PROBE_OFFSET_FROM_EXTRUDER)
  2549. && cpy >= Y_MIN_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)
  2550. && cpy <= Y_MAX_POS - (Y_PROBE_OFFSET_FROM_EXTRUDER)) {
  2551. // Home the Z axis
  2552. HOMEAXIS(Z);
  2553. }
  2554. else {
  2555. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2556. SERIAL_ECHO_START;
  2557. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2558. }
  2559. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2560. if (DEBUGGING(LEVELING)) {
  2561. SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2562. }
  2563. #endif
  2564. #else // !Z_SAFE_HOMING
  2565. HOMEAXIS(Z);
  2566. #endif // !Z_SAFE_HOMING
  2567. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2568. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all_axis || homeZ) > final", current_position);
  2569. #endif
  2570. } // home_all_axis || homeZ
  2571. #endif // Z_HOME_DIR < 0
  2572. SYNC_PLAN_POSITION_KINEMATIC();
  2573. #endif // !DELTA (gcode_G28)
  2574. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2575. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.not_homing()");
  2576. #endif
  2577. endstops.not_homing();
  2578. endstops.hit_on_purpose(); // clear endstop hit flags
  2579. // Enable mesh leveling again
  2580. #if ENABLED(MESH_BED_LEVELING)
  2581. if (mbl.has_mesh()) {
  2582. if (home_all_axis || (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && homeZ)) {
  2583. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  2584. #if Z_HOME_DIR > 0
  2585. + Z_MAX_POS
  2586. #endif
  2587. ;
  2588. SYNC_PLAN_POSITION_KINEMATIC();
  2589. mbl.set_active(true);
  2590. #if ENABLED(MESH_G28_REST_ORIGIN)
  2591. current_position[Z_AXIS] = 0.0;
  2592. set_destination_to_current();
  2593. feedrate = homing_feedrate[Z_AXIS];
  2594. line_to_destination();
  2595. stepper.synchronize();
  2596. #else
  2597. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z -
  2598. mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS))
  2599. #if Z_HOME_DIR > 0
  2600. + Z_MAX_POS
  2601. #endif
  2602. ;
  2603. #endif
  2604. }
  2605. else if ((axis_homed[X_AXIS] && axis_homed[Y_AXIS] && axis_homed[Z_AXIS]) && (homeX || homeY)) {
  2606. current_position[Z_AXIS] = pre_home_z;
  2607. SYNC_PLAN_POSITION_KINEMATIC();
  2608. mbl.set_active(true);
  2609. current_position[Z_AXIS] = pre_home_z -
  2610. mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS));
  2611. }
  2612. }
  2613. #endif
  2614. #if ENABLED(DELTA)
  2615. // move to a height where we can use the full xy-area
  2616. do_blocking_move_to_z(delta_clip_start_height);
  2617. #endif
  2618. clean_up_after_endstop_or_probe_move();
  2619. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2620. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  2621. #endif
  2622. report_current_position();
  2623. }
  2624. #if HAS_PROBING_PROCEDURE
  2625. void out_of_range_error(const char* p_edge) {
  2626. SERIAL_PROTOCOLPGM("?Probe ");
  2627. serialprintPGM(p_edge);
  2628. SERIAL_PROTOCOLLNPGM(" position out of range.");
  2629. }
  2630. #endif
  2631. #if ENABLED(MESH_BED_LEVELING)
  2632. enum MeshLevelingState { MeshReport, MeshStart, MeshNext, MeshSet, MeshSetZOffset, MeshReset };
  2633. inline void _mbl_goto_xy(float x, float y) {
  2634. float old_feedrate = feedrate;
  2635. feedrate = homing_feedrate[X_AXIS];
  2636. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  2637. #if Z_RAISE_BETWEEN_PROBINGS > MIN_Z_HEIGHT_FOR_HOMING
  2638. + Z_RAISE_BETWEEN_PROBINGS
  2639. #elif MIN_Z_HEIGHT_FOR_HOMING > 0
  2640. + MIN_Z_HEIGHT_FOR_HOMING
  2641. #endif
  2642. ;
  2643. line_to_current_position();
  2644. current_position[X_AXIS] = x + home_offset[X_AXIS];
  2645. current_position[Y_AXIS] = y + home_offset[Y_AXIS];
  2646. line_to_current_position();
  2647. #if Z_RAISE_BETWEEN_PROBINGS > 0 || MIN_Z_HEIGHT_FOR_HOMING > 0
  2648. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z;
  2649. line_to_current_position();
  2650. #endif
  2651. feedrate = old_feedrate;
  2652. stepper.synchronize();
  2653. }
  2654. /**
  2655. * G29: Mesh-based Z probe, probes a grid and produces a
  2656. * mesh to compensate for variable bed height
  2657. *
  2658. * Parameters With MESH_BED_LEVELING:
  2659. *
  2660. * S0 Produce a mesh report
  2661. * S1 Start probing mesh points
  2662. * S2 Probe the next mesh point
  2663. * S3 Xn Yn Zn.nn Manually modify a single point
  2664. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  2665. * S5 Reset and disable mesh
  2666. *
  2667. * The S0 report the points as below
  2668. *
  2669. * +----> X-axis 1-n
  2670. * |
  2671. * |
  2672. * v Y-axis 1-n
  2673. *
  2674. */
  2675. inline void gcode_G29() {
  2676. static int probe_point = -1;
  2677. MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_byte() : MeshReport;
  2678. if (state < 0 || state > 5) {
  2679. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  2680. return;
  2681. }
  2682. int8_t px, py;
  2683. switch (state) {
  2684. case MeshReport:
  2685. if (mbl.has_mesh()) {
  2686. SERIAL_PROTOCOLPAIR("State: ", mbl.active() ? "On" : "Off");
  2687. SERIAL_PROTOCOLPAIR("\nNum X,Y: ", MESH_NUM_X_POINTS);
  2688. SERIAL_PROTOCOLCHAR(','); SERIAL_PROTOCOL(MESH_NUM_Y_POINTS);
  2689. SERIAL_PROTOCOLPAIR("\nZ search height: ", MESH_HOME_SEARCH_Z);
  2690. SERIAL_PROTOCOLPGM("\nZ offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  2691. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  2692. for (py = 0; py < MESH_NUM_Y_POINTS; py++) {
  2693. for (px = 0; px < MESH_NUM_X_POINTS; px++) {
  2694. SERIAL_PROTOCOLPGM(" ");
  2695. SERIAL_PROTOCOL_F(mbl.z_values[py][px], 5);
  2696. }
  2697. SERIAL_EOL;
  2698. }
  2699. }
  2700. else
  2701. SERIAL_PROTOCOLLNPGM("Mesh bed leveling not active.");
  2702. break;
  2703. case MeshStart:
  2704. mbl.reset();
  2705. probe_point = 0;
  2706. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  2707. break;
  2708. case MeshNext:
  2709. if (probe_point < 0) {
  2710. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  2711. return;
  2712. }
  2713. // For each G29 S2...
  2714. if (probe_point == 0) {
  2715. // For the intial G29 S2 make Z a positive value (e.g., 4.0)
  2716. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  2717. #if Z_HOME_DIR > 0
  2718. + Z_MAX_POS
  2719. #endif
  2720. ;
  2721. SYNC_PLAN_POSITION_KINEMATIC();
  2722. }
  2723. else {
  2724. // For G29 S2 after adjusting Z.
  2725. mbl.set_zigzag_z(probe_point - 1, current_position[Z_AXIS]);
  2726. }
  2727. // If there's another point to sample, move there with optional lift.
  2728. if (probe_point < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  2729. mbl.zigzag(probe_point, px, py);
  2730. _mbl_goto_xy(mbl.get_probe_x(px), mbl.get_probe_y(py));
  2731. probe_point++;
  2732. }
  2733. else {
  2734. // One last "return to the bed" (as originally coded) at completion
  2735. current_position[Z_AXIS] = MESH_HOME_SEARCH_Z
  2736. #if Z_RAISE_BETWEEN_PROBINGS > MIN_Z_HEIGHT_FOR_HOMING
  2737. + Z_RAISE_BETWEEN_PROBINGS
  2738. #elif MIN_Z_HEIGHT_FOR_HOMING > 0
  2739. + MIN_Z_HEIGHT_FOR_HOMING
  2740. #endif
  2741. ;
  2742. line_to_current_position();
  2743. stepper.synchronize();
  2744. // After recording the last point, activate the mbl and home
  2745. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  2746. probe_point = -1;
  2747. mbl.set_has_mesh(true);
  2748. enqueue_and_echo_commands_P(PSTR("G28"));
  2749. }
  2750. break;
  2751. case MeshSet:
  2752. if (code_seen('X')) {
  2753. px = code_value_int() - 1;
  2754. if (px < 0 || px >= MESH_NUM_X_POINTS) {
  2755. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").");
  2756. return;
  2757. }
  2758. }
  2759. else {
  2760. SERIAL_PROTOCOLLNPGM("X not entered.");
  2761. return;
  2762. }
  2763. if (code_seen('Y')) {
  2764. py = code_value_int() - 1;
  2765. if (py < 0 || py >= MESH_NUM_Y_POINTS) {
  2766. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").");
  2767. return;
  2768. }
  2769. }
  2770. else {
  2771. SERIAL_PROTOCOLLNPGM("Y not entered.");
  2772. return;
  2773. }
  2774. if (code_seen('Z')) {
  2775. mbl.z_values[py][px] = code_value_axis_units(Z_AXIS);
  2776. }
  2777. else {
  2778. SERIAL_PROTOCOLLNPGM("Z not entered.");
  2779. return;
  2780. }
  2781. break;
  2782. case MeshSetZOffset:
  2783. if (code_seen('Z')) {
  2784. mbl.z_offset = code_value_axis_units(Z_AXIS);
  2785. }
  2786. else {
  2787. SERIAL_PROTOCOLLNPGM("Z not entered.");
  2788. return;
  2789. }
  2790. break;
  2791. case MeshReset:
  2792. if (mbl.active()) {
  2793. current_position[Z_AXIS] +=
  2794. mbl.get_z(RAW_CURRENT_POSITION(X_AXIS), RAW_CURRENT_POSITION(Y_AXIS)) - MESH_HOME_SEARCH_Z;
  2795. mbl.reset();
  2796. SYNC_PLAN_POSITION_KINEMATIC();
  2797. }
  2798. else
  2799. mbl.reset();
  2800. } // switch(state)
  2801. report_current_position();
  2802. }
  2803. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  2804. /**
  2805. * G29: Detailed Z probe, probes the bed at 3 or more points.
  2806. * Will fail if the printer has not been homed with G28.
  2807. *
  2808. * Enhanced G29 Auto Bed Leveling Probe Routine
  2809. *
  2810. * Parameters With AUTO_BED_LEVELING_GRID:
  2811. *
  2812. * P Set the size of the grid that will be probed (P x P points).
  2813. * Not supported by non-linear delta printer bed leveling.
  2814. * Example: "G29 P4"
  2815. *
  2816. * S Set the XY travel speed between probe points (in units/min)
  2817. *
  2818. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  2819. * or clean the rotation Matrix. Useful to check the topology
  2820. * after a first run of G29.
  2821. *
  2822. * V Set the verbose level (0-4). Example: "G29 V3"
  2823. *
  2824. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  2825. * This is useful for manual bed leveling and finding flaws in the bed (to
  2826. * assist with part placement).
  2827. * Not supported by non-linear delta printer bed leveling.
  2828. *
  2829. * F Set the Front limit of the probing grid
  2830. * B Set the Back limit of the probing grid
  2831. * L Set the Left limit of the probing grid
  2832. * R Set the Right limit of the probing grid
  2833. *
  2834. * Global Parameters:
  2835. *
  2836. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  2837. * Include "E" to engage/disengage the Z probe for each sample.
  2838. * There's no extra effect if you have a fixed Z probe.
  2839. * Usage: "G29 E" or "G29 e"
  2840. *
  2841. */
  2842. inline void gcode_G29() {
  2843. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2844. if (DEBUGGING(LEVELING)) {
  2845. SERIAL_ECHOLNPGM(">>> gcode_G29");
  2846. DEBUG_POS("", current_position);
  2847. }
  2848. #endif
  2849. // Don't allow auto-leveling without homing first
  2850. if (axis_unhomed_error(true, true, true)) return;
  2851. int verbose_level = code_seen('V') ? code_value_int() : 1;
  2852. if (verbose_level < 0 || verbose_level > 4) {
  2853. SERIAL_ECHOLNPGM("?(V)erbose Level is implausible (0-4).");
  2854. return;
  2855. }
  2856. bool dryrun = code_seen('D');
  2857. bool stow_probe_after_each = code_seen('E');
  2858. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2859. #if DISABLED(DELTA)
  2860. bool do_topography_map = verbose_level > 2 || code_seen('T');
  2861. #endif
  2862. if (verbose_level > 0) {
  2863. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  2864. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  2865. }
  2866. int auto_bed_leveling_grid_points = AUTO_BED_LEVELING_GRID_POINTS;
  2867. #if DISABLED(DELTA)
  2868. if (code_seen('P')) auto_bed_leveling_grid_points = code_value_int();
  2869. if (auto_bed_leveling_grid_points < 2) {
  2870. SERIAL_PROTOCOLLNPGM("?Number of probed (P)oints is implausible (2 minimum).");
  2871. return;
  2872. }
  2873. #endif
  2874. xy_probe_speed = code_seen('S') ? (int)code_value_linear_units() : XY_PROBE_SPEED;
  2875. int left_probe_bed_position = code_seen('L') ? (int)code_value_axis_units(X_AXIS) : LEFT_PROBE_BED_POSITION,
  2876. right_probe_bed_position = code_seen('R') ? (int)code_value_axis_units(X_AXIS) : RIGHT_PROBE_BED_POSITION,
  2877. front_probe_bed_position = code_seen('F') ? (int)code_value_axis_units(Y_AXIS) : FRONT_PROBE_BED_POSITION,
  2878. back_probe_bed_position = code_seen('B') ? (int)code_value_axis_units(Y_AXIS) : BACK_PROBE_BED_POSITION;
  2879. bool left_out_l = left_probe_bed_position < MIN_PROBE_X,
  2880. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  2881. right_out_r = right_probe_bed_position > MAX_PROBE_X,
  2882. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  2883. front_out_f = front_probe_bed_position < MIN_PROBE_Y,
  2884. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  2885. back_out_b = back_probe_bed_position > MAX_PROBE_Y,
  2886. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  2887. if (left_out || right_out || front_out || back_out) {
  2888. if (left_out) {
  2889. out_of_range_error(PSTR("(L)eft"));
  2890. left_probe_bed_position = left_out_l ? MIN_PROBE_X : right_probe_bed_position - (MIN_PROBE_EDGE);
  2891. }
  2892. if (right_out) {
  2893. out_of_range_error(PSTR("(R)ight"));
  2894. right_probe_bed_position = right_out_r ? MAX_PROBE_X : left_probe_bed_position + MIN_PROBE_EDGE;
  2895. }
  2896. if (front_out) {
  2897. out_of_range_error(PSTR("(F)ront"));
  2898. front_probe_bed_position = front_out_f ? MIN_PROBE_Y : back_probe_bed_position - (MIN_PROBE_EDGE);
  2899. }
  2900. if (back_out) {
  2901. out_of_range_error(PSTR("(B)ack"));
  2902. back_probe_bed_position = back_out_b ? MAX_PROBE_Y : front_probe_bed_position + MIN_PROBE_EDGE;
  2903. }
  2904. return;
  2905. }
  2906. #endif // AUTO_BED_LEVELING_GRID
  2907. if (!dryrun) {
  2908. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(DELTA)
  2909. if (DEBUGGING(LEVELING)) {
  2910. vector_3 corrected_position = planner.adjusted_position();
  2911. DEBUG_POS("BEFORE matrix.set_to_identity", corrected_position);
  2912. DEBUG_POS("BEFORE matrix.set_to_identity", current_position);
  2913. }
  2914. #endif
  2915. // make sure the bed_level_rotation_matrix is identity or the planner will get it wrong
  2916. planner.bed_level_matrix.set_to_identity();
  2917. #if ENABLED(DELTA)
  2918. reset_bed_level();
  2919. #else //!DELTA
  2920. //vector_3 corrected_position = planner.adjusted_position();
  2921. //corrected_position.debug("position before G29");
  2922. vector_3 uncorrected_position = planner.adjusted_position();
  2923. //uncorrected_position.debug("position during G29");
  2924. current_position[X_AXIS] = uncorrected_position.x;
  2925. current_position[Y_AXIS] = uncorrected_position.y;
  2926. current_position[Z_AXIS] = uncorrected_position.z;
  2927. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2928. if (DEBUGGING(LEVELING)) DEBUG_POS("AFTER matrix.set_to_identity", uncorrected_position);
  2929. #endif
  2930. SYNC_PLAN_POSITION_KINEMATIC();
  2931. #endif // !DELTA
  2932. }
  2933. stepper.synchronize();
  2934. setup_for_endstop_or_probe_move();
  2935. // Deploy the probe. Probe will raise if needed.
  2936. if (DEPLOY_PROBE()) return;
  2937. bed_leveling_in_progress = true;
  2938. #if ENABLED(AUTO_BED_LEVELING_GRID)
  2939. // probe at the points of a lattice grid
  2940. const int xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (auto_bed_leveling_grid_points - 1),
  2941. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (auto_bed_leveling_grid_points - 1);
  2942. #if ENABLED(DELTA)
  2943. delta_grid_spacing[0] = xGridSpacing;
  2944. delta_grid_spacing[1] = yGridSpacing;
  2945. float zoffset = zprobe_zoffset;
  2946. if (code_seen('Z')) zoffset += code_value_axis_units(Z_AXIS);
  2947. #else // !DELTA
  2948. /**
  2949. * solve the plane equation ax + by + d = z
  2950. * A is the matrix with rows [x y 1] for all the probed points
  2951. * B is the vector of the Z positions
  2952. * the normal vector to the plane is formed by the coefficients of the
  2953. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  2954. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  2955. */
  2956. int abl2 = auto_bed_leveling_grid_points * auto_bed_leveling_grid_points;
  2957. double eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  2958. eqnBVector[abl2], // "B" vector of Z points
  2959. mean = 0.0;
  2960. int8_t indexIntoAB[auto_bed_leveling_grid_points][auto_bed_leveling_grid_points];
  2961. #endif // !DELTA
  2962. int probePointCounter = 0;
  2963. bool zig = (auto_bed_leveling_grid_points & 1) ? true : false; //always end at [RIGHT_PROBE_BED_POSITION, BACK_PROBE_BED_POSITION]
  2964. for (int yCount = 0; yCount < auto_bed_leveling_grid_points; yCount++) {
  2965. double yProbe = front_probe_bed_position + yGridSpacing * yCount;
  2966. int xStart, xStop, xInc;
  2967. if (zig) {
  2968. xStart = 0;
  2969. xStop = auto_bed_leveling_grid_points;
  2970. xInc = 1;
  2971. }
  2972. else {
  2973. xStart = auto_bed_leveling_grid_points - 1;
  2974. xStop = -1;
  2975. xInc = -1;
  2976. }
  2977. zig = !zig;
  2978. for (int xCount = xStart; xCount != xStop; xCount += xInc) {
  2979. double xProbe = left_probe_bed_position + xGridSpacing * xCount;
  2980. #if ENABLED(DELTA)
  2981. // Avoid probing the corners (outside the round or hexagon print surface) on a delta printer.
  2982. float distance_from_center = sqrt(xProbe * xProbe + yProbe * yProbe);
  2983. if (distance_from_center > DELTA_PROBEABLE_RADIUS) continue;
  2984. #endif //DELTA
  2985. float measured_z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  2986. #if DISABLED(DELTA)
  2987. mean += measured_z;
  2988. eqnBVector[probePointCounter] = measured_z;
  2989. eqnAMatrix[probePointCounter + 0 * abl2] = xProbe;
  2990. eqnAMatrix[probePointCounter + 1 * abl2] = yProbe;
  2991. eqnAMatrix[probePointCounter + 2 * abl2] = 1;
  2992. indexIntoAB[xCount][yCount] = probePointCounter;
  2993. #else
  2994. bed_level[xCount][yCount] = measured_z + zoffset;
  2995. #endif
  2996. probePointCounter++;
  2997. idle();
  2998. } //xProbe
  2999. } //yProbe
  3000. #else // !AUTO_BED_LEVELING_GRID
  3001. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3002. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3003. #endif
  3004. // Probe at 3 arbitrary points
  3005. float z_at_pt_1 = probe_pt( ABL_PROBE_PT_1_X + home_offset[X_AXIS],
  3006. ABL_PROBE_PT_1_Y + home_offset[Y_AXIS],
  3007. stow_probe_after_each, verbose_level),
  3008. z_at_pt_2 = probe_pt( ABL_PROBE_PT_2_X + home_offset[X_AXIS],
  3009. ABL_PROBE_PT_2_Y + home_offset[Y_AXIS],
  3010. stow_probe_after_each, verbose_level),
  3011. z_at_pt_3 = probe_pt( ABL_PROBE_PT_3_X + home_offset[X_AXIS],
  3012. ABL_PROBE_PT_3_Y + home_offset[Y_AXIS],
  3013. stow_probe_after_each, verbose_level);
  3014. if (!dryrun) set_bed_level_equation_3pts(z_at_pt_1, z_at_pt_2, z_at_pt_3);
  3015. #endif // !AUTO_BED_LEVELING_GRID
  3016. // Raise to _Z_RAISE_PROBE_DEPLOY_STOW. Stow the probe.
  3017. if (STOW_PROBE()) return;
  3018. // Restore state after probing
  3019. clean_up_after_endstop_or_probe_move();
  3020. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3021. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  3022. #endif
  3023. // Calculate leveling, print reports, correct the position
  3024. #if ENABLED(AUTO_BED_LEVELING_GRID)
  3025. #if ENABLED(DELTA)
  3026. if (!dryrun) extrapolate_unprobed_bed_level();
  3027. print_bed_level();
  3028. #else // !DELTA
  3029. // solve lsq problem
  3030. double plane_equation_coefficients[3];
  3031. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  3032. mean /= abl2;
  3033. if (verbose_level) {
  3034. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3035. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  3036. SERIAL_PROTOCOLPGM(" b: ");
  3037. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  3038. SERIAL_PROTOCOLPGM(" d: ");
  3039. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  3040. SERIAL_EOL;
  3041. if (verbose_level > 2) {
  3042. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  3043. SERIAL_PROTOCOL_F(mean, 8);
  3044. SERIAL_EOL;
  3045. }
  3046. }
  3047. if (!dryrun) set_bed_level_equation_lsq(plane_equation_coefficients);
  3048. // Show the Topography map if enabled
  3049. if (do_topography_map) {
  3050. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  3051. " +--- BACK --+\n"
  3052. " | |\n"
  3053. " L | (+) | R\n"
  3054. " E | | I\n"
  3055. " F | (-) N (+) | G\n"
  3056. " T | | H\n"
  3057. " | (-) | T\n"
  3058. " | |\n"
  3059. " O-- FRONT --+\n"
  3060. " (0,0)");
  3061. float min_diff = 999;
  3062. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  3063. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  3064. int ind = indexIntoAB[xx][yy];
  3065. float diff = eqnBVector[ind] - mean;
  3066. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  3067. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3068. z_tmp = 0;
  3069. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3070. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  3071. if (diff >= 0.0)
  3072. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  3073. else
  3074. SERIAL_PROTOCOLCHAR(' ');
  3075. SERIAL_PROTOCOL_F(diff, 5);
  3076. } // xx
  3077. SERIAL_EOL;
  3078. } // yy
  3079. SERIAL_EOL;
  3080. if (verbose_level > 3) {
  3081. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  3082. for (int yy = auto_bed_leveling_grid_points - 1; yy >= 0; yy--) {
  3083. for (int xx = 0; xx < auto_bed_leveling_grid_points; xx++) {
  3084. int ind = indexIntoAB[xx][yy];
  3085. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  3086. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3087. z_tmp = 0;
  3088. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3089. float diff = eqnBVector[ind] - z_tmp - min_diff;
  3090. if (diff >= 0.0)
  3091. SERIAL_PROTOCOLPGM(" +");
  3092. // Include + for column alignment
  3093. else
  3094. SERIAL_PROTOCOLCHAR(' ');
  3095. SERIAL_PROTOCOL_F(diff, 5);
  3096. } // xx
  3097. SERIAL_EOL;
  3098. } // yy
  3099. SERIAL_EOL;
  3100. }
  3101. } //do_topography_map
  3102. #endif //!DELTA
  3103. #endif // AUTO_BED_LEVELING_GRID
  3104. #if DISABLED(DELTA)
  3105. if (verbose_level > 0)
  3106. planner.bed_level_matrix.debug("\n\nBed Level Correction Matrix:");
  3107. if (!dryrun) {
  3108. /**
  3109. * Correct the Z height difference from Z probe position and nozzle tip position.
  3110. * The Z height on homing is measured by Z probe, but the Z probe is quite far
  3111. * from the nozzle. When the bed is uneven, this height must be corrected.
  3112. */
  3113. float x_tmp = current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  3114. y_tmp = current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER,
  3115. z_tmp = current_position[Z_AXIS],
  3116. stepper_z = stepper.get_axis_position_mm(Z_AXIS); //get the real Z (since planner.adjusted_position is now correcting the plane)
  3117. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3118. if (DEBUGGING(LEVELING)) {
  3119. SERIAL_ECHOPAIR("> BEFORE apply_rotation_xyz > stepper_z = ", stepper_z);
  3120. SERIAL_ECHOPAIR(" ... z_tmp = ", z_tmp);
  3121. SERIAL_EOL;
  3122. }
  3123. #endif
  3124. // Apply the correction sending the Z probe offset
  3125. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3126. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3127. if (DEBUGGING(LEVELING)) {
  3128. SERIAL_ECHOPAIR("> AFTER apply_rotation_xyz > z_tmp = ", z_tmp);
  3129. SERIAL_EOL;
  3130. }
  3131. #endif
  3132. // Adjust the current Z and send it to the planner.
  3133. current_position[Z_AXIS] += z_tmp - stepper_z;
  3134. SYNC_PLAN_POSITION_KINEMATIC();
  3135. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3136. if (DEBUGGING(LEVELING)) DEBUG_POS("> corrected Z in G29", current_position);
  3137. #endif
  3138. }
  3139. #endif // !DELTA
  3140. #ifdef Z_PROBE_END_SCRIPT
  3141. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3142. if (DEBUGGING(LEVELING)) {
  3143. SERIAL_ECHOPGM("Z Probe End Script: ");
  3144. SERIAL_ECHOLNPGM(Z_PROBE_END_SCRIPT);
  3145. }
  3146. #endif
  3147. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  3148. stepper.synchronize();
  3149. #endif
  3150. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3151. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  3152. #endif
  3153. bed_leveling_in_progress = false;
  3154. report_current_position();
  3155. KEEPALIVE_STATE(IN_HANDLER);
  3156. }
  3157. #endif //AUTO_BED_LEVELING_FEATURE
  3158. #if HAS_BED_PROBE
  3159. /**
  3160. * G30: Do a single Z probe at the current XY
  3161. */
  3162. inline void gcode_G30() {
  3163. setup_for_endstop_or_probe_move();
  3164. // TODO: clear the leveling matrix or the planner will be set incorrectly
  3165. float measured_z = probe_pt(current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  3166. current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER,
  3167. true, 1);
  3168. SERIAL_PROTOCOLPGM("Bed X: ");
  3169. SERIAL_PROTOCOL(current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER + 0.0001);
  3170. SERIAL_PROTOCOLPGM(" Y: ");
  3171. SERIAL_PROTOCOL(current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER + 0.0001);
  3172. SERIAL_PROTOCOLPGM(" Z: ");
  3173. SERIAL_PROTOCOL(measured_z + 0.0001);
  3174. SERIAL_EOL;
  3175. clean_up_after_endstop_or_probe_move();
  3176. report_current_position();
  3177. }
  3178. #if ENABLED(Z_PROBE_SLED)
  3179. /**
  3180. * G31: Deploy the Z probe
  3181. */
  3182. inline void gcode_G31() { DEPLOY_PROBE(); }
  3183. /**
  3184. * G32: Stow the Z probe
  3185. */
  3186. inline void gcode_G32() { STOW_PROBE(); }
  3187. #endif // Z_PROBE_SLED
  3188. #endif // HAS_BED_PROBE
  3189. /**
  3190. * G92: Set current position to given X Y Z E
  3191. */
  3192. inline void gcode_G92() {
  3193. bool didE = code_seen('E');
  3194. if (!didE) stepper.synchronize();
  3195. bool didXYZ = false;
  3196. for (int i = 0; i < NUM_AXIS; i++) {
  3197. if (code_seen(axis_codes[i])) {
  3198. float p = current_position[i],
  3199. v = code_value_axis_units(i);
  3200. current_position[i] = v;
  3201. if (i != E_AXIS) {
  3202. position_shift[i] += v - p; // Offset the coordinate space
  3203. update_software_endstops((AxisEnum)i);
  3204. didXYZ = true;
  3205. }
  3206. }
  3207. }
  3208. if (didXYZ)
  3209. SYNC_PLAN_POSITION_KINEMATIC();
  3210. else if (didE)
  3211. sync_plan_position_e();
  3212. }
  3213. #if ENABLED(ULTIPANEL)
  3214. /**
  3215. * M0: Unconditional stop - Wait for user button press on LCD
  3216. * M1: Conditional stop - Wait for user button press on LCD
  3217. */
  3218. inline void gcode_M0_M1() {
  3219. char* args = current_command_args;
  3220. millis_t codenum = 0;
  3221. bool hasP = false, hasS = false;
  3222. if (code_seen('P')) {
  3223. codenum = code_value_millis(); // milliseconds to wait
  3224. hasP = codenum > 0;
  3225. }
  3226. if (code_seen('S')) {
  3227. codenum = code_value_millis_from_seconds(); // seconds to wait
  3228. hasS = codenum > 0;
  3229. }
  3230. if (!hasP && !hasS && *args != '\0')
  3231. lcd_setstatus(args, true);
  3232. else {
  3233. LCD_MESSAGEPGM(MSG_USERWAIT);
  3234. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  3235. dontExpireStatus();
  3236. #endif
  3237. }
  3238. lcd_ignore_click();
  3239. stepper.synchronize();
  3240. refresh_cmd_timeout();
  3241. if (codenum > 0) {
  3242. codenum += previous_cmd_ms; // wait until this time for a click
  3243. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3244. while (PENDING(millis(), codenum) && !lcd_clicked()) idle();
  3245. KEEPALIVE_STATE(IN_HANDLER);
  3246. lcd_ignore_click(false);
  3247. }
  3248. else {
  3249. if (!lcd_detected()) return;
  3250. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3251. while (!lcd_clicked()) idle();
  3252. KEEPALIVE_STATE(IN_HANDLER);
  3253. }
  3254. if (IS_SD_PRINTING)
  3255. LCD_MESSAGEPGM(MSG_RESUMING);
  3256. else
  3257. LCD_MESSAGEPGM(WELCOME_MSG);
  3258. }
  3259. #endif // ULTIPANEL
  3260. /**
  3261. * M17: Enable power on all stepper motors
  3262. */
  3263. inline void gcode_M17() {
  3264. LCD_MESSAGEPGM(MSG_NO_MOVE);
  3265. enable_all_steppers();
  3266. }
  3267. #if ENABLED(SDSUPPORT)
  3268. /**
  3269. * M20: List SD card to serial output
  3270. */
  3271. inline void gcode_M20() {
  3272. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  3273. card.ls();
  3274. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  3275. }
  3276. /**
  3277. * M21: Init SD Card
  3278. */
  3279. inline void gcode_M21() {
  3280. card.initsd();
  3281. }
  3282. /**
  3283. * M22: Release SD Card
  3284. */
  3285. inline void gcode_M22() {
  3286. card.release();
  3287. }
  3288. /**
  3289. * M23: Open a file
  3290. */
  3291. inline void gcode_M23() {
  3292. card.openFile(current_command_args, true);
  3293. }
  3294. /**
  3295. * M24: Start SD Print
  3296. */
  3297. inline void gcode_M24() {
  3298. card.startFileprint();
  3299. print_job_timer.start();
  3300. }
  3301. /**
  3302. * M25: Pause SD Print
  3303. */
  3304. inline void gcode_M25() {
  3305. card.pauseSDPrint();
  3306. }
  3307. /**
  3308. * M26: Set SD Card file index
  3309. */
  3310. inline void gcode_M26() {
  3311. if (card.cardOK && code_seen('S'))
  3312. card.setIndex(code_value_long());
  3313. }
  3314. /**
  3315. * M27: Get SD Card status
  3316. */
  3317. inline void gcode_M27() {
  3318. card.getStatus();
  3319. }
  3320. /**
  3321. * M28: Start SD Write
  3322. */
  3323. inline void gcode_M28() {
  3324. card.openFile(current_command_args, false);
  3325. }
  3326. /**
  3327. * M29: Stop SD Write
  3328. * Processed in write to file routine above
  3329. */
  3330. inline void gcode_M29() {
  3331. // card.saving = false;
  3332. }
  3333. /**
  3334. * M30 <filename>: Delete SD Card file
  3335. */
  3336. inline void gcode_M30() {
  3337. if (card.cardOK) {
  3338. card.closefile();
  3339. card.removeFile(current_command_args);
  3340. }
  3341. }
  3342. #endif //SDSUPPORT
  3343. /**
  3344. * M31: Get the time since the start of SD Print (or last M109)
  3345. */
  3346. inline void gcode_M31() {
  3347. millis_t t = print_job_timer.duration();
  3348. int d = int(t / 60 / 60 / 24),
  3349. h = int(t / 60 / 60) % 60,
  3350. m = int(t / 60) % 60,
  3351. s = int(t % 60);
  3352. char time[18]; // 123456789012345678
  3353. if (d)
  3354. sprintf_P(time, PSTR("%id %ih %im %is"), d, h, m, s); // 99d 23h 59m 59s
  3355. else
  3356. sprintf_P(time, PSTR("%ih %im %is"), h, m, s); // 23h 59m 59s
  3357. lcd_setstatus(time);
  3358. SERIAL_ECHO_START;
  3359. SERIAL_ECHOPGM(MSG_PRINT_TIME " ");
  3360. SERIAL_ECHOLN(time);
  3361. thermalManager.autotempShutdown();
  3362. }
  3363. #if ENABLED(SDSUPPORT)
  3364. /**
  3365. * M32: Select file and start SD Print
  3366. */
  3367. inline void gcode_M32() {
  3368. if (card.sdprinting)
  3369. stepper.synchronize();
  3370. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  3371. if (!namestartpos)
  3372. namestartpos = current_command_args; // Default name position, 4 letters after the M
  3373. else
  3374. namestartpos++; //to skip the '!'
  3375. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  3376. if (card.cardOK) {
  3377. card.openFile(namestartpos, true, call_procedure);
  3378. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  3379. card.setIndex(code_value_long());
  3380. card.startFileprint();
  3381. // Procedure calls count as normal print time.
  3382. if (!call_procedure) print_job_timer.start();
  3383. }
  3384. }
  3385. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  3386. /**
  3387. * M33: Get the long full path of a file or folder
  3388. *
  3389. * Parameters:
  3390. * <dospath> Case-insensitive DOS-style path to a file or folder
  3391. *
  3392. * Example:
  3393. * M33 miscel~1/armchair/armcha~1.gco
  3394. *
  3395. * Output:
  3396. * /Miscellaneous/Armchair/Armchair.gcode
  3397. */
  3398. inline void gcode_M33() {
  3399. card.printLongPath(current_command_args);
  3400. }
  3401. #endif
  3402. /**
  3403. * M928: Start SD Write
  3404. */
  3405. inline void gcode_M928() {
  3406. card.openLogFile(current_command_args);
  3407. }
  3408. #endif // SDSUPPORT
  3409. /**
  3410. * M42: Change pin status via GCode
  3411. *
  3412. * P<pin> Pin number (LED if omitted)
  3413. * S<byte> Pin status from 0 - 255
  3414. */
  3415. inline void gcode_M42() {
  3416. if (!code_seen('S')) return;
  3417. int pin_status = code_value_int();
  3418. if (pin_status < 0 || pin_status > 255) return;
  3419. int pin_number = code_seen('P') ? code_value_int() : LED_PIN;
  3420. if (pin_number < 0) return;
  3421. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  3422. if (pin_number == sensitive_pins[i]) return;
  3423. pinMode(pin_number, OUTPUT);
  3424. digitalWrite(pin_number, pin_status);
  3425. analogWrite(pin_number, pin_status);
  3426. #if FAN_COUNT > 0
  3427. switch (pin_number) {
  3428. #if HAS_FAN0
  3429. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  3430. #endif
  3431. #if HAS_FAN1
  3432. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  3433. #endif
  3434. #if HAS_FAN2
  3435. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  3436. #endif
  3437. }
  3438. #endif
  3439. }
  3440. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  3441. /**
  3442. * M48: Z probe repeatability measurement function.
  3443. *
  3444. * Usage:
  3445. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  3446. * P = Number of sampled points (4-50, default 10)
  3447. * X = Sample X position
  3448. * Y = Sample Y position
  3449. * V = Verbose level (0-4, default=1)
  3450. * E = Engage Z probe for each reading
  3451. * L = Number of legs of movement before probe
  3452. * S = Schizoid (Or Star if you prefer)
  3453. *
  3454. * This function assumes the bed has been homed. Specifically, that a G28 command
  3455. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  3456. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  3457. * regenerated.
  3458. */
  3459. inline void gcode_M48() {
  3460. if (axis_unhomed_error(true, true, true)) return;
  3461. int8_t verbose_level = code_seen('V') ? code_value_byte() : 1;
  3462. if (verbose_level < 0 || verbose_level > 4) {
  3463. SERIAL_PROTOCOLLNPGM("?Verbose Level not plausible (0-4).");
  3464. return;
  3465. }
  3466. if (verbose_level > 0)
  3467. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability test");
  3468. int8_t n_samples = code_seen('P') ? code_value_byte() : 10;
  3469. if (n_samples < 4 || n_samples > 50) {
  3470. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  3471. return;
  3472. }
  3473. float X_current = current_position[X_AXIS],
  3474. Y_current = current_position[Y_AXIS];
  3475. bool stow_probe_after_each = code_seen('E');
  3476. float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : X_current + X_PROBE_OFFSET_FROM_EXTRUDER;
  3477. #if DISABLED(DELTA)
  3478. if (X_probe_location < MIN_PROBE_X || X_probe_location > MAX_PROBE_X) {
  3479. out_of_range_error(PSTR("X"));
  3480. return;
  3481. }
  3482. #endif
  3483. float Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3484. #if DISABLED(DELTA)
  3485. if (Y_probe_location < MIN_PROBE_Y || Y_probe_location > MAX_PROBE_Y) {
  3486. out_of_range_error(PSTR("Y"));
  3487. return;
  3488. }
  3489. #else
  3490. if (sqrt(X_probe_location * X_probe_location + Y_probe_location * Y_probe_location) > DELTA_PROBEABLE_RADIUS) {
  3491. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  3492. return;
  3493. }
  3494. #endif
  3495. bool seen_L = code_seen('L');
  3496. uint8_t n_legs = seen_L ? code_value_byte() : 0;
  3497. if (n_legs > 15) {
  3498. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  3499. return;
  3500. }
  3501. if (n_legs == 1) n_legs = 2;
  3502. bool schizoid_flag = code_seen('S');
  3503. if (schizoid_flag && !seen_L) n_legs = 7;
  3504. /**
  3505. * Now get everything to the specified probe point So we can safely do a
  3506. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  3507. * we don't want to use that as a starting point for each probe.
  3508. */
  3509. if (verbose_level > 2)
  3510. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  3511. #if ENABLED(DELTA)
  3512. // we don't do bed level correction in M48 because we want the raw data when we probe
  3513. reset_bed_level();
  3514. #elif ENABLED(AUTO_BED_LEVELING_FEATURE)
  3515. // we don't do bed level correction in M48 because we want the raw data when we probe
  3516. planner.bed_level_matrix.set_to_identity();
  3517. #endif
  3518. setup_for_endstop_or_probe_move();
  3519. // Move to the first point, deploy, and probe
  3520. probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  3521. randomSeed(millis());
  3522. double mean = 0, sigma = 0, sample_set[n_samples];
  3523. for (uint8_t n = 0; n < n_samples; n++) {
  3524. if (n_legs) {
  3525. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  3526. float angle = random(0.0, 360.0),
  3527. radius = random(
  3528. #if ENABLED(DELTA)
  3529. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  3530. #else
  3531. 5, X_MAX_LENGTH / 8
  3532. #endif
  3533. );
  3534. if (verbose_level > 3) {
  3535. SERIAL_ECHOPAIR("Starting radius: ", radius);
  3536. SERIAL_ECHOPAIR(" angle: ", angle);
  3537. SERIAL_ECHOPGM(" Direction: ");
  3538. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  3539. SERIAL_ECHOLNPGM("Clockwise");
  3540. }
  3541. for (uint8_t l = 0; l < n_legs - 1; l++) {
  3542. double delta_angle;
  3543. if (schizoid_flag)
  3544. // The points of a 5 point star are 72 degrees apart. We need to
  3545. // skip a point and go to the next one on the star.
  3546. delta_angle = dir * 2.0 * 72.0;
  3547. else
  3548. // If we do this line, we are just trying to move further
  3549. // around the circle.
  3550. delta_angle = dir * (float) random(25, 45);
  3551. angle += delta_angle;
  3552. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  3553. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  3554. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  3555. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  3556. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  3557. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  3558. #if DISABLED(DELTA)
  3559. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  3560. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  3561. #else
  3562. // If we have gone out too far, we can do a simple fix and scale the numbers
  3563. // back in closer to the origin.
  3564. while (sqrt(X_current * X_current + Y_current * Y_current) > DELTA_PROBEABLE_RADIUS) {
  3565. X_current /= 1.25;
  3566. Y_current /= 1.25;
  3567. if (verbose_level > 3) {
  3568. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  3569. SERIAL_ECHOPAIR(", ", Y_current);
  3570. SERIAL_EOL;
  3571. }
  3572. }
  3573. #endif
  3574. if (verbose_level > 3) {
  3575. SERIAL_PROTOCOLPGM("Going to:");
  3576. SERIAL_ECHOPAIR(" X", X_current);
  3577. SERIAL_ECHOPAIR(" Y", Y_current);
  3578. SERIAL_ECHOPAIR(" Z", current_position[Z_AXIS]);
  3579. SERIAL_EOL;
  3580. }
  3581. do_blocking_move_to_xy(X_current, Y_current);
  3582. } // n_legs loop
  3583. } // n_legs
  3584. // Probe a single point
  3585. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  3586. /**
  3587. * Get the current mean for the data points we have so far
  3588. */
  3589. double sum = 0.0;
  3590. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  3591. mean = sum / (n + 1);
  3592. /**
  3593. * Now, use that mean to calculate the standard deviation for the
  3594. * data points we have so far
  3595. */
  3596. sum = 0.0;
  3597. for (uint8_t j = 0; j <= n; j++) {
  3598. float ss = sample_set[j] - mean;
  3599. sum += ss * ss;
  3600. }
  3601. sigma = sqrt(sum / (n + 1));
  3602. if (verbose_level > 0) {
  3603. if (verbose_level > 1) {
  3604. SERIAL_PROTOCOL(n + 1);
  3605. SERIAL_PROTOCOLPGM(" of ");
  3606. SERIAL_PROTOCOL((int)n_samples);
  3607. SERIAL_PROTOCOLPGM(" z: ");
  3608. SERIAL_PROTOCOL_F(current_position[Z_AXIS], 6);
  3609. if (verbose_level > 2) {
  3610. SERIAL_PROTOCOLPGM(" mean: ");
  3611. SERIAL_PROTOCOL_F(mean, 6);
  3612. SERIAL_PROTOCOLPGM(" sigma: ");
  3613. SERIAL_PROTOCOL_F(sigma, 6);
  3614. }
  3615. }
  3616. SERIAL_EOL;
  3617. }
  3618. } // End of probe loop
  3619. if (STOW_PROBE()) return;
  3620. if (verbose_level > 0) {
  3621. SERIAL_PROTOCOLPGM("Mean: ");
  3622. SERIAL_PROTOCOL_F(mean, 6);
  3623. SERIAL_EOL;
  3624. }
  3625. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  3626. SERIAL_PROTOCOL_F(sigma, 6);
  3627. SERIAL_EOL; SERIAL_EOL;
  3628. clean_up_after_endstop_or_probe_move();
  3629. report_current_position();
  3630. }
  3631. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  3632. /**
  3633. * M75: Start print timer
  3634. */
  3635. inline void gcode_M75() { print_job_timer.start(); }
  3636. /**
  3637. * M76: Pause print timer
  3638. */
  3639. inline void gcode_M76() { print_job_timer.pause(); }
  3640. /**
  3641. * M77: Stop print timer
  3642. */
  3643. inline void gcode_M77() { print_job_timer.stop(); }
  3644. #if ENABLED(PRINTCOUNTER)
  3645. /*+
  3646. * M78: Show print statistics
  3647. */
  3648. inline void gcode_M78() {
  3649. // "M78 S78" will reset the statistics
  3650. if (code_seen('S') && code_value_int() == 78)
  3651. print_job_timer.initStats();
  3652. else print_job_timer.showStats();
  3653. }
  3654. #endif
  3655. /**
  3656. * M104: Set hot end temperature
  3657. */
  3658. inline void gcode_M104() {
  3659. if (get_target_extruder_from_command(104)) return;
  3660. if (DEBUGGING(DRYRUN)) return;
  3661. #if ENABLED(SINGLENOZZLE)
  3662. if (target_extruder != active_extruder) return;
  3663. #endif
  3664. if (code_seen('S')) {
  3665. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  3666. #if ENABLED(DUAL_X_CARRIAGE)
  3667. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3668. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  3669. #endif
  3670. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  3671. /**
  3672. * Stop the timer at the end of print, starting is managed by
  3673. * 'heat and wait' M109.
  3674. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  3675. * stand by mode, for instance in a dual extruder setup, without affecting
  3676. * the running print timer.
  3677. */
  3678. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  3679. print_job_timer.stop();
  3680. LCD_MESSAGEPGM(WELCOME_MSG);
  3681. }
  3682. #endif
  3683. if (code_value_temp_abs() > thermalManager.degHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING);
  3684. }
  3685. }
  3686. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  3687. void print_heaterstates() {
  3688. #if HAS_TEMP_HOTEND
  3689. SERIAL_PROTOCOLPGM(" T:");
  3690. SERIAL_PROTOCOL_F(thermalManager.degHotend(target_extruder), 1);
  3691. SERIAL_PROTOCOLPGM(" /");
  3692. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(target_extruder), 1);
  3693. #endif
  3694. #if HAS_TEMP_BED
  3695. SERIAL_PROTOCOLPGM(" B:");
  3696. SERIAL_PROTOCOL_F(thermalManager.degBed(), 1);
  3697. SERIAL_PROTOCOLPGM(" /");
  3698. SERIAL_PROTOCOL_F(thermalManager.degTargetBed(), 1);
  3699. #endif
  3700. #if HOTENDS > 1
  3701. HOTEND_LOOP() {
  3702. SERIAL_PROTOCOLPGM(" T");
  3703. SERIAL_PROTOCOL(e);
  3704. SERIAL_PROTOCOLCHAR(':');
  3705. SERIAL_PROTOCOL_F(thermalManager.degHotend(e), 1);
  3706. SERIAL_PROTOCOLPGM(" /");
  3707. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(e), 1);
  3708. }
  3709. #endif
  3710. #if HAS_TEMP_BED
  3711. SERIAL_PROTOCOLPGM(" B@:");
  3712. #ifdef BED_WATTS
  3713. SERIAL_PROTOCOL(((BED_WATTS) * thermalManager.getHeaterPower(-1)) / 127);
  3714. SERIAL_PROTOCOLCHAR('W');
  3715. #else
  3716. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  3717. #endif
  3718. #endif
  3719. SERIAL_PROTOCOLPGM(" @:");
  3720. #ifdef EXTRUDER_WATTS
  3721. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * thermalManager.getHeaterPower(target_extruder)) / 127);
  3722. SERIAL_PROTOCOLCHAR('W');
  3723. #else
  3724. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  3725. #endif
  3726. #if HOTENDS > 1
  3727. HOTEND_LOOP() {
  3728. SERIAL_PROTOCOLPGM(" @");
  3729. SERIAL_PROTOCOL(e);
  3730. SERIAL_PROTOCOLCHAR(':');
  3731. #ifdef EXTRUDER_WATTS
  3732. SERIAL_PROTOCOL(((EXTRUDER_WATTS) * thermalManager.getHeaterPower(e)) / 127);
  3733. SERIAL_PROTOCOLCHAR('W');
  3734. #else
  3735. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  3736. #endif
  3737. }
  3738. #endif
  3739. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  3740. #if HAS_TEMP_BED
  3741. SERIAL_PROTOCOLPGM(" ADC B:");
  3742. SERIAL_PROTOCOL_F(thermalManager.degBed(), 1);
  3743. SERIAL_PROTOCOLPGM("C->");
  3744. SERIAL_PROTOCOL_F(thermalManager.rawBedTemp() / OVERSAMPLENR, 0);
  3745. #endif
  3746. HOTEND_LOOP() {
  3747. SERIAL_PROTOCOLPGM(" T");
  3748. SERIAL_PROTOCOL(e);
  3749. SERIAL_PROTOCOLCHAR(':');
  3750. SERIAL_PROTOCOL_F(thermalManager.degHotend(e), 1);
  3751. SERIAL_PROTOCOLPGM("C->");
  3752. SERIAL_PROTOCOL_F(thermalManager.rawHotendTemp(e) / OVERSAMPLENR, 0);
  3753. }
  3754. #endif
  3755. }
  3756. #endif
  3757. /**
  3758. * M105: Read hot end and bed temperature
  3759. */
  3760. inline void gcode_M105() {
  3761. if (get_target_extruder_from_command(105)) return;
  3762. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  3763. SERIAL_PROTOCOLPGM(MSG_OK);
  3764. print_heaterstates();
  3765. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  3766. SERIAL_ERROR_START;
  3767. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  3768. #endif
  3769. SERIAL_EOL;
  3770. }
  3771. #if FAN_COUNT > 0
  3772. /**
  3773. * M106: Set Fan Speed
  3774. *
  3775. * S<int> Speed between 0-255
  3776. * P<index> Fan index, if more than one fan
  3777. */
  3778. inline void gcode_M106() {
  3779. uint16_t s = code_seen('S') ? code_value_ushort() : 255,
  3780. p = code_seen('P') ? code_value_ushort() : 0;
  3781. NOMORE(s, 255);
  3782. if (p < FAN_COUNT) fanSpeeds[p] = s;
  3783. }
  3784. /**
  3785. * M107: Fan Off
  3786. */
  3787. inline void gcode_M107() {
  3788. uint16_t p = code_seen('P') ? code_value_ushort() : 0;
  3789. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  3790. }
  3791. #endif // FAN_COUNT > 0
  3792. #if DISABLED(EMERGENCY_PARSER)
  3793. /**
  3794. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  3795. */
  3796. inline void gcode_M108() { wait_for_heatup = false; }
  3797. /**
  3798. * M112: Emergency Stop
  3799. */
  3800. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  3801. /**
  3802. * M410: Quickstop - Abort all planned moves
  3803. *
  3804. * This will stop the carriages mid-move, so most likely they
  3805. * will be out of sync with the stepper position after this.
  3806. */
  3807. inline void gcode_M410() { quickstop_stepper(); }
  3808. #endif
  3809. #ifndef MIN_COOLING_SLOPE_DEG
  3810. #define MIN_COOLING_SLOPE_DEG 1.50
  3811. #endif
  3812. #ifndef MIN_COOLING_SLOPE_TIME
  3813. #define MIN_COOLING_SLOPE_TIME 60
  3814. #endif
  3815. /**
  3816. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  3817. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  3818. */
  3819. inline void gcode_M109() {
  3820. if (get_target_extruder_from_command(109)) return;
  3821. if (DEBUGGING(DRYRUN)) return;
  3822. #if ENABLED(SINGLENOZZLE)
  3823. if (target_extruder != active_extruder) return;
  3824. #endif
  3825. bool no_wait_for_cooling = code_seen('S');
  3826. if (no_wait_for_cooling || code_seen('R')) {
  3827. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  3828. #if ENABLED(DUAL_X_CARRIAGE)
  3829. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  3830. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  3831. #endif
  3832. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  3833. /**
  3834. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  3835. * stand by mode, for instance in a dual extruder setup, without affecting
  3836. * the running print timer.
  3837. */
  3838. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  3839. print_job_timer.stop();
  3840. LCD_MESSAGEPGM(WELCOME_MSG);
  3841. }
  3842. /**
  3843. * We do not check if the timer is already running because this check will
  3844. * be done for us inside the Stopwatch::start() method thus a running timer
  3845. * will not restart.
  3846. */
  3847. else print_job_timer.start();
  3848. #endif
  3849. if (thermalManager.isHeatingHotend(target_extruder)) LCD_MESSAGEPGM(MSG_HEATING);
  3850. }
  3851. #if ENABLED(AUTOTEMP)
  3852. planner.autotemp_M109();
  3853. #endif
  3854. #if TEMP_RESIDENCY_TIME > 0
  3855. millis_t residency_start_ms = 0;
  3856. // Loop until the temperature has stabilized
  3857. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  3858. #else
  3859. // Loop until the temperature is very close target
  3860. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  3861. #endif //TEMP_RESIDENCY_TIME > 0
  3862. float theTarget = -1.0, old_temp = 9999.0;
  3863. bool wants_to_cool = false;
  3864. wait_for_heatup = true;
  3865. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  3866. KEEPALIVE_STATE(NOT_BUSY);
  3867. do {
  3868. // Target temperature might be changed during the loop
  3869. if (theTarget != thermalManager.degTargetHotend(target_extruder)) {
  3870. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  3871. theTarget = thermalManager.degTargetHotend(target_extruder);
  3872. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3873. if (no_wait_for_cooling && wants_to_cool) break;
  3874. }
  3875. now = millis();
  3876. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  3877. next_temp_ms = now + 1000UL;
  3878. print_heaterstates();
  3879. #if TEMP_RESIDENCY_TIME > 0
  3880. SERIAL_PROTOCOLPGM(" W:");
  3881. if (residency_start_ms) {
  3882. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  3883. SERIAL_PROTOCOLLN(rem);
  3884. }
  3885. else {
  3886. SERIAL_PROTOCOLLNPGM("?");
  3887. }
  3888. #else
  3889. SERIAL_EOL;
  3890. #endif
  3891. }
  3892. idle();
  3893. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3894. float temp = thermalManager.degHotend(target_extruder);
  3895. #if TEMP_RESIDENCY_TIME > 0
  3896. float temp_diff = fabs(theTarget - temp);
  3897. if (!residency_start_ms) {
  3898. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  3899. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  3900. }
  3901. else if (temp_diff > TEMP_HYSTERESIS) {
  3902. // Restart the timer whenever the temperature falls outside the hysteresis.
  3903. residency_start_ms = now;
  3904. }
  3905. #endif //TEMP_RESIDENCY_TIME > 0
  3906. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  3907. if (wants_to_cool) {
  3908. // break after MIN_COOLING_SLOPE_TIME seconds
  3909. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  3910. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  3911. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  3912. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  3913. old_temp = temp;
  3914. }
  3915. }
  3916. } while (wait_for_heatup && TEMP_CONDITIONS);
  3917. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  3918. KEEPALIVE_STATE(IN_HANDLER);
  3919. }
  3920. #if HAS_TEMP_BED
  3921. #ifndef MIN_COOLING_SLOPE_DEG_BED
  3922. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  3923. #endif
  3924. #ifndef MIN_COOLING_SLOPE_TIME_BED
  3925. #define MIN_COOLING_SLOPE_TIME_BED 60
  3926. #endif
  3927. /**
  3928. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  3929. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  3930. */
  3931. inline void gcode_M190() {
  3932. if (DEBUGGING(DRYRUN)) return;
  3933. LCD_MESSAGEPGM(MSG_BED_HEATING);
  3934. bool no_wait_for_cooling = code_seen('S');
  3935. if (no_wait_for_cooling || code_seen('R')) {
  3936. thermalManager.setTargetBed(code_value_temp_abs());
  3937. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  3938. if (code_value_temp_abs() > BED_MINTEMP) {
  3939. /**
  3940. * We start the timer when 'heating and waiting' command arrives, LCD
  3941. * functions never wait. Cooling down managed by extruders.
  3942. *
  3943. * We do not check if the timer is already running because this check will
  3944. * be done for us inside the Stopwatch::start() method thus a running timer
  3945. * will not restart.
  3946. */
  3947. print_job_timer.start();
  3948. }
  3949. #endif
  3950. }
  3951. #if TEMP_BED_RESIDENCY_TIME > 0
  3952. millis_t residency_start_ms = 0;
  3953. // Loop until the temperature has stabilized
  3954. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  3955. #else
  3956. // Loop until the temperature is very close target
  3957. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  3958. #endif //TEMP_BED_RESIDENCY_TIME > 0
  3959. float theTarget = -1.0, old_temp = 9999.0;
  3960. bool wants_to_cool = false;
  3961. wait_for_heatup = true;
  3962. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  3963. KEEPALIVE_STATE(NOT_BUSY);
  3964. do {
  3965. // Target temperature might be changed during the loop
  3966. if (theTarget != thermalManager.degTargetBed()) {
  3967. wants_to_cool = thermalManager.isCoolingBed();
  3968. theTarget = thermalManager.degTargetBed();
  3969. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  3970. if (no_wait_for_cooling && wants_to_cool) break;
  3971. }
  3972. now = millis();
  3973. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  3974. next_temp_ms = now + 1000UL;
  3975. print_heaterstates();
  3976. #if TEMP_BED_RESIDENCY_TIME > 0
  3977. SERIAL_PROTOCOLPGM(" W:");
  3978. if (residency_start_ms) {
  3979. long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  3980. SERIAL_PROTOCOLLN(rem);
  3981. }
  3982. else {
  3983. SERIAL_PROTOCOLLNPGM("?");
  3984. }
  3985. #else
  3986. SERIAL_EOL;
  3987. #endif
  3988. }
  3989. idle();
  3990. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  3991. float temp = thermalManager.degBed();
  3992. #if TEMP_BED_RESIDENCY_TIME > 0
  3993. float temp_diff = fabs(theTarget - temp);
  3994. if (!residency_start_ms) {
  3995. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  3996. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  3997. }
  3998. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  3999. // Restart the timer whenever the temperature falls outside the hysteresis.
  4000. residency_start_ms = now;
  4001. }
  4002. #endif //TEMP_BED_RESIDENCY_TIME > 0
  4003. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  4004. if (wants_to_cool) {
  4005. // break after MIN_COOLING_SLOPE_TIME_BED seconds
  4006. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  4007. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  4008. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  4009. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  4010. old_temp = temp;
  4011. }
  4012. }
  4013. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  4014. LCD_MESSAGEPGM(MSG_BED_DONE);
  4015. KEEPALIVE_STATE(IN_HANDLER);
  4016. }
  4017. #endif // HAS_TEMP_BED
  4018. /**
  4019. * M110: Set Current Line Number
  4020. */
  4021. inline void gcode_M110() {
  4022. if (code_seen('N')) gcode_N = code_value_long();
  4023. }
  4024. /**
  4025. * M111: Set the debug level
  4026. */
  4027. inline void gcode_M111() {
  4028. marlin_debug_flags = code_seen('S') ? code_value_byte() : (uint8_t) DEBUG_NONE;
  4029. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  4030. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  4031. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  4032. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  4033. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  4034. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4035. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  4036. #endif
  4037. const static char* const debug_strings[] PROGMEM = {
  4038. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16,
  4039. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4040. str_debug_32
  4041. #endif
  4042. };
  4043. SERIAL_ECHO_START;
  4044. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  4045. if (marlin_debug_flags) {
  4046. uint8_t comma = 0;
  4047. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  4048. if (TEST(marlin_debug_flags, i)) {
  4049. if (comma++) SERIAL_CHAR(',');
  4050. serialprintPGM((char*)pgm_read_word(&(debug_strings[i])));
  4051. }
  4052. }
  4053. }
  4054. else {
  4055. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  4056. }
  4057. SERIAL_EOL;
  4058. }
  4059. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  4060. /**
  4061. * M113: Get or set Host Keepalive interval (0 to disable)
  4062. *
  4063. * S<seconds> Optional. Set the keepalive interval.
  4064. */
  4065. inline void gcode_M113() {
  4066. if (code_seen('S')) {
  4067. host_keepalive_interval = code_value_byte();
  4068. NOMORE(host_keepalive_interval, 60);
  4069. }
  4070. else {
  4071. SERIAL_ECHO_START;
  4072. SERIAL_ECHOPAIR("M113 S", (unsigned long)host_keepalive_interval);
  4073. SERIAL_EOL;
  4074. }
  4075. }
  4076. #endif
  4077. #if ENABLED(BARICUDA)
  4078. #if HAS_HEATER_1
  4079. /**
  4080. * M126: Heater 1 valve open
  4081. */
  4082. inline void gcode_M126() { baricuda_valve_pressure = code_seen('S') ? code_value_byte() : 255; }
  4083. /**
  4084. * M127: Heater 1 valve close
  4085. */
  4086. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  4087. #endif
  4088. #if HAS_HEATER_2
  4089. /**
  4090. * M128: Heater 2 valve open
  4091. */
  4092. inline void gcode_M128() { baricuda_e_to_p_pressure = code_seen('S') ? code_value_byte() : 255; }
  4093. /**
  4094. * M129: Heater 2 valve close
  4095. */
  4096. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  4097. #endif
  4098. #endif //BARICUDA
  4099. /**
  4100. * M140: Set bed temperature
  4101. */
  4102. inline void gcode_M140() {
  4103. if (DEBUGGING(DRYRUN)) return;
  4104. if (code_seen('S')) thermalManager.setTargetBed(code_value_temp_abs());
  4105. }
  4106. #if ENABLED(ULTIPANEL)
  4107. /**
  4108. * M145: Set the heatup state for a material in the LCD menu
  4109. * S<material> (0=PLA, 1=ABS)
  4110. * H<hotend temp>
  4111. * B<bed temp>
  4112. * F<fan speed>
  4113. */
  4114. inline void gcode_M145() {
  4115. int8_t material = code_seen('S') ? (int8_t)code_value_int() : 0;
  4116. if (material < 0 || material > 1) {
  4117. SERIAL_ERROR_START;
  4118. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  4119. }
  4120. else {
  4121. int v;
  4122. switch (material) {
  4123. case 0:
  4124. if (code_seen('H')) {
  4125. v = code_value_int();
  4126. preheatHotendTemp1 = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  4127. }
  4128. if (code_seen('F')) {
  4129. v = code_value_int();
  4130. preheatFanSpeed1 = constrain(v, 0, 255);
  4131. }
  4132. #if TEMP_SENSOR_BED != 0
  4133. if (code_seen('B')) {
  4134. v = code_value_int();
  4135. preheatBedTemp1 = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  4136. }
  4137. #endif
  4138. break;
  4139. case 1:
  4140. if (code_seen('H')) {
  4141. v = code_value_int();
  4142. preheatHotendTemp2 = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  4143. }
  4144. if (code_seen('F')) {
  4145. v = code_value_int();
  4146. preheatFanSpeed2 = constrain(v, 0, 255);
  4147. }
  4148. #if TEMP_SENSOR_BED != 0
  4149. if (code_seen('B')) {
  4150. v = code_value_int();
  4151. preheatBedTemp2 = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  4152. }
  4153. #endif
  4154. break;
  4155. }
  4156. }
  4157. }
  4158. #endif
  4159. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  4160. /**
  4161. * M149: Set temperature units
  4162. */
  4163. inline void gcode_M149() {
  4164. if (code_seen('C')) {
  4165. set_input_temp_units(TEMPUNIT_C);
  4166. } else if (code_seen('K')) {
  4167. set_input_temp_units(TEMPUNIT_K);
  4168. } else if (code_seen('F')) {
  4169. set_input_temp_units(TEMPUNIT_F);
  4170. }
  4171. }
  4172. #endif
  4173. #if HAS_POWER_SWITCH
  4174. /**
  4175. * M80: Turn on Power Supply
  4176. */
  4177. inline void gcode_M80() {
  4178. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  4179. /**
  4180. * If you have a switch on suicide pin, this is useful
  4181. * if you want to start another print with suicide feature after
  4182. * a print without suicide...
  4183. */
  4184. #if HAS_SUICIDE
  4185. OUT_WRITE(SUICIDE_PIN, HIGH);
  4186. #endif
  4187. #if ENABLED(ULTIPANEL)
  4188. powersupply = true;
  4189. LCD_MESSAGEPGM(WELCOME_MSG);
  4190. lcd_update();
  4191. #endif
  4192. }
  4193. #endif // HAS_POWER_SWITCH
  4194. /**
  4195. * M81: Turn off Power, including Power Supply, if there is one.
  4196. *
  4197. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  4198. */
  4199. inline void gcode_M81() {
  4200. thermalManager.disable_all_heaters();
  4201. stepper.finish_and_disable();
  4202. #if FAN_COUNT > 0
  4203. #if FAN_COUNT > 1
  4204. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  4205. #else
  4206. fanSpeeds[0] = 0;
  4207. #endif
  4208. #endif
  4209. delay(1000); // Wait 1 second before switching off
  4210. #if HAS_SUICIDE
  4211. stepper.synchronize();
  4212. suicide();
  4213. #elif HAS_POWER_SWITCH
  4214. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  4215. #endif
  4216. #if ENABLED(ULTIPANEL)
  4217. #if HAS_POWER_SWITCH
  4218. powersupply = false;
  4219. #endif
  4220. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  4221. lcd_update();
  4222. #endif
  4223. }
  4224. /**
  4225. * M82: Set E codes absolute (default)
  4226. */
  4227. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  4228. /**
  4229. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  4230. */
  4231. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  4232. /**
  4233. * M18, M84: Disable all stepper motors
  4234. */
  4235. inline void gcode_M18_M84() {
  4236. if (code_seen('S')) {
  4237. stepper_inactive_time = code_value_millis_from_seconds();
  4238. }
  4239. else {
  4240. bool all_axis = !((code_seen('X')) || (code_seen('Y')) || (code_seen('Z')) || (code_seen('E')));
  4241. if (all_axis) {
  4242. stepper.finish_and_disable();
  4243. }
  4244. else {
  4245. stepper.synchronize();
  4246. if (code_seen('X')) disable_x();
  4247. if (code_seen('Y')) disable_y();
  4248. if (code_seen('Z')) disable_z();
  4249. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  4250. if (code_seen('E')) {
  4251. disable_e0();
  4252. disable_e1();
  4253. disable_e2();
  4254. disable_e3();
  4255. }
  4256. #endif
  4257. }
  4258. }
  4259. }
  4260. /**
  4261. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  4262. */
  4263. inline void gcode_M85() {
  4264. if (code_seen('S')) max_inactive_time = code_value_millis_from_seconds();
  4265. }
  4266. /**
  4267. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  4268. * (Follows the same syntax as G92)
  4269. */
  4270. inline void gcode_M92() {
  4271. for (int8_t i = 0; i < NUM_AXIS; i++) {
  4272. if (code_seen(axis_codes[i])) {
  4273. if (i == E_AXIS) {
  4274. float value = code_value_per_axis_unit(i);
  4275. if (value < 20.0) {
  4276. float factor = planner.axis_steps_per_mm[i] / value; // increase e constants if M92 E14 is given for netfab.
  4277. planner.max_e_jerk *= factor;
  4278. planner.max_feedrate[i] *= factor;
  4279. planner.max_acceleration_steps_per_s2[i] *= factor;
  4280. }
  4281. planner.axis_steps_per_mm[i] = value;
  4282. }
  4283. else {
  4284. planner.axis_steps_per_mm[i] = code_value_per_axis_unit(i);
  4285. }
  4286. }
  4287. }
  4288. }
  4289. /**
  4290. * Output the current position to serial
  4291. */
  4292. static void report_current_position() {
  4293. SERIAL_PROTOCOLPGM("X:");
  4294. SERIAL_PROTOCOL(current_position[X_AXIS]);
  4295. SERIAL_PROTOCOLPGM(" Y:");
  4296. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  4297. SERIAL_PROTOCOLPGM(" Z:");
  4298. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  4299. SERIAL_PROTOCOLPGM(" E:");
  4300. SERIAL_PROTOCOL(current_position[E_AXIS]);
  4301. stepper.report_positions();
  4302. #if ENABLED(SCARA)
  4303. SERIAL_PROTOCOLPGM("SCARA Theta:");
  4304. SERIAL_PROTOCOL(delta[X_AXIS]);
  4305. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  4306. SERIAL_PROTOCOL(delta[Y_AXIS]);
  4307. SERIAL_EOL;
  4308. SERIAL_PROTOCOLPGM("SCARA Cal - Theta:");
  4309. SERIAL_PROTOCOL(delta[X_AXIS] + home_offset[X_AXIS]);
  4310. SERIAL_PROTOCOLPGM(" Psi+Theta (90):");
  4311. SERIAL_PROTOCOL(delta[Y_AXIS] - delta[X_AXIS] - 90 + home_offset[Y_AXIS]);
  4312. SERIAL_EOL;
  4313. SERIAL_PROTOCOLPGM("SCARA step Cal - Theta:");
  4314. SERIAL_PROTOCOL(delta[X_AXIS] / 90 * planner.axis_steps_per_mm[X_AXIS]);
  4315. SERIAL_PROTOCOLPGM(" Psi+Theta:");
  4316. SERIAL_PROTOCOL((delta[Y_AXIS] - delta[X_AXIS]) / 90 * planner.axis_steps_per_mm[Y_AXIS]);
  4317. SERIAL_EOL; SERIAL_EOL;
  4318. #endif
  4319. }
  4320. /**
  4321. * M114: Output current position to serial port
  4322. */
  4323. inline void gcode_M114() { report_current_position(); }
  4324. /**
  4325. * M115: Capabilities string
  4326. */
  4327. inline void gcode_M115() {
  4328. SERIAL_PROTOCOLPGM(MSG_M115_REPORT);
  4329. }
  4330. /**
  4331. * M117: Set LCD Status Message
  4332. */
  4333. inline void gcode_M117() {
  4334. lcd_setstatus(current_command_args);
  4335. }
  4336. /**
  4337. * M119: Output endstop states to serial output
  4338. */
  4339. inline void gcode_M119() { endstops.M119(); }
  4340. /**
  4341. * M120: Enable endstops and set non-homing endstop state to "enabled"
  4342. */
  4343. inline void gcode_M120() { endstops.enable_globally(true); }
  4344. /**
  4345. * M121: Disable endstops and set non-homing endstop state to "disabled"
  4346. */
  4347. inline void gcode_M121() { endstops.enable_globally(false); }
  4348. #if ENABLED(BLINKM)
  4349. /**
  4350. * M150: Set Status LED Color - Use R-U-B for R-G-B
  4351. */
  4352. inline void gcode_M150() {
  4353. SendColors(
  4354. code_seen('R') ? code_value_byte() : 0,
  4355. code_seen('U') ? code_value_byte() : 0,
  4356. code_seen('B') ? code_value_byte() : 0
  4357. );
  4358. }
  4359. #endif // BLINKM
  4360. #if ENABLED(EXPERIMENTAL_I2CBUS)
  4361. /**
  4362. * M155: Send data to a I2C slave device
  4363. *
  4364. * This is a PoC, the formating and arguments for the GCODE will
  4365. * change to be more compatible, the current proposal is:
  4366. *
  4367. * M155 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  4368. *
  4369. * M155 B<byte-1 value in base 10>
  4370. * M155 B<byte-2 value in base 10>
  4371. * M155 B<byte-3 value in base 10>
  4372. *
  4373. * M155 S1 ; Send the buffered data and reset the buffer
  4374. * M155 R1 ; Reset the buffer without sending data
  4375. *
  4376. */
  4377. inline void gcode_M155() {
  4378. // Set the target address
  4379. if (code_seen('A'))
  4380. i2c.address(code_value_byte());
  4381. // Add a new byte to the buffer
  4382. else if (code_seen('B'))
  4383. i2c.addbyte(code_value_int());
  4384. // Flush the buffer to the bus
  4385. else if (code_seen('S')) i2c.send();
  4386. // Reset and rewind the buffer
  4387. else if (code_seen('R')) i2c.reset();
  4388. }
  4389. /**
  4390. * M156: Request X bytes from I2C slave device
  4391. *
  4392. * Usage: M156 A<slave device address base 10> B<number of bytes>
  4393. */
  4394. inline void gcode_M156() {
  4395. uint8_t addr = code_seen('A') ? code_value_byte() : 0;
  4396. int bytes = code_seen('B') ? code_value_int() : 1;
  4397. if (addr && bytes > 0 && bytes <= 32) {
  4398. i2c.address(addr);
  4399. i2c.reqbytes(bytes);
  4400. }
  4401. else {
  4402. SERIAL_ERROR_START;
  4403. SERIAL_ERRORLN("Bad i2c request");
  4404. }
  4405. }
  4406. #endif //EXPERIMENTAL_I2CBUS
  4407. /**
  4408. * M200: Set filament diameter and set E axis units to cubic units
  4409. *
  4410. * T<extruder> - Optional extruder number. Current extruder if omitted.
  4411. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  4412. */
  4413. inline void gcode_M200() {
  4414. if (get_target_extruder_from_command(200)) return;
  4415. if (code_seen('D')) {
  4416. // setting any extruder filament size disables volumetric on the assumption that
  4417. // slicers either generate in extruder values as cubic mm or as as filament feeds
  4418. // for all extruders
  4419. volumetric_enabled = (code_value_linear_units() != 0.0);
  4420. if (volumetric_enabled) {
  4421. filament_size[target_extruder] = code_value_linear_units();
  4422. // make sure all extruders have some sane value for the filament size
  4423. for (int i = 0; i < EXTRUDERS; i++)
  4424. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  4425. }
  4426. }
  4427. else {
  4428. //reserved for setting filament diameter via UFID or filament measuring device
  4429. return;
  4430. }
  4431. calculate_volumetric_multipliers();
  4432. }
  4433. /**
  4434. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  4435. */
  4436. inline void gcode_M201() {
  4437. for (int8_t i = 0; i < NUM_AXIS; i++) {
  4438. if (code_seen(axis_codes[i])) {
  4439. planner.max_acceleration_mm_per_s2[i] = code_value_axis_units(i);
  4440. }
  4441. }
  4442. // 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)
  4443. planner.reset_acceleration_rates();
  4444. }
  4445. #if 0 // Not used for Sprinter/grbl gen6
  4446. inline void gcode_M202() {
  4447. for (int8_t i = 0; i < NUM_AXIS; i++) {
  4448. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value_axis_units(i) * planner.axis_steps_per_mm[i];
  4449. }
  4450. }
  4451. #endif
  4452. /**
  4453. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  4454. */
  4455. inline void gcode_M203() {
  4456. for (int8_t i = 0; i < NUM_AXIS; i++)
  4457. if (code_seen(axis_codes[i]))
  4458. planner.max_feedrate[i] = code_value_axis_units(i);
  4459. }
  4460. /**
  4461. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  4462. *
  4463. * P = Printing moves
  4464. * R = Retract only (no X, Y, Z) moves
  4465. * T = Travel (non printing) moves
  4466. *
  4467. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  4468. */
  4469. inline void gcode_M204() {
  4470. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  4471. planner.travel_acceleration = planner.acceleration = code_value_linear_units();
  4472. SERIAL_ECHOPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  4473. SERIAL_EOL;
  4474. }
  4475. if (code_seen('P')) {
  4476. planner.acceleration = code_value_linear_units();
  4477. SERIAL_ECHOPAIR("Setting Print Acceleration: ", planner.acceleration);
  4478. SERIAL_EOL;
  4479. }
  4480. if (code_seen('R')) {
  4481. planner.retract_acceleration = code_value_linear_units();
  4482. SERIAL_ECHOPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  4483. SERIAL_EOL;
  4484. }
  4485. if (code_seen('T')) {
  4486. planner.travel_acceleration = code_value_linear_units();
  4487. SERIAL_ECHOPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  4488. SERIAL_EOL;
  4489. }
  4490. }
  4491. /**
  4492. * M205: Set Advanced Settings
  4493. *
  4494. * S = Min Feed Rate (units/s)
  4495. * T = Min Travel Feed Rate (units/s)
  4496. * B = Min Segment Time (µs)
  4497. * X = Max XY Jerk (units/sec^2)
  4498. * Z = Max Z Jerk (units/sec^2)
  4499. * E = Max E Jerk (units/sec^2)
  4500. */
  4501. inline void gcode_M205() {
  4502. if (code_seen('S')) planner.min_feedrate = code_value_linear_units();
  4503. if (code_seen('T')) planner.min_travel_feedrate = code_value_linear_units();
  4504. if (code_seen('B')) planner.min_segment_time = code_value_millis();
  4505. if (code_seen('X')) planner.max_xy_jerk = code_value_linear_units();
  4506. if (code_seen('Z')) planner.max_z_jerk = code_value_axis_units(Z_AXIS);
  4507. if (code_seen('E')) planner.max_e_jerk = code_value_axis_units(E_AXIS);
  4508. }
  4509. /**
  4510. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  4511. */
  4512. inline void gcode_M206() {
  4513. for (int8_t i = X_AXIS; i <= Z_AXIS; i++)
  4514. if (code_seen(axis_codes[i]))
  4515. set_home_offset((AxisEnum)i, code_value_axis_units(i));
  4516. #if ENABLED(SCARA)
  4517. if (code_seen('T')) set_home_offset(X_AXIS, code_value_axis_units(X_AXIS)); // Theta
  4518. if (code_seen('P')) set_home_offset(Y_AXIS, code_value_axis_units(Y_AXIS)); // Psi
  4519. #endif
  4520. SYNC_PLAN_POSITION_KINEMATIC();
  4521. report_current_position();
  4522. }
  4523. #if ENABLED(DELTA)
  4524. /**
  4525. * M665: Set delta configurations
  4526. *
  4527. * L = diagonal rod
  4528. * R = delta radius
  4529. * S = segments per second
  4530. * A = Alpha (Tower 1) diagonal rod trim
  4531. * B = Beta (Tower 2) diagonal rod trim
  4532. * C = Gamma (Tower 3) diagonal rod trim
  4533. */
  4534. inline void gcode_M665() {
  4535. if (code_seen('L')) delta_diagonal_rod = code_value_linear_units();
  4536. if (code_seen('R')) delta_radius = code_value_linear_units();
  4537. if (code_seen('S')) delta_segments_per_second = code_value_float();
  4538. if (code_seen('A')) delta_diagonal_rod_trim_tower_1 = code_value_linear_units();
  4539. if (code_seen('B')) delta_diagonal_rod_trim_tower_2 = code_value_linear_units();
  4540. if (code_seen('C')) delta_diagonal_rod_trim_tower_3 = code_value_linear_units();
  4541. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4542. }
  4543. /**
  4544. * M666: Set delta endstop adjustment
  4545. */
  4546. inline void gcode_M666() {
  4547. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4548. if (DEBUGGING(LEVELING)) {
  4549. SERIAL_ECHOLNPGM(">>> gcode_M666");
  4550. }
  4551. #endif
  4552. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  4553. if (code_seen(axis_codes[i])) {
  4554. endstop_adj[i] = code_value_axis_units(i);
  4555. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4556. if (DEBUGGING(LEVELING)) {
  4557. SERIAL_ECHOPGM("endstop_adj[");
  4558. SERIAL_ECHO(axis_codes[i]);
  4559. SERIAL_ECHOPAIR("] = ", endstop_adj[i]);
  4560. SERIAL_EOL;
  4561. }
  4562. #endif
  4563. }
  4564. }
  4565. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4566. if (DEBUGGING(LEVELING)) {
  4567. SERIAL_ECHOLNPGM("<<< gcode_M666");
  4568. }
  4569. #endif
  4570. }
  4571. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  4572. /**
  4573. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  4574. */
  4575. inline void gcode_M666() {
  4576. if (code_seen('Z')) z_endstop_adj = code_value_axis_units(Z_AXIS);
  4577. SERIAL_ECHOPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  4578. SERIAL_EOL;
  4579. }
  4580. #endif // !DELTA && Z_DUAL_ENDSTOPS
  4581. #if ENABLED(FWRETRACT)
  4582. /**
  4583. * M207: Set firmware retraction values
  4584. *
  4585. * S[+units] retract_length
  4586. * W[+units] retract_length_swap (multi-extruder)
  4587. * F[units/min] retract_feedrate_mm_s
  4588. * Z[units] retract_zlift
  4589. */
  4590. inline void gcode_M207() {
  4591. if (code_seen('S')) retract_length = code_value_axis_units(E_AXIS);
  4592. if (code_seen('F')) retract_feedrate_mm_s = code_value_axis_units(E_AXIS) / 60;
  4593. if (code_seen('Z')) retract_zlift = code_value_axis_units(Z_AXIS);
  4594. #if EXTRUDERS > 1
  4595. if (code_seen('W')) retract_length_swap = code_value_axis_units(E_AXIS);
  4596. #endif
  4597. }
  4598. /**
  4599. * M208: Set firmware un-retraction values
  4600. *
  4601. * S[+units] retract_recover_length (in addition to M207 S*)
  4602. * W[+units] retract_recover_length_swap (multi-extruder)
  4603. * F[units/min] retract_recover_feedrate
  4604. */
  4605. inline void gcode_M208() {
  4606. if (code_seen('S')) retract_recover_length = code_value_axis_units(E_AXIS);
  4607. if (code_seen('F')) retract_recover_feedrate = code_value_axis_units(E_AXIS) / 60;
  4608. #if EXTRUDERS > 1
  4609. if (code_seen('W')) retract_recover_length_swap = code_value_axis_units(E_AXIS);
  4610. #endif
  4611. }
  4612. /**
  4613. * M209: Enable automatic retract (M209 S1)
  4614. * detect if the slicer did not support G10/11: every normal extrude-only move will be classified as retract depending on the direction.
  4615. */
  4616. inline void gcode_M209() {
  4617. if (code_seen('S')) {
  4618. int t = code_value_int();
  4619. switch (t) {
  4620. case 0:
  4621. autoretract_enabled = false;
  4622. break;
  4623. case 1:
  4624. autoretract_enabled = true;
  4625. break;
  4626. default:
  4627. unknown_command_error();
  4628. return;
  4629. }
  4630. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  4631. }
  4632. }
  4633. #endif // FWRETRACT
  4634. #if HOTENDS > 1
  4635. /**
  4636. * M218 - set hotend offset (in linear units)
  4637. *
  4638. * T<tool>
  4639. * X<xoffset>
  4640. * Y<yoffset>
  4641. * Z<zoffset> - Available with DUAL_X_CARRIAGE
  4642. */
  4643. inline void gcode_M218() {
  4644. if (get_target_extruder_from_command(218)) return;
  4645. if (code_seen('X')) hotend_offset[X_AXIS][target_extruder] = code_value_axis_units(X_AXIS);
  4646. if (code_seen('Y')) hotend_offset[Y_AXIS][target_extruder] = code_value_axis_units(Y_AXIS);
  4647. #if ENABLED(DUAL_X_CARRIAGE)
  4648. if (code_seen('Z')) hotend_offset[Z_AXIS][target_extruder] = code_value_axis_units(Z_AXIS);
  4649. #endif
  4650. SERIAL_ECHO_START;
  4651. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  4652. HOTEND_LOOP() {
  4653. SERIAL_CHAR(' ');
  4654. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  4655. SERIAL_CHAR(',');
  4656. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  4657. #if ENABLED(DUAL_X_CARRIAGE)
  4658. SERIAL_CHAR(',');
  4659. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  4660. #endif
  4661. }
  4662. SERIAL_EOL;
  4663. }
  4664. #endif // HOTENDS > 1
  4665. /**
  4666. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  4667. */
  4668. inline void gcode_M220() {
  4669. if (code_seen('S')) feedrate_multiplier = code_value_int();
  4670. }
  4671. /**
  4672. * M221: Set extrusion percentage (M221 T0 S95)
  4673. */
  4674. inline void gcode_M221() {
  4675. if (get_target_extruder_from_command(221)) return;
  4676. if (code_seen('S'))
  4677. extruder_multiplier[target_extruder] = code_value_int();
  4678. }
  4679. /**
  4680. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  4681. */
  4682. inline void gcode_M226() {
  4683. if (code_seen('P')) {
  4684. int pin_number = code_value_int();
  4685. int pin_state = code_seen('S') ? code_value_int() : -1; // required pin state - default is inverted
  4686. if (pin_state >= -1 && pin_state <= 1) {
  4687. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++) {
  4688. if (sensitive_pins[i] == pin_number) {
  4689. pin_number = -1;
  4690. break;
  4691. }
  4692. }
  4693. if (pin_number > -1) {
  4694. int target = LOW;
  4695. stepper.synchronize();
  4696. pinMode(pin_number, INPUT);
  4697. switch (pin_state) {
  4698. case 1:
  4699. target = HIGH;
  4700. break;
  4701. case 0:
  4702. target = LOW;
  4703. break;
  4704. case -1:
  4705. target = !digitalRead(pin_number);
  4706. break;
  4707. }
  4708. while (digitalRead(pin_number) != target) idle();
  4709. } // pin_number > -1
  4710. } // pin_state -1 0 1
  4711. } // code_seen('P')
  4712. }
  4713. #if HAS_SERVOS
  4714. /**
  4715. * M280: Get or set servo position. P<index> [S<angle>]
  4716. */
  4717. inline void gcode_M280() {
  4718. if (!code_seen('P')) return;
  4719. int servo_index = code_value_int();
  4720. if (servo_index >= 0 && servo_index < NUM_SERVOS) {
  4721. if (code_seen('S'))
  4722. MOVE_SERVO(servo_index, code_value_int());
  4723. else {
  4724. SERIAL_ECHO_START;
  4725. SERIAL_ECHOPGM(" Servo ");
  4726. SERIAL_ECHO(servo_index);
  4727. SERIAL_ECHOPGM(": ");
  4728. SERIAL_ECHOLN(servo[servo_index].read());
  4729. }
  4730. }
  4731. else {
  4732. SERIAL_ERROR_START;
  4733. SERIAL_ERROR("Servo ");
  4734. SERIAL_ERROR(servo_index);
  4735. SERIAL_ERRORLN(" out of range");
  4736. }
  4737. }
  4738. #endif // HAS_SERVOS
  4739. #if HAS_BUZZER
  4740. /**
  4741. * M300: Play beep sound S<frequency Hz> P<duration ms>
  4742. */
  4743. inline void gcode_M300() {
  4744. uint16_t const frequency = code_seen('S') ? code_value_ushort() : 260;
  4745. uint16_t duration = code_seen('P') ? code_value_ushort() : 1000;
  4746. // Limits the tone duration to 0-5 seconds.
  4747. NOMORE(duration, 5000);
  4748. buzzer.tone(duration, frequency);
  4749. }
  4750. #endif // HAS_BUZZER
  4751. #if ENABLED(PIDTEMP)
  4752. /**
  4753. * M301: Set PID parameters P I D (and optionally C, L)
  4754. *
  4755. * P[float] Kp term
  4756. * I[float] Ki term (unscaled)
  4757. * D[float] Kd term (unscaled)
  4758. *
  4759. * With PID_ADD_EXTRUSION_RATE:
  4760. *
  4761. * C[float] Kc term
  4762. * L[float] LPQ length
  4763. */
  4764. inline void gcode_M301() {
  4765. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  4766. // default behaviour (omitting E parameter) is to update for extruder 0 only
  4767. int e = code_seen('E') ? code_value_int() : 0; // extruder being updated
  4768. if (e < HOTENDS) { // catch bad input value
  4769. if (code_seen('P')) PID_PARAM(Kp, e) = code_value_float();
  4770. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value_float());
  4771. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value_float());
  4772. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4773. if (code_seen('C')) PID_PARAM(Kc, e) = code_value_float();
  4774. if (code_seen('L')) lpq_len = code_value_float();
  4775. NOMORE(lpq_len, LPQ_MAX_LEN);
  4776. #endif
  4777. thermalManager.updatePID();
  4778. SERIAL_ECHO_START;
  4779. #if ENABLED(PID_PARAMS_PER_HOTEND)
  4780. SERIAL_ECHOPGM(" e:"); // specify extruder in serial output
  4781. SERIAL_ECHO(e);
  4782. #endif // PID_PARAMS_PER_HOTEND
  4783. SERIAL_ECHOPGM(" p:");
  4784. SERIAL_ECHO(PID_PARAM(Kp, e));
  4785. SERIAL_ECHOPGM(" i:");
  4786. SERIAL_ECHO(unscalePID_i(PID_PARAM(Ki, e)));
  4787. SERIAL_ECHOPGM(" d:");
  4788. SERIAL_ECHO(unscalePID_d(PID_PARAM(Kd, e)));
  4789. #if ENABLED(PID_ADD_EXTRUSION_RATE)
  4790. SERIAL_ECHOPGM(" c:");
  4791. //Kc does not have scaling applied above, or in resetting defaults
  4792. SERIAL_ECHO(PID_PARAM(Kc, e));
  4793. #endif
  4794. SERIAL_EOL;
  4795. }
  4796. else {
  4797. SERIAL_ERROR_START;
  4798. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  4799. }
  4800. }
  4801. #endif // PIDTEMP
  4802. #if ENABLED(PIDTEMPBED)
  4803. inline void gcode_M304() {
  4804. if (code_seen('P')) thermalManager.bedKp = code_value_float();
  4805. if (code_seen('I')) thermalManager.bedKi = scalePID_i(code_value_float());
  4806. if (code_seen('D')) thermalManager.bedKd = scalePID_d(code_value_float());
  4807. thermalManager.updatePID();
  4808. SERIAL_ECHO_START;
  4809. SERIAL_ECHOPGM(" p:");
  4810. SERIAL_ECHO(thermalManager.bedKp);
  4811. SERIAL_ECHOPGM(" i:");
  4812. SERIAL_ECHO(unscalePID_i(thermalManager.bedKi));
  4813. SERIAL_ECHOPGM(" d:");
  4814. SERIAL_ECHOLN(unscalePID_d(thermalManager.bedKd));
  4815. }
  4816. #endif // PIDTEMPBED
  4817. #if defined(CHDK) || HAS_PHOTOGRAPH
  4818. /**
  4819. * M240: Trigger a camera by emulating a Canon RC-1
  4820. * See http://www.doc-diy.net/photo/rc-1_hacked/
  4821. */
  4822. inline void gcode_M240() {
  4823. #ifdef CHDK
  4824. OUT_WRITE(CHDK, HIGH);
  4825. chdkHigh = millis();
  4826. chdkActive = true;
  4827. #elif HAS_PHOTOGRAPH
  4828. const uint8_t NUM_PULSES = 16;
  4829. const float PULSE_LENGTH = 0.01524;
  4830. for (int i = 0; i < NUM_PULSES; i++) {
  4831. WRITE(PHOTOGRAPH_PIN, HIGH);
  4832. _delay_ms(PULSE_LENGTH);
  4833. WRITE(PHOTOGRAPH_PIN, LOW);
  4834. _delay_ms(PULSE_LENGTH);
  4835. }
  4836. delay(7.33);
  4837. for (int i = 0; i < NUM_PULSES; i++) {
  4838. WRITE(PHOTOGRAPH_PIN, HIGH);
  4839. _delay_ms(PULSE_LENGTH);
  4840. WRITE(PHOTOGRAPH_PIN, LOW);
  4841. _delay_ms(PULSE_LENGTH);
  4842. }
  4843. #endif // !CHDK && HAS_PHOTOGRAPH
  4844. }
  4845. #endif // CHDK || PHOTOGRAPH_PIN
  4846. #if HAS_LCD_CONTRAST
  4847. /**
  4848. * M250: Read and optionally set the LCD contrast
  4849. */
  4850. inline void gcode_M250() {
  4851. if (code_seen('C')) set_lcd_contrast(code_value_int());
  4852. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  4853. SERIAL_PROTOCOL(lcd_contrast);
  4854. SERIAL_EOL;
  4855. }
  4856. #endif // HAS_LCD_CONTRAST
  4857. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  4858. /**
  4859. * M302: Allow cold extrudes, or set the minimum extrude temperature
  4860. *
  4861. * S<temperature> sets the minimum extrude temperature
  4862. * P<bool> enables (1) or disables (0) cold extrusion
  4863. *
  4864. * Examples:
  4865. *
  4866. * M302 ; report current cold extrusion state
  4867. * M302 P0 ; enable cold extrusion checking
  4868. * M302 P1 ; disables cold extrusion checking
  4869. * M302 S0 ; always allow extrusion (disables checking)
  4870. * M302 S170 ; only allow extrusion above 170
  4871. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  4872. */
  4873. inline void gcode_M302() {
  4874. bool seen_S = code_seen('S');
  4875. if (seen_S) {
  4876. thermalManager.extrude_min_temp = code_value_temp_abs();
  4877. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  4878. }
  4879. if (code_seen('P'))
  4880. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || code_value_bool();
  4881. else if (!seen_S) {
  4882. // Report current state
  4883. SERIAL_ECHO_START;
  4884. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  4885. SERIAL_ECHOPAIR("abled (min temp ", int(thermalManager.extrude_min_temp + 0.5));
  4886. SERIAL_ECHOLNPGM("C)");
  4887. }
  4888. }
  4889. #endif // PREVENT_DANGEROUS_EXTRUDE
  4890. /**
  4891. * M303: PID relay autotune
  4892. *
  4893. * S<temperature> sets the target temperature. (default 150C)
  4894. * E<extruder> (-1 for the bed) (default 0)
  4895. * C<cycles>
  4896. * U<bool> with a non-zero value will apply the result to current settings
  4897. */
  4898. inline void gcode_M303() {
  4899. #if HAS_PID_HEATING
  4900. int e = code_seen('E') ? code_value_int() : 0;
  4901. int c = code_seen('C') ? code_value_int() : 5;
  4902. bool u = code_seen('U') && code_value_bool();
  4903. float temp = code_seen('S') ? code_value_temp_abs() : (e < 0 ? 70.0 : 150.0);
  4904. if (e >= 0 && e < HOTENDS)
  4905. target_extruder = e;
  4906. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  4907. thermalManager.PID_autotune(temp, e, c, u);
  4908. KEEPALIVE_STATE(IN_HANDLER);
  4909. #else
  4910. SERIAL_ERROR_START;
  4911. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  4912. #endif
  4913. }
  4914. #if ENABLED(SCARA)
  4915. bool SCARA_move_to_cal(uint8_t delta_x, uint8_t delta_y) {
  4916. //SoftEndsEnabled = false; // Ignore soft endstops during calibration
  4917. //SERIAL_ECHOLNPGM(" Soft endstops disabled");
  4918. if (IsRunning()) {
  4919. //gcode_get_destination(); // For X Y Z E F
  4920. delta[X_AXIS] = delta_x;
  4921. delta[Y_AXIS] = delta_y;
  4922. calculate_SCARA_forward_Transform(delta);
  4923. destination[X_AXIS] = delta[X_AXIS] / axis_scaling[X_AXIS];
  4924. destination[Y_AXIS] = delta[Y_AXIS] / axis_scaling[Y_AXIS];
  4925. prepare_move_to_destination();
  4926. //ok_to_send();
  4927. return true;
  4928. }
  4929. return false;
  4930. }
  4931. /**
  4932. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  4933. */
  4934. inline bool gcode_M360() {
  4935. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  4936. return SCARA_move_to_cal(0, 120);
  4937. }
  4938. /**
  4939. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  4940. */
  4941. inline bool gcode_M361() {
  4942. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  4943. return SCARA_move_to_cal(90, 130);
  4944. }
  4945. /**
  4946. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  4947. */
  4948. inline bool gcode_M362() {
  4949. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  4950. return SCARA_move_to_cal(60, 180);
  4951. }
  4952. /**
  4953. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  4954. */
  4955. inline bool gcode_M363() {
  4956. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  4957. return SCARA_move_to_cal(50, 90);
  4958. }
  4959. /**
  4960. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  4961. */
  4962. inline bool gcode_M364() {
  4963. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  4964. return SCARA_move_to_cal(45, 135);
  4965. }
  4966. /**
  4967. * M365: SCARA calibration: Scaling factor, X, Y, Z axis
  4968. */
  4969. inline void gcode_M365() {
  4970. for (int8_t i = X_AXIS; i <= Z_AXIS; i++)
  4971. if (code_seen(axis_codes[i]))
  4972. axis_scaling[i] = code_value_float();
  4973. }
  4974. #endif // SCARA
  4975. #if ENABLED(EXT_SOLENOID)
  4976. void enable_solenoid(uint8_t num) {
  4977. switch (num) {
  4978. case 0:
  4979. OUT_WRITE(SOL0_PIN, HIGH);
  4980. break;
  4981. #if HAS_SOLENOID_1
  4982. case 1:
  4983. OUT_WRITE(SOL1_PIN, HIGH);
  4984. break;
  4985. #endif
  4986. #if HAS_SOLENOID_2
  4987. case 2:
  4988. OUT_WRITE(SOL2_PIN, HIGH);
  4989. break;
  4990. #endif
  4991. #if HAS_SOLENOID_3
  4992. case 3:
  4993. OUT_WRITE(SOL3_PIN, HIGH);
  4994. break;
  4995. #endif
  4996. default:
  4997. SERIAL_ECHO_START;
  4998. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  4999. break;
  5000. }
  5001. }
  5002. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  5003. void disable_all_solenoids() {
  5004. OUT_WRITE(SOL0_PIN, LOW);
  5005. OUT_WRITE(SOL1_PIN, LOW);
  5006. OUT_WRITE(SOL2_PIN, LOW);
  5007. OUT_WRITE(SOL3_PIN, LOW);
  5008. }
  5009. /**
  5010. * M380: Enable solenoid on the active extruder
  5011. */
  5012. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  5013. /**
  5014. * M381: Disable all solenoids
  5015. */
  5016. inline void gcode_M381() { disable_all_solenoids(); }
  5017. #endif // EXT_SOLENOID
  5018. /**
  5019. * M400: Finish all moves
  5020. */
  5021. inline void gcode_M400() { stepper.synchronize(); }
  5022. #if HAS_BED_PROBE
  5023. /**
  5024. * M401: Engage Z Servo endstop if available
  5025. */
  5026. inline void gcode_M401() { DEPLOY_PROBE(); }
  5027. /**
  5028. * M402: Retract Z Servo endstop if enabled
  5029. */
  5030. inline void gcode_M402() { STOW_PROBE(); }
  5031. #endif // HAS_BED_PROBE
  5032. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  5033. /**
  5034. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  5035. */
  5036. inline void gcode_M404() {
  5037. if (code_seen('W')) {
  5038. filament_width_nominal = code_value_linear_units();
  5039. }
  5040. else {
  5041. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  5042. SERIAL_PROTOCOLLN(filament_width_nominal);
  5043. }
  5044. }
  5045. /**
  5046. * M405: Turn on filament sensor for control
  5047. */
  5048. inline void gcode_M405() {
  5049. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  5050. // everything else, it uses code_value_int() instead of code_value_linear_units().
  5051. if (code_seen('D')) meas_delay_cm = code_value_int();
  5052. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  5053. if (filwidth_delay_index2 == -1) { // Initialize the ring buffer if not done since startup
  5054. int temp_ratio = thermalManager.widthFil_to_size_ratio();
  5055. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  5056. measurement_delay[i] = temp_ratio - 100; // Subtract 100 to scale within a signed byte
  5057. filwidth_delay_index1 = filwidth_delay_index2 = 0;
  5058. }
  5059. filament_sensor = true;
  5060. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5061. //SERIAL_PROTOCOL(filament_width_meas);
  5062. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  5063. //SERIAL_PROTOCOL(extruder_multiplier[active_extruder]);
  5064. }
  5065. /**
  5066. * M406: Turn off filament sensor for control
  5067. */
  5068. inline void gcode_M406() { filament_sensor = false; }
  5069. /**
  5070. * M407: Get measured filament diameter on serial output
  5071. */
  5072. inline void gcode_M407() {
  5073. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5074. SERIAL_PROTOCOLLN(filament_width_meas);
  5075. }
  5076. #endif // FILAMENT_WIDTH_SENSOR
  5077. void quickstop_stepper() {
  5078. stepper.quick_stop();
  5079. #if DISABLED(DELTA) && DISABLED(SCARA)
  5080. stepper.synchronize();
  5081. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5082. vector_3 pos = planner.adjusted_position(); // values directly from steppers...
  5083. current_position[X_AXIS] = pos.x;
  5084. current_position[Y_AXIS] = pos.y;
  5085. current_position[Z_AXIS] = pos.z;
  5086. #else
  5087. current_position[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  5088. current_position[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  5089. current_position[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  5090. #endif
  5091. sync_plan_position(); // ...re-apply to planner position
  5092. #endif
  5093. }
  5094. #if ENABLED(MESH_BED_LEVELING)
  5095. /**
  5096. * M420: Enable/Disable Mesh Bed Leveling
  5097. */
  5098. inline void gcode_M420() { if (code_seen('S') && code_has_value()) mbl.set_has_mesh(code_value_bool()); }
  5099. /**
  5100. * M421: Set a single Mesh Bed Leveling Z coordinate
  5101. * Use either 'M421 X<linear> Y<linear> Z<linear>' or 'M421 I<xindex> J<yindex> Z<linear>'
  5102. */
  5103. inline void gcode_M421() {
  5104. int8_t px = 0, py = 0;
  5105. float z = 0;
  5106. bool hasX, hasY, hasZ, hasI, hasJ;
  5107. if ((hasX = code_seen('X'))) px = mbl.probe_index_x(code_value_axis_units(X_AXIS));
  5108. if ((hasY = code_seen('Y'))) py = mbl.probe_index_y(code_value_axis_units(Y_AXIS));
  5109. if ((hasI = code_seen('I'))) px = code_value_axis_units(X_AXIS);
  5110. if ((hasJ = code_seen('J'))) py = code_value_axis_units(Y_AXIS);
  5111. if ((hasZ = code_seen('Z'))) z = code_value_axis_units(Z_AXIS);
  5112. if (hasX && hasY && hasZ) {
  5113. if (px >= 0 && py >= 0)
  5114. mbl.set_z(px, py, z);
  5115. else {
  5116. SERIAL_ERROR_START;
  5117. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5118. }
  5119. }
  5120. else if (hasI && hasJ && hasZ) {
  5121. if (px >= 0 && px < MESH_NUM_X_POINTS && py >= 0 && py < MESH_NUM_Y_POINTS)
  5122. mbl.set_z(px, py, z);
  5123. else {
  5124. SERIAL_ERROR_START;
  5125. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5126. }
  5127. }
  5128. else {
  5129. SERIAL_ERROR_START;
  5130. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  5131. }
  5132. }
  5133. #endif
  5134. /**
  5135. * M428: Set home_offset based on the distance between the
  5136. * current_position and the nearest "reference point."
  5137. * If an axis is past center its endstop position
  5138. * is the reference-point. Otherwise it uses 0. This allows
  5139. * the Z offset to be set near the bed when using a max endstop.
  5140. *
  5141. * M428 can't be used more than 2cm away from 0 or an endstop.
  5142. *
  5143. * Use M206 to set these values directly.
  5144. */
  5145. inline void gcode_M428() {
  5146. bool err = false;
  5147. for (int8_t i = X_AXIS; i <= Z_AXIS; i++) {
  5148. if (axis_homed[i]) {
  5149. float base = (current_position[i] > (sw_endstop_min[i] + sw_endstop_max[i]) / 2) ? base_home_pos(i) : 0,
  5150. diff = current_position[i] - base;
  5151. if (diff > -20 && diff < 20) {
  5152. set_home_offset((AxisEnum)i, home_offset[i] - diff);
  5153. }
  5154. else {
  5155. SERIAL_ERROR_START;
  5156. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  5157. LCD_ALERTMESSAGEPGM("Err: Too far!");
  5158. #if HAS_BUZZER
  5159. buzzer.tone(200, 40);
  5160. #endif
  5161. err = true;
  5162. break;
  5163. }
  5164. }
  5165. }
  5166. if (!err) {
  5167. SYNC_PLAN_POSITION_KINEMATIC();
  5168. report_current_position();
  5169. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  5170. #if HAS_BUZZER
  5171. buzzer.tone(200, 659);
  5172. buzzer.tone(200, 698);
  5173. #endif
  5174. }
  5175. }
  5176. /**
  5177. * M500: Store settings in EEPROM
  5178. */
  5179. inline void gcode_M500() {
  5180. Config_StoreSettings();
  5181. }
  5182. /**
  5183. * M501: Read settings from EEPROM
  5184. */
  5185. inline void gcode_M501() {
  5186. Config_RetrieveSettings();
  5187. }
  5188. /**
  5189. * M502: Revert to default settings
  5190. */
  5191. inline void gcode_M502() {
  5192. Config_ResetDefault();
  5193. }
  5194. /**
  5195. * M503: print settings currently in memory
  5196. */
  5197. inline void gcode_M503() {
  5198. Config_PrintSettings(code_seen('S') && !code_value_bool());
  5199. }
  5200. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  5201. /**
  5202. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  5203. */
  5204. inline void gcode_M540() {
  5205. if (code_seen('S')) stepper.abort_on_endstop_hit = code_value_bool();
  5206. }
  5207. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  5208. #if HAS_BED_PROBE
  5209. inline void gcode_M851() {
  5210. SERIAL_ECHO_START;
  5211. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  5212. SERIAL_CHAR(' ');
  5213. if (code_seen('Z')) {
  5214. float value = code_value_axis_units(Z_AXIS);
  5215. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  5216. zprobe_zoffset = value;
  5217. SERIAL_ECHO(zprobe_zoffset);
  5218. }
  5219. else {
  5220. SERIAL_ECHOPGM(MSG_Z_MIN);
  5221. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MIN);
  5222. SERIAL_CHAR(' ');
  5223. SERIAL_ECHOPGM(MSG_Z_MAX);
  5224. SERIAL_ECHO(Z_PROBE_OFFSET_RANGE_MAX);
  5225. }
  5226. }
  5227. else {
  5228. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  5229. }
  5230. SERIAL_EOL;
  5231. }
  5232. #endif // HAS_BED_PROBE
  5233. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  5234. /**
  5235. * M600: Pause for filament change
  5236. *
  5237. * E[distance] - Retract the filament this far (negative value)
  5238. * Z[distance] - Move the Z axis by this distance
  5239. * X[position] - Move to this X position, with Y
  5240. * Y[position] - Move to this Y position, with X
  5241. * L[distance] - Retract distance for removal (manual reload)
  5242. *
  5243. * Default values are used for omitted arguments.
  5244. *
  5245. */
  5246. inline void gcode_M600() {
  5247. if (thermalManager.tooColdToExtrude(active_extruder)) {
  5248. SERIAL_ERROR_START;
  5249. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  5250. return;
  5251. }
  5252. // Show initial message and wait for synchronize steppers
  5253. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INIT);
  5254. stepper.synchronize();
  5255. float lastpos[NUM_AXIS];
  5256. // Save current position of all axes
  5257. for (uint8_t i = 0; i < NUM_AXIS; i++)
  5258. lastpos[i] = destination[i] = current_position[i];
  5259. // Define runplan for move axes
  5260. #if ENABLED(DELTA)
  5261. #define RUNPLAN(RATE) calculate_delta(destination); \
  5262. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], RATE, active_extruder);
  5263. #else
  5264. #define RUNPLAN(RATE) line_to_destination(RATE * 60);
  5265. #endif
  5266. KEEPALIVE_STATE(IN_HANDLER);
  5267. // Initial retract before move to filament change position
  5268. if (code_seen('E')) destination[E_AXIS] += code_value_axis_units(E_AXIS);
  5269. #if defined(FILAMENT_CHANGE_RETRACT_LENGTH) && FILAMENT_CHANGE_RETRACT_LENGTH > 0
  5270. else destination[E_AXIS] -= FILAMENT_CHANGE_RETRACT_LENGTH;
  5271. #endif
  5272. RUNPLAN(FILAMENT_CHANGE_RETRACT_FEEDRATE);
  5273. // Lift Z axis
  5274. float z_lift = code_seen('Z') ? code_value_axis_units(Z_AXIS) :
  5275. #if defined(FILAMENT_CHANGE_Z_ADD) && FILAMENT_CHANGE_Z_ADD > 0
  5276. FILAMENT_CHANGE_Z_ADD
  5277. #else
  5278. 0
  5279. #endif
  5280. ;
  5281. if (z_lift > 0) {
  5282. destination[Z_AXIS] += z_lift;
  5283. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  5284. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  5285. }
  5286. // Move XY axes to filament exchange position
  5287. if (code_seen('X')) destination[X_AXIS] = code_value_axis_units(X_AXIS);
  5288. #ifdef FILAMENT_CHANGE_X_POS
  5289. else destination[X_AXIS] = FILAMENT_CHANGE_X_POS;
  5290. #endif
  5291. if (code_seen('Y')) destination[Y_AXIS] = code_value_axis_units(Y_AXIS);
  5292. #ifdef FILAMENT_CHANGE_Y_POS
  5293. else destination[Y_AXIS] = FILAMENT_CHANGE_Y_POS;
  5294. #endif
  5295. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  5296. stepper.synchronize();
  5297. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_UNLOAD);
  5298. // Unload filament
  5299. if (code_seen('L')) destination[E_AXIS] += code_value_axis_units(E_AXIS);
  5300. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  5301. else destination[E_AXIS] -= FILAMENT_CHANGE_UNLOAD_LENGTH;
  5302. #endif
  5303. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  5304. // Synchronize steppers and then disable extruders steppers for manual filament changing
  5305. stepper.synchronize();
  5306. disable_e0();
  5307. disable_e1();
  5308. disable_e2();
  5309. disable_e3();
  5310. delay(100);
  5311. #if HAS_BUZZER
  5312. millis_t next_tick = 0;
  5313. #endif
  5314. // Wait for filament insert by user and press button
  5315. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INSERT);
  5316. while (!lcd_clicked()) {
  5317. #if HAS_BUZZER
  5318. millis_t ms = millis();
  5319. if (ms >= next_tick) {
  5320. buzzer.tone(300, 2000);
  5321. next_tick = ms + 2500; // Beep every 2.5s while waiting
  5322. }
  5323. #endif
  5324. idle(true);
  5325. }
  5326. delay(100);
  5327. while (lcd_clicked()) idle(true);
  5328. delay(100);
  5329. // Show load message
  5330. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_LOAD);
  5331. // Load filament
  5332. if (code_seen('L')) destination[E_AXIS] -= code_value_axis_units(E_AXIS);
  5333. #if defined(FILAMENT_CHANGE_LOAD_LENGTH) && FILAMENT_CHANGE_LOAD_LENGTH > 0
  5334. else destination[E_AXIS] += FILAMENT_CHANGE_LOAD_LENGTH;
  5335. #endif
  5336. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5337. stepper.synchronize();
  5338. #if defined(FILAMENT_CHANGE_EXTRUDE_LENGTH) && FILAMENT_CHANGE_EXTRUDE_LENGTH > 0
  5339. do {
  5340. // Extrude filament to get into hotend
  5341. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_EXTRUDE);
  5342. destination[E_AXIS] += FILAMENT_CHANGE_EXTRUDE_LENGTH;
  5343. RUNPLAN(FILAMENT_CHANGE_EXTRUDE_FEEDRATE);
  5344. stepper.synchronize();
  5345. // Ask user if more filament should be extruded
  5346. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5347. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_OPTION);
  5348. while (filament_change_menu_response == FILAMENT_CHANGE_RESPONSE_WAIT_FOR) idle(true);
  5349. KEEPALIVE_STATE(IN_HANDLER);
  5350. } while (filament_change_menu_response != FILAMENT_CHANGE_RESPONSE_RESUME_PRINT);
  5351. #endif
  5352. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_RESUME);
  5353. KEEPALIVE_STATE(IN_HANDLER);
  5354. // Set extruder to saved position
  5355. current_position[E_AXIS] = lastpos[E_AXIS];
  5356. destination[E_AXIS] = lastpos[E_AXIS];
  5357. planner.set_e_position_mm(current_position[E_AXIS]);
  5358. #if ENABLED(DELTA)
  5359. // Move XYZ to starting position, then E
  5360. calculate_delta(lastpos);
  5361. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], destination[E_AXIS], FILAMENT_CHANGE_XY_FEEDRATE, active_extruder);
  5362. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], lastpos[E_AXIS], FILAMENT_CHANGE_XY_FEEDRATE, active_extruder);
  5363. #else
  5364. // Move XY to starting position, then Z, then E
  5365. destination[X_AXIS] = lastpos[X_AXIS];
  5366. destination[Y_AXIS] = lastpos[Y_AXIS];
  5367. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  5368. destination[Z_AXIS] = lastpos[Z_AXIS];
  5369. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  5370. #endif
  5371. stepper.synchronize();
  5372. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5373. filament_ran_out = false;
  5374. #endif
  5375. // Show status screen
  5376. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_STATUS);
  5377. }
  5378. #endif // FILAMENT_CHANGE_FEATURE
  5379. #if ENABLED(DUAL_X_CARRIAGE)
  5380. /**
  5381. * M605: Set dual x-carriage movement mode
  5382. *
  5383. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  5384. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  5385. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  5386. * units x-offset and an optional differential hotend temperature of
  5387. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  5388. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  5389. *
  5390. * Note: the X axis should be homed after changing dual x-carriage mode.
  5391. */
  5392. inline void gcode_M605() {
  5393. stepper.synchronize();
  5394. if (code_seen('S')) dual_x_carriage_mode = code_value_byte();
  5395. switch (dual_x_carriage_mode) {
  5396. case DXC_DUPLICATION_MODE:
  5397. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value_axis_units(X_AXIS), X2_MIN_POS - x_home_pos(0));
  5398. if (code_seen('R')) duplicate_extruder_temp_offset = code_value_temp_diff();
  5399. SERIAL_ECHO_START;
  5400. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  5401. SERIAL_CHAR(' ');
  5402. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  5403. SERIAL_CHAR(',');
  5404. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  5405. SERIAL_CHAR(' ');
  5406. SERIAL_ECHO(duplicate_extruder_x_offset);
  5407. SERIAL_CHAR(',');
  5408. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  5409. break;
  5410. case DXC_FULL_CONTROL_MODE:
  5411. case DXC_AUTO_PARK_MODE:
  5412. break;
  5413. default:
  5414. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  5415. break;
  5416. }
  5417. active_extruder_parked = false;
  5418. extruder_duplication_enabled = false;
  5419. delayed_move_time = 0;
  5420. }
  5421. #endif // DUAL_X_CARRIAGE
  5422. #if ENABLED(LIN_ADVANCE)
  5423. /**
  5424. * M905: Set advance factor
  5425. */
  5426. inline void gcode_M905() {
  5427. stepper.synchronize();
  5428. stepper.advance_M905(code_seen('K') ? code_value_float() : -1.0);
  5429. }
  5430. #endif
  5431. /**
  5432. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  5433. */
  5434. inline void gcode_M907() {
  5435. #if HAS_DIGIPOTSS
  5436. for (int i = 0; i < NUM_AXIS; i++)
  5437. if (code_seen(axis_codes[i])) stepper.digipot_current(i, code_value_int());
  5438. if (code_seen('B')) stepper.digipot_current(4, code_value_int());
  5439. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.digipot_current(i, code_value_int());
  5440. #endif
  5441. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  5442. if (code_seen('X')) stepper.digipot_current(0, code_value_int());
  5443. #endif
  5444. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  5445. if (code_seen('Z')) stepper.digipot_current(1, code_value_int());
  5446. #endif
  5447. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  5448. if (code_seen('E')) stepper.digipot_current(2, code_value_int());
  5449. #endif
  5450. #if ENABLED(DIGIPOT_I2C)
  5451. // this one uses actual amps in floating point
  5452. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value_float());
  5453. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  5454. 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());
  5455. #endif
  5456. #if ENABLED(DAC_STEPPER_CURRENT)
  5457. if (code_seen('S')) {
  5458. float dac_percent = code_value_float();
  5459. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  5460. }
  5461. for (uint8_t i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) dac_current_percent(i, code_value_float());
  5462. #endif
  5463. }
  5464. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  5465. /**
  5466. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  5467. */
  5468. inline void gcode_M908() {
  5469. #if HAS_DIGIPOTSS
  5470. stepper.digitalPotWrite(
  5471. code_seen('P') ? code_value_int() : 0,
  5472. code_seen('S') ? code_value_int() : 0
  5473. );
  5474. #endif
  5475. #ifdef DAC_STEPPER_CURRENT
  5476. dac_current_raw(
  5477. code_seen('P') ? code_value_byte() : -1,
  5478. code_seen('S') ? code_value_ushort() : 0
  5479. );
  5480. #endif
  5481. }
  5482. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  5483. inline void gcode_M909() { dac_print_values(); }
  5484. inline void gcode_M910() { dac_commit_eeprom(); }
  5485. #endif
  5486. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  5487. #if HAS_MICROSTEPS
  5488. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  5489. inline void gcode_M350() {
  5490. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, code_value_byte());
  5491. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) stepper.microstep_mode(i, code_value_byte());
  5492. if (code_seen('B')) stepper.microstep_mode(4, code_value_byte());
  5493. stepper.microstep_readings();
  5494. }
  5495. /**
  5496. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  5497. * S# determines MS1 or MS2, X# sets the pin high/low.
  5498. */
  5499. inline void gcode_M351() {
  5500. if (code_seen('S')) switch (code_value_byte()) {
  5501. case 1:
  5502. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, code_value_byte(), -1);
  5503. if (code_seen('B')) stepper.microstep_ms(4, code_value_byte(), -1);
  5504. break;
  5505. case 2:
  5506. for (int i = 0; i < NUM_AXIS; i++) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, -1, code_value_byte());
  5507. if (code_seen('B')) stepper.microstep_ms(4, -1, code_value_byte());
  5508. break;
  5509. }
  5510. stepper.microstep_readings();
  5511. }
  5512. #endif // HAS_MICROSTEPS
  5513. /**
  5514. * M999: Restart after being stopped
  5515. *
  5516. * Default behaviour is to flush the serial buffer and request
  5517. * a resend to the host starting on the last N line received.
  5518. *
  5519. * Sending "M999 S1" will resume printing without flushing the
  5520. * existing command buffer.
  5521. *
  5522. */
  5523. inline void gcode_M999() {
  5524. Running = true;
  5525. lcd_reset_alert_level();
  5526. if (code_seen('S') && code_value_bool()) return;
  5527. // gcode_LastN = Stopped_gcode_LastN;
  5528. FlushSerialRequestResend();
  5529. }
  5530. /**
  5531. * T0-T3: Switch tool, usually switching extruders
  5532. *
  5533. * F[units/min] Set the movement feedrate
  5534. * S1 Don't move the tool in XY after change
  5535. */
  5536. inline void gcode_T(uint8_t tmp_extruder) {
  5537. if (tmp_extruder >= EXTRUDERS) {
  5538. SERIAL_ECHO_START;
  5539. SERIAL_CHAR('T');
  5540. SERIAL_PROTOCOL_F(tmp_extruder, DEC);
  5541. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  5542. return;
  5543. }
  5544. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5545. if (DEBUGGING(LEVELING)) {
  5546. SERIAL_ECHOLNPGM(">>> gcode_T");
  5547. DEBUG_POS("BEFORE", current_position);
  5548. }
  5549. #endif
  5550. #if HOTENDS > 1
  5551. float old_feedrate = feedrate;
  5552. if (code_seen('F')) {
  5553. float next_feedrate = code_value_axis_units(X_AXIS);
  5554. if (next_feedrate > 0.0) old_feedrate = feedrate = next_feedrate;
  5555. }
  5556. else
  5557. feedrate = XY_PROBE_FEEDRATE;
  5558. if (tmp_extruder != active_extruder) {
  5559. bool no_move = code_seen('S') && code_value_bool();
  5560. if (!no_move && axis_unhomed_error(true, true, true)) {
  5561. SERIAL_ECHOLNPGM("No move on toolchange");
  5562. no_move = true;
  5563. }
  5564. // Save current position to destination, for use later
  5565. set_destination_to_current();
  5566. #if ENABLED(DUAL_X_CARRIAGE)
  5567. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5568. if (DEBUGGING(LEVELING)) {
  5569. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  5570. switch (dual_x_carriage_mode) {
  5571. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  5572. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  5573. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  5574. }
  5575. }
  5576. #endif
  5577. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE && IsRunning()
  5578. && (delayed_move_time || current_position[X_AXIS] != x_home_pos(active_extruder))
  5579. ) {
  5580. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5581. if (DEBUGGING(LEVELING)) {
  5582. SERIAL_ECHOPAIR("Raise to ", current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT); SERIAL_EOL;
  5583. SERIAL_ECHOPAIR("MoveX to ", x_home_pos(active_extruder)); SERIAL_EOL;
  5584. SERIAL_ECHOPAIR("Lower to ", current_position[Z_AXIS]); SERIAL_EOL;
  5585. }
  5586. #endif
  5587. // Park old head: 1) raise 2) move to park position 3) lower
  5588. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  5589. current_position[E_AXIS], planner.max_feedrate[Z_AXIS], active_extruder);
  5590. planner.buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT,
  5591. current_position[E_AXIS], planner.max_feedrate[X_AXIS], active_extruder);
  5592. planner.buffer_line(x_home_pos(active_extruder), current_position[Y_AXIS], current_position[Z_AXIS],
  5593. current_position[E_AXIS], planner.max_feedrate[Z_AXIS], active_extruder);
  5594. stepper.synchronize();
  5595. }
  5596. // apply Y & Z extruder offset (x offset is already used in determining home pos)
  5597. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  5598. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  5599. active_extruder = tmp_extruder;
  5600. // This function resets the max/min values - the current position may be overwritten below.
  5601. set_axis_is_at_home(X_AXIS);
  5602. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5603. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  5604. #endif
  5605. switch (dual_x_carriage_mode) {
  5606. case DXC_FULL_CONTROL_MODE:
  5607. current_position[X_AXIS] = inactive_extruder_x_pos;
  5608. inactive_extruder_x_pos = destination[X_AXIS];
  5609. break;
  5610. case DXC_DUPLICATION_MODE:
  5611. active_extruder_parked = (active_extruder == 0); // this triggers the second extruder to move into the duplication position
  5612. if (active_extruder_parked)
  5613. current_position[X_AXIS] = inactive_extruder_x_pos;
  5614. else
  5615. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  5616. inactive_extruder_x_pos = destination[X_AXIS];
  5617. extruder_duplication_enabled = false;
  5618. break;
  5619. default:
  5620. // record raised toolhead position for use by unpark
  5621. memcpy(raised_parked_position, current_position, sizeof(raised_parked_position));
  5622. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  5623. active_extruder_parked = true;
  5624. delayed_move_time = 0;
  5625. break;
  5626. }
  5627. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5628. if (DEBUGGING(LEVELING)) {
  5629. SERIAL_ECHOPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  5630. SERIAL_EOL;
  5631. DEBUG_POS("New extruder (parked)", current_position);
  5632. }
  5633. #endif
  5634. // No extra case for AUTO_BED_LEVELING_FEATURE in DUAL_X_CARRIAGE. Does that mean they don't work together?
  5635. #else // !DUAL_X_CARRIAGE
  5636. /**
  5637. * Set current_position to the position of the new nozzle.
  5638. * Offsets are based on linear distance, so we need to get
  5639. * the resulting position in coordinate space.
  5640. *
  5641. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  5642. * - With mesh leveling, update Z for the new position
  5643. * - Otherwise, just use the raw linear distance
  5644. *
  5645. * Software endstops are altered here too. Consider a case where:
  5646. * E0 at X=0 ... E1 at X=10
  5647. * When we switch to E1 now X=10, but E1 can't move left.
  5648. * To express this we apply the change in XY to the software endstops.
  5649. * E1 can move farther right than E0, so the right limit is extended.
  5650. *
  5651. * Note that we don't adjust the Z software endstops. Why not?
  5652. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  5653. * because the bed is 1mm lower at the new position. As long as
  5654. * the first nozzle is out of the way, the carriage should be
  5655. * allowed to move 1mm lower. This technically "breaks" the
  5656. * Z software endstop. But this is technically correct (and
  5657. * there is no viable alternative).
  5658. */
  5659. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  5660. // Offset extruder, make sure to apply the bed level rotation matrix
  5661. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  5662. hotend_offset[Y_AXIS][tmp_extruder],
  5663. 0),
  5664. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  5665. hotend_offset[Y_AXIS][active_extruder],
  5666. 0),
  5667. offset_vec = tmp_offset_vec - act_offset_vec;
  5668. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5669. if (DEBUGGING(LEVELING)) {
  5670. tmp_offset_vec.debug("tmp_offset_vec");
  5671. act_offset_vec.debug("act_offset_vec");
  5672. offset_vec.debug("offset_vec (BEFORE)");
  5673. }
  5674. #endif
  5675. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  5676. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5677. if (DEBUGGING(LEVELING)) offset_vec.debug("offset_vec (AFTER)");
  5678. #endif
  5679. // Adjustments to the current position
  5680. float xydiff[2] = { offset_vec.x, offset_vec.y };
  5681. current_position[Z_AXIS] += offset_vec.z;
  5682. #else // !AUTO_BED_LEVELING_FEATURE
  5683. float xydiff[2] = {
  5684. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  5685. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  5686. };
  5687. #if ENABLED(MESH_BED_LEVELING)
  5688. if (mbl.active()) {
  5689. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5690. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  5691. #endif
  5692. float xpos = RAW_CURRENT_POSITION(X_AXIS),
  5693. ypos = RAW_CURRENT_POSITION(Y_AXIS);
  5694. current_position[Z_AXIS] += mbl.get_z(xpos + xydiff[X_AXIS], ypos + xydiff[Y_AXIS]) - mbl.get_z(xpos, ypos);
  5695. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5696. if (DEBUGGING(LEVELING)) {
  5697. SERIAL_ECHOPAIR(" after: ", current_position[Z_AXIS]);
  5698. SERIAL_EOL;
  5699. }
  5700. #endif
  5701. }
  5702. #endif // MESH_BED_LEVELING
  5703. #endif // !AUTO_BED_LEVELING_FEATURE
  5704. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5705. if (DEBUGGING(LEVELING)) {
  5706. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  5707. SERIAL_ECHOPAIR(", ", xydiff[X_AXIS]);
  5708. SERIAL_ECHOLNPGM(" }");
  5709. }
  5710. #endif
  5711. // The newly-selected extruder XY is actually at...
  5712. current_position[X_AXIS] += xydiff[X_AXIS];
  5713. current_position[Y_AXIS] += xydiff[Y_AXIS];
  5714. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  5715. position_shift[i] += xydiff[i];
  5716. update_software_endstops((AxisEnum)i);
  5717. }
  5718. // Set the new active extruder
  5719. active_extruder = tmp_extruder;
  5720. #endif // !DUAL_X_CARRIAGE
  5721. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5722. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  5723. #endif
  5724. // Tell the planner the new "current position"
  5725. SYNC_PLAN_POSITION_KINEMATIC();
  5726. // Move to the "old position" (move the extruder into place)
  5727. if (!no_move && IsRunning()) {
  5728. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5729. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  5730. #endif
  5731. prepare_move_to_destination();
  5732. }
  5733. } // (tmp_extruder != active_extruder)
  5734. stepper.synchronize();
  5735. #if ENABLED(EXT_SOLENOID)
  5736. disable_all_solenoids();
  5737. enable_solenoid_on_active_extruder();
  5738. #endif // EXT_SOLENOID
  5739. feedrate = old_feedrate;
  5740. #else // !HOTENDS > 1
  5741. // Set the new active extruder
  5742. active_extruder = tmp_extruder;
  5743. #endif
  5744. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5745. if (DEBUGGING(LEVELING)) {
  5746. DEBUG_POS("AFTER", current_position);
  5747. SERIAL_ECHOLNPGM("<<< gcode_T");
  5748. }
  5749. #endif
  5750. SERIAL_ECHO_START;
  5751. SERIAL_ECHOPGM(MSG_ACTIVE_EXTRUDER);
  5752. SERIAL_PROTOCOLLN((int)active_extruder);
  5753. }
  5754. /**
  5755. * Process a single command and dispatch it to its handler
  5756. * This is called from the main loop()
  5757. */
  5758. void process_next_command() {
  5759. current_command = command_queue[cmd_queue_index_r];
  5760. if (DEBUGGING(ECHO)) {
  5761. SERIAL_ECHO_START;
  5762. SERIAL_ECHOLN(current_command);
  5763. }
  5764. // Sanitize the current command:
  5765. // - Skip leading spaces
  5766. // - Bypass N[-0-9][0-9]*[ ]*
  5767. // - Overwrite * with nul to mark the end
  5768. while (*current_command == ' ') ++current_command;
  5769. if (*current_command == 'N' && NUMERIC_SIGNED(current_command[1])) {
  5770. current_command += 2; // skip N[-0-9]
  5771. while (NUMERIC(*current_command)) ++current_command; // skip [0-9]*
  5772. while (*current_command == ' ') ++current_command; // skip [ ]*
  5773. }
  5774. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  5775. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  5776. char *cmd_ptr = current_command;
  5777. // Get the command code, which must be G, M, or T
  5778. char command_code = *cmd_ptr++;
  5779. // Skip spaces to get the numeric part
  5780. while (*cmd_ptr == ' ') cmd_ptr++;
  5781. uint16_t codenum = 0; // define ahead of goto
  5782. // Bail early if there's no code
  5783. bool code_is_good = NUMERIC(*cmd_ptr);
  5784. if (!code_is_good) goto ExitUnknownCommand;
  5785. // Get and skip the code number
  5786. do {
  5787. codenum = (codenum * 10) + (*cmd_ptr - '0');
  5788. cmd_ptr++;
  5789. } while (NUMERIC(*cmd_ptr));
  5790. // Skip all spaces to get to the first argument, or nul
  5791. while (*cmd_ptr == ' ') cmd_ptr++;
  5792. // The command's arguments (if any) start here, for sure!
  5793. current_command_args = cmd_ptr;
  5794. KEEPALIVE_STATE(IN_HANDLER);
  5795. // Handle a known G, M, or T
  5796. switch (command_code) {
  5797. case 'G': switch (codenum) {
  5798. // G0, G1
  5799. case 0:
  5800. case 1:
  5801. gcode_G0_G1();
  5802. break;
  5803. // G2, G3
  5804. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  5805. case 2: // G2 - CW ARC
  5806. case 3: // G3 - CCW ARC
  5807. gcode_G2_G3(codenum == 2);
  5808. break;
  5809. #endif
  5810. // G4 Dwell
  5811. case 4:
  5812. gcode_G4();
  5813. break;
  5814. #if ENABLED(BEZIER_CURVE_SUPPORT)
  5815. // G5
  5816. case 5: // G5 - Cubic B_spline
  5817. gcode_G5();
  5818. break;
  5819. #endif // BEZIER_CURVE_SUPPORT
  5820. #if ENABLED(FWRETRACT)
  5821. case 10: // G10: retract
  5822. case 11: // G11: retract_recover
  5823. gcode_G10_G11(codenum == 10);
  5824. break;
  5825. #endif // FWRETRACT
  5826. #if ENABLED(NOZZLE_CLEAN_FEATURE) && HAS_BED_PROBE
  5827. case 12:
  5828. gcode_G12(); // G12: Clean Nozzle
  5829. break;
  5830. #endif // NOZZLE_CLEAN_FEATURE
  5831. #if ENABLED(INCH_MODE_SUPPORT)
  5832. case 20: //G20: Inch Mode
  5833. gcode_G20();
  5834. break;
  5835. case 21: //G21: MM Mode
  5836. gcode_G21();
  5837. break;
  5838. #endif // INCH_MODE_SUPPORT
  5839. case 28: // G28: Home all axes, one at a time
  5840. gcode_G28();
  5841. break;
  5842. #if ENABLED(AUTO_BED_LEVELING_FEATURE) || ENABLED(MESH_BED_LEVELING)
  5843. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points.
  5844. gcode_G29();
  5845. break;
  5846. #endif // AUTO_BED_LEVELING_FEATURE
  5847. #if HAS_BED_PROBE
  5848. case 30: // G30 Single Z probe
  5849. gcode_G30();
  5850. break;
  5851. #if ENABLED(Z_PROBE_SLED)
  5852. case 31: // G31: dock the sled
  5853. gcode_G31();
  5854. break;
  5855. case 32: // G32: undock the sled
  5856. gcode_G32();
  5857. break;
  5858. #endif // Z_PROBE_SLED
  5859. #endif // HAS_BED_PROBE
  5860. case 90: // G90
  5861. relative_mode = false;
  5862. break;
  5863. case 91: // G91
  5864. relative_mode = true;
  5865. break;
  5866. case 92: // G92
  5867. gcode_G92();
  5868. break;
  5869. }
  5870. break;
  5871. case 'M': switch (codenum) {
  5872. #if ENABLED(ULTIPANEL)
  5873. case 0: // M0 - Unconditional stop - Wait for user button press on LCD
  5874. case 1: // M1 - Conditional stop - Wait for user button press on LCD
  5875. gcode_M0_M1();
  5876. break;
  5877. #endif // ULTIPANEL
  5878. case 17:
  5879. gcode_M17();
  5880. break;
  5881. #if ENABLED(SDSUPPORT)
  5882. case 20: // M20 - list SD card
  5883. gcode_M20(); break;
  5884. case 21: // M21 - init SD card
  5885. gcode_M21(); break;
  5886. case 22: //M22 - release SD card
  5887. gcode_M22(); break;
  5888. case 23: //M23 - Select file
  5889. gcode_M23(); break;
  5890. case 24: //M24 - Start SD print
  5891. gcode_M24(); break;
  5892. case 25: //M25 - Pause SD print
  5893. gcode_M25(); break;
  5894. case 26: //M26 - Set SD index
  5895. gcode_M26(); break;
  5896. case 27: //M27 - Get SD status
  5897. gcode_M27(); break;
  5898. case 28: //M28 - Start SD write
  5899. gcode_M28(); break;
  5900. case 29: //M29 - Stop SD write
  5901. gcode_M29(); break;
  5902. case 30: //M30 <filename> Delete File
  5903. gcode_M30(); break;
  5904. case 32: //M32 - Select file and start SD print
  5905. gcode_M32(); break;
  5906. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5907. case 33: //M33 - Get the long full path to a file or folder
  5908. gcode_M33(); break;
  5909. #endif // LONG_FILENAME_HOST_SUPPORT
  5910. case 928: //M928 - Start SD write
  5911. gcode_M928(); break;
  5912. #endif //SDSUPPORT
  5913. case 31: //M31 take time since the start of the SD print or an M109 command
  5914. gcode_M31();
  5915. break;
  5916. case 42: //M42 -Change pin status via gcode
  5917. gcode_M42();
  5918. break;
  5919. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5920. case 48: // M48 Z probe repeatability
  5921. gcode_M48();
  5922. break;
  5923. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5924. case 75: // Start print timer
  5925. gcode_M75();
  5926. break;
  5927. case 76: // Pause print timer
  5928. gcode_M76();
  5929. break;
  5930. case 77: // Stop print timer
  5931. gcode_M77();
  5932. break;
  5933. #if ENABLED(PRINTCOUNTER)
  5934. case 78: // Show print statistics
  5935. gcode_M78();
  5936. break;
  5937. #endif
  5938. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  5939. case 100:
  5940. gcode_M100();
  5941. break;
  5942. #endif
  5943. case 104: // M104
  5944. gcode_M104();
  5945. break;
  5946. case 110: // M110: Set Current Line Number
  5947. gcode_M110();
  5948. break;
  5949. case 111: // M111: Set debug level
  5950. gcode_M111();
  5951. break;
  5952. #if DISABLED(EMERGENCY_PARSER)
  5953. case 108: // M108: Cancel Waiting
  5954. gcode_M108();
  5955. break;
  5956. case 112: // M112: Emergency Stop
  5957. gcode_M112();
  5958. break;
  5959. case 410: // M410 quickstop - Abort all the planned moves.
  5960. gcode_M410();
  5961. break;
  5962. #endif
  5963. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  5964. case 113: // M113: Set Host Keepalive interval
  5965. gcode_M113();
  5966. break;
  5967. #endif
  5968. case 140: // M140: Set bed temp
  5969. gcode_M140();
  5970. break;
  5971. case 105: // M105: Read current temperature
  5972. gcode_M105();
  5973. KEEPALIVE_STATE(NOT_BUSY);
  5974. return; // "ok" already printed
  5975. case 109: // M109: Wait for temperature
  5976. gcode_M109();
  5977. break;
  5978. #if HAS_TEMP_BED
  5979. case 190: // M190: Wait for bed heater to reach target
  5980. gcode_M190();
  5981. break;
  5982. #endif // HAS_TEMP_BED
  5983. #if FAN_COUNT > 0
  5984. case 106: // M106: Fan On
  5985. gcode_M106();
  5986. break;
  5987. case 107: // M107: Fan Off
  5988. gcode_M107();
  5989. break;
  5990. #endif // FAN_COUNT > 0
  5991. #if ENABLED(BARICUDA)
  5992. // PWM for HEATER_1_PIN
  5993. #if HAS_HEATER_1
  5994. case 126: // M126: valve open
  5995. gcode_M126();
  5996. break;
  5997. case 127: // M127: valve closed
  5998. gcode_M127();
  5999. break;
  6000. #endif // HAS_HEATER_1
  6001. // PWM for HEATER_2_PIN
  6002. #if HAS_HEATER_2
  6003. case 128: // M128: valve open
  6004. gcode_M128();
  6005. break;
  6006. case 129: // M129: valve closed
  6007. gcode_M129();
  6008. break;
  6009. #endif // HAS_HEATER_2
  6010. #endif // BARICUDA
  6011. #if HAS_POWER_SWITCH
  6012. case 80: // M80: Turn on Power Supply
  6013. gcode_M80();
  6014. break;
  6015. #endif // HAS_POWER_SWITCH
  6016. case 81: // M81: Turn off Power, including Power Supply, if possible
  6017. gcode_M81();
  6018. break;
  6019. case 82:
  6020. gcode_M82();
  6021. break;
  6022. case 83:
  6023. gcode_M83();
  6024. break;
  6025. case 18: // (for compatibility)
  6026. case 84: // M84
  6027. gcode_M18_M84();
  6028. break;
  6029. case 85: // M85
  6030. gcode_M85();
  6031. break;
  6032. case 92: // M92: Set the steps-per-unit for one or more axes
  6033. gcode_M92();
  6034. break;
  6035. case 115: // M115: Report capabilities
  6036. gcode_M115();
  6037. break;
  6038. case 117: // M117: Set LCD message text, if possible
  6039. gcode_M117();
  6040. break;
  6041. case 114: // M114: Report current position
  6042. gcode_M114();
  6043. break;
  6044. case 120: // M120: Enable endstops
  6045. gcode_M120();
  6046. break;
  6047. case 121: // M121: Disable endstops
  6048. gcode_M121();
  6049. break;
  6050. case 119: // M119: Report endstop states
  6051. gcode_M119();
  6052. break;
  6053. #if ENABLED(ULTIPANEL)
  6054. case 145: // M145: Set material heatup parameters
  6055. gcode_M145();
  6056. break;
  6057. #endif
  6058. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6059. case 149:
  6060. gcode_M149();
  6061. break;
  6062. #endif
  6063. #if ENABLED(BLINKM)
  6064. case 150: // M150
  6065. gcode_M150();
  6066. break;
  6067. #endif //BLINKM
  6068. #if ENABLED(EXPERIMENTAL_I2CBUS)
  6069. case 155:
  6070. gcode_M155();
  6071. break;
  6072. case 156:
  6073. gcode_M156();
  6074. break;
  6075. #endif //EXPERIMENTAL_I2CBUS
  6076. case 200: // M200 D<diameter> Set filament diameter and set E axis units to cubic. (Use S0 to revert to linear units.)
  6077. gcode_M200();
  6078. break;
  6079. case 201: // M201
  6080. gcode_M201();
  6081. break;
  6082. #if 0 // Not used for Sprinter/grbl gen6
  6083. case 202: // M202
  6084. gcode_M202();
  6085. break;
  6086. #endif
  6087. case 203: // M203 max feedrate units/sec
  6088. gcode_M203();
  6089. break;
  6090. case 204: // M204 acclereration S normal moves T filmanent only moves
  6091. gcode_M204();
  6092. break;
  6093. case 205: //M205 advanced settings: minimum travel speed S=while printing T=travel only, B=minimum segment time X= maximum xy jerk, Z=maximum Z jerk
  6094. gcode_M205();
  6095. break;
  6096. case 206: // M206 additional homing offset
  6097. gcode_M206();
  6098. break;
  6099. #if ENABLED(DELTA)
  6100. case 665: // M665 set delta configurations L<diagonal_rod> R<delta_radius> S<segments_per_sec>
  6101. gcode_M665();
  6102. break;
  6103. #endif
  6104. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  6105. case 666: // M666 set delta / dual endstop adjustment
  6106. gcode_M666();
  6107. break;
  6108. #endif
  6109. #if ENABLED(FWRETRACT)
  6110. case 207: // M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>
  6111. gcode_M207();
  6112. break;
  6113. case 208: // M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>
  6114. gcode_M208();
  6115. break;
  6116. case 209: // M209 - Turn Automatic Retract Detection on/off: S<bool> (For slicers that don't support G10/11). Every normal extrude-only move will be classified as retract depending on the direction.
  6117. gcode_M209();
  6118. break;
  6119. #endif // FWRETRACT
  6120. #if HOTENDS > 1
  6121. case 218: // M218 - Set a tool offset: T<index> X<offset> Y<offset>
  6122. gcode_M218();
  6123. break;
  6124. #endif
  6125. case 220: // M220 - Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  6126. gcode_M220();
  6127. break;
  6128. case 221: // M221 - Set Flow Percentage: S<percent>
  6129. gcode_M221();
  6130. break;
  6131. case 226: // M226 P<pin number> S<pin state>- Wait until the specified pin reaches the state required
  6132. gcode_M226();
  6133. break;
  6134. #if HAS_SERVOS
  6135. case 280: // M280 - set servo position absolute. P: servo index, S: angle or microseconds
  6136. gcode_M280();
  6137. break;
  6138. #endif // HAS_SERVOS
  6139. #if HAS_BUZZER
  6140. case 300: // M300 - Play beep tone
  6141. gcode_M300();
  6142. break;
  6143. #endif // HAS_BUZZER
  6144. #if ENABLED(PIDTEMP)
  6145. case 301: // M301
  6146. gcode_M301();
  6147. break;
  6148. #endif // PIDTEMP
  6149. #if ENABLED(PIDTEMPBED)
  6150. case 304: // M304
  6151. gcode_M304();
  6152. break;
  6153. #endif // PIDTEMPBED
  6154. #if defined(CHDK) || HAS_PHOTOGRAPH
  6155. case 240: // M240 Triggers a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  6156. gcode_M240();
  6157. break;
  6158. #endif // CHDK || PHOTOGRAPH_PIN
  6159. #if HAS_LCD_CONTRAST
  6160. case 250: // M250 Set LCD contrast value: C<value> (value 0..63)
  6161. gcode_M250();
  6162. break;
  6163. #endif // HAS_LCD_CONTRAST
  6164. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  6165. case 302: // allow cold extrudes, or set the minimum extrude temperature
  6166. gcode_M302();
  6167. break;
  6168. #endif // PREVENT_DANGEROUS_EXTRUDE
  6169. case 303: // M303 PID autotune
  6170. gcode_M303();
  6171. break;
  6172. #if ENABLED(SCARA)
  6173. case 360: // M360 SCARA Theta pos1
  6174. if (gcode_M360()) return;
  6175. break;
  6176. case 361: // M361 SCARA Theta pos2
  6177. if (gcode_M361()) return;
  6178. break;
  6179. case 362: // M362 SCARA Psi pos1
  6180. if (gcode_M362()) return;
  6181. break;
  6182. case 363: // M363 SCARA Psi pos2
  6183. if (gcode_M363()) return;
  6184. break;
  6185. case 364: // M364 SCARA Psi pos3 (90 deg to Theta)
  6186. if (gcode_M364()) return;
  6187. break;
  6188. case 365: // M365 Set SCARA scaling for X Y Z
  6189. gcode_M365();
  6190. break;
  6191. #endif // SCARA
  6192. case 400: // M400 finish all moves
  6193. gcode_M400();
  6194. break;
  6195. #if HAS_BED_PROBE
  6196. case 401:
  6197. gcode_M401();
  6198. break;
  6199. case 402:
  6200. gcode_M402();
  6201. break;
  6202. #endif // HAS_BED_PROBE
  6203. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  6204. case 404: //M404 Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  6205. gcode_M404();
  6206. break;
  6207. case 405: //M405 Turn on filament sensor for control
  6208. gcode_M405();
  6209. break;
  6210. case 406: //M406 Turn off filament sensor for control
  6211. gcode_M406();
  6212. break;
  6213. case 407: //M407 Display measured filament diameter
  6214. gcode_M407();
  6215. break;
  6216. #endif // ENABLED(FILAMENT_WIDTH_SENSOR)
  6217. #if ENABLED(MESH_BED_LEVELING)
  6218. case 420: // M420 Enable/Disable Mesh Bed Leveling
  6219. gcode_M420();
  6220. break;
  6221. case 421: // M421 Set a Mesh Bed Leveling Z coordinate
  6222. gcode_M421();
  6223. break;
  6224. #endif
  6225. case 428: // M428 Apply current_position to home_offset
  6226. gcode_M428();
  6227. break;
  6228. case 500: // M500 Store settings in EEPROM
  6229. gcode_M500();
  6230. break;
  6231. case 501: // M501 Read settings from EEPROM
  6232. gcode_M501();
  6233. break;
  6234. case 502: // M502 Revert to default settings
  6235. gcode_M502();
  6236. break;
  6237. case 503: // M503 print settings currently in memory
  6238. gcode_M503();
  6239. break;
  6240. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  6241. case 540:
  6242. gcode_M540();
  6243. break;
  6244. #endif
  6245. #if HAS_BED_PROBE
  6246. case 851:
  6247. gcode_M851();
  6248. break;
  6249. #endif // HAS_BED_PROBE
  6250. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  6251. case 600: //Pause for filament change X[pos] Y[pos] Z[relative lift] E[initial retract] L[later retract distance for removal]
  6252. gcode_M600();
  6253. break;
  6254. #endif // FILAMENT_CHANGE_FEATURE
  6255. #if ENABLED(DUAL_X_CARRIAGE)
  6256. case 605:
  6257. gcode_M605();
  6258. break;
  6259. #endif // DUAL_X_CARRIAGE
  6260. #if ENABLED(LIN_ADVANCE)
  6261. case 905: // M905 Set advance factor.
  6262. gcode_M905();
  6263. break;
  6264. #endif
  6265. case 907: // M907 Set digital trimpot motor current using axis codes.
  6266. gcode_M907();
  6267. break;
  6268. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  6269. case 908: // M908 Control digital trimpot directly.
  6270. gcode_M908();
  6271. break;
  6272. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  6273. case 909: // M909 Print digipot/DAC current value
  6274. gcode_M909();
  6275. break;
  6276. case 910: // M910 Commit digipot/DAC value to external EEPROM
  6277. gcode_M910();
  6278. break;
  6279. #endif
  6280. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  6281. #if HAS_MICROSTEPS
  6282. case 350: // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6283. gcode_M350();
  6284. break;
  6285. case 351: // M351 Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  6286. gcode_M351();
  6287. break;
  6288. #endif // HAS_MICROSTEPS
  6289. case 999: // M999: Restart after being Stopped
  6290. gcode_M999();
  6291. break;
  6292. }
  6293. break;
  6294. case 'T':
  6295. gcode_T(codenum);
  6296. break;
  6297. default: code_is_good = false;
  6298. }
  6299. KEEPALIVE_STATE(NOT_BUSY);
  6300. ExitUnknownCommand:
  6301. // Still unknown command? Throw an error
  6302. if (!code_is_good) unknown_command_error();
  6303. ok_to_send();
  6304. }
  6305. void FlushSerialRequestResend() {
  6306. //char command_queue[cmd_queue_index_r][100]="Resend:";
  6307. MYSERIAL.flush();
  6308. SERIAL_PROTOCOLPGM(MSG_RESEND);
  6309. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  6310. ok_to_send();
  6311. }
  6312. void ok_to_send() {
  6313. refresh_cmd_timeout();
  6314. if (!send_ok[cmd_queue_index_r]) return;
  6315. SERIAL_PROTOCOLPGM(MSG_OK);
  6316. #if ENABLED(ADVANCED_OK)
  6317. char* p = command_queue[cmd_queue_index_r];
  6318. if (*p == 'N') {
  6319. SERIAL_PROTOCOL(' ');
  6320. SERIAL_ECHO(*p++);
  6321. while (NUMERIC_SIGNED(*p))
  6322. SERIAL_ECHO(*p++);
  6323. }
  6324. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  6325. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  6326. #endif
  6327. SERIAL_EOL;
  6328. }
  6329. void clamp_to_software_endstops(float target[3]) {
  6330. if (min_software_endstops) {
  6331. NOLESS(target[X_AXIS], sw_endstop_min[X_AXIS]);
  6332. NOLESS(target[Y_AXIS], sw_endstop_min[Y_AXIS]);
  6333. NOLESS(target[Z_AXIS], sw_endstop_min[Z_AXIS]);
  6334. }
  6335. if (max_software_endstops) {
  6336. NOMORE(target[X_AXIS], sw_endstop_max[X_AXIS]);
  6337. NOMORE(target[Y_AXIS], sw_endstop_max[Y_AXIS]);
  6338. NOMORE(target[Z_AXIS], sw_endstop_max[Z_AXIS]);
  6339. }
  6340. }
  6341. #if ENABLED(DELTA)
  6342. void recalc_delta_settings(float radius, float diagonal_rod) {
  6343. delta_tower1_x = -SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1); // front left tower
  6344. delta_tower1_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_1);
  6345. delta_tower2_x = SIN_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2); // front right tower
  6346. delta_tower2_y = -COS_60 * (radius + DELTA_RADIUS_TRIM_TOWER_2);
  6347. delta_tower3_x = 0.0; // back middle tower
  6348. delta_tower3_y = (radius + DELTA_RADIUS_TRIM_TOWER_3);
  6349. delta_diagonal_rod_2_tower_1 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_1);
  6350. delta_diagonal_rod_2_tower_2 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_2);
  6351. delta_diagonal_rod_2_tower_3 = sq(diagonal_rod + delta_diagonal_rod_trim_tower_3);
  6352. }
  6353. void calculate_delta(float cartesian[3]) {
  6354. delta[TOWER_1] = sqrt(delta_diagonal_rod_2_tower_1
  6355. - sq(delta_tower1_x - cartesian[X_AXIS])
  6356. - sq(delta_tower1_y - cartesian[Y_AXIS])
  6357. ) + cartesian[Z_AXIS];
  6358. delta[TOWER_2] = sqrt(delta_diagonal_rod_2_tower_2
  6359. - sq(delta_tower2_x - cartesian[X_AXIS])
  6360. - sq(delta_tower2_y - cartesian[Y_AXIS])
  6361. ) + cartesian[Z_AXIS];
  6362. delta[TOWER_3] = sqrt(delta_diagonal_rod_2_tower_3
  6363. - sq(delta_tower3_x - cartesian[X_AXIS])
  6364. - sq(delta_tower3_y - cartesian[Y_AXIS])
  6365. ) + cartesian[Z_AXIS];
  6366. /**
  6367. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  6368. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  6369. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  6370. SERIAL_ECHOPGM("delta a="); SERIAL_ECHO(delta[TOWER_1]);
  6371. SERIAL_ECHOPGM(" b="); SERIAL_ECHO(delta[TOWER_2]);
  6372. SERIAL_ECHOPGM(" c="); SERIAL_ECHOLN(delta[TOWER_3]);
  6373. */
  6374. }
  6375. float delta_safe_distance_from_top() {
  6376. float cartesian[3] = { 0 };
  6377. calculate_delta(cartesian);
  6378. float distance = delta[TOWER_3];
  6379. cartesian[Y_AXIS] = DELTA_PRINTABLE_RADIUS;
  6380. calculate_delta(cartesian);
  6381. return abs(distance - delta[TOWER_3]);
  6382. }
  6383. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  6384. // Adjust print surface height by linear interpolation over the bed_level array.
  6385. void adjust_delta(float cartesian[3]) {
  6386. if (delta_grid_spacing[0] == 0 || delta_grid_spacing[1] == 0) return; // G29 not done!
  6387. int half = (AUTO_BED_LEVELING_GRID_POINTS - 1) / 2;
  6388. float h1 = 0.001 - half, h2 = half - 0.001,
  6389. grid_x = max(h1, min(h2, cartesian[X_AXIS] / delta_grid_spacing[0])),
  6390. grid_y = max(h1, min(h2, cartesian[Y_AXIS] / delta_grid_spacing[1]));
  6391. int floor_x = floor(grid_x), floor_y = floor(grid_y);
  6392. float ratio_x = grid_x - floor_x, ratio_y = grid_y - floor_y,
  6393. z1 = bed_level[floor_x + half][floor_y + half],
  6394. z2 = bed_level[floor_x + half][floor_y + half + 1],
  6395. z3 = bed_level[floor_x + half + 1][floor_y + half],
  6396. z4 = bed_level[floor_x + half + 1][floor_y + half + 1],
  6397. left = (1 - ratio_y) * z1 + ratio_y * z2,
  6398. right = (1 - ratio_y) * z3 + ratio_y * z4,
  6399. offset = (1 - ratio_x) * left + ratio_x * right;
  6400. delta[X_AXIS] += offset;
  6401. delta[Y_AXIS] += offset;
  6402. delta[Z_AXIS] += offset;
  6403. /**
  6404. SERIAL_ECHOPGM("grid_x="); SERIAL_ECHO(grid_x);
  6405. SERIAL_ECHOPGM(" grid_y="); SERIAL_ECHO(grid_y);
  6406. SERIAL_ECHOPGM(" floor_x="); SERIAL_ECHO(floor_x);
  6407. SERIAL_ECHOPGM(" floor_y="); SERIAL_ECHO(floor_y);
  6408. SERIAL_ECHOPGM(" ratio_x="); SERIAL_ECHO(ratio_x);
  6409. SERIAL_ECHOPGM(" ratio_y="); SERIAL_ECHO(ratio_y);
  6410. SERIAL_ECHOPGM(" z1="); SERIAL_ECHO(z1);
  6411. SERIAL_ECHOPGM(" z2="); SERIAL_ECHO(z2);
  6412. SERIAL_ECHOPGM(" z3="); SERIAL_ECHO(z3);
  6413. SERIAL_ECHOPGM(" z4="); SERIAL_ECHO(z4);
  6414. SERIAL_ECHOPGM(" left="); SERIAL_ECHO(left);
  6415. SERIAL_ECHOPGM(" right="); SERIAL_ECHO(right);
  6416. SERIAL_ECHOPGM(" offset="); SERIAL_ECHOLN(offset);
  6417. */
  6418. }
  6419. #endif // AUTO_BED_LEVELING_FEATURE
  6420. #endif // DELTA
  6421. #if ENABLED(MESH_BED_LEVELING)
  6422. // This function is used to split lines on mesh borders so each segment is only part of one mesh area
  6423. void mesh_buffer_line(float x, float y, float z, const float e, float feed_rate, const uint8_t& extruder, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  6424. if (!mbl.active()) {
  6425. planner.buffer_line(x, y, z, e, feed_rate, extruder);
  6426. set_current_to_destination();
  6427. return;
  6428. }
  6429. int pcx = mbl.cell_index_x(RAW_CURRENT_POSITION(X_AXIS)),
  6430. pcy = mbl.cell_index_y(RAW_CURRENT_POSITION(Y_AXIS)),
  6431. cx = mbl.cell_index_x(RAW_POSITION(x, X_AXIS)),
  6432. cy = mbl.cell_index_y(RAW_POSITION(y, Y_AXIS));
  6433. NOMORE(pcx, MESH_NUM_X_POINTS - 2);
  6434. NOMORE(pcy, MESH_NUM_Y_POINTS - 2);
  6435. NOMORE(cx, MESH_NUM_X_POINTS - 2);
  6436. NOMORE(cy, MESH_NUM_Y_POINTS - 2);
  6437. if (pcx == cx && pcy == cy) {
  6438. // Start and end on same mesh square
  6439. planner.buffer_line(x, y, z, e, feed_rate, extruder);
  6440. set_current_to_destination();
  6441. return;
  6442. }
  6443. float nx, ny, nz, ne, normalized_dist;
  6444. if (cx > pcx && TEST(x_splits, cx)) {
  6445. nx = mbl.get_probe_x(cx) + home_offset[X_AXIS];
  6446. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  6447. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  6448. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  6449. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  6450. CBI(x_splits, cx);
  6451. }
  6452. else if (cx < pcx && TEST(x_splits, pcx)) {
  6453. nx = mbl.get_probe_x(pcx) + home_offset[X_AXIS];
  6454. normalized_dist = (nx - current_position[X_AXIS]) / (x - current_position[X_AXIS]);
  6455. ny = current_position[Y_AXIS] + (y - current_position[Y_AXIS]) * normalized_dist;
  6456. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  6457. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  6458. CBI(x_splits, pcx);
  6459. }
  6460. else if (cy > pcy && TEST(y_splits, cy)) {
  6461. ny = mbl.get_probe_y(cy) + home_offset[Y_AXIS];
  6462. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  6463. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  6464. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  6465. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  6466. CBI(y_splits, cy);
  6467. }
  6468. else if (cy < pcy && TEST(y_splits, pcy)) {
  6469. ny = mbl.get_probe_y(pcy) + home_offset[Y_AXIS];
  6470. normalized_dist = (ny - current_position[Y_AXIS]) / (y - current_position[Y_AXIS]);
  6471. nx = current_position[X_AXIS] + (x - current_position[X_AXIS]) * normalized_dist;
  6472. nz = current_position[Z_AXIS] + (z - current_position[Z_AXIS]) * normalized_dist;
  6473. ne = current_position[E_AXIS] + (e - current_position[E_AXIS]) * normalized_dist;
  6474. CBI(y_splits, pcy);
  6475. }
  6476. else {
  6477. // Already split on a border
  6478. planner.buffer_line(x, y, z, e, feed_rate, extruder);
  6479. set_current_to_destination();
  6480. return;
  6481. }
  6482. // Do the split and look for more borders
  6483. destination[X_AXIS] = nx;
  6484. destination[Y_AXIS] = ny;
  6485. destination[Z_AXIS] = nz;
  6486. destination[E_AXIS] = ne;
  6487. mesh_buffer_line(nx, ny, nz, ne, feed_rate, extruder, x_splits, y_splits);
  6488. destination[X_AXIS] = x;
  6489. destination[Y_AXIS] = y;
  6490. destination[Z_AXIS] = z;
  6491. destination[E_AXIS] = e;
  6492. mesh_buffer_line(x, y, z, e, feed_rate, extruder, x_splits, y_splits);
  6493. }
  6494. #endif // MESH_BED_LEVELING
  6495. #if ENABLED(DELTA) || ENABLED(SCARA)
  6496. inline bool prepare_delta_move_to(float target[NUM_AXIS]) {
  6497. float difference[NUM_AXIS];
  6498. for (int8_t i = 0; i < NUM_AXIS; i++) difference[i] = target[i] - current_position[i];
  6499. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  6500. if (cartesian_mm < 0.000001) cartesian_mm = abs(difference[E_AXIS]);
  6501. if (cartesian_mm < 0.000001) return false;
  6502. float _feedrate = feedrate * feedrate_multiplier / 6000.0;
  6503. float seconds = cartesian_mm / _feedrate;
  6504. int steps = max(1, int(delta_segments_per_second * seconds));
  6505. float inv_steps = 1.0/steps;
  6506. // SERIAL_ECHOPGM("mm="); SERIAL_ECHO(cartesian_mm);
  6507. // SERIAL_ECHOPGM(" seconds="); SERIAL_ECHO(seconds);
  6508. // SERIAL_ECHOPGM(" steps="); SERIAL_ECHOLN(steps);
  6509. for (int s = 1; s <= steps; s++) {
  6510. float fraction = float(s) * inv_steps;
  6511. for (int8_t i = 0; i < NUM_AXIS; i++)
  6512. target[i] = current_position[i] + difference[i] * fraction;
  6513. calculate_delta(target);
  6514. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  6515. if (!bed_leveling_in_progress) adjust_delta(target);
  6516. #endif
  6517. //DEBUG_POS("prepare_delta_move_to", target);
  6518. //DEBUG_POS("prepare_delta_move_to", delta);
  6519. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], _feedrate, active_extruder);
  6520. }
  6521. return true;
  6522. }
  6523. #endif // DELTA || SCARA
  6524. #if ENABLED(SCARA)
  6525. inline bool prepare_scara_move_to(float target[NUM_AXIS]) { return prepare_delta_move_to(target); }
  6526. #endif
  6527. #if ENABLED(DUAL_X_CARRIAGE)
  6528. inline bool prepare_move_to_destination_dualx() {
  6529. if (active_extruder_parked) {
  6530. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && active_extruder == 0) {
  6531. // move duplicate extruder into correct duplication position.
  6532. planner.set_position_mm(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  6533. planner.buffer_line(current_position[X_AXIS] + duplicate_extruder_x_offset,
  6534. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate[X_AXIS], 1);
  6535. SYNC_PLAN_POSITION_KINEMATIC();
  6536. stepper.synchronize();
  6537. extruder_duplication_enabled = true;
  6538. active_extruder_parked = false;
  6539. }
  6540. else if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE) { // handle unparking of head
  6541. if (current_position[E_AXIS] == destination[E_AXIS]) {
  6542. // This is a travel move (with no extrusion)
  6543. // Skip it, but keep track of the current position
  6544. // (so it can be used as the start of the next non-travel move)
  6545. if (delayed_move_time != 0xFFFFFFFFUL) {
  6546. set_current_to_destination();
  6547. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  6548. delayed_move_time = millis();
  6549. return false;
  6550. }
  6551. }
  6552. delayed_move_time = 0;
  6553. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  6554. planner.buffer_line(raised_parked_position[X_AXIS], raised_parked_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate[Z_AXIS], active_extruder);
  6555. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], raised_parked_position[Z_AXIS], current_position[E_AXIS], PLANNER_XY_FEEDRATE(), active_extruder);
  6556. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], planner.max_feedrate[Z_AXIS], active_extruder);
  6557. active_extruder_parked = false;
  6558. }
  6559. }
  6560. return true;
  6561. }
  6562. #endif // DUAL_X_CARRIAGE
  6563. #if DISABLED(DELTA) && DISABLED(SCARA)
  6564. inline bool prepare_move_to_destination_cartesian() {
  6565. // Do not use feedrate_multiplier for E or Z only moves
  6566. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  6567. line_to_destination();
  6568. }
  6569. else {
  6570. #if ENABLED(MESH_BED_LEVELING)
  6571. mesh_buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], (feedrate / 60) * (feedrate_multiplier / 100.0), active_extruder);
  6572. return false;
  6573. #else
  6574. line_to_destination(feedrate * feedrate_multiplier / 100.0);
  6575. #endif
  6576. }
  6577. return true;
  6578. }
  6579. #endif // !DELTA && !SCARA
  6580. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  6581. inline void prevent_dangerous_extrude(float& curr_e, float& dest_e) {
  6582. if (DEBUGGING(DRYRUN)) return;
  6583. float de = dest_e - curr_e;
  6584. if (de) {
  6585. if (thermalManager.tooColdToExtrude(active_extruder)) {
  6586. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  6587. SERIAL_ECHO_START;
  6588. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  6589. }
  6590. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  6591. if (labs(de) > EXTRUDE_MAXLENGTH) {
  6592. curr_e = dest_e; // Behave as if the move really took place, but ignore E part
  6593. SERIAL_ECHO_START;
  6594. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  6595. }
  6596. #endif
  6597. }
  6598. }
  6599. #endif // PREVENT_DANGEROUS_EXTRUDE
  6600. /**
  6601. * Prepare a single move and get ready for the next one
  6602. *
  6603. * (This may call planner.buffer_line several times to put
  6604. * smaller moves into the planner for DELTA or SCARA.)
  6605. */
  6606. void prepare_move_to_destination() {
  6607. clamp_to_software_endstops(destination);
  6608. refresh_cmd_timeout();
  6609. #if ENABLED(PREVENT_DANGEROUS_EXTRUDE)
  6610. prevent_dangerous_extrude(current_position[E_AXIS], destination[E_AXIS]);
  6611. #endif
  6612. #if ENABLED(SCARA)
  6613. if (!prepare_scara_move_to(destination)) return;
  6614. #elif ENABLED(DELTA)
  6615. if (!prepare_delta_move_to(destination)) return;
  6616. #else
  6617. #if ENABLED(DUAL_X_CARRIAGE)
  6618. if (!prepare_move_to_destination_dualx()) return;
  6619. #endif
  6620. if (!prepare_move_to_destination_cartesian()) return;
  6621. #endif
  6622. set_current_to_destination();
  6623. }
  6624. #if ENABLED(ARC_SUPPORT)
  6625. /**
  6626. * Plan an arc in 2 dimensions
  6627. *
  6628. * The arc is approximated by generating many small linear segments.
  6629. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  6630. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  6631. * larger segments will tend to be more efficient. Your slicer should have
  6632. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  6633. */
  6634. void plan_arc(
  6635. float target[NUM_AXIS], // Destination position
  6636. float* offset, // Center of rotation relative to current_position
  6637. uint8_t clockwise // Clockwise?
  6638. ) {
  6639. float radius = hypot(offset[X_AXIS], offset[Y_AXIS]),
  6640. center_X = current_position[X_AXIS] + offset[X_AXIS],
  6641. center_Y = current_position[Y_AXIS] + offset[Y_AXIS],
  6642. linear_travel = target[Z_AXIS] - current_position[Z_AXIS],
  6643. extruder_travel = target[E_AXIS] - current_position[E_AXIS],
  6644. r_X = -offset[X_AXIS], // Radius vector from center to current location
  6645. r_Y = -offset[Y_AXIS],
  6646. rt_X = target[X_AXIS] - center_X,
  6647. rt_Y = target[Y_AXIS] - center_Y;
  6648. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  6649. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  6650. if (angular_travel < 0) angular_travel += RADIANS(360);
  6651. if (clockwise) angular_travel -= RADIANS(360);
  6652. // Make a circle if the angular rotation is 0
  6653. if (angular_travel == 0 && current_position[X_AXIS] == target[X_AXIS] && current_position[Y_AXIS] == target[Y_AXIS])
  6654. angular_travel += RADIANS(360);
  6655. float mm_of_travel = hypot(angular_travel * radius, fabs(linear_travel));
  6656. if (mm_of_travel < 0.001) return;
  6657. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  6658. if (segments == 0) segments = 1;
  6659. float theta_per_segment = angular_travel / segments;
  6660. float linear_per_segment = linear_travel / segments;
  6661. float extruder_per_segment = extruder_travel / segments;
  6662. /**
  6663. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  6664. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  6665. * r_T = [cos(phi) -sin(phi);
  6666. * sin(phi) cos(phi] * r ;
  6667. *
  6668. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  6669. * defined from the circle center to the initial position. Each line segment is formed by successive
  6670. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  6671. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  6672. * all double numbers are single precision on the Arduino. (True double precision will not have
  6673. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  6674. * tool precision in some cases. Therefore, arc path correction is implemented.
  6675. *
  6676. * Small angle approximation may be used to reduce computation overhead further. This approximation
  6677. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  6678. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  6679. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  6680. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  6681. * issue for CNC machines with the single precision Arduino calculations.
  6682. *
  6683. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  6684. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  6685. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  6686. * This is important when there are successive arc motions.
  6687. */
  6688. // Vector rotation matrix values
  6689. float cos_T = 1 - 0.5 * theta_per_segment * theta_per_segment; // Small angle approximation
  6690. float sin_T = theta_per_segment;
  6691. float arc_target[NUM_AXIS];
  6692. float sin_Ti, cos_Ti, r_new_Y;
  6693. uint16_t i;
  6694. int8_t count = 0;
  6695. // Initialize the linear axis
  6696. arc_target[Z_AXIS] = current_position[Z_AXIS];
  6697. // Initialize the extruder axis
  6698. arc_target[E_AXIS] = current_position[E_AXIS];
  6699. float feed_rate = feedrate * feedrate_multiplier / 60 / 100.0;
  6700. millis_t next_idle_ms = millis() + 200UL;
  6701. for (i = 1; i < segments; i++) { // Iterate (segments-1) times
  6702. thermalManager.manage_heater();
  6703. millis_t now = millis();
  6704. if (ELAPSED(now, next_idle_ms)) {
  6705. next_idle_ms = now + 200UL;
  6706. idle();
  6707. }
  6708. if (++count < N_ARC_CORRECTION) {
  6709. // Apply vector rotation matrix to previous r_X / 1
  6710. r_new_Y = r_X * sin_T + r_Y * cos_T;
  6711. r_X = r_X * cos_T - r_Y * sin_T;
  6712. r_Y = r_new_Y;
  6713. }
  6714. else {
  6715. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  6716. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  6717. // To reduce stuttering, the sin and cos could be computed at different times.
  6718. // For now, compute both at the same time.
  6719. cos_Ti = cos(i * theta_per_segment);
  6720. sin_Ti = sin(i * theta_per_segment);
  6721. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  6722. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  6723. count = 0;
  6724. }
  6725. // Update arc_target location
  6726. arc_target[X_AXIS] = center_X + r_X;
  6727. arc_target[Y_AXIS] = center_Y + r_Y;
  6728. arc_target[Z_AXIS] += linear_per_segment;
  6729. arc_target[E_AXIS] += extruder_per_segment;
  6730. clamp_to_software_endstops(arc_target);
  6731. #if ENABLED(DELTA) || ENABLED(SCARA)
  6732. calculate_delta(arc_target);
  6733. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  6734. adjust_delta(arc_target);
  6735. #endif
  6736. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  6737. #else
  6738. planner.buffer_line(arc_target[X_AXIS], arc_target[Y_AXIS], arc_target[Z_AXIS], arc_target[E_AXIS], feed_rate, active_extruder);
  6739. #endif
  6740. }
  6741. // Ensure last segment arrives at target location.
  6742. #if ENABLED(DELTA) || ENABLED(SCARA)
  6743. calculate_delta(target);
  6744. #if ENABLED(AUTO_BED_LEVELING_FEATURE)
  6745. adjust_delta(target);
  6746. #endif
  6747. planner.buffer_line(delta[X_AXIS], delta[Y_AXIS], delta[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  6748. #else
  6749. planner.buffer_line(target[X_AXIS], target[Y_AXIS], target[Z_AXIS], target[E_AXIS], feed_rate, active_extruder);
  6750. #endif
  6751. // As far as the parser is concerned, the position is now == target. In reality the
  6752. // motion control system might still be processing the action and the real tool position
  6753. // in any intermediate location.
  6754. set_current_to_destination();
  6755. }
  6756. #endif
  6757. #if ENABLED(BEZIER_CURVE_SUPPORT)
  6758. void plan_cubic_move(const float offset[4]) {
  6759. cubic_b_spline(current_position, destination, offset, feedrate * feedrate_multiplier / 60 / 100.0, active_extruder);
  6760. // As far as the parser is concerned, the position is now == target. In reality the
  6761. // motion control system might still be processing the action and the real tool position
  6762. // in any intermediate location.
  6763. set_current_to_destination();
  6764. }
  6765. #endif // BEZIER_CURVE_SUPPORT
  6766. #if HAS_CONTROLLERFAN
  6767. void controllerFan() {
  6768. static millis_t lastMotorOn = 0; // Last time a motor was turned on
  6769. static millis_t nextMotorCheck = 0; // Last time the state was checked
  6770. millis_t ms = millis();
  6771. if (ELAPSED(ms, nextMotorCheck)) {
  6772. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  6773. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_bed > 0
  6774. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  6775. #if EXTRUDERS > 1
  6776. || E1_ENABLE_READ == E_ENABLE_ON
  6777. #if HAS_X2_ENABLE
  6778. || X2_ENABLE_READ == X_ENABLE_ON
  6779. #endif
  6780. #if EXTRUDERS > 2
  6781. || E2_ENABLE_READ == E_ENABLE_ON
  6782. #if EXTRUDERS > 3
  6783. || E3_ENABLE_READ == E_ENABLE_ON
  6784. #endif
  6785. #endif
  6786. #endif
  6787. ) {
  6788. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  6789. }
  6790. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  6791. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  6792. // allows digital or PWM fan output to be used (see M42 handling)
  6793. digitalWrite(CONTROLLERFAN_PIN, speed);
  6794. analogWrite(CONTROLLERFAN_PIN, speed);
  6795. }
  6796. }
  6797. #endif // HAS_CONTROLLERFAN
  6798. #if ENABLED(SCARA)
  6799. void calculate_SCARA_forward_Transform(float f_scara[3]) {
  6800. // Perform forward kinematics, and place results in delta[3]
  6801. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  6802. float x_sin, x_cos, y_sin, y_cos;
  6803. //SERIAL_ECHOPGM("f_delta x="); SERIAL_ECHO(f_scara[X_AXIS]);
  6804. //SERIAL_ECHOPGM(" y="); SERIAL_ECHO(f_scara[Y_AXIS]);
  6805. x_sin = sin(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  6806. x_cos = cos(f_scara[X_AXIS] / SCARA_RAD2DEG) * Linkage_1;
  6807. y_sin = sin(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  6808. y_cos = cos(f_scara[Y_AXIS] / SCARA_RAD2DEG) * Linkage_2;
  6809. //SERIAL_ECHOPGM(" x_sin="); SERIAL_ECHO(x_sin);
  6810. //SERIAL_ECHOPGM(" x_cos="); SERIAL_ECHO(x_cos);
  6811. //SERIAL_ECHOPGM(" y_sin="); SERIAL_ECHO(y_sin);
  6812. //SERIAL_ECHOPGM(" y_cos="); SERIAL_ECHOLN(y_cos);
  6813. delta[X_AXIS] = x_cos + y_cos + SCARA_offset_x; //theta
  6814. delta[Y_AXIS] = x_sin + y_sin + SCARA_offset_y; //theta+phi
  6815. //SERIAL_ECHOPGM(" delta[X_AXIS]="); SERIAL_ECHO(delta[X_AXIS]);
  6816. //SERIAL_ECHOPGM(" delta[Y_AXIS]="); SERIAL_ECHOLN(delta[Y_AXIS]);
  6817. }
  6818. void calculate_delta(float cartesian[3]) {
  6819. //reverse kinematics.
  6820. // Perform reversed kinematics, and place results in delta[3]
  6821. // The maths and first version has been done by QHARLEY . Integrated into masterbranch 06/2014 and slightly restructured by Joachim Cerny in June 2014
  6822. float SCARA_pos[2];
  6823. static float SCARA_C2, SCARA_S2, SCARA_K1, SCARA_K2, SCARA_theta, SCARA_psi;
  6824. SCARA_pos[X_AXIS] = cartesian[X_AXIS] * axis_scaling[X_AXIS] - SCARA_offset_x; //Translate SCARA to standard X Y
  6825. SCARA_pos[Y_AXIS] = cartesian[Y_AXIS] * axis_scaling[Y_AXIS] - SCARA_offset_y; // With scaling factor.
  6826. #if (Linkage_1 == Linkage_2)
  6827. SCARA_C2 = ((sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS])) / (2 * (float)L1_2)) - 1;
  6828. #else
  6829. SCARA_C2 = (sq(SCARA_pos[X_AXIS]) + sq(SCARA_pos[Y_AXIS]) - (float)L1_2 - (float)L2_2) / 45000;
  6830. #endif
  6831. SCARA_S2 = sqrt(1 - sq(SCARA_C2));
  6832. SCARA_K1 = Linkage_1 + Linkage_2 * SCARA_C2;
  6833. SCARA_K2 = Linkage_2 * SCARA_S2;
  6834. SCARA_theta = (atan2(SCARA_pos[X_AXIS], SCARA_pos[Y_AXIS]) - atan2(SCARA_K1, SCARA_K2)) * -1;
  6835. SCARA_psi = atan2(SCARA_S2, SCARA_C2);
  6836. delta[X_AXIS] = SCARA_theta * SCARA_RAD2DEG; // Multiply by 180/Pi - theta is support arm angle
  6837. delta[Y_AXIS] = (SCARA_theta + SCARA_psi) * SCARA_RAD2DEG; // - equal to sub arm angle (inverted motor)
  6838. delta[Z_AXIS] = cartesian[Z_AXIS];
  6839. /**
  6840. SERIAL_ECHOPGM("cartesian x="); SERIAL_ECHO(cartesian[X_AXIS]);
  6841. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(cartesian[Y_AXIS]);
  6842. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(cartesian[Z_AXIS]);
  6843. SERIAL_ECHOPGM("scara x="); SERIAL_ECHO(SCARA_pos[X_AXIS]);
  6844. SERIAL_ECHOPGM(" y="); SERIAL_ECHOLN(SCARA_pos[Y_AXIS]);
  6845. SERIAL_ECHOPGM("delta x="); SERIAL_ECHO(delta[X_AXIS]);
  6846. SERIAL_ECHOPGM(" y="); SERIAL_ECHO(delta[Y_AXIS]);
  6847. SERIAL_ECHOPGM(" z="); SERIAL_ECHOLN(delta[Z_AXIS]);
  6848. SERIAL_ECHOPGM("C2="); SERIAL_ECHO(SCARA_C2);
  6849. SERIAL_ECHOPGM(" S2="); SERIAL_ECHO(SCARA_S2);
  6850. SERIAL_ECHOPGM(" Theta="); SERIAL_ECHO(SCARA_theta);
  6851. SERIAL_ECHOPGM(" Psi="); SERIAL_ECHOLN(SCARA_psi);
  6852. SERIAL_EOL;
  6853. */
  6854. }
  6855. #endif // SCARA
  6856. #if ENABLED(TEMP_STAT_LEDS)
  6857. static bool red_led = false;
  6858. static millis_t next_status_led_update_ms = 0;
  6859. void handle_status_leds(void) {
  6860. float max_temp = 0.0;
  6861. if (ELAPSED(millis(), next_status_led_update_ms)) {
  6862. next_status_led_update_ms += 500; // Update every 0.5s
  6863. HOTEND_LOOP() {
  6864. max_temp = max(max(max_temp, thermalManager.degHotend(e)), thermalManager.degTargetHotend(e));
  6865. }
  6866. #if HAS_TEMP_BED
  6867. max_temp = max(max(max_temp, thermalManager.degTargetBed()), thermalManager.degBed());
  6868. #endif
  6869. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  6870. if (new_led != red_led) {
  6871. red_led = new_led;
  6872. digitalWrite(STAT_LED_RED, new_led ? HIGH : LOW);
  6873. digitalWrite(STAT_LED_BLUE, new_led ? LOW : HIGH);
  6874. }
  6875. }
  6876. }
  6877. #endif
  6878. void enable_all_steppers() {
  6879. enable_x();
  6880. enable_y();
  6881. enable_z();
  6882. enable_e0();
  6883. enable_e1();
  6884. enable_e2();
  6885. enable_e3();
  6886. }
  6887. void disable_all_steppers() {
  6888. disable_x();
  6889. disable_y();
  6890. disable_z();
  6891. disable_e0();
  6892. disable_e1();
  6893. disable_e2();
  6894. disable_e3();
  6895. }
  6896. /**
  6897. * Standard idle routine keeps the machine alive
  6898. */
  6899. void idle(
  6900. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  6901. bool no_stepper_sleep/*=false*/
  6902. #endif
  6903. ) {
  6904. lcd_update();
  6905. host_keepalive();
  6906. manage_inactivity(
  6907. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  6908. no_stepper_sleep
  6909. #endif
  6910. );
  6911. thermalManager.manage_heater();
  6912. #if ENABLED(PRINTCOUNTER)
  6913. print_job_timer.tick();
  6914. #endif
  6915. #if HAS_BUZZER
  6916. buzzer.tick();
  6917. #endif
  6918. }
  6919. /**
  6920. * Manage several activities:
  6921. * - Check for Filament Runout
  6922. * - Keep the command buffer full
  6923. * - Check for maximum inactive time between commands
  6924. * - Check for maximum inactive time between stepper commands
  6925. * - Check if pin CHDK needs to go LOW
  6926. * - Check for KILL button held down
  6927. * - Check for HOME button held down
  6928. * - Check if cooling fan needs to be switched on
  6929. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  6930. */
  6931. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  6932. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6933. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && !(READ(FIL_RUNOUT_PIN) ^ FIL_RUNOUT_INVERTING))
  6934. handle_filament_runout();
  6935. #endif
  6936. if (commands_in_queue < BUFSIZE) get_available_commands();
  6937. millis_t ms = millis();
  6938. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) kill(PSTR(MSG_KILLED));
  6939. if (stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  6940. && !ignore_stepper_queue && !planner.blocks_queued()) {
  6941. #if ENABLED(DISABLE_INACTIVE_X)
  6942. disable_x();
  6943. #endif
  6944. #if ENABLED(DISABLE_INACTIVE_Y)
  6945. disable_y();
  6946. #endif
  6947. #if ENABLED(DISABLE_INACTIVE_Z)
  6948. disable_z();
  6949. #endif
  6950. #if ENABLED(DISABLE_INACTIVE_E)
  6951. disable_e0();
  6952. disable_e1();
  6953. disable_e2();
  6954. disable_e3();
  6955. #endif
  6956. }
  6957. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  6958. if (chdkActive && PENDING(ms, chdkHigh + CHDK_DELAY)) {
  6959. chdkActive = false;
  6960. WRITE(CHDK, LOW);
  6961. }
  6962. #endif
  6963. #if HAS_KILL
  6964. // Check if the kill button was pressed and wait just in case it was an accidental
  6965. // key kill key press
  6966. // -------------------------------------------------------------------------------
  6967. static int killCount = 0; // make the inactivity button a bit less responsive
  6968. const int KILL_DELAY = 750;
  6969. if (!READ(KILL_PIN))
  6970. killCount++;
  6971. else if (killCount > 0)
  6972. killCount--;
  6973. // Exceeded threshold and we can confirm that it was not accidental
  6974. // KILL the machine
  6975. // ----------------------------------------------------------------
  6976. if (killCount >= KILL_DELAY) kill(PSTR(MSG_KILLED));
  6977. #endif
  6978. #if HAS_HOME
  6979. // Check to see if we have to home, use poor man's debouncer
  6980. // ---------------------------------------------------------
  6981. static int homeDebounceCount = 0; // poor man's debouncing count
  6982. const int HOME_DEBOUNCE_DELAY = 2500;
  6983. if (!READ(HOME_PIN)) {
  6984. if (!homeDebounceCount) {
  6985. enqueue_and_echo_commands_P(PSTR("G28"));
  6986. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  6987. }
  6988. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  6989. homeDebounceCount++;
  6990. else
  6991. homeDebounceCount = 0;
  6992. }
  6993. #endif
  6994. #if HAS_CONTROLLERFAN
  6995. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  6996. #endif
  6997. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  6998. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL))
  6999. if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  7000. bool oldstatus;
  7001. switch (active_extruder) {
  7002. case 0:
  7003. oldstatus = E0_ENABLE_READ;
  7004. enable_e0();
  7005. break;
  7006. #if EXTRUDERS > 1
  7007. case 1:
  7008. oldstatus = E1_ENABLE_READ;
  7009. enable_e1();
  7010. break;
  7011. #if EXTRUDERS > 2
  7012. case 2:
  7013. oldstatus = E2_ENABLE_READ;
  7014. enable_e2();
  7015. break;
  7016. #if EXTRUDERS > 3
  7017. case 3:
  7018. oldstatus = E3_ENABLE_READ;
  7019. enable_e3();
  7020. break;
  7021. #endif
  7022. #endif
  7023. #endif
  7024. }
  7025. float oldepos = current_position[E_AXIS], oldedes = destination[E_AXIS];
  7026. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS],
  7027. destination[E_AXIS] + (EXTRUDER_RUNOUT_EXTRUDE) * (EXTRUDER_RUNOUT_ESTEPS) / planner.axis_steps_per_mm[E_AXIS],
  7028. (EXTRUDER_RUNOUT_SPEED) / 60. * (EXTRUDER_RUNOUT_ESTEPS) / planner.axis_steps_per_mm[E_AXIS], active_extruder);
  7029. current_position[E_AXIS] = oldepos;
  7030. destination[E_AXIS] = oldedes;
  7031. planner.set_e_position_mm(oldepos);
  7032. previous_cmd_ms = ms; // refresh_cmd_timeout()
  7033. stepper.synchronize();
  7034. switch (active_extruder) {
  7035. case 0:
  7036. E0_ENABLE_WRITE(oldstatus);
  7037. break;
  7038. #if EXTRUDERS > 1
  7039. case 1:
  7040. E1_ENABLE_WRITE(oldstatus);
  7041. break;
  7042. #if EXTRUDERS > 2
  7043. case 2:
  7044. E2_ENABLE_WRITE(oldstatus);
  7045. break;
  7046. #if EXTRUDERS > 3
  7047. case 3:
  7048. E3_ENABLE_WRITE(oldstatus);
  7049. break;
  7050. #endif
  7051. #endif
  7052. #endif
  7053. }
  7054. }
  7055. #endif
  7056. #if ENABLED(DUAL_X_CARRIAGE)
  7057. // handle delayed move timeout
  7058. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  7059. // travel moves have been received so enact them
  7060. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  7061. set_destination_to_current();
  7062. prepare_move_to_destination();
  7063. }
  7064. #endif
  7065. #if ENABLED(TEMP_STAT_LEDS)
  7066. handle_status_leds();
  7067. #endif
  7068. planner.check_axes_activity();
  7069. }
  7070. void kill(const char* lcd_msg) {
  7071. SERIAL_ERROR_START;
  7072. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  7073. #if ENABLED(ULTRA_LCD)
  7074. kill_screen(lcd_msg);
  7075. #else
  7076. UNUSED(lcd_msg);
  7077. #endif
  7078. for (int i = 5; i--;) delay(100); // Wait a short time
  7079. cli(); // Stop interrupts
  7080. thermalManager.disable_all_heaters();
  7081. disable_all_steppers();
  7082. #if HAS_POWER_SWITCH
  7083. pinMode(PS_ON_PIN, INPUT);
  7084. #endif
  7085. suicide();
  7086. while (1) {
  7087. #if ENABLED(USE_WATCHDOG)
  7088. watchdog_reset();
  7089. #endif
  7090. } // Wait for reset
  7091. }
  7092. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  7093. void handle_filament_runout() {
  7094. if (!filament_ran_out) {
  7095. filament_ran_out = true;
  7096. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  7097. stepper.synchronize();
  7098. }
  7099. }
  7100. #endif // FILAMENT_RUNOUT_SENSOR
  7101. #if ENABLED(FAST_PWM_FAN)
  7102. void setPwmFrequency(uint8_t pin, int val) {
  7103. val &= 0x07;
  7104. switch (digitalPinToTimer(pin)) {
  7105. #if defined(TCCR0A)
  7106. case TIMER0A:
  7107. case TIMER0B:
  7108. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  7109. // TCCR0B |= val;
  7110. break;
  7111. #endif
  7112. #if defined(TCCR1A)
  7113. case TIMER1A:
  7114. case TIMER1B:
  7115. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7116. // TCCR1B |= val;
  7117. break;
  7118. #endif
  7119. #if defined(TCCR2)
  7120. case TIMER2:
  7121. case TIMER2:
  7122. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  7123. TCCR2 |= val;
  7124. break;
  7125. #endif
  7126. #if defined(TCCR2A)
  7127. case TIMER2A:
  7128. case TIMER2B:
  7129. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  7130. TCCR2B |= val;
  7131. break;
  7132. #endif
  7133. #if defined(TCCR3A)
  7134. case TIMER3A:
  7135. case TIMER3B:
  7136. case TIMER3C:
  7137. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  7138. TCCR3B |= val;
  7139. break;
  7140. #endif
  7141. #if defined(TCCR4A)
  7142. case TIMER4A:
  7143. case TIMER4B:
  7144. case TIMER4C:
  7145. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  7146. TCCR4B |= val;
  7147. break;
  7148. #endif
  7149. #if defined(TCCR5A)
  7150. case TIMER5A:
  7151. case TIMER5B:
  7152. case TIMER5C:
  7153. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  7154. TCCR5B |= val;
  7155. break;
  7156. #endif
  7157. }
  7158. }
  7159. #endif // FAST_PWM_FAN
  7160. void stop() {
  7161. thermalManager.disable_all_heaters();
  7162. if (IsRunning()) {
  7163. Running = false;
  7164. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  7165. SERIAL_ERROR_START;
  7166. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  7167. LCD_MESSAGEPGM(MSG_STOPPED);
  7168. }
  7169. }
  7170. float calculate_volumetric_multiplier(float diameter) {
  7171. if (!volumetric_enabled || diameter == 0) return 1.0;
  7172. float d2 = diameter * 0.5;
  7173. return 1.0 / (M_PI * d2 * d2);
  7174. }
  7175. void calculate_volumetric_multipliers() {
  7176. for (int i = 0; i < EXTRUDERS; i++)
  7177. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  7178. }