Marlin_main.cpp 513 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/grbl/grbl
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G6 - Direct stepper move (Requires UNREGISTERED_MOVE_SUPPORT). Hangprinter defaults to relative moves. Others default to absolute moves.
  53. * G10 - Retract filament according to settings of M207 (Requires FWRETRACT)
  54. * G11 - Retract recover filament according to settings of M208 (Requires FWRETRACT)
  55. * G12 - Clean tool (Requires NOZZLE_CLEAN_FEATURE)
  56. * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES)
  57. * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES)
  58. * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES)
  59. * G20 - Set input units to inches (Requires INCH_MODE_SUPPORT)
  60. * G21 - Set input units to millimeters (Requires INCH_MODE_SUPPORT)
  61. * G26 - Mesh Validation Pattern (Requires G26_MESH_VALIDATION)
  62. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  63. * G28 - Home one or more axes
  64. * G29 - Start or continue the bed leveling probe procedure (Requires bed leveling)
  65. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  66. * G31 - Dock sled (Z_PROBE_SLED only)
  67. * G32 - Undock sled (Z_PROBE_SLED only)
  68. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  69. * G38 - Probe in any direction using the Z_MIN_PROBE (Requires G38_PROBE_TARGET)
  70. * G42 - Coordinated move to a mesh point (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BLINEAR, or AUTO_BED_LEVELING_UBL)
  71. * G90 - Use Absolute Coordinates
  72. * G91 - Use Relative Coordinates
  73. * G92 - Set current position to coordinates given
  74. * G95 - Set torque mode (Requires MECHADUINO_I2C_COMMANDS enabled)
  75. * G96 - Set encoder reference point (Requires MECHADUINO_I2C_COMMANDS enabled)
  76. *
  77. * "M" Codes
  78. *
  79. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  80. * M1 -> M0
  81. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  82. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  83. * M5 - Turn laser/spindle off
  84. * M17 - Enable/Power all stepper motors
  85. * M18 - Disable all stepper motors; same as M84
  86. * M20 - List SD card. (Requires SDSUPPORT)
  87. * M21 - Init SD card. (Requires SDSUPPORT)
  88. * M22 - Release SD card. (Requires SDSUPPORT)
  89. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  90. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  91. * M25 - Pause SD print. (Requires SDSUPPORT)
  92. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  93. * M27 - Report SD print status. (Requires SDSUPPORT)
  94. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  95. * OR, with 'C' get the current filename.
  96. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  97. * M29 - Stop SD write. (Requires SDSUPPORT)
  98. * M30 - Delete file from SD: "M30 /path/file.gco"
  99. * M31 - Report time since last M109 or SD card start to serial.
  100. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  101. * Use P to run other files as sub-programs: "M32 P !filename#"
  102. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  103. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  104. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  105. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  106. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  107. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs> S<chizoid>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  108. * M75 - Start the print job timer.
  109. * M76 - Pause the print job timer.
  110. * M77 - Stop the print job timer.
  111. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  112. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  113. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  114. * M82 - Set E codes absolute (default).
  115. * M83 - Set E codes relative while in Absolute (G90) mode.
  116. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  117. * duration after which steppers should turn off. S0 disables the timeout.
  118. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  119. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  120. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  121. * M104 - Set extruder target temp.
  122. * M105 - Report current temperatures.
  123. * M106 - Set print fan speed.
  124. * M107 - Print fan off.
  125. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  126. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  127. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  128. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  129. * M110 - Set the current line number. (Used by host printing)
  130. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  131. * M112 - Emergency stop.
  132. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  133. * M114 - Report current position.
  134. * - S1 Compute length traveled since last G96 using encoder position data (Requires MECHADUINO_I2C_COMMANDS, only kinematic axes)
  135. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  136. * M117 - Display a message on the controller screen. (Requires an LCD)
  137. * M118 - Display a message in the host console.
  138. * M119 - Report endstops status.
  139. * M120 - Enable endstops detection.
  140. * M121 - Disable endstops detection.
  141. * M122 - Debug stepper (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  142. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  143. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  144. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  145. * M128 - EtoP Open. (Requires BARICUDA)
  146. * M129 - EtoP Closed. (Requires BARICUDA)
  147. * M140 - Set bed target temp. S<temp>
  148. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  149. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  150. * M150 - Set Status LED Color as R<red> U<green> B<blue> P<bright>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, NEOPIXEL_LED, or PCA9632).
  151. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  152. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  153. * M164 - Commit the mix (Req. MIXING_EXTRUDER) and optionally save as a virtual tool (Req. MIXING_VIRTUAL_TOOLS > 1)
  154. * M165 - Set the mix for a mixing extruder wuth parameters ABCDHI. (Requires MIXING_EXTRUDER and DIRECT_MIXING_IN_G1)
  155. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  156. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  157. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  158. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  159. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  160. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  161. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  162. * M205 - Set advanced settings. Current units apply:
  163. S<print> T<travel> minimum speeds
  164. Q<minimum segment time>
  165. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  166. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  167. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  168. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  169. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  170. Every normal extrude-only move will be classified as retract depending on the direction.
  171. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  172. * M218 - Set/get a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  173. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  174. * M221 - Set Flow Percentage: "M221 S<percent>"
  175. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  176. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  177. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  178. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  179. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  180. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  181. * M290 - Babystepping (Requires BABYSTEPPING)
  182. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  183. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  184. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  185. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  186. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  187. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  188. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  189. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  190. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  191. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  192. * M400 - Finish all moves.
  193. * M401 - Deploy and activate Z probe. (Requires a probe)
  194. * M402 - Deactivate and stow Z probe. (Requires a probe)
  195. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  196. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  197. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  198. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  199. * M410 - Quickstop. Abort all planned moves.
  200. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  201. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING, AUTO_BED_LEVELING_BILINEAR, or AUTO_BED_LEVELING_UBL)
  202. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  203. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  204. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  205. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  206. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  207. * M524 - Abort SD card print job started with M24 (Requires SDSUPPORT)
  208. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  209. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  210. * M603 - Configure filament change: "M603 T<tool> U<unload_length> L<load_length>". (Requires ADVANCED_PAUSE_FEATURE)
  211. * M605 - Set Dual X-Carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  212. * M665 - Set Delta configurations: "M665 H<delta height> L<diagonal rod> R<delta radius> S<segments/s> B<calibration radius> X<Alpha angle trim> Y<Beta angle trim> Z<Gamma angle trim> (Requires DELTA)
  213. * M665 - Set Hangprinter configurations: "M665 W<Ay> E<Az> R<Bx> T<By> Y<Bz> U<Cx> I<Cy> O<Cz> P<Dz> S<segments/s>" (Requires HANGPRINTER)
  214. * M666 - Set/get endstop offsets for delta (Requires DELTA) or dual endstops (Requires [XYZ]_DUAL_ENDSTOPS).
  215. * M701 - Load filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  216. * M702 - Unload filament (requires FILAMENT_LOAD_UNLOAD_GCODES)
  217. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  218. * M852 - Set skew factors: "M852 [I<xy>] [J<xz>] [K<yz>]". (Requires SKEW_CORRECTION_GCODE, and SKEW_CORRECTION_FOR_Z for IJ)
  219. * M860 - Report the position of position encoder modules.
  220. * M861 - Report the status of position encoder modules.
  221. * M862 - Perform an axis continuity test for position encoder modules.
  222. * M863 - Perform steps-per-mm calibration for position encoder modules.
  223. * M864 - Change position encoder module I2C address.
  224. * M865 - Check position encoder module firmware version.
  225. * M866 - Report or reset position encoder module error count.
  226. * M867 - Enable/disable or toggle error correction for position encoder modules.
  227. * M868 - Report or set position encoder module error correction threshold.
  228. * M869 - Report position encoder module error.
  229. * M900 - Get or Set Linear Advance K-factor. (Requires LIN_ADVANCE)
  230. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  231. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  232. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  233. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  234. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  235. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  236. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires at least one _DRIVER_TYPE defined as TMC2130/TMC2208/TMC2660)
  237. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  238. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  239. *
  240. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  241. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  242. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  243. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  244. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  245. *
  246. * ************ Custom codes - This can change to suit future G-code regulations
  247. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  248. * M999 - Restart after being stopped by error
  249. *
  250. * "T" Codes
  251. *
  252. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  253. *
  254. */
  255. #include "Marlin.h"
  256. #include "ultralcd.h"
  257. #include "planner.h"
  258. #include "stepper.h"
  259. #include "endstops.h"
  260. #include "temperature.h"
  261. #include "cardreader.h"
  262. #include "configuration_store.h"
  263. #include "language.h"
  264. #include "pins_arduino.h"
  265. #include "math.h"
  266. #include "nozzle.h"
  267. #include "printcounter.h"
  268. #include "duration_t.h"
  269. #include "types.h"
  270. #include "parser.h"
  271. #if ENABLED(AUTO_POWER_CONTROL)
  272. #include "power.h"
  273. #endif
  274. #if ABL_PLANAR
  275. #include "vector_3.h"
  276. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  277. #include "least_squares_fit.h"
  278. #endif
  279. #elif ENABLED(MESH_BED_LEVELING)
  280. #include "mesh_bed_leveling.h"
  281. #endif
  282. #if ENABLED(BEZIER_CURVE_SUPPORT)
  283. #include "planner_bezier.h"
  284. #endif
  285. #if ENABLED(FWRETRACT)
  286. #include "fwretract.h"
  287. #endif
  288. #if ENABLED(POWER_LOSS_RECOVERY)
  289. #include "power_loss_recovery.h"
  290. #endif
  291. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  292. #include "runout.h"
  293. #endif
  294. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  295. #include "buzzer.h"
  296. #endif
  297. #if ENABLED(USE_WATCHDOG)
  298. #include "watchdog.h"
  299. #endif
  300. #if ENABLED(MAX7219_DEBUG)
  301. #include "Max7219_Debug_LEDs.h"
  302. #endif
  303. #if HAS_COLOR_LEDS
  304. #include "leds.h"
  305. #endif
  306. #if HAS_SERVOS
  307. #include "servo.h"
  308. #endif
  309. #if HAS_DIGIPOTSS
  310. #include <SPI.h>
  311. #endif
  312. #if HAS_TRINAMIC
  313. #include "tmc_util.h"
  314. #endif
  315. #if ENABLED(DAC_STEPPER_CURRENT)
  316. #include "stepper_dac.h"
  317. #endif
  318. #if ENABLED(EXPERIMENTAL_I2CBUS)
  319. #include "twibus.h"
  320. #endif
  321. #if ENABLED(I2C_POSITION_ENCODERS)
  322. #include "I2CPositionEncoder.h"
  323. #endif
  324. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  325. void gcode_M100();
  326. void M100_dump_routine(const char * const title, const char *start, const char *end);
  327. #endif
  328. #if ENABLED(G26_MESH_VALIDATION)
  329. bool g26_debug_flag; // =false
  330. void gcode_G26();
  331. #endif
  332. #if ENABLED(SDSUPPORT)
  333. CardReader card;
  334. #endif
  335. #if ENABLED(EXPERIMENTAL_I2CBUS)
  336. TWIBus i2c;
  337. #endif
  338. #if ENABLED(G38_PROBE_TARGET)
  339. bool G38_move = false,
  340. G38_endstop_hit = false;
  341. #endif
  342. #if ENABLED(AUTO_BED_LEVELING_UBL)
  343. #include "ubl.h"
  344. #endif
  345. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  346. int8_t active_coordinate_system = -1; // machine space
  347. float coordinate_system[MAX_COORDINATE_SYSTEMS][XYZ];
  348. #endif
  349. bool Running = true;
  350. uint8_t marlin_debug_flags = DEBUG_NONE;
  351. /**
  352. * Cartesian Current Position
  353. * Used to track the native machine position as moves are queued.
  354. * Used by 'buffer_line_to_current_position' to do a move after changing it.
  355. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  356. */
  357. float current_position[XYZE] = { 0 };
  358. /**
  359. * Cartesian Destination
  360. * The destination for a move, filled in by G-code movement commands,
  361. * and expected by functions like 'prepare_move_to_destination'.
  362. * Set with 'gcode_get_destination' or 'set_destination_from_current'.
  363. */
  364. float destination[XYZE] = { 0 };
  365. /**
  366. * axis_homed
  367. * Flags that each linear axis was homed.
  368. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  369. *
  370. * axis_known_position
  371. * Flags that the position is known in each linear axis. Set when homed.
  372. * Cleared whenever a stepper powers off, potentially losing its position.
  373. */
  374. uint8_t axis_homed, axis_known_position; // = 0
  375. /**
  376. * GCode line number handling. Hosts may opt to include line numbers when
  377. * sending commands to Marlin, and lines will be checked for sequentiality.
  378. * M110 N<int> sets the current line number.
  379. */
  380. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  381. /**
  382. * GCode Command Queue
  383. * A simple ring buffer of BUFSIZE command strings.
  384. *
  385. * Commands are copied into this buffer by the command injectors
  386. * (immediate, serial, sd card) and they are processed sequentially by
  387. * the main loop. The process_next_command function parses the next
  388. * command and hands off execution to individual handler functions.
  389. */
  390. uint8_t commands_in_queue = 0, // Count of commands in the queue
  391. cmd_queue_index_r = 0, // Ring buffer read (out) position
  392. cmd_queue_index_w = 0; // Ring buffer write (in) position
  393. char command_queue[BUFSIZE][MAX_CMD_SIZE];
  394. /**
  395. * Next Injected Command pointer. NULL if no commands are being injected.
  396. * Used by Marlin internally to ensure that commands initiated from within
  397. * are enqueued ahead of any pending serial or sd card commands.
  398. */
  399. static const char *injected_commands_P = NULL;
  400. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  401. TempUnit input_temp_units = TEMPUNIT_C;
  402. #endif
  403. /**
  404. * Feed rates are often configured with mm/m
  405. * but the planner and stepper like mm/s units.
  406. */
  407. static const float homing_feedrate_mm_s[] PROGMEM = {
  408. #if ENABLED(HANGPRINTER)
  409. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE),
  410. MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), MMM_TO_MMS(DUMMY_HOMING_FEEDRATE), 0
  411. #else
  412. #if ENABLED(DELTA)
  413. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  414. #else
  415. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  416. #endif
  417. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  418. #endif
  419. };
  420. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  421. float feedrate_mm_s = MMM_TO_MMS(1500.0f);
  422. static float saved_feedrate_mm_s;
  423. int16_t feedrate_percentage = 100, saved_feedrate_percentage;
  424. // Initialized by settings.load()
  425. bool axis_relative_modes[XYZE] = AXIS_RELATIVE_MODES;
  426. #if HAS_WORKSPACE_OFFSET
  427. #if HAS_POSITION_SHIFT
  428. // The distance that XYZ has been offset by G92. Reset by G28.
  429. float position_shift[XYZ] = { 0 };
  430. #endif
  431. #if HAS_HOME_OFFSET
  432. // This offset is added to the configured home position.
  433. // Set by M206, M428, or menu item. Saved to EEPROM.
  434. float home_offset[XYZ] = { 0 };
  435. #endif
  436. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  437. // The above two are combined to save on computes
  438. float workspace_offset[XYZ] = { 0 };
  439. #endif
  440. #endif
  441. // Software Endstops are based on the configured limits.
  442. float soft_endstop_min[XYZ] = { X_MIN_BED, Y_MIN_BED, Z_MIN_POS },
  443. soft_endstop_max[XYZ] = { X_MAX_BED, Y_MAX_BED, Z_MAX_POS };
  444. #if HAS_SOFTWARE_ENDSTOPS
  445. bool soft_endstops_enabled = true;
  446. #if IS_KINEMATIC
  447. float soft_endstop_radius, soft_endstop_radius_2;
  448. #endif
  449. #endif
  450. #if FAN_COUNT > 0
  451. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  452. #if ENABLED(EXTRA_FAN_SPEED)
  453. int16_t old_fanSpeeds[FAN_COUNT],
  454. new_fanSpeeds[FAN_COUNT];
  455. #endif
  456. #if ENABLED(PROBING_FANS_OFF)
  457. bool fans_paused; // = false;
  458. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  459. #endif
  460. #endif
  461. #if ENABLED(USE_CONTROLLER_FAN)
  462. int controllerFanSpeed; // = 0;
  463. #endif
  464. // The active extruder (tool). Set with T<extruder> command.
  465. uint8_t active_extruder; // = 0;
  466. // Relative Mode. Enable with G91, disable with G90.
  467. static bool relative_mode; // = false;
  468. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  469. volatile bool wait_for_heatup = true;
  470. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  471. #if HAS_RESUME_CONTINUE
  472. volatile bool wait_for_user; // = false;
  473. #endif
  474. #if HAS_AUTO_REPORTING || ENABLED(HOST_KEEPALIVE_FEATURE)
  475. bool suspend_auto_report; // = false
  476. #endif
  477. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  478. #if ENABLED(HANGPRINTER)
  479. const char axis_codes_hangprinter[ABCDE] = { 'A', 'B', 'C', 'D', 'E' };
  480. #define RAW_AXIS_CODES(I) axis_codes_hangprinter[I]
  481. #else
  482. #define RAW_AXIS_CODES(I) axis_codes[I]
  483. #endif
  484. // Number of characters read in the current line of serial input
  485. static int serial_count; // = 0;
  486. // Inactivity shutdown
  487. millis_t previous_move_ms; // = 0;
  488. static millis_t max_inactive_time; // = 0;
  489. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  490. // Buzzer - I2C on the LCD or a BEEPER_PIN
  491. #if ENABLED(LCD_USE_I2C_BUZZER)
  492. #define BUZZ(d,f) lcd_buzz(d, f)
  493. #elif PIN_EXISTS(BEEPER)
  494. Buzzer buzzer;
  495. #define BUZZ(d,f) buzzer.tone(d, f)
  496. #else
  497. #define BUZZ(d,f) NOOP
  498. #endif
  499. uint8_t target_extruder;
  500. #if HAS_BED_PROBE
  501. float zprobe_zoffset; // Initialized by settings.load()
  502. #endif
  503. #if HAS_ABL
  504. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  505. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  506. #elif defined(XY_PROBE_SPEED)
  507. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  508. #else
  509. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  510. #endif
  511. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  512. #if ENABLED(DELTA)
  513. #define ADJUST_DELTA(V) \
  514. if (planner.leveling_active) { \
  515. const float zadj = bilinear_z_offset(V); \
  516. delta[A_AXIS] += zadj; \
  517. delta[B_AXIS] += zadj; \
  518. delta[C_AXIS] += zadj; \
  519. }
  520. #else
  521. #define ADJUST_DELTA(V) if (planner.leveling_active) { delta[Z_AXIS] += bilinear_z_offset(V); }
  522. #endif
  523. #elif IS_KINEMATIC
  524. #define ADJUST_DELTA(V) NOOP
  525. #endif
  526. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  527. const static char msg_wait_for_bed_heating[] PROGMEM = "Wait for bed heating...\n";
  528. #endif
  529. // Extruder offsets
  530. #if HOTENDS > 1
  531. float hotend_offset[XYZ][HOTENDS]; // Initialized by settings.load()
  532. #endif
  533. #if HAS_Z_SERVO_PROBE
  534. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  535. #endif
  536. #if ENABLED(BARICUDA)
  537. uint8_t baricuda_valve_pressure = 0,
  538. baricuda_e_to_p_pressure = 0;
  539. #endif
  540. #if HAS_POWER_SWITCH
  541. bool powersupply_on;
  542. #if ENABLED(AUTO_POWER_CONTROL)
  543. #define PSU_ON() powerManager.power_on()
  544. #define PSU_OFF() powerManager.power_off()
  545. #else
  546. #define PSU_ON() PSU_PIN_ON()
  547. #define PSU_OFF() PSU_PIN_OFF()
  548. #endif
  549. #endif
  550. #if ENABLED(DELTA)
  551. float delta[ABC];
  552. // Initialized by settings.load()
  553. float delta_height,
  554. delta_endstop_adj[ABC] = { 0 },
  555. delta_radius,
  556. delta_tower_angle_trim[ABC],
  557. delta_tower[ABC][2],
  558. delta_diagonal_rod,
  559. delta_calibration_radius,
  560. delta_diagonal_rod_2_tower[ABC],
  561. delta_segments_per_second,
  562. delta_clip_start_height = Z_MAX_POS;
  563. float delta_safe_distance_from_top();
  564. #elif ENABLED(HANGPRINTER)
  565. float anchor_A_y,
  566. anchor_A_z,
  567. anchor_B_x,
  568. anchor_B_y,
  569. anchor_B_z,
  570. anchor_C_x,
  571. anchor_C_y,
  572. anchor_C_z,
  573. anchor_D_z,
  574. line_lengths[ABCD],
  575. line_lengths_origin[ABCD],
  576. delta_segments_per_second;
  577. #endif
  578. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  579. int bilinear_grid_spacing[2], bilinear_start[2];
  580. float bilinear_grid_factor[2],
  581. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  582. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  583. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  584. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  585. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  586. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  587. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  588. #else
  589. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  590. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  591. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  592. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  593. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  594. #endif
  595. #endif
  596. #if IS_SCARA
  597. // Float constants for SCARA calculations
  598. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  599. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  600. L2_2 = sq(float(L2));
  601. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  602. delta[ABC];
  603. #endif
  604. float cartes[XYZ] = { 0 };
  605. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  606. bool filament_sensor; // = false; // M405 turns on filament sensor control. M406 turns it off.
  607. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  608. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  609. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  610. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1], // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  611. filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  612. #endif
  613. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  614. AdvancedPauseMenuResponse advanced_pause_menu_response;
  615. float filament_change_unload_length[EXTRUDERS],
  616. filament_change_load_length[EXTRUDERS];
  617. #endif
  618. #if ENABLED(MIXING_EXTRUDER)
  619. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  620. #if MIXING_VIRTUAL_TOOLS > 1
  621. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  622. #endif
  623. #endif
  624. static bool send_ok[BUFSIZE];
  625. #if HAS_SERVOS
  626. Servo servo[NUM_SERVOS];
  627. #define MOVE_SERVO(I, P) servo[I].move(P)
  628. #if HAS_Z_SERVO_PROBE
  629. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[0])
  630. #define STOW_Z_SERVO() MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[1])
  631. #endif
  632. #endif
  633. #ifdef CHDK
  634. millis_t chdkHigh = 0;
  635. bool chdkActive = false;
  636. #endif
  637. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  638. MarlinBusyState busy_state = NOT_BUSY;
  639. static millis_t next_busy_signal_ms = 0;
  640. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  641. #else
  642. #define host_keepalive() NOOP
  643. #endif
  644. #if ENABLED(I2C_POSITION_ENCODERS)
  645. I2CPositionEncodersMgr I2CPEM;
  646. #endif
  647. #if ENABLED(CNC_WORKSPACE_PLANES)
  648. static WorkspacePlane workspace_plane = PLANE_XY;
  649. #endif
  650. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  651. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  652. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  653. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  654. static inline type array(const AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  655. typedef void __void_##CONFIG##__
  656. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  657. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  658. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  659. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  660. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  661. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  662. /**
  663. * ***************************************************************************
  664. * ******************************** FUNCTIONS ********************************
  665. * ***************************************************************************
  666. */
  667. void stop();
  668. void get_available_commands();
  669. void process_next_command();
  670. void process_parsed_command();
  671. void get_cartesian_from_steppers();
  672. void set_current_from_steppers_for_axis(const AxisEnum axis);
  673. #if ENABLED(ARC_SUPPORT)
  674. void plan_arc(const float (&cart)[XYZE], const float (&offset)[2], const bool clockwise);
  675. #endif
  676. #if ENABLED(BEZIER_CURVE_SUPPORT)
  677. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]);
  678. #endif
  679. void report_current_position();
  680. void report_current_position_detail();
  681. #if ENABLED(DEBUG_LEVELING_FEATURE)
  682. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  683. serialprintPGM(prefix);
  684. SERIAL_CHAR('(');
  685. SERIAL_ECHO(x);
  686. SERIAL_ECHOPAIR(", ", y);
  687. SERIAL_ECHOPAIR(", ", z);
  688. SERIAL_CHAR(')');
  689. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  690. }
  691. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  692. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  693. }
  694. #define DEBUG_POS(SUFFIX,VAR) do { \
  695. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  696. #endif
  697. /**
  698. * sync_plan_position
  699. *
  700. * Set the planner/stepper positions directly from current_position with
  701. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  702. *
  703. * This is not possible for Hangprinter because current_position and position are different sizes
  704. */
  705. void sync_plan_position() {
  706. #if DISABLED(HANGPRINTER)
  707. #if ENABLED(DEBUG_LEVELING_FEATURE)
  708. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  709. #endif
  710. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  711. #endif
  712. }
  713. void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_CART]); }
  714. #if IS_KINEMATIC
  715. inline void sync_plan_position_kinematic() {
  716. #if ENABLED(DEBUG_LEVELING_FEATURE)
  717. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  718. #endif
  719. planner.set_position_mm_kinematic(current_position);
  720. }
  721. #endif
  722. #if ENABLED(SDSUPPORT)
  723. #include "SdFatUtil.h"
  724. int freeMemory() { return SdFatUtil::FreeRam(); }
  725. #else
  726. extern "C" {
  727. extern char __bss_end;
  728. extern char __heap_start;
  729. extern void* __brkval;
  730. int freeMemory() {
  731. int free_memory;
  732. if (int(__brkval) == 0)
  733. free_memory = (int(&free_memory)) - (int(&__bss_end));
  734. else
  735. free_memory = (int(&free_memory)) - (int(__brkval));
  736. return free_memory;
  737. }
  738. }
  739. #endif // !SDSUPPORT
  740. #if ENABLED(DIGIPOT_I2C)
  741. extern void digipot_i2c_set_current(uint8_t channel, float current);
  742. extern void digipot_i2c_init();
  743. #endif
  744. /**
  745. * Inject the next "immediate" command, when possible, onto the front of the queue.
  746. * Return true if any immediate commands remain to inject.
  747. */
  748. static bool drain_injected_commands_P() {
  749. if (injected_commands_P != NULL) {
  750. size_t i = 0;
  751. char c, cmd[30];
  752. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  753. cmd[sizeof(cmd) - 1] = '\0';
  754. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  755. cmd[i] = '\0';
  756. if (enqueue_and_echo_command(cmd)) // success?
  757. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  758. }
  759. return (injected_commands_P != NULL); // return whether any more remain
  760. }
  761. /**
  762. * Record one or many commands to run from program memory.
  763. * Aborts the current queue, if any.
  764. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  765. */
  766. void enqueue_and_echo_commands_P(const char * const pgcode) {
  767. injected_commands_P = pgcode;
  768. (void)drain_injected_commands_P(); // first command executed asap (when possible)
  769. }
  770. /**
  771. * Clear the Marlin command queue
  772. */
  773. void clear_command_queue() {
  774. cmd_queue_index_r = cmd_queue_index_w = commands_in_queue = 0;
  775. }
  776. /**
  777. * Once a new command is in the ring buffer, call this to commit it
  778. */
  779. inline void _commit_command(bool say_ok) {
  780. send_ok[cmd_queue_index_w] = say_ok;
  781. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  782. commands_in_queue++;
  783. }
  784. /**
  785. * Copy a command from RAM into the main command buffer.
  786. * Return true if the command was successfully added.
  787. * Return false for a full buffer, or if the 'command' is a comment.
  788. */
  789. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  790. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  791. strcpy(command_queue[cmd_queue_index_w], cmd);
  792. _commit_command(say_ok);
  793. return true;
  794. }
  795. /**
  796. * Enqueue with Serial Echo
  797. */
  798. bool enqueue_and_echo_command(const char* cmd) {
  799. if (_enqueuecommand(cmd)) {
  800. SERIAL_ECHO_START();
  801. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  802. SERIAL_CHAR('"');
  803. SERIAL_EOL();
  804. return true;
  805. }
  806. return false;
  807. }
  808. #if HAS_QUEUE_NOW
  809. void enqueue_and_echo_command_now(const char* cmd) {
  810. while (!enqueue_and_echo_command(cmd)) idle();
  811. }
  812. #if HAS_LCD_QUEUE_NOW
  813. void enqueue_and_echo_commands_now_P(const char * const pgcode) {
  814. enqueue_and_echo_commands_P(pgcode);
  815. while (drain_injected_commands_P()) idle();
  816. }
  817. #endif
  818. #endif
  819. void setup_killpin() {
  820. #if HAS_KILL
  821. SET_INPUT_PULLUP(KILL_PIN);
  822. #endif
  823. }
  824. void setup_powerhold() {
  825. #if HAS_SUICIDE
  826. OUT_WRITE(SUICIDE_PIN, HIGH);
  827. #endif
  828. #if HAS_POWER_SWITCH
  829. #if ENABLED(PS_DEFAULT_OFF)
  830. powersupply_on = true; PSU_OFF();
  831. #else
  832. powersupply_on = false; PSU_ON();
  833. #endif
  834. #endif
  835. }
  836. void suicide() {
  837. #if HAS_SUICIDE
  838. OUT_WRITE(SUICIDE_PIN, LOW);
  839. #endif
  840. }
  841. void servo_init() {
  842. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  843. servo[0].attach(SERVO0_PIN);
  844. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  845. #endif
  846. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  847. servo[1].attach(SERVO1_PIN);
  848. servo[1].detach();
  849. #endif
  850. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  851. servo[2].attach(SERVO2_PIN);
  852. servo[2].detach();
  853. #endif
  854. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  855. servo[3].attach(SERVO3_PIN);
  856. servo[3].detach();
  857. #endif
  858. #if HAS_Z_SERVO_PROBE
  859. /**
  860. * Set position of Z Servo Endstop
  861. *
  862. * The servo might be deployed and positioned too low to stow
  863. * when starting up the machine or rebooting the board.
  864. * There's no way to know where the nozzle is positioned until
  865. * homing has been done - no homing with z-probe without init!
  866. *
  867. */
  868. STOW_Z_SERVO();
  869. #endif
  870. }
  871. /**
  872. * Stepper Reset (RigidBoard, et.al.)
  873. */
  874. #if HAS_STEPPER_RESET
  875. void disableStepperDrivers() {
  876. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  877. }
  878. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  879. #endif
  880. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  881. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  882. i2c.receive(bytes);
  883. }
  884. void i2c_on_request() { // just send dummy data for now
  885. i2c.reply("Hello World!\n");
  886. }
  887. #endif
  888. void gcode_line_error(const char* err, bool doFlush = true) {
  889. SERIAL_ERROR_START();
  890. serialprintPGM(err);
  891. SERIAL_ERRORLN(gcode_LastN);
  892. //Serial.println(gcode_N);
  893. if (doFlush) flush_and_request_resend();
  894. serial_count = 0;
  895. }
  896. /**
  897. * Get all commands waiting on the serial port and queue them.
  898. * Exit when the buffer is full or when no more characters are
  899. * left on the serial port.
  900. */
  901. inline void get_serial_commands() {
  902. static char serial_line_buffer[MAX_CMD_SIZE];
  903. static bool serial_comment_mode = false;
  904. // If the command buffer is empty for too long,
  905. // send "wait" to indicate Marlin is still waiting.
  906. #if NO_TIMEOUTS > 0
  907. static millis_t last_command_time = 0;
  908. const millis_t ms = millis();
  909. if (commands_in_queue == 0 && !MYSERIAL0.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  910. SERIAL_ECHOLNPGM(MSG_WAIT);
  911. last_command_time = ms;
  912. }
  913. #endif
  914. /**
  915. * Loop while serial characters are incoming and the queue is not full
  916. */
  917. int c;
  918. while (commands_in_queue < BUFSIZE && (c = MYSERIAL0.read()) >= 0) {
  919. char serial_char = c;
  920. /**
  921. * If the character ends the line
  922. */
  923. if (serial_char == '\n' || serial_char == '\r') {
  924. serial_comment_mode = false; // end of line == end of comment
  925. // Skip empty lines and comments
  926. if (!serial_count) { thermalManager.manage_heater(); continue; }
  927. serial_line_buffer[serial_count] = 0; // Terminate string
  928. serial_count = 0; // Reset buffer
  929. char* command = serial_line_buffer;
  930. while (*command == ' ') command++; // Skip leading spaces
  931. char *npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  932. if (npos) {
  933. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  934. if (M110) {
  935. char* n2pos = strchr(command + 4, 'N');
  936. if (n2pos) npos = n2pos;
  937. }
  938. gcode_N = strtol(npos + 1, NULL, 10);
  939. if (gcode_N != gcode_LastN + 1 && !M110)
  940. return gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  941. char *apos = strrchr(command, '*');
  942. if (apos) {
  943. uint8_t checksum = 0, count = uint8_t(apos - command);
  944. while (count) checksum ^= command[--count];
  945. if (strtol(apos + 1, NULL, 10) != checksum)
  946. return gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  947. }
  948. else
  949. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  950. gcode_LastN = gcode_N;
  951. }
  952. #if ENABLED(SDSUPPORT)
  953. else if (card.saving && strcmp(command, "M29") != 0) // No line number with M29 in Pronterface
  954. return gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  955. #endif
  956. // Movement commands alert when stopped
  957. if (IsStopped()) {
  958. char* gpos = strchr(command, 'G');
  959. if (gpos) {
  960. switch (strtol(gpos + 1, NULL, 10)) {
  961. case 0:
  962. case 1:
  963. #if ENABLED(ARC_SUPPORT)
  964. case 2:
  965. case 3:
  966. #endif
  967. #if ENABLED(BEZIER_CURVE_SUPPORT)
  968. case 5:
  969. #endif
  970. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  971. LCD_MESSAGEPGM(MSG_STOPPED);
  972. break;
  973. }
  974. }
  975. }
  976. #if DISABLED(EMERGENCY_PARSER)
  977. // Process critical commands early
  978. if (strcmp(command, "M108") == 0) {
  979. wait_for_heatup = false;
  980. #if ENABLED(NEWPANEL)
  981. wait_for_user = false;
  982. #endif
  983. }
  984. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  985. if (strcmp(command, "M410") == 0) quickstop_stepper();
  986. #endif
  987. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  988. last_command_time = ms;
  989. #endif
  990. // Add the command to the queue
  991. _enqueuecommand(serial_line_buffer, true);
  992. }
  993. else if (serial_count >= MAX_CMD_SIZE - 1) {
  994. // Keep fetching, but ignore normal characters beyond the max length
  995. // The command will be injected when EOL is reached
  996. }
  997. else if (serial_char == '\\') { // Handle escapes
  998. if ((c = MYSERIAL0.read()) >= 0 && !serial_comment_mode) // if we have one more character, copy it over
  999. serial_line_buffer[serial_count++] = (char)c;
  1000. // otherwise do nothing
  1001. }
  1002. else { // it's not a newline, carriage return or escape char
  1003. if (serial_char == ';') serial_comment_mode = true;
  1004. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1005. }
  1006. } // queue has space, serial has data
  1007. }
  1008. #if ENABLED(SDSUPPORT)
  1009. #if ENABLED(PRINTER_EVENT_LEDS) && HAS_RESUME_CONTINUE
  1010. static bool lights_off_after_print; // = false
  1011. #endif
  1012. /**
  1013. * Get commands from the SD Card until the command buffer is full
  1014. * or until the end of the file is reached. The special character '#'
  1015. * can also interrupt buffering.
  1016. */
  1017. inline void get_sdcard_commands() {
  1018. static bool stop_buffering = false,
  1019. sd_comment_mode = false;
  1020. if (!card.sdprinting) return;
  1021. /**
  1022. * '#' stops reading from SD to the buffer prematurely, so procedural
  1023. * macro calls are possible. If it occurs, stop_buffering is triggered
  1024. * and the buffer is run dry; this character _can_ occur in serial com
  1025. * due to checksums, however, no checksums are used in SD printing.
  1026. */
  1027. if (commands_in_queue == 0) stop_buffering = false;
  1028. uint16_t sd_count = 0;
  1029. bool card_eof = card.eof();
  1030. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1031. const int16_t n = card.get();
  1032. char sd_char = (char)n;
  1033. card_eof = card.eof();
  1034. if (card_eof || n == -1
  1035. || sd_char == '\n' || sd_char == '\r'
  1036. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1037. ) {
  1038. if (card_eof) {
  1039. card.printingHasFinished();
  1040. if (card.sdprinting)
  1041. sd_count = 0; // If a sub-file was printing, continue from call point
  1042. else {
  1043. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1044. #if ENABLED(PRINTER_EVENT_LEDS)
  1045. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1046. leds.set_green();
  1047. #if HAS_RESUME_CONTINUE
  1048. lights_off_after_print = true;
  1049. enqueue_and_echo_commands_P(PSTR("M0 S"
  1050. #if ENABLED(NEWPANEL)
  1051. "1800"
  1052. #else
  1053. "60"
  1054. #endif
  1055. ));
  1056. #else
  1057. safe_delay(2000);
  1058. leds.set_off();
  1059. #endif
  1060. #endif // PRINTER_EVENT_LEDS
  1061. }
  1062. }
  1063. else if (n == -1) {
  1064. SERIAL_ERROR_START();
  1065. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1066. }
  1067. if (sd_char == '#') stop_buffering = true;
  1068. sd_comment_mode = false; // for new command
  1069. // Skip empty lines and comments
  1070. if (!sd_count) { thermalManager.manage_heater(); continue; }
  1071. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1072. sd_count = 0; // clear sd line buffer
  1073. _commit_command(false);
  1074. }
  1075. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1076. /**
  1077. * Keep fetching, but ignore normal characters beyond the max length
  1078. * The command will be injected when EOL is reached
  1079. */
  1080. }
  1081. else {
  1082. if (sd_char == ';') sd_comment_mode = true;
  1083. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1084. }
  1085. }
  1086. }
  1087. #if ENABLED(POWER_LOSS_RECOVERY)
  1088. inline bool drain_job_recovery_commands() {
  1089. static uint8_t job_recovery_commands_index = 0; // Resets on reboot
  1090. if (job_recovery_commands_count) {
  1091. if (_enqueuecommand(job_recovery_commands[job_recovery_commands_index])) {
  1092. ++job_recovery_commands_index;
  1093. if (!--job_recovery_commands_count) job_recovery_phase = JOB_RECOVERY_DONE;
  1094. }
  1095. return true;
  1096. }
  1097. return false;
  1098. }
  1099. #endif
  1100. #endif // SDSUPPORT
  1101. /**
  1102. * Add to the circular command queue the next command from:
  1103. * - The command-injection queue (injected_commands_P)
  1104. * - The active serial input (usually USB)
  1105. * - Commands left in the queue after power-loss
  1106. * - The SD card file being actively printed
  1107. */
  1108. void get_available_commands() {
  1109. // Immediate commands block the other queues
  1110. if (drain_injected_commands_P()) return;
  1111. get_serial_commands();
  1112. #if ENABLED(POWER_LOSS_RECOVERY)
  1113. // Commands for power-loss recovery take precedence
  1114. if (job_recovery_phase == JOB_RECOVERY_YES && drain_job_recovery_commands()) return;
  1115. #endif
  1116. #if ENABLED(SDSUPPORT)
  1117. get_sdcard_commands();
  1118. #endif
  1119. }
  1120. /**
  1121. * Set target_extruder from the T parameter or the active_extruder
  1122. *
  1123. * Returns TRUE if the target is invalid
  1124. */
  1125. bool get_target_extruder_from_command(const uint16_t code) {
  1126. if (parser.seenval('T')) {
  1127. const int8_t e = parser.value_byte();
  1128. if (e >= EXTRUDERS) {
  1129. SERIAL_ECHO_START();
  1130. SERIAL_CHAR('M');
  1131. SERIAL_ECHO(code);
  1132. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1133. return true;
  1134. }
  1135. target_extruder = e;
  1136. }
  1137. else
  1138. target_extruder = active_extruder;
  1139. return false;
  1140. }
  1141. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1142. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1143. #endif
  1144. #if ENABLED(DUAL_X_CARRIAGE)
  1145. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1146. static float x_home_pos(const int extruder) {
  1147. if (extruder == 0)
  1148. return base_home_pos(X_AXIS);
  1149. else
  1150. /**
  1151. * In dual carriage mode the extruder offset provides an override of the
  1152. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1153. * This allows soft recalibration of the second extruder home position
  1154. * without firmware reflash (through the M218 command).
  1155. */
  1156. return hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS;
  1157. }
  1158. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1159. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1160. static bool active_extruder_parked = false; // used in mode 1 & 2
  1161. static float raised_parked_position[XYZE]; // used in mode 1
  1162. static millis_t delayed_move_time = 0; // used in mode 1
  1163. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1164. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1165. #endif // DUAL_X_CARRIAGE
  1166. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE) || ENABLED(DELTA)
  1167. /**
  1168. * Software endstops can be used to monitor the open end of
  1169. * an axis that has a hardware endstop on the other end. Or
  1170. * they can prevent axes from moving past endstops and grinding.
  1171. *
  1172. * To keep doing their job as the coordinate system changes,
  1173. * the software endstop positions must be refreshed to remain
  1174. * at the same positions relative to the machine.
  1175. */
  1176. void update_software_endstops(const AxisEnum axis) {
  1177. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1178. workspace_offset[axis] = home_offset[axis] + position_shift[axis];
  1179. #endif
  1180. #if ENABLED(DUAL_X_CARRIAGE)
  1181. if (axis == X_AXIS) {
  1182. // In Dual X mode hotend_offset[X] is T1's home position
  1183. const float dual_max_x = MAX(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1184. if (active_extruder != 0) {
  1185. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1186. soft_endstop_min[X_AXIS] = X2_MIN_POS;
  1187. soft_endstop_max[X_AXIS] = dual_max_x;
  1188. }
  1189. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1190. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1191. // but not so far to the right that T1 would move past the end
  1192. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS);
  1193. soft_endstop_max[X_AXIS] = MIN(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset);
  1194. }
  1195. else {
  1196. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1197. soft_endstop_min[axis] = base_min_pos(axis);
  1198. soft_endstop_max[axis] = base_max_pos(axis);
  1199. }
  1200. }
  1201. #elif ENABLED(DELTA)
  1202. soft_endstop_min[axis] = base_min_pos(axis);
  1203. soft_endstop_max[axis] = axis == Z_AXIS ? delta_height
  1204. #if HAS_BED_PROBE
  1205. - zprobe_zoffset
  1206. #endif
  1207. : base_max_pos(axis);
  1208. #else
  1209. soft_endstop_min[axis] = base_min_pos(axis);
  1210. soft_endstop_max[axis] = base_max_pos(axis);
  1211. #endif
  1212. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1213. if (DEBUGGING(LEVELING)) {
  1214. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1215. #if HAS_HOME_OFFSET
  1216. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1217. #endif
  1218. #if HAS_POSITION_SHIFT
  1219. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1220. #endif
  1221. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1222. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1223. }
  1224. #endif
  1225. #if ENABLED(DELTA)
  1226. switch (axis) {
  1227. #if HAS_SOFTWARE_ENDSTOPS
  1228. case X_AXIS:
  1229. case Y_AXIS:
  1230. // Get a minimum radius for clamping
  1231. soft_endstop_radius = MIN3(ABS(MAX(soft_endstop_min[X_AXIS], soft_endstop_min[Y_AXIS])), soft_endstop_max[X_AXIS], soft_endstop_max[Y_AXIS]);
  1232. soft_endstop_radius_2 = sq(soft_endstop_radius);
  1233. break;
  1234. #endif
  1235. case Z_AXIS:
  1236. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1237. default: break;
  1238. }
  1239. #endif
  1240. }
  1241. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE || DELTA
  1242. #if HAS_M206_COMMAND
  1243. /**
  1244. * Change the home offset for an axis.
  1245. * Also refreshes the workspace offset.
  1246. */
  1247. static void set_home_offset(const AxisEnum axis, const float v) {
  1248. home_offset[axis] = v;
  1249. update_software_endstops(axis);
  1250. }
  1251. #endif // HAS_M206_COMMAND
  1252. /**
  1253. * Set an axis' current position to its home position (after homing).
  1254. *
  1255. * For Core and Cartesian robots this applies one-to-one when an
  1256. * individual axis has been homed.
  1257. *
  1258. * DELTA should wait until all homing is done before setting the XYZ
  1259. * current_position to home, because homing is a single operation.
  1260. * In the case where the axis positions are already known and previously
  1261. * homed, DELTA could home to X or Y individually by moving either one
  1262. * to the center. However, homing Z always homes XY and Z.
  1263. *
  1264. * SCARA should wait until all XY homing is done before setting the XY
  1265. * current_position to home, because neither X nor Y is at home until
  1266. * both are at home. Z can however be homed individually.
  1267. *
  1268. * Callers must sync the planner position after calling this!
  1269. */
  1270. static void set_axis_is_at_home(const AxisEnum axis) {
  1271. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1272. if (DEBUGGING(LEVELING)) {
  1273. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1274. SERIAL_CHAR(')');
  1275. SERIAL_EOL();
  1276. }
  1277. #endif
  1278. SBI(axis_known_position, axis);
  1279. SBI(axis_homed, axis);
  1280. #if HAS_POSITION_SHIFT
  1281. position_shift[axis] = 0;
  1282. update_software_endstops(axis);
  1283. #endif
  1284. #if ENABLED(DUAL_X_CARRIAGE)
  1285. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1286. current_position[X_AXIS] = x_home_pos(active_extruder);
  1287. return;
  1288. }
  1289. #endif
  1290. #if ENABLED(MORGAN_SCARA)
  1291. /**
  1292. * Morgan SCARA homes XY at the same time
  1293. */
  1294. if (axis == X_AXIS || axis == Y_AXIS) {
  1295. float homeposition[XYZ] = {
  1296. base_home_pos(X_AXIS),
  1297. base_home_pos(Y_AXIS),
  1298. base_home_pos(Z_AXIS)
  1299. };
  1300. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1301. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1302. /**
  1303. * Get Home position SCARA arm angles using inverse kinematics,
  1304. * and calculate homing offset using forward kinematics
  1305. */
  1306. inverse_kinematics(homeposition);
  1307. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1308. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1309. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1310. current_position[axis] = cartes[axis];
  1311. /**
  1312. * SCARA home positions are based on configuration since the actual
  1313. * limits are determined by the inverse kinematic transform.
  1314. */
  1315. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1316. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1317. }
  1318. else
  1319. #elif ENABLED(DELTA)
  1320. current_position[axis] = (axis == Z_AXIS ? delta_height
  1321. #if HAS_BED_PROBE
  1322. - zprobe_zoffset
  1323. #endif
  1324. : base_home_pos(axis));
  1325. #else
  1326. current_position[axis] = base_home_pos(axis);
  1327. #endif
  1328. /**
  1329. * Z Probe Z Homing? Account for the probe's Z offset.
  1330. */
  1331. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1332. if (axis == Z_AXIS) {
  1333. #if HOMING_Z_WITH_PROBE
  1334. current_position[Z_AXIS] -= zprobe_zoffset;
  1335. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1336. if (DEBUGGING(LEVELING)) {
  1337. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1338. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1339. }
  1340. #endif
  1341. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1342. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1343. #endif
  1344. }
  1345. #endif
  1346. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1347. if (DEBUGGING(LEVELING)) {
  1348. #if HAS_HOME_OFFSET
  1349. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1350. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1351. #endif
  1352. DEBUG_POS("", current_position);
  1353. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1354. SERIAL_CHAR(')');
  1355. SERIAL_EOL();
  1356. }
  1357. #endif
  1358. #if ENABLED(I2C_POSITION_ENCODERS)
  1359. I2CPEM.homed(axis);
  1360. #endif
  1361. }
  1362. /**
  1363. * Homing bump feedrate (mm/s)
  1364. */
  1365. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1366. #if HOMING_Z_WITH_PROBE
  1367. if (axis == Z_AXIS) return MMM_TO_MMS(Z_PROBE_SPEED_SLOW);
  1368. #endif
  1369. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1370. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1371. if (hbd < 1) {
  1372. hbd = 10;
  1373. SERIAL_ECHO_START();
  1374. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1375. }
  1376. return homing_feedrate(axis) / hbd;
  1377. }
  1378. /**
  1379. * Some planner shorthand inline functions
  1380. */
  1381. /**
  1382. * Move the planner to the current position from wherever it last moved
  1383. * (or from wherever it has been told it is located).
  1384. *
  1385. * Impossible on Hangprinter because current_position and position are of different sizes
  1386. */
  1387. inline void buffer_line_to_current_position() {
  1388. #if DISABLED(HANGPRINTER) // emptying this function probably breaks do_blocking_move_to()
  1389. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], feedrate_mm_s, active_extruder);
  1390. #endif
  1391. }
  1392. /**
  1393. * Move the planner to the position stored in the destination array, which is
  1394. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1395. */
  1396. inline void buffer_line_to_destination(const float &fr_mm_s) {
  1397. #if ENABLED(HANGPRINTER)
  1398. UNUSED(fr_mm_s);
  1399. #else
  1400. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_CART], fr_mm_s, active_extruder);
  1401. #endif
  1402. }
  1403. #if IS_KINEMATIC
  1404. /**
  1405. * Calculate delta, start a line, and set current_position to destination
  1406. */
  1407. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0) {
  1408. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1409. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1410. #endif
  1411. #if UBL_SEGMENTED
  1412. // ubl segmented line will do z-only moves in single segment
  1413. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1414. #else
  1415. if ( current_position[X_AXIS] == destination[X_AXIS]
  1416. && current_position[Y_AXIS] == destination[Y_AXIS]
  1417. && current_position[Z_AXIS] == destination[Z_AXIS]
  1418. && current_position[E_CART] == destination[E_CART]
  1419. ) return;
  1420. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1421. #endif
  1422. set_current_from_destination();
  1423. }
  1424. #endif // IS_KINEMATIC
  1425. /**
  1426. * Plan a move to (X, Y, Z) and set the current_position.
  1427. * The final current_position may not be the one that was requested
  1428. * Caution: 'destination' is modified by this function.
  1429. */
  1430. void do_blocking_move_to(const float rx, const float ry, const float rz, const float &fr_mm_s/*=0.0*/) {
  1431. const float old_feedrate_mm_s = feedrate_mm_s;
  1432. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1433. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, LOGICAL_X_POSITION(rx), LOGICAL_Y_POSITION(ry), LOGICAL_Z_POSITION(rz));
  1434. #endif
  1435. const float z_feedrate = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1436. #if ENABLED(DELTA)
  1437. if (!position_is_reachable(rx, ry)) return;
  1438. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1439. set_destination_from_current(); // sync destination at the start
  1440. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1441. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_from_current", destination);
  1442. #endif
  1443. // when in the danger zone
  1444. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1445. if (rz > delta_clip_start_height) { // staying in the danger zone
  1446. destination[X_AXIS] = rx; // move directly (uninterpolated)
  1447. destination[Y_AXIS] = ry;
  1448. destination[Z_AXIS] = rz;
  1449. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1450. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1451. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1452. #endif
  1453. return;
  1454. }
  1455. destination[Z_AXIS] = delta_clip_start_height;
  1456. prepare_uninterpolated_move_to_destination(); // set_current_from_destination
  1457. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1458. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1459. #endif
  1460. }
  1461. if (rz > current_position[Z_AXIS]) { // raising?
  1462. destination[Z_AXIS] = rz;
  1463. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1464. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1465. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1466. #endif
  1467. }
  1468. destination[X_AXIS] = rx;
  1469. destination[Y_AXIS] = ry;
  1470. prepare_move_to_destination(); // set_current_from_destination
  1471. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1472. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1473. #endif
  1474. if (rz < current_position[Z_AXIS]) { // lowering?
  1475. destination[Z_AXIS] = rz;
  1476. prepare_uninterpolated_move_to_destination(z_feedrate); // set_current_from_destination
  1477. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1478. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1479. #endif
  1480. }
  1481. #elif IS_SCARA
  1482. if (!position_is_reachable(rx, ry)) return;
  1483. set_destination_from_current();
  1484. // If Z needs to raise, do it before moving XY
  1485. if (destination[Z_AXIS] < rz) {
  1486. destination[Z_AXIS] = rz;
  1487. prepare_uninterpolated_move_to_destination(z_feedrate);
  1488. }
  1489. destination[X_AXIS] = rx;
  1490. destination[Y_AXIS] = ry;
  1491. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1492. // If Z needs to lower, do it after moving XY
  1493. if (destination[Z_AXIS] > rz) {
  1494. destination[Z_AXIS] = rz;
  1495. prepare_uninterpolated_move_to_destination(z_feedrate);
  1496. }
  1497. #else
  1498. // If Z needs to raise, do it before moving XY
  1499. if (current_position[Z_AXIS] < rz) {
  1500. feedrate_mm_s = z_feedrate;
  1501. current_position[Z_AXIS] = rz;
  1502. buffer_line_to_current_position();
  1503. }
  1504. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1505. current_position[X_AXIS] = rx;
  1506. current_position[Y_AXIS] = ry;
  1507. buffer_line_to_current_position();
  1508. // If Z needs to lower, do it after moving XY
  1509. if (current_position[Z_AXIS] > rz) {
  1510. feedrate_mm_s = z_feedrate;
  1511. current_position[Z_AXIS] = rz;
  1512. buffer_line_to_current_position();
  1513. }
  1514. #endif
  1515. planner.synchronize();
  1516. feedrate_mm_s = old_feedrate_mm_s;
  1517. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1518. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1519. #endif
  1520. }
  1521. void do_blocking_move_to_x(const float &rx, const float &fr_mm_s/*=0.0*/) {
  1522. do_blocking_move_to(rx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1523. }
  1524. void do_blocking_move_to_z(const float &rz, const float &fr_mm_s/*=0.0*/) {
  1525. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], rz, fr_mm_s);
  1526. }
  1527. void do_blocking_move_to_xy(const float &rx, const float &ry, const float &fr_mm_s/*=0.0*/) {
  1528. do_blocking_move_to(rx, ry, current_position[Z_AXIS], fr_mm_s);
  1529. }
  1530. //
  1531. // Prepare to do endstop or probe moves
  1532. // with custom feedrates.
  1533. //
  1534. // - Save current feedrates
  1535. // - Reset the rate multiplier
  1536. // - Reset the command timeout
  1537. // - Enable the endstops (for endstop moves)
  1538. //
  1539. void setup_for_endstop_or_probe_move() {
  1540. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1541. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1542. #endif
  1543. saved_feedrate_mm_s = feedrate_mm_s;
  1544. saved_feedrate_percentage = feedrate_percentage;
  1545. feedrate_percentage = 100;
  1546. }
  1547. void clean_up_after_endstop_or_probe_move() {
  1548. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1549. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1550. #endif
  1551. feedrate_mm_s = saved_feedrate_mm_s;
  1552. feedrate_percentage = saved_feedrate_percentage;
  1553. }
  1554. #if HAS_AXIS_UNHOMED_ERR
  1555. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1556. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1557. const bool xx = x && !TEST(axis_known_position, X_AXIS),
  1558. yy = y && !TEST(axis_known_position, Y_AXIS),
  1559. zz = z && !TEST(axis_known_position, Z_AXIS);
  1560. #else
  1561. const bool xx = x && !TEST(axis_homed, X_AXIS),
  1562. yy = y && !TEST(axis_homed, Y_AXIS),
  1563. zz = z && !TEST(axis_homed, Z_AXIS);
  1564. #endif
  1565. if (xx || yy || zz) {
  1566. SERIAL_ECHO_START();
  1567. SERIAL_ECHOPGM(MSG_HOME " ");
  1568. if (xx) SERIAL_ECHOPGM(MSG_X);
  1569. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1570. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1571. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1572. #if ENABLED(ULTRA_LCD)
  1573. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1574. #endif
  1575. return true;
  1576. }
  1577. return false;
  1578. }
  1579. #endif // HAS_AXIS_UNHOMED_ERR
  1580. #if ENABLED(Z_PROBE_SLED)
  1581. #ifndef SLED_DOCKING_OFFSET
  1582. #define SLED_DOCKING_OFFSET 0
  1583. #endif
  1584. /**
  1585. * Method to dock/undock a sled designed by Charles Bell.
  1586. *
  1587. * stow[in] If false, move to MAX_X and engage the solenoid
  1588. * If true, move to MAX_X and release the solenoid
  1589. */
  1590. static void dock_sled(bool stow) {
  1591. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1592. if (DEBUGGING(LEVELING)) {
  1593. SERIAL_ECHOPAIR("dock_sled(", stow);
  1594. SERIAL_CHAR(')');
  1595. SERIAL_EOL();
  1596. }
  1597. #endif
  1598. // Dock sled a bit closer to ensure proper capturing
  1599. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1600. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1601. WRITE(SOL1_PIN, !stow); // switch solenoid
  1602. #endif
  1603. }
  1604. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1605. FORCE_INLINE void do_blocking_move_to(const float (&raw)[XYZ], const float &fr_mm_s) {
  1606. do_blocking_move_to(raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS], fr_mm_s);
  1607. }
  1608. void run_deploy_moves_script() {
  1609. #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)
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1615. #endif
  1616. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1617. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1618. #endif
  1619. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1620. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1621. #endif
  1622. const float deploy_1[] = { Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z };
  1623. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1624. #endif
  1625. #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)
  1626. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1627. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1628. #endif
  1629. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1630. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1631. #endif
  1632. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1633. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1634. #endif
  1635. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1636. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1637. #endif
  1638. const float deploy_2[] = { Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z };
  1639. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1640. #endif
  1641. #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)
  1642. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1643. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1646. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1647. #endif
  1648. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1649. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1650. #endif
  1651. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1652. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1653. #endif
  1654. const float deploy_3[] = { Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z };
  1655. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1656. #endif
  1657. #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)
  1658. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1659. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1660. #endif
  1661. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1662. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1663. #endif
  1664. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1665. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1666. #endif
  1667. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1668. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1669. #endif
  1670. const float deploy_4[] = { Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z };
  1671. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1672. #endif
  1673. #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)
  1674. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1675. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1676. #endif
  1677. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1678. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1679. #endif
  1680. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1681. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1682. #endif
  1683. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1684. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1685. #endif
  1686. const float deploy_5[] = { Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z };
  1687. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1688. #endif
  1689. }
  1690. void run_stow_moves_script() {
  1691. #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)
  1692. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1693. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1694. #endif
  1695. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1696. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1697. #endif
  1698. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1699. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1700. #endif
  1701. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1702. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1703. #endif
  1704. const float stow_1[] = { Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z };
  1705. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1706. #endif
  1707. #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)
  1708. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1709. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1710. #endif
  1711. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1712. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1713. #endif
  1714. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1715. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1716. #endif
  1717. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1718. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1719. #endif
  1720. const float stow_2[] = { Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z };
  1721. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1722. #endif
  1723. #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)
  1724. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1725. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1726. #endif
  1727. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1728. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1729. #endif
  1730. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1731. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1732. #endif
  1733. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1734. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1735. #endif
  1736. const float stow_3[] = { Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z };
  1737. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1738. #endif
  1739. #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)
  1740. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1741. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1742. #endif
  1743. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1744. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1745. #endif
  1746. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1747. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1748. #endif
  1749. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1750. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1751. #endif
  1752. const float stow_4[] = { Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z };
  1753. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1754. #endif
  1755. #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)
  1756. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1757. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1758. #endif
  1759. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1760. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1761. #endif
  1762. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1763. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1764. #endif
  1765. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1766. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1767. #endif
  1768. const float stow_5[] = { Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z };
  1769. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1770. #endif
  1771. }
  1772. #endif // Z_PROBE_ALLEN_KEY
  1773. #if ENABLED(PROBING_FANS_OFF)
  1774. void fans_pause(const bool p) {
  1775. if (p != fans_paused) {
  1776. fans_paused = p;
  1777. if (p)
  1778. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1779. paused_fanSpeeds[x] = fanSpeeds[x];
  1780. fanSpeeds[x] = 0;
  1781. }
  1782. else
  1783. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1784. fanSpeeds[x] = paused_fanSpeeds[x];
  1785. }
  1786. }
  1787. #endif // PROBING_FANS_OFF
  1788. #if HAS_BED_PROBE
  1789. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1790. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1791. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1792. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1793. #else
  1794. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1795. #endif
  1796. #endif
  1797. #if QUIET_PROBING
  1798. void probing_pause(const bool p) {
  1799. #if ENABLED(PROBING_HEATERS_OFF)
  1800. thermalManager.pause(p);
  1801. #endif
  1802. #if ENABLED(PROBING_FANS_OFF)
  1803. fans_pause(p);
  1804. #endif
  1805. if (p) safe_delay(
  1806. #if DELAY_BEFORE_PROBING > 25
  1807. DELAY_BEFORE_PROBING
  1808. #else
  1809. 25
  1810. #endif
  1811. );
  1812. }
  1813. #endif // QUIET_PROBING
  1814. #if ENABLED(BLTOUCH)
  1815. typedef unsigned char BLTCommand;
  1816. void bltouch_init(const bool set_voltage=false);
  1817. bool bltouch_last_written_mode; // Initialized by settings.load, 0 = Open Drain; 1 = 5V Drain
  1818. bool bltouch_triggered() {
  1819. return (
  1820. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  1821. READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING
  1822. #else
  1823. READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING
  1824. #endif
  1825. );
  1826. }
  1827. bool bltouch_command(const BLTCommand cmd, const millis_t &ms) {
  1828. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1829. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("BLTouch Command :", cmd);
  1830. #endif
  1831. MOVE_SERVO(Z_PROBE_SERVO_NR, cmd);
  1832. safe_delay(MAX(ms, (uint32_t)BLTOUCH_DELAY)); // BLTOUCH_DELAY is also the *minimum* delay
  1833. return bltouch_triggered();
  1834. }
  1835. // Native BLTouch commands ("Underscore"...), used in lcd menus and internally
  1836. void _bltouch_reset() { bltouch_command(BLTOUCH_RESET, BLTOUCH_RESET_DELAY); }
  1837. void _bltouch_selftest() { bltouch_command(BLTOUCH_SELFTEST, BLTOUCH_DELAY); }
  1838. void _bltouch_set_SW_mode() { bltouch_command(BLTOUCH_SW_MODE, BLTOUCH_DELAY); }
  1839. void _bltouch_set_5V_mode() { bltouch_command(BLTOUCH_5V_MODE, BLTOUCH_SET5V_DELAY); }
  1840. void _bltouch_set_OD_mode() { bltouch_command(BLTOUCH_OD_MODE, BLTOUCH_SETOD_DELAY); }
  1841. void _bltouch_mode_store() { bltouch_command(BLTOUCH_MODE_STORE, BLTOUCH_MODE_STORE_DELAY); }
  1842. void _bltouch_deploy() { bltouch_command(BLTOUCH_DEPLOY, BLTOUCH_DEPLOY_DELAY); }
  1843. void _bltouch_stow() { bltouch_command(BLTOUCH_STOW, BLTOUCH_STOW_DELAY); }
  1844. void _bltouch_reset_SW_mode() { if (bltouch_triggered()) _bltouch_stow(); else _bltouch_deploy(); }
  1845. bool _bltouch_deploy_query_alarm() { return bltouch_command(BLTOUCH_DEPLOY, BLTOUCH_DEPLOY_DELAY); }
  1846. bool _bltouch_stow_query_alarm() { return bltouch_command(BLTOUCH_STOW, BLTOUCH_STOW_DELAY); }
  1847. void bltouch_clear() {
  1848. _bltouch_reset(); // RESET or RESET_SW will clear an alarm condition but...
  1849. // ...it will not clear a triggered condition in SW mode when the pin is currently up
  1850. // ANTClabs <-- CODE ERROR
  1851. _bltouch_stow(); // STOW will pull up the pin and clear any triggered condition unless it fails, don't care
  1852. _bltouch_deploy(); // DEPLOY to test the probe. Could fail, don't care
  1853. _bltouch_stow(); // STOW to be ready for meaningful work. Could fail, don't care
  1854. }
  1855. bool bltouch_deploy_proc() {
  1856. // Do a DEPLOY
  1857. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1858. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch DEPLOY requested");
  1859. #endif
  1860. // Attempt to DEPLOY, wait for DEPLOY_DELAY or ALARM
  1861. if (_bltouch_deploy_query_alarm()) {
  1862. // The deploy might have failed or the probe is already triggered (nozzle too low?)
  1863. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1864. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch ALARM or TRIGGER after DEPLOY, recovering");
  1865. #endif
  1866. bltouch_clear(); // Get the probe into start condition
  1867. // Last attempt to DEPLOY
  1868. if (_bltouch_deploy_query_alarm()) {
  1869. // The deploy might have failed or the probe is actually triggered (nozzle too low?) again
  1870. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1871. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch Recovery Failed");
  1872. #endif
  1873. SERIAL_ECHOLN(MSG_STOP_BLTOUCH); // Tell the user something is wrong, needs action
  1874. stop(); // but it's not too bad, no need to kill, allow restart
  1875. return true; // Tell our caller we goofed in case he cares to know
  1876. }
  1877. }
  1878. // One of the recommended ANTClabs ways to probe, using SW MODE
  1879. #if ENABLED(BLTOUCH_FORCE_SW_MODE)
  1880. _bltouch_set_SW_mode();
  1881. #endif
  1882. // Now the probe is ready to issue a 10ms pulse when the pin goes up.
  1883. // The trigger STOW (see motion.cpp for example) will pull up the probes pin as soon as the pulse
  1884. // is registered.
  1885. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1886. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("bltouch.deploy_proc() end");
  1887. #endif
  1888. return false; // report success to caller
  1889. }
  1890. bool bltouch_stow_proc() {
  1891. // Do a STOW
  1892. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1893. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch STOW requested");
  1894. #endif
  1895. // A STOW will clear a triggered condition in the probe (10ms pulse).
  1896. // At the moment that we come in here, we might (pulse) or will (SW mode) see the trigger on the pin.
  1897. // So even though we know a STOW will be ignored if an ALARM condition is active, we will STOW.
  1898. // Note: If the probe is deployed AND in an ALARM condition, this STOW will not pull up the pin
  1899. // and the ALARM condition will still be there. --> ANTClabs should change this behavior maybe
  1900. // Attempt to STOW, wait for STOW_DELAY or ALARM
  1901. if (_bltouch_stow_query_alarm()) {
  1902. // The stow might have failed
  1903. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1904. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch ALARM or TRIGGER after STOW, recovering");
  1905. #endif
  1906. _bltouch_reset(); // This RESET will then also pull up the pin. If it doesn't
  1907. // work and the pin is still down, there will no longer be
  1908. // an ALARM condition though.
  1909. // But one more STOW will catch that
  1910. // Last attempt to STOW
  1911. if (_bltouch_stow_query_alarm()) { // so if there is now STILL an ALARM condition:
  1912. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1913. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch Recovery Failed");
  1914. #endif
  1915. SERIAL_ECHOLN(MSG_STOP_BLTOUCH); // Tell the user something is wrong, needs action
  1916. stop(); // but it's not too bad, no need to kill, allow restart
  1917. return true; // Tell our caller we goofed in case he cares to know
  1918. }
  1919. }
  1920. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1921. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("bltouch.stow_proc() end");
  1922. #endif
  1923. return false; // report success to caller
  1924. }
  1925. bool bltouch_status_proc() {
  1926. /**
  1927. * Return a TRUE for "YES, it is DEPLOYED"
  1928. * This function will ensure switch state is reset after execution
  1929. */
  1930. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1931. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("BLTouch STATUS requested");
  1932. #endif
  1933. _bltouch_set_SW_mode(); // Incidentally, _set_SW_mode() will also RESET any active alarm
  1934. const bool tr = bltouch_triggered(); // If triggered in SW mode, the pin is up, it is STOWED
  1935. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1936. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("BLTouch is ", (int)tr);
  1937. #endif
  1938. if (tr) _bltouch_stow(); else _bltouch_deploy(); // Turn off SW mode, reset any trigger, honor pin state
  1939. return !tr;
  1940. }
  1941. void bltouch_mode_conv_proc(const bool M5V) {
  1942. /**
  1943. * BLTOUCH pre V3.0 and clones: No reaction at all to this sequence apart from a DEPLOY -> STOW
  1944. * BLTOUCH V3.0: This will set the mode (twice) and sadly, a STOW is needed at the end, because of the deploy
  1945. * BLTOUCH V3.1: This will set the mode and store it in the eeprom. The STOW is not needed but does not hurt
  1946. */
  1947. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1948. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("BLTouch Set Mode - ", (int)M5V);
  1949. #endif
  1950. _bltouch_deploy();
  1951. if (M5V) _bltouch_set_5V_mode(); else _bltouch_set_OD_mode();
  1952. _bltouch_mode_store();
  1953. if (M5V) _bltouch_set_5V_mode(); else _bltouch_set_OD_mode();
  1954. _bltouch_stow();
  1955. bltouch_last_written_mode = M5V;
  1956. }
  1957. bool set_bltouch_deployed(const bool deploy) {
  1958. if (deploy) _bltouch_deploy(); else _bltouch_stow();
  1959. return false;
  1960. }
  1961. void bltouch_mode_conv_5V() { bltouch_mode_conv_proc(true); }
  1962. void bltouch_mode_conv_OD() { bltouch_mode_conv_proc(false); }
  1963. // DEPLOY and STOW are wrapped for error handling - these are used by homing and by probing
  1964. bool bltouch_deploy() { return bltouch_deploy_proc(); }
  1965. bool bltouch_stow() { return bltouch_stow_proc(); }
  1966. bool bltouch_status() { return bltouch_status_proc(); }
  1967. // Init the class and device. Call from setup().
  1968. void bltouch_init(const bool set_voltage/*=false*/) {
  1969. // Voltage Setting (if enabled). At every Marlin initialization:
  1970. // BLTOUCH < V3.0 and clones: This will be ignored by the probe
  1971. // BLTOUCH V3.0: SET_5V_MODE or SET_OD_MODE (if enabled).
  1972. // OD_MODE is the default on power on, but setting it does not hurt
  1973. // This mode will stay active until manual SET_OD_MODE or power cycle
  1974. // BLTOUCH V3.1: SET_5V_MODE or SET_OD_MODE (if enabled).
  1975. // At power on, the probe will default to the eeprom settings configured by the user
  1976. _bltouch_reset();
  1977. _bltouch_stow();
  1978. #if ENABLED(BLTOUCH_FORCE_MODE_SET)
  1979. constexpr bool should_set = true;
  1980. #else
  1981. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1982. if (DEBUGGING(LEVELING)) {
  1983. SERIAL_ECHOPAIR("last_written_mode - ", int(bltouch_last_written_mode));
  1984. SERIAL_ECHOLNPGM("config mode - "
  1985. #if ENABLED(BLTOUCH_SET_5V_MODE)
  1986. "BLTOUCH_SET_5V_MODE"
  1987. #else
  1988. "OD"
  1989. #endif
  1990. );
  1991. }
  1992. #endif
  1993. const bool should_set = bltouch_last_written_mode != (false
  1994. #if ENABLED(BLTOUCH_SET_5V_MODE)
  1995. || true
  1996. #endif
  1997. );
  1998. #endif
  1999. if (should_set && set_voltage)
  2000. bltouch_mode_conv_proc((false
  2001. #if ENABLED(BLTOUCH_SET_5V_MODE)
  2002. || true
  2003. #endif
  2004. ));
  2005. }
  2006. #endif // BLTOUCH
  2007. /**
  2008. * Raise Z to a minimum height to make room for a probe to move
  2009. */
  2010. inline void do_probe_raise(const float z_raise) {
  2011. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2012. if (DEBUGGING(LEVELING)) {
  2013. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  2014. SERIAL_CHAR(')');
  2015. SERIAL_EOL();
  2016. }
  2017. #endif
  2018. float z_dest = z_raise;
  2019. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  2020. NOMORE(z_dest, Z_MAX_POS);
  2021. if (z_dest > current_position[Z_AXIS])
  2022. do_blocking_move_to_z(z_dest);
  2023. }
  2024. // returns false for ok and true for failure
  2025. bool set_probe_deployed(const bool deploy) {
  2026. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2027. if (DEBUGGING(LEVELING)) {
  2028. DEBUG_POS("set_probe_deployed", current_position);
  2029. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  2030. }
  2031. #endif
  2032. if (endstops.z_probe_enabled == deploy) return false;
  2033. // Make room for probe to deploy (or stow)
  2034. // Fix-mounted probe should only raise for deploy
  2035. #if ENABLED(FIX_MOUNTED_PROBE)
  2036. const bool deploy_stow_condition = deploy;
  2037. #else
  2038. constexpr bool deploy_stow_condition = true;
  2039. #endif
  2040. // For beds that fall when Z is powered off only raise for trusted Z
  2041. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  2042. const bool unknown_condition = TEST(axis_known_position, Z_AXIS);
  2043. #else
  2044. constexpr float unknown_condition = true;
  2045. #endif
  2046. if (deploy_stow_condition && unknown_condition)
  2047. do_probe_raise(MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_CLEARANCE_DEPLOY_PROBE));
  2048. #if ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  2049. #if ENABLED(Z_PROBE_SLED)
  2050. #define _AUE_ARGS true, false, false
  2051. #else
  2052. #define _AUE_ARGS
  2053. #endif
  2054. if (axis_unhomed_error(_AUE_ARGS)) {
  2055. SERIAL_ERROR_START();
  2056. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  2057. stop();
  2058. return true;
  2059. }
  2060. #endif
  2061. const float oldXpos = current_position[X_AXIS],
  2062. oldYpos = current_position[Y_AXIS];
  2063. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  2064. // If endstop is already false, the Z probe is deployed
  2065. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  2066. // Would a goto be less ugly?
  2067. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  2068. // for a triggered when stowed manual probe.
  2069. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  2070. // otherwise an Allen-Key probe can't be stowed.
  2071. #endif
  2072. #if ENABLED(SOLENOID_PROBE)
  2073. #if HAS_SOLENOID_1
  2074. WRITE(SOL1_PIN, deploy);
  2075. #endif
  2076. #elif ENABLED(Z_PROBE_SLED)
  2077. dock_sled(!deploy);
  2078. #elif HAS_Z_SERVO_PROBE && DISABLED(BLTOUCH)
  2079. MOVE_SERVO(Z_PROBE_SERVO_NR, z_servo_angle[deploy ? 0 : 1]);
  2080. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2081. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  2082. #endif
  2083. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  2084. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  2085. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  2086. if (IsRunning()) {
  2087. SERIAL_ERROR_START();
  2088. SERIAL_ERRORLNPGM("Z-Probe failed");
  2089. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  2090. }
  2091. stop();
  2092. return true;
  2093. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  2094. #endif
  2095. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  2096. endstops.enable_z_probe(deploy);
  2097. return false;
  2098. }
  2099. /**
  2100. * @brief Used by run_z_probe to do a single Z probe move.
  2101. *
  2102. * @param z Z destination
  2103. * @param fr_mm_s Feedrate in mm/s
  2104. * @return true to indicate an error
  2105. */
  2106. static bool do_probe_move(const float z, const float fr_mm_s) {
  2107. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2108. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  2109. #endif
  2110. #if HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  2111. // Wait for bed to heat back up between probing points
  2112. if (thermalManager.isHeatingBed()) {
  2113. serialprintPGM(msg_wait_for_bed_heating);
  2114. LCD_MESSAGEPGM(MSG_BED_HEATING);
  2115. while (thermalManager.isHeatingBed()) safe_delay(200);
  2116. lcd_reset_status();
  2117. }
  2118. #endif
  2119. // Deploy BLTouch at the start of any probe
  2120. #if ENABLED(BLTOUCH)
  2121. if (set_bltouch_deployed(true)) return true;
  2122. #endif
  2123. #if QUIET_PROBING
  2124. probing_pause(true);
  2125. #endif
  2126. // Move down until probe triggered
  2127. do_blocking_move_to_z(z, fr_mm_s);
  2128. // Check to see if the probe was triggered
  2129. const bool probe_triggered = TEST(endstops.trigger_state(),
  2130. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  2131. Z_MIN
  2132. #else
  2133. Z_MIN_PROBE
  2134. #endif
  2135. );
  2136. #if QUIET_PROBING
  2137. probing_pause(false);
  2138. #endif
  2139. // Retract BLTouch immediately after a probe if it was triggered
  2140. #if ENABLED(BLTOUCH)
  2141. if (probe_triggered && set_bltouch_deployed(false)) return true;
  2142. #endif
  2143. endstops.hit_on_purpose();
  2144. // Get Z where the steppers were interrupted
  2145. set_current_from_steppers_for_axis(Z_AXIS);
  2146. // Tell the planner where we actually are
  2147. SYNC_PLAN_POSITION_KINEMATIC();
  2148. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2149. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  2150. #endif
  2151. return !probe_triggered;
  2152. }
  2153. /**
  2154. * @details Used by probe_pt to do a single Z probe at the current position.
  2155. * Leaves current_position[Z_AXIS] at the height where the probe triggered.
  2156. *
  2157. * @return The raw Z position where the probe was triggered
  2158. */
  2159. static float run_z_probe() {
  2160. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2161. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  2162. #endif
  2163. // Stop the probe before it goes too low to prevent damage.
  2164. // If Z isn't known then probe to -10mm.
  2165. const float z_probe_low_point = TEST(axis_known_position, Z_AXIS) ? -zprobe_zoffset + Z_PROBE_LOW_POINT : -10.0;
  2166. // Double-probing does a fast probe followed by a slow probe
  2167. #if MULTIPLE_PROBING == 2
  2168. // Do a first probe at the fast speed
  2169. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_FAST))) {
  2170. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2171. if (DEBUGGING(LEVELING)) {
  2172. SERIAL_ECHOLNPGM("FAST Probe fail!");
  2173. DEBUG_POS("<<< run_z_probe", current_position);
  2174. }
  2175. #endif
  2176. return NAN;
  2177. }
  2178. float first_probe_z = current_position[Z_AXIS];
  2179. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2180. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  2181. #endif
  2182. // move up to make clearance for the probe
  2183. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2184. #else
  2185. // If the nozzle is well over the travel height then
  2186. // move down quickly before doing the slow probe
  2187. float z = Z_CLEARANCE_DEPLOY_PROBE + 5.0;
  2188. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  2189. if (current_position[Z_AXIS] > z) {
  2190. // If we don't make it to the z position (i.e. the probe triggered), move up to make clearance for the probe
  2191. if (!do_probe_move(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST)))
  2192. do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_BETWEEN_PROBES, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2193. }
  2194. #endif
  2195. #if MULTIPLE_PROBING > 2
  2196. float probes_total = 0;
  2197. for (uint8_t p = MULTIPLE_PROBING + 1; --p;) {
  2198. #endif
  2199. // move down slowly to find bed
  2200. if (do_probe_move(z_probe_low_point, MMM_TO_MMS(Z_PROBE_SPEED_SLOW))) {
  2201. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2202. if (DEBUGGING(LEVELING)) {
  2203. SERIAL_ECHOLNPGM("SLOW Probe fail!");
  2204. DEBUG_POS("<<< run_z_probe", current_position);
  2205. }
  2206. #endif
  2207. return NAN;
  2208. }
  2209. #if MULTIPLE_PROBING > 2
  2210. probes_total += current_position[Z_AXIS];
  2211. if (p > 1) do_blocking_move_to_z(current_position[Z_AXIS] + Z_CLEARANCE_MULTI_PROBE, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2212. }
  2213. #endif
  2214. #if MULTIPLE_PROBING > 2
  2215. // Return the average value of all probes
  2216. const float measured_z = probes_total * (1.0f / (MULTIPLE_PROBING));
  2217. #elif MULTIPLE_PROBING == 2
  2218. const float z2 = current_position[Z_AXIS];
  2219. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2220. if (DEBUGGING(LEVELING)) {
  2221. SERIAL_ECHOPAIR("2nd Probe Z:", z2);
  2222. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - z2);
  2223. }
  2224. #endif
  2225. // Return a weighted average of the fast and slow probes
  2226. const float measured_z = (z2 * 3.0 + first_probe_z * 2.0) * 0.2;
  2227. #else
  2228. // Return the single probe result
  2229. const float measured_z = current_position[Z_AXIS];
  2230. #endif
  2231. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2232. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  2233. #endif
  2234. return measured_z;
  2235. }
  2236. /**
  2237. * - Move to the given XY
  2238. * - Deploy the probe, if not already deployed
  2239. * - Probe the bed, get the Z position
  2240. * - Depending on the 'stow' flag
  2241. * - Stow the probe, or
  2242. * - Raise to the BETWEEN height
  2243. * - Return the probed Z position
  2244. */
  2245. float probe_pt(const float &rx, const float &ry, const ProbePtRaise raise_after/*=PROBE_PT_NONE*/, const uint8_t verbose_level/*=0*/, const bool probe_relative/*=true*/) {
  2246. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2247. if (DEBUGGING(LEVELING)) {
  2248. SERIAL_ECHOPAIR(">>> probe_pt(", LOGICAL_X_POSITION(rx));
  2249. SERIAL_ECHOPAIR(", ", LOGICAL_Y_POSITION(ry));
  2250. SERIAL_ECHOPAIR(", ", raise_after == PROBE_PT_RAISE ? "raise" : raise_after == PROBE_PT_STOW ? "stow" : "none");
  2251. SERIAL_ECHOPAIR(", ", int(verbose_level));
  2252. SERIAL_ECHOPAIR(", ", probe_relative ? "probe" : "nozzle");
  2253. SERIAL_ECHOLNPGM("_relative)");
  2254. DEBUG_POS("", current_position);
  2255. }
  2256. #endif
  2257. // TODO: Adapt for SCARA, where the offset rotates
  2258. float nx = rx, ny = ry;
  2259. if (probe_relative) {
  2260. if (!position_is_reachable_by_probe(rx, ry)) return NAN; // The given position is in terms of the probe
  2261. nx -= (X_PROBE_OFFSET_FROM_EXTRUDER); // Get the nozzle position
  2262. ny -= (Y_PROBE_OFFSET_FROM_EXTRUDER);
  2263. }
  2264. else if (!position_is_reachable(nx, ny)) return NAN; // The given position is in terms of the nozzle
  2265. const float nz =
  2266. #if ENABLED(DELTA)
  2267. // Move below clip height or xy move will be aborted by do_blocking_move_to
  2268. MIN(current_position[Z_AXIS], delta_clip_start_height)
  2269. #else
  2270. current_position[Z_AXIS]
  2271. #endif
  2272. ;
  2273. const float old_feedrate_mm_s = feedrate_mm_s;
  2274. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  2275. // Move the probe to the starting XYZ
  2276. do_blocking_move_to(nx, ny, nz);
  2277. float measured_z = NAN;
  2278. if (!DEPLOY_PROBE()) {
  2279. measured_z = run_z_probe() + zprobe_zoffset;
  2280. const bool big_raise = raise_after == PROBE_PT_BIG_RAISE;
  2281. if (big_raise || raise_after == PROBE_PT_RAISE)
  2282. do_blocking_move_to_z(current_position[Z_AXIS] + (big_raise ? 25 : Z_CLEARANCE_BETWEEN_PROBES), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  2283. else if (raise_after == PROBE_PT_STOW)
  2284. if (STOW_PROBE()) measured_z = NAN;
  2285. }
  2286. if (verbose_level > 2) {
  2287. SERIAL_PROTOCOLPGM("Bed X: ");
  2288. SERIAL_PROTOCOL_F(LOGICAL_X_POSITION(rx), 3);
  2289. SERIAL_PROTOCOLPGM(" Y: ");
  2290. SERIAL_PROTOCOL_F(LOGICAL_Y_POSITION(ry), 3);
  2291. SERIAL_PROTOCOLPGM(" Z: ");
  2292. SERIAL_PROTOCOL_F(measured_z, 3);
  2293. SERIAL_EOL();
  2294. }
  2295. feedrate_mm_s = old_feedrate_mm_s;
  2296. if (isnan(measured_z)) {
  2297. LCD_MESSAGEPGM(MSG_ERR_PROBING_FAILED);
  2298. SERIAL_ERROR_START();
  2299. SERIAL_ERRORLNPGM(MSG_ERR_PROBING_FAILED);
  2300. }
  2301. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2302. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2303. #endif
  2304. return measured_z;
  2305. }
  2306. #endif // HAS_BED_PROBE
  2307. #if HAS_LEVELING
  2308. bool leveling_is_valid() {
  2309. return
  2310. #if ENABLED(MESH_BED_LEVELING)
  2311. mbl.has_mesh()
  2312. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2313. !!bilinear_grid_spacing[X_AXIS]
  2314. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2315. ubl.mesh_is_valid()
  2316. #else // 3POINT, LINEAR
  2317. true
  2318. #endif
  2319. ;
  2320. }
  2321. /**
  2322. * Turn bed leveling on or off, fixing the current
  2323. * position as-needed.
  2324. *
  2325. * Disable: Current position = physical position
  2326. * Enable: Current position = "unleveled" physical position
  2327. */
  2328. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2329. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2330. const bool can_change = (!enable || leveling_is_valid());
  2331. #else
  2332. constexpr bool can_change = true;
  2333. #endif
  2334. if (can_change && enable != planner.leveling_active) {
  2335. planner.synchronize();
  2336. #if ENABLED(MESH_BED_LEVELING)
  2337. if (!enable)
  2338. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2339. const bool enabling = enable && leveling_is_valid();
  2340. planner.leveling_active = enabling;
  2341. if (enabling) planner.unapply_leveling(current_position);
  2342. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2343. #if PLANNER_LEVELING
  2344. if (planner.leveling_active) { // leveling from on to off
  2345. // change unleveled current_position to physical current_position without moving steppers.
  2346. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2347. planner.leveling_active = false; // disable only AFTER calling apply_leveling
  2348. }
  2349. else { // leveling from off to on
  2350. planner.leveling_active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2351. // change physical current_position to unleveled current_position without moving steppers.
  2352. planner.unapply_leveling(current_position);
  2353. }
  2354. #else
  2355. // UBL equivalents for apply/unapply_leveling
  2356. #if ENABLED(SKEW_CORRECTION)
  2357. float pos[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2358. planner.skew(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS]);
  2359. #else
  2360. const float (&pos)[XYZE] = current_position;
  2361. #endif
  2362. if (planner.leveling_active) {
  2363. current_position[Z_AXIS] += ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2364. planner.leveling_active = false;
  2365. }
  2366. else {
  2367. planner.leveling_active = true;
  2368. current_position[Z_AXIS] -= ubl.get_z_correction(pos[X_AXIS], pos[Y_AXIS]);
  2369. }
  2370. #endif
  2371. #else // ABL
  2372. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2373. // Force bilinear_z_offset to re-calculate next time
  2374. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2375. (void)bilinear_z_offset(reset);
  2376. #endif
  2377. // Enable or disable leveling compensation in the planner
  2378. planner.leveling_active = enable;
  2379. if (!enable)
  2380. // When disabling just get the current position from the steppers.
  2381. // This will yield the smallest error when first converted back to steps.
  2382. set_current_from_steppers_for_axis(
  2383. #if ABL_PLANAR
  2384. ALL_AXES
  2385. #else
  2386. Z_AXIS
  2387. #endif
  2388. );
  2389. else
  2390. // When enabling, remove compensation from the current position,
  2391. // so compensation will give the right stepper counts.
  2392. planner.unapply_leveling(current_position);
  2393. SYNC_PLAN_POSITION_KINEMATIC();
  2394. #endif // ABL
  2395. }
  2396. }
  2397. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2398. void set_z_fade_height(const float zfh, const bool do_report/*=true*/) {
  2399. if (planner.z_fade_height == zfh) return;
  2400. const bool leveling_was_active = planner.leveling_active;
  2401. set_bed_leveling_enabled(false);
  2402. planner.set_z_fade_height(zfh);
  2403. if (leveling_was_active) {
  2404. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  2405. set_bed_leveling_enabled(true);
  2406. if (do_report && memcmp(oldpos, current_position, sizeof(oldpos)))
  2407. report_current_position();
  2408. }
  2409. }
  2410. #endif // LEVELING_FADE_HEIGHT
  2411. /**
  2412. * Reset calibration results to zero.
  2413. */
  2414. void reset_bed_level() {
  2415. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2416. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2417. #endif
  2418. set_bed_leveling_enabled(false);
  2419. #if ENABLED(MESH_BED_LEVELING)
  2420. mbl.reset();
  2421. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2422. ubl.reset();
  2423. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2424. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2425. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2426. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2427. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2428. z_values[x][y] = NAN;
  2429. #elif ABL_PLANAR
  2430. planner.bed_level_matrix.set_to_identity();
  2431. #endif
  2432. }
  2433. #endif // HAS_LEVELING
  2434. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2435. /**
  2436. * Enable to produce output in JSON format suitable
  2437. * for SCAD or JavaScript mesh visualizers.
  2438. *
  2439. * Visualize meshes in OpenSCAD using the included script.
  2440. *
  2441. * buildroot/shared/scripts/MarlinMesh.scad
  2442. */
  2443. //#define SCAD_MESH_OUTPUT
  2444. /**
  2445. * Print calibration results for plotting or manual frame adjustment.
  2446. */
  2447. void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, const element_2d_fn fn) {
  2448. #ifndef SCAD_MESH_OUTPUT
  2449. for (uint8_t x = 0; x < sx; x++) {
  2450. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2451. SERIAL_PROTOCOLCHAR(' ');
  2452. SERIAL_PROTOCOL(int(x));
  2453. }
  2454. SERIAL_EOL();
  2455. #endif
  2456. #ifdef SCAD_MESH_OUTPUT
  2457. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2458. #endif
  2459. for (uint8_t y = 0; y < sy; y++) {
  2460. #ifdef SCAD_MESH_OUTPUT
  2461. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2462. #else
  2463. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2464. SERIAL_PROTOCOL(int(y));
  2465. #endif
  2466. for (uint8_t x = 0; x < sx; x++) {
  2467. SERIAL_PROTOCOLCHAR(' ');
  2468. const float offset = fn(x, y);
  2469. if (!isnan(offset)) {
  2470. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2471. SERIAL_PROTOCOL_F(offset, int(precision));
  2472. }
  2473. else {
  2474. #ifdef SCAD_MESH_OUTPUT
  2475. for (uint8_t i = 3; i < precision + 3; i++)
  2476. SERIAL_PROTOCOLCHAR(' ');
  2477. SERIAL_PROTOCOLPGM("NAN");
  2478. #else
  2479. for (uint8_t i = 0; i < precision + 3; i++)
  2480. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2481. #endif
  2482. }
  2483. #ifdef SCAD_MESH_OUTPUT
  2484. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2485. #endif
  2486. }
  2487. #ifdef SCAD_MESH_OUTPUT
  2488. SERIAL_PROTOCOLCHAR(' ');
  2489. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2490. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2491. #endif
  2492. SERIAL_EOL();
  2493. }
  2494. #ifdef SCAD_MESH_OUTPUT
  2495. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2496. #endif
  2497. SERIAL_EOL();
  2498. }
  2499. #endif
  2500. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2501. /**
  2502. * Extrapolate a single point from its neighbors
  2503. */
  2504. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2505. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2506. if (DEBUGGING(LEVELING)) {
  2507. SERIAL_ECHOPGM("Extrapolate [");
  2508. if (x < 10) SERIAL_CHAR(' ');
  2509. SERIAL_ECHO(int(x));
  2510. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2511. SERIAL_CHAR(' ');
  2512. if (y < 10) SERIAL_CHAR(' ');
  2513. SERIAL_ECHO(int(y));
  2514. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2515. SERIAL_CHAR(']');
  2516. }
  2517. #endif
  2518. if (!isnan(z_values[x][y])) {
  2519. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2520. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2521. #endif
  2522. return; // Don't overwrite good values.
  2523. }
  2524. SERIAL_EOL();
  2525. // Get X neighbors, Y neighbors, and XY neighbors
  2526. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2527. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2528. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2529. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2530. // Treat far unprobed points as zero, near as equal to far
  2531. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2532. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2533. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2534. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2535. // Take the average instead of the median
  2536. z_values[x][y] = (a + b + c) / 3.0;
  2537. // Median is robust (ignores outliers).
  2538. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2539. // : ((c < b) ? b : (a < c) ? a : c);
  2540. }
  2541. //Enable this if your SCARA uses 180° of total area
  2542. //#define EXTRAPOLATE_FROM_EDGE
  2543. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2544. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2545. #define HALF_IN_X
  2546. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2547. #define HALF_IN_Y
  2548. #endif
  2549. #endif
  2550. /**
  2551. * Fill in the unprobed points (corners of circular print surface)
  2552. * using linear extrapolation, away from the center.
  2553. */
  2554. static void extrapolate_unprobed_bed_level() {
  2555. #ifdef HALF_IN_X
  2556. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2557. #else
  2558. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2559. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2560. xlen = ctrx1;
  2561. #endif
  2562. #ifdef HALF_IN_Y
  2563. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2564. #else
  2565. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2566. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2567. ylen = ctry1;
  2568. #endif
  2569. for (uint8_t xo = 0; xo <= xlen; xo++)
  2570. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2571. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2572. #ifndef HALF_IN_X
  2573. const uint8_t x1 = ctrx1 - xo;
  2574. #endif
  2575. #ifndef HALF_IN_Y
  2576. const uint8_t y1 = ctry1 - yo;
  2577. #ifndef HALF_IN_X
  2578. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2579. #endif
  2580. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2581. #endif
  2582. #ifndef HALF_IN_X
  2583. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2584. #endif
  2585. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2586. }
  2587. }
  2588. static void print_bilinear_leveling_grid() {
  2589. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2590. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2591. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2592. );
  2593. }
  2594. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2595. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2596. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2597. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2598. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2599. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2600. int bilinear_grid_spacing_virt[2] = { 0 };
  2601. float bilinear_grid_factor_virt[2] = { 0 };
  2602. static void print_bilinear_leveling_grid_virt() {
  2603. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2604. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2605. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2606. );
  2607. }
  2608. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2609. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2610. uint8_t ep = 0, ip = 1;
  2611. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2612. if (x) {
  2613. ep = GRID_MAX_POINTS_X - 1;
  2614. ip = GRID_MAX_POINTS_X - 2;
  2615. }
  2616. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2617. return LINEAR_EXTRAPOLATION(
  2618. z_values[ep][y - 1],
  2619. z_values[ip][y - 1]
  2620. );
  2621. else
  2622. return LINEAR_EXTRAPOLATION(
  2623. bed_level_virt_coord(ep + 1, y),
  2624. bed_level_virt_coord(ip + 1, y)
  2625. );
  2626. }
  2627. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2628. if (y) {
  2629. ep = GRID_MAX_POINTS_Y - 1;
  2630. ip = GRID_MAX_POINTS_Y - 2;
  2631. }
  2632. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2633. return LINEAR_EXTRAPOLATION(
  2634. z_values[x - 1][ep],
  2635. z_values[x - 1][ip]
  2636. );
  2637. else
  2638. return LINEAR_EXTRAPOLATION(
  2639. bed_level_virt_coord(x, ep + 1),
  2640. bed_level_virt_coord(x, ip + 1)
  2641. );
  2642. }
  2643. return z_values[x - 1][y - 1];
  2644. }
  2645. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2646. return (
  2647. p[i-1] * -t * sq(1 - t)
  2648. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2649. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2650. - p[i+2] * sq(t) * (1 - t)
  2651. ) * 0.5;
  2652. }
  2653. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2654. float row[4], column[4];
  2655. for (uint8_t i = 0; i < 4; i++) {
  2656. for (uint8_t j = 0; j < 4; j++) {
  2657. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2658. }
  2659. row[i] = bed_level_virt_cmr(column, 1, ty);
  2660. }
  2661. return bed_level_virt_cmr(row, 1, tx);
  2662. }
  2663. void bed_level_virt_interpolate() {
  2664. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2665. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2666. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2667. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2668. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2669. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2670. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2671. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2672. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2673. continue;
  2674. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2675. bed_level_virt_2cmr(
  2676. x + 1,
  2677. y + 1,
  2678. (float)tx / (BILINEAR_SUBDIVISIONS),
  2679. (float)ty / (BILINEAR_SUBDIVISIONS)
  2680. );
  2681. }
  2682. }
  2683. #endif // ABL_BILINEAR_SUBDIVISION
  2684. // Refresh after other values have been updated
  2685. void refresh_bed_level() {
  2686. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2687. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2688. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2689. bed_level_virt_interpolate();
  2690. #endif
  2691. }
  2692. #endif // AUTO_BED_LEVELING_BILINEAR
  2693. #if ENABLED(SENSORLESS_HOMING)
  2694. /**
  2695. * Set sensorless homing if the axis has it, accounting for Core Kinematics.
  2696. */
  2697. void sensorless_homing_per_axis(const AxisEnum axis, const bool enable=true) {
  2698. switch (axis) {
  2699. #if X_SENSORLESS
  2700. case X_AXIS:
  2701. tmc_sensorless_homing(stepperX, enable);
  2702. #if CORE_IS_XY && Y_SENSORLESS
  2703. tmc_sensorless_homing(stepperY, enable);
  2704. #elif CORE_IS_XZ && Z_SENSORLESS
  2705. tmc_sensorless_homing(stepperZ, enable);
  2706. #endif
  2707. break;
  2708. #endif
  2709. #if Y_SENSORLESS
  2710. case Y_AXIS:
  2711. tmc_sensorless_homing(stepperY, enable);
  2712. #if CORE_IS_XY && X_SENSORLESS
  2713. tmc_sensorless_homing(stepperX, enable);
  2714. #elif CORE_IS_YZ && Z_SENSORLESS
  2715. tmc_sensorless_homing(stepperZ, enable);
  2716. #endif
  2717. break;
  2718. #endif
  2719. #if Z_SENSORLESS
  2720. case Z_AXIS:
  2721. tmc_sensorless_homing(stepperZ, enable);
  2722. #if CORE_IS_XZ && X_SENSORLESS
  2723. tmc_sensorless_homing(stepperX, enable);
  2724. #elif CORE_IS_YZ && Y_SENSORLESS
  2725. tmc_sensorless_homing(stepperY, enable);
  2726. #endif
  2727. break;
  2728. #endif
  2729. default: break;
  2730. }
  2731. }
  2732. #endif // SENSORLESS_HOMING
  2733. /**
  2734. * Home an individual linear axis
  2735. */
  2736. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0) {
  2737. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2738. if (DEBUGGING(LEVELING)) {
  2739. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2740. SERIAL_ECHOPAIR(", ", distance);
  2741. SERIAL_ECHOPGM(", ");
  2742. if (fr_mm_s)
  2743. SERIAL_ECHO(fr_mm_s);
  2744. else {
  2745. SERIAL_ECHOPAIR("[", homing_feedrate(axis));
  2746. SERIAL_CHAR(']');
  2747. }
  2748. SERIAL_ECHOLNPGM(")");
  2749. }
  2750. #endif
  2751. #if HOMING_Z_WITH_PROBE && HAS_HEATED_BED && ENABLED(WAIT_FOR_BED_HEATER)
  2752. // Wait for bed to heat back up between probing points
  2753. if (axis == Z_AXIS && distance < 0 && thermalManager.isHeatingBed()) {
  2754. serialprintPGM(msg_wait_for_bed_heating);
  2755. LCD_MESSAGEPGM(MSG_BED_HEATING);
  2756. while (thermalManager.isHeatingBed()) safe_delay(200);
  2757. lcd_reset_status();
  2758. }
  2759. #endif
  2760. // Only do some things when moving towards an endstop
  2761. const int8_t axis_home_dir =
  2762. #if ENABLED(DUAL_X_CARRIAGE)
  2763. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2764. #endif
  2765. home_dir(axis);
  2766. const bool is_home_dir = (axis_home_dir > 0) == (distance > 0);
  2767. if (is_home_dir) {
  2768. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2769. if (axis == Z_AXIS) probing_pause(true);
  2770. #endif
  2771. // Disable stealthChop if used. Enable diag1 pin on driver.
  2772. #if ENABLED(SENSORLESS_HOMING)
  2773. sensorless_homing_per_axis(axis);
  2774. #endif
  2775. }
  2776. // Tell the planner the axis is at 0
  2777. current_position[axis] = 0;
  2778. // Do the move, which is required to hit an endstop
  2779. #if IS_SCARA
  2780. SYNC_PLAN_POSITION_KINEMATIC();
  2781. current_position[axis] = distance;
  2782. inverse_kinematics(current_position);
  2783. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2784. #elif ENABLED(HANGPRINTER) // TODO: Hangprinter homing is not finished (Jan 7, 2018)
  2785. SYNC_PLAN_POSITION_KINEMATIC();
  2786. current_position[axis] = distance;
  2787. inverse_kinematics(current_position);
  2788. planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2789. #else
  2790. sync_plan_position();
  2791. current_position[axis] = distance; // Set delta/cartesian axes directly
  2792. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2793. #endif
  2794. planner.synchronize();
  2795. if (is_home_dir) {
  2796. #if HOMING_Z_WITH_PROBE && QUIET_PROBING
  2797. if (axis == Z_AXIS) probing_pause(false);
  2798. #endif
  2799. endstops.validate_homing_move();
  2800. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2801. #if ENABLED(SENSORLESS_HOMING)
  2802. sensorless_homing_per_axis(axis, false);
  2803. #endif
  2804. }
  2805. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2806. if (DEBUGGING(LEVELING)) {
  2807. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2808. SERIAL_CHAR(')');
  2809. SERIAL_EOL();
  2810. }
  2811. #endif
  2812. }
  2813. /**
  2814. * Home an individual "raw axis" to its endstop.
  2815. * This applies to XYZ on Cartesian and Core robots, and
  2816. * to the individual ABC steppers on DELTA and SCARA.
  2817. *
  2818. * At the end of the procedure the axis is marked as
  2819. * homed and the current position of that axis is updated.
  2820. * Kinematic robots should wait till all axes are homed
  2821. * before updating the current position.
  2822. */
  2823. static void homeaxis(const AxisEnum axis) {
  2824. #if IS_SCARA
  2825. // Only Z homing (with probe) is permitted
  2826. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2827. #else
  2828. #define CAN_HOME(A) \
  2829. (axis == _AXIS(A) && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2830. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2831. #endif
  2832. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2833. if (DEBUGGING(LEVELING)) {
  2834. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2835. SERIAL_CHAR(')');
  2836. SERIAL_EOL();
  2837. }
  2838. #endif
  2839. const int axis_home_dir = (
  2840. #if ENABLED(DUAL_X_CARRIAGE)
  2841. axis == X_AXIS ? x_home_dir(active_extruder) :
  2842. #endif
  2843. home_dir(axis)
  2844. );
  2845. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2846. #if HOMING_Z_WITH_PROBE
  2847. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2848. #endif
  2849. // Set flags for X, Y, Z motor locking
  2850. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2851. switch (axis) {
  2852. #if ENABLED(X_DUAL_ENDSTOPS)
  2853. case X_AXIS:
  2854. #endif
  2855. #if ENABLED(Y_DUAL_ENDSTOPS)
  2856. case Y_AXIS:
  2857. #endif
  2858. #if ENABLED(Z_DUAL_ENDSTOPS)
  2859. case Z_AXIS:
  2860. #endif
  2861. stepper.set_homing_dual_axis(true);
  2862. default: break;
  2863. }
  2864. #endif
  2865. // Fast move towards endstop until triggered
  2866. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2867. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2868. #endif
  2869. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2870. // BLTOUCH needs to be deployed every time
  2871. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2872. #endif
  2873. do_homing_move(axis, 1.5f * max_length(axis) * axis_home_dir);
  2874. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2875. // BLTOUCH needs to be stowed after trigger to rearm itself
  2876. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2877. #endif
  2878. // When homing Z with probe respect probe clearance
  2879. const float bump = axis_home_dir * (
  2880. #if HOMING_Z_WITH_PROBE
  2881. (axis == Z_AXIS && (Z_HOME_BUMP_MM)) ? MAX(Z_CLEARANCE_BETWEEN_PROBES, Z_HOME_BUMP_MM) :
  2882. #endif
  2883. home_bump_mm(axis)
  2884. );
  2885. // If a second homing move is configured...
  2886. if (bump) {
  2887. // Move away from the endstop by the axis HOME_BUMP_MM
  2888. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2889. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2890. #endif
  2891. do_homing_move(axis, -bump
  2892. #if HOMING_Z_WITH_PROBE
  2893. , axis == Z_AXIS ? MMM_TO_MMS(Z_PROBE_SPEED_FAST) : 0.00
  2894. #endif
  2895. );
  2896. // Slow move towards endstop until triggered
  2897. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2898. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2899. #endif
  2900. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2901. // BLTOUCH needs to be deployed every time
  2902. if (axis == Z_AXIS && set_bltouch_deployed(true)) return;
  2903. #endif
  2904. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2905. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2906. // BLTOUCH needs to be stowed after trigger to rearm itself
  2907. if (axis == Z_AXIS) set_bltouch_deployed(false);
  2908. #endif
  2909. }
  2910. /**
  2911. * Home axes that have dual endstops... differently
  2912. */
  2913. #if ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  2914. const bool pos_dir = axis_home_dir > 0;
  2915. #if ENABLED(X_DUAL_ENDSTOPS)
  2916. if (axis == X_AXIS) {
  2917. const float adj = ABS(endstops.x_endstop_adj);
  2918. if (adj) {
  2919. if (pos_dir ? (endstops.x_endstop_adj > 0) : (endstops.x_endstop_adj < 0)) stepper.set_x_lock(true); else stepper.set_x2_lock(true);
  2920. do_homing_move(axis, pos_dir ? -adj : adj);
  2921. stepper.set_x_lock(false);
  2922. stepper.set_x2_lock(false);
  2923. }
  2924. }
  2925. #endif
  2926. #if ENABLED(Y_DUAL_ENDSTOPS)
  2927. if (axis == Y_AXIS) {
  2928. const float adj = ABS(endstops.y_endstop_adj);
  2929. if (adj) {
  2930. if (pos_dir ? (endstops.y_endstop_adj > 0) : (endstops.y_endstop_adj < 0)) stepper.set_y_lock(true); else stepper.set_y2_lock(true);
  2931. do_homing_move(axis, pos_dir ? -adj : adj);
  2932. stepper.set_y_lock(false);
  2933. stepper.set_y2_lock(false);
  2934. }
  2935. }
  2936. #endif
  2937. #if ENABLED(Z_DUAL_ENDSTOPS)
  2938. if (axis == Z_AXIS) {
  2939. const float adj = ABS(endstops.z_endstop_adj);
  2940. if (adj) {
  2941. if (pos_dir ? (endstops.z_endstop_adj > 0) : (endstops.z_endstop_adj < 0)) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2942. do_homing_move(axis, pos_dir ? -adj : adj);
  2943. stepper.set_z_lock(false);
  2944. stepper.set_z2_lock(false);
  2945. }
  2946. }
  2947. #endif
  2948. stepper.set_homing_dual_axis(false);
  2949. #endif
  2950. #if IS_SCARA
  2951. set_axis_is_at_home(axis);
  2952. SYNC_PLAN_POSITION_KINEMATIC();
  2953. #elif ENABLED(DELTA)
  2954. // Delta has already moved all three towers up in G28
  2955. // so here it re-homes each tower in turn.
  2956. // Delta homing treats the axes as normal linear axes.
  2957. // retrace by the amount specified in delta_endstop_adj + additional dist in order to have minimum steps
  2958. if (delta_endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2959. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2960. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("delta_endstop_adj:");
  2961. #endif
  2962. do_homing_move(axis, delta_endstop_adj[axis] - (MIN_STEPS_PER_SEGMENT + 1) * planner.steps_to_mm[axis] * Z_HOME_DIR);
  2963. }
  2964. #else
  2965. // For cartesian/core machines,
  2966. // set the axis to its home position
  2967. set_axis_is_at_home(axis);
  2968. sync_plan_position();
  2969. destination[axis] = current_position[axis];
  2970. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2971. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2972. #endif
  2973. #endif
  2974. // Put away the Z probe
  2975. #if HOMING_Z_WITH_PROBE
  2976. if (axis == Z_AXIS && STOW_PROBE()) return;
  2977. #endif
  2978. // Clear retracted status if homing the Z axis
  2979. #if ENABLED(FWRETRACT)
  2980. if (axis == Z_AXIS) fwretract.hop_amount = 0.0;
  2981. #endif
  2982. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2983. if (DEBUGGING(LEVELING)) {
  2984. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2985. SERIAL_CHAR(')');
  2986. SERIAL_EOL();
  2987. }
  2988. #endif
  2989. } // homeaxis()
  2990. #if ENABLED(MIXING_EXTRUDER)
  2991. void normalize_mix() {
  2992. float mix_total = 0.0;
  2993. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += mixing_factor[i];
  2994. // Scale all values if they don't add up to ~1.0
  2995. if (!NEAR(mix_total, 1.0)) {
  2996. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2997. const float inverse_sum = RECIPROCAL(mix_total);
  2998. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= inverse_sum;
  2999. }
  3000. }
  3001. #if ENABLED(DIRECT_MIXING_IN_G1)
  3002. // Get mixing parameters from the GCode
  3003. // The total "must" be 1.0 (but it will be normalized)
  3004. // If no mix factors are given, the old mix is preserved
  3005. void gcode_get_mix() {
  3006. const char mixing_codes[] = { 'A', 'B'
  3007. #if MIXING_STEPPERS > 2
  3008. , 'C'
  3009. #if MIXING_STEPPERS > 3
  3010. , 'D'
  3011. #if MIXING_STEPPERS > 4
  3012. , 'H'
  3013. #if MIXING_STEPPERS > 5
  3014. , 'I'
  3015. #endif // MIXING_STEPPERS > 5
  3016. #endif // MIXING_STEPPERS > 4
  3017. #endif // MIXING_STEPPERS > 3
  3018. #endif // MIXING_STEPPERS > 2
  3019. };
  3020. byte mix_bits = 0;
  3021. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  3022. if (parser.seenval(mixing_codes[i])) {
  3023. SBI(mix_bits, i);
  3024. mixing_factor[i] = MAX(parser.value_float(), 0.0);
  3025. }
  3026. }
  3027. // If any mixing factors were included, clear the rest
  3028. // If none were included, preserve the last mix
  3029. if (mix_bits) {
  3030. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  3031. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  3032. normalize_mix();
  3033. }
  3034. }
  3035. #endif
  3036. #endif
  3037. /**
  3038. * ***************************************************************************
  3039. * ***************************** G-CODE HANDLING *****************************
  3040. * ***************************************************************************
  3041. */
  3042. /**
  3043. * Set XYZE destination and feedrate from the current GCode command
  3044. *
  3045. * - Set destination from included axis codes
  3046. * - Set to current for missing axis codes
  3047. * - Set the feedrate, if included
  3048. */
  3049. void gcode_get_destination() {
  3050. LOOP_XYZE(i) {
  3051. if (parser.seen(axis_codes[i])) {
  3052. const float v = parser.value_axis_units((AxisEnum)i);
  3053. destination[i] = (axis_relative_modes[i] || relative_mode)
  3054. ? current_position[i] + v
  3055. : (i == E_CART) ? v : LOGICAL_TO_NATIVE(v, i);
  3056. }
  3057. else
  3058. destination[i] = current_position[i];
  3059. }
  3060. if (parser.linearval('F') > 0)
  3061. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  3062. #if ENABLED(PRINTCOUNTER)
  3063. if (!DEBUGGING(DRYRUN))
  3064. print_job_timer.incFilamentUsed(destination[E_CART] - current_position[E_CART]);
  3065. #endif
  3066. // Get ABCDHI mixing factors
  3067. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  3068. gcode_get_mix();
  3069. #endif
  3070. }
  3071. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  3072. /**
  3073. * Output a "busy" message at regular intervals
  3074. * while the machine is not accepting commands.
  3075. */
  3076. void host_keepalive() {
  3077. const millis_t ms = millis();
  3078. if (!suspend_auto_report && host_keepalive_interval && busy_state != NOT_BUSY) {
  3079. if (PENDING(ms, next_busy_signal_ms)) return;
  3080. switch (busy_state) {
  3081. case IN_HANDLER:
  3082. case IN_PROCESS:
  3083. SERIAL_ECHO_START();
  3084. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  3085. break;
  3086. case PAUSED_FOR_USER:
  3087. SERIAL_ECHO_START();
  3088. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  3089. break;
  3090. case PAUSED_FOR_INPUT:
  3091. SERIAL_ECHO_START();
  3092. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  3093. break;
  3094. default:
  3095. break;
  3096. }
  3097. }
  3098. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  3099. }
  3100. #endif // HOST_KEEPALIVE_FEATURE
  3101. /**************************************************
  3102. ***************** GCode Handlers *****************
  3103. **************************************************/
  3104. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3105. #define G0_G1_CONDITION !axis_unhomed_error(parser.seen('X'), parser.seen('Y'), parser.seen('Z'))
  3106. #else
  3107. #define G0_G1_CONDITION true
  3108. #endif
  3109. /**
  3110. * G0, G1: Coordinated movement of X Y Z E axes
  3111. */
  3112. inline void gcode_G0_G1(
  3113. #if IS_SCARA
  3114. bool fast_move=false
  3115. #endif
  3116. ) {
  3117. if (IsRunning() && G0_G1_CONDITION) {
  3118. gcode_get_destination(); // For X Y Z E F
  3119. #if ENABLED(FWRETRACT)
  3120. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  3121. // When M209 Autoretract is enabled, convert E-only moves to firmware retract/prime moves
  3122. if (fwretract.autoretract_enabled && parser.seen('E') && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z'))) {
  3123. const float echange = destination[E_CART] - current_position[E_CART];
  3124. // Is this a retract or prime move?
  3125. if (WITHIN(ABS(echange), MIN_AUTORETRACT, MAX_AUTORETRACT) && fwretract.retracted[active_extruder] == (echange > 0.0)) {
  3126. current_position[E_CART] = destination[E_CART]; // Hide a G1-based retract/prime from calculations
  3127. sync_plan_position_e(); // AND from the planner
  3128. return fwretract.retract(echange < 0.0); // Firmware-based retract/prime (double-retract ignored)
  3129. }
  3130. }
  3131. }
  3132. #endif // FWRETRACT
  3133. #if IS_SCARA
  3134. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  3135. #else
  3136. prepare_move_to_destination();
  3137. #endif
  3138. #if ENABLED(NANODLP_Z_SYNC)
  3139. #if ENABLED(NANODLP_ALL_AXIS)
  3140. #define _MOVE_SYNC parser.seenval('X') || parser.seenval('Y') || parser.seenval('Z') // For any move wait and output sync message
  3141. #else
  3142. #define _MOVE_SYNC parser.seenval('Z') // Only for Z move
  3143. #endif
  3144. if (_MOVE_SYNC) {
  3145. planner.synchronize();
  3146. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3147. }
  3148. #endif
  3149. }
  3150. }
  3151. /**
  3152. * G2: Clockwise Arc
  3153. * G3: Counterclockwise Arc
  3154. *
  3155. * This command has two forms: IJ-form and R-form.
  3156. *
  3157. * - I specifies an X offset. J specifies a Y offset.
  3158. * At least one of the IJ parameters is required.
  3159. * X and Y can be omitted to do a complete circle.
  3160. * The given XY is not error-checked. The arc ends
  3161. * based on the angle of the destination.
  3162. * Mixing I or J with R will throw an error.
  3163. *
  3164. * - R specifies the radius. X or Y is required.
  3165. * Omitting both X and Y will throw an error.
  3166. * X or Y must differ from the current XY.
  3167. * Mixing R with I or J will throw an error.
  3168. *
  3169. * - P specifies the number of full circles to do
  3170. * before the specified arc move.
  3171. *
  3172. * Examples:
  3173. *
  3174. * G2 I10 ; CW circle centered at X+10
  3175. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  3176. */
  3177. #if ENABLED(ARC_SUPPORT)
  3178. inline void gcode_G2_G3(const bool clockwise) {
  3179. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3180. if (axis_unhomed_error()) return;
  3181. #endif
  3182. if (IsRunning()) {
  3183. #if ENABLED(SF_ARC_FIX)
  3184. const bool relative_mode_backup = relative_mode;
  3185. relative_mode = true;
  3186. #endif
  3187. gcode_get_destination();
  3188. #if ENABLED(SF_ARC_FIX)
  3189. relative_mode = relative_mode_backup;
  3190. #endif
  3191. float arc_offset[2] = { 0, 0 };
  3192. if (parser.seenval('R')) {
  3193. const float r = parser.value_linear_units(),
  3194. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  3195. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  3196. if (r && (p2 != p1 || q2 != q1)) {
  3197. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  3198. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  3199. d = HYPOT(dx, dy), // Linear distance between the points
  3200. h2 = (r - 0.5f * d) * (r + 0.5f * d), // factor to reduce rounding error
  3201. h = (h2 >= 0) ? SQRT(h2) : 0.0f, // Distance to the arc pivot-point
  3202. mx = (p1 + p2) * 0.5f, my = (q1 + q2) * 0.5f, // Point between the two points
  3203. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  3204. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  3205. arc_offset[0] = cx - p1;
  3206. arc_offset[1] = cy - q1;
  3207. }
  3208. }
  3209. else {
  3210. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  3211. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  3212. }
  3213. if (arc_offset[0] || arc_offset[1]) {
  3214. #if ENABLED(ARC_P_CIRCLES)
  3215. // P indicates number of circles to do
  3216. int8_t circles_to_do = parser.byteval('P');
  3217. if (!WITHIN(circles_to_do, 0, 100)) {
  3218. SERIAL_ERROR_START();
  3219. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3220. }
  3221. while (circles_to_do--)
  3222. plan_arc(current_position, arc_offset, clockwise);
  3223. #endif
  3224. // Send the arc to the planner
  3225. plan_arc(destination, arc_offset, clockwise);
  3226. }
  3227. else {
  3228. // Bad arguments
  3229. SERIAL_ERROR_START();
  3230. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  3231. }
  3232. }
  3233. }
  3234. #endif // ARC_SUPPORT
  3235. void dwell(millis_t time) {
  3236. time += millis();
  3237. while (PENDING(millis(), time)) idle();
  3238. }
  3239. /**
  3240. * G4: Dwell S<seconds> or P<milliseconds>
  3241. */
  3242. inline void gcode_G4() {
  3243. millis_t dwell_ms = 0;
  3244. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  3245. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  3246. planner.synchronize();
  3247. #if ENABLED(NANODLP_Z_SYNC)
  3248. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3249. #endif
  3250. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  3251. dwell(dwell_ms);
  3252. }
  3253. #if ENABLED(BEZIER_CURVE_SUPPORT)
  3254. /**
  3255. * Parameters interpreted according to:
  3256. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  3257. * However I, J omission is not supported at this point; all
  3258. * parameters can be omitted and default to zero.
  3259. */
  3260. /**
  3261. * G5: Cubic B-spline
  3262. */
  3263. inline void gcode_G5() {
  3264. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3265. if (axis_unhomed_error()) return;
  3266. #endif
  3267. if (IsRunning()) {
  3268. #if ENABLED(CNC_WORKSPACE_PLANES)
  3269. if (workspace_plane != PLANE_XY) {
  3270. SERIAL_ERROR_START();
  3271. SERIAL_ERRORLNPGM(MSG_ERR_BAD_PLANE_MODE);
  3272. return;
  3273. }
  3274. #endif
  3275. gcode_get_destination();
  3276. const float offset[] = {
  3277. parser.linearval('I'),
  3278. parser.linearval('J'),
  3279. parser.linearval('P'),
  3280. parser.linearval('Q')
  3281. };
  3282. plan_cubic_move(destination, offset);
  3283. }
  3284. }
  3285. #endif // BEZIER_CURVE_SUPPORT
  3286. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  3287. /**
  3288. * G6 implementation for Hangprinter based on
  3289. * http://reprap.org/wiki/GCodes#G6:_Direct_Stepper_Move
  3290. * Accessed Jan 8, 2018
  3291. *
  3292. * G6 is used frequently to tighten lines with Hangprinter, so Hangprinter default is relative moves.
  3293. * Hangprinter uses switches
  3294. * S1 for absolute moves
  3295. * S2 for saving recording new line length after unregistered move
  3296. * (typically used while tuning LINE_BUILDUP_COMPENSATION_FEATURE parameters)
  3297. */
  3298. /**
  3299. * G6: Direct Stepper Move
  3300. */
  3301. inline void gcode_G6() {
  3302. bool count_it = false;
  3303. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  3304. if (axis_unhomed_error()) return;
  3305. #endif
  3306. if (IsRunning()) {
  3307. float go[MOV_AXIS] = { 0.0 },
  3308. tmp_fr_mm_s = 0.0;
  3309. LOOP_MOV_AXIS(i)
  3310. if (parser.seen(RAW_AXIS_CODES(i)))
  3311. go[i] = parser.value_axis_units((AxisEnum)i);
  3312. #if ENABLED(HANGPRINTER)
  3313. #define GO_SRC line_lengths
  3314. #elif ENABLED(DELTA)
  3315. #define GO_SRC delta
  3316. #else
  3317. #define GO_SRC current_position
  3318. #endif
  3319. if (
  3320. #if ENABLED(HANGPRINTER) // Sending R to another machine is the same as not sending S1 to Hangprinter
  3321. parser.byteval('S') != 2
  3322. #else
  3323. parser.seen('R')
  3324. #endif
  3325. )
  3326. LOOP_MOV_AXIS(i) go[i] += GO_SRC[i];
  3327. else
  3328. LOOP_MOV_AXIS(i) if (!parser.seen(RAW_AXIS_CODES(i))) go[i] += GO_SRC[i];
  3329. tmp_fr_mm_s = parser.linearval('F') > 0.0 ? MMM_TO_MMS(parser.value_feedrate()) : feedrate_mm_s;
  3330. #if ENABLED(HANGPRINTER)
  3331. if (parser.byteval('S') == 2) {
  3332. LOOP_MOV_AXIS(i) line_lengths[i] = go[i];
  3333. count_it = true;
  3334. }
  3335. #endif
  3336. planner.buffer_segment(go[A_AXIS], go[B_AXIS], go[C_AXIS]
  3337. #if ENABLED(HANGPRINTER)
  3338. , go[D_AXIS]
  3339. #endif
  3340. , current_position[E_CART], tmp_fr_mm_s, active_extruder, 0.0, count_it
  3341. );
  3342. }
  3343. }
  3344. #endif
  3345. #if ENABLED(FWRETRACT)
  3346. /**
  3347. * G10 - Retract filament according to settings of M207
  3348. */
  3349. inline void gcode_G10() {
  3350. #if EXTRUDERS > 1
  3351. const bool rs = parser.boolval('S');
  3352. #endif
  3353. fwretract.retract(true
  3354. #if EXTRUDERS > 1
  3355. , rs
  3356. #endif
  3357. );
  3358. }
  3359. /**
  3360. * G11 - Recover filament according to settings of M208
  3361. */
  3362. inline void gcode_G11() { fwretract.retract(false); }
  3363. #endif // FWRETRACT
  3364. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  3365. /**
  3366. * G12: Clean the nozzle
  3367. */
  3368. inline void gcode_G12() {
  3369. // Don't allow nozzle cleaning without homing first
  3370. if (axis_unhomed_error()) return;
  3371. const uint8_t pattern = parser.ushortval('P', 0),
  3372. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  3373. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  3374. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  3375. Nozzle::clean(pattern, strokes, radius, objects);
  3376. }
  3377. #endif
  3378. #if ENABLED(CNC_WORKSPACE_PLANES)
  3379. inline void report_workspace_plane() {
  3380. SERIAL_ECHO_START();
  3381. SERIAL_ECHOPGM("Workspace Plane ");
  3382. serialprintPGM(
  3383. workspace_plane == PLANE_YZ ? PSTR("YZ\n") :
  3384. workspace_plane == PLANE_ZX ? PSTR("ZX\n") :
  3385. PSTR("XY\n")
  3386. );
  3387. }
  3388. inline void set_workspace_plane(const WorkspacePlane plane) {
  3389. workspace_plane = plane;
  3390. if (DEBUGGING(INFO)) report_workspace_plane();
  3391. }
  3392. /**
  3393. * G17: Select Plane XY
  3394. * G18: Select Plane ZX
  3395. * G19: Select Plane YZ
  3396. */
  3397. inline void gcode_G17() { set_workspace_plane(PLANE_XY); }
  3398. inline void gcode_G18() { set_workspace_plane(PLANE_ZX); }
  3399. inline void gcode_G19() { set_workspace_plane(PLANE_YZ); }
  3400. #endif // CNC_WORKSPACE_PLANES
  3401. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  3402. /**
  3403. * Select a coordinate system and update the workspace offset.
  3404. * System index -1 is used to specify machine-native.
  3405. */
  3406. bool select_coordinate_system(const int8_t _new) {
  3407. if (active_coordinate_system == _new) return false;
  3408. float old_offset[XYZ] = { 0 }, new_offset[XYZ] = { 0 };
  3409. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  3410. COPY(old_offset, coordinate_system[active_coordinate_system]);
  3411. if (WITHIN(_new, 0, MAX_COORDINATE_SYSTEMS - 1))
  3412. COPY(new_offset, coordinate_system[_new]);
  3413. active_coordinate_system = _new;
  3414. LOOP_XYZ(i) {
  3415. const float diff = new_offset[i] - old_offset[i];
  3416. if (diff) {
  3417. position_shift[i] += diff;
  3418. update_software_endstops((AxisEnum)i);
  3419. }
  3420. }
  3421. return true;
  3422. }
  3423. /**
  3424. * G53: Apply native workspace to the current move
  3425. *
  3426. * In CNC G-code G53 is a modifier.
  3427. * It precedes a movement command (or other modifiers) on the same line.
  3428. * This is the first command to use parser.chain() to make this possible.
  3429. *
  3430. * Marlin also uses G53 on a line by itself to go back to native space.
  3431. */
  3432. inline void gcode_G53() {
  3433. const int8_t _system = active_coordinate_system;
  3434. active_coordinate_system = -1;
  3435. if (parser.chain()) { // If this command has more following...
  3436. process_parsed_command();
  3437. active_coordinate_system = _system;
  3438. }
  3439. }
  3440. /**
  3441. * G54-G59.3: Select a new workspace
  3442. *
  3443. * A workspace is an XYZ offset to the machine native space.
  3444. * All workspaces default to 0,0,0 at start, or with EEPROM
  3445. * support they may be restored from a previous session.
  3446. *
  3447. * G92 is used to set the current workspace's offset.
  3448. */
  3449. inline void gcode_G54_59(uint8_t subcode=0) {
  3450. const int8_t _space = parser.codenum - 54 + subcode;
  3451. if (select_coordinate_system(_space)) {
  3452. SERIAL_PROTOCOLLNPAIR("Select workspace ", _space);
  3453. report_current_position();
  3454. }
  3455. }
  3456. FORCE_INLINE void gcode_G54() { gcode_G54_59(); }
  3457. FORCE_INLINE void gcode_G55() { gcode_G54_59(); }
  3458. FORCE_INLINE void gcode_G56() { gcode_G54_59(); }
  3459. FORCE_INLINE void gcode_G57() { gcode_G54_59(); }
  3460. FORCE_INLINE void gcode_G58() { gcode_G54_59(); }
  3461. FORCE_INLINE void gcode_G59() { gcode_G54_59(parser.subcode); }
  3462. #endif
  3463. #if ENABLED(INCH_MODE_SUPPORT)
  3464. /**
  3465. * G20: Set input mode to inches
  3466. */
  3467. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  3468. /**
  3469. * G21: Set input mode to millimeters
  3470. */
  3471. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  3472. #endif
  3473. #if ENABLED(NOZZLE_PARK_FEATURE)
  3474. /**
  3475. * G27: Park the nozzle
  3476. */
  3477. inline void gcode_G27() {
  3478. // Don't allow nozzle parking without homing first
  3479. if (axis_unhomed_error()) return;
  3480. Nozzle::park(parser.ushortval('P'));
  3481. }
  3482. #endif // NOZZLE_PARK_FEATURE
  3483. #if ENABLED(QUICK_HOME)
  3484. static void quick_home_xy() {
  3485. // Pretend the current position is 0,0
  3486. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3487. sync_plan_position();
  3488. const int x_axis_home_dir =
  3489. #if ENABLED(DUAL_X_CARRIAGE)
  3490. x_home_dir(active_extruder)
  3491. #else
  3492. home_dir(X_AXIS)
  3493. #endif
  3494. ;
  3495. const float mlx = max_length(X_AXIS),
  3496. mly = max_length(Y_AXIS),
  3497. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  3498. fr_mm_s = MIN(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  3499. #if ENABLED(SENSORLESS_HOMING)
  3500. sensorless_homing_per_axis(X_AXIS);
  3501. sensorless_homing_per_axis(Y_AXIS);
  3502. #endif
  3503. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  3504. endstops.validate_homing_move();
  3505. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  3506. #if ENABLED(SENSORLESS_HOMING)
  3507. sensorless_homing_per_axis(X_AXIS, false);
  3508. sensorless_homing_per_axis(Y_AXIS, false);
  3509. #endif
  3510. }
  3511. #endif // QUICK_HOME
  3512. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3513. void log_machine_info() {
  3514. SERIAL_ECHOPGM("Machine Type: ");
  3515. #if ENABLED(DELTA)
  3516. SERIAL_ECHOLNPGM("Delta");
  3517. #elif IS_SCARA
  3518. SERIAL_ECHOLNPGM("SCARA");
  3519. #elif IS_CORE
  3520. SERIAL_ECHOLNPGM("Core");
  3521. #else
  3522. SERIAL_ECHOLNPGM("Cartesian");
  3523. #endif
  3524. SERIAL_ECHOPGM("Probe: ");
  3525. #if ENABLED(PROBE_MANUALLY)
  3526. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  3527. #elif ENABLED(FIX_MOUNTED_PROBE)
  3528. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3529. #elif ENABLED(BLTOUCH)
  3530. SERIAL_ECHOLNPGM("BLTOUCH");
  3531. #elif HAS_Z_SERVO_PROBE
  3532. SERIAL_ECHOLNPGM("SERVO PROBE");
  3533. #elif ENABLED(Z_PROBE_SLED)
  3534. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3535. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3536. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3537. #else
  3538. SERIAL_ECHOLNPGM("NONE");
  3539. #endif
  3540. #if HAS_BED_PROBE
  3541. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3542. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3543. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3544. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3545. SERIAL_ECHOPGM(" (Right");
  3546. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3547. SERIAL_ECHOPGM(" (Left");
  3548. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3549. SERIAL_ECHOPGM(" (Middle");
  3550. #else
  3551. SERIAL_ECHOPGM(" (Aligned With");
  3552. #endif
  3553. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3554. #if IS_SCARA
  3555. SERIAL_ECHOPGM("-Distal");
  3556. #else
  3557. SERIAL_ECHOPGM("-Back");
  3558. #endif
  3559. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3560. #if IS_SCARA
  3561. SERIAL_ECHOPGM("-Proximal");
  3562. #else
  3563. SERIAL_ECHOPGM("-Front");
  3564. #endif
  3565. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3566. SERIAL_ECHOPGM("-Center");
  3567. #endif
  3568. if (zprobe_zoffset < 0)
  3569. SERIAL_ECHOPGM(" & Below");
  3570. else if (zprobe_zoffset > 0)
  3571. SERIAL_ECHOPGM(" & Above");
  3572. else
  3573. SERIAL_ECHOPGM(" & Same Z as");
  3574. SERIAL_ECHOLNPGM(" Nozzle)");
  3575. #endif
  3576. #if HAS_ABL
  3577. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3578. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3579. SERIAL_ECHOPGM("LINEAR");
  3580. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3581. SERIAL_ECHOPGM("BILINEAR");
  3582. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3583. SERIAL_ECHOPGM("3POINT");
  3584. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3585. SERIAL_ECHOPGM("UBL");
  3586. #endif
  3587. if (planner.leveling_active) {
  3588. SERIAL_ECHOLNPGM(" (enabled)");
  3589. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3590. if (planner.z_fade_height)
  3591. SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height);
  3592. #endif
  3593. #if ABL_PLANAR
  3594. const float diff[XYZ] = {
  3595. planner.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3596. planner.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3597. planner.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3598. };
  3599. SERIAL_ECHOPGM("ABL Adjustment X");
  3600. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3601. SERIAL_ECHO(diff[X_AXIS]);
  3602. SERIAL_ECHOPGM(" Y");
  3603. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3604. SERIAL_ECHO(diff[Y_AXIS]);
  3605. SERIAL_ECHOPGM(" Z");
  3606. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3607. SERIAL_ECHO(diff[Z_AXIS]);
  3608. #else
  3609. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3610. SERIAL_ECHOPGM("UBL Adjustment Z");
  3611. const float rz = ubl.get_z_correction(current_position[X_AXIS], current_position[Y_AXIS]);
  3612. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3613. SERIAL_ECHOPAIR("Bilinear Grid X", bilinear_start[X_AXIS]);
  3614. SERIAL_ECHOPAIR(" Y", bilinear_start[Y_AXIS]);
  3615. SERIAL_ECHOPAIR(" W", ABL_BG_SPACING(X_AXIS));
  3616. SERIAL_ECHOLNPAIR(" H", ABL_BG_SPACING(Y_AXIS));
  3617. SERIAL_ECHOPGM("ABL Adjustment Z");
  3618. const float rz = bilinear_z_offset(current_position);
  3619. #endif
  3620. SERIAL_ECHO(ftostr43sign(rz, '+'));
  3621. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3622. if (planner.z_fade_height) {
  3623. SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position[Z_AXIS]), '+'));
  3624. SERIAL_CHAR(')');
  3625. }
  3626. #endif
  3627. #endif
  3628. }
  3629. else
  3630. SERIAL_ECHOLNPGM(" (disabled)");
  3631. SERIAL_EOL();
  3632. #elif ENABLED(MESH_BED_LEVELING)
  3633. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3634. if (planner.leveling_active) {
  3635. SERIAL_ECHOLNPGM(" (enabled)");
  3636. SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS]
  3637. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3638. , 1.0
  3639. #endif
  3640. ), '+'));
  3641. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  3642. if (planner.z_fade_height) {
  3643. SERIAL_ECHOPAIR(" (", ftostr43sign(
  3644. mbl.get_z(current_position[X_AXIS], current_position[Y_AXIS], planner.fade_scaling_factor_for_z(current_position[Z_AXIS])), '+'
  3645. ));
  3646. SERIAL_CHAR(')');
  3647. }
  3648. #endif
  3649. }
  3650. else
  3651. SERIAL_ECHOPGM(" (disabled)");
  3652. SERIAL_EOL();
  3653. #endif // MESH_BED_LEVELING
  3654. }
  3655. #endif // DEBUG_LEVELING_FEATURE
  3656. #if ENABLED(DELTA)
  3657. #if ENABLED(SENSORLESS_HOMING)
  3658. inline void delta_sensorless_homing(const bool on=true) {
  3659. sensorless_homing_per_axis(A_AXIS, on);
  3660. sensorless_homing_per_axis(B_AXIS, on);
  3661. sensorless_homing_per_axis(C_AXIS, on);
  3662. }
  3663. #endif
  3664. /**
  3665. * A delta can only safely home all axes at the same time
  3666. * This is like quick_home_xy() but for 3 towers.
  3667. */
  3668. inline void home_delta() {
  3669. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3670. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3671. #endif
  3672. // Init the current position of all carriages to 0,0,0
  3673. ZERO(current_position);
  3674. sync_plan_position();
  3675. // Disable stealthChop if used. Enable diag1 pin on driver.
  3676. #if ENABLED(SENSORLESS_HOMING)
  3677. delta_sensorless_homing();
  3678. #endif
  3679. // Move all carriages together linearly until an endstop is hit.
  3680. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (delta_height + 10
  3681. #if HAS_BED_PROBE
  3682. - zprobe_zoffset
  3683. #endif
  3684. );
  3685. feedrate_mm_s = homing_feedrate(X_AXIS);
  3686. buffer_line_to_current_position();
  3687. planner.synchronize();
  3688. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  3689. #if ENABLED(SENSORLESS_HOMING)
  3690. delta_sensorless_homing(false);
  3691. #endif
  3692. endstops.validate_homing_move();
  3693. // At least one carriage has reached the top.
  3694. // Now re-home each carriage separately.
  3695. homeaxis(A_AXIS);
  3696. homeaxis(B_AXIS);
  3697. homeaxis(C_AXIS);
  3698. // Set all carriages to their home positions
  3699. // Do this here all at once for Delta, because
  3700. // XYZ isn't ABC. Applying this per-tower would
  3701. // give the impression that they are the same.
  3702. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3703. SYNC_PLAN_POSITION_KINEMATIC();
  3704. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3705. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3706. #endif
  3707. }
  3708. #elif ENABLED(HANGPRINTER)
  3709. /**
  3710. * A hangprinter cannot home itself
  3711. */
  3712. inline void home_hangprinter() {
  3713. SERIAL_ECHOLNPGM("Warning: G28 is not implemented for Hangprinter.");
  3714. }
  3715. #endif
  3716. #ifdef Z_AFTER_PROBING
  3717. void move_z_after_probing() {
  3718. if (current_position[Z_AXIS] != Z_AFTER_PROBING) {
  3719. do_blocking_move_to_z(Z_AFTER_PROBING);
  3720. current_position[Z_AXIS] = Z_AFTER_PROBING;
  3721. }
  3722. }
  3723. #endif
  3724. #if ENABLED(Z_SAFE_HOMING)
  3725. inline void home_z_safely() {
  3726. // Disallow Z homing if X or Y are unknown
  3727. if (!TEST(axis_known_position, X_AXIS) || !TEST(axis_known_position, Y_AXIS)) {
  3728. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3729. SERIAL_ECHO_START();
  3730. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3731. return;
  3732. }
  3733. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3734. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3735. #endif
  3736. SYNC_PLAN_POSITION_KINEMATIC();
  3737. /**
  3738. * Move the Z probe (or just the nozzle) to the safe homing point
  3739. */
  3740. destination[X_AXIS] = Z_SAFE_HOMING_X_POINT;
  3741. destination[Y_AXIS] = Z_SAFE_HOMING_Y_POINT;
  3742. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3743. #if HOMING_Z_WITH_PROBE
  3744. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3745. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3746. #endif
  3747. if (position_is_reachable(destination[X_AXIS], destination[Y_AXIS])) {
  3748. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3749. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3750. #endif
  3751. // This causes the carriage on Dual X to unpark
  3752. #if ENABLED(DUAL_X_CARRIAGE)
  3753. active_extruder_parked = false;
  3754. #endif
  3755. #if ENABLED(SENSORLESS_HOMING)
  3756. safe_delay(500); // Short delay needed to settle
  3757. #endif
  3758. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3759. homeaxis(Z_AXIS);
  3760. }
  3761. else {
  3762. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3763. SERIAL_ECHO_START();
  3764. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3765. }
  3766. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3767. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3768. #endif
  3769. }
  3770. #endif // Z_SAFE_HOMING
  3771. #if ENABLED(PROBE_MANUALLY)
  3772. bool g29_in_progress = false;
  3773. #else
  3774. constexpr bool g29_in_progress = false;
  3775. #endif
  3776. /**
  3777. * G28: Home all axes according to settings
  3778. *
  3779. * Parameters
  3780. *
  3781. * None Home to all axes with no parameters.
  3782. * With QUICK_HOME enabled XY will home together, then Z.
  3783. *
  3784. * O Home only if position is unknown
  3785. *
  3786. * Rn Raise by n mm/inches before homing
  3787. *
  3788. * Cartesian parameters
  3789. *
  3790. * X Home to the X endstop
  3791. * Y Home to the Y endstop
  3792. * Z Home to the Z endstop
  3793. *
  3794. */
  3795. inline void gcode_G28(const bool always_home_all) {
  3796. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3797. if (DEBUGGING(LEVELING)) {
  3798. SERIAL_ECHOLNPGM(">>> G28");
  3799. log_machine_info();
  3800. }
  3801. #endif
  3802. #if ENABLED(MARLIN_DEV_MODE)
  3803. if (parser.seen('S')) {
  3804. LOOP_XYZ(a) set_axis_is_at_home((AxisEnum)a);
  3805. SYNC_PLAN_POSITION_KINEMATIC();
  3806. SERIAL_ECHOLNPGM("Simulated Homing");
  3807. report_current_position();
  3808. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3809. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3810. #endif
  3811. return;
  3812. }
  3813. #endif
  3814. if (all_axes_known() && parser.boolval('O')) { // home only if needed
  3815. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3816. if (DEBUGGING(LEVELING)) {
  3817. SERIAL_ECHOLNPGM("> homing not needed, skip");
  3818. SERIAL_ECHOLNPGM("<<< G28");
  3819. }
  3820. #endif
  3821. return;
  3822. }
  3823. // Wait for planner moves to finish!
  3824. planner.synchronize();
  3825. // Cancel the active G29 session
  3826. #if ENABLED(PROBE_MANUALLY)
  3827. g29_in_progress = false;
  3828. #endif
  3829. // Disable the leveling matrix before homing
  3830. #if HAS_LEVELING
  3831. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3832. const bool leveling_was_active = planner.leveling_active;
  3833. #endif
  3834. set_bed_leveling_enabled(false);
  3835. #endif
  3836. #if ENABLED(CNC_WORKSPACE_PLANES)
  3837. workspace_plane = PLANE_XY;
  3838. #endif
  3839. #if ENABLED(BLTOUCH)
  3840. // Make sure any BLTouch error condition is cleared
  3841. bltouch_command(BLTOUCH_RESET, BLTOUCH_RESET_DELAY);
  3842. set_bltouch_deployed(false);
  3843. #endif
  3844. // Always home with tool 0 active
  3845. #if HOTENDS > 1
  3846. #if DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3847. const uint8_t old_tool_index = active_extruder;
  3848. #endif
  3849. tool_change(0, 0, true);
  3850. #endif
  3851. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3852. extruder_duplication_enabled = false;
  3853. #endif
  3854. setup_for_endstop_or_probe_move();
  3855. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3856. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3857. #endif
  3858. endstops.enable(true); // Enable endstops for next homing move
  3859. #if ENABLED(DELTA)
  3860. home_delta();
  3861. UNUSED(always_home_all);
  3862. #elif ENABLED(HANGPRINTER)
  3863. home_hangprinter();
  3864. UNUSED(always_home_all);
  3865. #else // NOT Delta or Hangprinter
  3866. const bool homeX = always_home_all || parser.seen('X'),
  3867. homeY = always_home_all || parser.seen('Y'),
  3868. homeZ = always_home_all || parser.seen('Z'),
  3869. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3870. set_destination_from_current();
  3871. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3872. if (home_all || homeZ) homeaxis(Z_AXIS);
  3873. #endif
  3874. const float z_homing_height = (
  3875. #if ENABLED(UNKNOWN_Z_NO_RAISE)
  3876. !TEST(axis_known_position, Z_AXIS) ? 0 :
  3877. #endif
  3878. (parser.seenval('R') ? parser.value_linear_units() : Z_HOMING_HEIGHT)
  3879. );
  3880. if (z_homing_height && (home_all || homeX || homeY)) {
  3881. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3882. destination[Z_AXIS] = z_homing_height;
  3883. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3884. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3885. if (DEBUGGING(LEVELING))
  3886. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3887. #endif
  3888. do_blocking_move_to_z(destination[Z_AXIS]);
  3889. }
  3890. }
  3891. #if ENABLED(QUICK_HOME)
  3892. if (home_all || (homeX && homeY)) quick_home_xy();
  3893. #endif
  3894. // Home Y (before X)
  3895. #if ENABLED(HOME_Y_BEFORE_X)
  3896. if (home_all || homeY
  3897. #if ENABLED(CODEPENDENT_XY_HOMING)
  3898. || homeX
  3899. #endif
  3900. ) homeaxis(Y_AXIS);
  3901. #endif
  3902. // Home X
  3903. if (home_all || homeX
  3904. #if ENABLED(CODEPENDENT_XY_HOMING) && DISABLED(HOME_Y_BEFORE_X)
  3905. || homeY
  3906. #endif
  3907. ) {
  3908. #if ENABLED(DUAL_X_CARRIAGE)
  3909. // Always home the 2nd (right) extruder first
  3910. active_extruder = 1;
  3911. homeaxis(X_AXIS);
  3912. // Remember this extruder's position for later tool change
  3913. inactive_extruder_x_pos = current_position[X_AXIS];
  3914. // Home the 1st (left) extruder
  3915. active_extruder = 0;
  3916. homeaxis(X_AXIS);
  3917. // Consider the active extruder to be parked
  3918. COPY(raised_parked_position, current_position);
  3919. delayed_move_time = 0;
  3920. active_extruder_parked = true;
  3921. #else
  3922. homeaxis(X_AXIS);
  3923. #endif
  3924. }
  3925. // Home Y (after X)
  3926. #if DISABLED(HOME_Y_BEFORE_X)
  3927. if (home_all || homeY) homeaxis(Y_AXIS);
  3928. #endif
  3929. // Home Z last if homing towards the bed
  3930. #if Z_HOME_DIR < 0
  3931. if (home_all || homeZ) {
  3932. #if ENABLED(Z_SAFE_HOMING)
  3933. home_z_safely();
  3934. #else
  3935. homeaxis(Z_AXIS);
  3936. #endif
  3937. #if HOMING_Z_WITH_PROBE && defined(Z_AFTER_PROBING)
  3938. move_z_after_probing();
  3939. #endif
  3940. } // home_all || homeZ
  3941. #endif // Z_HOME_DIR < 0
  3942. SYNC_PLAN_POSITION_KINEMATIC();
  3943. #endif // !DELTA (gcode_G28)
  3944. endstops.not_homing();
  3945. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3946. // move to a height where we can use the full xy-area
  3947. do_blocking_move_to_z(delta_clip_start_height);
  3948. #endif
  3949. #if ENABLED(RESTORE_LEVELING_AFTER_G28)
  3950. set_bed_leveling_enabled(leveling_was_active);
  3951. #endif
  3952. clean_up_after_endstop_or_probe_move();
  3953. // Restore the active tool after homing
  3954. #if HOTENDS > 1 && (DISABLED(DELTA) || ENABLED(DELTA_HOME_TO_SAFE_ZONE))
  3955. #if ENABLED(PARKING_EXTRUDER)
  3956. #define NO_FETCH false // fetch the previous toolhead
  3957. #else
  3958. #define NO_FETCH true
  3959. #endif
  3960. tool_change(old_tool_index, 0, NO_FETCH);
  3961. #endif
  3962. lcd_refresh();
  3963. report_current_position();
  3964. #if ENABLED(NANODLP_Z_SYNC)
  3965. #if ENABLED(NANODLP_ALL_AXIS)
  3966. #define _HOME_SYNC true // For any axis, output sync text.
  3967. #else
  3968. #define _HOME_SYNC (home_all || homeZ) // Only for Z-axis
  3969. #endif
  3970. if (_HOME_SYNC)
  3971. SERIAL_ECHOLNPGM(MSG_Z_MOVE_COMP);
  3972. #endif
  3973. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3974. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G28");
  3975. #endif
  3976. } // G28
  3977. void home_all_axes() { gcode_G28(true); }
  3978. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3979. inline void _manual_goto_xy(const float &rx, const float &ry) {
  3980. #ifdef MANUAL_PROBE_START_Z
  3981. #if MANUAL_PROBE_HEIGHT > 0
  3982. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3983. do_blocking_move_to_z(MAX(0,MANUAL_PROBE_START_Z));
  3984. #else
  3985. do_blocking_move_to(rx, ry, MAX(0,MANUAL_PROBE_START_Z));
  3986. #endif
  3987. #elif MANUAL_PROBE_HEIGHT > 0
  3988. const float prev_z = current_position[Z_AXIS];
  3989. do_blocking_move_to(rx, ry, MANUAL_PROBE_HEIGHT);
  3990. do_blocking_move_to_z(prev_z);
  3991. #else
  3992. do_blocking_move_to_xy(rx, ry);
  3993. #endif
  3994. current_position[X_AXIS] = rx;
  3995. current_position[Y_AXIS] = ry;
  3996. #if ENABLED(LCD_BED_LEVELING)
  3997. lcd_wait_for_move = false;
  3998. #endif
  3999. }
  4000. #endif
  4001. #if ENABLED(MESH_BED_LEVELING)
  4002. // Save 130 bytes with non-duplication of PSTR
  4003. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  4004. /**
  4005. * G29: Mesh-based Z probe, probes a grid and produces a
  4006. * mesh to compensate for variable bed height
  4007. *
  4008. * Parameters With MESH_BED_LEVELING:
  4009. *
  4010. * S0 Produce a mesh report
  4011. * S1 Start probing mesh points
  4012. * S2 Probe the next mesh point
  4013. * S3 Xn Yn Zn.nn Manually modify a single point
  4014. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  4015. * S5 Reset and disable mesh
  4016. *
  4017. * The S0 report the points as below
  4018. *
  4019. * +----> X-axis 1-n
  4020. * |
  4021. * |
  4022. * v Y-axis 1-n
  4023. *
  4024. */
  4025. inline void gcode_G29() {
  4026. static int mbl_probe_index = -1;
  4027. #if HAS_SOFTWARE_ENDSTOPS
  4028. static bool enable_soft_endstops;
  4029. #endif
  4030. MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  4031. if (!WITHIN(state, 0, 5)) {
  4032. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  4033. return;
  4034. }
  4035. int8_t px, py;
  4036. switch (state) {
  4037. case MeshReport:
  4038. if (leveling_is_valid()) {
  4039. SERIAL_PROTOCOLLNPAIR("State: ", planner.leveling_active ? MSG_ON : MSG_OFF);
  4040. mbl.report_mesh();
  4041. }
  4042. else
  4043. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  4044. break;
  4045. case MeshStart:
  4046. mbl.reset();
  4047. mbl_probe_index = 0;
  4048. if (!lcd_wait_for_move) {
  4049. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  4050. return;
  4051. }
  4052. state = MeshNext;
  4053. case MeshNext:
  4054. if (mbl_probe_index < 0) {
  4055. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  4056. return;
  4057. }
  4058. // For each G29 S2...
  4059. if (mbl_probe_index == 0) {
  4060. #if HAS_SOFTWARE_ENDSTOPS
  4061. // For the initial G29 S2 save software endstop state
  4062. enable_soft_endstops = soft_endstops_enabled;
  4063. #endif
  4064. // Move close to the bed before the first point
  4065. do_blocking_move_to_z(0);
  4066. }
  4067. else {
  4068. // Save Z for the previous mesh position
  4069. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  4070. #if HAS_SOFTWARE_ENDSTOPS
  4071. soft_endstops_enabled = enable_soft_endstops;
  4072. #endif
  4073. }
  4074. // If there's another point to sample, move there with optional lift.
  4075. if (mbl_probe_index < GRID_MAX_POINTS) {
  4076. #if HAS_SOFTWARE_ENDSTOPS
  4077. // Disable software endstops to allow manual adjustment
  4078. // If G29 is not completed, they will not be re-enabled
  4079. soft_endstops_enabled = false;
  4080. #endif
  4081. mbl.zigzag(mbl_probe_index++, px, py);
  4082. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  4083. }
  4084. else {
  4085. // One last "return to the bed" (as originally coded) at completion
  4086. current_position[Z_AXIS] = MANUAL_PROBE_HEIGHT;
  4087. buffer_line_to_current_position();
  4088. planner.synchronize();
  4089. // After recording the last point, activate home and activate
  4090. mbl_probe_index = -1;
  4091. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  4092. BUZZ(100, 659);
  4093. BUZZ(100, 698);
  4094. home_all_axes();
  4095. set_bed_leveling_enabled(true);
  4096. #if ENABLED(MESH_G28_REST_ORIGIN)
  4097. current_position[Z_AXIS] = 0;
  4098. set_destination_from_current();
  4099. buffer_line_to_destination(homing_feedrate(Z_AXIS));
  4100. planner.synchronize();
  4101. #endif
  4102. #if ENABLED(LCD_BED_LEVELING)
  4103. lcd_wait_for_move = false;
  4104. #endif
  4105. }
  4106. break;
  4107. case MeshSet:
  4108. if (parser.seenval('X')) {
  4109. px = parser.value_int() - 1;
  4110. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  4111. SERIAL_PROTOCOLPAIR("X out of range (1-", int(GRID_MAX_POINTS_X));
  4112. SERIAL_PROTOCOLLNPGM(")");
  4113. return;
  4114. }
  4115. }
  4116. else {
  4117. SERIAL_CHAR('X'); echo_not_entered();
  4118. return;
  4119. }
  4120. if (parser.seenval('Y')) {
  4121. py = parser.value_int() - 1;
  4122. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  4123. SERIAL_PROTOCOLPAIR("Y out of range (1-", int(GRID_MAX_POINTS_Y));
  4124. SERIAL_PROTOCOLLNPGM(")");
  4125. return;
  4126. }
  4127. }
  4128. else {
  4129. SERIAL_CHAR('Y'); echo_not_entered();
  4130. return;
  4131. }
  4132. if (parser.seenval('Z'))
  4133. mbl.z_values[px][py] = parser.value_linear_units();
  4134. else {
  4135. SERIAL_CHAR('Z'); echo_not_entered();
  4136. return;
  4137. }
  4138. break;
  4139. case MeshSetZOffset:
  4140. if (parser.seenval('Z'))
  4141. mbl.z_offset = parser.value_linear_units();
  4142. else {
  4143. SERIAL_CHAR('Z'); echo_not_entered();
  4144. return;
  4145. }
  4146. break;
  4147. case MeshReset:
  4148. reset_bed_level();
  4149. break;
  4150. } // switch (state)
  4151. if (state == MeshNext) {
  4152. SERIAL_PROTOCOLPAIR("MBL G29 point ", MIN(mbl_probe_index, GRID_MAX_POINTS));
  4153. SERIAL_PROTOCOLLNPAIR(" of ", int(GRID_MAX_POINTS));
  4154. }
  4155. report_current_position();
  4156. }
  4157. #elif OLDSCHOOL_ABL
  4158. #if ABL_GRID
  4159. #if ENABLED(PROBE_Y_FIRST)
  4160. #define PR_OUTER_VAR xCount
  4161. #define PR_OUTER_END abl_grid_points_x
  4162. #define PR_INNER_VAR yCount
  4163. #define PR_INNER_END abl_grid_points_y
  4164. #else
  4165. #define PR_OUTER_VAR yCount
  4166. #define PR_OUTER_END abl_grid_points_y
  4167. #define PR_INNER_VAR xCount
  4168. #define PR_INNER_END abl_grid_points_x
  4169. #endif
  4170. #endif
  4171. /**
  4172. * G29: Detailed Z probe, probes the bed at 3 or more points.
  4173. * Will fail if the printer has not been homed with G28.
  4174. *
  4175. * Enhanced G29 Auto Bed Leveling Probe Routine
  4176. *
  4177. * O Auto-level only if needed
  4178. *
  4179. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  4180. * or alter the bed level data. Useful to check the topology
  4181. * after a first run of G29.
  4182. *
  4183. * J Jettison current bed leveling data
  4184. *
  4185. * V Set the verbose level (0-4). Example: "G29 V3"
  4186. *
  4187. * Parameters With LINEAR leveling only:
  4188. *
  4189. * P Set the size of the grid that will be probed (P x P points).
  4190. * Example: "G29 P4"
  4191. *
  4192. * X Set the X size of the grid that will be probed (X x Y points).
  4193. * Example: "G29 X7 Y5"
  4194. *
  4195. * Y Set the Y size of the grid that will be probed (X x Y points).
  4196. *
  4197. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  4198. * This is useful for manual bed leveling and finding flaws in the bed (to
  4199. * assist with part placement).
  4200. * Not supported by non-linear delta printer bed leveling.
  4201. *
  4202. * Parameters With LINEAR and BILINEAR leveling only:
  4203. *
  4204. * S Set the XY travel speed between probe points (in units/min)
  4205. *
  4206. * F Set the Front limit of the probing grid
  4207. * B Set the Back limit of the probing grid
  4208. * L Set the Left limit of the probing grid
  4209. * R Set the Right limit of the probing grid
  4210. *
  4211. * Parameters with DEBUG_LEVELING_FEATURE only:
  4212. *
  4213. * C Make a totally fake grid with no actual probing.
  4214. * For use in testing when no probing is possible.
  4215. *
  4216. * Parameters with BILINEAR leveling only:
  4217. *
  4218. * Z Supply an additional Z probe offset
  4219. *
  4220. * Extra parameters with PROBE_MANUALLY:
  4221. *
  4222. * To do manual probing simply repeat G29 until the procedure is complete.
  4223. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  4224. *
  4225. * Q Query leveling and G29 state
  4226. *
  4227. * A Abort current leveling procedure
  4228. *
  4229. * Extra parameters with BILINEAR only:
  4230. *
  4231. * W Write a mesh point. (If G29 is idle.)
  4232. * I X index for mesh point
  4233. * J Y index for mesh point
  4234. * X X for mesh point, overrides I
  4235. * Y Y for mesh point, overrides J
  4236. * Z Z for mesh point. Otherwise, raw current Z.
  4237. *
  4238. * Without PROBE_MANUALLY:
  4239. *
  4240. * E By default G29 will engage the Z probe, test the bed, then disengage.
  4241. * Include "E" to engage/disengage the Z probe for each sample.
  4242. * There's no extra effect if you have a fixed Z probe.
  4243. *
  4244. */
  4245. inline void gcode_G29() {
  4246. #if ENABLED(DEBUG_LEVELING_FEATURE) || ENABLED(PROBE_MANUALLY)
  4247. const bool seenQ = parser.seen('Q');
  4248. #else
  4249. constexpr bool seenQ = false;
  4250. #endif
  4251. // G29 Q is also available if debugging
  4252. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4253. const uint8_t old_debug_flags = marlin_debug_flags;
  4254. if (seenQ) marlin_debug_flags |= DEBUG_LEVELING;
  4255. if (DEBUGGING(LEVELING)) {
  4256. DEBUG_POS(">>> G29", current_position);
  4257. log_machine_info();
  4258. }
  4259. marlin_debug_flags = old_debug_flags;
  4260. #if DISABLED(PROBE_MANUALLY)
  4261. if (seenQ) return;
  4262. #endif
  4263. #endif
  4264. #if ENABLED(PROBE_MANUALLY)
  4265. const bool seenA = parser.seen('A');
  4266. #else
  4267. constexpr bool seenA = false;
  4268. #endif
  4269. const bool no_action = seenA || seenQ,
  4270. faux =
  4271. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  4272. parser.boolval('C')
  4273. #else
  4274. no_action
  4275. #endif
  4276. ;
  4277. // Don't allow auto-leveling without homing first
  4278. if (axis_unhomed_error()) return;
  4279. if (!no_action && planner.leveling_active && parser.boolval('O')) { // Auto-level only if needed
  4280. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4281. if (DEBUGGING(LEVELING)) {
  4282. SERIAL_ECHOLNPGM("> Auto-level not needed, skip");
  4283. SERIAL_ECHOLNPGM("<<< G29");
  4284. }
  4285. #endif
  4286. return;
  4287. }
  4288. // Define local vars 'static' for manual probing, 'auto' otherwise
  4289. #if ENABLED(PROBE_MANUALLY)
  4290. #define ABL_VAR static
  4291. #else
  4292. #define ABL_VAR
  4293. #endif
  4294. ABL_VAR int verbose_level;
  4295. ABL_VAR float xProbe, yProbe, measured_z;
  4296. ABL_VAR bool dryrun, abl_should_enable;
  4297. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4298. ABL_VAR int16_t abl_probe_index;
  4299. #endif
  4300. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  4301. ABL_VAR bool enable_soft_endstops = true;
  4302. #endif
  4303. #if ABL_GRID
  4304. #if ENABLED(PROBE_MANUALLY)
  4305. ABL_VAR uint8_t PR_OUTER_VAR;
  4306. ABL_VAR int8_t PR_INNER_VAR;
  4307. #endif
  4308. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  4309. ABL_VAR float xGridSpacing = 0, yGridSpacing = 0;
  4310. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4311. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  4312. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4313. ABL_VAR bool do_topography_map;
  4314. #else // Bilinear
  4315. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  4316. abl_grid_points_y = GRID_MAX_POINTS_Y;
  4317. #endif
  4318. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4319. ABL_VAR int16_t abl_points;
  4320. #elif ENABLED(PROBE_MANUALLY) // Bilinear
  4321. int16_t constexpr abl_points = GRID_MAX_POINTS;
  4322. #endif
  4323. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4324. ABL_VAR float zoffset;
  4325. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4326. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  4327. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  4328. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  4329. mean;
  4330. #endif
  4331. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4332. #if ENABLED(PROBE_MANUALLY)
  4333. int8_t constexpr abl_points = 3; // used to show total points
  4334. #endif
  4335. // Probe at 3 arbitrary points
  4336. ABL_VAR vector_3 points[3] = {
  4337. vector_3(PROBE_PT_1_X, PROBE_PT_1_Y, 0),
  4338. vector_3(PROBE_PT_2_X, PROBE_PT_2_Y, 0),
  4339. vector_3(PROBE_PT_3_X, PROBE_PT_3_Y, 0)
  4340. };
  4341. #endif // AUTO_BED_LEVELING_3POINT
  4342. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4343. struct linear_fit_data lsf_results;
  4344. incremental_LSF_reset(&lsf_results);
  4345. #endif
  4346. /**
  4347. * On the initial G29 fetch command parameters.
  4348. */
  4349. if (!g29_in_progress) {
  4350. #if ENABLED(DUAL_X_CARRIAGE)
  4351. if (active_extruder != 0) tool_change(0);
  4352. #endif
  4353. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  4354. abl_probe_index = -1;
  4355. #endif
  4356. abl_should_enable = planner.leveling_active;
  4357. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4358. const bool seen_w = parser.seen('W');
  4359. if (seen_w) {
  4360. if (!leveling_is_valid()) {
  4361. SERIAL_ERROR_START();
  4362. SERIAL_ERRORLNPGM("No bilinear grid");
  4363. return;
  4364. }
  4365. const float rz = parser.seenval('Z') ? RAW_Z_POSITION(parser.value_linear_units()) : current_position[Z_AXIS];
  4366. if (!WITHIN(rz, -10, 10)) {
  4367. SERIAL_ERROR_START();
  4368. SERIAL_ERRORLNPGM("Bad Z value");
  4369. return;
  4370. }
  4371. const float rx = RAW_X_POSITION(parser.linearval('X', NAN)),
  4372. ry = RAW_Y_POSITION(parser.linearval('Y', NAN));
  4373. int8_t i = parser.byteval('I', -1),
  4374. j = parser.byteval('J', -1);
  4375. if (!isnan(rx) && !isnan(ry)) {
  4376. // Get nearest i / j from rx / ry
  4377. i = (rx - bilinear_start[X_AXIS] + 0.5f * xGridSpacing) / xGridSpacing;
  4378. j = (ry - bilinear_start[Y_AXIS] + 0.5f * yGridSpacing) / yGridSpacing;
  4379. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  4380. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  4381. }
  4382. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  4383. set_bed_leveling_enabled(false);
  4384. z_values[i][j] = rz;
  4385. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4386. bed_level_virt_interpolate();
  4387. #endif
  4388. set_bed_leveling_enabled(abl_should_enable);
  4389. if (abl_should_enable) report_current_position();
  4390. }
  4391. return;
  4392. } // parser.seen('W')
  4393. #else
  4394. constexpr bool seen_w = false;
  4395. #endif
  4396. // Jettison bed leveling data
  4397. if (!seen_w && parser.seen('J')) {
  4398. reset_bed_level();
  4399. return;
  4400. }
  4401. verbose_level = parser.intval('V');
  4402. if (!WITHIN(verbose_level, 0, 4)) {
  4403. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  4404. return;
  4405. }
  4406. dryrun = parser.boolval('D')
  4407. #if ENABLED(PROBE_MANUALLY)
  4408. || no_action
  4409. #endif
  4410. ;
  4411. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4412. do_topography_map = verbose_level > 2 || parser.boolval('T');
  4413. // X and Y specify points in each direction, overriding the default
  4414. // These values may be saved with the completed mesh
  4415. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  4416. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  4417. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  4418. if (!WITHIN(abl_grid_points_x, 2, GRID_MAX_POINTS_X)) {
  4419. SERIAL_PROTOCOLLNPGM("?Probe points (X) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  4420. return;
  4421. }
  4422. if (!WITHIN(abl_grid_points_y, 2, GRID_MAX_POINTS_Y)) {
  4423. SERIAL_PROTOCOLLNPGM("?Probe points (Y) is implausible (2-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  4424. return;
  4425. }
  4426. abl_points = abl_grid_points_x * abl_grid_points_y;
  4427. mean = 0;
  4428. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4429. zoffset = parser.linearval('Z');
  4430. #endif
  4431. #if ABL_GRID
  4432. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  4433. left_probe_bed_position = parser.seenval('L') ? int(RAW_X_POSITION(parser.value_linear_units())) : LEFT_PROBE_BED_POSITION;
  4434. right_probe_bed_position = parser.seenval('R') ? int(RAW_X_POSITION(parser.value_linear_units())) : RIGHT_PROBE_BED_POSITION;
  4435. front_probe_bed_position = parser.seenval('F') ? int(RAW_Y_POSITION(parser.value_linear_units())) : FRONT_PROBE_BED_POSITION;
  4436. back_probe_bed_position = parser.seenval('B') ? int(RAW_Y_POSITION(parser.value_linear_units())) : BACK_PROBE_BED_POSITION;
  4437. if (
  4438. #if IS_SCARA || ENABLED(DELTA)
  4439. !position_is_reachable_by_probe(left_probe_bed_position, 0)
  4440. || !position_is_reachable_by_probe(right_probe_bed_position, 0)
  4441. || !position_is_reachable_by_probe(0, front_probe_bed_position)
  4442. || !position_is_reachable_by_probe(0, back_probe_bed_position)
  4443. #else
  4444. !position_is_reachable_by_probe(left_probe_bed_position, front_probe_bed_position)
  4445. || !position_is_reachable_by_probe(right_probe_bed_position, back_probe_bed_position)
  4446. #endif
  4447. ) {
  4448. SERIAL_PROTOCOLLNPGM("? (L,R,F,B) out of bounds.");
  4449. return;
  4450. }
  4451. // probe at the points of a lattice grid
  4452. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  4453. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  4454. #endif // ABL_GRID
  4455. if (verbose_level > 0) {
  4456. SERIAL_PROTOCOLPGM("G29 Auto Bed Leveling");
  4457. if (dryrun) SERIAL_PROTOCOLPGM(" (DRYRUN)");
  4458. SERIAL_EOL();
  4459. }
  4460. planner.synchronize();
  4461. // Disable auto bed leveling during G29.
  4462. // Be formal so G29 can be done successively without G28.
  4463. if (!no_action) set_bed_leveling_enabled(false);
  4464. #if HAS_BED_PROBE
  4465. // Deploy the probe. Probe will raise if needed.
  4466. if (DEPLOY_PROBE()) {
  4467. set_bed_leveling_enabled(abl_should_enable);
  4468. return;
  4469. }
  4470. #endif
  4471. if (!faux) setup_for_endstop_or_probe_move();
  4472. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4473. #if ENABLED(PROBE_MANUALLY)
  4474. if (!no_action)
  4475. #endif
  4476. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  4477. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  4478. || left_probe_bed_position != bilinear_start[X_AXIS]
  4479. || front_probe_bed_position != bilinear_start[Y_AXIS]
  4480. ) {
  4481. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  4482. reset_bed_level();
  4483. // Initialize a grid with the given dimensions
  4484. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  4485. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  4486. bilinear_start[X_AXIS] = left_probe_bed_position;
  4487. bilinear_start[Y_AXIS] = front_probe_bed_position;
  4488. // Can't re-enable (on error) until the new grid is written
  4489. abl_should_enable = false;
  4490. }
  4491. #endif // AUTO_BED_LEVELING_BILINEAR
  4492. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  4493. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4494. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  4495. #endif
  4496. // Probe at 3 arbitrary points
  4497. points[0].z = points[1].z = points[2].z = 0;
  4498. #endif // AUTO_BED_LEVELING_3POINT
  4499. } // !g29_in_progress
  4500. #if ENABLED(PROBE_MANUALLY)
  4501. // For manual probing, get the next index to probe now.
  4502. // On the first probe this will be incremented to 0.
  4503. if (!no_action) {
  4504. ++abl_probe_index;
  4505. g29_in_progress = true;
  4506. }
  4507. // Abort current G29 procedure, go back to idle state
  4508. if (seenA && g29_in_progress) {
  4509. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  4510. #if HAS_SOFTWARE_ENDSTOPS
  4511. soft_endstops_enabled = enable_soft_endstops;
  4512. #endif
  4513. set_bed_leveling_enabled(abl_should_enable);
  4514. g29_in_progress = false;
  4515. #if ENABLED(LCD_BED_LEVELING)
  4516. lcd_wait_for_move = false;
  4517. #endif
  4518. }
  4519. // Query G29 status
  4520. if (verbose_level || seenQ) {
  4521. SERIAL_PROTOCOLPGM("Manual G29 ");
  4522. if (g29_in_progress) {
  4523. SERIAL_PROTOCOLPAIR("point ", MIN(abl_probe_index + 1, abl_points));
  4524. SERIAL_PROTOCOLLNPAIR(" of ", abl_points);
  4525. }
  4526. else
  4527. SERIAL_PROTOCOLLNPGM("idle");
  4528. }
  4529. if (no_action) return;
  4530. if (abl_probe_index == 0) {
  4531. // For the initial G29 save software endstop state
  4532. #if HAS_SOFTWARE_ENDSTOPS
  4533. enable_soft_endstops = soft_endstops_enabled;
  4534. #endif
  4535. // Move close to the bed before the first point
  4536. do_blocking_move_to_z(0);
  4537. }
  4538. else {
  4539. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT)
  4540. const uint16_t index = abl_probe_index - 1;
  4541. #endif
  4542. // For G29 after adjusting Z.
  4543. // Save the previous Z before going to the next point
  4544. measured_z = current_position[Z_AXIS];
  4545. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4546. mean += measured_z;
  4547. eqnBVector[index] = measured_z;
  4548. eqnAMatrix[index + 0 * abl_points] = xProbe;
  4549. eqnAMatrix[index + 1 * abl_points] = yProbe;
  4550. eqnAMatrix[index + 2 * abl_points] = 1;
  4551. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4552. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4553. points[index].z = measured_z;
  4554. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4555. z_values[xCount][yCount] = measured_z + zoffset;
  4556. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4557. if (DEBUGGING(LEVELING)) {
  4558. SERIAL_PROTOCOLPAIR("Save X", xCount);
  4559. SERIAL_PROTOCOLPAIR(" Y", yCount);
  4560. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  4561. }
  4562. #endif
  4563. #endif
  4564. }
  4565. //
  4566. // If there's another point to sample, move there with optional lift.
  4567. //
  4568. #if ABL_GRID
  4569. // Skip any unreachable points
  4570. while (abl_probe_index < abl_points) {
  4571. // Set xCount, yCount based on abl_probe_index, with zig-zag
  4572. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  4573. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  4574. // Probe in reverse order for every other row/column
  4575. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  4576. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  4577. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  4578. yBase = yCount * yGridSpacing + front_probe_bed_position;
  4579. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4580. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4581. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4582. indexIntoAB[xCount][yCount] = abl_probe_index;
  4583. #endif
  4584. // Keep looping till a reachable point is found
  4585. if (position_is_reachable(xProbe, yProbe)) break;
  4586. ++abl_probe_index;
  4587. }
  4588. // Is there a next point to move to?
  4589. if (abl_probe_index < abl_points) {
  4590. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  4591. #if HAS_SOFTWARE_ENDSTOPS
  4592. // Disable software endstops to allow manual adjustment
  4593. // If G29 is not completed, they will not be re-enabled
  4594. soft_endstops_enabled = false;
  4595. #endif
  4596. return;
  4597. }
  4598. else {
  4599. // Leveling done! Fall through to G29 finishing code below
  4600. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  4601. // Re-enable software endstops, if needed
  4602. #if HAS_SOFTWARE_ENDSTOPS
  4603. soft_endstops_enabled = enable_soft_endstops;
  4604. #endif
  4605. }
  4606. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4607. // Probe at 3 arbitrary points
  4608. if (abl_probe_index < abl_points) {
  4609. xProbe = points[abl_probe_index].x;
  4610. yProbe = points[abl_probe_index].y;
  4611. _manual_goto_xy(xProbe, yProbe);
  4612. #if HAS_SOFTWARE_ENDSTOPS
  4613. // Disable software endstops to allow manual adjustment
  4614. // If G29 is not completed, they will not be re-enabled
  4615. soft_endstops_enabled = false;
  4616. #endif
  4617. return;
  4618. }
  4619. else {
  4620. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  4621. // Re-enable software endstops, if needed
  4622. #if HAS_SOFTWARE_ENDSTOPS
  4623. soft_endstops_enabled = enable_soft_endstops;
  4624. #endif
  4625. if (!dryrun) {
  4626. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4627. if (planeNormal.z < 0) {
  4628. planeNormal.x *= -1;
  4629. planeNormal.y *= -1;
  4630. planeNormal.z *= -1;
  4631. }
  4632. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4633. // Can't re-enable (on error) until the new grid is written
  4634. abl_should_enable = false;
  4635. }
  4636. }
  4637. #endif // AUTO_BED_LEVELING_3POINT
  4638. #else // !PROBE_MANUALLY
  4639. {
  4640. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  4641. measured_z = 0;
  4642. #if ABL_GRID
  4643. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  4644. measured_z = 0;
  4645. // Outer loop is Y with PROBE_Y_FIRST disabled
  4646. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END && !isnan(measured_z); PR_OUTER_VAR++) {
  4647. int8_t inStart, inStop, inInc;
  4648. if (zig) { // away from origin
  4649. inStart = 0;
  4650. inStop = PR_INNER_END;
  4651. inInc = 1;
  4652. }
  4653. else { // towards origin
  4654. inStart = PR_INNER_END - 1;
  4655. inStop = -1;
  4656. inInc = -1;
  4657. }
  4658. zig ^= true; // zag
  4659. // Inner loop is Y with PROBE_Y_FIRST enabled
  4660. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4661. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4662. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4663. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4664. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4665. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4666. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4667. #endif
  4668. #if IS_KINEMATIC
  4669. // Avoid probing outside the round or hexagonal area
  4670. if (!position_is_reachable_by_probe(xProbe, yProbe)) continue;
  4671. #endif
  4672. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4673. if (isnan(measured_z)) {
  4674. set_bed_leveling_enabled(abl_should_enable);
  4675. break;
  4676. }
  4677. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4678. mean += measured_z;
  4679. eqnBVector[abl_probe_index] = measured_z;
  4680. eqnAMatrix[abl_probe_index + 0 * abl_points] = xProbe;
  4681. eqnAMatrix[abl_probe_index + 1 * abl_points] = yProbe;
  4682. eqnAMatrix[abl_probe_index + 2 * abl_points] = 1;
  4683. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4684. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4685. z_values[xCount][yCount] = measured_z + zoffset;
  4686. #endif
  4687. abl_should_enable = false;
  4688. idle();
  4689. } // inner
  4690. } // outer
  4691. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4692. // Probe at 3 arbitrary points
  4693. for (uint8_t i = 0; i < 3; ++i) {
  4694. // Retain the last probe position
  4695. xProbe = points[i].x;
  4696. yProbe = points[i].y;
  4697. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, raise_after, verbose_level);
  4698. if (isnan(measured_z)) {
  4699. set_bed_leveling_enabled(abl_should_enable);
  4700. break;
  4701. }
  4702. points[i].z = measured_z;
  4703. }
  4704. if (!dryrun && !isnan(measured_z)) {
  4705. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4706. if (planeNormal.z < 0) {
  4707. planeNormal.x *= -1;
  4708. planeNormal.y *= -1;
  4709. planeNormal.z *= -1;
  4710. }
  4711. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4712. // Can't re-enable (on error) until the new grid is written
  4713. abl_should_enable = false;
  4714. }
  4715. #endif // AUTO_BED_LEVELING_3POINT
  4716. // Stow the probe. No raise for FIX_MOUNTED_PROBE.
  4717. if (STOW_PROBE()) {
  4718. set_bed_leveling_enabled(abl_should_enable);
  4719. measured_z = NAN;
  4720. }
  4721. }
  4722. #endif // !PROBE_MANUALLY
  4723. //
  4724. // G29 Finishing Code
  4725. //
  4726. // Unless this is a dry run, auto bed leveling will
  4727. // definitely be enabled after this point.
  4728. //
  4729. // If code above wants to continue leveling, it should
  4730. // return or loop before this point.
  4731. //
  4732. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4733. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4734. #endif
  4735. #if ENABLED(PROBE_MANUALLY)
  4736. g29_in_progress = false;
  4737. #if ENABLED(LCD_BED_LEVELING)
  4738. lcd_wait_for_move = false;
  4739. #endif
  4740. #endif
  4741. // Calculate leveling, print reports, correct the position
  4742. if (!isnan(measured_z)) {
  4743. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4744. if (!dryrun) extrapolate_unprobed_bed_level();
  4745. print_bilinear_leveling_grid();
  4746. refresh_bed_level();
  4747. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4748. print_bilinear_leveling_grid_virt();
  4749. #endif
  4750. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4751. // For LINEAR leveling calculate matrix, print reports, correct the position
  4752. /**
  4753. * solve the plane equation ax + by + d = z
  4754. * A is the matrix with rows [x y 1] for all the probed points
  4755. * B is the vector of the Z positions
  4756. * the normal vector to the plane is formed by the coefficients of the
  4757. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4758. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4759. */
  4760. float plane_equation_coefficients[3];
  4761. finish_incremental_LSF(&lsf_results);
  4762. plane_equation_coefficients[0] = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below
  4763. plane_equation_coefficients[1] = -lsf_results.B; // but that is not yet tested.
  4764. plane_equation_coefficients[2] = -lsf_results.D;
  4765. mean /= abl_points;
  4766. if (verbose_level) {
  4767. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4768. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4769. SERIAL_PROTOCOLPGM(" b: ");
  4770. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4771. SERIAL_PROTOCOLPGM(" d: ");
  4772. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4773. SERIAL_EOL();
  4774. if (verbose_level > 2) {
  4775. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4776. SERIAL_PROTOCOL_F(mean, 8);
  4777. SERIAL_EOL();
  4778. }
  4779. }
  4780. // Create the matrix but don't correct the position yet
  4781. if (!dryrun)
  4782. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4783. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1) // We can eliminate the '-' here and up above
  4784. );
  4785. // Show the Topography map if enabled
  4786. if (do_topography_map) {
  4787. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4788. " +--- BACK --+\n"
  4789. " | |\n"
  4790. " L | (+) | R\n"
  4791. " E | | I\n"
  4792. " F | (-) N (+) | G\n"
  4793. " T | | H\n"
  4794. " | (-) | T\n"
  4795. " | |\n"
  4796. " O-- FRONT --+\n"
  4797. " (0,0)");
  4798. float min_diff = 999;
  4799. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4800. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4801. int ind = indexIntoAB[xx][yy];
  4802. float diff = eqnBVector[ind] - mean,
  4803. x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4804. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4805. z_tmp = 0;
  4806. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4807. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4808. if (diff >= 0.0)
  4809. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4810. else
  4811. SERIAL_PROTOCOLCHAR(' ');
  4812. SERIAL_PROTOCOL_F(diff, 5);
  4813. } // xx
  4814. SERIAL_EOL();
  4815. } // yy
  4816. SERIAL_EOL();
  4817. if (verbose_level > 3) {
  4818. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4819. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4820. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4821. int ind = indexIntoAB[xx][yy];
  4822. float x_tmp = eqnAMatrix[ind + 0 * abl_points],
  4823. y_tmp = eqnAMatrix[ind + 1 * abl_points],
  4824. z_tmp = 0;
  4825. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4826. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4827. if (diff >= 0.0)
  4828. SERIAL_PROTOCOLPGM(" +");
  4829. // Include + for column alignment
  4830. else
  4831. SERIAL_PROTOCOLCHAR(' ');
  4832. SERIAL_PROTOCOL_F(diff, 5);
  4833. } // xx
  4834. SERIAL_EOL();
  4835. } // yy
  4836. SERIAL_EOL();
  4837. }
  4838. } //do_topography_map
  4839. #endif // AUTO_BED_LEVELING_LINEAR
  4840. #if ABL_PLANAR
  4841. // For LINEAR and 3POINT leveling correct the current position
  4842. if (verbose_level > 0)
  4843. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4844. if (!dryrun) {
  4845. //
  4846. // Correct the current XYZ position based on the tilted plane.
  4847. //
  4848. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4849. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4850. #endif
  4851. float converted[XYZ];
  4852. COPY(converted, current_position);
  4853. planner.leveling_active = true;
  4854. planner.unapply_leveling(converted); // use conversion machinery
  4855. planner.leveling_active = false;
  4856. // Use the last measured distance to the bed, if possible
  4857. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4858. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4859. ) {
  4860. const float simple_z = current_position[Z_AXIS] - measured_z;
  4861. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4862. if (DEBUGGING(LEVELING)) {
  4863. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4864. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4865. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4866. }
  4867. #endif
  4868. converted[Z_AXIS] = simple_z;
  4869. }
  4870. // The rotated XY and corrected Z are now current_position
  4871. COPY(current_position, converted);
  4872. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4873. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4874. #endif
  4875. }
  4876. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4877. if (!dryrun) {
  4878. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4879. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4880. #endif
  4881. // Unapply the offset because it is going to be immediately applied
  4882. // and cause compensation movement in Z
  4883. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  4884. const float fade_scaling_factor = planner.fade_scaling_factor_for_z(current_position[Z_AXIS]);
  4885. #else
  4886. constexpr float fade_scaling_factor = 1.0f;
  4887. #endif
  4888. current_position[Z_AXIS] -= fade_scaling_factor * bilinear_z_offset(current_position);
  4889. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4890. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4891. #endif
  4892. }
  4893. #endif // ABL_PLANAR
  4894. #ifdef Z_PROBE_END_SCRIPT
  4895. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4896. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4897. #endif
  4898. planner.synchronize();
  4899. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4900. #endif
  4901. // Auto Bed Leveling is complete! Enable if possible.
  4902. planner.leveling_active = dryrun ? abl_should_enable : true;
  4903. } // !isnan(measured_z)
  4904. // Restore state after probing
  4905. if (!faux) clean_up_after_endstop_or_probe_move();
  4906. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4907. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< G29");
  4908. #endif
  4909. KEEPALIVE_STATE(IN_HANDLER);
  4910. if (planner.leveling_active)
  4911. SYNC_PLAN_POSITION_KINEMATIC();
  4912. #if HAS_BED_PROBE && defined(Z_AFTER_PROBING)
  4913. move_z_after_probing();
  4914. #endif
  4915. report_current_position();
  4916. }
  4917. #endif // OLDSCHOOL_ABL
  4918. #if HAS_BED_PROBE
  4919. /**
  4920. * G30: Do a single Z probe at the current XY
  4921. *
  4922. * Parameters:
  4923. *
  4924. * X Probe X position (default current X)
  4925. * Y Probe Y position (default current Y)
  4926. * E Engage the probe for each probe (default 1)
  4927. */
  4928. inline void gcode_G30() {
  4929. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4930. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4931. if (!position_is_reachable_by_probe(xpos, ypos)) return;
  4932. // Disable leveling so the planner won't mess with us
  4933. #if HAS_LEVELING
  4934. set_bed_leveling_enabled(false);
  4935. #endif
  4936. setup_for_endstop_or_probe_move();
  4937. const ProbePtRaise raise_after = parser.boolval('E', true) ? PROBE_PT_STOW : PROBE_PT_NONE;
  4938. const float measured_z = probe_pt(xpos, ypos, raise_after, parser.intval('V', 1));
  4939. if (!isnan(measured_z)) {
  4940. SERIAL_PROTOCOLPAIR_F("Bed X: ", xpos);
  4941. SERIAL_PROTOCOLPAIR_F(" Y: ", ypos);
  4942. SERIAL_PROTOCOLLNPAIR_F(" Z: ", measured_z);
  4943. }
  4944. clean_up_after_endstop_or_probe_move();
  4945. #ifdef Z_AFTER_PROBING
  4946. if (raise_after == PROBE_PT_STOW) move_z_after_probing();
  4947. #endif
  4948. report_current_position();
  4949. }
  4950. #if ENABLED(Z_PROBE_SLED)
  4951. /**
  4952. * G31: Deploy the Z probe
  4953. */
  4954. inline void gcode_G31() { DEPLOY_PROBE(); }
  4955. /**
  4956. * G32: Stow the Z probe
  4957. */
  4958. inline void gcode_G32() { STOW_PROBE(); }
  4959. #endif // Z_PROBE_SLED
  4960. #endif // HAS_BED_PROBE
  4961. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4962. constexpr uint8_t _7P_STEP = 1, // 7-point step - to change number of calibration points
  4963. _4P_STEP = _7P_STEP * 2, // 4-point step
  4964. NPP = _7P_STEP * 6; // number of calibration points on the radius
  4965. enum CalEnum : char { // the 7 main calibration points - add definitions if needed
  4966. CEN = 0,
  4967. __A = 1,
  4968. _AB = __A + _7P_STEP,
  4969. __B = _AB + _7P_STEP,
  4970. _BC = __B + _7P_STEP,
  4971. __C = _BC + _7P_STEP,
  4972. _CA = __C + _7P_STEP,
  4973. };
  4974. #define LOOP_CAL_PT(VAR, S, N) for (uint8_t VAR=S; VAR<=NPP; VAR+=N)
  4975. #define F_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR<NPP+0.9999; VAR+=N)
  4976. #define I_LOOP_CAL_PT(VAR, S, N) for (float VAR=S; VAR>CEN+0.9999; VAR-=N)
  4977. #define LOOP_CAL_ALL(VAR) LOOP_CAL_PT(VAR, CEN, 1)
  4978. #define LOOP_CAL_RAD(VAR) LOOP_CAL_PT(VAR, __A, _7P_STEP)
  4979. #define LOOP_CAL_ACT(VAR, _4P, _OP) LOOP_CAL_PT(VAR, _OP ? _AB : __A, _4P ? _4P_STEP : _7P_STEP)
  4980. #if HOTENDS > 1
  4981. const uint8_t old_tool_index = active_extruder;
  4982. #define AC_CLEANUP() ac_cleanup(old_tool_index)
  4983. #else
  4984. #define AC_CLEANUP() ac_cleanup()
  4985. #endif
  4986. float lcd_probe_pt(const float &rx, const float &ry);
  4987. void ac_home() {
  4988. endstops.enable(true);
  4989. home_delta();
  4990. endstops.not_homing();
  4991. }
  4992. void ac_setup(const bool reset_bed) {
  4993. #if HOTENDS > 1
  4994. tool_change(0, 0, true);
  4995. #endif
  4996. planner.synchronize();
  4997. setup_for_endstop_or_probe_move();
  4998. #if HAS_LEVELING
  4999. if (reset_bed) reset_bed_level(); // After full calibration bed-level data is no longer valid
  5000. #endif
  5001. }
  5002. void ac_cleanup(
  5003. #if HOTENDS > 1
  5004. const uint8_t old_tool_index
  5005. #endif
  5006. ) {
  5007. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  5008. do_blocking_move_to_z(delta_clip_start_height);
  5009. #endif
  5010. #if HAS_BED_PROBE
  5011. STOW_PROBE();
  5012. #endif
  5013. clean_up_after_endstop_or_probe_move();
  5014. #if HOTENDS > 1
  5015. tool_change(old_tool_index, 0, true);
  5016. #endif
  5017. }
  5018. void print_signed_float(const char * const prefix, const float &f) {
  5019. SERIAL_PROTOCOLPGM(" ");
  5020. serialprintPGM(prefix);
  5021. SERIAL_PROTOCOLCHAR(':');
  5022. if (f >= 0) SERIAL_CHAR('+');
  5023. SERIAL_PROTOCOL_F(f, 2);
  5024. }
  5025. /**
  5026. * - Print the delta settings
  5027. */
  5028. static void print_calibration_settings(const bool end_stops, const bool tower_angles) {
  5029. SERIAL_PROTOCOLPAIR(".Height:", delta_height);
  5030. if (end_stops) {
  5031. print_signed_float(PSTR("Ex"), delta_endstop_adj[A_AXIS]);
  5032. print_signed_float(PSTR("Ey"), delta_endstop_adj[B_AXIS]);
  5033. print_signed_float(PSTR("Ez"), delta_endstop_adj[C_AXIS]);
  5034. }
  5035. if (end_stops && tower_angles) {
  5036. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  5037. SERIAL_EOL();
  5038. SERIAL_CHAR('.');
  5039. SERIAL_PROTOCOL_SP(13);
  5040. }
  5041. if (tower_angles) {
  5042. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  5043. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  5044. print_signed_float(PSTR("Tz"), delta_tower_angle_trim[C_AXIS]);
  5045. }
  5046. if ((!end_stops && tower_angles) || (end_stops && !tower_angles)) { // XOR
  5047. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  5048. }
  5049. SERIAL_EOL();
  5050. }
  5051. /**
  5052. * - Print the probe results
  5053. */
  5054. static void print_calibration_results(const float z_pt[NPP + 1], const bool tower_points, const bool opposite_points) {
  5055. SERIAL_PROTOCOLPGM(". ");
  5056. print_signed_float(PSTR("c"), z_pt[CEN]);
  5057. if (tower_points) {
  5058. print_signed_float(PSTR(" x"), z_pt[__A]);
  5059. print_signed_float(PSTR(" y"), z_pt[__B]);
  5060. print_signed_float(PSTR(" z"), z_pt[__C]);
  5061. }
  5062. if (tower_points && opposite_points) {
  5063. SERIAL_EOL();
  5064. SERIAL_CHAR('.');
  5065. SERIAL_PROTOCOL_SP(13);
  5066. }
  5067. if (opposite_points) {
  5068. print_signed_float(PSTR("yz"), z_pt[_BC]);
  5069. print_signed_float(PSTR("zx"), z_pt[_CA]);
  5070. print_signed_float(PSTR("xy"), z_pt[_AB]);
  5071. }
  5072. SERIAL_EOL();
  5073. }
  5074. /**
  5075. * - Calculate the standard deviation from the zero plane
  5076. */
  5077. static float std_dev_points(float z_pt[NPP + 1], const bool _0p_cal, const bool _1p_cal, const bool _4p_cal, const bool _4p_opp) {
  5078. if (!_0p_cal) {
  5079. float S2 = sq(z_pt[CEN]);
  5080. int16_t N = 1;
  5081. if (!_1p_cal) { // std dev from zero plane
  5082. LOOP_CAL_ACT(rad, _4p_cal, _4p_opp) {
  5083. S2 += sq(z_pt[rad]);
  5084. N++;
  5085. }
  5086. return LROUND(SQRT(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  5087. }
  5088. }
  5089. return 0.00001;
  5090. }
  5091. /**
  5092. * - Probe a point
  5093. */
  5094. static float calibration_probe(const float &nx, const float &ny, const bool stow) {
  5095. #if HAS_BED_PROBE
  5096. return probe_pt(nx, ny, stow ? PROBE_PT_STOW : PROBE_PT_RAISE, 0, false);
  5097. #else
  5098. UNUSED(stow);
  5099. return lcd_probe_pt(nx, ny);
  5100. #endif
  5101. }
  5102. /**
  5103. * - Probe a grid
  5104. */
  5105. static bool probe_calibration_points(float z_pt[NPP + 1], const int8_t probe_points, const bool towers_set, const bool stow_after_each) {
  5106. const bool _0p_calibration = probe_points == 0,
  5107. _1p_calibration = probe_points == 1 || probe_points == -1,
  5108. _4p_calibration = probe_points == 2,
  5109. _4p_opposite_points = _4p_calibration && !towers_set,
  5110. _7p_calibration = probe_points >= 3,
  5111. _7p_no_intermediates = probe_points == 3,
  5112. _7p_1_intermediates = probe_points == 4,
  5113. _7p_2_intermediates = probe_points == 5,
  5114. _7p_4_intermediates = probe_points == 6,
  5115. _7p_6_intermediates = probe_points == 7,
  5116. _7p_8_intermediates = probe_points == 8,
  5117. _7p_11_intermediates = probe_points == 9,
  5118. _7p_14_intermediates = probe_points == 10,
  5119. _7p_intermed_points = probe_points >= 4,
  5120. _7p_6_center = probe_points >= 5 && probe_points <= 7,
  5121. _7p_9_center = probe_points >= 8;
  5122. LOOP_CAL_ALL(rad) z_pt[rad] = 0.0;
  5123. if (!_0p_calibration) {
  5124. if (!_7p_no_intermediates && !_7p_4_intermediates && !_7p_11_intermediates) { // probe the center
  5125. z_pt[CEN] += calibration_probe(0, 0, stow_after_each);
  5126. if (isnan(z_pt[CEN])) return false;
  5127. }
  5128. if (_7p_calibration) { // probe extra center points
  5129. const float start = _7p_9_center ? float(_CA) + _7P_STEP / 3.0 : _7p_6_center ? float(_CA) : float(__C),
  5130. steps = _7p_9_center ? _4P_STEP / 3.0 : _7p_6_center ? _7P_STEP : _4P_STEP;
  5131. I_LOOP_CAL_PT(rad, start, steps) {
  5132. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  5133. r = delta_calibration_radius * 0.1;
  5134. z_pt[CEN] += calibration_probe(cos(a) * r, sin(a) * r, stow_after_each);
  5135. if (isnan(z_pt[CEN])) return false;
  5136. }
  5137. z_pt[CEN] /= float(_7p_2_intermediates ? 7 : probe_points);
  5138. }
  5139. if (!_1p_calibration) { // probe the radius
  5140. const CalEnum start = _4p_opposite_points ? _AB : __A;
  5141. const float steps = _7p_14_intermediates ? _7P_STEP / 15.0 : // 15r * 6 + 10c = 100
  5142. _7p_11_intermediates ? _7P_STEP / 12.0 : // 12r * 6 + 9c = 81
  5143. _7p_8_intermediates ? _7P_STEP / 9.0 : // 9r * 6 + 10c = 64
  5144. _7p_6_intermediates ? _7P_STEP / 7.0 : // 7r * 6 + 7c = 49
  5145. _7p_4_intermediates ? _7P_STEP / 5.0 : // 5r * 6 + 6c = 36
  5146. _7p_2_intermediates ? _7P_STEP / 3.0 : // 3r * 6 + 7c = 25
  5147. _7p_1_intermediates ? _7P_STEP / 2.0 : // 2r * 6 + 4c = 16
  5148. _7p_no_intermediates ? _7P_STEP : // 1r * 6 + 3c = 9
  5149. _4P_STEP; // .5r * 6 + 1c = 4
  5150. bool zig_zag = true;
  5151. F_LOOP_CAL_PT(rad, start, _7p_9_center ? steps * 3 : steps) {
  5152. const int8_t offset = _7p_9_center ? 2 : 0;
  5153. for (int8_t circle = 0; circle <= offset; circle++) {
  5154. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  5155. r = delta_calibration_radius * (1 - 0.1 * (zig_zag ? offset - circle : circle)),
  5156. interpol = fmod(rad, 1);
  5157. const float z_temp = calibration_probe(cos(a) * r, sin(a) * r, stow_after_each);
  5158. if (isnan(z_temp)) return false;
  5159. // split probe point to neighbouring calibration points
  5160. z_pt[uint8_t(LROUND(rad - interpol + NPP - 1)) % NPP + 1] += z_temp * sq(cos(RADIANS(interpol * 90)));
  5161. z_pt[uint8_t(LROUND(rad - interpol)) % NPP + 1] += z_temp * sq(sin(RADIANS(interpol * 90)));
  5162. }
  5163. zig_zag = !zig_zag;
  5164. }
  5165. if (_7p_intermed_points)
  5166. LOOP_CAL_RAD(rad)
  5167. z_pt[rad] /= _7P_STEP / steps;
  5168. do_blocking_move_to_xy(0.0, 0.0);
  5169. }
  5170. }
  5171. return true;
  5172. }
  5173. /**
  5174. * kinematics routines and auto tune matrix scaling parameters:
  5175. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5176. * - formulae for approximative forward kinematics in the end-stop displacement matrix
  5177. * - definition of the matrix scaling parameters
  5178. */
  5179. static void reverse_kinematics_probe_points(float z_pt[NPP + 1], float mm_at_pt_axis[NPP + 1][ABC]) {
  5180. float pos[XYZ] = { 0.0 };
  5181. LOOP_CAL_ALL(rad) {
  5182. const float a = RADIANS(210 + (360 / NPP) * (rad - 1)),
  5183. r = (rad == CEN ? 0.0 : delta_calibration_radius);
  5184. pos[X_AXIS] = cos(a) * r;
  5185. pos[Y_AXIS] = sin(a) * r;
  5186. pos[Z_AXIS] = z_pt[rad];
  5187. inverse_kinematics(pos);
  5188. LOOP_XYZ(axis) mm_at_pt_axis[rad][axis] = delta[axis];
  5189. }
  5190. }
  5191. static void forward_kinematics_probe_points(float mm_at_pt_axis[NPP + 1][ABC], float z_pt[NPP + 1]) {
  5192. const float r_quot = delta_calibration_radius / delta_radius;
  5193. #define ZPP(N,I,A) ((1 / 3.0 + r_quot * (N) / 3.0 ) * mm_at_pt_axis[I][A])
  5194. #define Z00(I, A) ZPP( 0, I, A)
  5195. #define Zp1(I, A) ZPP(+1, I, A)
  5196. #define Zm1(I, A) ZPP(-1, I, A)
  5197. #define Zp2(I, A) ZPP(+2, I, A)
  5198. #define Zm2(I, A) ZPP(-2, I, A)
  5199. z_pt[CEN] = Z00(CEN, A_AXIS) + Z00(CEN, B_AXIS) + Z00(CEN, C_AXIS);
  5200. z_pt[__A] = Zp2(__A, A_AXIS) + Zm1(__A, B_AXIS) + Zm1(__A, C_AXIS);
  5201. z_pt[__B] = Zm1(__B, A_AXIS) + Zp2(__B, B_AXIS) + Zm1(__B, C_AXIS);
  5202. z_pt[__C] = Zm1(__C, A_AXIS) + Zm1(__C, B_AXIS) + Zp2(__C, C_AXIS);
  5203. z_pt[_BC] = Zm2(_BC, A_AXIS) + Zp1(_BC, B_AXIS) + Zp1(_BC, C_AXIS);
  5204. z_pt[_CA] = Zp1(_CA, A_AXIS) + Zm2(_CA, B_AXIS) + Zp1(_CA, C_AXIS);
  5205. z_pt[_AB] = Zp1(_AB, A_AXIS) + Zp1(_AB, B_AXIS) + Zm2(_AB, C_AXIS);
  5206. }
  5207. static void calc_kinematics_diff_probe_points(float z_pt[NPP + 1], float delta_e[ABC], float delta_r, float delta_t[ABC]) {
  5208. const float z_center = z_pt[CEN];
  5209. float diff_mm_at_pt_axis[NPP + 1][ABC],
  5210. new_mm_at_pt_axis[NPP + 1][ABC];
  5211. reverse_kinematics_probe_points(z_pt, diff_mm_at_pt_axis);
  5212. delta_radius += delta_r;
  5213. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += delta_t[axis];
  5214. recalc_delta_settings();
  5215. reverse_kinematics_probe_points(z_pt, new_mm_at_pt_axis);
  5216. LOOP_XYZ(axis) LOOP_CAL_ALL(rad) diff_mm_at_pt_axis[rad][axis] -= new_mm_at_pt_axis[rad][axis] + delta_e[axis];
  5217. forward_kinematics_probe_points(diff_mm_at_pt_axis, z_pt);
  5218. LOOP_CAL_RAD(rad) z_pt[rad] -= z_pt[CEN] - z_center;
  5219. z_pt[CEN] = z_center;
  5220. delta_radius -= delta_r;
  5221. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= delta_t[axis];
  5222. recalc_delta_settings();
  5223. }
  5224. static float auto_tune_h() {
  5225. const float r_quot = delta_calibration_radius / delta_radius;
  5226. float h_fac = 0.0;
  5227. h_fac = r_quot / (2.0 / 3.0);
  5228. h_fac = 1.0f / h_fac; // (2/3)/CR
  5229. return h_fac;
  5230. }
  5231. static float auto_tune_r() {
  5232. const float diff = 0.01;
  5233. float r_fac = 0.0,
  5234. z_pt[NPP + 1] = { 0.0 },
  5235. delta_e[ABC] = {0.0},
  5236. delta_r = {0.0},
  5237. delta_t[ABC] = {0.0};
  5238. delta_r = diff;
  5239. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5240. r_fac = -(z_pt[__A] + z_pt[__B] + z_pt[__C] + z_pt[_BC] + z_pt[_CA] + z_pt[_AB]) / 6.0;
  5241. r_fac = diff / r_fac / 3.0; // 1/(3*delta_Z)
  5242. return r_fac;
  5243. }
  5244. static float auto_tune_a() {
  5245. const float diff = 0.01;
  5246. float a_fac = 0.0,
  5247. z_pt[NPP + 1] = { 0.0 },
  5248. delta_e[ABC] = {0.0},
  5249. delta_r = {0.0},
  5250. delta_t[ABC] = {0.0};
  5251. LOOP_XYZ(axis) {
  5252. LOOP_XYZ(axis_2) delta_t[axis_2] = 0.0;
  5253. delta_t[axis] = diff;
  5254. calc_kinematics_diff_probe_points(z_pt, delta_e, delta_r, delta_t);
  5255. a_fac += z_pt[uint8_t((axis * _4P_STEP) - _7P_STEP + NPP) % NPP + 1] / 6.0;
  5256. a_fac -= z_pt[uint8_t((axis * _4P_STEP) + 1 + _7P_STEP)] / 6.0;
  5257. }
  5258. a_fac = diff / a_fac / 3.0; // 1/(3*delta_Z)
  5259. return a_fac;
  5260. }
  5261. /**
  5262. * G33 - Delta '1-4-7-point' Auto-Calibration
  5263. * Calibrate height, z_offset, endstops, delta radius, and tower angles.
  5264. *
  5265. * Parameters:
  5266. *
  5267. * Pn Number of probe points:
  5268. * P0 Normalizes calibration.
  5269. * P1 Calibrates height only with center probe.
  5270. * P2 Probe center and towers. Calibrate height, endstops and delta radius.
  5271. * P3 Probe all positions: center, towers and opposite towers. Calibrate all.
  5272. * P4-P10 Probe all positions at different intermediate locations and average them.
  5273. *
  5274. * T Don't calibrate tower angle corrections
  5275. *
  5276. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  5277. *
  5278. * Fn Force to run at least n iterations and take the best result
  5279. *
  5280. * Vn Verbose level:
  5281. * V0 Dry-run mode. Report settings and probe results. No calibration.
  5282. * V1 Report start and end settings only
  5283. * V2 Report settings at each iteration
  5284. * V3 Report settings and probe results
  5285. *
  5286. * E Engage the probe for each point
  5287. */
  5288. inline void gcode_G33() {
  5289. const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  5290. if (!WITHIN(probe_points, 0, 10)) {
  5291. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (0-10).");
  5292. return;
  5293. }
  5294. const bool towers_set = !parser.seen('T');
  5295. const float calibration_precision = parser.floatval('C', 0.0);
  5296. if (calibration_precision < 0) {
  5297. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>=0).");
  5298. return;
  5299. }
  5300. const int8_t force_iterations = parser.intval('F', 0);
  5301. if (!WITHIN(force_iterations, 0, 30)) {
  5302. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0-30).");
  5303. return;
  5304. }
  5305. const int8_t verbose_level = parser.byteval('V', 1);
  5306. if (!WITHIN(verbose_level, 0, 3)) {
  5307. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-3).");
  5308. return;
  5309. }
  5310. const bool stow_after_each = parser.seen('E');
  5311. const bool _0p_calibration = probe_points == 0,
  5312. _1p_calibration = probe_points == 1 || probe_points == -1,
  5313. _4p_calibration = probe_points == 2,
  5314. _4p_opposite_points = _4p_calibration && !towers_set,
  5315. _7p_9_center = probe_points >= 8,
  5316. _tower_results = (_4p_calibration && towers_set) || probe_points >= 3,
  5317. _opposite_results = (_4p_calibration && !towers_set) || probe_points >= 3,
  5318. _endstop_results = probe_points != 1 && probe_points != -1 && probe_points != 0,
  5319. _angle_results = probe_points >= 3 && towers_set;
  5320. static const char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  5321. int8_t iterations = 0;
  5322. float test_precision,
  5323. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  5324. zero_std_dev_min = zero_std_dev,
  5325. zero_std_dev_old = zero_std_dev,
  5326. h_factor,
  5327. r_factor,
  5328. a_factor,
  5329. e_old[ABC] = {
  5330. delta_endstop_adj[A_AXIS],
  5331. delta_endstop_adj[B_AXIS],
  5332. delta_endstop_adj[C_AXIS]
  5333. },
  5334. r_old = delta_radius,
  5335. h_old = delta_height,
  5336. a_old[ABC] = {
  5337. delta_tower_angle_trim[A_AXIS],
  5338. delta_tower_angle_trim[B_AXIS],
  5339. delta_tower_angle_trim[C_AXIS]
  5340. };
  5341. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  5342. if (!_1p_calibration && !_0p_calibration) { // test if the outer radius is reachable
  5343. LOOP_CAL_RAD(axis) {
  5344. const float a = RADIANS(210 + (360 / NPP) * (axis - 1)),
  5345. r = delta_calibration_radius;
  5346. if (!position_is_reachable(cos(a) * r, sin(a) * r)) {
  5347. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  5348. return;
  5349. }
  5350. }
  5351. }
  5352. // Report settings
  5353. const char *checkingac = PSTR("Checking... AC");
  5354. serialprintPGM(checkingac);
  5355. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  5356. SERIAL_EOL();
  5357. lcd_setstatusPGM(checkingac);
  5358. print_calibration_settings(_endstop_results, _angle_results);
  5359. ac_setup(!_0p_calibration && !_1p_calibration);
  5360. if (!_0p_calibration) ac_home();
  5361. do { // start iterations
  5362. float z_at_pt[NPP + 1] = { 0.0 };
  5363. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  5364. iterations++;
  5365. // Probe the points
  5366. zero_std_dev_old = zero_std_dev;
  5367. if (!probe_calibration_points(z_at_pt, probe_points, towers_set, stow_after_each)) {
  5368. SERIAL_PROTOCOLLNPGM("Correct delta settings with M665 and M666");
  5369. return AC_CLEANUP();
  5370. }
  5371. zero_std_dev = std_dev_points(z_at_pt, _0p_calibration, _1p_calibration, _4p_calibration, _4p_opposite_points);
  5372. // Solve matrices
  5373. if ((zero_std_dev < test_precision || iterations <= force_iterations) && zero_std_dev > calibration_precision) {
  5374. #if !HAS_BED_PROBE
  5375. test_precision = 0.00; // forced end
  5376. #endif
  5377. if (zero_std_dev < zero_std_dev_min) {
  5378. // set roll-back point
  5379. COPY(e_old, delta_endstop_adj);
  5380. r_old = delta_radius;
  5381. h_old = delta_height;
  5382. COPY(a_old, delta_tower_angle_trim);
  5383. }
  5384. float e_delta[ABC] = { 0.0 },
  5385. r_delta = 0.0,
  5386. t_delta[ABC] = { 0.0 };
  5387. /**
  5388. * convergence matrices:
  5389. * see https://github.com/LVD-AC/Marlin-AC/tree/1.1.x-AC/documentation for
  5390. * - definition of the matrix scaling parameters
  5391. * - matrices for 4 and 7 point calibration
  5392. */
  5393. #define ZP(N,I) ((N) * z_at_pt[I] / 4.0) // 4.0 = divider to normalize to integers
  5394. #define Z12(I) ZP(12, I)
  5395. #define Z4(I) ZP(4, I)
  5396. #define Z2(I) ZP(2, I)
  5397. #define Z1(I) ZP(1, I)
  5398. #define Z0(I) ZP(0, I)
  5399. // calculate factors
  5400. const float cr_old = delta_calibration_radius;
  5401. if (_7p_9_center) delta_calibration_radius *= 0.9;
  5402. h_factor = auto_tune_h();
  5403. r_factor = auto_tune_r();
  5404. a_factor = auto_tune_a();
  5405. delta_calibration_radius = cr_old;
  5406. switch (probe_points) {
  5407. case 0:
  5408. test_precision = 0.00; // forced end
  5409. break;
  5410. case 1:
  5411. test_precision = 0.00; // forced end
  5412. LOOP_XYZ(axis) e_delta[axis] = +Z4(CEN);
  5413. break;
  5414. case 2:
  5415. if (towers_set) { // see 4 point calibration (towers) matrix
  5416. e_delta[A_AXIS] = (+Z4(__A) -Z2(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5417. e_delta[B_AXIS] = (-Z2(__A) +Z4(__B) -Z2(__C)) * h_factor +Z4(CEN);
  5418. e_delta[C_AXIS] = (-Z2(__A) -Z2(__B) +Z4(__C)) * h_factor +Z4(CEN);
  5419. r_delta = (+Z4(__A) +Z4(__B) +Z4(__C) -Z12(CEN)) * r_factor;
  5420. }
  5421. else { // see 4 point calibration (opposites) matrix
  5422. e_delta[A_AXIS] = (-Z4(_BC) +Z2(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5423. e_delta[B_AXIS] = (+Z2(_BC) -Z4(_CA) +Z2(_AB)) * h_factor +Z4(CEN);
  5424. e_delta[C_AXIS] = (+Z2(_BC) +Z2(_CA) -Z4(_AB)) * h_factor +Z4(CEN);
  5425. r_delta = (+Z4(_BC) +Z4(_CA) +Z4(_AB) -Z12(CEN)) * r_factor;
  5426. }
  5427. break;
  5428. default: // see 7 point calibration (towers & opposites) matrix
  5429. e_delta[A_AXIS] = (+Z2(__A) -Z1(__B) -Z1(__C) -Z2(_BC) +Z1(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5430. e_delta[B_AXIS] = (-Z1(__A) +Z2(__B) -Z1(__C) +Z1(_BC) -Z2(_CA) +Z1(_AB)) * h_factor +Z4(CEN);
  5431. e_delta[C_AXIS] = (-Z1(__A) -Z1(__B) +Z2(__C) +Z1(_BC) +Z1(_CA) -Z2(_AB)) * h_factor +Z4(CEN);
  5432. r_delta = (+Z2(__A) +Z2(__B) +Z2(__C) +Z2(_BC) +Z2(_CA) +Z2(_AB) -Z12(CEN)) * r_factor;
  5433. if (towers_set) { // see 7 point tower angle calibration (towers & opposites) matrix
  5434. t_delta[A_AXIS] = (+Z0(__A) -Z4(__B) +Z4(__C) +Z0(_BC) -Z4(_CA) +Z4(_AB) +Z0(CEN)) * a_factor;
  5435. t_delta[B_AXIS] = (+Z4(__A) +Z0(__B) -Z4(__C) +Z4(_BC) +Z0(_CA) -Z4(_AB) +Z0(CEN)) * a_factor;
  5436. t_delta[C_AXIS] = (-Z4(__A) +Z4(__B) +Z0(__C) -Z4(_BC) +Z4(_CA) +Z0(_AB) +Z0(CEN)) * a_factor;
  5437. }
  5438. break;
  5439. }
  5440. LOOP_XYZ(axis) delta_endstop_adj[axis] += e_delta[axis];
  5441. delta_radius += r_delta;
  5442. LOOP_XYZ(axis) delta_tower_angle_trim[axis] += t_delta[axis];
  5443. }
  5444. else if (zero_std_dev >= test_precision) {
  5445. // roll back
  5446. COPY(delta_endstop_adj, e_old);
  5447. delta_radius = r_old;
  5448. delta_height = h_old;
  5449. COPY(delta_tower_angle_trim, a_old);
  5450. }
  5451. if (verbose_level != 0) { // !dry run
  5452. // normalise angles to least squares
  5453. if (_angle_results) {
  5454. float a_sum = 0.0;
  5455. LOOP_XYZ(axis) a_sum += delta_tower_angle_trim[axis];
  5456. LOOP_XYZ(axis) delta_tower_angle_trim[axis] -= a_sum / 3.0;
  5457. }
  5458. // adjust delta_height and endstops by the max amount
  5459. const float z_temp = MAX3(delta_endstop_adj[A_AXIS], delta_endstop_adj[B_AXIS], delta_endstop_adj[C_AXIS]);
  5460. delta_height -= z_temp;
  5461. LOOP_XYZ(axis) delta_endstop_adj[axis] -= z_temp;
  5462. }
  5463. recalc_delta_settings();
  5464. NOMORE(zero_std_dev_min, zero_std_dev);
  5465. // print report
  5466. if (verbose_level == 3)
  5467. print_calibration_results(z_at_pt, _tower_results, _opposite_results);
  5468. if (verbose_level != 0) { // !dry run
  5469. if ((zero_std_dev >= test_precision && iterations > force_iterations) || zero_std_dev <= calibration_precision) { // end iterations
  5470. SERIAL_PROTOCOLPGM("Calibration OK");
  5471. SERIAL_PROTOCOL_SP(32);
  5472. #if HAS_BED_PROBE
  5473. if (zero_std_dev >= test_precision && !_1p_calibration && !_0p_calibration)
  5474. SERIAL_PROTOCOLPGM("rolling back.");
  5475. else
  5476. #endif
  5477. {
  5478. SERIAL_PROTOCOLPGM("std dev:");
  5479. SERIAL_PROTOCOL_F(zero_std_dev_min, 3);
  5480. }
  5481. SERIAL_EOL();
  5482. char mess[21];
  5483. strcpy_P(mess, PSTR("Calibration sd:"));
  5484. if (zero_std_dev_min < 1)
  5485. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev_min * 1000.0)));
  5486. else
  5487. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev_min)));
  5488. lcd_setstatus(mess);
  5489. print_calibration_settings(_endstop_results, _angle_results);
  5490. serialprintPGM(save_message);
  5491. SERIAL_EOL();
  5492. }
  5493. else { // !end iterations
  5494. char mess[15];
  5495. if (iterations < 31)
  5496. sprintf_P(mess, PSTR("Iteration : %02i"), int(iterations));
  5497. else
  5498. strcpy_P(mess, PSTR("No convergence"));
  5499. SERIAL_PROTOCOL(mess);
  5500. SERIAL_PROTOCOL_SP(32);
  5501. SERIAL_PROTOCOLPGM("std dev:");
  5502. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5503. SERIAL_EOL();
  5504. lcd_setstatus(mess);
  5505. if (verbose_level > 1)
  5506. print_calibration_settings(_endstop_results, _angle_results);
  5507. }
  5508. }
  5509. else { // dry run
  5510. const char *enddryrun = PSTR("End DRY-RUN");
  5511. serialprintPGM(enddryrun);
  5512. SERIAL_PROTOCOL_SP(35);
  5513. SERIAL_PROTOCOLPGM("std dev:");
  5514. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  5515. SERIAL_EOL();
  5516. char mess[21];
  5517. strcpy_P(mess, enddryrun);
  5518. strcpy_P(&mess[11], PSTR(" sd:"));
  5519. if (zero_std_dev < 1)
  5520. sprintf_P(&mess[15], PSTR("0.%03i"), int(LROUND(zero_std_dev * 1000.0)));
  5521. else
  5522. sprintf_P(&mess[15], PSTR("%03i.x"), int(LROUND(zero_std_dev)));
  5523. lcd_setstatus(mess);
  5524. }
  5525. ac_home();
  5526. }
  5527. while (((zero_std_dev < test_precision && iterations < 31) || iterations <= force_iterations) && zero_std_dev > calibration_precision);
  5528. AC_CLEANUP();
  5529. }
  5530. #endif // DELTA_AUTO_CALIBRATION
  5531. #if ENABLED(G38_PROBE_TARGET)
  5532. static bool G38_run_probe() {
  5533. bool G38_pass_fail = false;
  5534. #if MULTIPLE_PROBING > 1
  5535. // Get direction of move and retract
  5536. float retract_mm[XYZ];
  5537. LOOP_XYZ(i) {
  5538. float dist = destination[i] - current_position[i];
  5539. retract_mm[i] = ABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  5540. }
  5541. #endif
  5542. // Move until destination reached or target hit
  5543. planner.synchronize();
  5544. endstops.enable(true);
  5545. G38_move = true;
  5546. G38_endstop_hit = false;
  5547. prepare_move_to_destination();
  5548. planner.synchronize();
  5549. G38_move = false;
  5550. endstops.hit_on_purpose();
  5551. set_current_from_steppers_for_axis(ALL_AXES);
  5552. SYNC_PLAN_POSITION_KINEMATIC();
  5553. if (G38_endstop_hit) {
  5554. G38_pass_fail = true;
  5555. #if MULTIPLE_PROBING > 1
  5556. // Move away by the retract distance
  5557. set_destination_from_current();
  5558. LOOP_XYZ(i) destination[i] += retract_mm[i];
  5559. endstops.enable(false);
  5560. prepare_move_to_destination();
  5561. feedrate_mm_s /= 4;
  5562. // Bump the target more slowly
  5563. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  5564. planner.synchronize();
  5565. endstops.enable(true);
  5566. G38_move = true;
  5567. prepare_move_to_destination();
  5568. planner.synchronize();
  5569. G38_move = false;
  5570. set_current_from_steppers_for_axis(ALL_AXES);
  5571. SYNC_PLAN_POSITION_KINEMATIC();
  5572. #endif
  5573. }
  5574. endstops.hit_on_purpose();
  5575. endstops.not_homing();
  5576. return G38_pass_fail;
  5577. }
  5578. /**
  5579. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  5580. * G38.3 - probe toward workpiece, stop on contact
  5581. *
  5582. * Like G28 except uses Z min probe for all axes
  5583. */
  5584. inline void gcode_G38(bool is_38_2) {
  5585. // Get X Y Z E F
  5586. gcode_get_destination();
  5587. setup_for_endstop_or_probe_move();
  5588. // If any axis has enough movement, do the move
  5589. LOOP_XYZ(i)
  5590. if (ABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  5591. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate((AxisEnum)i);
  5592. // If G38.2 fails throw an error
  5593. if (!G38_run_probe() && is_38_2) {
  5594. SERIAL_ERROR_START();
  5595. SERIAL_ERRORLNPGM("Failed to reach target");
  5596. }
  5597. break;
  5598. }
  5599. clean_up_after_endstop_or_probe_move();
  5600. }
  5601. #endif // G38_PROBE_TARGET
  5602. #if HAS_MESH
  5603. /**
  5604. * G42: Move X & Y axes to mesh coordinates (I & J)
  5605. */
  5606. inline void gcode_G42() {
  5607. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  5608. if (axis_unhomed_error()) return;
  5609. #endif
  5610. if (IsRunning()) {
  5611. const bool hasI = parser.seenval('I');
  5612. const int8_t ix = hasI ? parser.value_int() : 0;
  5613. const bool hasJ = parser.seenval('J');
  5614. const int8_t iy = hasJ ? parser.value_int() : 0;
  5615. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  5616. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  5617. return;
  5618. }
  5619. set_destination_from_current();
  5620. if (hasI) destination[X_AXIS] = _GET_MESH_X(ix);
  5621. if (hasJ) destination[Y_AXIS] = _GET_MESH_Y(iy);
  5622. if (parser.boolval('P')) {
  5623. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  5624. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  5625. }
  5626. const float fval = parser.linearval('F');
  5627. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  5628. // SCARA kinematic has "safe" XY raw moves
  5629. #if IS_SCARA
  5630. prepare_uninterpolated_move_to_destination();
  5631. #else
  5632. prepare_move_to_destination();
  5633. #endif
  5634. }
  5635. }
  5636. #endif // HAS_MESH
  5637. /**
  5638. * G92: Set current position to given X Y Z E
  5639. */
  5640. inline void gcode_G92() {
  5641. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5642. switch (parser.subcode) {
  5643. case 1:
  5644. // Zero the G92 values and restore current position
  5645. #if !IS_SCARA
  5646. LOOP_XYZ(i) {
  5647. const float v = position_shift[i];
  5648. if (v) {
  5649. position_shift[i] = 0;
  5650. update_software_endstops((AxisEnum)i);
  5651. }
  5652. }
  5653. #endif // Not SCARA
  5654. return;
  5655. }
  5656. #endif
  5657. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5658. #define IS_G92_0 (parser.subcode == 0)
  5659. #else
  5660. #define IS_G92_0 true
  5661. #endif
  5662. bool didE = false;
  5663. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5664. bool didXYZ = false;
  5665. #else
  5666. constexpr bool didXYZ = false;
  5667. #endif
  5668. if (IS_G92_0) LOOP_XYZE(i) {
  5669. if (parser.seenval(axis_codes[i])) {
  5670. const float l = parser.value_axis_units((AxisEnum)i),
  5671. v = i == E_CART ? l : LOGICAL_TO_NATIVE(l, i),
  5672. d = v - current_position[i];
  5673. if (!NEAR_ZERO(d)
  5674. #if ENABLED(HANGPRINTER)
  5675. || true // Hangprinter needs to update its line lengths whether current_position changed or not
  5676. #endif
  5677. ) {
  5678. #if IS_SCARA || !HAS_POSITION_SHIFT || ENABLED(HANGPRINTER)
  5679. if (i == E_CART) didE = true; else didXYZ = true;
  5680. current_position[i] = v; // Without workspaces revert to Marlin 1.0 behavior
  5681. #elif HAS_POSITION_SHIFT
  5682. if (i == E_CART) {
  5683. didE = true;
  5684. current_position[E_CART] = v; // When using coordinate spaces, only E is set directly
  5685. }
  5686. else {
  5687. position_shift[i] += d; // Other axes simply offset the coordinate space
  5688. update_software_endstops((AxisEnum)i);
  5689. }
  5690. #endif
  5691. }
  5692. }
  5693. }
  5694. #if ENABLED(CNC_COORDINATE_SYSTEMS)
  5695. // Apply workspace offset to the active coordinate system
  5696. if (WITHIN(active_coordinate_system, 0, MAX_COORDINATE_SYSTEMS - 1))
  5697. COPY(coordinate_system[active_coordinate_system], position_shift);
  5698. #endif
  5699. // Update planner/steppers only if the native coordinates changed
  5700. if (didXYZ) SYNC_PLAN_POSITION_KINEMATIC();
  5701. else if (didE) sync_plan_position_e();
  5702. report_current_position();
  5703. }
  5704. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  5705. /**
  5706. * G95: Set torque mode
  5707. */
  5708. inline void gcode_G95() {
  5709. i2cFloat torques[NUM_AXIS]; // Assumes 4-byte floats here and in Mechaduino firmware
  5710. LOOP_NUM_AXIS(i)
  5711. torques[i].fval = parser.floatval(RAW_AXIS_CODES(i), 999.9); // 999.9 chosen to satisfy fabs(999.9) > 255.0
  5712. // 0x5f == 95
  5713. #define G95_SEND(LETTER) do { \
  5714. if (fabs(torques[_AXIS(LETTER)].fval) < 255.0){ \
  5715. torques[_AXIS(LETTER)].fval = -fabs(torques[_AXIS(LETTER)].fval); \
  5716. if(!INVERT_##LETTER##_DIR) torques[_AXIS(LETTER)].fval = -torques[_AXIS(LETTER)].fval; \
  5717. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5718. i2c.reset(); \
  5719. i2c.addbyte(0x5f); \
  5720. i2c.addbytes(torques[_AXIS(LETTER)].bval, sizeof(float)); \
  5721. i2c.send(); \
  5722. }} while(0)
  5723. #if ENABLED(HANGPRINTER)
  5724. #if ENABLED(A_IS_MECHADUINO)
  5725. G95_SEND(A);
  5726. #endif
  5727. #if ENABLED(B_IS_MECHADUINO)
  5728. G95_SEND(B);
  5729. #endif
  5730. #if ENABLED(C_IS_MECHADUINO)
  5731. G95_SEND(C);
  5732. #endif
  5733. #if ENABLED(D_IS_MECHADUINO)
  5734. G95_SEND(D);
  5735. #endif
  5736. #else
  5737. #if ENABLED(X_IS_MECHADUINO)
  5738. G95_SEND(X);
  5739. #endif
  5740. #if ENABLED(Y_IS_MECHADUINO)
  5741. G95_SEND(Y);
  5742. #endif
  5743. #if ENABLED(Z_IS_MECHADUINO)
  5744. G95_SEND(Z);
  5745. #endif
  5746. #endif
  5747. #if ENABLED(E_IS_MECHADUINO)
  5748. G95_SEND(E);
  5749. #endif
  5750. }
  5751. /**
  5752. * G96: Mark encoder reference point
  5753. */
  5754. inline void gcode_G96() {
  5755. bool mark[NUM_AXIS] = { false };
  5756. if (!parser.seen_any())
  5757. LOOP_NUM_AXIS(i)
  5758. mark[i] = true;
  5759. else
  5760. LOOP_NUM_AXIS(i)
  5761. if (parser.seen(RAW_AXIS_CODES(i)))
  5762. mark[i] = true;
  5763. // 0x60 == 96
  5764. #define G96_SEND(LETTER) do {\
  5765. if (mark[LETTER##_AXIS]){ \
  5766. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5767. i2c.reset(); \
  5768. i2c.addbyte(0x60); \
  5769. i2c.send(); \
  5770. }} while(0)
  5771. #if ENABLED(HANGPRINTER)
  5772. #if ENABLED(A_IS_MECHADUINO)
  5773. G96_SEND(A);
  5774. #endif
  5775. #if ENABLED(B_IS_MECHADUINO)
  5776. G96_SEND(B);
  5777. #endif
  5778. #if ENABLED(C_IS_MECHADUINO)
  5779. G96_SEND(C);
  5780. #endif
  5781. #if ENABLED(D_IS_MECHADUINO)
  5782. G96_SEND(D);
  5783. #endif
  5784. #else
  5785. #if ENABLED(X_IS_MECHADUINO)
  5786. G96_SEND(X);
  5787. #endif
  5788. #if ENABLED(Y_IS_MECHADUINO)
  5789. G96_SEND(Y);
  5790. #endif
  5791. #if ENABLED(Z_IS_MECHADUINO)
  5792. G96_SEND(Z);
  5793. #endif
  5794. #endif
  5795. #if ENABLED(E_IS_MECHADUINO)
  5796. G96_SEND(E); // E ref point not used by any other commands (Feb 7, 2018)
  5797. #endif
  5798. }
  5799. float ang_to_mm(float ang, const AxisEnum axis) {
  5800. const float abs_step_in_origin =
  5801. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5802. planner.k0[axis] * (SQRT(planner.k1[axis] + planner.k2[axis] * line_lengths_origin[axis]) - planner.sqrtk1[axis])
  5803. #else
  5804. line_lengths_origin[axis] * planner.axis_steps_per_mm[axis]
  5805. #endif
  5806. ;
  5807. const float c = abs_step_in_origin + ang * float(STEPS_PER_MOTOR_REVOLUTION) / 360.0; // current step count
  5808. return
  5809. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  5810. // Inverse function found in planner.cpp, where target[AXIS_A] is calculated
  5811. ((c / planner.k0[axis] + planner.sqrtk1[axis]) * (c / planner.k0[axis] + planner.sqrtk1[axis]) - planner.k1[axis]) / planner.k2[axis] - line_lengths_origin[axis]
  5812. #else
  5813. c / planner.axis_steps_per_mm[axis] - line_lengths_origin[axis]
  5814. #endif
  5815. ;
  5816. }
  5817. void report_axis_position_from_encoder_data() {
  5818. i2cFloat ang;
  5819. #define M114_S1_RECEIVE(LETTER) do { \
  5820. i2c.address(LETTER##_MOTOR_I2C_ADDR); \
  5821. i2c.request(sizeof(float)); \
  5822. i2c.capture(ang.bval, sizeof(float)); \
  5823. if(LETTER##_INVERT_REPORTED_ANGLE == INVERT_##LETTER##_DIR) ang.fval = -ang.fval; \
  5824. SERIAL_PROTOCOL(ang_to_mm(ang.fval, LETTER##_AXIS)); \
  5825. } while(0)
  5826. SERIAL_CHAR('[');
  5827. #if ENABLED(HANGPRINTER)
  5828. #if ENABLED(A_IS_MECHADUINO)
  5829. M114_S1_RECEIVE(A);
  5830. #endif
  5831. #if ENABLED(B_IS_MECHADUINO)
  5832. SERIAL_PROTOCOLPGM(", ");
  5833. M114_S1_RECEIVE(B);
  5834. #endif
  5835. #if ENABLED(C_IS_MECHADUINO)
  5836. SERIAL_PROTOCOLPGM(", ");
  5837. M114_S1_RECEIVE(C);
  5838. #endif
  5839. #if ENABLED(D_IS_MECHADUINO)
  5840. SERIAL_PROTOCOLPGM(", ");
  5841. M114_S1_RECEIVE(D);
  5842. #endif
  5843. #else
  5844. #if ENABLED(X_IS_MECHADUINO)
  5845. M114_S1_RECEIVE(X);
  5846. #endif
  5847. #if ENABLED(Y_IS_MECHADUINO)
  5848. SERIAL_PROTOCOLPGM(", ");
  5849. M114_S1_RECEIVE(Y);
  5850. #endif
  5851. #if ENABLED(Z_IS_MECHADUINO)
  5852. SERIAL_PROTOCOLPGM(", ");
  5853. M114_S1_RECEIVE(Z);
  5854. #endif
  5855. #endif
  5856. SERIAL_CHAR(']');
  5857. SERIAL_EOL();
  5858. }
  5859. #endif // MECHADUINO_I2C_COMMANDS
  5860. void report_xyz_from_stepper_position() {
  5861. get_cartesian_from_steppers(); // writes to cartes[XYZ]
  5862. SERIAL_CHAR('[');
  5863. SERIAL_PROTOCOL(cartes[X_AXIS]);
  5864. SERIAL_PROTOCOLPAIR(", ", cartes[Y_AXIS]);
  5865. SERIAL_PROTOCOLPAIR(", ", cartes[Z_AXIS]);
  5866. SERIAL_CHAR(']');
  5867. SERIAL_EOL();
  5868. }
  5869. #if HAS_RESUME_CONTINUE
  5870. /**
  5871. * M0: Unconditional stop - Wait for user button press on LCD
  5872. * M1: Conditional stop - Wait for user button press on LCD
  5873. */
  5874. inline void gcode_M0_M1() {
  5875. const char * const args = parser.string_arg;
  5876. millis_t ms = 0;
  5877. bool hasP = false, hasS = false;
  5878. if (parser.seenval('P')) {
  5879. ms = parser.value_millis(); // milliseconds to wait
  5880. hasP = ms > 0;
  5881. }
  5882. if (parser.seenval('S')) {
  5883. ms = parser.value_millis_from_seconds(); // seconds to wait
  5884. hasS = ms > 0;
  5885. }
  5886. const bool has_message = !hasP && !hasS && args && *args;
  5887. planner.synchronize();
  5888. #if ENABLED(ULTIPANEL)
  5889. if (has_message)
  5890. lcd_setstatus(args, true);
  5891. else {
  5892. LCD_MESSAGEPGM(MSG_USERWAIT);
  5893. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  5894. dontExpireStatus();
  5895. #endif
  5896. }
  5897. #else
  5898. if (has_message) {
  5899. SERIAL_ECHO_START();
  5900. SERIAL_ECHOLN(args);
  5901. }
  5902. #endif
  5903. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5904. wait_for_user = true;
  5905. if (ms > 0) {
  5906. ms += millis(); // wait until this time for a click
  5907. while (PENDING(millis(), ms) && wait_for_user) idle();
  5908. }
  5909. else
  5910. while (wait_for_user) idle();
  5911. #if ENABLED(PRINTER_EVENT_LEDS) && ENABLED(SDSUPPORT)
  5912. if (lights_off_after_print) {
  5913. leds.set_off();
  5914. lights_off_after_print = false;
  5915. }
  5916. #endif
  5917. lcd_reset_status();
  5918. wait_for_user = false;
  5919. KEEPALIVE_STATE(IN_HANDLER);
  5920. }
  5921. #endif // HAS_RESUME_CONTINUE
  5922. #if ENABLED(SPINDLE_LASER_ENABLE)
  5923. /**
  5924. * M3: Spindle Clockwise
  5925. * M4: Spindle Counter-clockwise
  5926. *
  5927. * S0 turns off spindle.
  5928. *
  5929. * If no speed PWM output is defined then M3/M4 just turns it on.
  5930. *
  5931. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  5932. * Hardware PWM is required. ISRs are too slow.
  5933. *
  5934. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  5935. * No other settings give a PWM signal that goes from 0 to 5 volts.
  5936. *
  5937. * The system automatically sets WGM to Mode 1, so no special
  5938. * initialization is needed.
  5939. *
  5940. * WGM bits for timer 2 are automatically set by the system to
  5941. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  5942. * No special initialization is needed.
  5943. *
  5944. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  5945. * factors for timers 2, 3, 4, and 5 are acceptable.
  5946. *
  5947. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  5948. * the spindle/laser during power-up or when connecting to the host
  5949. * (usually goes through a reset which sets all I/O pins to tri-state)
  5950. *
  5951. * PWM duty cycle goes from 0 (off) to 255 (always on).
  5952. */
  5953. // Wait for spindle to come up to speed
  5954. inline void delay_for_power_up() { dwell(SPINDLE_LASER_POWERUP_DELAY); }
  5955. // Wait for spindle to stop turning
  5956. inline void delay_for_power_down() { dwell(SPINDLE_LASER_POWERDOWN_DELAY); }
  5957. /**
  5958. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  5959. *
  5960. * it accepts inputs of 0-255
  5961. */
  5962. inline void ocr_val_mode() {
  5963. uint8_t spindle_laser_power = parser.value_byte();
  5964. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  5965. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  5966. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  5967. }
  5968. inline void gcode_M3_M4(bool is_M3) {
  5969. planner.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  5970. #if SPINDLE_DIR_CHANGE
  5971. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  5972. if (SPINDLE_STOP_ON_DIR_CHANGE \
  5973. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  5974. && READ(SPINDLE_DIR_PIN) != rotation_dir
  5975. ) {
  5976. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  5977. delay_for_power_down();
  5978. }
  5979. WRITE(SPINDLE_DIR_PIN, rotation_dir);
  5980. #endif
  5981. /**
  5982. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  5983. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  5984. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  5985. */
  5986. #if ENABLED(SPINDLE_LASER_PWM)
  5987. if (parser.seen('O')) ocr_val_mode();
  5988. else {
  5989. const float spindle_laser_power = parser.floatval('S');
  5990. if (spindle_laser_power == 0) {
  5991. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  5992. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // only write low byte
  5993. delay_for_power_down();
  5994. }
  5995. else {
  5996. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  5997. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  5998. if (spindle_laser_power <= SPEED_POWER_MIN)
  5999. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // minimum setting
  6000. if (spindle_laser_power >= SPEED_POWER_MAX)
  6001. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0f / (SPEED_POWER_SLOPE)); // limit to max RPM
  6002. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  6003. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  6004. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  6005. delay_for_power_up();
  6006. }
  6007. }
  6008. #else
  6009. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  6010. delay_for_power_up();
  6011. #endif
  6012. }
  6013. /**
  6014. * M5 turn off spindle
  6015. */
  6016. inline void gcode_M5() {
  6017. planner.synchronize();
  6018. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  6019. #if ENABLED(SPINDLE_LASER_PWM)
  6020. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0);
  6021. #endif
  6022. delay_for_power_down();
  6023. }
  6024. #endif // SPINDLE_LASER_ENABLE
  6025. /**
  6026. * M17: Enable power on all stepper motors
  6027. */
  6028. inline void gcode_M17() {
  6029. LCD_MESSAGEPGM(MSG_NO_MOVE);
  6030. enable_all_steppers();
  6031. }
  6032. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  6033. void do_pause_e_move(const float &length, const float &fr) {
  6034. set_destination_from_current();
  6035. destination[E_CART] += length / planner.e_factor[active_extruder];
  6036. planner.buffer_line_kinematic(destination, fr, active_extruder);
  6037. set_current_from_destination();
  6038. planner.synchronize();
  6039. }
  6040. static float resume_position[XYZE];
  6041. int8_t did_pause_print = 0;
  6042. #if HAS_BUZZER
  6043. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  6044. static millis_t next_buzz = 0;
  6045. static int8_t runout_beep = 0;
  6046. if (init) next_buzz = runout_beep = 0;
  6047. const millis_t ms = millis();
  6048. if (ELAPSED(ms, next_buzz)) {
  6049. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  6050. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 1000 : 500);
  6051. BUZZ(50, 880 - (runout_beep & 1) * 220);
  6052. runout_beep++;
  6053. }
  6054. }
  6055. }
  6056. #endif
  6057. /**
  6058. * Ensure a safe temperature for extrusion
  6059. *
  6060. * - Fail if the TARGET temperature is too low
  6061. * - Display LCD placard with temperature status
  6062. * - Return when heating is done or aborted
  6063. *
  6064. * Returns 'true' if heating was completed, 'false' for abort
  6065. */
  6066. static bool ensure_safe_temperature(const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT) {
  6067. #if ENABLED(PREVENT_COLD_EXTRUSION)
  6068. if (!DEBUGGING(DRYRUN) && thermalManager.targetTooColdToExtrude(active_extruder)) {
  6069. SERIAL_ERROR_START();
  6070. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  6071. return false;
  6072. }
  6073. #endif
  6074. #if ENABLED(ULTIPANEL)
  6075. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT, mode);
  6076. #else
  6077. UNUSED(mode);
  6078. #endif
  6079. wait_for_heatup = true; // M108 will clear this
  6080. while (wait_for_heatup && thermalManager.wait_for_heating(active_extruder)) idle();
  6081. const bool status = wait_for_heatup;
  6082. wait_for_heatup = false;
  6083. return status;
  6084. }
  6085. /**
  6086. * Load filament into the hotend
  6087. *
  6088. * - Fail if the a safe temperature was not reached
  6089. * - If pausing for confirmation, wait for a click or M108
  6090. * - Show "wait for load" placard
  6091. * - Load and purge filament
  6092. * - Show "Purge more" / "Continue" menu
  6093. * - Return when "Continue" is selected
  6094. *
  6095. * Returns 'true' if load was completed, 'false' for abort
  6096. */
  6097. static bool load_filament(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=0, const int8_t max_beep_count=0,
  6098. const bool show_lcd=false, const bool pause_for_user=false,
  6099. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  6100. ) {
  6101. #if DISABLED(ULTIPANEL)
  6102. UNUSED(show_lcd);
  6103. #endif
  6104. if (!ensure_safe_temperature(mode)) {
  6105. #if ENABLED(ULTIPANEL)
  6106. if (show_lcd) // Show status screen
  6107. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6108. #endif
  6109. return false;
  6110. }
  6111. if (pause_for_user) {
  6112. #if ENABLED(ULTIPANEL)
  6113. if (show_lcd) // Show "insert filament"
  6114. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT, mode);
  6115. #endif
  6116. SERIAL_ECHO_START();
  6117. SERIAL_ECHOLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6118. #if HAS_BUZZER
  6119. filament_change_beep(max_beep_count, true);
  6120. #else
  6121. UNUSED(max_beep_count);
  6122. #endif
  6123. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6124. wait_for_user = true; // LCD click or M108 will clear this
  6125. while (wait_for_user) {
  6126. #if HAS_BUZZER
  6127. filament_change_beep(max_beep_count);
  6128. #endif
  6129. idle(true);
  6130. }
  6131. KEEPALIVE_STATE(IN_HANDLER);
  6132. }
  6133. #if ENABLED(ULTIPANEL)
  6134. if (show_lcd) // Show "wait for load" message
  6135. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, mode);
  6136. #endif
  6137. // Slow Load filament
  6138. if (slow_load_length) do_pause_e_move(slow_load_length, FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE);
  6139. // Fast Load Filament
  6140. if (fast_load_length) {
  6141. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6142. const float saved_acceleration = planner.retract_acceleration;
  6143. planner.retract_acceleration = FILAMENT_CHANGE_FAST_LOAD_ACCEL;
  6144. #endif
  6145. do_pause_e_move(fast_load_length, FILAMENT_CHANGE_FAST_LOAD_FEEDRATE);
  6146. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6147. planner.retract_acceleration = saved_acceleration;
  6148. #endif
  6149. }
  6150. #if ENABLED(ADVANCED_PAUSE_CONTINUOUS_PURGE)
  6151. #if ENABLED(ULTIPANEL)
  6152. if (show_lcd)
  6153. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CONTINUOUS_PURGE);
  6154. #endif
  6155. wait_for_user = true;
  6156. for (float purge_count = purge_length; purge_count > 0 && wait_for_user; --purge_count)
  6157. do_pause_e_move(1, ADVANCED_PAUSE_PURGE_FEEDRATE);
  6158. wait_for_user = false;
  6159. #else
  6160. do {
  6161. if (purge_length > 0) {
  6162. // "Wait for filament purge"
  6163. #if ENABLED(ULTIPANEL)
  6164. if (show_lcd)
  6165. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_PURGE, mode);
  6166. #endif
  6167. // Extrude filament to get into hotend
  6168. do_pause_e_move(purge_length, ADVANCED_PAUSE_PURGE_FEEDRATE);
  6169. }
  6170. // Show "Purge More" / "Resume" menu and wait for reply
  6171. #if ENABLED(ULTIPANEL)
  6172. if (show_lcd) {
  6173. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6174. wait_for_user = false;
  6175. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION, mode);
  6176. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  6177. KEEPALIVE_STATE(IN_HANDLER);
  6178. }
  6179. #endif
  6180. // Keep looping if "Purge More" was selected
  6181. } while (
  6182. #if ENABLED(ULTIPANEL)
  6183. show_lcd && advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE
  6184. #else
  6185. 0
  6186. #endif
  6187. );
  6188. #endif
  6189. return true;
  6190. }
  6191. /**
  6192. * Unload filament from the hotend
  6193. *
  6194. * - Fail if the a safe temperature was not reached
  6195. * - Show "wait for unload" placard
  6196. * - Retract, pause, then unload filament
  6197. * - Disable E stepper (on most machines)
  6198. *
  6199. * Returns 'true' if unload was completed, 'false' for abort
  6200. */
  6201. static bool unload_filament(const float &unload_length, const bool show_lcd=false,
  6202. const AdvancedPauseMode mode=ADVANCED_PAUSE_MODE_PAUSE_PRINT
  6203. ) {
  6204. if (!ensure_safe_temperature(mode)) {
  6205. #if ENABLED(ULTIPANEL)
  6206. if (show_lcd) // Show status screen
  6207. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6208. #endif
  6209. return false;
  6210. }
  6211. #if DISABLED(ULTIPANEL)
  6212. UNUSED(show_lcd);
  6213. #else
  6214. if (show_lcd)
  6215. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, mode);
  6216. #endif
  6217. // Retract filament
  6218. do_pause_e_move(-FILAMENT_UNLOAD_RETRACT_LENGTH, PAUSE_PARK_RETRACT_FEEDRATE);
  6219. // Wait for filament to cool
  6220. safe_delay(FILAMENT_UNLOAD_DELAY);
  6221. // Quickly purge
  6222. do_pause_e_move(FILAMENT_UNLOAD_RETRACT_LENGTH + FILAMENT_UNLOAD_PURGE_LENGTH, planner.max_feedrate_mm_s[E_AXIS]);
  6223. // Unload filament
  6224. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6225. const float saved_acceleration = planner.retract_acceleration;
  6226. planner.retract_acceleration = FILAMENT_CHANGE_UNLOAD_ACCEL;
  6227. #endif
  6228. do_pause_e_move(unload_length, FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  6229. #if FILAMENT_CHANGE_FAST_LOAD_ACCEL > 0
  6230. planner.retract_acceleration = saved_acceleration;
  6231. #endif
  6232. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  6233. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  6234. disable_e_stepper(active_extruder);
  6235. safe_delay(100);
  6236. #endif
  6237. return true;
  6238. }
  6239. /**
  6240. * Pause procedure
  6241. *
  6242. * - Abort if already paused
  6243. * - Send host action for pause, if configured
  6244. * - Abort if TARGET temperature is too low
  6245. * - Display "wait for start of filament change" (if a length was specified)
  6246. * - Initial retract, if current temperature is hot enough
  6247. * - Park the nozzle at the given position
  6248. * - Call unload_filament (if a length was specified)
  6249. *
  6250. * Returns 'true' if pause was completed, 'false' for abort
  6251. */
  6252. static bool pause_print(const float &retract, const point_t &park_point, const float &unload_length=0, const bool show_lcd=false) {
  6253. if (did_pause_print) return false; // already paused
  6254. #ifdef ACTION_ON_PAUSE
  6255. SERIAL_ECHOLNPGM("//action:" ACTION_ON_PAUSE);
  6256. #endif
  6257. if (!DEBUGGING(DRYRUN) && unload_length && thermalManager.targetTooColdToExtrude(active_extruder)) {
  6258. SERIAL_ERROR_START();
  6259. SERIAL_ERRORLNPGM(MSG_HOTEND_TOO_COLD);
  6260. #if ENABLED(ULTIPANEL)
  6261. if (show_lcd) // Show status screen
  6262. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6263. LCD_MESSAGEPGM(MSG_M600_TOO_COLD);
  6264. #endif
  6265. return false; // unable to reach safe temperature
  6266. }
  6267. // Indicate that the printer is paused
  6268. ++did_pause_print;
  6269. // Pause the print job and timer
  6270. #if ENABLED(SDSUPPORT)
  6271. if (card.sdprinting) {
  6272. card.pauseSDPrint();
  6273. ++did_pause_print; // Indicate SD pause also
  6274. }
  6275. #endif
  6276. print_job_timer.pause();
  6277. // Save current position
  6278. COPY(resume_position, current_position);
  6279. // Wait for synchronize steppers
  6280. planner.synchronize();
  6281. // Initial retract before move to filament change position
  6282. if (retract && thermalManager.hotEnoughToExtrude(active_extruder))
  6283. do_pause_e_move(retract, PAUSE_PARK_RETRACT_FEEDRATE);
  6284. // Park the nozzle by moving up by z_lift and then moving to (x_pos, y_pos)
  6285. if (!axis_unhomed_error())
  6286. Nozzle::park(2, park_point);
  6287. // Unload the filament
  6288. if (unload_length)
  6289. unload_filament(unload_length, show_lcd);
  6290. return true;
  6291. }
  6292. /**
  6293. * - Show "Insert filament and press button to continue"
  6294. * - Wait for a click before returning
  6295. * - Heaters can time out, reheated before accepting a click
  6296. *
  6297. * Used by M125 and M600
  6298. */
  6299. static void wait_for_filament_reload(const int8_t max_beep_count=0) {
  6300. bool nozzle_timed_out = false;
  6301. #if ENABLED(ULTIPANEL)
  6302. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6303. #endif
  6304. SERIAL_ECHO_START();
  6305. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6306. #if HAS_BUZZER
  6307. filament_change_beep(max_beep_count, true);
  6308. #endif
  6309. // Start the heater idle timers
  6310. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6311. HOTEND_LOOP()
  6312. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6313. // Wait for filament insert by user and press button
  6314. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6315. wait_for_user = true; // LCD click or M108 will clear this
  6316. while (wait_for_user) {
  6317. #if HAS_BUZZER
  6318. filament_change_beep(max_beep_count);
  6319. #endif
  6320. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  6321. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  6322. if (!nozzle_timed_out)
  6323. HOTEND_LOOP()
  6324. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6325. if (nozzle_timed_out) {
  6326. #if ENABLED(ULTIPANEL)
  6327. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  6328. #endif
  6329. SERIAL_ECHO_START();
  6330. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6331. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT);
  6332. #elif ENABLED(EMERGENCY_PARSER)
  6333. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_M108);
  6334. #else
  6335. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_HEAT_LCD);
  6336. #endif
  6337. // Wait for LCD click or M108
  6338. while (wait_for_user) idle(true);
  6339. // Re-enable the heaters if they timed out
  6340. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  6341. // Wait for the heaters to reach the target temperatures
  6342. ensure_safe_temperature();
  6343. #if ENABLED(ULTIPANEL)
  6344. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  6345. #endif
  6346. SERIAL_ECHO_START();
  6347. #if ENABLED(ULTIPANEL) && ENABLED(EMERGENCY_PARSER)
  6348. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT);
  6349. #elif ENABLED(EMERGENCY_PARSER)
  6350. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_M108);
  6351. #else
  6352. SERIAL_ERRORLNPGM(MSG_FILAMENT_CHANGE_INSERT_LCD);
  6353. #endif
  6354. // Start the heater idle timers
  6355. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  6356. HOTEND_LOOP()
  6357. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  6358. wait_for_user = true; // Wait for user to load filament
  6359. nozzle_timed_out = false;
  6360. #if HAS_BUZZER
  6361. filament_change_beep(max_beep_count, true);
  6362. #endif
  6363. }
  6364. idle(true);
  6365. }
  6366. KEEPALIVE_STATE(IN_HANDLER);
  6367. }
  6368. /**
  6369. * Resume or Start print procedure
  6370. *
  6371. * - Abort if not paused
  6372. * - Reset heater idle timers
  6373. * - Load filament if specified, but only if:
  6374. * - a nozzle timed out, or
  6375. * - the nozzle is already heated.
  6376. * - Display "wait for print to resume"
  6377. * - Re-prime the nozzle...
  6378. * - FWRETRACT: Recover/prime from the prior G10.
  6379. * - !FWRETRACT: Retract by resume_position[E], if negative.
  6380. * Not sure how this logic comes into use.
  6381. * - Move the nozzle back to resume_position
  6382. * - Sync the planner E to resume_position[E]
  6383. * - Send host action for resume, if configured
  6384. * - Resume the current SD print job, if any
  6385. */
  6386. static void resume_print(const float &slow_load_length=0, const float &fast_load_length=0, const float &purge_length=ADVANCED_PAUSE_PURGE_LENGTH, const int8_t max_beep_count=0) {
  6387. if (!did_pause_print) return;
  6388. // Re-enable the heaters if they timed out
  6389. bool nozzle_timed_out = false;
  6390. HOTEND_LOOP() {
  6391. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  6392. thermalManager.reset_heater_idle_timer(e);
  6393. }
  6394. if (nozzle_timed_out || thermalManager.hotEnoughToExtrude(active_extruder)) {
  6395. // Load the new filament
  6396. load_filament(slow_load_length, fast_load_length, purge_length, max_beep_count, true, nozzle_timed_out);
  6397. }
  6398. #if ENABLED(ULTIPANEL)
  6399. // "Wait for print to resume"
  6400. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  6401. #endif
  6402. // Intelligent resuming
  6403. #if ENABLED(FWRETRACT)
  6404. // If retracted before goto pause
  6405. if (fwretract.retracted[active_extruder])
  6406. do_pause_e_move(-fwretract.retract_length, fwretract.retract_feedrate_mm_s);
  6407. #endif
  6408. // If resume_position is negative
  6409. if (resume_position[E_CART] < 0) do_pause_e_move(resume_position[E_CART], PAUSE_PARK_RETRACT_FEEDRATE);
  6410. // Move XY to starting position, then Z
  6411. do_blocking_move_to_xy(resume_position[X_AXIS], resume_position[Y_AXIS], NOZZLE_PARK_XY_FEEDRATE);
  6412. // Set Z_AXIS to saved position
  6413. do_blocking_move_to_z(resume_position[Z_AXIS], NOZZLE_PARK_Z_FEEDRATE);
  6414. // Now all extrusion positions are resumed and ready to be confirmed
  6415. // Set extruder to saved position
  6416. planner.set_e_position_mm((destination[E_CART] = current_position[E_CART] = resume_position[E_CART]));
  6417. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6418. runout.reset();
  6419. #endif
  6420. #if ENABLED(ULTIPANEL)
  6421. // Show status screen
  6422. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  6423. #endif
  6424. #ifdef ACTION_ON_RESUME
  6425. SERIAL_ECHOLNPGM("//action:" ACTION_ON_RESUME);
  6426. #endif
  6427. --did_pause_print;
  6428. #if ENABLED(SDSUPPORT)
  6429. if (did_pause_print) {
  6430. card.startFileprint();
  6431. --did_pause_print;
  6432. }
  6433. #endif
  6434. }
  6435. #endif // ADVANCED_PAUSE_FEATURE
  6436. #if ENABLED(SDSUPPORT)
  6437. /**
  6438. * M20: List SD card to serial output
  6439. */
  6440. inline void gcode_M20() {
  6441. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  6442. card.ls();
  6443. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  6444. }
  6445. /**
  6446. * M21: Init SD Card
  6447. */
  6448. inline void gcode_M21() { card.initsd(); }
  6449. /**
  6450. * M22: Release SD Card
  6451. */
  6452. inline void gcode_M22() { card.release(); }
  6453. /**
  6454. * M23: Open a file
  6455. */
  6456. inline void gcode_M23() {
  6457. #if ENABLED(POWER_LOSS_RECOVERY)
  6458. card.removeJobRecoveryFile();
  6459. #endif
  6460. // Simplify3D includes the size, so zero out all spaces (#7227)
  6461. for (char *fn = parser.string_arg; *fn; ++fn) if (*fn == ' ') *fn = '\0';
  6462. card.openFile(parser.string_arg, true);
  6463. }
  6464. /**
  6465. * M24: Start or Resume SD Print
  6466. */
  6467. inline void gcode_M24() {
  6468. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6469. resume_print();
  6470. #endif
  6471. #if ENABLED(POWER_LOSS_RECOVERY)
  6472. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6473. #endif
  6474. card.startFileprint();
  6475. #if ENABLED(POWER_LOSS_RECOVERY)
  6476. if (parser.seenval('T'))
  6477. print_job_timer.resume(parser.value_long());
  6478. else
  6479. #endif
  6480. print_job_timer.start();
  6481. }
  6482. /**
  6483. * M25: Pause SD Print
  6484. */
  6485. inline void gcode_M25() {
  6486. card.pauseSDPrint();
  6487. print_job_timer.pause();
  6488. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6489. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  6490. #endif
  6491. }
  6492. /**
  6493. * M26: Set SD Card file index
  6494. */
  6495. inline void gcode_M26() {
  6496. if (card.cardOK && parser.seenval('S'))
  6497. card.setIndex(parser.value_long());
  6498. }
  6499. /**
  6500. * M27: Get SD Card status
  6501. * OR, with 'S<seconds>' set the SD status auto-report interval. (Requires AUTO_REPORT_SD_STATUS)
  6502. * OR, with 'C' get the current filename.
  6503. */
  6504. inline void gcode_M27() {
  6505. if (parser.seen('C')) {
  6506. SERIAL_ECHOPGM("Current file: ");
  6507. card.printFilename();
  6508. }
  6509. #if ENABLED(AUTO_REPORT_SD_STATUS)
  6510. else if (parser.seenval('S'))
  6511. card.set_auto_report_interval(parser.value_byte());
  6512. #endif
  6513. else
  6514. card.getStatus();
  6515. }
  6516. /**
  6517. * M28: Start SD Write
  6518. */
  6519. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  6520. /**
  6521. * M29: Stop SD Write
  6522. * Processed in write to file routine above
  6523. */
  6524. inline void gcode_M29() {
  6525. // card.saving = false;
  6526. }
  6527. /**
  6528. * M30 <filename>: Delete SD Card file
  6529. */
  6530. inline void gcode_M30() {
  6531. if (card.cardOK) {
  6532. card.closefile();
  6533. card.removeFile(parser.string_arg);
  6534. }
  6535. }
  6536. #endif // SDSUPPORT
  6537. /**
  6538. * M31: Get the time since the start of SD Print (or last M109)
  6539. */
  6540. inline void gcode_M31() {
  6541. char buffer[21];
  6542. duration_t elapsed = print_job_timer.duration();
  6543. elapsed.toString(buffer);
  6544. lcd_setstatus(buffer);
  6545. SERIAL_ECHO_START();
  6546. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  6547. }
  6548. #if ENABLED(SDSUPPORT)
  6549. /**
  6550. * M32: Select file and start SD Print
  6551. *
  6552. * Examples:
  6553. *
  6554. * M32 !PATH/TO/FILE.GCO# ; Start FILE.GCO
  6555. * M32 P !PATH/TO/FILE.GCO# ; Start FILE.GCO as a procedure
  6556. * M32 S60 !PATH/TO/FILE.GCO# ; Start FILE.GCO at byte 60
  6557. *
  6558. */
  6559. inline void gcode_M32() {
  6560. if (card.sdprinting) planner.synchronize();
  6561. if (card.cardOK) {
  6562. const bool call_procedure = parser.boolval('P');
  6563. card.openFile(parser.string_arg, true, call_procedure);
  6564. if (parser.seenval('S')) card.setIndex(parser.value_long());
  6565. card.startFileprint();
  6566. // Procedure calls count as normal print time.
  6567. if (!call_procedure) print_job_timer.start();
  6568. }
  6569. }
  6570. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  6571. /**
  6572. * M33: Get the long full path of a file or folder
  6573. *
  6574. * Parameters:
  6575. * <dospath> Case-insensitive DOS-style path to a file or folder
  6576. *
  6577. * Example:
  6578. * M33 miscel~1/armchair/armcha~1.gco
  6579. *
  6580. * Output:
  6581. * /Miscellaneous/Armchair/Armchair.gcode
  6582. */
  6583. inline void gcode_M33() {
  6584. card.printLongPath(parser.string_arg);
  6585. }
  6586. #endif
  6587. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  6588. /**
  6589. * M34: Set SD Card Sorting Options
  6590. */
  6591. inline void gcode_M34() {
  6592. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  6593. if (parser.seenval('F')) {
  6594. const int v = parser.value_long();
  6595. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  6596. }
  6597. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  6598. }
  6599. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  6600. /**
  6601. * M928: Start SD Write
  6602. */
  6603. inline void gcode_M928() {
  6604. card.openLogFile(parser.string_arg);
  6605. }
  6606. #endif // SDSUPPORT
  6607. /**
  6608. * Sensitive pin test for M42, M226
  6609. */
  6610. static bool pin_is_protected(const pin_t pin) {
  6611. static const pin_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  6612. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  6613. if (pin == (pin_t)pgm_read_byte(&sensitive_pins[i])) return true;
  6614. return false;
  6615. }
  6616. inline void protected_pin_err() {
  6617. SERIAL_ERROR_START();
  6618. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  6619. }
  6620. /**
  6621. * M42: Change pin status via GCode
  6622. *
  6623. * P<pin> Pin number (LED if omitted)
  6624. * S<byte> Pin status from 0 - 255
  6625. * I Flag to ignore Marlin's pin protection
  6626. */
  6627. inline void gcode_M42() {
  6628. if (!parser.seenval('S')) return;
  6629. const byte pin_status = parser.value_byte();
  6630. const pin_t pin_number = parser.byteval('P', LED_PIN);
  6631. if (pin_number < 0) return;
  6632. if (!parser.boolval('I') && pin_is_protected(pin_number)) return protected_pin_err();
  6633. pinMode(pin_number, OUTPUT);
  6634. digitalWrite(pin_number, pin_status);
  6635. analogWrite(pin_number, pin_status);
  6636. #if FAN_COUNT > 0
  6637. switch (pin_number) {
  6638. #if HAS_FAN0
  6639. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  6640. #endif
  6641. #if HAS_FAN1
  6642. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  6643. #endif
  6644. #if HAS_FAN2
  6645. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  6646. #endif
  6647. }
  6648. #endif
  6649. }
  6650. #if ENABLED(PINS_DEBUGGING)
  6651. #include "pinsDebug.h"
  6652. inline void toggle_pins() {
  6653. const bool ignore_protection = parser.boolval('I');
  6654. const int repeat = parser.intval('R', 1),
  6655. start = parser.intval('S'),
  6656. end = parser.intval('L', NUM_DIGITAL_PINS - 1),
  6657. wait = parser.intval('W', 500);
  6658. for (uint8_t pin = start; pin <= end; pin++) {
  6659. //report_pin_state_extended(pin, ignore_protection, false);
  6660. if (!ignore_protection && pin_is_protected(pin)) {
  6661. report_pin_state_extended(pin, ignore_protection, true, "Untouched ");
  6662. SERIAL_EOL();
  6663. }
  6664. else {
  6665. report_pin_state_extended(pin, ignore_protection, true, "Pulsing ");
  6666. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  6667. if (pin == TEENSY_E2) {
  6668. SET_OUTPUT(TEENSY_E2);
  6669. for (int16_t j = 0; j < repeat; j++) {
  6670. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6671. WRITE(TEENSY_E2, HIGH); safe_delay(wait);
  6672. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  6673. }
  6674. }
  6675. else if (pin == TEENSY_E3) {
  6676. SET_OUTPUT(TEENSY_E3);
  6677. for (int16_t j = 0; j < repeat; j++) {
  6678. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6679. WRITE(TEENSY_E3, HIGH); safe_delay(wait);
  6680. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  6681. }
  6682. }
  6683. else
  6684. #endif
  6685. {
  6686. pinMode(pin, OUTPUT);
  6687. for (int16_t j = 0; j < repeat; j++) {
  6688. digitalWrite(pin, 0); safe_delay(wait);
  6689. digitalWrite(pin, 1); safe_delay(wait);
  6690. digitalWrite(pin, 0); safe_delay(wait);
  6691. }
  6692. }
  6693. }
  6694. SERIAL_EOL();
  6695. }
  6696. SERIAL_ECHOLNPGM("Done.");
  6697. } // toggle_pins
  6698. inline void servo_probe_test() {
  6699. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  6700. SERIAL_ERROR_START();
  6701. SERIAL_ERRORLNPGM("SERVO not setup");
  6702. #elif !HAS_Z_SERVO_PROBE
  6703. SERIAL_ERROR_START();
  6704. SERIAL_ERRORLNPGM("Z_PROBE_SERVO_NR not setup");
  6705. #else // HAS_Z_SERVO_PROBE
  6706. const uint8_t probe_index = parser.byteval('P', Z_PROBE_SERVO_NR);
  6707. SERIAL_PROTOCOLLNPGM("Servo probe test");
  6708. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  6709. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  6710. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  6711. bool probe_inverting;
  6712. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  6713. #define PROBE_TEST_PIN Z_MIN_PIN
  6714. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  6715. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  6716. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  6717. #if Z_MIN_ENDSTOP_INVERTING
  6718. SERIAL_PROTOCOLLNPGM("true");
  6719. #else
  6720. SERIAL_PROTOCOLLNPGM("false");
  6721. #endif
  6722. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  6723. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  6724. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  6725. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  6726. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  6727. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  6728. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  6729. SERIAL_PROTOCOLLNPGM("true");
  6730. #else
  6731. SERIAL_PROTOCOLLNPGM("false");
  6732. #endif
  6733. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  6734. #endif
  6735. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  6736. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  6737. bool deploy_state, stow_state;
  6738. for (uint8_t i = 0; i < 4; i++) {
  6739. MOVE_SERVO(probe_index, z_servo_angle[0]); //deploy
  6740. safe_delay(500);
  6741. deploy_state = READ(PROBE_TEST_PIN);
  6742. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6743. safe_delay(500);
  6744. stow_state = READ(PROBE_TEST_PIN);
  6745. }
  6746. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  6747. if (deploy_state != stow_state) {
  6748. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  6749. if (deploy_state) {
  6750. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  6751. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  6752. }
  6753. else {
  6754. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  6755. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  6756. }
  6757. #if ENABLED(BLTOUCH)
  6758. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  6759. #endif
  6760. }
  6761. else { // measure active signal length
  6762. MOVE_SERVO(probe_index, z_servo_angle[0]); // deploy
  6763. safe_delay(500);
  6764. SERIAL_PROTOCOLLNPGM("please trigger probe");
  6765. uint16_t probe_counter = 0;
  6766. // Allow 30 seconds max for operator to trigger probe
  6767. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  6768. safe_delay(2);
  6769. if (0 == j % (500 * 1)) reset_stepper_timeout(); // Keep steppers powered
  6770. if (deploy_state != READ(PROBE_TEST_PIN)) { // probe triggered
  6771. for (probe_counter = 1; probe_counter < 50 && deploy_state != READ(PROBE_TEST_PIN); ++probe_counter)
  6772. safe_delay(2);
  6773. if (probe_counter == 50)
  6774. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  6775. else if (probe_counter >= 2)
  6776. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  6777. else
  6778. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  6779. MOVE_SERVO(probe_index, z_servo_angle[1]); //stow
  6780. } // pulse detected
  6781. } // for loop waiting for trigger
  6782. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  6783. } // measure active signal length
  6784. #endif
  6785. } // servo_probe_test
  6786. /**
  6787. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  6788. *
  6789. * M43 - report name and state of pin(s)
  6790. * P<pin> Pin to read or watch. If omitted, reads all pins.
  6791. * I Flag to ignore Marlin's pin protection.
  6792. *
  6793. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  6794. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  6795. * I Flag to ignore Marlin's pin protection.
  6796. *
  6797. * M43 E<bool> - Enable / disable background endstop monitoring
  6798. * - Machine continues to operate
  6799. * - Reports changes to endstops
  6800. * - Toggles LED_PIN when an endstop changes
  6801. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  6802. *
  6803. * M43 T - Toggle pin(s) and report which pin is being toggled
  6804. * S<pin> - Start Pin number. If not given, will default to 0
  6805. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  6806. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  6807. * R - Repeat pulses on each pin this number of times before continueing to next pin
  6808. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  6809. *
  6810. * M43 S - Servo probe test
  6811. * P<index> - Probe index (optional - defaults to 0
  6812. */
  6813. inline void gcode_M43() {
  6814. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  6815. toggle_pins();
  6816. return;
  6817. }
  6818. // Enable or disable endstop monitoring
  6819. if (parser.seen('E')) {
  6820. endstops.monitor_flag = parser.value_bool();
  6821. SERIAL_PROTOCOLPGM("endstop monitor ");
  6822. serialprintPGM(endstops.monitor_flag ? PSTR("en") : PSTR("dis"));
  6823. SERIAL_PROTOCOLLNPGM("abled");
  6824. return;
  6825. }
  6826. if (parser.seen('S')) {
  6827. servo_probe_test();
  6828. return;
  6829. }
  6830. // Get the range of pins to test or watch
  6831. const pin_t first_pin = parser.byteval('P'),
  6832. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  6833. if (first_pin > last_pin) return;
  6834. const bool ignore_protection = parser.boolval('I');
  6835. // Watch until click, M108, or reset
  6836. if (parser.boolval('W')) {
  6837. SERIAL_PROTOCOLLNPGM("Watching pins");
  6838. byte pin_state[last_pin - first_pin + 1];
  6839. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6840. if (!ignore_protection && pin_is_protected(pin)) continue;
  6841. pinMode(pin, INPUT_PULLUP);
  6842. delay(1);
  6843. /*
  6844. if (IS_ANALOG(pin))
  6845. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  6846. else
  6847. //*/
  6848. pin_state[pin - first_pin] = digitalRead(pin);
  6849. }
  6850. #if HAS_RESUME_CONTINUE
  6851. wait_for_user = true;
  6852. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6853. #endif
  6854. for (;;) {
  6855. for (pin_t pin = first_pin; pin <= last_pin; pin++) {
  6856. if (!ignore_protection && pin_is_protected(pin)) continue;
  6857. const byte val =
  6858. /*
  6859. IS_ANALOG(pin)
  6860. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  6861. :
  6862. //*/
  6863. digitalRead(pin);
  6864. if (val != pin_state[pin - first_pin]) {
  6865. report_pin_state_extended(pin, ignore_protection, false);
  6866. pin_state[pin - first_pin] = val;
  6867. }
  6868. }
  6869. #if HAS_RESUME_CONTINUE
  6870. if (!wait_for_user) {
  6871. KEEPALIVE_STATE(IN_HANDLER);
  6872. break;
  6873. }
  6874. #endif
  6875. safe_delay(200);
  6876. }
  6877. return;
  6878. }
  6879. // Report current state of selected pin(s)
  6880. for (pin_t pin = first_pin; pin <= last_pin; pin++)
  6881. report_pin_state_extended(pin, ignore_protection, true);
  6882. }
  6883. #endif // PINS_DEBUGGING
  6884. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  6885. /**
  6886. * M48: Z probe repeatability measurement function.
  6887. *
  6888. * Usage:
  6889. * M48 <P#> <X#> <Y#> <V#> <E> <L#> <S>
  6890. * P = Number of sampled points (4-50, default 10)
  6891. * X = Sample X position
  6892. * Y = Sample Y position
  6893. * V = Verbose level (0-4, default=1)
  6894. * E = Engage Z probe for each reading
  6895. * L = Number of legs of movement before probe
  6896. * S = Schizoid (Or Star if you prefer)
  6897. *
  6898. * This function requires the machine to be homed before invocation.
  6899. */
  6900. inline void gcode_M48() {
  6901. if (axis_unhomed_error()) return;
  6902. const int8_t verbose_level = parser.byteval('V', 1);
  6903. if (!WITHIN(verbose_level, 0, 4)) {
  6904. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  6905. return;
  6906. }
  6907. if (verbose_level > 0)
  6908. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  6909. const int8_t n_samples = parser.byteval('P', 10);
  6910. if (!WITHIN(n_samples, 4, 50)) {
  6911. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  6912. return;
  6913. }
  6914. const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;
  6915. float X_current = current_position[X_AXIS],
  6916. Y_current = current_position[Y_AXIS];
  6917. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  6918. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  6919. if (!position_is_reachable_by_probe(X_probe_location, Y_probe_location)) {
  6920. SERIAL_PROTOCOLLNPGM("? (X,Y) out of bounds.");
  6921. return;
  6922. }
  6923. bool seen_L = parser.seen('L');
  6924. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  6925. if (n_legs > 15) {
  6926. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  6927. return;
  6928. }
  6929. if (n_legs == 1) n_legs = 2;
  6930. const bool schizoid_flag = parser.boolval('S');
  6931. if (schizoid_flag && !seen_L) n_legs = 7;
  6932. /**
  6933. * Now get everything to the specified probe point So we can safely do a
  6934. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  6935. * we don't want to use that as a starting point for each probe.
  6936. */
  6937. if (verbose_level > 2)
  6938. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  6939. // Disable bed level correction in M48 because we want the raw data when we probe
  6940. #if HAS_LEVELING
  6941. const bool was_enabled = planner.leveling_active;
  6942. set_bed_leveling_enabled(false);
  6943. #endif
  6944. setup_for_endstop_or_probe_move();
  6945. float mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  6946. // Move to the first point, deploy, and probe
  6947. const float t = probe_pt(X_probe_location, Y_probe_location, raise_after, verbose_level);
  6948. bool probing_good = !isnan(t);
  6949. if (probing_good) {
  6950. randomSeed(millis());
  6951. for (uint8_t n = 0; n < n_samples; n++) {
  6952. if (n_legs) {
  6953. const int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  6954. float angle = random(0.0, 360.0);
  6955. const float radius = random(
  6956. #if ENABLED(DELTA)
  6957. 0.1250000000 * (DELTA_PRINTABLE_RADIUS),
  6958. 0.3333333333 * (DELTA_PRINTABLE_RADIUS)
  6959. #else
  6960. 5.0, 0.125 * MIN(X_BED_SIZE, Y_BED_SIZE)
  6961. #endif
  6962. );
  6963. if (verbose_level > 3) {
  6964. SERIAL_ECHOPAIR("Starting radius: ", radius);
  6965. SERIAL_ECHOPAIR(" angle: ", angle);
  6966. SERIAL_ECHOPGM(" Direction: ");
  6967. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  6968. SERIAL_ECHOLNPGM("Clockwise");
  6969. }
  6970. for (uint8_t l = 0; l < n_legs - 1; l++) {
  6971. float delta_angle;
  6972. if (schizoid_flag)
  6973. // The points of a 5 point star are 72 degrees apart. We need to
  6974. // skip a point and go to the next one on the star.
  6975. delta_angle = dir * 2.0 * 72.0;
  6976. else
  6977. // If we do this line, we are just trying to move further
  6978. // around the circle.
  6979. delta_angle = dir * (float) random(25, 45);
  6980. angle += delta_angle;
  6981. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  6982. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  6983. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  6984. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  6985. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  6986. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  6987. #if DISABLED(DELTA)
  6988. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  6989. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  6990. #else
  6991. // If we have gone out too far, we can do a simple fix and scale the numbers
  6992. // back in closer to the origin.
  6993. while (!position_is_reachable_by_probe(X_current, Y_current)) {
  6994. X_current *= 0.8;
  6995. Y_current *= 0.8;
  6996. if (verbose_level > 3) {
  6997. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  6998. SERIAL_ECHOLNPAIR(", ", Y_current);
  6999. }
  7000. }
  7001. #endif
  7002. if (verbose_level > 3) {
  7003. SERIAL_PROTOCOLPGM("Going to:");
  7004. SERIAL_ECHOPAIR(" X", X_current);
  7005. SERIAL_ECHOPAIR(" Y", Y_current);
  7006. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  7007. }
  7008. do_blocking_move_to_xy(X_current, Y_current);
  7009. } // n_legs loop
  7010. } // n_legs
  7011. // Probe a single point
  7012. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, raise_after);
  7013. // Break the loop if the probe fails
  7014. probing_good = !isnan(sample_set[n]);
  7015. if (!probing_good) break;
  7016. /**
  7017. * Get the current mean for the data points we have so far
  7018. */
  7019. float sum = 0.0;
  7020. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  7021. mean = sum / (n + 1);
  7022. NOMORE(min, sample_set[n]);
  7023. NOLESS(max, sample_set[n]);
  7024. /**
  7025. * Now, use that mean to calculate the standard deviation for the
  7026. * data points we have so far
  7027. */
  7028. sum = 0.0;
  7029. for (uint8_t j = 0; j <= n; j++)
  7030. sum += sq(sample_set[j] - mean);
  7031. sigma = SQRT(sum / (n + 1));
  7032. if (verbose_level > 0) {
  7033. if (verbose_level > 1) {
  7034. SERIAL_PROTOCOL(n + 1);
  7035. SERIAL_PROTOCOLPGM(" of ");
  7036. SERIAL_PROTOCOL(int(n_samples));
  7037. SERIAL_PROTOCOLPGM(": z: ");
  7038. SERIAL_PROTOCOL_F(sample_set[n], 3);
  7039. if (verbose_level > 2) {
  7040. SERIAL_PROTOCOLPGM(" mean: ");
  7041. SERIAL_PROTOCOL_F(mean, 4);
  7042. SERIAL_PROTOCOLPGM(" sigma: ");
  7043. SERIAL_PROTOCOL_F(sigma, 6);
  7044. SERIAL_PROTOCOLPGM(" min: ");
  7045. SERIAL_PROTOCOL_F(min, 3);
  7046. SERIAL_PROTOCOLPGM(" max: ");
  7047. SERIAL_PROTOCOL_F(max, 3);
  7048. SERIAL_PROTOCOLPGM(" range: ");
  7049. SERIAL_PROTOCOL_F(max-min, 3);
  7050. }
  7051. SERIAL_EOL();
  7052. }
  7053. }
  7054. } // n_samples loop
  7055. }
  7056. STOW_PROBE();
  7057. if (probing_good) {
  7058. SERIAL_PROTOCOLLNPGM("Finished!");
  7059. if (verbose_level > 0) {
  7060. SERIAL_PROTOCOLPGM("Mean: ");
  7061. SERIAL_PROTOCOL_F(mean, 6);
  7062. SERIAL_PROTOCOLPGM(" Min: ");
  7063. SERIAL_PROTOCOL_F(min, 3);
  7064. SERIAL_PROTOCOLPGM(" Max: ");
  7065. SERIAL_PROTOCOL_F(max, 3);
  7066. SERIAL_PROTOCOLPGM(" Range: ");
  7067. SERIAL_PROTOCOL_F(max-min, 3);
  7068. SERIAL_EOL();
  7069. }
  7070. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  7071. SERIAL_PROTOCOL_F(sigma, 6);
  7072. SERIAL_EOL();
  7073. SERIAL_EOL();
  7074. }
  7075. clean_up_after_endstop_or_probe_move();
  7076. // Re-enable bed level correction if it had been on
  7077. #if HAS_LEVELING
  7078. set_bed_leveling_enabled(was_enabled);
  7079. #endif
  7080. #ifdef Z_AFTER_PROBING
  7081. move_z_after_probing();
  7082. #endif
  7083. report_current_position();
  7084. }
  7085. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  7086. #if ENABLED(G26_MESH_VALIDATION)
  7087. inline void gcode_M49() {
  7088. g26_debug_flag ^= true;
  7089. SERIAL_PROTOCOLPGM("G26 Debug ");
  7090. serialprintPGM(g26_debug_flag ? PSTR("on.\n") : PSTR("off.\n"));
  7091. }
  7092. #endif // G26_MESH_VALIDATION
  7093. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  7094. /**
  7095. * M73: Set percentage complete (for display on LCD)
  7096. *
  7097. * Example:
  7098. * M73 P25 ; Set progress to 25%
  7099. *
  7100. * Notes:
  7101. * This has no effect during an SD print job
  7102. */
  7103. inline void gcode_M73() {
  7104. if (!IS_SD_PRINTING() && parser.seen('P')) {
  7105. progress_bar_percent = parser.value_byte();
  7106. NOMORE(progress_bar_percent, 100);
  7107. }
  7108. }
  7109. #endif // ULTRA_LCD && LCD_SET_PROGRESS_MANUALLY
  7110. /**
  7111. * M75: Start print timer
  7112. */
  7113. inline void gcode_M75() { print_job_timer.start(); }
  7114. /**
  7115. * M76: Pause print timer
  7116. */
  7117. inline void gcode_M76() { print_job_timer.pause(); }
  7118. /**
  7119. * M77: Stop print timer
  7120. */
  7121. inline void gcode_M77() { print_job_timer.stop(); }
  7122. #if ENABLED(PRINTCOUNTER)
  7123. /**
  7124. * M78: Show print statistics
  7125. */
  7126. inline void gcode_M78() {
  7127. // "M78 S78" will reset the statistics
  7128. if (parser.intval('S') == 78)
  7129. print_job_timer.initStats();
  7130. else
  7131. print_job_timer.showStats();
  7132. }
  7133. #endif
  7134. /**
  7135. * M104: Set hot end temperature
  7136. */
  7137. inline void gcode_M104() {
  7138. if (get_target_extruder_from_command(104)) return;
  7139. if (DEBUGGING(DRYRUN)) return;
  7140. #if ENABLED(SINGLENOZZLE)
  7141. if (target_extruder != active_extruder) return;
  7142. #endif
  7143. if (parser.seenval('S')) {
  7144. const int16_t temp = parser.value_celsius();
  7145. thermalManager.setTargetHotend(temp, target_extruder);
  7146. #if ENABLED(DUAL_X_CARRIAGE)
  7147. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  7148. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  7149. #endif
  7150. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7151. /**
  7152. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  7153. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  7154. * standby mode, for instance in a dual extruder setup, without affecting
  7155. * the running print timer.
  7156. */
  7157. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  7158. print_job_timer.stop();
  7159. lcd_reset_status();
  7160. }
  7161. #endif
  7162. }
  7163. #if ENABLED(AUTOTEMP)
  7164. planner.autotemp_M104_M109();
  7165. #endif
  7166. }
  7167. /**
  7168. * M105: Read hot end and bed temperature
  7169. */
  7170. inline void gcode_M105() {
  7171. if (get_target_extruder_from_command(105)) return;
  7172. #if HAS_TEMP_SENSOR
  7173. SERIAL_PROTOCOLPGM(MSG_OK);
  7174. thermalManager.print_heaterstates();
  7175. #else // !HAS_TEMP_SENSOR
  7176. SERIAL_ERROR_START();
  7177. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  7178. #endif
  7179. SERIAL_EOL();
  7180. }
  7181. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7182. /**
  7183. * M155: Set temperature auto-report interval. M155 S<seconds>
  7184. */
  7185. inline void gcode_M155() {
  7186. if (parser.seenval('S'))
  7187. thermalManager.set_auto_report_interval(parser.value_byte());
  7188. }
  7189. #endif // AUTO_REPORT_TEMPERATURES
  7190. #if FAN_COUNT > 0
  7191. /**
  7192. * M106: Set Fan Speed
  7193. *
  7194. * S<int> Speed between 0-255
  7195. * P<index> Fan index, if more than one fan
  7196. *
  7197. * With EXTRA_FAN_SPEED enabled:
  7198. *
  7199. * T<int> Restore/Use/Set Temporary Speed:
  7200. * 1 = Restore previous speed after T2
  7201. * 2 = Use temporary speed set with T3-255
  7202. * 3-255 = Set the speed for use with T2
  7203. */
  7204. inline void gcode_M106() {
  7205. const uint8_t p = parser.byteval('P');
  7206. if (p < FAN_COUNT) {
  7207. #if ENABLED(EXTRA_FAN_SPEED)
  7208. const int16_t t = parser.intval('T');
  7209. if (t > 0) {
  7210. switch (t) {
  7211. case 1:
  7212. fanSpeeds[p] = old_fanSpeeds[p];
  7213. break;
  7214. case 2:
  7215. old_fanSpeeds[p] = fanSpeeds[p];
  7216. fanSpeeds[p] = new_fanSpeeds[p];
  7217. break;
  7218. default:
  7219. new_fanSpeeds[p] = MIN(t, 255);
  7220. break;
  7221. }
  7222. return;
  7223. }
  7224. #endif // EXTRA_FAN_SPEED
  7225. const uint16_t s = parser.ushortval('S', 255);
  7226. fanSpeeds[p] = MIN(s, 255U);
  7227. }
  7228. }
  7229. /**
  7230. * M107: Fan Off
  7231. */
  7232. inline void gcode_M107() {
  7233. const uint16_t p = parser.ushortval('P');
  7234. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  7235. }
  7236. #endif // FAN_COUNT > 0
  7237. #if DISABLED(EMERGENCY_PARSER)
  7238. /**
  7239. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  7240. */
  7241. inline void gcode_M108() { wait_for_heatup = false; }
  7242. /**
  7243. * M112: Emergency Stop
  7244. */
  7245. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  7246. /**
  7247. * M410: Quickstop - Abort all planned moves
  7248. *
  7249. * This will stop the carriages mid-move, so most likely they
  7250. * will be out of sync with the stepper position after this.
  7251. */
  7252. inline void gcode_M410() { quickstop_stepper(); }
  7253. #endif
  7254. /**
  7255. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  7256. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  7257. */
  7258. #ifndef MIN_COOLING_SLOPE_DEG
  7259. #define MIN_COOLING_SLOPE_DEG 1.50
  7260. #endif
  7261. #ifndef MIN_COOLING_SLOPE_TIME
  7262. #define MIN_COOLING_SLOPE_TIME 60
  7263. #endif
  7264. inline void gcode_M109() {
  7265. if (get_target_extruder_from_command(109)) return;
  7266. if (DEBUGGING(DRYRUN)) return;
  7267. #if ENABLED(SINGLENOZZLE)
  7268. if (target_extruder != active_extruder) return;
  7269. #endif
  7270. const bool no_wait_for_cooling = parser.seenval('S'),
  7271. set_temp = no_wait_for_cooling || parser.seenval('R');
  7272. if (set_temp) {
  7273. const int16_t temp = parser.value_celsius();
  7274. thermalManager.setTargetHotend(temp, target_extruder);
  7275. #if ENABLED(DUAL_X_CARRIAGE)
  7276. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  7277. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  7278. #endif
  7279. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7280. /**
  7281. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  7282. * standby mode, (e.g., in a dual extruder setup) without affecting
  7283. * the running print timer.
  7284. */
  7285. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  7286. print_job_timer.stop();
  7287. lcd_reset_status();
  7288. }
  7289. else
  7290. print_job_timer.start();
  7291. #endif
  7292. #if ENABLED(ULTRA_LCD)
  7293. const bool heating = thermalManager.isHeatingHotend(target_extruder);
  7294. if (heating || !no_wait_for_cooling)
  7295. #if HOTENDS > 1
  7296. lcd_status_printf_P(0, heating ? PSTR("E%i " MSG_HEATING) : PSTR("E%i " MSG_COOLING), target_extruder + 1);
  7297. #else
  7298. lcd_setstatusPGM(heating ? PSTR("E " MSG_HEATING) : PSTR("E " MSG_COOLING));
  7299. #endif
  7300. #endif
  7301. }
  7302. #if ENABLED(AUTOTEMP)
  7303. planner.autotemp_M104_M109();
  7304. #endif
  7305. if (!set_temp) return;
  7306. #if TEMP_RESIDENCY_TIME > 0
  7307. millis_t residency_start_ms = 0;
  7308. // Loop until the temperature has stabilized
  7309. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  7310. #else
  7311. // Loop until the temperature is very close target
  7312. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  7313. #endif
  7314. float target_temp = -1, old_temp = 9999;
  7315. bool wants_to_cool = false;
  7316. wait_for_heatup = true;
  7317. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7318. #if DISABLED(BUSY_WHILE_HEATING)
  7319. KEEPALIVE_STATE(NOT_BUSY);
  7320. #endif
  7321. #if ENABLED(PRINTER_EVENT_LEDS)
  7322. const float start_temp = thermalManager.degHotend(target_extruder);
  7323. uint8_t old_blue = 0;
  7324. #endif
  7325. do {
  7326. // Target temperature might be changed during the loop
  7327. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  7328. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  7329. target_temp = thermalManager.degTargetHotend(target_extruder);
  7330. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7331. if (no_wait_for_cooling && wants_to_cool) break;
  7332. }
  7333. now = millis();
  7334. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  7335. next_temp_ms = now + 1000UL;
  7336. thermalManager.print_heaterstates();
  7337. #if TEMP_RESIDENCY_TIME > 0
  7338. SERIAL_PROTOCOLPGM(" W:");
  7339. if (residency_start_ms)
  7340. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7341. else
  7342. SERIAL_PROTOCOLCHAR('?');
  7343. #endif
  7344. SERIAL_EOL();
  7345. }
  7346. idle();
  7347. reset_stepper_timeout(); // Keep steppers powered
  7348. const float temp = thermalManager.degHotend(target_extruder);
  7349. #if ENABLED(PRINTER_EVENT_LEDS)
  7350. // Gradually change LED strip from violet to red as nozzle heats up
  7351. if (!wants_to_cool) {
  7352. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  7353. if (blue != old_blue) {
  7354. old_blue = blue;
  7355. leds.set_color(
  7356. MakeLEDColor(255, 0, blue, 0, pixels.getBrightness())
  7357. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7358. , true
  7359. #endif
  7360. );
  7361. }
  7362. }
  7363. #endif
  7364. #if TEMP_RESIDENCY_TIME > 0
  7365. const float temp_diff = ABS(target_temp - temp);
  7366. if (!residency_start_ms) {
  7367. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  7368. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  7369. }
  7370. else if (temp_diff > TEMP_HYSTERESIS) {
  7371. // Restart the timer whenever the temperature falls outside the hysteresis.
  7372. residency_start_ms = now;
  7373. }
  7374. #endif
  7375. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  7376. if (wants_to_cool) {
  7377. // break after MIN_COOLING_SLOPE_TIME seconds
  7378. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  7379. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7380. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG)) break;
  7381. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  7382. old_temp = temp;
  7383. }
  7384. }
  7385. } while (wait_for_heatup && TEMP_CONDITIONS);
  7386. if (wait_for_heatup) {
  7387. lcd_reset_status();
  7388. #if ENABLED(PRINTER_EVENT_LEDS)
  7389. leds.set_white();
  7390. #endif
  7391. }
  7392. #if DISABLED(BUSY_WHILE_HEATING)
  7393. KEEPALIVE_STATE(IN_HANDLER);
  7394. #endif
  7395. }
  7396. #if HAS_HEATED_BED
  7397. /**
  7398. * M140: Set bed temperature
  7399. */
  7400. inline void gcode_M140() {
  7401. if (DEBUGGING(DRYRUN)) return;
  7402. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  7403. }
  7404. #ifndef MIN_COOLING_SLOPE_DEG_BED
  7405. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  7406. #endif
  7407. #ifndef MIN_COOLING_SLOPE_TIME_BED
  7408. #define MIN_COOLING_SLOPE_TIME_BED 60
  7409. #endif
  7410. /**
  7411. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  7412. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  7413. */
  7414. inline void gcode_M190() {
  7415. if (DEBUGGING(DRYRUN)) return;
  7416. const bool no_wait_for_cooling = parser.seenval('S');
  7417. if (no_wait_for_cooling || parser.seenval('R')) {
  7418. thermalManager.setTargetBed(parser.value_celsius());
  7419. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  7420. if (parser.value_celsius() > BED_MINTEMP)
  7421. print_job_timer.start();
  7422. #endif
  7423. }
  7424. else return;
  7425. lcd_setstatusPGM(thermalManager.isHeatingBed() ? PSTR(MSG_BED_HEATING) : PSTR(MSG_BED_COOLING));
  7426. #if TEMP_BED_RESIDENCY_TIME > 0
  7427. millis_t residency_start_ms = 0;
  7428. // Loop until the temperature has stabilized
  7429. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  7430. #else
  7431. // Loop until the temperature is very close target
  7432. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  7433. #endif
  7434. float target_temp = -1.0, old_temp = 9999.0;
  7435. bool wants_to_cool = false;
  7436. wait_for_heatup = true;
  7437. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  7438. #if DISABLED(BUSY_WHILE_HEATING)
  7439. KEEPALIVE_STATE(NOT_BUSY);
  7440. #endif
  7441. target_extruder = active_extruder; // for print_heaterstates
  7442. #if ENABLED(PRINTER_EVENT_LEDS)
  7443. const float start_temp = thermalManager.degBed();
  7444. uint8_t old_red = 127;
  7445. #endif
  7446. do {
  7447. // Target temperature might be changed during the loop
  7448. if (target_temp != thermalManager.degTargetBed()) {
  7449. wants_to_cool = thermalManager.isCoolingBed();
  7450. target_temp = thermalManager.degTargetBed();
  7451. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  7452. if (no_wait_for_cooling && wants_to_cool) break;
  7453. }
  7454. now = millis();
  7455. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  7456. next_temp_ms = now + 1000UL;
  7457. thermalManager.print_heaterstates();
  7458. #if TEMP_BED_RESIDENCY_TIME > 0
  7459. SERIAL_PROTOCOLPGM(" W:");
  7460. if (residency_start_ms)
  7461. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  7462. else
  7463. SERIAL_PROTOCOLCHAR('?');
  7464. #endif
  7465. SERIAL_EOL();
  7466. }
  7467. idle();
  7468. reset_stepper_timeout(); // Keep steppers powered
  7469. const float temp = thermalManager.degBed();
  7470. #if ENABLED(PRINTER_EVENT_LEDS)
  7471. // Gradually change LED strip from blue to violet as bed heats up
  7472. if (!wants_to_cool) {
  7473. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  7474. if (red != old_red) {
  7475. old_red = red;
  7476. leds.set_color(
  7477. MakeLEDColor(red, 0, 255, 0, pixels.getBrightness())
  7478. #if ENABLED(NEOPIXEL_IS_SEQUENTIAL)
  7479. , true
  7480. #endif
  7481. );
  7482. }
  7483. }
  7484. #endif
  7485. #if TEMP_BED_RESIDENCY_TIME > 0
  7486. const float temp_diff = ABS(target_temp - temp);
  7487. if (!residency_start_ms) {
  7488. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  7489. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  7490. }
  7491. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  7492. // Restart the timer whenever the temperature falls outside the hysteresis.
  7493. residency_start_ms = now;
  7494. }
  7495. #endif // TEMP_BED_RESIDENCY_TIME > 0
  7496. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  7497. if (wants_to_cool) {
  7498. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  7499. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  7500. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  7501. if (old_temp - temp < float(MIN_COOLING_SLOPE_DEG_BED)) break;
  7502. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  7503. old_temp = temp;
  7504. }
  7505. }
  7506. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  7507. if (wait_for_heatup) lcd_reset_status();
  7508. #if DISABLED(BUSY_WHILE_HEATING)
  7509. KEEPALIVE_STATE(IN_HANDLER);
  7510. #endif
  7511. }
  7512. #endif // HAS_HEATED_BED
  7513. /**
  7514. * M110: Set Current Line Number
  7515. */
  7516. inline void gcode_M110() {
  7517. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  7518. }
  7519. /**
  7520. * M111: Set the debug level
  7521. */
  7522. inline void gcode_M111() {
  7523. if (parser.seen('S')) marlin_debug_flags = parser.byteval('S');
  7524. static const char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO,
  7525. str_debug_2[] PROGMEM = MSG_DEBUG_INFO,
  7526. str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS,
  7527. str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN,
  7528. str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION
  7529. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7530. , str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING
  7531. #endif
  7532. ;
  7533. static const char* const debug_strings[] PROGMEM = {
  7534. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  7535. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7536. , str_debug_32
  7537. #endif
  7538. };
  7539. SERIAL_ECHO_START();
  7540. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  7541. if (marlin_debug_flags) {
  7542. uint8_t comma = 0;
  7543. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  7544. if (TEST(marlin_debug_flags, i)) {
  7545. if (comma++) SERIAL_CHAR(',');
  7546. serialprintPGM((char*)pgm_read_ptr(&debug_strings[i]));
  7547. }
  7548. }
  7549. }
  7550. else {
  7551. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  7552. #if !defined(__AVR__) || !defined(USBCON)
  7553. #if ENABLED(SERIAL_STATS_RX_BUFFER_OVERRUNS)
  7554. SERIAL_ECHOPAIR("\nBuffer Overruns: ", customizedSerial.buffer_overruns());
  7555. #endif
  7556. #if ENABLED(SERIAL_STATS_RX_FRAMING_ERRORS)
  7557. SERIAL_ECHOPAIR("\nFraming Errors: ", customizedSerial.framing_errors());
  7558. #endif
  7559. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  7560. SERIAL_ECHOPAIR("\nDropped bytes: ", customizedSerial.dropped());
  7561. #endif
  7562. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  7563. SERIAL_ECHOPAIR("\nMax RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  7564. #endif
  7565. #endif // !__AVR__ || !USBCON
  7566. }
  7567. SERIAL_EOL();
  7568. }
  7569. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  7570. /**
  7571. * M113: Get or set Host Keepalive interval (0 to disable)
  7572. *
  7573. * S<seconds> Optional. Set the keepalive interval.
  7574. */
  7575. inline void gcode_M113() {
  7576. if (parser.seenval('S')) {
  7577. host_keepalive_interval = parser.value_byte();
  7578. NOMORE(host_keepalive_interval, 60);
  7579. }
  7580. else {
  7581. SERIAL_ECHO_START();
  7582. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  7583. }
  7584. }
  7585. #endif
  7586. #if ENABLED(BARICUDA)
  7587. #if HAS_HEATER_1
  7588. /**
  7589. * M126: Heater 1 valve open
  7590. */
  7591. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  7592. /**
  7593. * M127: Heater 1 valve close
  7594. */
  7595. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  7596. #endif
  7597. #if HAS_HEATER_2
  7598. /**
  7599. * M128: Heater 2 valve open
  7600. */
  7601. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  7602. /**
  7603. * M129: Heater 2 valve close
  7604. */
  7605. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  7606. #endif
  7607. #endif // BARICUDA
  7608. #if ENABLED(ULTIPANEL)
  7609. /**
  7610. * M145: Set the heatup state for a material in the LCD menu
  7611. *
  7612. * S<material> (0=PLA, 1=ABS)
  7613. * H<hotend temp>
  7614. * B<bed temp>
  7615. * F<fan speed>
  7616. */
  7617. inline void gcode_M145() {
  7618. const uint8_t material = (uint8_t)parser.intval('S');
  7619. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  7620. SERIAL_ERROR_START();
  7621. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  7622. }
  7623. else {
  7624. int v;
  7625. if (parser.seenval('H')) {
  7626. v = parser.value_int();
  7627. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  7628. }
  7629. if (parser.seenval('F')) {
  7630. v = parser.value_int();
  7631. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  7632. }
  7633. #if TEMP_SENSOR_BED != 0
  7634. if (parser.seenval('B')) {
  7635. v = parser.value_int();
  7636. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  7637. }
  7638. #endif
  7639. }
  7640. }
  7641. #endif // ULTIPANEL
  7642. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  7643. /**
  7644. * M149: Set temperature units
  7645. */
  7646. inline void gcode_M149() {
  7647. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  7648. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  7649. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  7650. }
  7651. #endif
  7652. #if HAS_POWER_SWITCH
  7653. /**
  7654. * M80 : Turn on the Power Supply
  7655. * M80 S : Report the current state and exit
  7656. */
  7657. inline void gcode_M80() {
  7658. // S: Report the current power supply state and exit
  7659. if (parser.seen('S')) {
  7660. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  7661. return;
  7662. }
  7663. PSU_ON();
  7664. /**
  7665. * If you have a switch on suicide pin, this is useful
  7666. * if you want to start another print with suicide feature after
  7667. * a print without suicide...
  7668. */
  7669. #if HAS_SUICIDE
  7670. OUT_WRITE(SUICIDE_PIN, HIGH);
  7671. #endif
  7672. #if DISABLED(AUTO_POWER_CONTROL)
  7673. delay(100); // Wait for power to settle
  7674. restore_stepper_drivers();
  7675. #endif
  7676. #if ENABLED(ULTIPANEL)
  7677. lcd_reset_status();
  7678. #endif
  7679. }
  7680. #endif // HAS_POWER_SWITCH
  7681. /**
  7682. * M81: Turn off Power, including Power Supply, if there is one.
  7683. *
  7684. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  7685. */
  7686. inline void gcode_M81() {
  7687. thermalManager.disable_all_heaters();
  7688. planner.finish_and_disable();
  7689. #if FAN_COUNT > 0
  7690. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  7691. #if ENABLED(PROBING_FANS_OFF)
  7692. fans_paused = false;
  7693. ZERO(paused_fanSpeeds);
  7694. #endif
  7695. #endif
  7696. safe_delay(1000); // Wait 1 second before switching off
  7697. #if HAS_SUICIDE
  7698. suicide();
  7699. #elif HAS_POWER_SWITCH
  7700. PSU_OFF();
  7701. #endif
  7702. #if ENABLED(ULTIPANEL)
  7703. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  7704. #endif
  7705. }
  7706. /**
  7707. * M82: Set E codes absolute (default)
  7708. */
  7709. inline void gcode_M82() { axis_relative_modes[E_CART] = false; }
  7710. /**
  7711. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  7712. */
  7713. inline void gcode_M83() { axis_relative_modes[E_CART] = true; }
  7714. /**
  7715. * M18, M84: Disable stepper motors
  7716. */
  7717. inline void gcode_M18_M84() {
  7718. if (parser.seenval('S')) {
  7719. stepper_inactive_time = parser.value_millis_from_seconds();
  7720. }
  7721. else {
  7722. bool all_axis = !(parser.seen('X') || parser.seen('Y') || parser.seen('Z') || parser.seen('E'));
  7723. if (all_axis) {
  7724. planner.finish_and_disable();
  7725. }
  7726. else {
  7727. planner.synchronize();
  7728. if (parser.seen('X')) disable_X();
  7729. if (parser.seen('Y')) disable_Y();
  7730. if (parser.seen('Z')) disable_Z();
  7731. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only disable on boards that have separate ENABLE_PINS
  7732. if (parser.seen('E')) disable_e_steppers();
  7733. #endif
  7734. }
  7735. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  7736. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  7737. #endif
  7738. }
  7739. }
  7740. /**
  7741. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  7742. */
  7743. inline void gcode_M85() {
  7744. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  7745. }
  7746. /**
  7747. * Multi-stepper support for M92, M201, M203
  7748. */
  7749. #if ENABLED(DISTINCT_E_FACTORS)
  7750. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  7751. #define TARGET_EXTRUDER target_extruder
  7752. #else
  7753. #define GET_TARGET_EXTRUDER(CMD) NOOP
  7754. #define TARGET_EXTRUDER 0
  7755. #endif
  7756. /**
  7757. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  7758. * (for Hangprinter: A, B, C, D, and E)
  7759. * (Follows the same syntax as G92)
  7760. *
  7761. * With multiple extruders use T to specify which one.
  7762. */
  7763. inline void gcode_M92() {
  7764. GET_TARGET_EXTRUDER(92);
  7765. LOOP_NUM_AXIS(i) {
  7766. if (parser.seen(RAW_AXIS_CODES(i))) {
  7767. if (i == E_AXIS) {
  7768. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  7769. if (value < 20) {
  7770. const float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  7771. #if DISABLED(JUNCTION_DEVIATION)
  7772. planner.max_jerk[E_AXIS] *= factor;
  7773. #endif
  7774. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  7775. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  7776. }
  7777. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  7778. }
  7779. else {
  7780. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  7781. SERIAL_ECHOLNPGM("Warning: "
  7782. "M92 A, B, C, and D only affect acceleration planning "
  7783. "when BUILDUP_COMPENSATION_FEATURE is enabled.");
  7784. #endif
  7785. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  7786. }
  7787. }
  7788. }
  7789. planner.refresh_positioning();
  7790. }
  7791. /**
  7792. * Output the current position to serial
  7793. */
  7794. void report_current_position() {
  7795. SERIAL_PROTOCOLPAIR("X:", LOGICAL_X_POSITION(current_position[X_AXIS]));
  7796. SERIAL_PROTOCOLPAIR(" Y:", LOGICAL_Y_POSITION(current_position[Y_AXIS]));
  7797. SERIAL_PROTOCOLPAIR(" Z:", LOGICAL_Z_POSITION(current_position[Z_AXIS]));
  7798. SERIAL_PROTOCOLPAIR(" E:", current_position[E_CART]);
  7799. #if ENABLED(HANGPRINTER)
  7800. SERIAL_EOL();
  7801. SERIAL_PROTOCOLPAIR("A:", line_lengths[A_AXIS]);
  7802. SERIAL_PROTOCOLPAIR(" B:", line_lengths[B_AXIS]);
  7803. SERIAL_PROTOCOLPAIR(" C:", line_lengths[C_AXIS]);
  7804. SERIAL_PROTOCOLLNPAIR(" D:", line_lengths[D_AXIS]);
  7805. #endif
  7806. stepper.report_positions();
  7807. #if IS_SCARA
  7808. SERIAL_PROTOCOLPAIR("SCARA Theta:", planner.get_axis_position_degrees(A_AXIS));
  7809. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", planner.get_axis_position_degrees(B_AXIS));
  7810. SERIAL_EOL();
  7811. #endif
  7812. }
  7813. #ifdef M114_DETAIL
  7814. void report_xyze(const float pos[], const uint8_t n = 4, const uint8_t precision = 3) {
  7815. char str[12];
  7816. for (uint8_t i = 0; i < n; i++) {
  7817. SERIAL_CHAR(' ');
  7818. SERIAL_CHAR(axis_codes[i]);
  7819. SERIAL_CHAR(':');
  7820. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  7821. }
  7822. SERIAL_EOL();
  7823. }
  7824. inline void report_xyz(const float pos[]) { report_xyze(pos, 3); }
  7825. void report_current_position_detail() {
  7826. SERIAL_PROTOCOLPGM("\nLogical:");
  7827. const float logical[XYZ] = {
  7828. LOGICAL_X_POSITION(current_position[X_AXIS]),
  7829. LOGICAL_Y_POSITION(current_position[Y_AXIS]),
  7830. LOGICAL_Z_POSITION(current_position[Z_AXIS])
  7831. };
  7832. report_xyz(logical);
  7833. SERIAL_PROTOCOLPGM("Raw: ");
  7834. report_xyz(current_position);
  7835. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  7836. #if PLANNER_LEVELING
  7837. SERIAL_PROTOCOLPGM("Leveled:");
  7838. planner.apply_leveling(leveled);
  7839. report_xyz(leveled);
  7840. SERIAL_PROTOCOLPGM("UnLevel:");
  7841. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  7842. planner.unapply_leveling(unleveled);
  7843. report_xyz(unleveled);
  7844. #endif
  7845. #if IS_KINEMATIC
  7846. #if IS_SCARA
  7847. SERIAL_PROTOCOLPGM("ScaraK: ");
  7848. #else
  7849. SERIAL_PROTOCOLPGM("DeltaK: ");
  7850. #endif
  7851. inverse_kinematics(leveled); // writes delta[]
  7852. report_xyz(delta);
  7853. #endif
  7854. planner.synchronize();
  7855. SERIAL_PROTOCOLPGM("Stepper:");
  7856. LOOP_NUM_AXIS(i) {
  7857. SERIAL_CHAR(' ');
  7858. SERIAL_CHAR(RAW_AXIS_CODES(i));
  7859. SERIAL_CHAR(':');
  7860. SERIAL_PROTOCOL(stepper.position((AxisEnum)i));
  7861. }
  7862. SERIAL_EOL();
  7863. #if IS_SCARA
  7864. const float deg[XYZ] = {
  7865. planner.get_axis_position_degrees(A_AXIS),
  7866. planner.get_axis_position_degrees(B_AXIS)
  7867. };
  7868. SERIAL_PROTOCOLPGM("Degrees:");
  7869. report_xyze(deg, 2);
  7870. #endif
  7871. SERIAL_PROTOCOLPGM("FromStp:");
  7872. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  7873. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], planner.get_axis_position_mm(E_AXIS) };
  7874. report_xyze(from_steppers);
  7875. const float diff[XYZE] = {
  7876. from_steppers[X_AXIS] - leveled[X_AXIS],
  7877. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  7878. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  7879. from_steppers[E_CART] - current_position[E_CART]
  7880. };
  7881. SERIAL_PROTOCOLPGM("Differ: ");
  7882. report_xyze(diff);
  7883. }
  7884. #endif // M114_DETAIL
  7885. /**
  7886. * M114: Report current position to host
  7887. */
  7888. inline void gcode_M114() {
  7889. #ifdef M114_DETAIL
  7890. if (parser.seen('D')) return report_current_position_detail();
  7891. #endif
  7892. planner.synchronize();
  7893. const uint16_t sval = parser.ushortval('S');
  7894. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  7895. if (sval == 1) return report_axis_position_from_encoder_data();
  7896. #endif
  7897. if (sval == 2) return report_xyz_from_stepper_position();
  7898. report_current_position();
  7899. }
  7900. /**
  7901. * M115: Capabilities string
  7902. */
  7903. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7904. static void cap_line(const char * const name, bool ena=false) {
  7905. SERIAL_PROTOCOLPGM("Cap:");
  7906. serialprintPGM(name);
  7907. SERIAL_PROTOCOLPGM(":");
  7908. SERIAL_PROTOCOLLN(int(ena ? 1 : 0));
  7909. }
  7910. #endif
  7911. inline void gcode_M115() {
  7912. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  7913. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  7914. // SERIAL_XON_XOFF
  7915. cap_line(PSTR("SERIAL_XON_XOFF")
  7916. #if ENABLED(SERIAL_XON_XOFF)
  7917. , true
  7918. #endif
  7919. );
  7920. // EEPROM (M500, M501)
  7921. cap_line(PSTR("EEPROM")
  7922. #if ENABLED(EEPROM_SETTINGS)
  7923. , true
  7924. #endif
  7925. );
  7926. // Volumetric Extrusion (M200)
  7927. cap_line(PSTR("VOLUMETRIC")
  7928. #if DISABLED(NO_VOLUMETRICS)
  7929. , true
  7930. #endif
  7931. );
  7932. // AUTOREPORT_TEMP (M155)
  7933. cap_line(PSTR("AUTOREPORT_TEMP")
  7934. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  7935. , true
  7936. #endif
  7937. );
  7938. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  7939. cap_line(PSTR("PROGRESS"));
  7940. // Print Job timer M75, M76, M77
  7941. cap_line(PSTR("PRINT_JOB"), true);
  7942. // AUTOLEVEL (G29)
  7943. cap_line(PSTR("AUTOLEVEL")
  7944. #if HAS_AUTOLEVEL
  7945. , true
  7946. #endif
  7947. );
  7948. // Z_PROBE (G30)
  7949. cap_line(PSTR("Z_PROBE")
  7950. #if HAS_BED_PROBE
  7951. , true
  7952. #endif
  7953. );
  7954. // MESH_REPORT (M420 V)
  7955. cap_line(PSTR("LEVELING_DATA")
  7956. #if HAS_LEVELING
  7957. , true
  7958. #endif
  7959. );
  7960. // BUILD_PERCENT (M73)
  7961. cap_line(PSTR("BUILD_PERCENT")
  7962. #if ENABLED(LCD_SET_PROGRESS_MANUALLY)
  7963. , true
  7964. #endif
  7965. );
  7966. // SOFTWARE_POWER (M80, M81)
  7967. cap_line(PSTR("SOFTWARE_POWER")
  7968. #if HAS_POWER_SWITCH
  7969. , true
  7970. #endif
  7971. );
  7972. // CASE LIGHTS (M355)
  7973. cap_line(PSTR("TOGGLE_LIGHTS")
  7974. #if HAS_CASE_LIGHT
  7975. , true
  7976. #endif
  7977. );
  7978. cap_line(PSTR("CASE_LIGHT_BRIGHTNESS")
  7979. #if HAS_CASE_LIGHT
  7980. , USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)
  7981. #endif
  7982. );
  7983. // EMERGENCY_PARSER (M108, M112, M410)
  7984. cap_line(PSTR("EMERGENCY_PARSER")
  7985. #if ENABLED(EMERGENCY_PARSER)
  7986. , true
  7987. #endif
  7988. );
  7989. // AUTOREPORT_SD_STATUS (M27 extension)
  7990. cap_line(PSTR("AUTOREPORT_SD_STATUS")
  7991. #if ENABLED(AUTO_REPORT_SD_STATUS)
  7992. , true
  7993. #endif
  7994. );
  7995. // THERMAL_PROTECTION
  7996. cap_line(PSTR("THERMAL_PROTECTION")
  7997. #if ENABLED(THERMAL_PROTECTION_HOTENDS) && ENABLED(THERMAL_PROTECTION_BED)
  7998. , true
  7999. #endif
  8000. );
  8001. #endif // EXTENDED_CAPABILITIES_REPORT
  8002. }
  8003. /**
  8004. * M117: Set LCD Status Message
  8005. */
  8006. inline void gcode_M117() {
  8007. if (parser.string_arg[0])
  8008. lcd_setstatus(parser.string_arg);
  8009. else
  8010. lcd_reset_status();
  8011. }
  8012. /**
  8013. * M118: Display a message in the host console.
  8014. *
  8015. * A1 Prepend '// ' for an action command, as in OctoPrint
  8016. * E1 Have the host 'echo:' the text
  8017. */
  8018. inline void gcode_M118() {
  8019. bool hasE = false, hasA = false;
  8020. char *p = parser.string_arg;
  8021. for (uint8_t i = 2; i--;)
  8022. if ((p[0] == 'A' || p[0] == 'E') && p[1] == '1') {
  8023. if (p[0] == 'A') hasA = true;
  8024. if (p[0] == 'E') hasE = true;
  8025. p += 2;
  8026. while (*p == ' ') ++p;
  8027. }
  8028. if (hasE) SERIAL_ECHO_START();
  8029. if (hasA) SERIAL_ECHOPGM("// ");
  8030. SERIAL_ECHOLN(p);
  8031. }
  8032. /**
  8033. * M119: Output endstop states to serial output
  8034. */
  8035. inline void gcode_M119() { endstops.M119(); }
  8036. /**
  8037. * M120: Enable endstops and set non-homing endstop state to "enabled"
  8038. */
  8039. inline void gcode_M120() { endstops.enable_globally(true); }
  8040. /**
  8041. * M121: Disable endstops and set non-homing endstop state to "disabled"
  8042. */
  8043. inline void gcode_M121() { endstops.enable_globally(false); }
  8044. #if ENABLED(PARK_HEAD_ON_PAUSE)
  8045. /**
  8046. * M125: Store current position and move to filament change position.
  8047. * Called on pause (by M25) to prevent material leaking onto the
  8048. * object. On resume (M24) the head will be moved back and the
  8049. * print will resume.
  8050. *
  8051. * If Marlin is compiled without SD Card support, M125 can be
  8052. * used directly to pause the print and move to park position,
  8053. * resuming with a button click or M108.
  8054. *
  8055. * L = override retract length
  8056. * X = override X
  8057. * Y = override Y
  8058. * Z = override Z raise
  8059. */
  8060. inline void gcode_M125() {
  8061. // Initial retract before move to filament change position
  8062. const float retract = -ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  8063. #ifdef PAUSE_PARK_RETRACT_LENGTH
  8064. + (PAUSE_PARK_RETRACT_LENGTH)
  8065. #endif
  8066. );
  8067. point_t park_point = NOZZLE_PARK_POINT;
  8068. // Move XY axes to filament change position or given position
  8069. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  8070. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  8071. // Lift Z axis
  8072. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  8073. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  8074. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  8075. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  8076. #endif
  8077. #if DISABLED(SDSUPPORT)
  8078. const bool job_running = print_job_timer.isRunning();
  8079. #endif
  8080. if (pause_print(retract, park_point)) {
  8081. #if DISABLED(SDSUPPORT)
  8082. // Wait for lcd click or M108
  8083. wait_for_filament_reload();
  8084. // Return to print position and continue
  8085. resume_print();
  8086. if (job_running) print_job_timer.start();
  8087. #endif
  8088. }
  8089. }
  8090. #endif // PARK_HEAD_ON_PAUSE
  8091. #if HAS_COLOR_LEDS
  8092. /**
  8093. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  8094. * and Brightness - Use P (for NEOPIXEL only)
  8095. *
  8096. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  8097. * If brightness is left out, no value changed
  8098. *
  8099. * Examples:
  8100. *
  8101. * M150 R255 ; Turn LED red
  8102. * M150 R255 U127 ; Turn LED orange (PWM only)
  8103. * M150 ; Turn LED off
  8104. * M150 R U B ; Turn LED white
  8105. * M150 W ; Turn LED white using a white LED
  8106. * M150 P127 ; Set LED 50% brightness
  8107. * M150 P ; Set LED full brightness
  8108. */
  8109. inline void gcode_M150() {
  8110. leds.set_color(MakeLEDColor(
  8111. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  8112. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  8113. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  8114. parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  8115. parser.seen('P') ? (parser.has_value() ? parser.value_byte() : 255) : pixels.getBrightness()
  8116. ));
  8117. }
  8118. #endif // HAS_COLOR_LEDS
  8119. #if DISABLED(NO_VOLUMETRICS)
  8120. /**
  8121. * M200: Set filament diameter and set E axis units to cubic units
  8122. *
  8123. * T<extruder> - Optional extruder number. Current extruder if omitted.
  8124. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  8125. */
  8126. inline void gcode_M200() {
  8127. if (get_target_extruder_from_command(200)) return;
  8128. if (parser.seen('D')) {
  8129. // setting any extruder filament size disables volumetric on the assumption that
  8130. // slicers either generate in extruder values as cubic mm or as as filament feeds
  8131. // for all extruders
  8132. if ( (parser.volumetric_enabled = (parser.value_linear_units() != 0)) )
  8133. planner.set_filament_size(target_extruder, parser.value_linear_units());
  8134. }
  8135. planner.calculate_volumetric_multipliers();
  8136. }
  8137. #endif // !NO_VOLUMETRICS
  8138. /**
  8139. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  8140. *
  8141. * With multiple extruders use T to specify which one.
  8142. */
  8143. inline void gcode_M201() {
  8144. GET_TARGET_EXTRUDER(201);
  8145. LOOP_NUM_AXIS(i) {
  8146. if (parser.seen(RAW_AXIS_CODES(i))) {
  8147. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  8148. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  8149. }
  8150. }
  8151. // 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)
  8152. planner.reset_acceleration_rates();
  8153. }
  8154. #if 0 // Not used for Sprinter/grbl gen6
  8155. inline void gcode_M202() {
  8156. LOOP_XYZE(i) {
  8157. if (parser.seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = parser.value_axis_units((AxisEnum)i) * planner.axis_steps_per_mm[i];
  8158. }
  8159. }
  8160. #endif
  8161. /**
  8162. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  8163. *
  8164. * With multiple extruders use T to specify which one.
  8165. */
  8166. inline void gcode_M203() {
  8167. GET_TARGET_EXTRUDER(203);
  8168. LOOP_NUM_AXIS(i)
  8169. if (parser.seen(RAW_AXIS_CODES(i))) {
  8170. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  8171. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  8172. }
  8173. }
  8174. /**
  8175. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  8176. *
  8177. * P = Printing moves
  8178. * R = Retract only (no X, Y, Z) moves
  8179. * T = Travel (non printing) moves
  8180. */
  8181. inline void gcode_M204() {
  8182. bool report = true;
  8183. if (parser.seenval('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  8184. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  8185. report = false;
  8186. }
  8187. if (parser.seenval('P')) {
  8188. planner.acceleration = parser.value_linear_units();
  8189. report = false;
  8190. }
  8191. if (parser.seenval('R')) {
  8192. planner.retract_acceleration = parser.value_linear_units();
  8193. report = false;
  8194. }
  8195. if (parser.seenval('T')) {
  8196. planner.travel_acceleration = parser.value_linear_units();
  8197. report = false;
  8198. }
  8199. if (report) {
  8200. SERIAL_ECHOPAIR("Acceleration: P", planner.acceleration);
  8201. SERIAL_ECHOPAIR(" R", planner.retract_acceleration);
  8202. SERIAL_ECHOLNPAIR(" T", planner.travel_acceleration);
  8203. }
  8204. }
  8205. /**
  8206. * M205: Set Advanced Settings
  8207. *
  8208. * Q = Min Segment Time (µs)
  8209. * S = Min Feed Rate (units/s)
  8210. * T = Min Travel Feed Rate (units/s)
  8211. * X = Max X Jerk (units/sec^2)
  8212. * Y = Max Y Jerk (units/sec^2)
  8213. * Z = Max Z Jerk (units/sec^2)
  8214. * E = Max E Jerk (units/sec^2)
  8215. * J = Junction Deviation (mm) (Requires JUNCTION_DEVIATION)
  8216. */
  8217. inline void gcode_M205() {
  8218. if (parser.seen('Q')) planner.min_segment_time_us = parser.value_ulong();
  8219. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  8220. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  8221. #if ENABLED(JUNCTION_DEVIATION)
  8222. if (parser.seen('J')) {
  8223. const float junc_dev = parser.value_linear_units();
  8224. if (WITHIN(junc_dev, 0.01f, 0.3f)) {
  8225. planner.junction_deviation_mm = junc_dev;
  8226. planner.recalculate_max_e_jerk();
  8227. }
  8228. else {
  8229. SERIAL_ERROR_START();
  8230. SERIAL_ERRORLNPGM("?J out of range (0.01 to 0.3)");
  8231. }
  8232. }
  8233. #else
  8234. #if ENABLED(HANGPRINTER)
  8235. if (parser.seen('A')) planner.max_jerk[A_AXIS] = parser.value_linear_units();
  8236. if (parser.seen('B')) planner.max_jerk[B_AXIS] = parser.value_linear_units();
  8237. if (parser.seen('C')) planner.max_jerk[C_AXIS] = parser.value_linear_units();
  8238. if (parser.seen('D')) planner.max_jerk[D_AXIS] = parser.value_linear_units();
  8239. #else
  8240. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  8241. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  8242. if (parser.seen('Z')) {
  8243. planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  8244. #if HAS_MESH
  8245. if (planner.max_jerk[Z_AXIS] <= 0.1f)
  8246. SERIAL_ECHOLNPGM("WARNING! Low Z Jerk may lead to unwanted pauses.");
  8247. #endif
  8248. }
  8249. #endif
  8250. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  8251. #endif
  8252. }
  8253. #if HAS_M206_COMMAND
  8254. /**
  8255. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  8256. *
  8257. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  8258. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  8259. * *** In the next 1.2 release, it will simply be disabled by default.
  8260. */
  8261. inline void gcode_M206() {
  8262. LOOP_XYZ(i)
  8263. if (parser.seen(axis_codes[i]))
  8264. set_home_offset((AxisEnum)i, parser.value_linear_units());
  8265. #if ENABLED(MORGAN_SCARA)
  8266. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_float()); // Theta
  8267. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_float()); // Psi
  8268. #endif
  8269. report_current_position();
  8270. }
  8271. #endif // HAS_M206_COMMAND
  8272. #if ENABLED(DELTA)
  8273. /**
  8274. * M665: Set delta configurations
  8275. *
  8276. * H = delta height
  8277. * L = diagonal rod
  8278. * R = delta radius
  8279. * S = segments per second
  8280. * B = delta calibration radius
  8281. * X = Alpha (Tower 1) angle trim
  8282. * Y = Beta (Tower 2) angle trim
  8283. * Z = Gamma (Tower 3) angle trim
  8284. */
  8285. inline void gcode_M665() {
  8286. if (parser.seen('H')) delta_height = parser.value_linear_units();
  8287. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  8288. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  8289. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8290. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  8291. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  8292. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  8293. if (parser.seen('Z')) delta_tower_angle_trim[C_AXIS] = parser.value_float();
  8294. recalc_delta_settings();
  8295. }
  8296. /**
  8297. * M666: Set delta endstop adjustment
  8298. */
  8299. inline void gcode_M666() {
  8300. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8301. if (DEBUGGING(LEVELING)) {
  8302. SERIAL_ECHOLNPGM(">>> gcode_M666");
  8303. }
  8304. #endif
  8305. LOOP_XYZ(i) {
  8306. if (parser.seen(axis_codes[i])) {
  8307. if (parser.value_linear_units() * Z_HOME_DIR <= 0)
  8308. delta_endstop_adj[i] = parser.value_linear_units();
  8309. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8310. if (DEBUGGING(LEVELING)) {
  8311. SERIAL_ECHOPAIR("delta_endstop_adj[", axis_codes[i]);
  8312. SERIAL_ECHOLNPAIR("] = ", delta_endstop_adj[i]);
  8313. }
  8314. #endif
  8315. }
  8316. }
  8317. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8318. if (DEBUGGING(LEVELING)) {
  8319. SERIAL_ECHOLNPGM("<<< gcode_M666");
  8320. }
  8321. #endif
  8322. }
  8323. #elif IS_SCARA
  8324. /**
  8325. * M665: Set SCARA settings
  8326. *
  8327. * Parameters:
  8328. *
  8329. * S[segments-per-second] - Segments-per-second
  8330. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  8331. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  8332. *
  8333. * A, P, and X are all aliases for the shoulder angle
  8334. * B, T, and Y are all aliases for the elbow angle
  8335. */
  8336. inline void gcode_M665() {
  8337. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8338. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  8339. const uint8_t sumAPX = hasA + hasP + hasX;
  8340. if (sumAPX == 1)
  8341. home_offset[A_AXIS] = parser.value_float();
  8342. else if (sumAPX > 1) {
  8343. SERIAL_ERROR_START();
  8344. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  8345. return;
  8346. }
  8347. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  8348. const uint8_t sumBTY = hasB + hasT + hasY;
  8349. if (sumBTY == 1)
  8350. home_offset[B_AXIS] = parser.value_float();
  8351. else if (sumBTY > 1) {
  8352. SERIAL_ERROR_START();
  8353. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  8354. return;
  8355. }
  8356. }
  8357. #elif ENABLED(HANGPRINTER)
  8358. /**
  8359. * M665: Set HANGPRINTER settings
  8360. *
  8361. * Parameters:
  8362. *
  8363. * W[anchor_A_y] - A-anchor's y coordinate (see note)
  8364. * E[anchor_A_z] - A-anchor's z coordinate (see note)
  8365. * R[anchor_B_x] - B-anchor's x coordinate (see note)
  8366. * T[anchor_B_y] - B-anchor's y coordinate (see note)
  8367. * Y[anchor_B_z] - B-anchor's z coordinate (see note)
  8368. * U[anchor_C_x] - C-anchor's x coordinate (see note)
  8369. * I[anchor_C_y] - C-anchor's y coordinate (see note)
  8370. * O[anchor_C_z] - C-anchor's z coordinate (see note)
  8371. * P[anchor_D_z] - D-anchor's z coordinate (see note)
  8372. * S[segments-per-second] - Segments-per-second
  8373. *
  8374. * Note: All xyz coordinates are measured relative to the line's pivot point in the mover,
  8375. * when it is at its home position (nozzle in (0,0,0), and lines tight).
  8376. * The y-axis is defined to be horizontal right above/below the A-lines when mover is at home.
  8377. * The z-axis is along the vertical direction.
  8378. */
  8379. inline void gcode_M665() {
  8380. if (parser.seen('W')) anchor_A_y = parser.value_float();
  8381. if (parser.seen('E')) anchor_A_z = parser.value_float();
  8382. if (parser.seen('R')) anchor_B_x = parser.value_float();
  8383. if (parser.seen('T')) anchor_B_y = parser.value_float();
  8384. if (parser.seen('Y')) anchor_B_z = parser.value_float();
  8385. if (parser.seen('U')) anchor_C_x = parser.value_float();
  8386. if (parser.seen('I')) anchor_C_y = parser.value_float();
  8387. if (parser.seen('O')) anchor_C_z = parser.value_float();
  8388. if (parser.seen('P')) anchor_D_z = parser.value_float();
  8389. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  8390. recalc_hangprinter_settings();
  8391. }
  8392. #elif ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  8393. /**
  8394. * M666: Set Dual Endstops offsets for X, Y, and/or Z.
  8395. * With no parameters report current offsets.
  8396. */
  8397. inline void gcode_M666() {
  8398. bool report = true;
  8399. #if ENABLED(X_DUAL_ENDSTOPS)
  8400. if (parser.seenval('X')) {
  8401. endstops.x_endstop_adj = parser.value_linear_units();
  8402. report = false;
  8403. }
  8404. #endif
  8405. #if ENABLED(Y_DUAL_ENDSTOPS)
  8406. if (parser.seenval('Y')) {
  8407. endstops.y_endstop_adj = parser.value_linear_units();
  8408. report = false;
  8409. }
  8410. #endif
  8411. #if ENABLED(Z_DUAL_ENDSTOPS)
  8412. if (parser.seenval('Z')) {
  8413. endstops.z_endstop_adj = parser.value_linear_units();
  8414. report = false;
  8415. }
  8416. #endif
  8417. if (report) {
  8418. SERIAL_ECHOPGM("Dual Endstop Adjustment (mm): ");
  8419. #if ENABLED(X_DUAL_ENDSTOPS)
  8420. SERIAL_ECHOPAIR(" X", endstops.x_endstop_adj);
  8421. #endif
  8422. #if ENABLED(Y_DUAL_ENDSTOPS)
  8423. SERIAL_ECHOPAIR(" Y", endstops.y_endstop_adj);
  8424. #endif
  8425. #if ENABLED(Z_DUAL_ENDSTOPS)
  8426. SERIAL_ECHOPAIR(" Z", endstops.z_endstop_adj);
  8427. #endif
  8428. SERIAL_EOL();
  8429. }
  8430. }
  8431. #endif // X_DUAL_ENDSTOPS || Y_DUAL_ENDSTOPS || Z_DUAL_ENDSTOPS
  8432. #if ENABLED(FWRETRACT)
  8433. /**
  8434. * M207: Set firmware retraction values
  8435. *
  8436. * S[+units] retract_length
  8437. * W[+units] swap_retract_length (multi-extruder)
  8438. * F[units/min] retract_feedrate_mm_s
  8439. * Z[units] retract_zlift
  8440. */
  8441. inline void gcode_M207() {
  8442. if (parser.seen('S')) fwretract.retract_length = parser.value_axis_units(E_AXIS);
  8443. if (parser.seen('F')) fwretract.retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8444. if (parser.seen('Z')) fwretract.retract_zlift = parser.value_linear_units();
  8445. if (parser.seen('W')) fwretract.swap_retract_length = parser.value_axis_units(E_AXIS);
  8446. }
  8447. /**
  8448. * M208: Set firmware un-retraction values
  8449. *
  8450. * S[+units] retract_recover_length (in addition to M207 S*)
  8451. * W[+units] swap_retract_recover_length (multi-extruder)
  8452. * F[units/min] retract_recover_feedrate_mm_s
  8453. * R[units/min] swap_retract_recover_feedrate_mm_s
  8454. */
  8455. inline void gcode_M208() {
  8456. if (parser.seen('S')) fwretract.retract_recover_length = parser.value_axis_units(E_AXIS);
  8457. if (parser.seen('F')) fwretract.retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8458. if (parser.seen('R')) fwretract.swap_retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  8459. if (parser.seen('W')) fwretract.swap_retract_recover_length = parser.value_axis_units(E_AXIS);
  8460. }
  8461. /**
  8462. * M209: Enable automatic retract (M209 S1)
  8463. * For slicers that don't support G10/11, reversed extrude-only
  8464. * moves will be classified as retraction.
  8465. */
  8466. inline void gcode_M209() {
  8467. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) {
  8468. if (parser.seen('S')) {
  8469. fwretract.autoretract_enabled = parser.value_bool();
  8470. for (uint8_t i = 0; i < EXTRUDERS; i++) fwretract.retracted[i] = false;
  8471. }
  8472. }
  8473. }
  8474. #endif // FWRETRACT
  8475. /**
  8476. * M211: Enable, Disable, and/or Report software endstops
  8477. *
  8478. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  8479. */
  8480. inline void gcode_M211() {
  8481. SERIAL_ECHO_START();
  8482. #if HAS_SOFTWARE_ENDSTOPS
  8483. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  8484. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8485. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  8486. #else
  8487. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  8488. SERIAL_ECHOPGM(MSG_OFF);
  8489. #endif
  8490. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  8491. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_min[X_AXIS]));
  8492. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_min[Y_AXIS]));
  8493. SERIAL_ECHOPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_min[Z_AXIS]));
  8494. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  8495. SERIAL_ECHOPAIR( MSG_X, LOGICAL_X_POSITION(soft_endstop_max[X_AXIS]));
  8496. SERIAL_ECHOPAIR(" " MSG_Y, LOGICAL_Y_POSITION(soft_endstop_max[Y_AXIS]));
  8497. SERIAL_ECHOLNPAIR(" " MSG_Z, LOGICAL_Z_POSITION(soft_endstop_max[Z_AXIS]));
  8498. }
  8499. #if HOTENDS > 1
  8500. /**
  8501. * M218 - Set/get hotend offset (in linear units)
  8502. *
  8503. * T<tool>
  8504. * X<xoffset>
  8505. * Y<yoffset>
  8506. * Z<zoffset> - Available with DUAL_X_CARRIAGE, SWITCHING_NOZZLE, and PARKING_EXTRUDER
  8507. */
  8508. inline void gcode_M218() {
  8509. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  8510. bool report = true;
  8511. if (parser.seenval('X')) {
  8512. hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  8513. report = false;
  8514. }
  8515. if (parser.seenval('Y')) {
  8516. hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  8517. report = false;
  8518. }
  8519. #if HAS_HOTEND_OFFSET_Z
  8520. if (parser.seenval('Z')) {
  8521. hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  8522. report = false;
  8523. }
  8524. #endif
  8525. if (report) {
  8526. SERIAL_ECHO_START();
  8527. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  8528. HOTEND_LOOP() {
  8529. SERIAL_CHAR(' ');
  8530. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  8531. SERIAL_CHAR(',');
  8532. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  8533. #if HAS_HOTEND_OFFSET_Z
  8534. SERIAL_CHAR(',');
  8535. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  8536. #endif
  8537. }
  8538. SERIAL_EOL();
  8539. }
  8540. #if ENABLED(DELTA)
  8541. if (target_extruder == active_extruder)
  8542. do_blocking_move_to_xy(current_position[X_AXIS], current_position[Y_AXIS], planner.max_feedrate_mm_s[X_AXIS]);
  8543. #endif
  8544. }
  8545. #endif // HOTENDS > 1
  8546. /**
  8547. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  8548. */
  8549. inline void gcode_M220() {
  8550. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  8551. }
  8552. /**
  8553. * M221: Set extrusion percentage (M221 T0 S95)
  8554. */
  8555. inline void gcode_M221() {
  8556. if (get_target_extruder_from_command(221)) return;
  8557. if (parser.seenval('S')) {
  8558. planner.flow_percentage[target_extruder] = parser.value_int();
  8559. planner.refresh_e_factor(target_extruder);
  8560. }
  8561. else {
  8562. SERIAL_ECHO_START();
  8563. SERIAL_CHAR('E');
  8564. SERIAL_CHAR('0' + target_extruder);
  8565. SERIAL_ECHOPAIR(" Flow: ", planner.flow_percentage[target_extruder]);
  8566. SERIAL_CHAR('%');
  8567. SERIAL_EOL();
  8568. }
  8569. }
  8570. /**
  8571. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  8572. */
  8573. inline void gcode_M226() {
  8574. if (parser.seen('P')) {
  8575. const int pin = parser.value_int(), pin_state = parser.intval('S', -1);
  8576. if (WITHIN(pin_state, -1, 1) && pin > -1) {
  8577. if (pin_is_protected(pin))
  8578. protected_pin_err();
  8579. else {
  8580. int target = LOW;
  8581. planner.synchronize();
  8582. pinMode(pin, INPUT);
  8583. switch (pin_state) {
  8584. case 1: target = HIGH; break;
  8585. case 0: target = LOW; break;
  8586. case -1: target = !digitalRead(pin); break;
  8587. }
  8588. while (digitalRead(pin) != target) idle();
  8589. }
  8590. } // pin_state -1 0 1 && pin > -1
  8591. } // parser.seen('P')
  8592. }
  8593. #if ENABLED(EXPERIMENTAL_I2CBUS)
  8594. /**
  8595. * M260: Send data to a I2C slave device
  8596. *
  8597. * This is a PoC, the formating and arguments for the GCODE will
  8598. * change to be more compatible, the current proposal is:
  8599. *
  8600. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  8601. *
  8602. * M260 B<byte-1 value in base 10>
  8603. * M260 B<byte-2 value in base 10>
  8604. * M260 B<byte-3 value in base 10>
  8605. *
  8606. * M260 S1 ; Send the buffered data and reset the buffer
  8607. * M260 R1 ; Reset the buffer without sending data
  8608. *
  8609. */
  8610. inline void gcode_M260() {
  8611. // Set the target address
  8612. if (parser.seen('A')) i2c.address(parser.value_byte());
  8613. // Add a new byte to the buffer
  8614. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  8615. // Flush the buffer to the bus
  8616. if (parser.seen('S')) i2c.send();
  8617. // Reset and rewind the buffer
  8618. else if (parser.seen('R')) i2c.reset();
  8619. }
  8620. /**
  8621. * M261: Request X bytes from I2C slave device
  8622. *
  8623. * Usage: M261 A<slave device address base 10> B<number of bytes>
  8624. */
  8625. inline void gcode_M261() {
  8626. if (parser.seen('A')) i2c.address(parser.value_byte());
  8627. uint8_t bytes = parser.byteval('B', 1);
  8628. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  8629. i2c.relay(bytes);
  8630. }
  8631. else {
  8632. SERIAL_ERROR_START();
  8633. SERIAL_ERRORLNPGM("Bad i2c request");
  8634. }
  8635. }
  8636. #endif // EXPERIMENTAL_I2CBUS
  8637. #if HAS_SERVOS
  8638. /**
  8639. * M280: Get or set servo position. P<index> [S<angle>]
  8640. */
  8641. inline void gcode_M280() {
  8642. if (!parser.seen('P')) return;
  8643. const int servo_index = parser.value_int();
  8644. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  8645. if (parser.seen('S'))
  8646. MOVE_SERVO(servo_index, parser.value_int());
  8647. else {
  8648. SERIAL_ECHO_START();
  8649. SERIAL_ECHOPAIR(" Servo ", servo_index);
  8650. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  8651. }
  8652. }
  8653. else {
  8654. SERIAL_ERROR_START();
  8655. SERIAL_ECHOPAIR("Servo ", servo_index);
  8656. SERIAL_ECHOLNPGM(" out of range");
  8657. }
  8658. }
  8659. #endif // HAS_SERVOS
  8660. #if ENABLED(BABYSTEPPING)
  8661. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8662. FORCE_INLINE void mod_zprobe_zoffset(const float &offs) {
  8663. zprobe_zoffset += offs;
  8664. SERIAL_ECHO_START();
  8665. SERIAL_ECHOLNPAIR(MSG_PROBE_Z_OFFSET ": ", zprobe_zoffset);
  8666. }
  8667. #endif
  8668. /**
  8669. * M290: Babystepping
  8670. */
  8671. inline void gcode_M290() {
  8672. #if ENABLED(BABYSTEP_XY)
  8673. for (uint8_t a = X_AXIS; a <= Z_AXIS; a++)
  8674. if (parser.seenval(axis_codes[a]) || (a == Z_AXIS && parser.seenval('S'))) {
  8675. const float offs = constrain(parser.value_axis_units((AxisEnum)a), -2, 2);
  8676. thermalManager.babystep_axis((AxisEnum)a, offs * planner.axis_steps_per_mm[a]);
  8677. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8678. if (a == Z_AXIS && (!parser.seen('P') || parser.value_bool())) mod_zprobe_zoffset(offs);
  8679. #endif
  8680. }
  8681. #else
  8682. if (parser.seenval('Z') || parser.seenval('S')) {
  8683. const float offs = constrain(parser.value_axis_units(Z_AXIS), -2, 2);
  8684. thermalManager.babystep_axis(Z_AXIS, offs * planner.axis_steps_per_mm[Z_AXIS]);
  8685. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  8686. if (!parser.seen('P') || parser.value_bool()) mod_zprobe_zoffset(offs);
  8687. #endif
  8688. }
  8689. #endif
  8690. }
  8691. #endif // BABYSTEPPING
  8692. #if HAS_BUZZER
  8693. /**
  8694. * M300: Play beep sound S<frequency Hz> P<duration ms>
  8695. */
  8696. inline void gcode_M300() {
  8697. uint16_t const frequency = parser.ushortval('S', 260);
  8698. uint16_t duration = parser.ushortval('P', 1000);
  8699. // Limits the tone duration to 0-5 seconds.
  8700. NOMORE(duration, 5000);
  8701. BUZZ(duration, frequency);
  8702. }
  8703. #endif // HAS_BUZZER
  8704. #if ENABLED(PIDTEMP)
  8705. /**
  8706. * M301: Set PID parameters P I D (and optionally C, L)
  8707. *
  8708. * P[float] Kp term
  8709. * I[float] Ki term (unscaled)
  8710. * D[float] Kd term (unscaled)
  8711. *
  8712. * With PID_EXTRUSION_SCALING:
  8713. *
  8714. * C[float] Kc term
  8715. * L[int] LPQ length
  8716. */
  8717. inline void gcode_M301() {
  8718. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  8719. // default behaviour (omitting E parameter) is to update for extruder 0 only
  8720. const uint8_t e = parser.byteval('E'); // extruder being updated
  8721. if (e < HOTENDS) { // catch bad input value
  8722. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  8723. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  8724. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  8725. #if ENABLED(PID_EXTRUSION_SCALING)
  8726. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  8727. if (parser.seen('L')) thermalManager.lpq_len = parser.value_float();
  8728. NOMORE(thermalManager.lpq_len, LPQ_MAX_LEN);
  8729. NOLESS(thermalManager.lpq_len, 0);
  8730. #endif
  8731. thermalManager.update_pid();
  8732. SERIAL_ECHO_START();
  8733. #if ENABLED(PID_PARAMS_PER_HOTEND)
  8734. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  8735. #endif // PID_PARAMS_PER_HOTEND
  8736. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  8737. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  8738. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  8739. #if ENABLED(PID_EXTRUSION_SCALING)
  8740. //Kc does not have scaling applied above, or in resetting defaults
  8741. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  8742. #endif
  8743. SERIAL_EOL();
  8744. }
  8745. else {
  8746. SERIAL_ERROR_START();
  8747. SERIAL_ERRORLNPGM(MSG_INVALID_EXTRUDER);
  8748. }
  8749. }
  8750. #endif // PIDTEMP
  8751. #if ENABLED(PIDTEMPBED)
  8752. inline void gcode_M304() {
  8753. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  8754. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  8755. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  8756. SERIAL_ECHO_START();
  8757. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  8758. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  8759. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  8760. }
  8761. #endif // PIDTEMPBED
  8762. #if defined(CHDK) || HAS_PHOTOGRAPH
  8763. /**
  8764. * M240: Trigger a camera by emulating a Canon RC-1
  8765. * See http://www.doc-diy.net/photo/rc-1_hacked/
  8766. */
  8767. inline void gcode_M240() {
  8768. #ifdef CHDK
  8769. OUT_WRITE(CHDK, HIGH);
  8770. chdkHigh = millis();
  8771. chdkActive = true;
  8772. #elif HAS_PHOTOGRAPH
  8773. const uint8_t NUM_PULSES = 16;
  8774. const float PULSE_LENGTH = 0.01524;
  8775. for (int i = 0; i < NUM_PULSES; i++) {
  8776. WRITE(PHOTOGRAPH_PIN, HIGH);
  8777. _delay_ms(PULSE_LENGTH);
  8778. WRITE(PHOTOGRAPH_PIN, LOW);
  8779. _delay_ms(PULSE_LENGTH);
  8780. }
  8781. delay(7.33);
  8782. for (int i = 0; i < NUM_PULSES; i++) {
  8783. WRITE(PHOTOGRAPH_PIN, HIGH);
  8784. _delay_ms(PULSE_LENGTH);
  8785. WRITE(PHOTOGRAPH_PIN, LOW);
  8786. _delay_ms(PULSE_LENGTH);
  8787. }
  8788. #endif // !CHDK && HAS_PHOTOGRAPH
  8789. }
  8790. #endif // CHDK || PHOTOGRAPH_PIN
  8791. #if HAS_LCD_CONTRAST
  8792. /**
  8793. * M250: Read and optionally set the LCD contrast
  8794. */
  8795. inline void gcode_M250() {
  8796. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  8797. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  8798. SERIAL_PROTOCOL(lcd_contrast);
  8799. SERIAL_EOL();
  8800. }
  8801. #endif // HAS_LCD_CONTRAST
  8802. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8803. /**
  8804. * M302: Allow cold extrudes, or set the minimum extrude temperature
  8805. *
  8806. * S<temperature> sets the minimum extrude temperature
  8807. * P<bool> enables (1) or disables (0) cold extrusion
  8808. *
  8809. * Examples:
  8810. *
  8811. * M302 ; report current cold extrusion state
  8812. * M302 P0 ; enable cold extrusion checking
  8813. * M302 P1 ; disables cold extrusion checking
  8814. * M302 S0 ; always allow extrusion (disables checking)
  8815. * M302 S170 ; only allow extrusion above 170
  8816. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  8817. */
  8818. inline void gcode_M302() {
  8819. const bool seen_S = parser.seen('S');
  8820. if (seen_S) {
  8821. thermalManager.extrude_min_temp = parser.value_celsius();
  8822. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  8823. }
  8824. if (parser.seen('P'))
  8825. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  8826. else if (!seen_S) {
  8827. // Report current state
  8828. SERIAL_ECHO_START();
  8829. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  8830. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  8831. SERIAL_ECHOLNPGM("C)");
  8832. }
  8833. }
  8834. #endif // PREVENT_COLD_EXTRUSION
  8835. /**
  8836. * M303: PID relay autotune
  8837. *
  8838. * S<temperature> sets the target temperature. (default 150C / 70C)
  8839. * E<extruder> (-1 for the bed) (default 0)
  8840. * C<cycles>
  8841. * U<bool> with a non-zero value will apply the result to current settings
  8842. */
  8843. inline void gcode_M303() {
  8844. #if HAS_PID_HEATING
  8845. const int e = parser.intval('E'), c = parser.intval('C', 5);
  8846. const bool u = parser.boolval('U');
  8847. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  8848. if (WITHIN(e, 0, HOTENDS - 1))
  8849. target_extruder = e;
  8850. #if DISABLED(BUSY_WHILE_HEATING)
  8851. KEEPALIVE_STATE(NOT_BUSY);
  8852. #endif
  8853. thermalManager.pid_autotune(temp, e, c, u);
  8854. #if DISABLED(BUSY_WHILE_HEATING)
  8855. KEEPALIVE_STATE(IN_HANDLER);
  8856. #endif
  8857. #else
  8858. SERIAL_ERROR_START();
  8859. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  8860. #endif
  8861. }
  8862. #if ENABLED(MORGAN_SCARA)
  8863. bool SCARA_move_to_cal(const uint8_t delta_a, const uint8_t delta_b) {
  8864. if (IsRunning()) {
  8865. forward_kinematics_SCARA(delta_a, delta_b);
  8866. destination[X_AXIS] = cartes[X_AXIS];
  8867. destination[Y_AXIS] = cartes[Y_AXIS];
  8868. destination[Z_AXIS] = current_position[Z_AXIS];
  8869. prepare_move_to_destination();
  8870. return true;
  8871. }
  8872. return false;
  8873. }
  8874. /**
  8875. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  8876. */
  8877. inline bool gcode_M360() {
  8878. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  8879. return SCARA_move_to_cal(0, 120);
  8880. }
  8881. /**
  8882. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  8883. */
  8884. inline bool gcode_M361() {
  8885. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  8886. return SCARA_move_to_cal(90, 130);
  8887. }
  8888. /**
  8889. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  8890. */
  8891. inline bool gcode_M362() {
  8892. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  8893. return SCARA_move_to_cal(60, 180);
  8894. }
  8895. /**
  8896. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  8897. */
  8898. inline bool gcode_M363() {
  8899. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  8900. return SCARA_move_to_cal(50, 90);
  8901. }
  8902. /**
  8903. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  8904. */
  8905. inline bool gcode_M364() {
  8906. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  8907. return SCARA_move_to_cal(45, 135);
  8908. }
  8909. #endif // SCARA
  8910. #if ENABLED(EXT_SOLENOID)
  8911. void enable_solenoid(const uint8_t num) {
  8912. switch (num) {
  8913. case 0:
  8914. OUT_WRITE(SOL0_PIN, HIGH);
  8915. break;
  8916. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8917. case 1:
  8918. OUT_WRITE(SOL1_PIN, HIGH);
  8919. break;
  8920. #endif
  8921. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8922. case 2:
  8923. OUT_WRITE(SOL2_PIN, HIGH);
  8924. break;
  8925. #endif
  8926. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8927. case 3:
  8928. OUT_WRITE(SOL3_PIN, HIGH);
  8929. break;
  8930. #endif
  8931. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8932. case 4:
  8933. OUT_WRITE(SOL4_PIN, HIGH);
  8934. break;
  8935. #endif
  8936. default:
  8937. SERIAL_ECHO_START();
  8938. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  8939. break;
  8940. }
  8941. }
  8942. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  8943. void disable_all_solenoids() {
  8944. OUT_WRITE(SOL0_PIN, LOW);
  8945. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  8946. OUT_WRITE(SOL1_PIN, LOW);
  8947. #endif
  8948. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  8949. OUT_WRITE(SOL2_PIN, LOW);
  8950. #endif
  8951. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  8952. OUT_WRITE(SOL3_PIN, LOW);
  8953. #endif
  8954. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  8955. OUT_WRITE(SOL4_PIN, LOW);
  8956. #endif
  8957. }
  8958. /**
  8959. * M380: Enable solenoid on the active extruder
  8960. */
  8961. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  8962. /**
  8963. * M381: Disable all solenoids
  8964. */
  8965. inline void gcode_M381() { disable_all_solenoids(); }
  8966. #endif // EXT_SOLENOID
  8967. /**
  8968. * M400: Finish all moves
  8969. */
  8970. inline void gcode_M400() { planner.synchronize(); }
  8971. #if HAS_BED_PROBE
  8972. /**
  8973. * M401: Deploy and activate the Z probe
  8974. */
  8975. inline void gcode_M401() {
  8976. DEPLOY_PROBE();
  8977. report_current_position();
  8978. }
  8979. /**
  8980. * M402: Deactivate and stow the Z probe
  8981. */
  8982. inline void gcode_M402() {
  8983. STOW_PROBE();
  8984. #ifdef Z_AFTER_PROBING
  8985. move_z_after_probing();
  8986. #endif
  8987. report_current_position();
  8988. }
  8989. #endif // HAS_BED_PROBE
  8990. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  8991. /**
  8992. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  8993. */
  8994. inline void gcode_M404() {
  8995. if (parser.seen('W')) {
  8996. filament_width_nominal = parser.value_linear_units();
  8997. planner.volumetric_area_nominal = CIRCLE_AREA(filament_width_nominal * 0.5);
  8998. }
  8999. else {
  9000. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  9001. SERIAL_PROTOCOLLN(filament_width_nominal);
  9002. }
  9003. }
  9004. /**
  9005. * M405: Turn on filament sensor for control
  9006. */
  9007. inline void gcode_M405() {
  9008. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  9009. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  9010. if (parser.seen('D')) {
  9011. meas_delay_cm = parser.value_byte();
  9012. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  9013. }
  9014. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  9015. const int8_t temp_ratio = thermalManager.widthFil_to_size_ratio();
  9016. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  9017. measurement_delay[i] = temp_ratio;
  9018. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  9019. }
  9020. filament_sensor = true;
  9021. }
  9022. /**
  9023. * M406: Turn off filament sensor for control
  9024. */
  9025. inline void gcode_M406() {
  9026. filament_sensor = false;
  9027. planner.calculate_volumetric_multipliers(); // Restore correct 'volumetric_multiplier' value
  9028. }
  9029. /**
  9030. * M407: Get measured filament diameter on serial output
  9031. */
  9032. inline void gcode_M407() {
  9033. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  9034. SERIAL_PROTOCOLLN(filament_width_meas);
  9035. }
  9036. #endif // FILAMENT_WIDTH_SENSOR
  9037. void quickstop_stepper() {
  9038. planner.quick_stop();
  9039. planner.synchronize();
  9040. set_current_from_steppers_for_axis(ALL_AXES);
  9041. SYNC_PLAN_POSITION_KINEMATIC();
  9042. }
  9043. #if HAS_LEVELING
  9044. //#define M420_C_USE_MEAN
  9045. /**
  9046. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  9047. *
  9048. * S[bool] Turns leveling on or off
  9049. * Z[height] Sets the Z fade height (0 or none to disable)
  9050. * V[bool] Verbose - Print the leveling grid
  9051. *
  9052. * With AUTO_BED_LEVELING_UBL only:
  9053. *
  9054. * L[index] Load UBL mesh from index (0 is default)
  9055. * T[map] 0:Human-readable 1:CSV 2:"LCD" 4:Compact
  9056. *
  9057. * With mesh-based leveling only:
  9058. *
  9059. * C Center mesh on the mean of the lowest and highest
  9060. */
  9061. inline void gcode_M420() {
  9062. const bool seen_S = parser.seen('S');
  9063. bool to_enable = seen_S ? parser.value_bool() : planner.leveling_active;
  9064. // If disabling leveling do it right away
  9065. // (Don't disable for just M420 or M420 V)
  9066. if (seen_S && !to_enable) set_bed_leveling_enabled(false);
  9067. const float oldpos[] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  9068. #if ENABLED(AUTO_BED_LEVELING_UBL)
  9069. // L to load a mesh from the EEPROM
  9070. if (parser.seen('L')) {
  9071. set_bed_leveling_enabled(false);
  9072. #if ENABLED(EEPROM_SETTINGS)
  9073. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.storage_slot;
  9074. const int16_t a = settings.calc_num_meshes();
  9075. if (!a) {
  9076. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  9077. return;
  9078. }
  9079. if (!WITHIN(storage_slot, 0, a - 1)) {
  9080. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  9081. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  9082. return;
  9083. }
  9084. settings.load_mesh(storage_slot);
  9085. ubl.storage_slot = storage_slot;
  9086. #else
  9087. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  9088. return;
  9089. #endif
  9090. }
  9091. // L or V display the map info
  9092. if (parser.seen('L') || parser.seen('V')) {
  9093. ubl.display_map(parser.byteval('T'));
  9094. SERIAL_ECHOPGM("Mesh is ");
  9095. if (!ubl.mesh_is_valid()) SERIAL_ECHOPGM("in");
  9096. SERIAL_ECHOLNPAIR("valid\nStorage slot: ", ubl.storage_slot);
  9097. }
  9098. #endif // AUTO_BED_LEVELING_UBL
  9099. #if HAS_MESH
  9100. #if ENABLED(MESH_BED_LEVELING)
  9101. #define Z_VALUES(X,Y) mbl.z_values[X][Y]
  9102. #else
  9103. #define Z_VALUES(X,Y) z_values[X][Y]
  9104. #endif
  9105. // Subtract the given value or the mean from all mesh values
  9106. if (leveling_is_valid() && parser.seen('C')) {
  9107. const float cval = parser.value_float();
  9108. #if ENABLED(AUTO_BED_LEVELING_UBL)
  9109. set_bed_leveling_enabled(false);
  9110. ubl.adjust_mesh_to_mean(true, cval);
  9111. #else
  9112. #if ENABLED(M420_C_USE_MEAN)
  9113. // Get the sum and average of all mesh values
  9114. float mesh_sum = 0;
  9115. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  9116. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  9117. mesh_sum += Z_VALUES(x, y);
  9118. const float zmean = mesh_sum / float(GRID_MAX_POINTS);
  9119. #else
  9120. // Find the low and high mesh values
  9121. float lo_val = 100, hi_val = -100;
  9122. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  9123. for (uint8_t y = GRID_MAX_POINTS_Y; y--;) {
  9124. const float z = Z_VALUES(x, y);
  9125. NOMORE(lo_val, z);
  9126. NOLESS(hi_val, z);
  9127. }
  9128. // Take the mean of the lowest and highest
  9129. const float zmean = (lo_val + hi_val) / 2.0 + cval;
  9130. #endif
  9131. // If not very close to 0, adjust the mesh
  9132. if (!NEAR_ZERO(zmean)) {
  9133. set_bed_leveling_enabled(false);
  9134. // Subtract the mean from all values
  9135. for (uint8_t x = GRID_MAX_POINTS_X; x--;)
  9136. for (uint8_t y = GRID_MAX_POINTS_Y; y--;)
  9137. Z_VALUES(x, y) -= zmean;
  9138. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9139. bed_level_virt_interpolate();
  9140. #endif
  9141. }
  9142. #endif
  9143. }
  9144. #endif // HAS_MESH
  9145. // V to print the matrix or mesh
  9146. if (parser.seen('V')) {
  9147. #if ABL_PLANAR
  9148. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  9149. #else
  9150. if (leveling_is_valid()) {
  9151. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9152. print_bilinear_leveling_grid();
  9153. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9154. print_bilinear_leveling_grid_virt();
  9155. #endif
  9156. #elif ENABLED(MESH_BED_LEVELING)
  9157. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  9158. mbl.report_mesh();
  9159. #endif
  9160. }
  9161. #endif
  9162. }
  9163. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  9164. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units(), false);
  9165. #endif
  9166. // Enable leveling if specified, or if previously active
  9167. set_bed_leveling_enabled(to_enable);
  9168. // Error if leveling failed to enable or reenable
  9169. if (to_enable && !planner.leveling_active) {
  9170. SERIAL_ERROR_START();
  9171. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  9172. }
  9173. SERIAL_ECHO_START();
  9174. SERIAL_ECHOLNPAIR("Bed Leveling ", planner.leveling_active ? MSG_ON : MSG_OFF);
  9175. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  9176. SERIAL_ECHO_START();
  9177. SERIAL_ECHOPGM("Fade Height ");
  9178. if (planner.z_fade_height > 0.0)
  9179. SERIAL_ECHOLN(planner.z_fade_height);
  9180. else
  9181. SERIAL_ECHOLNPGM(MSG_OFF);
  9182. #endif
  9183. // Report change in position
  9184. if (memcmp(oldpos, current_position, sizeof(oldpos)))
  9185. report_current_position();
  9186. }
  9187. #endif // HAS_LEVELING
  9188. #if ENABLED(MESH_BED_LEVELING)
  9189. /**
  9190. * M421: Set a single Mesh Bed Leveling Z coordinate
  9191. *
  9192. * Usage:
  9193. * M421 X<linear> Y<linear> Z<linear>
  9194. * M421 X<linear> Y<linear> Q<offset>
  9195. * M421 I<xindex> J<yindex> Z<linear>
  9196. * M421 I<xindex> J<yindex> Q<offset>
  9197. */
  9198. inline void gcode_M421() {
  9199. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  9200. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(parser.value_linear_units()) : -1;
  9201. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  9202. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(parser.value_linear_units()) : -1;
  9203. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  9204. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  9205. SERIAL_ERROR_START();
  9206. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9207. }
  9208. else if (ix < 0 || iy < 0) {
  9209. SERIAL_ERROR_START();
  9210. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9211. }
  9212. else
  9213. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  9214. }
  9215. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9216. /**
  9217. * M421: Set a single Mesh Bed Leveling Z coordinate
  9218. *
  9219. * Usage:
  9220. * M421 I<xindex> J<yindex> Z<linear>
  9221. * M421 I<xindex> J<yindex> Q<offset>
  9222. */
  9223. inline void gcode_M421() {
  9224. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9225. const bool hasI = ix >= 0,
  9226. hasJ = iy >= 0,
  9227. hasZ = parser.seen('Z'),
  9228. hasQ = !hasZ && parser.seen('Q');
  9229. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  9230. SERIAL_ERROR_START();
  9231. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9232. }
  9233. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9234. SERIAL_ERROR_START();
  9235. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9236. }
  9237. else {
  9238. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  9239. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9240. bed_level_virt_interpolate();
  9241. #endif
  9242. }
  9243. }
  9244. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  9245. /**
  9246. * M421: Set a single Mesh Bed Leveling Z coordinate
  9247. *
  9248. * Usage:
  9249. * M421 I<xindex> J<yindex> Z<linear>
  9250. * M421 I<xindex> J<yindex> Q<offset>
  9251. * M421 I<xindex> J<yindex> N
  9252. * M421 C Z<linear>
  9253. * M421 C Q<offset>
  9254. */
  9255. inline void gcode_M421() {
  9256. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  9257. const bool hasI = ix >= 0,
  9258. hasJ = iy >= 0,
  9259. hasC = parser.seen('C'),
  9260. hasN = parser.seen('N'),
  9261. hasZ = parser.seen('Z'),
  9262. hasQ = !hasZ && parser.seen('Q');
  9263. if (hasC) {
  9264. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL);
  9265. ix = location.x_index;
  9266. iy = location.y_index;
  9267. }
  9268. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ || hasN)) {
  9269. SERIAL_ERROR_START();
  9270. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  9271. }
  9272. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  9273. SERIAL_ERROR_START();
  9274. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  9275. }
  9276. else
  9277. ubl.z_values[ix][iy] = hasN ? NAN : parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  9278. }
  9279. #endif // AUTO_BED_LEVELING_UBL
  9280. #if HAS_M206_COMMAND
  9281. /**
  9282. * M428: Set home_offset based on the distance between the
  9283. * current_position and the nearest "reference point."
  9284. * If an axis is past center its endstop position
  9285. * is the reference-point. Otherwise it uses 0. This allows
  9286. * the Z offset to be set near the bed when using a max endstop.
  9287. *
  9288. * M428 can't be used more than 2cm away from 0 or an endstop.
  9289. *
  9290. * Use M206 to set these values directly.
  9291. */
  9292. inline void gcode_M428() {
  9293. if (axis_unhomed_error()) return;
  9294. float diff[XYZ];
  9295. LOOP_XYZ(i) {
  9296. diff[i] = base_home_pos((AxisEnum)i) - current_position[i];
  9297. if (!WITHIN(diff[i], -20, 20) && home_dir((AxisEnum)i) > 0)
  9298. diff[i] = -current_position[i];
  9299. if (!WITHIN(diff[i], -20, 20)) {
  9300. SERIAL_ERROR_START();
  9301. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  9302. LCD_ALERTMESSAGEPGM("Err: Too far!");
  9303. BUZZ(200, 40);
  9304. return;
  9305. }
  9306. }
  9307. LOOP_XYZ(i) set_home_offset((AxisEnum)i, diff[i]);
  9308. report_current_position();
  9309. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  9310. BUZZ(100, 659);
  9311. BUZZ(100, 698);
  9312. }
  9313. #endif // HAS_M206_COMMAND
  9314. /**
  9315. * M500: Store settings in EEPROM
  9316. */
  9317. inline void gcode_M500() {
  9318. (void)settings.save();
  9319. }
  9320. /**
  9321. * M501: Read settings from EEPROM
  9322. */
  9323. inline void gcode_M501() {
  9324. (void)settings.load();
  9325. }
  9326. /**
  9327. * M502: Revert to default settings
  9328. */
  9329. inline void gcode_M502() {
  9330. (void)settings.reset();
  9331. }
  9332. #if DISABLED(DISABLE_M503)
  9333. /**
  9334. * M503: print settings currently in memory
  9335. */
  9336. inline void gcode_M503() {
  9337. (void)settings.report(parser.seen('S') && !parser.value_bool());
  9338. }
  9339. #endif
  9340. #if ENABLED(EEPROM_SETTINGS)
  9341. /**
  9342. * M504: Validate EEPROM Contents
  9343. */
  9344. inline void gcode_M504() {
  9345. if (settings.validate()) {
  9346. SERIAL_ECHO_START();
  9347. SERIAL_ECHOLNPGM("EEPROM OK");
  9348. }
  9349. }
  9350. #endif
  9351. #if ENABLED(SDSUPPORT)
  9352. /**
  9353. * M524: Abort the current SD print job (started with M24)
  9354. */
  9355. inline void gcode_M524() {
  9356. if (IS_SD_PRINTING()) card.abort_sd_printing = true;
  9357. }
  9358. #endif // SDSUPPORT
  9359. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9360. /**
  9361. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  9362. */
  9363. inline void gcode_M540() {
  9364. if (parser.seen('S')) planner.abort_on_endstop_hit = parser.value_bool();
  9365. }
  9366. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  9367. #if HAS_BED_PROBE
  9368. inline void gcode_M851() {
  9369. if (parser.seenval('Z')) {
  9370. const float value = parser.value_linear_units();
  9371. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX))
  9372. zprobe_zoffset = value;
  9373. else {
  9374. SERIAL_ERROR_START();
  9375. SERIAL_ERRORLNPGM("?Z out of range (" STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " to " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX) ")");
  9376. }
  9377. return;
  9378. }
  9379. SERIAL_ECHO_START();
  9380. SERIAL_ECHOPGM(MSG_PROBE_Z_OFFSET);
  9381. SERIAL_ECHOLNPAIR(": ", zprobe_zoffset);
  9382. }
  9383. #endif // HAS_BED_PROBE
  9384. #if ENABLED(SKEW_CORRECTION_GCODE)
  9385. /**
  9386. * M852: Get or set the machine skew factors. Reports current values with no arguments.
  9387. *
  9388. * S[xy_factor] - Alias for 'I'
  9389. * I[xy_factor] - New XY skew factor
  9390. * J[xz_factor] - New XZ skew factor
  9391. * K[yz_factor] - New YZ skew factor
  9392. */
  9393. inline void gcode_M852() {
  9394. uint8_t ijk = 0, badval = 0, setval = 0;
  9395. if (parser.seen('I') || parser.seen('S')) {
  9396. ++ijk;
  9397. const float value = parser.value_linear_units();
  9398. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9399. if (planner.xy_skew_factor != value) {
  9400. planner.xy_skew_factor = value;
  9401. ++setval;
  9402. }
  9403. }
  9404. else
  9405. ++badval;
  9406. }
  9407. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9408. if (parser.seen('J')) {
  9409. ++ijk;
  9410. const float value = parser.value_linear_units();
  9411. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9412. if (planner.xz_skew_factor != value) {
  9413. planner.xz_skew_factor = value;
  9414. ++setval;
  9415. }
  9416. }
  9417. else
  9418. ++badval;
  9419. }
  9420. if (parser.seen('K')) {
  9421. ++ijk;
  9422. const float value = parser.value_linear_units();
  9423. if (WITHIN(value, SKEW_FACTOR_MIN, SKEW_FACTOR_MAX)) {
  9424. if (planner.yz_skew_factor != value) {
  9425. planner.yz_skew_factor = value;
  9426. ++setval;
  9427. }
  9428. }
  9429. else
  9430. ++badval;
  9431. }
  9432. #endif
  9433. if (badval)
  9434. SERIAL_ECHOLNPGM(MSG_SKEW_MIN " " STRINGIFY(SKEW_FACTOR_MIN) " " MSG_SKEW_MAX " " STRINGIFY(SKEW_FACTOR_MAX));
  9435. // When skew is changed the current position changes
  9436. if (setval) {
  9437. set_current_from_steppers_for_axis(ALL_AXES);
  9438. SYNC_PLAN_POSITION_KINEMATIC();
  9439. report_current_position();
  9440. }
  9441. if (!ijk) {
  9442. SERIAL_ECHO_START();
  9443. SERIAL_ECHOPGM(MSG_SKEW_FACTOR " XY: ");
  9444. SERIAL_ECHO_F(planner.xy_skew_factor, 6);
  9445. SERIAL_EOL();
  9446. #if ENABLED(SKEW_CORRECTION_FOR_Z)
  9447. SERIAL_ECHOPAIR(" XZ: ", planner.xz_skew_factor);
  9448. SERIAL_ECHOLNPAIR(" YZ: ", planner.yz_skew_factor);
  9449. #else
  9450. SERIAL_EOL();
  9451. #endif
  9452. }
  9453. }
  9454. #endif // SKEW_CORRECTION_GCODE
  9455. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9456. /**
  9457. * M600: Pause for filament change
  9458. *
  9459. * E[distance] - Retract the filament this far
  9460. * Z[distance] - Move the Z axis by this distance
  9461. * X[position] - Move to this X position, with Y
  9462. * Y[position] - Move to this Y position, with X
  9463. * U[distance] - Retract distance for removal (manual reload)
  9464. * L[distance] - Extrude distance for insertion (manual reload)
  9465. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  9466. * T[toolhead] - Select extruder for filament change
  9467. *
  9468. * Default values are used for omitted arguments.
  9469. */
  9470. inline void gcode_M600() {
  9471. point_t park_point = NOZZLE_PARK_POINT;
  9472. if (get_target_extruder_from_command(600)) return;
  9473. // Show initial message
  9474. #if ENABLED(ULTIPANEL)
  9475. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT, ADVANCED_PAUSE_MODE_PAUSE_PRINT, target_extruder);
  9476. #endif
  9477. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  9478. // Don't allow filament change without homing first
  9479. if (axis_unhomed_error()) home_all_axes();
  9480. #endif
  9481. #if EXTRUDERS > 1
  9482. // Change toolhead if specified
  9483. uint8_t active_extruder_before_filament_change = active_extruder;
  9484. if (active_extruder != target_extruder)
  9485. tool_change(target_extruder, 0, true);
  9486. #endif
  9487. // Initial retract before move to filament change position
  9488. const float retract = -ABS(parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  9489. #ifdef PAUSE_PARK_RETRACT_LENGTH
  9490. + (PAUSE_PARK_RETRACT_LENGTH)
  9491. #endif
  9492. );
  9493. // Lift Z axis
  9494. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9495. // Move XY axes to filament change position or given position
  9496. if (parser.seenval('X')) park_point.x = parser.linearval('X');
  9497. if (parser.seenval('Y')) park_point.y = parser.linearval('Y');
  9498. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE) && DISABLED(DELTA)
  9499. park_point.x += (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0);
  9500. park_point.y += (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0);
  9501. #endif
  9502. // Unload filament
  9503. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9504. filament_change_unload_length[active_extruder]);
  9505. // Slow load filament
  9506. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9507. // Fast load filament
  9508. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) :
  9509. filament_change_load_length[active_extruder]);
  9510. const int beep_count = parser.intval('B',
  9511. #ifdef FILAMENT_CHANGE_ALERT_BEEPS
  9512. FILAMENT_CHANGE_ALERT_BEEPS
  9513. #else
  9514. -1
  9515. #endif
  9516. );
  9517. const bool job_running = print_job_timer.isRunning();
  9518. if (pause_print(retract, park_point, unload_length, true)) {
  9519. wait_for_filament_reload(beep_count);
  9520. resume_print(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, beep_count);
  9521. }
  9522. #if EXTRUDERS > 1
  9523. // Restore toolhead if it was changed
  9524. if (active_extruder_before_filament_change != active_extruder)
  9525. tool_change(active_extruder_before_filament_change, 0, true);
  9526. #endif
  9527. // Resume the print job timer if it was running
  9528. if (job_running) print_job_timer.start();
  9529. }
  9530. /**
  9531. * M603: Configure filament change
  9532. *
  9533. * T[toolhead] - Select extruder to configure, active extruder if not specified
  9534. * U[distance] - Retract distance for removal, for the specified extruder
  9535. * L[distance] - Extrude distance for insertion, for the specified extruder
  9536. *
  9537. */
  9538. inline void gcode_M603() {
  9539. if (get_target_extruder_from_command(603)) return;
  9540. // Unload length
  9541. if (parser.seen('U')) {
  9542. filament_change_unload_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9543. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9544. NOMORE(filament_change_unload_length[target_extruder], EXTRUDE_MAXLENGTH);
  9545. #endif
  9546. }
  9547. // Load length
  9548. if (parser.seen('L')) {
  9549. filament_change_load_length[target_extruder] = ABS(parser.value_axis_units(E_AXIS));
  9550. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9551. NOMORE(filament_change_load_length[target_extruder], EXTRUDE_MAXLENGTH);
  9552. #endif
  9553. }
  9554. }
  9555. #endif // ADVANCED_PAUSE_FEATURE
  9556. #if ENABLED(MK2_MULTIPLEXER)
  9557. inline void select_multiplexed_stepper(const uint8_t e) {
  9558. planner.synchronize();
  9559. disable_e_steppers();
  9560. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  9561. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  9562. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  9563. safe_delay(100);
  9564. }
  9565. #endif // MK2_MULTIPLEXER
  9566. #if ENABLED(DUAL_X_CARRIAGE)
  9567. /**
  9568. * M605: Set dual x-carriage movement mode
  9569. *
  9570. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  9571. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  9572. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  9573. * units x-offset and an optional differential hotend temperature of
  9574. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  9575. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  9576. *
  9577. * Note: the X axis should be homed after changing dual x-carriage mode.
  9578. */
  9579. inline void gcode_M605() {
  9580. planner.synchronize();
  9581. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  9582. switch (dual_x_carriage_mode) {
  9583. case DXC_FULL_CONTROL_MODE:
  9584. case DXC_AUTO_PARK_MODE:
  9585. break;
  9586. case DXC_DUPLICATION_MODE:
  9587. if (parser.seen('X')) duplicate_extruder_x_offset = MAX(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  9588. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  9589. SERIAL_ECHO_START();
  9590. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  9591. SERIAL_CHAR(' ');
  9592. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  9593. SERIAL_CHAR(',');
  9594. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  9595. SERIAL_CHAR(' ');
  9596. SERIAL_ECHO(duplicate_extruder_x_offset);
  9597. SERIAL_CHAR(',');
  9598. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  9599. break;
  9600. default:
  9601. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  9602. break;
  9603. }
  9604. active_extruder_parked = false;
  9605. extruder_duplication_enabled = false;
  9606. delayed_move_time = 0;
  9607. }
  9608. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9609. inline void gcode_M605() {
  9610. planner.synchronize();
  9611. extruder_duplication_enabled = parser.intval('S') == int(DXC_DUPLICATION_MODE);
  9612. SERIAL_ECHO_START();
  9613. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  9614. }
  9615. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  9616. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  9617. /**
  9618. * M701: Load filament
  9619. *
  9620. * T<extruder> - Optional extruder number. Current extruder if omitted.
  9621. * Z<distance> - Move the Z axis by this distance
  9622. * L<distance> - Extrude distance for insertion (positive value) (manual reload)
  9623. *
  9624. * Default values are used for omitted arguments.
  9625. */
  9626. inline void gcode_M701() {
  9627. point_t park_point = NOZZLE_PARK_POINT;
  9628. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9629. // Only raise Z if the machine is homed
  9630. if (axis_unhomed_error()) park_point.z = 0;
  9631. #endif
  9632. if (get_target_extruder_from_command(701)) return;
  9633. // Z axis lift
  9634. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9635. // Show initial "wait for load" message
  9636. #if ENABLED(ULTIPANEL)
  9637. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD, ADVANCED_PAUSE_MODE_LOAD_FILAMENT, target_extruder);
  9638. #endif
  9639. #if EXTRUDERS > 1
  9640. // Change toolhead if specified
  9641. uint8_t active_extruder_before_filament_change = active_extruder;
  9642. if (active_extruder != target_extruder)
  9643. tool_change(target_extruder, 0, true);
  9644. #endif
  9645. // Lift Z axis
  9646. if (park_point.z > 0)
  9647. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9648. constexpr float slow_load_length = FILAMENT_CHANGE_SLOW_LOAD_LENGTH;
  9649. const float fast_load_length = ABS(parser.seen('L') ? parser.value_axis_units(E_AXIS) : filament_change_load_length[active_extruder]);
  9650. load_filament(slow_load_length, fast_load_length, ADVANCED_PAUSE_PURGE_LENGTH, FILAMENT_CHANGE_ALERT_BEEPS,
  9651. true, thermalManager.wait_for_heating(target_extruder), ADVANCED_PAUSE_MODE_LOAD_FILAMENT);
  9652. // Restore Z axis
  9653. if (park_point.z > 0)
  9654. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9655. #if EXTRUDERS > 1
  9656. // Restore toolhead if it was changed
  9657. if (active_extruder_before_filament_change != active_extruder)
  9658. tool_change(active_extruder_before_filament_change, 0, true);
  9659. #endif
  9660. // Show status screen
  9661. #if ENABLED(ULTIPANEL)
  9662. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9663. #endif
  9664. }
  9665. /**
  9666. * M702: Unload filament
  9667. *
  9668. * T<extruder> - Optional extruder number. If omitted, current extruder
  9669. * (or ALL extruders with FILAMENT_UNLOAD_ALL_EXTRUDERS).
  9670. * Z<distance> - Move the Z axis by this distance
  9671. * U<distance> - Retract distance for removal (manual reload)
  9672. *
  9673. * Default values are used for omitted arguments.
  9674. */
  9675. inline void gcode_M702() {
  9676. point_t park_point = NOZZLE_PARK_POINT;
  9677. #if ENABLED(NO_MOTION_BEFORE_HOMING)
  9678. // Only raise Z if the machine is homed
  9679. if (axis_unhomed_error()) park_point.z = 0;
  9680. #endif
  9681. if (get_target_extruder_from_command(702)) return;
  9682. // Z axis lift
  9683. if (parser.seenval('Z')) park_point.z = parser.linearval('Z');
  9684. // Show initial message
  9685. #if ENABLED(ULTIPANEL)
  9686. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT, target_extruder);
  9687. #endif
  9688. #if EXTRUDERS > 1
  9689. // Change toolhead if specified
  9690. uint8_t active_extruder_before_filament_change = active_extruder;
  9691. if (active_extruder != target_extruder)
  9692. tool_change(target_extruder, 0, true);
  9693. #endif
  9694. // Lift Z axis
  9695. if (park_point.z > 0)
  9696. do_blocking_move_to_z(MIN(current_position[Z_AXIS] + park_point.z, Z_MAX_POS), NOZZLE_PARK_Z_FEEDRATE);
  9697. // Unload filament
  9698. #if EXTRUDERS > 1 && ENABLED(FILAMENT_UNLOAD_ALL_EXTRUDERS)
  9699. if (!parser.seenval('T')) {
  9700. HOTEND_LOOP() {
  9701. if (e != active_extruder) tool_change(e, 0, true);
  9702. unload_filament(-filament_change_unload_length[e], true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9703. }
  9704. }
  9705. else
  9706. #endif
  9707. {
  9708. // Unload length
  9709. const float unload_length = -ABS(parser.seen('U') ? parser.value_axis_units(E_AXIS) :
  9710. filament_change_unload_length[target_extruder]);
  9711. unload_filament(unload_length, true, ADVANCED_PAUSE_MODE_UNLOAD_FILAMENT);
  9712. }
  9713. // Restore Z axis
  9714. if (park_point.z > 0)
  9715. do_blocking_move_to_z(MAX(current_position[Z_AXIS] - park_point.z, 0), NOZZLE_PARK_Z_FEEDRATE);
  9716. #if EXTRUDERS > 1
  9717. // Restore toolhead if it was changed
  9718. if (active_extruder_before_filament_change != active_extruder)
  9719. tool_change(active_extruder_before_filament_change, 0, true);
  9720. #endif
  9721. // Show status screen
  9722. #if ENABLED(ULTIPANEL)
  9723. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  9724. #endif
  9725. }
  9726. #endif // FILAMENT_LOAD_UNLOAD_GCODES
  9727. #if ENABLED(MAX7219_GCODE)
  9728. /**
  9729. * M7219: Control the Max7219 LED matrix
  9730. *
  9731. * I - Initialize (clear) the matrix
  9732. * F - Fill the matrix (set all bits)
  9733. * P - Dump the LEDs[] array values
  9734. * C<column> - Set a column to the 8-bit value V
  9735. * R<row> - Set a row to the 8-bit value V
  9736. * X<pos> - X position of an LED to set or toggle
  9737. * Y<pos> - Y position of an LED to set or toggle
  9738. * V<value> - The potentially 32-bit value or on/off state to set
  9739. * (for example: a chain of 4 Max7219 devices can have 32 bit
  9740. * rows or columns depending upon rotation)
  9741. */
  9742. inline void gcode_M7219() {
  9743. if (parser.seen('I')) {
  9744. max7219.register_setup();
  9745. max7219.clear();
  9746. }
  9747. if (parser.seen('F')) max7219.fill();
  9748. const uint32_t v = parser.ulongval('V');
  9749. if (parser.seenval('R')) {
  9750. const uint8_t r = parser.value_byte();
  9751. max7219.set_row(r, v);
  9752. }
  9753. else if (parser.seenval('C')) {
  9754. const uint8_t c = parser.value_byte();
  9755. max7219.set_column(c, v);
  9756. }
  9757. else if (parser.seenval('X') || parser.seenval('Y')) {
  9758. const uint8_t x = parser.byteval('X'), y = parser.byteval('Y');
  9759. if (parser.seenval('V'))
  9760. max7219.led_set(x, y, parser.boolval('V'));
  9761. else
  9762. max7219.led_toggle(x, y);
  9763. }
  9764. else if (parser.seen('D')) {
  9765. const uint8_t line = parser.byteval('D') + (parser.byteval('U') << 3);
  9766. if (line < MAX7219_LINES) {
  9767. max7219.led_line[line] = v;
  9768. return max7219.refresh_line(line);
  9769. }
  9770. }
  9771. if (parser.seen('P')) {
  9772. for (uint8_t r = 0; r < MAX7219_LINES; r++) {
  9773. SERIAL_ECHOPGM("led_line[");
  9774. if (r < 10) SERIAL_CHAR(' ');
  9775. SERIAL_ECHO(int(r));
  9776. SERIAL_ECHOPGM("]=");
  9777. for (uint8_t b = 8; b--;) SERIAL_CHAR('0' + TEST(max7219.led_line[r], b));
  9778. SERIAL_EOL();
  9779. }
  9780. }
  9781. }
  9782. #endif // MAX7219_GCODE
  9783. #if ENABLED(LIN_ADVANCE)
  9784. /**
  9785. * M900: Get or Set Linear Advance K-factor
  9786. *
  9787. * K<factor> Set advance K factor
  9788. */
  9789. inline void gcode_M900() {
  9790. if (parser.seenval('K')) {
  9791. const float newK = parser.floatval('K');
  9792. if (WITHIN(newK, 0, 10)) {
  9793. planner.synchronize();
  9794. planner.extruder_advance_K = newK;
  9795. }
  9796. else
  9797. SERIAL_PROTOCOLLNPGM("?K value out of range (0-10).");
  9798. }
  9799. else {
  9800. SERIAL_ECHO_START();
  9801. SERIAL_ECHOLNPAIR("Advance K=", planner.extruder_advance_K);
  9802. }
  9803. }
  9804. #endif // LIN_ADVANCE
  9805. #if HAS_TRINAMIC
  9806. #if ENABLED(TMC_DEBUG)
  9807. inline void gcode_M122() {
  9808. if (parser.seen('S'))
  9809. tmc_set_report_status(parser.value_bool());
  9810. else
  9811. tmc_report_all();
  9812. }
  9813. #endif // TMC_DEBUG
  9814. /**
  9815. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9816. * Uses axis codes A, B, C, D, E for Hangprinter
  9817. * Report driver currents when no axis specified
  9818. */
  9819. inline void gcode_M906() {
  9820. #define TMC_SAY_CURRENT(Q) tmc_get_current(stepper##Q, TMC_##Q)
  9821. #define TMC_SET_CURRENT(Q) tmc_set_current(stepper##Q, value)
  9822. bool report = true;
  9823. const uint8_t index = parser.byteval('I');
  9824. LOOP_NUM_AXIS(i) if (uint16_t value = parser.intval(RAW_AXIS_CODES(i))) {
  9825. report = false;
  9826. switch (i) {
  9827. // Assumes {A_AXIS, B_AXIS, C_AXIS} == {X_AXIS, Y_AXIS, Z_AXIS}
  9828. case X_AXIS:
  9829. #if AXIS_IS_TMC(X)
  9830. if (index < 2) TMC_SET_CURRENT(X);
  9831. #endif
  9832. #if AXIS_IS_TMC(X2)
  9833. if (!(index & 1)) TMC_SET_CURRENT(X2);
  9834. #endif
  9835. break;
  9836. case Y_AXIS:
  9837. #if AXIS_IS_TMC(Y)
  9838. if (index < 2) TMC_SET_CURRENT(Y);
  9839. #endif
  9840. #if AXIS_IS_TMC(Y2)
  9841. if (!(index & 1)) TMC_SET_CURRENT(Y2);
  9842. #endif
  9843. break;
  9844. case Z_AXIS:
  9845. #if AXIS_IS_TMC(Z)
  9846. if (index < 2) TMC_SET_CURRENT(Z);
  9847. #endif
  9848. #if AXIS_IS_TMC(Z2)
  9849. if (!(index & 1)) TMC_SET_CURRENT(Z2);
  9850. #endif
  9851. break;
  9852. case E_AXIS: {
  9853. if (get_target_extruder_from_command(906)) return;
  9854. switch (target_extruder) {
  9855. #if AXIS_IS_TMC(E0)
  9856. case 0: TMC_SET_CURRENT(E0); break;
  9857. #endif
  9858. #if ENABLED(HANGPRINTER)
  9859. // Avoid setting the D-current
  9860. #if AXIS_IS_TMC(E1) && EXTRUDERS > 1
  9861. case 1: TMC_SET_CURRENT(E1); break;
  9862. #endif
  9863. #if AXIS_IS_TMC(E2) && EXTRUDERS > 2
  9864. case 2: TMC_SET_CURRENT(E2); break;
  9865. #endif
  9866. #if AXIS_IS_TMC(E3) && EXTRUDERS > 3
  9867. case 3: TMC_SET_CURRENT(E3); break;
  9868. #endif
  9869. #if AXIS_IS_TMC(E4) && EXTRUDERS > 4
  9870. case 4: TMC_SET_CURRENT(E4); break;
  9871. #endif
  9872. #else
  9873. #if AXIS_IS_TMC(E1)
  9874. case 1: TMC_SET_CURRENT(E1); break;
  9875. #endif
  9876. #if AXIS_IS_TMC(E2)
  9877. case 2: TMC_SET_CURRENT(E2); break;
  9878. #endif
  9879. #if AXIS_IS_TMC(E3)
  9880. case 3: TMC_SET_CURRENT(E3); break;
  9881. #endif
  9882. #if AXIS_IS_TMC(E4)
  9883. case 4: TMC_SET_CURRENT(E4); break;
  9884. #endif
  9885. #endif
  9886. }
  9887. } break;
  9888. #if ENABLED(HANGPRINTER)
  9889. case D_AXIS:
  9890. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9891. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9892. TMC_SET_CURRENT(E1); break;
  9893. #endif
  9894. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9895. TMC_SET_CURRENT(E2); break;
  9896. #endif
  9897. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9898. TMC_SET_CURRENT(E3); break;
  9899. #endif
  9900. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9901. TMC_SET_CURRENT(E4); break;
  9902. #endif
  9903. #endif
  9904. }
  9905. }
  9906. if (report) {
  9907. #if AXIS_IS_TMC(X)
  9908. TMC_SAY_CURRENT(X);
  9909. #endif
  9910. #if AXIS_IS_TMC(X2)
  9911. TMC_SAY_CURRENT(X2);
  9912. #endif
  9913. #if AXIS_IS_TMC(Y)
  9914. TMC_SAY_CURRENT(Y);
  9915. #endif
  9916. #if AXIS_IS_TMC(Y2)
  9917. TMC_SAY_CURRENT(Y2);
  9918. #endif
  9919. #if AXIS_IS_TMC(Z)
  9920. TMC_SAY_CURRENT(Z);
  9921. #endif
  9922. #if AXIS_IS_TMC(Z2)
  9923. TMC_SAY_CURRENT(Z2);
  9924. #endif
  9925. #if AXIS_IS_TMC(E0)
  9926. TMC_SAY_CURRENT(E0);
  9927. #endif
  9928. #if ENABLED(HANGPRINTER)
  9929. // D is connected on the first of E1, E2, E3, E4 output that is not an extruder
  9930. #if AXIS_IS_TMC(E1) && EXTRUDERS == 1
  9931. TMC_SAY_CURRENT(E1);
  9932. #endif
  9933. #if AXIS_IS_TMC(E2) && EXTRUDERS == 2
  9934. TMC_SAY_CURRENT(E2);
  9935. #endif
  9936. #if AXIS_IS_TMC(E3) && EXTRUDERS == 3
  9937. TMC_SAY_CURRENT(E3);
  9938. #endif
  9939. #if AXIS_IS_TMC(E4) && EXTRUDERS == 4
  9940. TMC_SAY_CURRENT(E4);
  9941. #endif
  9942. #else
  9943. #if AXIS_IS_TMC(E1)
  9944. TMC_SAY_CURRENT(E1);
  9945. #endif
  9946. #if AXIS_IS_TMC(E2)
  9947. TMC_SAY_CURRENT(E2);
  9948. #endif
  9949. #if AXIS_IS_TMC(E3)
  9950. TMC_SAY_CURRENT(E3);
  9951. #endif
  9952. #if AXIS_IS_TMC(E4)
  9953. TMC_SAY_CURRENT(E4);
  9954. #endif
  9955. #endif
  9956. }
  9957. }
  9958. #define M91x_USE(ST) (AXIS_DRIVER_TYPE(ST, TMC2130) || (AXIS_DRIVER_TYPE(ST, TMC2208) && PIN_EXISTS(ST##_SERIAL_RX)))
  9959. #define M91x_USE_E(N) (E_STEPPERS > N && M91x_USE(E##N))
  9960. /**
  9961. * M911: Report TMC stepper driver overtemperature pre-warn flag
  9962. * This flag is held by the library, persisting until cleared by M912
  9963. */
  9964. inline void gcode_M911() {
  9965. #if M91x_USE(X)
  9966. tmc_report_otpw(stepperX, TMC_X);
  9967. #endif
  9968. #if M91x_USE(X2)
  9969. tmc_report_otpw(stepperX2, TMC_X2);
  9970. #endif
  9971. #if M91x_USE(Y)
  9972. tmc_report_otpw(stepperY, TMC_Y);
  9973. #endif
  9974. #if M91x_USE(Y2)
  9975. tmc_report_otpw(stepperY2, TMC_Y2);
  9976. #endif
  9977. #if M91x_USE(Z)
  9978. tmc_report_otpw(stepperZ, TMC_Z);
  9979. #endif
  9980. #if M91x_USE(Z2)
  9981. tmc_report_otpw(stepperZ2, TMC_Z2);
  9982. #endif
  9983. #if M91x_USE_E(0)
  9984. tmc_report_otpw(stepperE0, TMC_E0);
  9985. #endif
  9986. #if M91x_USE_E(1)
  9987. tmc_report_otpw(stepperE1, TMC_E1);
  9988. #endif
  9989. #if M91x_USE_E(2)
  9990. tmc_report_otpw(stepperE2, TMC_E2);
  9991. #endif
  9992. #if M91x_USE_E(3)
  9993. tmc_report_otpw(stepperE3, TMC_E3);
  9994. #endif
  9995. #if M91x_USE_E(4)
  9996. tmc_report_otpw(stepperE4, TMC_E4);
  9997. #endif
  9998. }
  9999. /**
  10000. * M912: Clear TMC stepper driver overtemperature pre-warn flag held by the library
  10001. * Specify one or more axes with X, Y, Z, X1, Y1, Z1, X2, Y2, Z2, and E[index].
  10002. * If no axes are given, clear all.
  10003. *
  10004. * Examples:
  10005. * M912 X ; clear X and X2
  10006. * M912 X1 ; clear X1 only
  10007. * M912 X2 ; clear X2 only
  10008. * M912 X E ; clear X, X2, and all E
  10009. * M912 E1 ; clear E1 only
  10010. */
  10011. inline void gcode_M912() {
  10012. const bool hasX = parser.seen(axis_codes[X_AXIS]),
  10013. hasY = parser.seen(axis_codes[Y_AXIS]),
  10014. hasZ = parser.seen(axis_codes[Z_AXIS]),
  10015. hasE = parser.seen(axis_codes[E_CART]),
  10016. hasNone = !hasX && !hasY && !hasZ && !hasE;
  10017. #if M91x_USE(X) || M91x_USE(X2)
  10018. const uint8_t xval = parser.byteval(axis_codes[X_AXIS], 10);
  10019. #if M91x_USE(X)
  10020. if (hasNone || xval == 1 || (hasX && xval == 10)) tmc_clear_otpw(stepperX, TMC_X);
  10021. #endif
  10022. #if M91x_USE(X2)
  10023. if (hasNone || xval == 2 || (hasX && xval == 10)) tmc_clear_otpw(stepperX2, TMC_X2);
  10024. #endif
  10025. #endif
  10026. #if M91x_USE(Y) || M91x_USE(Y2)
  10027. const uint8_t yval = parser.byteval(axis_codes[Y_AXIS], 10);
  10028. #if M91x_USE(Y)
  10029. if (hasNone || yval == 1 || (hasY && yval == 10)) tmc_clear_otpw(stepperY, TMC_Y);
  10030. #endif
  10031. #if M91x_USE(Y2)
  10032. if (hasNone || yval == 2 || (hasY && yval == 10)) tmc_clear_otpw(stepperY2, TMC_Y2);
  10033. #endif
  10034. #endif
  10035. #if M91x_USE(Z) || M91x_USE(Z2)
  10036. const uint8_t zval = parser.byteval(axis_codes[Z_AXIS], 10);
  10037. #if M91x_USE(Z)
  10038. if (hasNone || zval == 1 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ, TMC_Z);
  10039. #endif
  10040. #if M91x_USE(Z2)
  10041. if (hasNone || zval == 2 || (hasZ && zval == 10)) tmc_clear_otpw(stepperZ2, TMC_Z2);
  10042. #endif
  10043. #endif
  10044. // TODO: If this is a Hangprinter, E_AXIS will not correspond to E0, E1, etc in this way
  10045. #if M91x_USE_E(0) || M91x_USE_E(1) || M91x_USE_E(2) || M91x_USE_E(3) || M91x_USE_E(4)
  10046. const uint8_t eval = parser.byteval(axis_codes[E_AXIS], 10);
  10047. #if M91x_USE_E(0)
  10048. if (hasNone || eval == 0 || (hasE && eval == 10)) tmc_clear_otpw(stepperE0, TMC_E0);
  10049. #endif
  10050. #if M91x_USE_E(1)
  10051. if (hasNone || eval == 1 || (hasE && eval == 10)) tmc_clear_otpw(stepperE1, TMC_E1);
  10052. #endif
  10053. #if M91x_USE_E(2)
  10054. if (hasNone || eval == 2 || (hasE && eval == 10)) tmc_clear_otpw(stepperE2, TMC_E2);
  10055. #endif
  10056. #if M91x_USE_E(3)
  10057. if (hasNone || eval == 3 || (hasE && eval == 10)) tmc_clear_otpw(stepperE3, TMC_E3);
  10058. #endif
  10059. #if M91x_USE_E(4)
  10060. if (hasNone || eval == 4 || (hasE && eval == 10)) tmc_clear_otpw(stepperE4, TMC_E4);
  10061. #endif
  10062. #endif
  10063. }
  10064. /**
  10065. * M913: Set HYBRID_THRESHOLD speed.
  10066. */
  10067. #if ENABLED(HYBRID_THRESHOLD)
  10068. inline void gcode_M913() {
  10069. #define TMC_SAY_PWMTHRS(A,Q) tmc_get_pwmthrs(stepper##Q, TMC_##Q, planner.axis_steps_per_mm[_AXIS(A)])
  10070. #define TMC_SET_PWMTHRS(A,Q) tmc_set_pwmthrs(stepper##Q, value, planner.axis_steps_per_mm[_AXIS(A)])
  10071. #define TMC_SAY_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_get_pwmthrs(stepperE##E, TMC_E##E, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  10072. #define TMC_SET_PWMTHRS_E(E) do{ const uint8_t extruder = E; tmc_set_pwmthrs(stepperE##E, value, planner.axis_steps_per_mm[E_AXIS_N]); }while(0)
  10073. bool report = true;
  10074. const uint8_t index = parser.byteval('I');
  10075. LOOP_XYZE(i) if (int32_t value = parser.longval(axis_codes[i])) {
  10076. report = false;
  10077. switch (i) {
  10078. case X_AXIS:
  10079. #if AXIS_HAS_STEALTHCHOP(X)
  10080. if (index < 2) TMC_SET_PWMTHRS(X,X);
  10081. #endif
  10082. #if AXIS_HAS_STEALTHCHOP(X2)
  10083. if (!(index & 1)) TMC_SET_PWMTHRS(X,X2);
  10084. #endif
  10085. break;
  10086. case Y_AXIS:
  10087. #if AXIS_HAS_STEALTHCHOP(Y)
  10088. if (index < 2) TMC_SET_PWMTHRS(Y,Y);
  10089. #endif
  10090. #if AXIS_HAS_STEALTHCHOP(Y2)
  10091. if (!(index & 1)) TMC_SET_PWMTHRS(Y,Y2);
  10092. #endif
  10093. break;
  10094. case Z_AXIS:
  10095. #if AXIS_HAS_STEALTHCHOP(Z)
  10096. if (index < 2) TMC_SET_PWMTHRS(Z,Z);
  10097. #endif
  10098. #if AXIS_HAS_STEALTHCHOP(Z2)
  10099. if (!(index & 1)) TMC_SET_PWMTHRS(Z,Z2);
  10100. #endif
  10101. break;
  10102. case E_CART: {
  10103. if (get_target_extruder_from_command(913)) return;
  10104. switch (target_extruder) {
  10105. #if AXIS_HAS_STEALTHCHOP(E0)
  10106. case 0: TMC_SET_PWMTHRS_E(0); break;
  10107. #endif
  10108. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  10109. case 1: TMC_SET_PWMTHRS_E(1); break;
  10110. #endif
  10111. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  10112. case 2: TMC_SET_PWMTHRS_E(2); break;
  10113. #endif
  10114. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  10115. case 3: TMC_SET_PWMTHRS_E(3); break;
  10116. #endif
  10117. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  10118. case 4: TMC_SET_PWMTHRS_E(4); break;
  10119. #endif
  10120. }
  10121. } break;
  10122. }
  10123. }
  10124. if (report) {
  10125. #if AXIS_HAS_STEALTHCHOP(X)
  10126. TMC_SAY_PWMTHRS(X,X);
  10127. #endif
  10128. #if AXIS_HAS_STEALTHCHOP(X2)
  10129. TMC_SAY_PWMTHRS(X,X2);
  10130. #endif
  10131. #if AXIS_HAS_STEALTHCHOP(Y)
  10132. TMC_SAY_PWMTHRS(Y,Y);
  10133. #endif
  10134. #if AXIS_HAS_STEALTHCHOP(Y2)
  10135. TMC_SAY_PWMTHRS(Y,Y2);
  10136. #endif
  10137. #if AXIS_HAS_STEALTHCHOP(Z)
  10138. TMC_SAY_PWMTHRS(Z,Z);
  10139. #endif
  10140. #if AXIS_HAS_STEALTHCHOP(Z2)
  10141. TMC_SAY_PWMTHRS(Z,Z2);
  10142. #endif
  10143. #if AXIS_HAS_STEALTHCHOP(E0)
  10144. TMC_SAY_PWMTHRS_E(0);
  10145. #endif
  10146. #if E_STEPPERS > 1 && AXIS_HAS_STEALTHCHOP(E1)
  10147. TMC_SAY_PWMTHRS_E(1);
  10148. #endif
  10149. #if E_STEPPERS > 2 && AXIS_HAS_STEALTHCHOP(E2)
  10150. TMC_SAY_PWMTHRS_E(2);
  10151. #endif
  10152. #if E_STEPPERS > 3 && AXIS_HAS_STEALTHCHOP(E3)
  10153. TMC_SAY_PWMTHRS_E(3);
  10154. #endif
  10155. #if E_STEPPERS > 4 && AXIS_HAS_STEALTHCHOP(E4)
  10156. TMC_SAY_PWMTHRS_E(4);
  10157. #endif
  10158. }
  10159. }
  10160. #endif // HYBRID_THRESHOLD
  10161. /**
  10162. * M914: Set SENSORLESS_HOMING sensitivity.
  10163. */
  10164. #if ENABLED(SENSORLESS_HOMING)
  10165. inline void gcode_M914() {
  10166. #define TMC_SAY_SGT(Q) tmc_get_sgt(stepper##Q, TMC_##Q)
  10167. #define TMC_SET_SGT(Q) tmc_set_sgt(stepper##Q, value)
  10168. bool report = true;
  10169. const uint8_t index = parser.byteval('I');
  10170. LOOP_XYZ(i) if (parser.seen(axis_codes[i])) {
  10171. const int8_t value = (int8_t)constrain(parser.value_int(), -64, 63);
  10172. report = false;
  10173. switch (i) {
  10174. #if X_SENSORLESS
  10175. case X_AXIS:
  10176. #if AXIS_HAS_STALLGUARD(X)
  10177. if (index < 2) TMC_SET_SGT(X);
  10178. #endif
  10179. #if AXIS_HAS_STALLGUARD(X2)
  10180. if (!(index & 1)) TMC_SET_SGT(X2);
  10181. #endif
  10182. break;
  10183. #endif
  10184. #if Y_SENSORLESS
  10185. case Y_AXIS:
  10186. #if AXIS_HAS_STALLGUARD(Y)
  10187. if (index < 2) TMC_SET_SGT(Y);
  10188. #endif
  10189. #if AXIS_HAS_STALLGUARD(Y2)
  10190. if (!(index & 1)) TMC_SET_SGT(Y2);
  10191. #endif
  10192. break;
  10193. #endif
  10194. #if Z_SENSORLESS
  10195. case Z_AXIS:
  10196. #if AXIS_HAS_STALLGUARD(Z)
  10197. if (index < 2) TMC_SET_SGT(Z);
  10198. #endif
  10199. #if AXIS_HAS_STALLGUARD(Z2)
  10200. if (!(index & 1)) TMC_SET_SGT(Z2);
  10201. #endif
  10202. break;
  10203. #endif
  10204. }
  10205. }
  10206. if (report) {
  10207. #if X_SENSORLESS
  10208. #if AXIS_HAS_STALLGUARD(X)
  10209. TMC_SAY_SGT(X);
  10210. #endif
  10211. #if AXIS_HAS_STALLGUARD(X2)
  10212. TMC_SAY_SGT(X2);
  10213. #endif
  10214. #endif
  10215. #if Y_SENSORLESS
  10216. #if AXIS_HAS_STALLGUARD(Y)
  10217. TMC_SAY_SGT(Y);
  10218. #endif
  10219. #if AXIS_HAS_STALLGUARD(Y2)
  10220. TMC_SAY_SGT(Y2);
  10221. #endif
  10222. #endif
  10223. #if Z_SENSORLESS
  10224. #if AXIS_HAS_STALLGUARD(Z)
  10225. TMC_SAY_SGT(Z);
  10226. #endif
  10227. #if AXIS_HAS_STALLGUARD(Z2)
  10228. TMC_SAY_SGT(Z2);
  10229. #endif
  10230. #endif
  10231. }
  10232. }
  10233. #endif // SENSORLESS_HOMING
  10234. /**
  10235. * TMC Z axis calibration routine
  10236. */
  10237. #if ENABLED(TMC_Z_CALIBRATION)
  10238. inline void gcode_M915() {
  10239. const uint16_t _rms = parser.seenval('S') ? parser.value_int() : CALIBRATION_CURRENT,
  10240. _z = parser.seenval('Z') ? parser.value_linear_units() : CALIBRATION_EXTRA_HEIGHT;
  10241. if (!TEST(axis_known_position, Z_AXIS)) {
  10242. SERIAL_ECHOLNPGM("\nPlease home Z axis first");
  10243. return;
  10244. }
  10245. #if AXIS_IS_TMC(Z)
  10246. const uint16_t Z_current_1 = stepperZ.getCurrent();
  10247. stepperZ.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10248. #endif
  10249. #if AXIS_IS_TMC(Z2)
  10250. const uint16_t Z2_current_1 = stepperZ2.getCurrent();
  10251. stepperZ2.setCurrent(_rms, R_SENSE, HOLD_MULTIPLIER);
  10252. #endif
  10253. SERIAL_ECHOPAIR("\nCalibration current: Z", _rms);
  10254. soft_endstops_enabled = false;
  10255. do_blocking_move_to_z(Z_MAX_POS+_z);
  10256. #if AXIS_IS_TMC(Z)
  10257. stepperZ.setCurrent(Z_current_1, R_SENSE, HOLD_MULTIPLIER);
  10258. #endif
  10259. #if AXIS_IS_TMC(Z2)
  10260. stepperZ2.setCurrent(Z2_current_1, R_SENSE, HOLD_MULTIPLIER);
  10261. #endif
  10262. do_blocking_move_to_z(Z_MAX_POS);
  10263. soft_endstops_enabled = true;
  10264. SERIAL_ECHOLNPGM("\nHoming Z due to lost steps");
  10265. enqueue_and_echo_commands_P(PSTR("G28 Z"));
  10266. }
  10267. #endif
  10268. #endif // HAS_TRINAMIC
  10269. /**
  10270. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  10271. */
  10272. inline void gcode_M907() {
  10273. #if HAS_DIGIPOTSS
  10274. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  10275. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  10276. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  10277. #elif HAS_MOTOR_CURRENT_PWM
  10278. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  10279. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  10280. #endif
  10281. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  10282. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  10283. #endif
  10284. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  10285. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  10286. #endif
  10287. #endif
  10288. #if ENABLED(DIGIPOT_I2C)
  10289. // this one uses actual amps in floating point
  10290. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  10291. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  10292. for (uint8_t i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (parser.seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, parser.value_float());
  10293. #endif
  10294. #if ENABLED(DAC_STEPPER_CURRENT)
  10295. if (parser.seen('S')) {
  10296. const float dac_percent = parser.value_float();
  10297. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  10298. }
  10299. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  10300. #endif
  10301. }
  10302. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  10303. /**
  10304. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  10305. */
  10306. inline void gcode_M908() {
  10307. #if HAS_DIGIPOTSS
  10308. stepper.digitalPotWrite(
  10309. parser.intval('P'),
  10310. parser.intval('S')
  10311. );
  10312. #endif
  10313. #ifdef DAC_STEPPER_CURRENT
  10314. dac_current_raw(
  10315. parser.byteval('P', -1),
  10316. parser.ushortval('S', 0)
  10317. );
  10318. #endif
  10319. }
  10320. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  10321. inline void gcode_M909() { dac_print_values(); }
  10322. inline void gcode_M910() { dac_commit_eeprom(); }
  10323. #endif
  10324. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  10325. #if HAS_MICROSTEPS
  10326. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  10327. inline void gcode_M350() {
  10328. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  10329. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  10330. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  10331. stepper.microstep_readings();
  10332. }
  10333. /**
  10334. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  10335. * S# determines MS1 or MS2, X# sets the pin high/low.
  10336. */
  10337. inline void gcode_M351() {
  10338. if (parser.seenval('S')) switch (parser.value_byte()) {
  10339. case 1:
  10340. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  10341. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  10342. break;
  10343. case 2:
  10344. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  10345. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  10346. break;
  10347. }
  10348. stepper.microstep_readings();
  10349. }
  10350. #endif // HAS_MICROSTEPS
  10351. #if HAS_CASE_LIGHT
  10352. #ifndef INVERT_CASE_LIGHT
  10353. #define INVERT_CASE_LIGHT false
  10354. #endif
  10355. uint8_t case_light_brightness; // LCD routine wants INT
  10356. bool case_light_on;
  10357. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10358. LEDColor case_light_color =
  10359. #ifdef CASE_LIGHT_NEOPIXEL_COLOR
  10360. CASE_LIGHT_NEOPIXEL_COLOR
  10361. #else
  10362. { 255, 255, 255, 255 }
  10363. #endif
  10364. ;
  10365. #endif
  10366. void update_case_light() {
  10367. const uint8_t i = case_light_on ? case_light_brightness : 0, n10ct = INVERT_CASE_LIGHT ? 255 - i : i;
  10368. #if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
  10369. leds.set_color(
  10370. MakeLEDColor(case_light_color.r, case_light_color.g, case_light_color.b, case_light_color.w, n10ct),
  10371. false
  10372. );
  10373. #else // !CASE_LIGHT_USE_NEOPIXEL
  10374. SET_OUTPUT(CASE_LIGHT_PIN);
  10375. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN))
  10376. analogWrite(CASE_LIGHT_PIN, n10ct);
  10377. else {
  10378. const bool s = case_light_on ? !INVERT_CASE_LIGHT : INVERT_CASE_LIGHT;
  10379. WRITE(CASE_LIGHT_PIN, s ? HIGH : LOW);
  10380. }
  10381. #endif // !CASE_LIGHT_USE_NEOPIXEL
  10382. }
  10383. #endif // HAS_CASE_LIGHT
  10384. /**
  10385. * M355: Turn case light on/off and set brightness
  10386. *
  10387. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  10388. *
  10389. * S<bool> Set case light on/off
  10390. *
  10391. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  10392. *
  10393. * M355 P200 S0 turns off the light & sets the brightness level
  10394. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  10395. */
  10396. inline void gcode_M355() {
  10397. #if HAS_CASE_LIGHT
  10398. uint8_t args = 0;
  10399. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  10400. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  10401. if (args) update_case_light();
  10402. // always report case light status
  10403. SERIAL_ECHO_START();
  10404. if (!case_light_on) {
  10405. SERIAL_ECHOLNPGM("Case light: off");
  10406. }
  10407. else {
  10408. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLNPGM("Case light: on");
  10409. else SERIAL_ECHOLNPAIR("Case light: ", int(case_light_brightness));
  10410. }
  10411. #else
  10412. SERIAL_ERROR_START();
  10413. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  10414. #endif // HAS_CASE_LIGHT
  10415. }
  10416. #if ENABLED(MIXING_EXTRUDER)
  10417. /**
  10418. * M163: Set a single mix factor for a mixing extruder
  10419. * This is called "weight" by some systems.
  10420. * The 'P' values must sum to 1.0 or must be followed by M164 to normalize them.
  10421. *
  10422. * S[index] The channel index to set
  10423. * P[float] The mix value
  10424. */
  10425. inline void gcode_M163() {
  10426. const int mix_index = parser.intval('S');
  10427. if (mix_index < MIXING_STEPPERS)
  10428. mixing_factor[mix_index] = MAX(parser.floatval('P'), 0.0);
  10429. }
  10430. /**
  10431. * M164: Normalize and commit the mix.
  10432. * If 'S' is given store as a virtual tool. (Requires MIXING_VIRTUAL_TOOLS > 1)
  10433. *
  10434. * S[index] The virtual tool to store
  10435. */
  10436. inline void gcode_M164() {
  10437. normalize_mix();
  10438. #if MIXING_VIRTUAL_TOOLS > 1
  10439. const int tool_index = parser.intval('S', -1);
  10440. if (WITHIN(tool_index, 0, MIXING_VIRTUAL_TOOLS - 1)) {
  10441. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10442. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  10443. }
  10444. #endif
  10445. }
  10446. #if ENABLED(DIRECT_MIXING_IN_G1)
  10447. /**
  10448. * M165: Set multiple mix factors for a mixing extruder.
  10449. * Factors that are left out will be set to 0.
  10450. * All factors should sum to 1.0, but they will be normalized regardless.
  10451. *
  10452. * A[factor] Mix factor for extruder stepper 1
  10453. * B[factor] Mix factor for extruder stepper 2
  10454. * C[factor] Mix factor for extruder stepper 3
  10455. * D[factor] Mix factor for extruder stepper 4
  10456. * H[factor] Mix factor for extruder stepper 5
  10457. * I[factor] Mix factor for extruder stepper 6
  10458. */
  10459. inline void gcode_M165() { gcode_get_mix(); }
  10460. #endif
  10461. #endif // MIXING_EXTRUDER
  10462. /**
  10463. * M999: Restart after being stopped
  10464. *
  10465. * Default behaviour is to flush the serial buffer and request
  10466. * a resend to the host starting on the last N line received.
  10467. *
  10468. * Sending "M999 S1" will resume printing without flushing the
  10469. * existing command buffer.
  10470. *
  10471. */
  10472. inline void gcode_M999() {
  10473. Running = true;
  10474. lcd_reset_alert_level();
  10475. if (parser.boolval('S')) return;
  10476. // gcode_LastN = Stopped_gcode_LastN;
  10477. flush_and_request_resend();
  10478. }
  10479. #if DO_SWITCH_EXTRUDER
  10480. #if EXTRUDERS > 3
  10481. #define REQ_ANGLES 4
  10482. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  10483. #else
  10484. #define REQ_ANGLES 2
  10485. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  10486. #endif
  10487. inline void move_extruder_servo(const uint8_t e) {
  10488. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  10489. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  10490. planner.synchronize();
  10491. #if EXTRUDERS & 1
  10492. if (e < EXTRUDERS - 1)
  10493. #endif
  10494. {
  10495. MOVE_SERVO(_SERVO_NR, angles[e]);
  10496. safe_delay(500);
  10497. }
  10498. }
  10499. #endif // DO_SWITCH_EXTRUDER
  10500. #if ENABLED(SWITCHING_NOZZLE)
  10501. inline void move_nozzle_servo(const uint8_t e) {
  10502. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  10503. planner.synchronize();
  10504. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  10505. safe_delay(500);
  10506. }
  10507. #endif
  10508. inline void invalid_extruder_error(const uint8_t e) {
  10509. SERIAL_ECHO_START();
  10510. SERIAL_CHAR('T');
  10511. SERIAL_ECHO_F(e, DEC);
  10512. SERIAL_CHAR(' ');
  10513. SERIAL_ECHOLNPGM(MSG_INVALID_EXTRUDER);
  10514. }
  10515. #if ENABLED(PARKING_EXTRUDER)
  10516. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10517. #define PE_MAGNET_ON_STATE !PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10518. #else
  10519. #define PE_MAGNET_ON_STATE PARKING_EXTRUDER_SOLENOIDS_PINS_ACTIVE
  10520. #endif
  10521. void pe_set_magnet(const uint8_t extruder_num, const uint8_t state) {
  10522. switch (extruder_num) {
  10523. case 1: OUT_WRITE(SOL1_PIN, state); break;
  10524. default: OUT_WRITE(SOL0_PIN, state); break;
  10525. }
  10526. #if PARKING_EXTRUDER_SOLENOIDS_DELAY > 0
  10527. dwell(PARKING_EXTRUDER_SOLENOIDS_DELAY);
  10528. #endif
  10529. }
  10530. inline void pe_activate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, PE_MAGNET_ON_STATE); }
  10531. inline void pe_deactivate_magnet(const uint8_t extruder_num) { pe_set_magnet(extruder_num, !PE_MAGNET_ON_STATE); }
  10532. #endif // PARKING_EXTRUDER
  10533. #if HAS_FANMUX
  10534. void fanmux_switch(const uint8_t e) {
  10535. WRITE(FANMUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  10536. #if PIN_EXISTS(FANMUX1)
  10537. WRITE(FANMUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  10538. #if PIN_EXISTS(FANMUX2)
  10539. WRITE(FANMUX2, TEST(e, 2) ? HIGH : LOW);
  10540. #endif
  10541. #endif
  10542. }
  10543. FORCE_INLINE void fanmux_init(void) {
  10544. SET_OUTPUT(FANMUX0_PIN);
  10545. #if PIN_EXISTS(FANMUX1)
  10546. SET_OUTPUT(FANMUX1_PIN);
  10547. #if PIN_EXISTS(FANMUX2)
  10548. SET_OUTPUT(FANMUX2_PIN);
  10549. #endif
  10550. #endif
  10551. fanmux_switch(0);
  10552. }
  10553. #endif // HAS_FANMUX
  10554. /**
  10555. * Tool Change functions
  10556. */
  10557. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10558. inline void mixing_tool_change(const uint8_t tmp_extruder) {
  10559. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  10560. return invalid_extruder_error(tmp_extruder);
  10561. // T0-Tnnn: Switch virtual tool by changing the mix
  10562. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  10563. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  10564. }
  10565. #endif // MIXING_EXTRUDER && MIXING_VIRTUAL_TOOLS > 1
  10566. #if ENABLED(DUAL_X_CARRIAGE)
  10567. inline void dualx_tool_change(const uint8_t tmp_extruder, bool &no_move) {
  10568. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10569. if (DEBUGGING(LEVELING)) {
  10570. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  10571. switch (dual_x_carriage_mode) {
  10572. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  10573. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  10574. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  10575. }
  10576. }
  10577. #endif
  10578. const float xhome = x_home_pos(active_extruder);
  10579. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  10580. && IsRunning()
  10581. && (delayed_move_time || current_position[X_AXIS] != xhome)
  10582. ) {
  10583. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  10584. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10585. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  10586. #endif
  10587. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10588. if (DEBUGGING(LEVELING)) {
  10589. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  10590. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  10591. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  10592. }
  10593. #endif
  10594. // Park old head: 1) raise 2) move to park position 3) lower
  10595. for (uint8_t i = 0; i < 3; i++)
  10596. planner.buffer_line(
  10597. i == 0 ? current_position[X_AXIS] : xhome,
  10598. current_position[Y_AXIS],
  10599. i == 2 ? current_position[Z_AXIS] : raised_z,
  10600. current_position[E_CART],
  10601. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  10602. active_extruder
  10603. );
  10604. planner.synchronize();
  10605. }
  10606. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  10607. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  10608. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10609. // Activate the new extruder ahead of calling set_axis_is_at_home!
  10610. active_extruder = tmp_extruder;
  10611. // This function resets the max/min values - the current position may be overwritten below.
  10612. set_axis_is_at_home(X_AXIS);
  10613. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10614. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  10615. #endif
  10616. // Only when auto-parking are carriages safe to move
  10617. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  10618. switch (dual_x_carriage_mode) {
  10619. case DXC_FULL_CONTROL_MODE:
  10620. // New current position is the position of the activated extruder
  10621. current_position[X_AXIS] = inactive_extruder_x_pos;
  10622. // Save the inactive extruder's position (from the old current_position)
  10623. inactive_extruder_x_pos = destination[X_AXIS];
  10624. break;
  10625. case DXC_AUTO_PARK_MODE:
  10626. // record raised toolhead position for use by unpark
  10627. COPY(raised_parked_position, current_position);
  10628. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  10629. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  10630. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  10631. #endif
  10632. active_extruder_parked = true;
  10633. delayed_move_time = 0;
  10634. break;
  10635. case DXC_DUPLICATION_MODE:
  10636. // If the new extruder is the left one, set it "parked"
  10637. // This triggers the second extruder to move into the duplication position
  10638. active_extruder_parked = (active_extruder == 0);
  10639. current_position[X_AXIS] = active_extruder_parked ? inactive_extruder_x_pos : destination[X_AXIS] + duplicate_extruder_x_offset;
  10640. inactive_extruder_x_pos = destination[X_AXIS];
  10641. extruder_duplication_enabled = false;
  10642. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10643. if (DEBUGGING(LEVELING)) {
  10644. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  10645. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  10646. }
  10647. #endif
  10648. break;
  10649. }
  10650. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10651. if (DEBUGGING(LEVELING)) {
  10652. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  10653. DEBUG_POS("New extruder (parked)", current_position);
  10654. }
  10655. #endif
  10656. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  10657. }
  10658. #endif // DUAL_X_CARRIAGE
  10659. #if ENABLED(PARKING_EXTRUDER)
  10660. inline void parking_extruder_tool_change(const uint8_t tmp_extruder, bool no_move) {
  10661. constexpr float z_raise = PARKING_EXTRUDER_SECURITY_RAISE;
  10662. if (!no_move) {
  10663. const float parkingposx[] = PARKING_EXTRUDER_PARKING_X,
  10664. midpos = (parkingposx[0] + parkingposx[1]) * 0.5 + hotend_offset[X_AXIS][active_extruder],
  10665. grabpos = parkingposx[tmp_extruder] + hotend_offset[X_AXIS][active_extruder]
  10666. + (tmp_extruder == 0 ? -(PARKING_EXTRUDER_GRAB_DISTANCE) : PARKING_EXTRUDER_GRAB_DISTANCE);
  10667. /**
  10668. * Steps:
  10669. * 1. Raise Z-Axis to give enough clearance
  10670. * 2. Move to park position of old extruder
  10671. * 3. Disengage magnetic field, wait for delay
  10672. * 4. Move near new extruder
  10673. * 5. Engage magnetic field for new extruder
  10674. * 6. Move to parking incl. offset of new extruder
  10675. * 7. Lower Z-Axis
  10676. */
  10677. // STEP 1
  10678. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10679. SERIAL_ECHOLNPGM("Starting Autopark");
  10680. if (DEBUGGING(LEVELING)) DEBUG_POS("current position:", current_position);
  10681. #endif
  10682. current_position[Z_AXIS] += z_raise;
  10683. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10684. SERIAL_ECHOLNPGM("(1) Raise Z-Axis ");
  10685. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving to Raised Z-Position", current_position);
  10686. #endif
  10687. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10688. planner.synchronize();
  10689. // STEP 2
  10690. current_position[X_AXIS] = parkingposx[active_extruder] + hotend_offset[X_AXIS][active_extruder];
  10691. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10692. SERIAL_ECHOLNPAIR("(2) Park extruder ", active_extruder);
  10693. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving ParkPos", current_position);
  10694. #endif
  10695. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10696. planner.synchronize();
  10697. // STEP 3
  10698. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10699. SERIAL_ECHOLNPGM("(3) Disengage magnet ");
  10700. #endif
  10701. pe_deactivate_magnet(active_extruder);
  10702. // STEP 4
  10703. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10704. SERIAL_ECHOLNPGM("(4) Move to position near new extruder");
  10705. #endif
  10706. current_position[X_AXIS] += (active_extruder == 0 ? 10 : -10); // move 10mm away from parked extruder
  10707. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10708. if (DEBUGGING(LEVELING)) DEBUG_POS("Moving away from parked extruder", current_position);
  10709. #endif
  10710. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10711. planner.synchronize();
  10712. // STEP 5
  10713. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10714. SERIAL_ECHOLNPGM("(5) Engage magnetic field");
  10715. #endif
  10716. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10717. pe_activate_magnet(active_extruder); //just save power for inverted magnets
  10718. #endif
  10719. pe_activate_magnet(tmp_extruder);
  10720. // STEP 6
  10721. current_position[X_AXIS] = grabpos + (tmp_extruder == 0 ? (+10) : (-10));
  10722. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10723. current_position[X_AXIS] = grabpos;
  10724. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10725. SERIAL_ECHOLNPAIR("(6) Unpark extruder ", tmp_extruder);
  10726. if (DEBUGGING(LEVELING)) DEBUG_POS("Move UnparkPos", current_position);
  10727. #endif
  10728. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS]/2, active_extruder);
  10729. planner.synchronize();
  10730. // Step 7
  10731. current_position[X_AXIS] = midpos - hotend_offset[X_AXIS][tmp_extruder];
  10732. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10733. SERIAL_ECHOLNPGM("(7) Move midway between hotends");
  10734. if (DEBUGGING(LEVELING)) DEBUG_POS("Move midway to new extruder", current_position);
  10735. #endif
  10736. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[X_AXIS], active_extruder);
  10737. planner.synchronize();
  10738. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10739. SERIAL_ECHOLNPGM("Autopark done.");
  10740. #endif
  10741. }
  10742. else { // nomove == true
  10743. // Only engage magnetic field for new extruder
  10744. pe_activate_magnet(tmp_extruder);
  10745. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  10746. pe_activate_magnet(active_extruder); // Just save power for inverted magnets
  10747. #endif
  10748. }
  10749. current_position[Z_AXIS] += hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10750. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10751. if (DEBUGGING(LEVELING)) DEBUG_POS("Applying Z-offset", current_position);
  10752. #endif
  10753. }
  10754. #endif // PARKING_EXTRUDER
  10755. /**
  10756. * Perform a tool-change, which may result in moving the
  10757. * previous tool out of the way and the new tool into place.
  10758. */
  10759. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  10760. planner.synchronize();
  10761. #if HAS_LEVELING
  10762. // Set current position to the physical position
  10763. const bool leveling_was_active = planner.leveling_active;
  10764. set_bed_leveling_enabled(false);
  10765. #endif
  10766. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10767. mixing_tool_change(tmp_extruder);
  10768. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10769. if (tmp_extruder >= EXTRUDERS)
  10770. return invalid_extruder_error(tmp_extruder);
  10771. #if HOTENDS > 1
  10772. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  10773. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  10774. if (tmp_extruder != active_extruder) {
  10775. if (!no_move && axis_unhomed_error()) {
  10776. no_move = true;
  10777. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10778. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("No move on toolchange");
  10779. #endif
  10780. }
  10781. #if ENABLED(DUAL_X_CARRIAGE)
  10782. #if HAS_SOFTWARE_ENDSTOPS
  10783. // Update the X software endstops early
  10784. active_extruder = tmp_extruder;
  10785. update_software_endstops(X_AXIS);
  10786. active_extruder = !tmp_extruder;
  10787. #endif
  10788. // Don't move the new extruder out of bounds
  10789. if (!WITHIN(current_position[X_AXIS], soft_endstop_min[X_AXIS], soft_endstop_max[X_AXIS]))
  10790. no_move = true;
  10791. if (!no_move) set_destination_from_current();
  10792. dualx_tool_change(tmp_extruder, no_move); // Can modify no_move
  10793. #else // !DUAL_X_CARRIAGE
  10794. set_destination_from_current();
  10795. #if ENABLED(PARKING_EXTRUDER)
  10796. parking_extruder_tool_change(tmp_extruder, no_move);
  10797. #endif
  10798. #if ENABLED(SWITCHING_NOZZLE)
  10799. // Always raise by at least 1 to avoid workpiece
  10800. const float zdiff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  10801. current_position[Z_AXIS] += (zdiff > 0.0 ? zdiff : 0.0) + 1;
  10802. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10803. move_nozzle_servo(tmp_extruder);
  10804. #endif
  10805. const float xdiff = hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  10806. ydiff = hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder];
  10807. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10808. if (DEBUGGING(LEVELING)) {
  10809. SERIAL_ECHOPAIR("Offset Tool XY by { ", xdiff);
  10810. SERIAL_ECHOPAIR(", ", ydiff);
  10811. SERIAL_ECHOLNPGM(" }");
  10812. }
  10813. #endif
  10814. // The newly-selected extruder XY is actually at...
  10815. current_position[X_AXIS] += xdiff;
  10816. current_position[Y_AXIS] += ydiff;
  10817. // Set the new active extruder
  10818. active_extruder = tmp_extruder;
  10819. #endif // !DUAL_X_CARRIAGE
  10820. #if ENABLED(SWITCHING_NOZZLE)
  10821. // The newly-selected extruder Z is actually at...
  10822. current_position[Z_AXIS] -= zdiff;
  10823. #endif
  10824. // Tell the planner the new "current position"
  10825. SYNC_PLAN_POSITION_KINEMATIC();
  10826. #if ENABLED(DELTA)
  10827. //LOOP_XYZ(i) update_software_endstops(i); // or modify the constrain function
  10828. const bool safe_to_move = current_position[Z_AXIS] < delta_clip_start_height - 1;
  10829. #else
  10830. constexpr bool safe_to_move = true;
  10831. #endif
  10832. // Raise, move, and lower again
  10833. if (safe_to_move && !no_move && IsRunning()) {
  10834. #if DISABLED(SWITCHING_NOZZLE)
  10835. // Do a small lift to avoid the workpiece in the move back (below)
  10836. current_position[Z_AXIS] += 1.0;
  10837. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  10838. #endif
  10839. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10840. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  10841. #endif
  10842. // Move back to the original (or tweaked) position
  10843. do_blocking_move_to(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS]);
  10844. #if ENABLED(DUAL_X_CARRIAGE)
  10845. active_extruder_parked = false;
  10846. #endif
  10847. }
  10848. #if ENABLED(SWITCHING_NOZZLE)
  10849. else {
  10850. // Move back down. (Including when the new tool is higher.)
  10851. do_blocking_move_to_z(destination[Z_AXIS], planner.max_feedrate_mm_s[Z_AXIS]);
  10852. }
  10853. #endif
  10854. } // (tmp_extruder != active_extruder)
  10855. planner.synchronize();
  10856. #if ENABLED(EXT_SOLENOID) && !ENABLED(PARKING_EXTRUDER)
  10857. disable_all_solenoids();
  10858. enable_solenoid_on_active_extruder();
  10859. #endif
  10860. feedrate_mm_s = old_feedrate_mm_s;
  10861. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(DUAL_X_CARRIAGE)
  10862. update_software_endstops(X_AXIS);
  10863. #endif
  10864. #else // HOTENDS <= 1
  10865. UNUSED(fr_mm_s);
  10866. UNUSED(no_move);
  10867. #if ENABLED(MK2_MULTIPLEXER)
  10868. if (tmp_extruder >= E_STEPPERS)
  10869. return invalid_extruder_error(tmp_extruder);
  10870. select_multiplexed_stepper(tmp_extruder);
  10871. #endif
  10872. // Set the new active extruder
  10873. active_extruder = tmp_extruder;
  10874. #endif // HOTENDS <= 1
  10875. #if DO_SWITCH_EXTRUDER
  10876. planner.synchronize();
  10877. move_extruder_servo(active_extruder);
  10878. #endif
  10879. #if HAS_FANMUX
  10880. fanmux_switch(active_extruder);
  10881. #endif
  10882. #if HAS_LEVELING
  10883. // Restore leveling to re-establish the logical position
  10884. set_bed_leveling_enabled(leveling_was_active);
  10885. #endif
  10886. SERIAL_ECHO_START();
  10887. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, int(active_extruder));
  10888. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  10889. }
  10890. /**
  10891. * T0-T3: Switch tool, usually switching extruders
  10892. *
  10893. * F[units/min] Set the movement feedrate
  10894. * S1 Don't move the tool in XY after change
  10895. */
  10896. inline void gcode_T(const uint8_t tmp_extruder) {
  10897. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10898. if (DEBUGGING(LEVELING)) {
  10899. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  10900. SERIAL_CHAR(')');
  10901. SERIAL_EOL();
  10902. DEBUG_POS("BEFORE", current_position);
  10903. }
  10904. #endif
  10905. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  10906. tool_change(tmp_extruder);
  10907. #elif HOTENDS > 1
  10908. tool_change(
  10909. tmp_extruder,
  10910. MMM_TO_MMS(parser.linearval('F')),
  10911. (tmp_extruder == active_extruder) || parser.boolval('S')
  10912. );
  10913. #endif
  10914. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10915. if (DEBUGGING(LEVELING)) {
  10916. DEBUG_POS("AFTER", current_position);
  10917. SERIAL_ECHOLNPGM("<<< gcode_T");
  10918. }
  10919. #endif
  10920. }
  10921. /**
  10922. * Process the parsed command and dispatch it to its handler
  10923. */
  10924. void process_parsed_command() {
  10925. KEEPALIVE_STATE(IN_HANDLER);
  10926. // Handle a known G, M, or T
  10927. switch (parser.command_letter) {
  10928. case 'G': switch (parser.codenum) {
  10929. case 0: case 1: gcode_G0_G1( // G0: Fast Move, G1: Linear Move
  10930. #if IS_SCARA
  10931. parser.codenum == 0
  10932. #endif
  10933. ); break;
  10934. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  10935. case 2: case 3: gcode_G2_G3(parser.codenum == 2); break; // G2: CW ARC, G3: CCW ARC
  10936. #endif
  10937. case 4: gcode_G4(); break; // G4: Dwell
  10938. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10939. case 5: gcode_G5(); break; // G5: Cubic B_spline
  10940. #endif
  10941. #if ENABLED(UNREGISTERED_MOVE_SUPPORT)
  10942. case 6: gcode_G6(); break; // G6: Direct stepper move
  10943. #endif
  10944. #if ENABLED(FWRETRACT)
  10945. case 10: gcode_G10(); break; // G10: Retract
  10946. case 11: gcode_G11(); break; // G11: Prime
  10947. #endif
  10948. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  10949. case 12: gcode_G12(); break; // G12: Clean Nozzle
  10950. #endif
  10951. #if ENABLED(CNC_WORKSPACE_PLANES)
  10952. case 17: gcode_G17(); break; // G17: Select Plane XY
  10953. case 18: gcode_G18(); break; // G18: Select Plane ZX
  10954. case 19: gcode_G19(); break; // G19: Select Plane YZ
  10955. #endif
  10956. #if ENABLED(INCH_MODE_SUPPORT)
  10957. case 20: gcode_G20(); break; // G20: Inch Units
  10958. case 21: gcode_G21(); break; // G21: Millimeter Units
  10959. #endif
  10960. #if ENABLED(G26_MESH_VALIDATION)
  10961. case 26: gcode_G26(); break; // G26: Mesh Validation Pattern
  10962. #endif
  10963. #if ENABLED(NOZZLE_PARK_FEATURE)
  10964. case 27: gcode_G27(); break; // G27: Park Nozzle
  10965. #endif
  10966. case 28: gcode_G28(false); break; // G28: Home one or more axes
  10967. #if HAS_LEVELING
  10968. case 29: gcode_G29(); break; // G29: Detailed Z probe
  10969. #endif
  10970. #if HAS_BED_PROBE
  10971. case 30: gcode_G30(); break; // G30: Single Z probe
  10972. #endif
  10973. #if ENABLED(Z_PROBE_SLED)
  10974. case 31: gcode_G31(); break; // G31: Dock sled
  10975. case 32: gcode_G32(); break; // G32: Undock sled
  10976. #endif
  10977. #if ENABLED(DELTA_AUTO_CALIBRATION)
  10978. case 33: gcode_G33(); break; // G33: Delta Auto-Calibration
  10979. #endif
  10980. #if ENABLED(G38_PROBE_TARGET)
  10981. case 38:
  10982. if (parser.subcode == 2 || parser.subcode == 3)
  10983. gcode_G38(parser.subcode == 2); // G38.2, G38.3: Probe towards object
  10984. break;
  10985. #endif
  10986. #if HAS_MESH
  10987. case 42: gcode_G42(); break; // G42: Move to mesh point
  10988. #endif
  10989. case 90: relative_mode = false; break; // G90: Absolute coordinates
  10990. case 91: relative_mode = true; break; // G91: Relative coordinates
  10991. case 92: gcode_G92(); break; // G92: Set Position
  10992. #if ENABLED(MECHADUINO_I2C_COMMANDS)
  10993. case 95: gcode_G95(); break; // G95: Set torque mode
  10994. case 96: gcode_G96(); break; // G96: Mark encoder reference point
  10995. #endif
  10996. #if ENABLED(DEBUG_GCODE_PARSER)
  10997. case 800: parser.debug(); break; // G800: GCode Parser Test for G
  10998. #endif
  10999. default: parser.unknown_command_error();
  11000. }
  11001. break;
  11002. case 'M': switch (parser.codenum) {
  11003. #if HAS_RESUME_CONTINUE
  11004. case 0: case 1: gcode_M0_M1(); break; // M0: Unconditional stop, M1: Conditional stop
  11005. #endif
  11006. #if ENABLED(SPINDLE_LASER_ENABLE)
  11007. case 3: gcode_M3_M4(true); break; // M3: Laser/CW-Spindle Power
  11008. case 4: gcode_M3_M4(false); break; // M4: Laser/CCW-Spindle Power
  11009. case 5: gcode_M5(); break; // M5: Laser/Spindle OFF
  11010. #endif
  11011. case 17: gcode_M17(); break; // M17: Enable all steppers
  11012. #if ENABLED(SDSUPPORT)
  11013. case 20: gcode_M20(); break; // M20: List SD Card
  11014. case 21: gcode_M21(); break; // M21: Init SD Card
  11015. case 22: gcode_M22(); break; // M22: Release SD Card
  11016. case 23: gcode_M23(); break; // M23: Select File
  11017. case 24: gcode_M24(); break; // M24: Start SD Print
  11018. case 25: gcode_M25(); break; // M25: Pause SD Print
  11019. case 26: gcode_M26(); break; // M26: Set SD Index
  11020. case 27: gcode_M27(); break; // M27: Get SD Status
  11021. case 28: gcode_M28(); break; // M28: Start SD Write
  11022. case 29: gcode_M29(); break; // M29: Stop SD Write
  11023. case 30: gcode_M30(); break; // M30: Delete File
  11024. case 32: gcode_M32(); break; // M32: Select file, Start SD Print
  11025. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  11026. case 33: gcode_M33(); break; // M33: Report longname path
  11027. #endif
  11028. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  11029. case 34: gcode_M34(); break; // M34: Set SD card sorting options
  11030. #endif
  11031. case 928: gcode_M928(); break; // M928: Start SD write
  11032. #endif // SDSUPPORT
  11033. case 31: gcode_M31(); break; // M31: Report print job elapsed time
  11034. case 42: gcode_M42(); break; // M42: Change pin state
  11035. #if ENABLED(PINS_DEBUGGING)
  11036. case 43: gcode_M43(); break; // M43: Read/monitor pin and endstop states
  11037. #endif
  11038. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  11039. case 48: gcode_M48(); break; // M48: Z probe repeatability test
  11040. #endif
  11041. #if ENABLED(G26_MESH_VALIDATION)
  11042. case 49: gcode_M49(); break; // M49: Toggle the G26 Debug Flag
  11043. #endif
  11044. #if ENABLED(ULTRA_LCD) && ENABLED(LCD_SET_PROGRESS_MANUALLY)
  11045. case 73: gcode_M73(); break; // M73: Set Print Progress %
  11046. #endif
  11047. case 75: gcode_M75(); break; // M75: Start Print Job Timer
  11048. case 76: gcode_M76(); break; // M76: Pause Print Job Timer
  11049. case 77: gcode_M77(); break; // M77: Stop Print Job Timer
  11050. #if ENABLED(PRINTCOUNTER)
  11051. case 78: gcode_M78(); break; // M78: Report Print Statistics
  11052. #endif
  11053. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  11054. case 100: gcode_M100(); break; // M100: Free Memory Report
  11055. #endif
  11056. case 104: gcode_M104(); break; // M104: Set Hotend Temperature
  11057. case 110: gcode_M110(); break; // M110: Set Current Line Number
  11058. case 111: gcode_M111(); break; // M111: Set Debug Flags
  11059. #if DISABLED(EMERGENCY_PARSER)
  11060. case 108: gcode_M108(); break; // M108: Cancel Waiting
  11061. case 112: gcode_M112(); break; // M112: Emergency Stop
  11062. case 410: gcode_M410(); break; // M410: Quickstop. Abort all planned moves
  11063. #else
  11064. case 108: case 112: case 410: break; // Silently drop as handled by emergency parser
  11065. #endif
  11066. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  11067. case 113: gcode_M113(); break; // M113: Set Host Keepalive Interval
  11068. #endif
  11069. case 105: gcode_M105(); KEEPALIVE_STATE(NOT_BUSY); return; // M105: Report Temperatures (and say "ok")
  11070. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  11071. case 155: gcode_M155(); break; // M155: Set Temperature Auto-report Interval
  11072. #endif
  11073. case 109: gcode_M109(); break; // M109: Set Hotend Temperature. Wait for target.
  11074. #if HAS_HEATED_BED
  11075. case 140: gcode_M140(); break; // M140: Set Bed Temperature
  11076. case 190: gcode_M190(); break; // M190: Set Bed Temperature. Wait for target.
  11077. #endif
  11078. #if FAN_COUNT > 0
  11079. case 106: gcode_M106(); break; // M106: Set Fan Speed
  11080. case 107: gcode_M107(); break; // M107: Fan Off
  11081. #endif
  11082. #if ENABLED(PARK_HEAD_ON_PAUSE)
  11083. case 125: gcode_M125(); break; // M125: Park (for Filament Change)
  11084. #endif
  11085. #if ENABLED(BARICUDA)
  11086. #if HAS_HEATER_1
  11087. case 126: gcode_M126(); break; // M126: Valve 1 Open
  11088. case 127: gcode_M127(); break; // M127: Valve 1 Closed
  11089. #endif
  11090. #if HAS_HEATER_2
  11091. case 128: gcode_M128(); break; // M128: Valve 2 Open
  11092. case 129: gcode_M129(); break; // M129: Valve 2 Closed
  11093. #endif
  11094. #endif
  11095. #if HAS_POWER_SWITCH
  11096. case 80: gcode_M80(); break; // M80: Turn on Power Supply
  11097. #endif
  11098. case 81: gcode_M81(); break; // M81: Turn off Power and Power Supply
  11099. case 82: gcode_M82(); break; // M82: Disable Relative E-Axis
  11100. case 83: gcode_M83(); break; // M83: Set Relative E-Axis
  11101. case 18: case 84: gcode_M18_M84(); break; // M18/M84: Disable Steppers / Set Timeout
  11102. case 85: gcode_M85(); break; // M85: Set inactivity stepper shutdown timeout
  11103. case 92: gcode_M92(); break; // M92: Set steps-per-unit
  11104. case 114: gcode_M114(); break; // M114: Report Current Position
  11105. case 115: gcode_M115(); break; // M115: Capabilities Report
  11106. case 117: gcode_M117(); break; // M117: Set LCD message text
  11107. case 118: gcode_M118(); break; // M118: Print a message in the host console
  11108. case 119: gcode_M119(); break; // M119: Report Endstop states
  11109. case 120: gcode_M120(); break; // M120: Enable Endstops
  11110. case 121: gcode_M121(); break; // M121: Disable Endstops
  11111. #if ENABLED(ULTIPANEL)
  11112. case 145: gcode_M145(); break; // M145: Set material heatup parameters
  11113. #endif
  11114. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  11115. case 149: gcode_M149(); break; // M149: Set Temperature Units, C F K
  11116. #endif
  11117. #if HAS_COLOR_LEDS
  11118. case 150: gcode_M150(); break; // M150: Set Status LED Color
  11119. #endif
  11120. #if ENABLED(MIXING_EXTRUDER)
  11121. case 163: gcode_M163(); break; // M163: Set Mixing Component
  11122. #if MIXING_VIRTUAL_TOOLS > 1
  11123. case 164: gcode_M164(); break; // M164: Save Current Mix
  11124. #endif
  11125. #if ENABLED(DIRECT_MIXING_IN_G1)
  11126. case 165: gcode_M165(); break; // M165: Set Multiple Mixing Components
  11127. #endif
  11128. #endif
  11129. #if DISABLED(NO_VOLUMETRICS)
  11130. case 200: gcode_M200(); break; // M200: Set Filament Diameter, Volumetric Extrusion
  11131. #endif
  11132. case 201: gcode_M201(); break; // M201: Set Max Printing Acceleration (units/sec^2)
  11133. #if 0
  11134. case 202: gcode_M202(); break; // M202: Not used for Sprinter/grbl gen6
  11135. #endif
  11136. case 203: gcode_M203(); break; // M203: Set Max Feedrate (units/sec)
  11137. case 204: gcode_M204(); break; // M204: Set Acceleration
  11138. case 205: gcode_M205(); break; // M205: Set Advanced settings
  11139. #if HAS_M206_COMMAND
  11140. case 206: gcode_M206(); break; // M206: Set Home Offsets
  11141. case 428: gcode_M428(); break; // M428: Set Home Offsets based on current position
  11142. #endif
  11143. #if ENABLED(FWRETRACT)
  11144. case 207: gcode_M207(); break; // M207: Set Retract Length, Feedrate, Z lift
  11145. case 208: gcode_M208(); break; // M208: Set Additional Prime Length and Feedrate
  11146. case 209:
  11147. if (MIN_AUTORETRACT <= MAX_AUTORETRACT) gcode_M209(); // M209: Turn Auto-Retract on/off
  11148. break;
  11149. #endif
  11150. case 211: gcode_M211(); break; // M211: Enable/Disable/Report Software Endstops
  11151. #if HOTENDS > 1
  11152. case 218: gcode_M218(); break; // M218: Set Tool Offset
  11153. #endif
  11154. case 220: gcode_M220(); break; // M220: Set Feedrate Percentage
  11155. case 221: gcode_M221(); break; // M221: Set Flow Percentage
  11156. case 226: gcode_M226(); break; // M226: Wait for Pin State
  11157. #if defined(CHDK) || HAS_PHOTOGRAPH
  11158. case 240: gcode_M240(); break; // M240: Trigger Camera
  11159. #endif
  11160. #if HAS_LCD_CONTRAST
  11161. case 250: gcode_M250(); break; // M250: Set LCD Contrast
  11162. #endif
  11163. #if ENABLED(EXPERIMENTAL_I2CBUS)
  11164. case 260: gcode_M260(); break; // M260: Send Data to i2c slave
  11165. case 261: gcode_M261(); break; // M261: Request Data from i2c slave
  11166. #endif
  11167. #if HAS_SERVOS
  11168. case 280: gcode_M280(); break; // M280: Set Servo Position
  11169. #endif
  11170. #if ENABLED(BABYSTEPPING)
  11171. case 290: gcode_M290(); break; // M290: Babystepping
  11172. #endif
  11173. #if HAS_BUZZER
  11174. case 300: gcode_M300(); break; // M300: Add Tone/Buzz to Queue
  11175. #endif
  11176. #if ENABLED(PIDTEMP)
  11177. case 301: gcode_M301(); break; // M301: Set Hotend PID parameters
  11178. #endif
  11179. #if ENABLED(PREVENT_COLD_EXTRUSION)
  11180. case 302: gcode_M302(); break; // M302: Set Minimum Extrusion Temp
  11181. #endif
  11182. case 303: gcode_M303(); break; // M303: PID Autotune
  11183. #if ENABLED(PIDTEMPBED)
  11184. case 304: gcode_M304(); break; // M304: Set Bed PID parameters
  11185. #endif
  11186. #if HAS_MICROSTEPS
  11187. case 350: gcode_M350(); break; // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  11188. case 351: gcode_M351(); break; // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  11189. #endif
  11190. case 355: gcode_M355(); break; // M355: Set Case Light brightness
  11191. #if ENABLED(MORGAN_SCARA)
  11192. case 360: if (gcode_M360()) return; break; // M360: SCARA Theta pos1
  11193. case 361: if (gcode_M361()) return; break; // M361: SCARA Theta pos2
  11194. case 362: if (gcode_M362()) return; break; // M362: SCARA Psi pos1
  11195. case 363: if (gcode_M363()) return; break; // M363: SCARA Psi pos2
  11196. case 364: if (gcode_M364()) return; break; // M364: SCARA Psi pos3 (90 deg to Theta)
  11197. #endif
  11198. case 400: gcode_M400(); break; // M400: Synchronize. Wait for moves to finish.
  11199. #if HAS_BED_PROBE
  11200. case 401: gcode_M401(); break; // M401: Deploy Probe
  11201. case 402: gcode_M402(); break; // M402: Stow Probe
  11202. #endif
  11203. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  11204. case 404: gcode_M404(); break; // M404: Set/Report Nominal Filament Width
  11205. case 405: gcode_M405(); break; // M405: Enable Filament Width Sensor
  11206. case 406: gcode_M406(); break; // M406: Disable Filament Width Sensor
  11207. case 407: gcode_M407(); break; // M407: Report Measured Filament Width
  11208. #endif
  11209. #if HAS_LEVELING
  11210. case 420: gcode_M420(); break; // M420: Set Bed Leveling Enabled / Fade
  11211. #endif
  11212. #if HAS_MESH
  11213. case 421: gcode_M421(); break; // M421: Set a Mesh Z value
  11214. #endif
  11215. case 500: gcode_M500(); break; // M500: Store Settings in EEPROM
  11216. case 501: gcode_M501(); break; // M501: Read Settings from EEPROM
  11217. case 502: gcode_M502(); break; // M502: Revert Settings to defaults
  11218. #if DISABLED(DISABLE_M503)
  11219. case 503: gcode_M503(); break; // M503: Report Settings (in SRAM)
  11220. #endif
  11221. #if ENABLED(EEPROM_SETTINGS)
  11222. case 504: gcode_M504(); break; // M504: Validate EEPROM
  11223. #endif
  11224. #if ENABLED(SDSUPPORT)
  11225. case 524: gcode_M524(); break; // M524: Abort SD print job
  11226. #endif
  11227. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  11228. case 540: gcode_M540(); break; // M540: Set Abort on Endstop Hit for SD Printing
  11229. #endif
  11230. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  11231. case 600: gcode_M600(); break; // M600: Pause for Filament Change
  11232. case 603: gcode_M603(); break; // M603: Configure Filament Change
  11233. #endif
  11234. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  11235. case 605: gcode_M605(); break; // M605: Set Dual X Carriage movement mode
  11236. #endif
  11237. #if ENABLED(DELTA) || ENABLED(HANGPRINTER)
  11238. case 665: gcode_M665(); break; // M665: Delta / Hangprinter Configuration
  11239. #endif
  11240. #if ENABLED(DELTA) || ENABLED(X_DUAL_ENDSTOPS) || ENABLED(Y_DUAL_ENDSTOPS) || ENABLED(Z_DUAL_ENDSTOPS)
  11241. case 666: gcode_M666(); break; // M666: DELTA/Dual Endstop Adjustment
  11242. #endif
  11243. #if ENABLED(FILAMENT_LOAD_UNLOAD_GCODES)
  11244. case 701: gcode_M701(); break; // M701: Load Filament
  11245. case 702: gcode_M702(); break; // M702: Unload Filament
  11246. #endif
  11247. #if ENABLED(MAX7219_GCODE)
  11248. case 7219: gcode_M7219(); break; // M7219: Set LEDs, columns, and rows
  11249. #endif
  11250. #if ENABLED(DEBUG_GCODE_PARSER)
  11251. case 800: parser.debug(); break; // M800: GCode Parser Test for M
  11252. #endif
  11253. #if HAS_BED_PROBE
  11254. case 851: gcode_M851(); break; // M851: Set Z Probe Z Offset
  11255. #endif
  11256. #if ENABLED(SKEW_CORRECTION_GCODE)
  11257. case 852: gcode_M852(); break; // M852: Set Skew factors
  11258. #endif
  11259. #if ENABLED(I2C_POSITION_ENCODERS)
  11260. case 860: gcode_M860(); break; // M860: Report encoder module position
  11261. case 861: gcode_M861(); break; // M861: Report encoder module status
  11262. case 862: gcode_M862(); break; // M862: Perform axis test
  11263. case 863: gcode_M863(); break; // M863: Calibrate steps/mm
  11264. case 864: gcode_M864(); break; // M864: Change module address
  11265. case 865: gcode_M865(); break; // M865: Check module firmware version
  11266. case 866: gcode_M866(); break; // M866: Report axis error count
  11267. case 867: gcode_M867(); break; // M867: Toggle error correction
  11268. case 868: gcode_M868(); break; // M868: Set error correction threshold
  11269. case 869: gcode_M869(); break; // M869: Report axis error
  11270. #endif
  11271. #if ENABLED(LIN_ADVANCE)
  11272. case 900: gcode_M900(); break; // M900: Set Linear Advance K factor
  11273. #endif
  11274. case 907: gcode_M907(); break; // M907: Set Digital Trimpot Motor Current using axis codes.
  11275. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  11276. case 908: gcode_M908(); break; // M908: Direct Control Digital Trimpot
  11277. #if ENABLED(DAC_STEPPER_CURRENT)
  11278. case 909: gcode_M909(); break; // M909: Print Digipot/DAC current value (As with Printrbot RevF)
  11279. case 910: gcode_M910(); break; // M910: Commit Digipot/DAC value to External EEPROM (As with Printrbot RevF)
  11280. #endif
  11281. #endif
  11282. #if HAS_DRIVER(TMC2130) || HAS_DRIVER(TMC2208)
  11283. #if ENABLED(TMC_DEBUG)
  11284. case 122: gcode_M122(); break; // M122: Debug TMC steppers
  11285. #endif
  11286. case 906: gcode_M906(); break; // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  11287. case 911: gcode_M911(); break; // M911: Report TMC prewarn triggered flags
  11288. case 912: gcode_M912(); break; // M911: Clear TMC prewarn triggered flags
  11289. #if ENABLED(HYBRID_THRESHOLD)
  11290. case 913: gcode_M913(); break; // M913: Set HYBRID_THRESHOLD speed.
  11291. #endif
  11292. #if ENABLED(SENSORLESS_HOMING)
  11293. case 914: gcode_M914(); break; // M914: Set SENSORLESS_HOMING sensitivity.
  11294. #endif
  11295. #if ENABLED(TMC_Z_CALIBRATION)
  11296. case 915: gcode_M915(); break; // M915: TMC Z axis calibration routine
  11297. #endif
  11298. #endif
  11299. case 999: gcode_M999(); break; // M999: Restart after being Stopped
  11300. default: parser.unknown_command_error();
  11301. }
  11302. break;
  11303. case 'T': gcode_T(parser.codenum); break; // T: Tool Select
  11304. default: parser.unknown_command_error();
  11305. }
  11306. KEEPALIVE_STATE(NOT_BUSY);
  11307. ok_to_send();
  11308. }
  11309. void process_next_command() {
  11310. char * const current_command = command_queue[cmd_queue_index_r];
  11311. if (DEBUGGING(ECHO)) {
  11312. SERIAL_ECHO_START();
  11313. SERIAL_ECHOLN(current_command);
  11314. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  11315. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  11316. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  11317. #endif
  11318. }
  11319. // Parse the next command in the queue
  11320. parser.parse(current_command);
  11321. process_parsed_command();
  11322. }
  11323. /**
  11324. * Send a "Resend: nnn" message to the host to
  11325. * indicate that a command needs to be re-sent.
  11326. */
  11327. void flush_and_request_resend() {
  11328. //char command_queue[cmd_queue_index_r][100]="Resend:";
  11329. SERIAL_FLUSH();
  11330. SERIAL_PROTOCOLPGM(MSG_RESEND);
  11331. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  11332. ok_to_send();
  11333. }
  11334. /**
  11335. * Send an "ok" message to the host, indicating
  11336. * that a command was successfully processed.
  11337. *
  11338. * If ADVANCED_OK is enabled also include:
  11339. * N<int> Line number of the command, if any
  11340. * P<int> Planner space remaining
  11341. * B<int> Block queue space remaining
  11342. */
  11343. void ok_to_send() {
  11344. if (!send_ok[cmd_queue_index_r]) return;
  11345. SERIAL_PROTOCOLPGM(MSG_OK);
  11346. #if ENABLED(ADVANCED_OK)
  11347. char* p = command_queue[cmd_queue_index_r];
  11348. if (*p == 'N') {
  11349. SERIAL_PROTOCOL(' ');
  11350. SERIAL_ECHO(*p++);
  11351. while (NUMERIC_SIGNED(*p))
  11352. SERIAL_ECHO(*p++);
  11353. }
  11354. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  11355. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  11356. #endif
  11357. SERIAL_EOL();
  11358. }
  11359. #if HAS_SOFTWARE_ENDSTOPS
  11360. /**
  11361. * Constrain the given coordinates to the software endstops.
  11362. *
  11363. * For DELTA/SCARA the XY constraint is based on the smallest
  11364. * radius within the set software endstops.
  11365. */
  11366. void clamp_to_software_endstops(float target[XYZ]) {
  11367. if (!soft_endstops_enabled) return;
  11368. #if IS_KINEMATIC
  11369. const float dist_2 = HYPOT2(target[X_AXIS], target[Y_AXIS]);
  11370. if (dist_2 > soft_endstop_radius_2) {
  11371. const float ratio = soft_endstop_radius / SQRT(dist_2); // 200 / 300 = 0.66
  11372. target[X_AXIS] *= ratio;
  11373. target[Y_AXIS] *= ratio;
  11374. }
  11375. #else
  11376. #if ENABLED(MIN_SOFTWARE_ENDSTOP_X)
  11377. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  11378. #endif
  11379. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Y)
  11380. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  11381. #endif
  11382. #if ENABLED(MAX_SOFTWARE_ENDSTOP_X)
  11383. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  11384. #endif
  11385. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Y)
  11386. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  11387. #endif
  11388. #endif
  11389. #if ENABLED(MIN_SOFTWARE_ENDSTOP_Z)
  11390. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  11391. #endif
  11392. #if ENABLED(MAX_SOFTWARE_ENDSTOP_Z)
  11393. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  11394. #endif
  11395. }
  11396. #endif
  11397. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11398. // Get the Z adjustment for non-linear bed leveling
  11399. float bilinear_z_offset(const float raw[XYZ]) {
  11400. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  11401. last_x = -999.999, last_y = -999.999;
  11402. // Whole units for the grid line indices. Constrained within bounds.
  11403. static int8_t gridx, gridy, nextx, nexty,
  11404. last_gridx = -99, last_gridy = -99;
  11405. // XY relative to the probed area
  11406. const float rx = raw[X_AXIS] - bilinear_start[X_AXIS],
  11407. ry = raw[Y_AXIS] - bilinear_start[Y_AXIS];
  11408. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  11409. // Keep using the last grid box
  11410. #define FAR_EDGE_OR_BOX 2
  11411. #else
  11412. // Just use the grid far edge
  11413. #define FAR_EDGE_OR_BOX 1
  11414. #endif
  11415. if (last_x != rx) {
  11416. last_x = rx;
  11417. ratio_x = rx * ABL_BG_FACTOR(X_AXIS);
  11418. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  11419. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  11420. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11421. // Beyond the grid maintain height at grid edges
  11422. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  11423. #endif
  11424. gridx = gx;
  11425. nextx = MIN(gridx + 1, ABL_BG_POINTS_X - 1);
  11426. }
  11427. if (last_y != ry || last_gridx != gridx) {
  11428. if (last_y != ry) {
  11429. last_y = ry;
  11430. ratio_y = ry * ABL_BG_FACTOR(Y_AXIS);
  11431. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  11432. ratio_y -= gy;
  11433. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  11434. // Beyond the grid maintain height at grid edges
  11435. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  11436. #endif
  11437. gridy = gy;
  11438. nexty = MIN(gridy + 1, ABL_BG_POINTS_Y - 1);
  11439. }
  11440. if (last_gridx != gridx || last_gridy != gridy) {
  11441. last_gridx = gridx;
  11442. last_gridy = gridy;
  11443. // Z at the box corners
  11444. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  11445. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  11446. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  11447. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  11448. }
  11449. // Bilinear interpolate. Needed since ry or gridx has changed.
  11450. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  11451. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  11452. D = R - L;
  11453. }
  11454. const float offset = L + ratio_x * D; // the offset almost always changes
  11455. /*
  11456. static float last_offset = 0;
  11457. if (ABS(last_offset - offset) > 0.2) {
  11458. SERIAL_ECHOPGM("Sudden Shift at ");
  11459. SERIAL_ECHOPAIR("x=", rx);
  11460. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  11461. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  11462. SERIAL_ECHOPAIR(" y=", ry);
  11463. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  11464. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  11465. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  11466. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  11467. SERIAL_ECHOPAIR(" z1=", z1);
  11468. SERIAL_ECHOPAIR(" z2=", z2);
  11469. SERIAL_ECHOPAIR(" z3=", z3);
  11470. SERIAL_ECHOLNPAIR(" z4=", z4);
  11471. SERIAL_ECHOPAIR(" L=", L);
  11472. SERIAL_ECHOPAIR(" R=", R);
  11473. SERIAL_ECHOLNPAIR(" offset=", offset);
  11474. }
  11475. last_offset = offset;
  11476. //*/
  11477. return offset;
  11478. }
  11479. #endif // AUTO_BED_LEVELING_BILINEAR
  11480. #if ENABLED(DELTA)
  11481. /**
  11482. * Recalculate factors used for delta kinematics whenever
  11483. * settings have been changed (e.g., by M665).
  11484. */
  11485. void recalc_delta_settings() {
  11486. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  11487. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  11488. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]); // front left tower
  11489. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (delta_radius + trt[A_AXIS]);
  11490. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]); // front right tower
  11491. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + trt[B_AXIS]);
  11492. delta_tower[C_AXIS][X_AXIS] = cos(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]); // back middle tower
  11493. delta_tower[C_AXIS][Y_AXIS] = sin(RADIANS( 90 + delta_tower_angle_trim[C_AXIS])) * (delta_radius + trt[C_AXIS]);
  11494. delta_diagonal_rod_2_tower[A_AXIS] = sq(delta_diagonal_rod + drt[A_AXIS]);
  11495. delta_diagonal_rod_2_tower[B_AXIS] = sq(delta_diagonal_rod + drt[B_AXIS]);
  11496. delta_diagonal_rod_2_tower[C_AXIS] = sq(delta_diagonal_rod + drt[C_AXIS]);
  11497. update_software_endstops(Z_AXIS);
  11498. axis_homed = 0;
  11499. }
  11500. /**
  11501. * Delta Inverse Kinematics
  11502. *
  11503. * Calculate the tower positions for a given machine
  11504. * position, storing the result in the delta[] array.
  11505. *
  11506. * This is an expensive calculation, requiring 3 square
  11507. * roots per segmented linear move, and strains the limits
  11508. * of a Mega2560 with a Graphical Display.
  11509. *
  11510. * Suggested optimizations include:
  11511. *
  11512. * - Disable the home_offset (M206) and/or position_shift (G92)
  11513. * features to remove up to 12 float additions.
  11514. */
  11515. #define DELTA_DEBUG(VAR) do { \
  11516. SERIAL_ECHOPAIR("cartesian X:", VAR[X_AXIS]); \
  11517. SERIAL_ECHOPAIR(" Y:", VAR[Y_AXIS]); \
  11518. SERIAL_ECHOLNPAIR(" Z:", VAR[Z_AXIS]); \
  11519. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  11520. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  11521. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  11522. }while(0)
  11523. void inverse_kinematics(const float raw[XYZ]) {
  11524. #if HOTENDS > 1
  11525. // Delta hotend offsets must be applied in Cartesian space with no "spoofing"
  11526. const float pos[XYZ] = {
  11527. raw[X_AXIS] - hotend_offset[X_AXIS][active_extruder],
  11528. raw[Y_AXIS] - hotend_offset[Y_AXIS][active_extruder],
  11529. raw[Z_AXIS]
  11530. };
  11531. DELTA_IK(pos);
  11532. //DELTA_DEBUG(pos);
  11533. #else
  11534. DELTA_IK(raw);
  11535. //DELTA_DEBUG(raw);
  11536. #endif
  11537. }
  11538. /**
  11539. * Calculate the highest Z position where the
  11540. * effector has the full range of XY motion.
  11541. */
  11542. float delta_safe_distance_from_top() {
  11543. float cartesian[XYZ] = { 0, 0, 0 };
  11544. inverse_kinematics(cartesian);
  11545. const float centered_extent = delta[A_AXIS];
  11546. cartesian[Y_AXIS] = DELTA_PRINTABLE_RADIUS;
  11547. inverse_kinematics(cartesian);
  11548. return ABS(centered_extent - delta[A_AXIS]);
  11549. }
  11550. /**
  11551. * Delta Forward Kinematics
  11552. *
  11553. * See the Wikipedia article "Trilateration"
  11554. * https://en.wikipedia.org/wiki/Trilateration
  11555. *
  11556. * Establish a new coordinate system in the plane of the
  11557. * three carriage points. This system has its origin at
  11558. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  11559. * plane with a Z component of zero.
  11560. * We will define unit vectors in this coordinate system
  11561. * in our original coordinate system. Then when we calculate
  11562. * the Xnew, Ynew and Znew values, we can translate back into
  11563. * the original system by moving along those unit vectors
  11564. * by the corresponding values.
  11565. *
  11566. * Variable names matched to Marlin, c-version, and avoid the
  11567. * use of any vector library.
  11568. *
  11569. * by Andreas Hardtung 2016-06-07
  11570. * based on a Java function from "Delta Robot Kinematics V3"
  11571. * by Steve Graves
  11572. *
  11573. * The result is stored in the cartes[] array.
  11574. */
  11575. void forward_kinematics_DELTA(const float &z1, const float &z2, const float &z3) {
  11576. // Create a vector in old coordinates along x axis of new coordinate
  11577. const float p12[] = {
  11578. delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11579. delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11580. z2 - z1
  11581. },
  11582. // Get the reciprocal of Magnitude of vector.
  11583. d2 = sq(p12[0]) + sq(p12[1]) + sq(p12[2]), inv_d = RSQRT(d2),
  11584. // Create unit vector by multiplying by the inverse of the magnitude.
  11585. ex[3] = { p12[0] * inv_d, p12[1] * inv_d, p12[2] * inv_d },
  11586. // Get the vector from the origin of the new system to the third point.
  11587. p13[3] = {
  11588. delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS],
  11589. delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS],
  11590. z3 - z1
  11591. },
  11592. // Use the dot product to find the component of this vector on the X axis.
  11593. i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2],
  11594. // Create a vector along the x axis that represents the x component of p13.
  11595. iex[] = { ex[0] * i, ex[1] * i, ex[2] * i };
  11596. // Subtract the X component from the original vector leaving only Y. We use the
  11597. // variable that will be the unit vector after we scale it.
  11598. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  11599. // The magnitude and the inverse of the magnitude of Y component
  11600. const float j2 = sq(ey[0]) + sq(ey[1]) + sq(ey[2]), inv_j = RSQRT(j2);
  11601. // Convert to a unit vector
  11602. ey[0] *= inv_j; ey[1] *= inv_j; ey[2] *= inv_j;
  11603. // The cross product of the unit x and y is the unit z
  11604. // float[] ez = vectorCrossProd(ex, ey);
  11605. const float ez[3] = {
  11606. ex[1] * ey[2] - ex[2] * ey[1],
  11607. ex[2] * ey[0] - ex[0] * ey[2],
  11608. ex[0] * ey[1] - ex[1] * ey[0]
  11609. },
  11610. // We now have the d, i and j values defined in Wikipedia.
  11611. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  11612. Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + d2) * inv_d * 0.5,
  11613. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + sq(i) + j2) * 0.5 - i * Xnew) * inv_j,
  11614. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  11615. // Start from the origin of the old coordinates and add vectors in the
  11616. // old coords that represent the Xnew, Ynew and Znew to find the point
  11617. // in the old system.
  11618. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  11619. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  11620. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  11621. }
  11622. void forward_kinematics_DELTA(const float (&point)[ABC]) {
  11623. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  11624. }
  11625. #endif // DELTA
  11626. #if ENABLED(HANGPRINTER)
  11627. /**
  11628. * Recalculate factors used for hangprinter kinematics whenever
  11629. * settings have been changed (e.g., by M665).
  11630. */
  11631. void recalc_hangprinter_settings(){
  11632. HANGPRINTER_IK_ORIGIN(line_lengths_origin);
  11633. #if ENABLED(LINE_BUILDUP_COMPENSATION_FEATURE)
  11634. const uint8_t mech_adv_tmp[MOV_AXIS] = MECHANICAL_ADVANTAGE,
  11635. actn_pts_tmp[MOV_AXIS] = ACTION_POINTS;
  11636. const uint16_t m_g_t_tmp[MOV_AXIS] = MOTOR_GEAR_TEETH,
  11637. s_g_t_tmp[MOV_AXIS] = SPOOL_GEAR_TEETH;
  11638. const float mnt_l_tmp[MOV_AXIS] = MOUNTED_LINE;
  11639. float s_r2_tmp[MOV_AXIS] = SPOOL_RADII,
  11640. steps_per_unit_times_r_tmp[MOV_AXIS];
  11641. uint8_t nr_lines_dir_tmp[MOV_AXIS];
  11642. LOOP_MOV_AXIS(i){
  11643. steps_per_unit_times_r_tmp[i] = (float(mech_adv_tmp[i])*STEPS_PER_MOTOR_REVOLUTION*s_g_t_tmp[i])/(2*M_PI*m_g_t_tmp[i]);
  11644. nr_lines_dir_tmp[i] = mech_adv_tmp[i]*actn_pts_tmp[i];
  11645. s_r2_tmp[i] *= s_r2_tmp[i];
  11646. planner.k2[i] = -(float)nr_lines_dir_tmp[i]*SPOOL_BUILDUP_FACTOR;
  11647. planner.k0[i] = 2.0*steps_per_unit_times_r_tmp[i]/planner.k2[i];
  11648. }
  11649. // Assumes spools are mounted near D-anchor in ceiling
  11650. #define HYP3D(x,y,z) SQRT(sq(x) + sq(y) + sq(z))
  11651. float line_on_spool_origin_tmp[MOV_AXIS];
  11652. line_on_spool_origin_tmp[A_AXIS] = actn_pts_tmp[A_AXIS] * mnt_l_tmp[A_AXIS]
  11653. - actn_pts_tmp[A_AXIS] * HYPOT(anchor_A_y, anchor_D_z - anchor_A_z)
  11654. - nr_lines_dir_tmp[A_AXIS] * line_lengths_origin[A_AXIS];
  11655. line_on_spool_origin_tmp[B_AXIS] = actn_pts_tmp[B_AXIS] * mnt_l_tmp[B_AXIS]
  11656. - actn_pts_tmp[B_AXIS] * HYP3D(anchor_B_x, anchor_B_y, anchor_D_z - anchor_B_z)
  11657. - nr_lines_dir_tmp[B_AXIS] * line_lengths_origin[B_AXIS];
  11658. line_on_spool_origin_tmp[C_AXIS] = actn_pts_tmp[C_AXIS] * mnt_l_tmp[C_AXIS]
  11659. - actn_pts_tmp[C_AXIS] * HYP3D(anchor_C_x, anchor_C_y, anchor_D_z - anchor_C_z)
  11660. - nr_lines_dir_tmp[C_AXIS] * line_lengths_origin[C_AXIS];
  11661. line_on_spool_origin_tmp[D_AXIS] = actn_pts_tmp[D_AXIS] * mnt_l_tmp[D_AXIS]
  11662. - nr_lines_dir_tmp[D_AXIS] * line_lengths_origin[D_AXIS];
  11663. LOOP_MOV_AXIS(i) {
  11664. planner.axis_steps_per_mm[i] = steps_per_unit_times_r_tmp[i] /
  11665. SQRT((SPOOL_BUILDUP_FACTOR) * line_on_spool_origin_tmp[i] + s_r2_tmp[i]);
  11666. planner.k1[i] = (SPOOL_BUILDUP_FACTOR) *
  11667. (line_on_spool_origin_tmp[i] + nr_lines_dir_tmp[i] * line_lengths_origin[i]) + s_r2_tmp[i];
  11668. planner.sqrtk1[i] = SQRT(planner.k1[i]);
  11669. }
  11670. planner.axis_steps_per_mm[E_AXIS] = DEFAULT_E_AXIS_STEPS_PER_UNIT;
  11671. #endif // LINE_BUILDUP_COMPENSATION_FEATURE
  11672. SYNC_PLAN_POSITION_KINEMATIC(); // recalcs line lengths in case anchor was moved
  11673. }
  11674. /**
  11675. * Hangprinter inverse kinematics
  11676. */
  11677. void inverse_kinematics(const float raw[XYZ]) {
  11678. HANGPRINTER_IK(raw);
  11679. }
  11680. /**
  11681. * Hangprinter forward kinematics
  11682. * Basic idea is to subtract squared line lengths to get linear equations.
  11683. * Subtracting d*d from a*a, b*b, and c*c gives the cleanest derivation:
  11684. *
  11685. * a*a - d*d = k1 + k2*y + k3*z <---- a line (I)
  11686. * b*b - d*d = k4 + k5*x + k6*y + k7*z <---- a plane (II)
  11687. * c*c - d*d = k8 + k9*x + k10*y + k11*z <---- a plane (III)
  11688. *
  11689. * Use (I) to reduce (II) and (III) into lines. Eliminate y, keep z.
  11690. *
  11691. * (II): b*b - d*d = k12 + k13*x + k14*z
  11692. * <=> x = k0b + k1b*z, <---- a line (IV)
  11693. *
  11694. * (III): c*c - d*d = k15 + k16*x + k17*z
  11695. * <=> x = k0c + k1c*z, <---- a line (V)
  11696. *
  11697. * where k1, k2, ..., k17, k0b, k0c, k1b, and k1c are known constants.
  11698. *
  11699. * These two straight lines are not parallel, so they will cross in exactly one point.
  11700. * Find z by setting (IV) = (V)
  11701. * Find x by inserting z into (V)
  11702. * Find y by inserting z into (I)
  11703. *
  11704. * Warning: truncation errors will typically be in the order of a few tens of microns.
  11705. */
  11706. void forward_kinematics_HANGPRINTER(float a, float b, float c, float d){
  11707. const float Asq = sq(anchor_A_y) + sq(anchor_A_z),
  11708. Bsq = sq(anchor_B_x) + sq(anchor_B_y) + sq(anchor_B_z),
  11709. Csq = sq(anchor_C_x) + sq(anchor_C_y) + sq(anchor_C_z),
  11710. Dsq = sq(anchor_D_z),
  11711. aa = sq(a),
  11712. dd = sq(d),
  11713. k0b = (-sq(b) + Bsq - Dsq + dd) / (2.0 * anchor_B_x) + (anchor_B_y / (2.0 * anchor_A_y * anchor_B_x)) * (Dsq - Asq + aa - dd),
  11714. k0c = (-sq(c) + Csq - Dsq + dd) / (2.0 * anchor_C_x) + (anchor_C_y / (2.0 * anchor_A_y * anchor_C_x)) * (Dsq - Asq + aa - dd),
  11715. k1b = (anchor_B_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_B_x) + (anchor_D_z - anchor_B_z) / anchor_B_x,
  11716. k1c = (anchor_C_y * (anchor_A_z - anchor_D_z)) / (anchor_A_y * anchor_C_x) + (anchor_D_z - anchor_C_z) / anchor_C_x;
  11717. cartes[Z_AXIS] = (k0b - k0c) / (k1c - k1b);
  11718. cartes[X_AXIS] = k0c + k1c * cartes[Z_AXIS];
  11719. cartes[Y_AXIS] = (Asq - Dsq - aa + dd) / (2.0 * anchor_A_y) + ((anchor_D_z - anchor_A_z) / anchor_A_y) * cartes[Z_AXIS];
  11720. }
  11721. #endif // HANGPRINTER
  11722. /**
  11723. * Get the stepper positions in the cartes[] array.
  11724. * Forward kinematics are applied for DELTA and SCARA.
  11725. *
  11726. * The result is in the current coordinate space with
  11727. * leveling applied. The coordinates need to be run through
  11728. * unapply_leveling to obtain machine coordinates suitable
  11729. * for current_position, etc.
  11730. */
  11731. void get_cartesian_from_steppers() {
  11732. #if ENABLED(DELTA)
  11733. forward_kinematics_DELTA(
  11734. planner.get_axis_position_mm(A_AXIS),
  11735. planner.get_axis_position_mm(B_AXIS),
  11736. planner.get_axis_position_mm(C_AXIS)
  11737. );
  11738. #elif ENABLED(HANGPRINTER)
  11739. forward_kinematics_HANGPRINTER(
  11740. planner.get_axis_position_mm(A_AXIS),
  11741. planner.get_axis_position_mm(B_AXIS),
  11742. planner.get_axis_position_mm(C_AXIS),
  11743. planner.get_axis_position_mm(D_AXIS)
  11744. );
  11745. #else
  11746. #if IS_SCARA
  11747. forward_kinematics_SCARA(
  11748. planner.get_axis_position_degrees(A_AXIS),
  11749. planner.get_axis_position_degrees(B_AXIS)
  11750. );
  11751. #else
  11752. cartes[X_AXIS] = planner.get_axis_position_mm(X_AXIS);
  11753. cartes[Y_AXIS] = planner.get_axis_position_mm(Y_AXIS);
  11754. #endif
  11755. cartes[Z_AXIS] = planner.get_axis_position_mm(Z_AXIS);
  11756. #endif
  11757. }
  11758. /**
  11759. * Set the current_position for an axis based on
  11760. * the stepper positions, removing any leveling that
  11761. * may have been applied.
  11762. *
  11763. * To prevent small shifts in axis position always call
  11764. * SYNC_PLAN_POSITION_KINEMATIC after updating axes with this.
  11765. *
  11766. * To keep hosts in sync, always call report_current_position
  11767. * after updating the current_position.
  11768. */
  11769. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  11770. get_cartesian_from_steppers();
  11771. #if PLANNER_LEVELING
  11772. planner.unapply_leveling(cartes);
  11773. #endif
  11774. if (axis == ALL_AXES)
  11775. COPY(current_position, cartes);
  11776. else
  11777. current_position[axis] = cartes[axis];
  11778. }
  11779. #if IS_CARTESIAN
  11780. #if ENABLED(SEGMENT_LEVELED_MOVES)
  11781. /**
  11782. * Prepare a segmented move on a CARTESIAN setup.
  11783. *
  11784. * This calls planner.buffer_line several times, adding
  11785. * small incremental moves. This allows the planner to
  11786. * apply more detailed bed leveling to the full move.
  11787. */
  11788. inline void segmented_line_to_destination(const float &fr_mm_s, const float segment_size=LEVELED_SEGMENT_LENGTH) {
  11789. const float xdiff = destination[X_AXIS] - current_position[X_AXIS],
  11790. ydiff = destination[Y_AXIS] - current_position[Y_AXIS];
  11791. // If the move is only in Z/E don't split up the move
  11792. if (!xdiff && !ydiff) {
  11793. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder);
  11794. return;
  11795. }
  11796. // Remaining cartesian distances
  11797. const float zdiff = destination[Z_AXIS] - current_position[Z_AXIS],
  11798. ediff = destination[E_CART] - current_position[E_CART];
  11799. // Get the linear distance in XYZ
  11800. // If the move is very short, check the E move distance
  11801. // No E move either? Game over.
  11802. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  11803. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  11804. if (UNEAR_ZERO(cartesian_mm)) return;
  11805. // The length divided by the segment size
  11806. // At least one segment is required
  11807. uint16_t segments = cartesian_mm / segment_size;
  11808. NOLESS(segments, 1);
  11809. // The approximate length of each segment
  11810. const float inv_segments = 1.0f / float(segments),
  11811. cartesian_segment_mm = cartesian_mm * inv_segments,
  11812. segment_distance[XYZE] = {
  11813. xdiff * inv_segments,
  11814. ydiff * inv_segments,
  11815. zdiff * inv_segments,
  11816. ediff * inv_segments
  11817. };
  11818. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  11819. // SERIAL_ECHOLNPAIR(" segments=", segments);
  11820. // SERIAL_ECHOLNPAIR(" segment_mm=", cartesian_segment_mm);
  11821. // Get the raw current position as starting point
  11822. float raw[XYZE];
  11823. COPY(raw, current_position);
  11824. // Calculate and execute the segments
  11825. while (--segments) {
  11826. static millis_t next_idle_ms = millis() + 200UL;
  11827. thermalManager.manage_heater(); // This returns immediately if not really needed.
  11828. if (ELAPSED(millis(), next_idle_ms)) {
  11829. next_idle_ms = millis() + 200UL;
  11830. idle();
  11831. }
  11832. LOOP_XYZE(i) raw[i] += segment_distance[i];
  11833. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder, cartesian_segment_mm))
  11834. break;
  11835. }
  11836. // Since segment_distance is only approximate,
  11837. // the final move must be to the exact destination.
  11838. planner.buffer_line_kinematic(destination, fr_mm_s, active_extruder, cartesian_segment_mm);
  11839. }
  11840. #elif ENABLED(MESH_BED_LEVELING)
  11841. /**
  11842. * Prepare a mesh-leveled linear move in a Cartesian setup,
  11843. * splitting the move where it crosses mesh borders.
  11844. */
  11845. void mesh_line_to_destination(const float fr_mm_s, uint8_t x_splits=0xFF, uint8_t y_splits=0xFF) {
  11846. // Get current and destination cells for this line
  11847. int cx1 = mbl.cell_index_x(current_position[X_AXIS]),
  11848. cy1 = mbl.cell_index_y(current_position[Y_AXIS]),
  11849. cx2 = mbl.cell_index_x(destination[X_AXIS]),
  11850. cy2 = mbl.cell_index_y(destination[Y_AXIS]);
  11851. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  11852. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  11853. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  11854. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  11855. // Start and end in the same cell? No split needed.
  11856. if (cx1 == cx2 && cy1 == cy2) {
  11857. buffer_line_to_destination(fr_mm_s);
  11858. set_current_from_destination();
  11859. return;
  11860. }
  11861. #define MBL_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11862. #define MBL_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11863. float normalized_dist, end[XYZE];
  11864. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11865. // Crosses on the X and not already split on this X?
  11866. // The x_splits flags are insurance against rounding errors.
  11867. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11868. // Split on the X grid line
  11869. CBI(x_splits, gcx);
  11870. COPY(end, destination);
  11871. destination[X_AXIS] = mbl.index_to_xpos[gcx];
  11872. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11873. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  11874. }
  11875. // Crosses on the Y and not already split on this Y?
  11876. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11877. // Split on the Y grid line
  11878. CBI(y_splits, gcy);
  11879. COPY(end, destination);
  11880. destination[Y_AXIS] = mbl.index_to_ypos[gcy];
  11881. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11882. destination[X_AXIS] = MBL_SEGMENT_END(X);
  11883. }
  11884. else {
  11885. // Must already have been split on these border(s)
  11886. buffer_line_to_destination(fr_mm_s);
  11887. set_current_from_destination();
  11888. return;
  11889. }
  11890. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  11891. destination[E_CART] = MBL_SEGMENT_END_E;
  11892. // Do the split and look for more borders
  11893. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11894. // Restore destination from stack
  11895. COPY(destination, end);
  11896. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  11897. }
  11898. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  11899. #define CELL_INDEX(A,V) ((V - bilinear_start[_AXIS(A)]) * ABL_BG_FACTOR(_AXIS(A)))
  11900. /**
  11901. * Prepare a bilinear-leveled linear move on Cartesian,
  11902. * splitting the move where it crosses grid borders.
  11903. */
  11904. void bilinear_line_to_destination(const float fr_mm_s, uint16_t x_splits=0xFFFF, uint16_t y_splits=0xFFFF) {
  11905. // Get current and destination cells for this line
  11906. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  11907. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  11908. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  11909. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  11910. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  11911. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  11912. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  11913. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  11914. // Start and end in the same cell? No split needed.
  11915. if (cx1 == cx2 && cy1 == cy2) {
  11916. buffer_line_to_destination(fr_mm_s);
  11917. set_current_from_destination();
  11918. return;
  11919. }
  11920. #define LINE_SEGMENT_END(A) (current_position[_AXIS(A)] + (destination[_AXIS(A)] - current_position[_AXIS(A)]) * normalized_dist)
  11921. #define LINE_SEGMENT_END_E (current_position[E_CART] + (destination[E_CART] - current_position[E_CART]) * normalized_dist)
  11922. float normalized_dist, end[XYZE];
  11923. const int8_t gcx = MAX(cx1, cx2), gcy = MAX(cy1, cy2);
  11924. // Crosses on the X and not already split on this X?
  11925. // The x_splits flags are insurance against rounding errors.
  11926. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  11927. // Split on the X grid line
  11928. CBI(x_splits, gcx);
  11929. COPY(end, destination);
  11930. destination[X_AXIS] = bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx;
  11931. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  11932. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  11933. }
  11934. // Crosses on the Y and not already split on this Y?
  11935. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  11936. // Split on the Y grid line
  11937. CBI(y_splits, gcy);
  11938. COPY(end, destination);
  11939. destination[Y_AXIS] = bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy;
  11940. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  11941. destination[X_AXIS] = LINE_SEGMENT_END(X);
  11942. }
  11943. else {
  11944. // Must already have been split on these border(s)
  11945. buffer_line_to_destination(fr_mm_s);
  11946. set_current_from_destination();
  11947. return;
  11948. }
  11949. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  11950. destination[E_CART] = LINE_SEGMENT_END_E;
  11951. // Do the split and look for more borders
  11952. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11953. // Restore destination from stack
  11954. COPY(destination, end);
  11955. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  11956. }
  11957. #endif // AUTO_BED_LEVELING_BILINEAR
  11958. #endif // IS_CARTESIAN
  11959. #if !UBL_SEGMENTED
  11960. #if IS_KINEMATIC
  11961. #if IS_SCARA
  11962. /**
  11963. * Before raising this value, use M665 S[seg_per_sec] to decrease
  11964. * the number of segments-per-second. Default is 200. Some deltas
  11965. * do better with 160 or lower. It would be good to know how many
  11966. * segments-per-second are actually possible for SCARA on AVR.
  11967. *
  11968. * Longer segments result in less kinematic overhead
  11969. * but may produce jagged lines. Try 0.5mm, 1.0mm, and 2.0mm
  11970. * and compare the difference.
  11971. */
  11972. #define SCARA_MIN_SEGMENT_LENGTH 0.5f
  11973. #endif
  11974. /**
  11975. * Prepare a linear move in a DELTA, SCARA or HANGPRINTER setup.
  11976. *
  11977. * This calls planner.buffer_line several times, adding
  11978. * small incremental moves for DELTA, SCARA or HANGPRINTER.
  11979. *
  11980. * For Unified Bed Leveling (Delta or Segmented Cartesian)
  11981. * the ubl.prepare_segmented_line_to method replaces this.
  11982. */
  11983. inline bool prepare_kinematic_move_to(const float (&rtarget)[XYZE]) {
  11984. // Get the top feedrate of the move in the XY plane
  11985. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  11986. const float xdiff = rtarget[X_AXIS] - current_position[X_AXIS],
  11987. ydiff = rtarget[Y_AXIS] - current_position[Y_AXIS]
  11988. #if ENABLED(HANGPRINTER)
  11989. , zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS]
  11990. #endif
  11991. ;
  11992. // If the move is only in Z/E (for Hangprinter only in E) don't split up the move
  11993. if (!xdiff && !ydiff
  11994. #if ENABLED(HANGPRINTER)
  11995. && !zdiff
  11996. #endif
  11997. ) {
  11998. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder);
  11999. return false; // caller will update current_position
  12000. }
  12001. // Fail if attempting move outside printable radius
  12002. if (!position_is_reachable(rtarget[X_AXIS], rtarget[Y_AXIS])) return true;
  12003. // Remaining cartesian distances
  12004. const float
  12005. #if DISABLED(HANGPRINTER)
  12006. zdiff = rtarget[Z_AXIS] - current_position[Z_AXIS],
  12007. #endif
  12008. ediff = rtarget[E_CART] - current_position[E_CART];
  12009. // Get the linear distance in XYZ
  12010. // If the move is very short, check the E move distance
  12011. // No E move either? Game over.
  12012. float cartesian_mm = SQRT(sq(xdiff) + sq(ydiff) + sq(zdiff));
  12013. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = ABS(ediff);
  12014. if (UNEAR_ZERO(cartesian_mm)) return true;
  12015. // Minimum number of seconds to move the given distance
  12016. const float seconds = cartesian_mm / _feedrate_mm_s;
  12017. // The number of segments-per-second times the duration
  12018. // gives the number of segments
  12019. uint16_t segments = delta_segments_per_second * seconds;
  12020. // For SCARA enforce a minimum segment size
  12021. #if IS_SCARA
  12022. NOMORE(segments, cartesian_mm * (1.0f / float(SCARA_MIN_SEGMENT_LENGTH)));
  12023. #endif
  12024. // At least one segment is required
  12025. NOLESS(segments, 1);
  12026. // The approximate length of each segment
  12027. const float inv_segments = 1.0f / float(segments),
  12028. segment_distance[XYZE] = {
  12029. xdiff * inv_segments,
  12030. ydiff * inv_segments,
  12031. zdiff * inv_segments,
  12032. ediff * inv_segments
  12033. };
  12034. #if !HAS_FEEDRATE_SCALING
  12035. const float cartesian_segment_mm = cartesian_mm * inv_segments;
  12036. #endif
  12037. /*
  12038. SERIAL_ECHOPAIR("mm=", cartesian_mm);
  12039. SERIAL_ECHOPAIR(" seconds=", seconds);
  12040. SERIAL_ECHOPAIR(" segments=", segments);
  12041. #if !HAS_FEEDRATE_SCALING
  12042. SERIAL_ECHOPAIR(" segment_mm=", cartesian_segment_mm);
  12043. #endif
  12044. SERIAL_EOL();
  12045. //*/
  12046. #if HAS_FEEDRATE_SCALING
  12047. // SCARA needs to scale the feed rate from mm/s to degrees/s
  12048. // i.e., Complete the angular vector in the given time.
  12049. const float segment_length = cartesian_mm * inv_segments,
  12050. inv_segment_length = 1.0f / segment_length, // 1/mm/segs
  12051. inverse_secs = inv_segment_length * _feedrate_mm_s;
  12052. float oldA = planner.position_float[A_AXIS],
  12053. oldB = planner.position_float[B_AXIS]
  12054. #if ENABLED(DELTA_FEEDRATE_SCALING)
  12055. , oldC = planner.position_float[C_AXIS]
  12056. #endif
  12057. ;
  12058. /*
  12059. SERIAL_ECHOPGM("Scaled kinematic move: ");
  12060. SERIAL_ECHOPAIR(" segment_length (inv)=", segment_length);
  12061. SERIAL_ECHOPAIR(" (", inv_segment_length);
  12062. SERIAL_ECHOPAIR(") _feedrate_mm_s=", _feedrate_mm_s);
  12063. SERIAL_ECHOPAIR(" inverse_secs=", inverse_secs);
  12064. SERIAL_ECHOPAIR(" oldA=", oldA);
  12065. SERIAL_ECHOPAIR(" oldB=", oldB);
  12066. #if ENABLED(DELTA_FEEDRATE_SCALING)
  12067. SERIAL_ECHOPAIR(" oldC=", oldC);
  12068. #endif
  12069. SERIAL_EOL();
  12070. safe_delay(5);
  12071. //*/
  12072. #endif
  12073. // Get the current position as starting point
  12074. float raw[XYZE];
  12075. COPY(raw, current_position);
  12076. // Calculate and execute the segments
  12077. while (--segments) {
  12078. static millis_t next_idle_ms = millis() + 200UL;
  12079. thermalManager.manage_heater(); // This returns immediately if not really needed.
  12080. if (ELAPSED(millis(), next_idle_ms)) {
  12081. next_idle_ms = millis() + 200UL;
  12082. idle();
  12083. }
  12084. LOOP_XYZE(i) raw[i] += segment_distance[i];
  12085. #if ENABLED(DELTA) && HOTENDS < 2
  12086. DELTA_IK(raw); // Delta can inline its kinematics
  12087. #elif ENABLED(HANGPRINTER)
  12088. HANGPRINTER_IK(raw); // Modifies line_lengths[ABCD]
  12089. #else
  12090. inverse_kinematics(raw);
  12091. #endif
  12092. ADJUST_DELTA(raw); // Adjust Z if bed leveling is enabled
  12093. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12094. // For SCARA scale the feed rate from mm/s to degrees/s
  12095. // i.e., Complete the angular vector in the given time.
  12096. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, segment_length))
  12097. break;
  12098. /*
  12099. SERIAL_ECHO(segments);
  12100. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  12101. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  12102. SERIAL_ECHOLNPAIR(" F", HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs * 60);
  12103. safe_delay(5);
  12104. //*/
  12105. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  12106. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12107. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  12108. // i.e., Complete the linear vector in the given time.
  12109. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, segment_length))
  12110. break;
  12111. /*
  12112. SERIAL_ECHO(segments);
  12113. SERIAL_ECHOPAIR(": X=", raw[X_AXIS]); SERIAL_ECHOPAIR(" Y=", raw[Y_AXIS]);
  12114. SERIAL_ECHOPAIR(" A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  12115. SERIAL_ECHOLNPAIR(" F", SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs * 60);
  12116. safe_delay(5);
  12117. //*/
  12118. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  12119. #elif ENABLED(HANGPRINTER)
  12120. if (!planner.buffer_line(line_lengths[A_AXIS], line_lengths[B_AXIS], line_lengths[C_AXIS], line_lengths[D_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  12121. break;
  12122. #else
  12123. if (!planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_CART], _feedrate_mm_s, active_extruder, cartesian_segment_mm))
  12124. break;
  12125. #endif
  12126. }
  12127. // Ensure last segment arrives at target location.
  12128. #if HAS_FEEDRATE_SCALING
  12129. inverse_kinematics(rtarget);
  12130. ADJUST_DELTA(rtarget);
  12131. #endif
  12132. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12133. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  12134. if (diff2) {
  12135. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], rtarget[Z_AXIS], rtarget[E_CART], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  12136. /*
  12137. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]);
  12138. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB);
  12139. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  12140. SERIAL_EOL();
  12141. safe_delay(5);
  12142. //*/
  12143. }
  12144. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12145. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  12146. if (diff2) {
  12147. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], rtarget[E_AXIS], SQRT(diff2) * inverse_secs, active_extruder, segment_length);
  12148. /*
  12149. SERIAL_ECHOPAIR("final: A=", delta[A_AXIS]); SERIAL_ECHOPAIR(" B=", delta[B_AXIS]); SERIAL_ECHOPAIR(" C=", delta[C_AXIS]);
  12150. SERIAL_ECHOPAIR(" adiff=", delta[A_AXIS] - oldA); SERIAL_ECHOPAIR(" bdiff=", delta[B_AXIS] - oldB); SERIAL_ECHOPAIR(" cdiff=", delta[C_AXIS] - oldC);
  12151. SERIAL_ECHOLNPAIR(" F", SQRT(diff2) * inverse_secs * 60);
  12152. SERIAL_EOL();
  12153. safe_delay(5);
  12154. //*/
  12155. }
  12156. #else
  12157. planner.buffer_line_kinematic(rtarget, _feedrate_mm_s, active_extruder, cartesian_segment_mm);
  12158. #endif
  12159. return false; // caller will update current_position
  12160. }
  12161. #else // !IS_KINEMATIC
  12162. /**
  12163. * Prepare a linear move in a Cartesian setup.
  12164. *
  12165. * When a mesh-based leveling system is active, moves are segmented
  12166. * according to the configuration of the leveling system.
  12167. *
  12168. * Returns true if current_position[] was set to destination[]
  12169. */
  12170. inline bool prepare_move_to_destination_cartesian() {
  12171. #if HAS_MESH
  12172. if (planner.leveling_active && planner.leveling_active_at_z(destination[Z_AXIS])) {
  12173. #if ENABLED(AUTO_BED_LEVELING_UBL)
  12174. ubl.line_to_destination_cartesian(MMS_SCALED(feedrate_mm_s), active_extruder); // UBL's motion routine needs to know about
  12175. return true; // all moves, including Z-only moves.
  12176. #elif ENABLED(SEGMENT_LEVELED_MOVES)
  12177. segmented_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12178. return false; // caller will update current_position
  12179. #else
  12180. /**
  12181. * For MBL and ABL-BILINEAR only segment moves when X or Y are involved.
  12182. * Otherwise fall through to do a direct single move.
  12183. */
  12184. if (current_position[X_AXIS] != destination[X_AXIS] || current_position[Y_AXIS] != destination[Y_AXIS]) {
  12185. #if ENABLED(MESH_BED_LEVELING)
  12186. mesh_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12187. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  12188. bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12189. #endif
  12190. return true;
  12191. }
  12192. #endif
  12193. }
  12194. #endif // HAS_MESH
  12195. buffer_line_to_destination(MMS_SCALED(feedrate_mm_s));
  12196. return false; // caller will update current_position
  12197. }
  12198. #endif // !IS_KINEMATIC
  12199. #endif // !UBL_SEGMENTED
  12200. #if ENABLED(DUAL_X_CARRIAGE)
  12201. /**
  12202. * Unpark the carriage, if needed
  12203. */
  12204. inline bool dual_x_carriage_unpark() {
  12205. if (active_extruder_parked)
  12206. switch (dual_x_carriage_mode) {
  12207. case DXC_FULL_CONTROL_MODE: break;
  12208. case DXC_AUTO_PARK_MODE:
  12209. if (current_position[E_CART] == destination[E_CART]) {
  12210. // This is a travel move (with no extrusion)
  12211. // Skip it, but keep track of the current position
  12212. // (so it can be used as the start of the next non-travel move)
  12213. if (delayed_move_time != 0xFFFFFFFFUL) {
  12214. set_current_from_destination();
  12215. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  12216. delayed_move_time = millis();
  12217. return true;
  12218. }
  12219. }
  12220. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  12221. for (uint8_t i = 0; i < 3; i++)
  12222. if (!planner.buffer_line(
  12223. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  12224. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  12225. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  12226. current_position[E_CART],
  12227. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  12228. active_extruder)
  12229. ) break;
  12230. delayed_move_time = 0;
  12231. active_extruder_parked = false;
  12232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12233. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  12234. #endif
  12235. break;
  12236. case DXC_DUPLICATION_MODE:
  12237. if (active_extruder == 0) {
  12238. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12239. if (DEBUGGING(LEVELING)) {
  12240. SERIAL_ECHOPAIR("Set planner X", inactive_extruder_x_pos);
  12241. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  12242. }
  12243. #endif
  12244. // move duplicate extruder into correct duplication position.
  12245. planner.set_position_mm(inactive_extruder_x_pos, current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART]);
  12246. if (!planner.buffer_line(
  12247. current_position[X_AXIS] + duplicate_extruder_x_offset,
  12248. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_CART],
  12249. planner.max_feedrate_mm_s[X_AXIS], 1)
  12250. ) break;
  12251. planner.synchronize();
  12252. SYNC_PLAN_POSITION_KINEMATIC();
  12253. extruder_duplication_enabled = true;
  12254. active_extruder_parked = false;
  12255. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12256. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  12257. #endif
  12258. }
  12259. else {
  12260. #if ENABLED(DEBUG_LEVELING_FEATURE)
  12261. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  12262. #endif
  12263. }
  12264. break;
  12265. }
  12266. return false;
  12267. }
  12268. #endif // DUAL_X_CARRIAGE
  12269. /**
  12270. * Prepare a single move and get ready for the next one
  12271. *
  12272. * This may result in several calls to planner.buffer_line to
  12273. * do smaller moves for DELTA, SCARA, HANGPRINTER, mesh moves, etc.
  12274. *
  12275. * Make sure current_position[E] and destination[E] are good
  12276. * before calling or cold/lengthy extrusion may get missed.
  12277. */
  12278. void prepare_move_to_destination() {
  12279. clamp_to_software_endstops(destination);
  12280. #if ENABLED(PREVENT_COLD_EXTRUSION) || ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12281. if (!DEBUGGING(DRYRUN)) {
  12282. if (destination[E_CART] != current_position[E_CART]) {
  12283. #if ENABLED(PREVENT_COLD_EXTRUSION)
  12284. if (thermalManager.tooColdToExtrude(active_extruder)) {
  12285. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12286. SERIAL_ECHO_START();
  12287. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  12288. }
  12289. #endif // PREVENT_COLD_EXTRUSION
  12290. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  12291. if (ABS(destination[E_CART] - current_position[E_CART]) * planner.e_factor[active_extruder] > (EXTRUDE_MAXLENGTH)) {
  12292. current_position[E_CART] = destination[E_CART]; // Behave as if the move really took place, but ignore E part
  12293. SERIAL_ECHO_START();
  12294. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  12295. }
  12296. #endif // PREVENT_LENGTHY_EXTRUDE
  12297. }
  12298. }
  12299. #endif
  12300. #if ENABLED(DUAL_X_CARRIAGE)
  12301. if (dual_x_carriage_unpark()) return;
  12302. #endif
  12303. if (
  12304. #if UBL_SEGMENTED
  12305. ubl.prepare_segmented_line_to(destination, MMS_SCALED(feedrate_mm_s))
  12306. #elif IS_KINEMATIC
  12307. prepare_kinematic_move_to(destination)
  12308. #else
  12309. prepare_move_to_destination_cartesian()
  12310. #endif
  12311. ) return;
  12312. set_current_from_destination();
  12313. }
  12314. #if ENABLED(ARC_SUPPORT)
  12315. #if N_ARC_CORRECTION < 1
  12316. #undef N_ARC_CORRECTION
  12317. #define N_ARC_CORRECTION 1
  12318. #endif
  12319. /**
  12320. * Plan an arc in 2 dimensions
  12321. *
  12322. * The arc is approximated by generating many small linear segments.
  12323. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  12324. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  12325. * larger segments will tend to be more efficient. Your slicer should have
  12326. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  12327. */
  12328. void plan_arc(
  12329. const float (&cart)[XYZE], // Destination position
  12330. const float (&offset)[2], // Center of rotation relative to current_position
  12331. const bool clockwise // Clockwise?
  12332. ) {
  12333. #if ENABLED(CNC_WORKSPACE_PLANES)
  12334. AxisEnum p_axis, q_axis, l_axis;
  12335. switch (workspace_plane) {
  12336. default:
  12337. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  12338. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  12339. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  12340. }
  12341. #else
  12342. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  12343. #endif
  12344. // Radius vector from center to current location
  12345. float r_P = -offset[0], r_Q = -offset[1];
  12346. const float radius = HYPOT(r_P, r_Q),
  12347. center_P = current_position[p_axis] - r_P,
  12348. center_Q = current_position[q_axis] - r_Q,
  12349. rt_X = cart[p_axis] - center_P,
  12350. rt_Y = cart[q_axis] - center_Q,
  12351. linear_travel = cart[l_axis] - current_position[l_axis],
  12352. extruder_travel = cart[E_CART] - current_position[E_CART];
  12353. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  12354. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  12355. if (angular_travel < 0) angular_travel += RADIANS(360);
  12356. if (clockwise) angular_travel -= RADIANS(360);
  12357. // Make a circle if the angular rotation is 0 and the target is current position
  12358. if (angular_travel == 0 && current_position[p_axis] == cart[p_axis] && current_position[q_axis] == cart[q_axis])
  12359. angular_travel = RADIANS(360);
  12360. const float flat_mm = radius * angular_travel,
  12361. mm_of_travel = linear_travel ? HYPOT(flat_mm, linear_travel) : ABS(flat_mm);
  12362. if (mm_of_travel < 0.001f) return;
  12363. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  12364. NOLESS(segments, 1);
  12365. /**
  12366. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  12367. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  12368. * r_T = [cos(phi) -sin(phi);
  12369. * sin(phi) cos(phi)] * r ;
  12370. *
  12371. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  12372. * defined from the circle center to the initial position. Each line segment is formed by successive
  12373. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  12374. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  12375. * all double numbers are single precision on the Arduino. (True double precision will not have
  12376. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  12377. * tool precision in some cases. Therefore, arc path correction is implemented.
  12378. *
  12379. * Small angle approximation may be used to reduce computation overhead further. This approximation
  12380. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  12381. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  12382. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  12383. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  12384. * issue for CNC machines with the single precision Arduino calculations.
  12385. *
  12386. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  12387. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  12388. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  12389. * This is important when there are successive arc motions.
  12390. */
  12391. // Vector rotation matrix values
  12392. float raw[XYZE];
  12393. const float theta_per_segment = angular_travel / segments,
  12394. linear_per_segment = linear_travel / segments,
  12395. extruder_per_segment = extruder_travel / segments,
  12396. sin_T = theta_per_segment,
  12397. cos_T = 1 - 0.5f * sq(theta_per_segment); // Small angle approximation
  12398. // Initialize the linear axis
  12399. raw[l_axis] = current_position[l_axis];
  12400. // Initialize the extruder axis
  12401. raw[E_CART] = current_position[E_CART];
  12402. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  12403. millis_t next_idle_ms = millis() + 200UL;
  12404. #if HAS_FEEDRATE_SCALING
  12405. // SCARA needs to scale the feed rate from mm/s to degrees/s
  12406. const float inv_segment_length = 1.0f / (MM_PER_ARC_SEGMENT),
  12407. inverse_secs = inv_segment_length * fr_mm_s;
  12408. float oldA = planner.position_float[A_AXIS],
  12409. oldB = planner.position_float[B_AXIS]
  12410. #if ENABLED(DELTA_FEEDRATE_SCALING)
  12411. , oldC = planner.position_float[C_AXIS]
  12412. #endif
  12413. ;
  12414. #endif
  12415. #if N_ARC_CORRECTION > 1
  12416. int8_t arc_recalc_count = N_ARC_CORRECTION;
  12417. #endif
  12418. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  12419. thermalManager.manage_heater();
  12420. if (ELAPSED(millis(), next_idle_ms)) {
  12421. next_idle_ms = millis() + 200UL;
  12422. idle();
  12423. }
  12424. #if N_ARC_CORRECTION > 1
  12425. if (--arc_recalc_count) {
  12426. // Apply vector rotation matrix to previous r_P / 1
  12427. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  12428. r_P = r_P * cos_T - r_Q * sin_T;
  12429. r_Q = r_new_Y;
  12430. }
  12431. else
  12432. #endif
  12433. {
  12434. #if N_ARC_CORRECTION > 1
  12435. arc_recalc_count = N_ARC_CORRECTION;
  12436. #endif
  12437. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  12438. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  12439. // To reduce stuttering, the sin and cos could be computed at different times.
  12440. // For now, compute both at the same time.
  12441. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  12442. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  12443. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  12444. }
  12445. // Update raw location
  12446. raw[p_axis] = center_P + r_P;
  12447. raw[q_axis] = center_Q + r_Q;
  12448. raw[l_axis] += linear_per_segment;
  12449. raw[E_CART] += extruder_per_segment;
  12450. clamp_to_software_endstops(raw);
  12451. #if HAS_FEEDRATE_SCALING
  12452. inverse_kinematics(raw);
  12453. ADJUST_DELTA(raw);
  12454. #endif
  12455. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12456. // For SCARA scale the feed rate from mm/s to degrees/s
  12457. // i.e., Complete the angular vector in the given time.
  12458. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], raw[Z_AXIS], raw[E_CART], HYPOT(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12459. break;
  12460. oldA = delta[A_AXIS]; oldB = delta[B_AXIS];
  12461. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12462. // For DELTA scale the feed rate from Effector mm/s to Carriage mm/s
  12463. // i.e., Complete the linear vector in the given time.
  12464. if (!planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], raw[E_AXIS], SQRT(sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC)) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT))
  12465. break;
  12466. oldA = delta[A_AXIS]; oldB = delta[B_AXIS]; oldC = delta[C_AXIS];
  12467. #elif HAS_UBL_AND_CURVES
  12468. float pos[XYZ] = { raw[X_AXIS], raw[Y_AXIS], raw[Z_AXIS] };
  12469. planner.apply_leveling(pos);
  12470. if (!planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], raw[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT))
  12471. break;
  12472. #else
  12473. if (!planner.buffer_line_kinematic(raw, fr_mm_s, active_extruder))
  12474. break;
  12475. #endif
  12476. }
  12477. // Ensure last segment arrives at target location.
  12478. #if HAS_FEEDRATE_SCALING
  12479. inverse_kinematics(cart);
  12480. ADJUST_DELTA(cart);
  12481. #endif
  12482. #if ENABLED(SCARA_FEEDRATE_SCALING)
  12483. const float diff2 = HYPOT2(delta[A_AXIS] - oldA, delta[B_AXIS] - oldB);
  12484. if (diff2)
  12485. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], cart[Z_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12486. #elif ENABLED(DELTA_FEEDRATE_SCALING)
  12487. const float diff2 = sq(delta[A_AXIS] - oldA) + sq(delta[B_AXIS] - oldB) + sq(delta[C_AXIS] - oldC);
  12488. if (diff2)
  12489. planner.buffer_segment(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], cart[E_CART], SQRT(diff2) * inverse_secs, active_extruder, MM_PER_ARC_SEGMENT);
  12490. #elif HAS_UBL_AND_CURVES
  12491. float pos[XYZ] = { cart[X_AXIS], cart[Y_AXIS], cart[Z_AXIS] };
  12492. planner.apply_leveling(pos);
  12493. planner.buffer_segment(pos[X_AXIS], pos[Y_AXIS], pos[Z_AXIS], cart[E_CART], fr_mm_s, active_extruder, MM_PER_ARC_SEGMENT);
  12494. #else
  12495. planner.buffer_line_kinematic(cart, fr_mm_s, active_extruder);
  12496. #endif
  12497. COPY(current_position, cart);
  12498. } // plan_arc
  12499. #endif // ARC_SUPPORT
  12500. #if ENABLED(BEZIER_CURVE_SUPPORT)
  12501. void plan_cubic_move(const float (&cart)[XYZE], const float (&offset)[4]) {
  12502. cubic_b_spline(current_position, cart, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  12503. COPY(current_position, cart);
  12504. }
  12505. #endif // BEZIER_CURVE_SUPPORT
  12506. #if ENABLED(USE_CONTROLLER_FAN)
  12507. void controllerFan() {
  12508. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  12509. nextMotorCheck = 0; // Last time the state was checked
  12510. const millis_t ms = millis();
  12511. if (ELAPSED(ms, nextMotorCheck)) {
  12512. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  12513. // If any of the drivers or the bed are enabled...
  12514. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON
  12515. #if HAS_HEATED_BED
  12516. || thermalManager.soft_pwm_amount_bed > 0
  12517. #endif
  12518. #if HAS_X2_ENABLE
  12519. || X2_ENABLE_READ == X_ENABLE_ON
  12520. #endif
  12521. #if HAS_Y2_ENABLE
  12522. || Y2_ENABLE_READ == Y_ENABLE_ON
  12523. #endif
  12524. #if HAS_Z2_ENABLE
  12525. || Z2_ENABLE_READ == Z_ENABLE_ON
  12526. #endif
  12527. || E0_ENABLE_READ == E_ENABLE_ON
  12528. #if E_STEPPERS > 1
  12529. || E1_ENABLE_READ == E_ENABLE_ON
  12530. #if E_STEPPERS > 2
  12531. || E2_ENABLE_READ == E_ENABLE_ON
  12532. #if E_STEPPERS > 3
  12533. || E3_ENABLE_READ == E_ENABLE_ON
  12534. #if E_STEPPERS > 4
  12535. || E4_ENABLE_READ == E_ENABLE_ON
  12536. #endif
  12537. #endif
  12538. #endif
  12539. #endif
  12540. ) {
  12541. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  12542. }
  12543. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  12544. const uint8_t speed = (lastMotorOn && PENDING(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? CONTROLLERFAN_SPEED : 0;
  12545. controllerFanSpeed = speed;
  12546. // allows digital or PWM fan output to be used (see M42 handling)
  12547. WRITE(CONTROLLER_FAN_PIN, speed);
  12548. analogWrite(CONTROLLER_FAN_PIN, speed);
  12549. }
  12550. }
  12551. #endif // USE_CONTROLLER_FAN
  12552. #if ENABLED(MORGAN_SCARA)
  12553. /**
  12554. * Morgan SCARA Forward Kinematics. Results in cartes[].
  12555. * Maths and first version by QHARLEY.
  12556. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12557. */
  12558. void forward_kinematics_SCARA(const float &a, const float &b) {
  12559. float a_sin = sin(RADIANS(a)) * L1,
  12560. a_cos = cos(RADIANS(a)) * L1,
  12561. b_sin = sin(RADIANS(b)) * L2,
  12562. b_cos = cos(RADIANS(b)) * L2;
  12563. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  12564. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  12565. /*
  12566. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  12567. SERIAL_ECHOPAIR(" b=", b);
  12568. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  12569. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  12570. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  12571. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  12572. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  12573. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  12574. //*/
  12575. }
  12576. /**
  12577. * Morgan SCARA Inverse Kinematics. Results in delta[].
  12578. *
  12579. * See http://forums.reprap.org/read.php?185,283327
  12580. *
  12581. * Maths and first version by QHARLEY.
  12582. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  12583. */
  12584. void inverse_kinematics(const float raw[XYZ]) {
  12585. static float C2, S2, SK1, SK2, THETA, PSI;
  12586. float sx = raw[X_AXIS] - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  12587. sy = raw[Y_AXIS] - SCARA_OFFSET_Y; // With scaling factor.
  12588. if (L1 == L2)
  12589. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  12590. else
  12591. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  12592. S2 = SQRT(1 - sq(C2));
  12593. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  12594. SK1 = L1 + L2 * C2;
  12595. // Rotated Arm2 gives the distance from Arm1 to Arm2
  12596. SK2 = L2 * S2;
  12597. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  12598. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  12599. // Angle of Arm2
  12600. PSI = ATAN2(S2, C2);
  12601. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  12602. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  12603. delta[C_AXIS] = raw[Z_AXIS];
  12604. /*
  12605. DEBUG_POS("SCARA IK", raw);
  12606. DEBUG_POS("SCARA IK", delta);
  12607. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  12608. SERIAL_ECHOPAIR(",", sy);
  12609. SERIAL_ECHOPAIR(" C2=", C2);
  12610. SERIAL_ECHOPAIR(" S2=", S2);
  12611. SERIAL_ECHOPAIR(" Theta=", THETA);
  12612. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  12613. //*/
  12614. }
  12615. #endif // MORGAN_SCARA
  12616. #if ENABLED(TEMP_STAT_LEDS)
  12617. static uint8_t red_led = -1; // Invalid value to force leds initializzation on startup
  12618. static millis_t next_status_led_update_ms = 0;
  12619. void handle_status_leds(void) {
  12620. if (ELAPSED(millis(), next_status_led_update_ms)) {
  12621. next_status_led_update_ms += 500; // Update every 0.5s
  12622. float max_temp = 0.0;
  12623. #if HAS_HEATED_BED
  12624. max_temp = MAX(thermalManager.degTargetBed(), thermalManager.degBed());
  12625. #endif
  12626. HOTEND_LOOP()
  12627. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  12628. const uint8_t new_led = (max_temp > 55.0) ? HIGH : (max_temp < 54.0 || red_led == -1) ? LOW : red_led;
  12629. if (new_led != red_led) {
  12630. red_led = new_led;
  12631. #if PIN_EXISTS(STAT_LED_RED)
  12632. WRITE(STAT_LED_RED_PIN, new_led);
  12633. #endif
  12634. #if PIN_EXISTS(STAT_LED_BLUE)
  12635. WRITE(STAT_LED_BLUE_PIN, !new_led);
  12636. #endif
  12637. }
  12638. }
  12639. }
  12640. #endif
  12641. void enable_all_steppers() {
  12642. #if ENABLED(AUTO_POWER_CONTROL)
  12643. powerManager.power_on();
  12644. #endif
  12645. #if ENABLED(HANGPRINTER)
  12646. enable_A();
  12647. enable_B();
  12648. enable_C();
  12649. enable_D();
  12650. #else
  12651. enable_X();
  12652. enable_Y();
  12653. enable_Z();
  12654. enable_E4();
  12655. #endif
  12656. enable_E0();
  12657. enable_E1();
  12658. enable_E2();
  12659. enable_E3();
  12660. }
  12661. void disable_e_stepper(const uint8_t e) {
  12662. switch (e) {
  12663. case 0: disable_E0(); break;
  12664. case 1: disable_E1(); break;
  12665. case 2: disable_E2(); break;
  12666. case 3: disable_E3(); break;
  12667. case 4: disable_E4(); break;
  12668. }
  12669. }
  12670. void disable_e_steppers() {
  12671. disable_E0();
  12672. disable_E1();
  12673. disable_E2();
  12674. disable_E3();
  12675. disable_E4();
  12676. }
  12677. void disable_all_steppers() {
  12678. disable_X();
  12679. disable_Y();
  12680. disable_Z();
  12681. disable_e_steppers();
  12682. }
  12683. /**
  12684. * Manage several activities:
  12685. * - Check for Filament Runout
  12686. * - Keep the command buffer full
  12687. * - Check for maximum inactive time between commands
  12688. * - Check for maximum inactive time between stepper commands
  12689. * - Check if pin CHDK needs to go LOW
  12690. * - Check for KILL button held down
  12691. * - Check for HOME button held down
  12692. * - Check if cooling fan needs to be switched on
  12693. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  12694. */
  12695. void manage_inactivity(const bool ignore_stepper_queue/*=false*/) {
  12696. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12697. runout.run();
  12698. #endif
  12699. if (commands_in_queue < BUFSIZE) get_available_commands();
  12700. const millis_t ms = millis();
  12701. if (max_inactive_time && ELAPSED(ms, previous_move_ms + max_inactive_time)) {
  12702. SERIAL_ERROR_START();
  12703. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  12704. kill(PSTR(MSG_KILLED));
  12705. }
  12706. // Prevent steppers timing-out in the middle of M600
  12707. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  12708. #define MOVE_AWAY_TEST !did_pause_print
  12709. #else
  12710. #define MOVE_AWAY_TEST true
  12711. #endif
  12712. if (stepper_inactive_time) {
  12713. if (planner.has_blocks_queued())
  12714. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12715. else if (MOVE_AWAY_TEST && !ignore_stepper_queue && ELAPSED(ms, previous_move_ms + stepper_inactive_time)) {
  12716. #if ENABLED(DISABLE_INACTIVE_X)
  12717. disable_X();
  12718. #endif
  12719. #if ENABLED(DISABLE_INACTIVE_Y)
  12720. disable_Y();
  12721. #endif
  12722. #if ENABLED(DISABLE_INACTIVE_Z)
  12723. disable_Z();
  12724. #endif
  12725. #if ENABLED(DISABLE_INACTIVE_E)
  12726. disable_e_steppers();
  12727. #endif
  12728. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTIPANEL) // Only needed with an LCD
  12729. if (ubl.lcd_map_control) ubl.lcd_map_control = defer_return_to_status = false;
  12730. #endif
  12731. }
  12732. }
  12733. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  12734. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  12735. chdkActive = false;
  12736. WRITE(CHDK, LOW);
  12737. }
  12738. #endif
  12739. #if HAS_KILL
  12740. // Check if the kill button was pressed and wait just in case it was an accidental
  12741. // key kill key press
  12742. // -------------------------------------------------------------------------------
  12743. static int killCount = 0; // make the inactivity button a bit less responsive
  12744. const int KILL_DELAY = 750;
  12745. if (!READ(KILL_PIN))
  12746. killCount++;
  12747. else if (killCount > 0)
  12748. killCount--;
  12749. // Exceeded threshold and we can confirm that it was not accidental
  12750. // KILL the machine
  12751. // ----------------------------------------------------------------
  12752. if (killCount >= KILL_DELAY) {
  12753. SERIAL_ERROR_START();
  12754. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  12755. kill(PSTR(MSG_KILLED));
  12756. }
  12757. #endif
  12758. #if HAS_HOME
  12759. // Check to see if we have to home, use poor man's debouncer
  12760. // ---------------------------------------------------------
  12761. static int homeDebounceCount = 0; // poor man's debouncing count
  12762. const int HOME_DEBOUNCE_DELAY = 2500;
  12763. if (!IS_SD_PRINTING() && !READ(HOME_PIN)) {
  12764. if (!homeDebounceCount) {
  12765. enqueue_and_echo_commands_P(PSTR("G28"));
  12766. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  12767. }
  12768. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  12769. homeDebounceCount++;
  12770. else
  12771. homeDebounceCount = 0;
  12772. }
  12773. #endif
  12774. #if ENABLED(USE_CONTROLLER_FAN)
  12775. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  12776. #endif
  12777. #if ENABLED(AUTO_POWER_CONTROL)
  12778. powerManager.check();
  12779. #endif
  12780. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  12781. if (thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP
  12782. && ELAPSED(ms, previous_move_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  12783. && !planner.has_blocks_queued()
  12784. ) {
  12785. #if ENABLED(SWITCHING_EXTRUDER)
  12786. bool oldstatus;
  12787. switch (active_extruder) {
  12788. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12789. #if E_STEPPERS > 1
  12790. case 2: case 3: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12791. #if E_STEPPERS > 2
  12792. case 4: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12793. #endif // E_STEPPERS > 2
  12794. #endif // E_STEPPERS > 1
  12795. }
  12796. #else // !SWITCHING_EXTRUDER
  12797. bool oldstatus;
  12798. switch (active_extruder) {
  12799. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  12800. #if E_STEPPERS > 1
  12801. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  12802. #if E_STEPPERS > 2
  12803. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  12804. #if E_STEPPERS > 3
  12805. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  12806. #if E_STEPPERS > 4
  12807. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  12808. #endif // E_STEPPERS > 4
  12809. #endif // E_STEPPERS > 3
  12810. #endif // E_STEPPERS > 2
  12811. #endif // E_STEPPERS > 1
  12812. }
  12813. #endif // !SWITCHING_EXTRUDER
  12814. const float olde = current_position[E_CART];
  12815. current_position[E_CART] += EXTRUDER_RUNOUT_EXTRUDE;
  12816. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  12817. current_position[E_CART] = olde;
  12818. planner.set_e_position_mm(olde);
  12819. planner.synchronize();
  12820. #if ENABLED(SWITCHING_EXTRUDER)
  12821. switch (active_extruder) {
  12822. default: oldstatus = E0_ENABLE_WRITE(oldstatus); break;
  12823. #if E_STEPPERS > 1
  12824. case 2: case 3: oldstatus = E1_ENABLE_WRITE(oldstatus); break;
  12825. #if E_STEPPERS > 2
  12826. case 4: oldstatus = E2_ENABLE_WRITE(oldstatus); break;
  12827. #endif // E_STEPPERS > 2
  12828. #endif // E_STEPPERS > 1
  12829. }
  12830. #else // !SWITCHING_EXTRUDER
  12831. switch (active_extruder) {
  12832. case 0: E0_ENABLE_WRITE(oldstatus); break;
  12833. #if E_STEPPERS > 1
  12834. case 1: E1_ENABLE_WRITE(oldstatus); break;
  12835. #if E_STEPPERS > 2
  12836. case 2: E2_ENABLE_WRITE(oldstatus); break;
  12837. #if E_STEPPERS > 3
  12838. case 3: E3_ENABLE_WRITE(oldstatus); break;
  12839. #if E_STEPPERS > 4
  12840. case 4: E4_ENABLE_WRITE(oldstatus); break;
  12841. #endif // E_STEPPERS > 4
  12842. #endif // E_STEPPERS > 3
  12843. #endif // E_STEPPERS > 2
  12844. #endif // E_STEPPERS > 1
  12845. }
  12846. #endif // !SWITCHING_EXTRUDER
  12847. previous_move_ms = ms; // reset_stepper_timeout to keep steppers powered
  12848. }
  12849. #endif // EXTRUDER_RUNOUT_PREVENT
  12850. #if ENABLED(DUAL_X_CARRIAGE)
  12851. // handle delayed move timeout
  12852. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  12853. // travel moves have been received so enact them
  12854. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  12855. set_destination_from_current();
  12856. prepare_move_to_destination();
  12857. }
  12858. #endif
  12859. #if ENABLED(TEMP_STAT_LEDS)
  12860. handle_status_leds();
  12861. #endif
  12862. #if ENABLED(MONITOR_DRIVER_STATUS)
  12863. monitor_tmc_driver();
  12864. #endif
  12865. planner.check_axes_activity();
  12866. }
  12867. /**
  12868. * Standard idle routine keeps the machine alive
  12869. */
  12870. void idle(
  12871. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12872. bool no_stepper_sleep/*=false*/
  12873. #endif
  12874. ) {
  12875. #if ENABLED(MAX7219_DEBUG)
  12876. max7219.idle_tasks();
  12877. #endif
  12878. lcd_update();
  12879. host_keepalive();
  12880. manage_inactivity(
  12881. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  12882. no_stepper_sleep
  12883. #endif
  12884. );
  12885. thermalManager.manage_heater();
  12886. #if ENABLED(PRINTCOUNTER)
  12887. print_job_timer.tick();
  12888. #endif
  12889. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  12890. buzzer.tick();
  12891. #endif
  12892. #if ENABLED(I2C_POSITION_ENCODERS)
  12893. static millis_t i2cpem_next_update_ms;
  12894. if (planner.has_blocks_queued() && ELAPSED(millis(), i2cpem_next_update_ms)) {
  12895. I2CPEM.update();
  12896. i2cpem_next_update_ms = millis() + I2CPE_MIN_UPD_TIME_MS;
  12897. }
  12898. #endif
  12899. #if HAS_AUTO_REPORTING
  12900. if (!suspend_auto_report) {
  12901. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  12902. thermalManager.auto_report_temperatures();
  12903. #endif
  12904. #if ENABLED(AUTO_REPORT_SD_STATUS)
  12905. card.auto_report_sd_status();
  12906. #endif
  12907. }
  12908. #endif
  12909. }
  12910. /**
  12911. * Kill all activity and lock the machine.
  12912. * After this the machine will need to be reset.
  12913. */
  12914. void kill(const char* lcd_msg) {
  12915. SERIAL_ERROR_START();
  12916. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  12917. thermalManager.disable_all_heaters();
  12918. disable_all_steppers();
  12919. #if ENABLED(ULTRA_LCD)
  12920. kill_screen(lcd_msg);
  12921. #else
  12922. UNUSED(lcd_msg);
  12923. #endif
  12924. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  12925. cli(); // Stop interrupts
  12926. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  12927. thermalManager.disable_all_heaters(); //turn off heaters again
  12928. #ifdef ACTION_ON_KILL
  12929. SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL);
  12930. #endif
  12931. #if HAS_POWER_SWITCH
  12932. PSU_OFF();
  12933. #endif
  12934. suicide();
  12935. while (1) {
  12936. #if ENABLED(USE_WATCHDOG)
  12937. watchdog_reset();
  12938. #endif
  12939. } // Wait for reset
  12940. }
  12941. /**
  12942. * Turn off heaters and stop the print in progress
  12943. * After a stop the machine may be resumed with M999
  12944. */
  12945. void stop() {
  12946. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  12947. #if ENABLED(PROBING_FANS_OFF)
  12948. if (fans_paused) fans_pause(false); // put things back the way they were
  12949. #endif
  12950. if (IsRunning()) {
  12951. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  12952. SERIAL_ERROR_START();
  12953. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  12954. LCD_MESSAGEPGM(MSG_STOPPED);
  12955. safe_delay(350); // allow enough time for messages to get out before stopping
  12956. Running = false;
  12957. }
  12958. }
  12959. /**
  12960. * Marlin entry-point: Set up before the program loop
  12961. * - Set up the kill pin, filament runout, power hold
  12962. * - Start the serial port
  12963. * - Print startup messages and diagnostics
  12964. * - Get EEPROM or default settings
  12965. * - Initialize managers for:
  12966. * • temperature
  12967. * • planner
  12968. * • watchdog
  12969. * • stepper
  12970. * • photo pin
  12971. * • servos
  12972. * • LCD controller
  12973. * • Digipot I2C
  12974. * • Z probe sled
  12975. * • status LEDs
  12976. */
  12977. void setup() {
  12978. #if ENABLED(MAX7219_DEBUG)
  12979. max7219.init();
  12980. #endif
  12981. #if ENABLED(DISABLE_JTAG)
  12982. // Disable JTAG on AT90USB chips to free up pins for IO
  12983. MCUCR = 0x80;
  12984. MCUCR = 0x80;
  12985. #endif
  12986. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  12987. runout.setup();
  12988. #endif
  12989. setup_killpin();
  12990. setup_powerhold();
  12991. #if HAS_STEPPER_RESET
  12992. disableStepperDrivers();
  12993. #endif
  12994. MYSERIAL0.begin(BAUDRATE);
  12995. SERIAL_PROTOCOLLNPGM("start");
  12996. SERIAL_ECHO_START();
  12997. // Prepare communication for TMC drivers
  12998. #if HAS_DRIVER(TMC2130)
  12999. tmc_init_cs_pins();
  13000. #endif
  13001. #if HAS_DRIVER(TMC2208)
  13002. tmc2208_serial_begin();
  13003. #endif
  13004. // Check startup - does nothing if bootloader sets MCUSR to 0
  13005. byte mcu = MCUSR;
  13006. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  13007. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  13008. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  13009. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  13010. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  13011. MCUSR = 0;
  13012. SERIAL_ECHOPGM(MSG_MARLIN);
  13013. SERIAL_CHAR(' ');
  13014. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  13015. SERIAL_EOL();
  13016. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  13017. SERIAL_ECHO_START();
  13018. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  13019. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  13020. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  13021. SERIAL_ECHO_START();
  13022. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  13023. #endif
  13024. SERIAL_ECHO_START();
  13025. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  13026. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, int(sizeof(block_t))*(BLOCK_BUFFER_SIZE));
  13027. // Send "ok" after commands by default
  13028. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  13029. // Load data from EEPROM if available (or use defaults)
  13030. // This also updates variables in the planner, elsewhere
  13031. (void)settings.load();
  13032. #if HAS_M206_COMMAND
  13033. // Initialize current position based on home_offset
  13034. COPY(current_position, home_offset);
  13035. #else
  13036. ZERO(current_position);
  13037. #endif
  13038. // Vital to init stepper/planner equivalent for current_position
  13039. SYNC_PLAN_POSITION_KINEMATIC();
  13040. thermalManager.init(); // Initialize temperature loop
  13041. print_job_timer.init(); // Initial setup of print job timer
  13042. endstops.init(); // Init endstops and pullups
  13043. stepper.init(); // Init stepper. This enables interrupts!
  13044. servo_init(); // Initialize all servos, stow servo probe
  13045. #if HAS_PHOTOGRAPH
  13046. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  13047. #endif
  13048. #if HAS_CASE_LIGHT
  13049. case_light_on = CASE_LIGHT_DEFAULT_ON;
  13050. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  13051. update_case_light();
  13052. #endif
  13053. #if ENABLED(SPINDLE_LASER_ENABLE)
  13054. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  13055. #if SPINDLE_DIR_CHANGE
  13056. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  13057. #endif
  13058. #if ENABLED(SPINDLE_LASER_PWM)
  13059. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  13060. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  13061. #endif
  13062. #endif
  13063. #if HAS_BED_PROBE
  13064. endstops.enable_z_probe(false);
  13065. #endif
  13066. #if ENABLED(USE_CONTROLLER_FAN)
  13067. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  13068. #endif
  13069. #if HAS_STEPPER_RESET
  13070. enableStepperDrivers();
  13071. #endif
  13072. #if ENABLED(DIGIPOT_I2C)
  13073. digipot_i2c_init();
  13074. #endif
  13075. #if ENABLED(DAC_STEPPER_CURRENT)
  13076. dac_init();
  13077. #endif
  13078. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  13079. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  13080. #endif
  13081. #if HAS_HOME
  13082. SET_INPUT_PULLUP(HOME_PIN);
  13083. #endif
  13084. #if PIN_EXISTS(STAT_LED_RED)
  13085. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  13086. #endif
  13087. #if PIN_EXISTS(STAT_LED_BLUE)
  13088. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  13089. #endif
  13090. #if HAS_COLOR_LEDS
  13091. leds.setup();
  13092. #endif
  13093. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  13094. SET_OUTPUT(RGB_LED_R_PIN);
  13095. SET_OUTPUT(RGB_LED_G_PIN);
  13096. SET_OUTPUT(RGB_LED_B_PIN);
  13097. #if ENABLED(RGBW_LED)
  13098. SET_OUTPUT(RGB_LED_W_PIN);
  13099. #endif
  13100. #endif
  13101. #if ENABLED(MK2_MULTIPLEXER)
  13102. SET_OUTPUT(E_MUX0_PIN);
  13103. SET_OUTPUT(E_MUX1_PIN);
  13104. SET_OUTPUT(E_MUX2_PIN);
  13105. #endif
  13106. #if HAS_FANMUX
  13107. fanmux_init();
  13108. #endif
  13109. lcd_init();
  13110. lcd_reset_status();
  13111. #if ENABLED(SHOW_BOOTSCREEN)
  13112. lcd_bootscreen();
  13113. #endif
  13114. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  13115. // Virtual Tools 0, 1, 2, 3 = Filament 1, 2, 3, 4, etc.
  13116. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS && t < MIXING_STEPPERS; t++)
  13117. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  13118. mixing_virtual_tool_mix[t][i] = (t == i) ? 1.0 : 0.0;
  13119. // Remaining virtual tools are 100% filament 1
  13120. #if MIXING_STEPPERS < MIXING_VIRTUAL_TOOLS
  13121. for (uint8_t t = MIXING_STEPPERS; t < MIXING_VIRTUAL_TOOLS; t++)
  13122. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  13123. mixing_virtual_tool_mix[t][i] = (i == 0) ? 1.0 : 0.0;
  13124. #endif
  13125. // Initialize mixing to tool 0 color
  13126. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  13127. mixing_factor[i] = mixing_virtual_tool_mix[0][i];
  13128. #endif
  13129. #if ENABLED(BLTOUCH)
  13130. // Make sure any BLTouch error condition is cleared
  13131. bltouch_command(BLTOUCH_RESET, BLTOUCH_RESET_DELAY);
  13132. set_bltouch_deployed(false);
  13133. #endif
  13134. #if ENABLED(I2C_POSITION_ENCODERS)
  13135. I2CPEM.init();
  13136. #endif
  13137. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  13138. i2c.onReceive(i2c_on_receive);
  13139. i2c.onRequest(i2c_on_request);
  13140. #endif
  13141. #if DO_SWITCH_EXTRUDER
  13142. move_extruder_servo(0); // Initialize extruder servo
  13143. #endif
  13144. #if ENABLED(SWITCHING_NOZZLE)
  13145. move_nozzle_servo(0); // Initialize nozzle servo
  13146. #endif
  13147. #if ENABLED(PARKING_EXTRUDER)
  13148. #if ENABLED(PARKING_EXTRUDER_SOLENOIDS_INVERT)
  13149. pe_activate_magnet(0);
  13150. pe_activate_magnet(1);
  13151. #else
  13152. pe_deactivate_magnet(0);
  13153. pe_deactivate_magnet(1);
  13154. #endif
  13155. #endif
  13156. #if ENABLED(POWER_LOSS_RECOVERY)
  13157. check_print_job_recovery();
  13158. #endif
  13159. #if ENABLED(USE_WATCHDOG)
  13160. watchdog_init();
  13161. #endif
  13162. #if ENABLED(HANGPRINTER)
  13163. enable_A();
  13164. enable_B();
  13165. enable_C();
  13166. enable_D();
  13167. #endif
  13168. #if ENABLED(SDSUPPORT) && !(ENABLED(ULTRA_LCD) && PIN_EXISTS(SD_DETECT))
  13169. card.beginautostart();
  13170. #endif
  13171. }
  13172. /**
  13173. * The main Marlin program loop
  13174. *
  13175. * - Abort SD printing if flagged
  13176. * - Save or log commands to SD
  13177. * - Process available commands (if not saving)
  13178. * - Call heater manager
  13179. * - Call inactivity manager
  13180. * - Call endstop manager
  13181. * - Call LCD update
  13182. */
  13183. void loop() {
  13184. #if ENABLED(SDSUPPORT)
  13185. card.checkautostart();
  13186. if (card.abort_sd_printing) {
  13187. card.stopSDPrint(
  13188. #if SD_RESORT
  13189. true
  13190. #endif
  13191. );
  13192. clear_command_queue();
  13193. quickstop_stepper();
  13194. print_job_timer.stop();
  13195. thermalManager.disable_all_heaters();
  13196. #if FAN_COUNT > 0
  13197. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  13198. #endif
  13199. wait_for_heatup = false;
  13200. #if ENABLED(POWER_LOSS_RECOVERY)
  13201. card.removeJobRecoveryFile();
  13202. #endif
  13203. }
  13204. #endif // SDSUPPORT
  13205. if (commands_in_queue < BUFSIZE) get_available_commands();
  13206. if (commands_in_queue) {
  13207. #if ENABLED(SDSUPPORT)
  13208. if (card.saving) {
  13209. char* command = command_queue[cmd_queue_index_r];
  13210. if (strstr_P(command, PSTR("M29"))) {
  13211. // M29 closes the file
  13212. card.closefile();
  13213. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  13214. #if USE_MARLINSERIAL
  13215. #if ENABLED(SERIAL_STATS_DROPPED_RX)
  13216. SERIAL_ECHOLNPAIR("Dropped bytes: ", customizedSerial.dropped());
  13217. #endif
  13218. #if ENABLED(SERIAL_STATS_MAX_RX_QUEUED)
  13219. SERIAL_ECHOLNPAIR("Max RX Queue Size: ", customizedSerial.rxMaxEnqueued());
  13220. #endif
  13221. #endif
  13222. ok_to_send();
  13223. }
  13224. else {
  13225. // Write the string from the read buffer to SD
  13226. card.write_command(command);
  13227. if (card.logging)
  13228. process_next_command(); // The card is saving because it's logging
  13229. else
  13230. ok_to_send();
  13231. }
  13232. }
  13233. else {
  13234. process_next_command();
  13235. #if ENABLED(POWER_LOSS_RECOVERY)
  13236. if (card.cardOK && card.sdprinting) save_job_recovery_info();
  13237. #endif
  13238. }
  13239. #else
  13240. process_next_command();
  13241. #endif // SDSUPPORT
  13242. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  13243. if (commands_in_queue) {
  13244. --commands_in_queue;
  13245. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  13246. }
  13247. }
  13248. endstops.event_handler();
  13249. idle();
  13250. }