My Marlin configs for Fabrikator Mini and CTC i3 Pro B
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Marlin_main.cpp 413KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/simen/grbl/tree
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G10 - Retract filament according to settings of M207
  53. * G11 - Retract recover filament according to settings of M208
  54. * G12 - Clean tool
  55. * G20 - Set input units to inches
  56. * G21 - Set input units to millimeters
  57. * G26 - Mesh Validation Pattern (Requires UBL_G26_MESH_VALIDATION)
  58. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  59. * G28 - Home one or more axes
  60. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  61. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  62. * G31 - Dock sled (Z_PROBE_SLED only)
  63. * G32 - Undock sled (Z_PROBE_SLED only)
  64. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  65. * G38 - Probe target - similar to G28 except it uses the Z_MIN_PROBE for all three axes
  66. * G42 - Coordinated move to a mesh point (Requires AUTO_BED_LEVELING_UBL)
  67. * G90 - Use Absolute Coordinates
  68. * G91 - Use Relative Coordinates
  69. * G92 - Set current position to coordinates given
  70. *
  71. * "M" Codes
  72. *
  73. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  74. * M1 - Same as M0
  75. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  76. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  77. * M5 - Turn laser/spindle off
  78. * M17 - Enable/Power all stepper motors
  79. * M18 - Disable all stepper motors; same as M84
  80. * M20 - List SD card. (Requires SDSUPPORT)
  81. * M21 - Init SD card. (Requires SDSUPPORT)
  82. * M22 - Release SD card. (Requires SDSUPPORT)
  83. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  84. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  85. * M25 - Pause SD print. (Requires SDSUPPORT)
  86. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  87. * M27 - Report SD print status. (Requires SDSUPPORT)
  88. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  89. * M29 - Stop SD write. (Requires SDSUPPORT)
  90. * M30 - Delete file from SD: "M30 /path/file.gco"
  91. * M31 - Report time since last M109 or SD card start to serial.
  92. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  93. * Use P to run other files as sub-programs: "M32 P !filename#"
  94. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  95. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  96. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  97. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  98. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  99. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  100. * M75 - Start the print job timer.
  101. * M76 - Pause the print job timer.
  102. * M77 - Stop the print job timer.
  103. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  104. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  105. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  106. * M82 - Set E codes absolute (default).
  107. * M83 - Set E codes relative while in Absolute (G90) mode.
  108. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  109. * duration after which steppers should turn off. S0 disables the timeout.
  110. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  111. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  112. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  113. * M104 - Set extruder target temp.
  114. * M105 - Report current temperatures.
  115. * M106 - Fan on.
  116. * M107 - Fan off.
  117. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  118. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  119. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  120. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  121. * M110 - Set the current line number. (Used by host printing)
  122. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  123. * M112 - Emergency stop.
  124. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  125. * M114 - Report current position.
  126. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  127. * M117 - Display a message on the controller screen. (Requires an LCD)
  128. * M119 - Report endstops status.
  129. * M120 - Enable endstops detection.
  130. * M121 - Disable endstops detection.
  131. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  132. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  133. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  134. * M128 - EtoP Open. (Requires BARICUDA)
  135. * M129 - EtoP Closed. (Requires BARICUDA)
  136. * M140 - Set bed target temp. S<temp>
  137. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  138. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  139. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM or RGB_LED)
  140. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  141. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  142. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  143. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  144. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  145. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  146. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  147. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  148. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  149. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  150. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  151. * M205 - Set advanced settings. Current units apply:
  152. S<print> T<travel> minimum speeds
  153. B<minimum segment time>
  154. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  155. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  156. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  157. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  158. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  159. Every normal extrude-only move will be classified as retract depending on the direction.
  160. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  161. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  162. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  163. * M221 - Set Flow Percentage: "M221 S<percent>"
  164. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  165. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  166. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  167. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  168. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  169. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  170. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  171. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  172. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  173. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  174. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  175. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  176. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  177. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  178. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  179. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  180. * M400 - Finish all moves.
  181. * M401 - Lower Z probe. (Requires a probe)
  182. * M402 - Raise Z probe. (Requires a probe)
  183. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  184. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  185. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  186. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  187. * M410 - Quickstop. Abort all planned moves.
  188. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  189. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING or AUTO_BED_LEVELING_UBL)
  190. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  191. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  192. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  193. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  194. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  195. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  196. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  197. * M665 - Set delta configurations: "M665 L<diagonal rod> R<delta radius> S<segments/s> A<rod A trim mm> B<rod B trim mm> C<rod C trim mm> I<tower A trim angle> J<tower B trim angle> K<tower C trim angle>" (Requires DELTA)
  198. * M666 - Set delta endstop adjustment. (Requires DELTA)
  199. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  200. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  201. * M860 - Report the position of position encoder modules.
  202. * M861 - Report the status of position encoder modules.
  203. * M862 - Perform an axis continuity test for position encoder modules.
  204. * M863 - Perform steps-per-mm calibration for position encoder modules.
  205. * M864 - Change position encoder module I2C address.
  206. * M865 - Check position encoder module firmware version.
  207. * M866 - Report or reset position encoder module error count.
  208. * M867 - Enable/disable or toggle error correction for position encoder modules.
  209. * M868 - Report or set position encoder module error correction threshold.
  210. * M869 - Report position encoder module error.
  211. * M900 - Get and/or Set advance K factor and WH/D ratio. (Requires LIN_ADVANCE)
  212. * M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given. (Requires HAVE_TMC2130)
  213. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  214. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  215. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  216. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  217. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  218. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  219. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  220. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  221. *
  222. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  223. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  224. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  225. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  226. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  227. *
  228. * ************ Custom codes - This can change to suit future G-code regulations
  229. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  230. * M999 - Restart after being stopped by error
  231. *
  232. * "T" Codes
  233. *
  234. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  235. *
  236. */
  237. #include "Marlin.h"
  238. #include "ultralcd.h"
  239. #include "planner.h"
  240. #include "stepper.h"
  241. #include "endstops.h"
  242. #include "temperature.h"
  243. #include "cardreader.h"
  244. #include "configuration_store.h"
  245. #include "language.h"
  246. #include "pins_arduino.h"
  247. #include "math.h"
  248. #include "nozzle.h"
  249. #include "duration_t.h"
  250. #include "types.h"
  251. #include "gcode.h"
  252. #if HAS_ABL
  253. #include "vector_3.h"
  254. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  255. #include "qr_solve.h"
  256. #endif
  257. #elif ENABLED(MESH_BED_LEVELING)
  258. #include "mesh_bed_leveling.h"
  259. #endif
  260. #if ENABLED(BEZIER_CURVE_SUPPORT)
  261. #include "planner_bezier.h"
  262. #endif
  263. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  264. #include "buzzer.h"
  265. #endif
  266. #if ENABLED(USE_WATCHDOG)
  267. #include "watchdog.h"
  268. #endif
  269. #if ENABLED(BLINKM)
  270. #include "blinkm.h"
  271. #include "Wire.h"
  272. #endif
  273. #if HAS_SERVOS
  274. #include "servo.h"
  275. #endif
  276. #if HAS_DIGIPOTSS
  277. #include <SPI.h>
  278. #endif
  279. #if ENABLED(DAC_STEPPER_CURRENT)
  280. #include "stepper_dac.h"
  281. #endif
  282. #if ENABLED(EXPERIMENTAL_I2CBUS)
  283. #include "twibus.h"
  284. #endif
  285. #if ENABLED(I2C_POSITION_ENCODERS)
  286. #include "I2CPositionEncoder.h"
  287. #endif
  288. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  289. #include "endstop_interrupts.h"
  290. #endif
  291. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  292. void gcode_M100();
  293. void M100_dump_routine(const char * const title, const char *start, const char *end);
  294. #endif
  295. #if ENABLED(SDSUPPORT)
  296. CardReader card;
  297. #endif
  298. #if ENABLED(EXPERIMENTAL_I2CBUS)
  299. TWIBus i2c;
  300. #endif
  301. #if ENABLED(G38_PROBE_TARGET)
  302. bool G38_move = false,
  303. G38_endstop_hit = false;
  304. #endif
  305. #if ENABLED(AUTO_BED_LEVELING_UBL)
  306. #include "ubl.h"
  307. unified_bed_leveling ubl;
  308. #define UBL_MESH_VALID !( ( ubl.z_values[0][0] == ubl.z_values[0][1] && ubl.z_values[0][1] == ubl.z_values[0][2] \
  309. && ubl.z_values[1][0] == ubl.z_values[1][1] && ubl.z_values[1][1] == ubl.z_values[1][2] \
  310. && ubl.z_values[2][0] == ubl.z_values[2][1] && ubl.z_values[2][1] == ubl.z_values[2][2] \
  311. && ubl.z_values[0][0] == 0 && ubl.z_values[1][0] == 0 && ubl.z_values[2][0] == 0 ) \
  312. || isnan(ubl.z_values[0][0]))
  313. #endif
  314. bool Running = true;
  315. uint8_t marlin_debug_flags = DEBUG_NONE;
  316. /**
  317. * Cartesian Current Position
  318. * Used to track the logical position as moves are queued.
  319. * Used by 'line_to_current_position' to do a move after changing it.
  320. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  321. */
  322. float current_position[XYZE] = { 0.0 };
  323. /**
  324. * Cartesian Destination
  325. * A temporary position, usually applied to 'current_position'.
  326. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  327. * 'line_to_destination' sets 'current_position' to 'destination'.
  328. */
  329. float destination[XYZE] = { 0.0 };
  330. /**
  331. * axis_homed
  332. * Flags that each linear axis was homed.
  333. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  334. *
  335. * axis_known_position
  336. * Flags that the position is known in each linear axis. Set when homed.
  337. * Cleared whenever a stepper powers off, potentially losing its position.
  338. */
  339. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  340. /**
  341. * GCode line number handling. Hosts may opt to include line numbers when
  342. * sending commands to Marlin, and lines will be checked for sequentiality.
  343. * M110 N<int> sets the current line number.
  344. */
  345. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  346. /**
  347. * GCode Command Queue
  348. * A simple ring buffer of BUFSIZE command strings.
  349. *
  350. * Commands are copied into this buffer by the command injectors
  351. * (immediate, serial, sd card) and they are processed sequentially by
  352. * the main loop. The process_next_command function parses the next
  353. * command and hands off execution to individual handler functions.
  354. */
  355. uint8_t commands_in_queue = 0; // Count of commands in the queue
  356. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  357. cmd_queue_index_w = 0; // Ring buffer write position
  358. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  359. char command_queue[BUFSIZE][MAX_CMD_SIZE]; // Necessary so M100 Free Memory Dumper can show us the commands and any corruption
  360. #else // This can be collapsed back to the way it was soon.
  361. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  362. #endif
  363. /**
  364. * Next Injected Command pointer. NULL if no commands are being injected.
  365. * Used by Marlin internally to ensure that commands initiated from within
  366. * are enqueued ahead of any pending serial or sd card commands.
  367. */
  368. static const char *injected_commands_P = NULL;
  369. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  370. TempUnit input_temp_units = TEMPUNIT_C;
  371. #endif
  372. /**
  373. * Feed rates are often configured with mm/m
  374. * but the planner and stepper like mm/s units.
  375. */
  376. static const float homing_feedrate_mm_s[] PROGMEM = {
  377. #if ENABLED(DELTA)
  378. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  379. #else
  380. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  381. #endif
  382. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  383. };
  384. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  385. float feedrate_mm_s = MMM_TO_MMS(1500.0);
  386. static float saved_feedrate_mm_s;
  387. int feedrate_percentage = 100, saved_feedrate_percentage,
  388. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  389. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  390. volumetric_enabled =
  391. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  392. true
  393. #else
  394. false
  395. #endif
  396. ;
  397. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  398. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  399. #if HAS_WORKSPACE_OFFSET
  400. #if HAS_POSITION_SHIFT
  401. // The distance that XYZ has been offset by G92. Reset by G28.
  402. float position_shift[XYZ] = { 0 };
  403. #endif
  404. #if HAS_HOME_OFFSET
  405. // This offset is added to the configured home position.
  406. // Set by M206, M428, or menu item. Saved to EEPROM.
  407. float home_offset[XYZ] = { 0 };
  408. #endif
  409. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  410. // The above two are combined to save on computes
  411. float workspace_offset[XYZ] = { 0 };
  412. #endif
  413. #endif
  414. // Software Endstops are based on the configured limits.
  415. #if HAS_SOFTWARE_ENDSTOPS
  416. bool soft_endstops_enabled = true;
  417. #endif
  418. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  419. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  420. #if FAN_COUNT > 0
  421. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  422. #if ENABLED(PROBING_FANS_OFF)
  423. bool fans_paused = false;
  424. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  425. #endif
  426. #endif
  427. // The active extruder (tool). Set with T<extruder> command.
  428. uint8_t active_extruder = 0;
  429. // Relative Mode. Enable with G91, disable with G90.
  430. static bool relative_mode = false;
  431. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  432. volatile bool wait_for_heatup = true;
  433. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  434. #if HAS_RESUME_CONTINUE
  435. volatile bool wait_for_user = false;
  436. #endif
  437. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  438. // Number of characters read in the current line of serial input
  439. static int serial_count = 0;
  440. // Inactivity shutdown
  441. millis_t previous_cmd_ms = 0;
  442. static millis_t max_inactive_time = 0;
  443. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  444. // Print Job Timer
  445. #if ENABLED(PRINTCOUNTER)
  446. PrintCounter print_job_timer = PrintCounter();
  447. #else
  448. Stopwatch print_job_timer = Stopwatch();
  449. #endif
  450. // Buzzer - I2C on the LCD or a BEEPER_PIN
  451. #if ENABLED(LCD_USE_I2C_BUZZER)
  452. #define BUZZ(d,f) lcd_buzz(d, f)
  453. #elif PIN_EXISTS(BEEPER)
  454. Buzzer buzzer;
  455. #define BUZZ(d,f) buzzer.tone(d, f)
  456. #else
  457. #define BUZZ(d,f) NOOP
  458. #endif
  459. static uint8_t target_extruder;
  460. #if HAS_BED_PROBE
  461. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  462. #endif
  463. #if HAS_ABL
  464. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  465. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  466. #elif defined(XY_PROBE_SPEED)
  467. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  468. #else
  469. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  470. #endif
  471. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  472. #if ENABLED(DELTA)
  473. #define ADJUST_DELTA(V) \
  474. if (planner.abl_enabled) { \
  475. const float zadj = bilinear_z_offset(V); \
  476. delta[A_AXIS] += zadj; \
  477. delta[B_AXIS] += zadj; \
  478. delta[C_AXIS] += zadj; \
  479. }
  480. #else
  481. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  482. #endif
  483. #elif IS_KINEMATIC
  484. #define ADJUST_DELTA(V) NOOP
  485. #endif
  486. #if ENABLED(Z_DUAL_ENDSTOPS)
  487. float z_endstop_adj =
  488. #ifdef Z_DUAL_ENDSTOPS_ADJUSTMENT
  489. Z_DUAL_ENDSTOPS_ADJUSTMENT
  490. #else
  491. 0
  492. #endif
  493. ;
  494. #endif
  495. // Extruder offsets
  496. #if HOTENDS > 1
  497. float hotend_offset[XYZ][HOTENDS];
  498. #endif
  499. #if HAS_Z_SERVO_ENDSTOP
  500. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  501. #endif
  502. #if ENABLED(BARICUDA)
  503. int baricuda_valve_pressure = 0;
  504. int baricuda_e_to_p_pressure = 0;
  505. #endif
  506. #if ENABLED(FWRETRACT)
  507. bool autoretract_enabled = false;
  508. bool retracted[EXTRUDERS] = { false };
  509. bool retracted_swap[EXTRUDERS] = { false };
  510. float retract_length = RETRACT_LENGTH;
  511. float retract_length_swap = RETRACT_LENGTH_SWAP;
  512. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  513. float retract_zlift = RETRACT_ZLIFT;
  514. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  515. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  516. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  517. #endif // FWRETRACT
  518. #if HAS_POWER_SWITCH
  519. bool powersupply_on =
  520. #if ENABLED(PS_DEFAULT_OFF)
  521. false
  522. #else
  523. true
  524. #endif
  525. ;
  526. #endif
  527. #if ENABLED(DELTA)
  528. float delta[ABC],
  529. endstop_adj[ABC] = { 0 };
  530. // These values are loaded or reset at boot time when setup() calls
  531. // settings.load(), which calls recalc_delta_settings().
  532. float delta_radius,
  533. delta_tower_angle_trim[2],
  534. delta_tower[ABC][2],
  535. delta_diagonal_rod,
  536. delta_calibration_radius,
  537. delta_diagonal_rod_2_tower[ABC],
  538. delta_segments_per_second,
  539. delta_clip_start_height = Z_MAX_POS;
  540. float delta_safe_distance_from_top();
  541. #endif
  542. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  543. int bilinear_grid_spacing[2], bilinear_start[2];
  544. float bilinear_grid_factor[2],
  545. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  546. #endif
  547. #if IS_SCARA
  548. // Float constants for SCARA calculations
  549. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  550. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  551. L2_2 = sq(float(L2));
  552. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  553. delta[ABC];
  554. #endif
  555. float cartes[XYZ] = { 0 };
  556. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  557. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  558. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  559. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  560. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  561. int filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  562. int meas_delay_cm = MEASUREMENT_DELAY_CM; // Distance delay setting
  563. #endif
  564. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  565. static bool filament_ran_out = false;
  566. #endif
  567. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  568. AdvancedPauseMenuResponse advanced_pause_menu_response;
  569. #endif
  570. #if ENABLED(MIXING_EXTRUDER)
  571. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  572. #if MIXING_VIRTUAL_TOOLS > 1
  573. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  574. #endif
  575. #endif
  576. static bool send_ok[BUFSIZE];
  577. #if HAS_SERVOS
  578. Servo servo[NUM_SERVOS];
  579. #define MOVE_SERVO(I, P) servo[I].move(P)
  580. #if HAS_Z_SERVO_ENDSTOP
  581. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  582. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  583. #endif
  584. #endif
  585. #ifdef CHDK
  586. millis_t chdkHigh = 0;
  587. bool chdkActive = false;
  588. #endif
  589. #ifdef AUTOMATIC_CURRENT_CONTROL
  590. bool auto_current_control = 0;
  591. #endif
  592. #if ENABLED(PID_EXTRUSION_SCALING)
  593. int lpq_len = 20;
  594. #endif
  595. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  596. MarlinBusyState busy_state = NOT_BUSY;
  597. static millis_t next_busy_signal_ms = 0;
  598. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  599. #else
  600. #define host_keepalive() NOOP
  601. #endif
  602. #if ENABLED(I2C_POSITION_ENCODERS)
  603. I2CPositionEncodersMgr I2CPEM;
  604. uint8_t blockBufferIndexRef = 0;
  605. millis_t lastUpdateMillis;
  606. #endif
  607. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  608. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  609. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  610. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  611. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  612. typedef void __void_##CONFIG##__
  613. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  614. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  615. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  616. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  617. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  618. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  619. /**
  620. * ***************************************************************************
  621. * ******************************** FUNCTIONS ********************************
  622. * ***************************************************************************
  623. */
  624. void stop();
  625. void get_available_commands();
  626. void process_next_command();
  627. void prepare_move_to_destination();
  628. void get_cartesian_from_steppers();
  629. void set_current_from_steppers_for_axis(const AxisEnum axis);
  630. #if ENABLED(ARC_SUPPORT)
  631. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  632. #endif
  633. #if ENABLED(BEZIER_CURVE_SUPPORT)
  634. void plan_cubic_move(const float offset[4]);
  635. #endif
  636. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  637. void report_current_position();
  638. void report_current_position_detail();
  639. #if ENABLED(DEBUG_LEVELING_FEATURE)
  640. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  641. serialprintPGM(prefix);
  642. SERIAL_CHAR('(');
  643. SERIAL_ECHO(x);
  644. SERIAL_ECHOPAIR(", ", y);
  645. SERIAL_ECHOPAIR(", ", z);
  646. SERIAL_CHAR(')');
  647. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  648. }
  649. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  650. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  651. }
  652. #if HAS_ABL
  653. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  654. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  655. }
  656. #endif
  657. #define DEBUG_POS(SUFFIX,VAR) do { \
  658. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  659. #endif
  660. /**
  661. * sync_plan_position
  662. *
  663. * Set the planner/stepper positions directly from current_position with
  664. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  665. */
  666. inline void sync_plan_position() {
  667. #if ENABLED(DEBUG_LEVELING_FEATURE)
  668. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  669. #endif
  670. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  671. }
  672. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  673. #if IS_KINEMATIC
  674. inline void sync_plan_position_kinematic() {
  675. #if ENABLED(DEBUG_LEVELING_FEATURE)
  676. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  677. #endif
  678. planner.set_position_mm_kinematic(current_position);
  679. }
  680. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  681. #else
  682. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  683. #endif
  684. #if ENABLED(SDSUPPORT)
  685. #include "SdFatUtil.h"
  686. int freeMemory() { return SdFatUtil::FreeRam(); }
  687. #else
  688. extern "C" {
  689. extern char __bss_end;
  690. extern char __heap_start;
  691. extern void* __brkval;
  692. int freeMemory() {
  693. int free_memory;
  694. if ((int)__brkval == 0)
  695. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  696. else
  697. free_memory = ((int)&free_memory) - ((int)__brkval);
  698. return free_memory;
  699. }
  700. }
  701. #endif // !SDSUPPORT
  702. #if ENABLED(DIGIPOT_I2C)
  703. extern void digipot_i2c_set_current(uint8_t channel, float current);
  704. extern void digipot_i2c_init();
  705. #endif
  706. /**
  707. * Inject the next "immediate" command, when possible, onto the front of the queue.
  708. * Return true if any immediate commands remain to inject.
  709. */
  710. static bool drain_injected_commands_P() {
  711. if (injected_commands_P != NULL) {
  712. size_t i = 0;
  713. char c, cmd[30];
  714. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  715. cmd[sizeof(cmd) - 1] = '\0';
  716. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  717. cmd[i] = '\0';
  718. if (enqueue_and_echo_command(cmd)) // success?
  719. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  720. }
  721. return (injected_commands_P != NULL); // return whether any more remain
  722. }
  723. /**
  724. * Record one or many commands to run from program memory.
  725. * Aborts the current queue, if any.
  726. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  727. */
  728. void enqueue_and_echo_commands_P(const char * const pgcode) {
  729. injected_commands_P = pgcode;
  730. drain_injected_commands_P(); // first command executed asap (when possible)
  731. }
  732. /**
  733. * Clear the Marlin command queue
  734. */
  735. void clear_command_queue() {
  736. cmd_queue_index_r = cmd_queue_index_w;
  737. commands_in_queue = 0;
  738. }
  739. /**
  740. * Once a new command is in the ring buffer, call this to commit it
  741. */
  742. inline void _commit_command(bool say_ok) {
  743. send_ok[cmd_queue_index_w] = say_ok;
  744. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  745. commands_in_queue++;
  746. }
  747. /**
  748. * Copy a command from RAM into the main command buffer.
  749. * Return true if the command was successfully added.
  750. * Return false for a full buffer, or if the 'command' is a comment.
  751. */
  752. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  753. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  754. strcpy(command_queue[cmd_queue_index_w], cmd);
  755. _commit_command(say_ok);
  756. return true;
  757. }
  758. /**
  759. * Enqueue with Serial Echo
  760. */
  761. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  762. if (_enqueuecommand(cmd, say_ok)) {
  763. SERIAL_ECHO_START();
  764. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  765. SERIAL_CHAR('"');
  766. SERIAL_EOL();
  767. return true;
  768. }
  769. return false;
  770. }
  771. void setup_killpin() {
  772. #if HAS_KILL
  773. SET_INPUT_PULLUP(KILL_PIN);
  774. #endif
  775. }
  776. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  777. void setup_filrunoutpin() {
  778. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  779. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  780. #else
  781. SET_INPUT(FIL_RUNOUT_PIN);
  782. #endif
  783. }
  784. #endif
  785. void setup_homepin(void) {
  786. #if HAS_HOME
  787. SET_INPUT_PULLUP(HOME_PIN);
  788. #endif
  789. }
  790. void setup_powerhold() {
  791. #if HAS_SUICIDE
  792. OUT_WRITE(SUICIDE_PIN, HIGH);
  793. #endif
  794. #if HAS_POWER_SWITCH
  795. #if ENABLED(PS_DEFAULT_OFF)
  796. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  797. #else
  798. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  799. #endif
  800. #endif
  801. }
  802. void suicide() {
  803. #if HAS_SUICIDE
  804. OUT_WRITE(SUICIDE_PIN, LOW);
  805. #endif
  806. }
  807. void servo_init() {
  808. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  809. servo[0].attach(SERVO0_PIN);
  810. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  811. #endif
  812. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  813. servo[1].attach(SERVO1_PIN);
  814. servo[1].detach();
  815. #endif
  816. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  817. servo[2].attach(SERVO2_PIN);
  818. servo[2].detach();
  819. #endif
  820. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  821. servo[3].attach(SERVO3_PIN);
  822. servo[3].detach();
  823. #endif
  824. #if HAS_Z_SERVO_ENDSTOP
  825. /**
  826. * Set position of Z Servo Endstop
  827. *
  828. * The servo might be deployed and positioned too low to stow
  829. * when starting up the machine or rebooting the board.
  830. * There's no way to know where the nozzle is positioned until
  831. * homing has been done - no homing with z-probe without init!
  832. *
  833. */
  834. STOW_Z_SERVO();
  835. #endif
  836. }
  837. /**
  838. * Stepper Reset (RigidBoard, et.al.)
  839. */
  840. #if HAS_STEPPER_RESET
  841. void disableStepperDrivers() {
  842. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  843. }
  844. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  845. #endif
  846. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  847. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  848. i2c.receive(bytes);
  849. }
  850. void i2c_on_request() { // just send dummy data for now
  851. i2c.reply("Hello World!\n");
  852. }
  853. #endif
  854. #if HAS_COLOR_LEDS
  855. void set_led_color(
  856. const uint8_t r, const uint8_t g, const uint8_t b
  857. #if ENABLED(RGBW_LED)
  858. , const uint8_t w=0
  859. #endif
  860. ) {
  861. #if ENABLED(BLINKM)
  862. // This variant uses i2c to send the RGB components to the device.
  863. SendColors(r, g, b);
  864. #else
  865. // This variant uses 3 separate pins for the RGB components.
  866. // If the pins can do PWM then their intensity will be set.
  867. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  868. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  869. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  870. analogWrite(RGB_LED_R_PIN, r);
  871. analogWrite(RGB_LED_G_PIN, g);
  872. analogWrite(RGB_LED_B_PIN, b);
  873. #if ENABLED(RGBW_LED)
  874. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  875. analogWrite(RGB_LED_W_PIN, w);
  876. #endif
  877. #endif
  878. }
  879. #endif // HAS_COLOR_LEDS
  880. void gcode_line_error(const char* err, bool doFlush = true) {
  881. SERIAL_ERROR_START();
  882. serialprintPGM(err);
  883. SERIAL_ERRORLN(gcode_LastN);
  884. //Serial.println(gcode_N);
  885. if (doFlush) FlushSerialRequestResend();
  886. serial_count = 0;
  887. }
  888. /**
  889. * Get all commands waiting on the serial port and queue them.
  890. * Exit when the buffer is full or when no more characters are
  891. * left on the serial port.
  892. */
  893. inline void get_serial_commands() {
  894. static char serial_line_buffer[MAX_CMD_SIZE];
  895. static bool serial_comment_mode = false;
  896. // If the command buffer is empty for too long,
  897. // send "wait" to indicate Marlin is still waiting.
  898. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  899. static millis_t last_command_time = 0;
  900. const millis_t ms = millis();
  901. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  902. SERIAL_ECHOLNPGM(MSG_WAIT);
  903. last_command_time = ms;
  904. }
  905. #endif
  906. /**
  907. * Loop while serial characters are incoming and the queue is not full
  908. */
  909. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  910. char serial_char = MYSERIAL.read();
  911. /**
  912. * If the character ends the line
  913. */
  914. if (serial_char == '\n' || serial_char == '\r') {
  915. serial_comment_mode = false; // end of line == end of comment
  916. if (!serial_count) continue; // skip empty lines
  917. serial_line_buffer[serial_count] = 0; // terminate string
  918. serial_count = 0; //reset buffer
  919. char* command = serial_line_buffer;
  920. while (*command == ' ') command++; // skip any leading spaces
  921. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  922. *apos = strchr(command, '*');
  923. if (npos) {
  924. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  925. if (M110) {
  926. char* n2pos = strchr(command + 4, 'N');
  927. if (n2pos) npos = n2pos;
  928. }
  929. gcode_N = strtol(npos + 1, NULL, 10);
  930. if (gcode_N != gcode_LastN + 1 && !M110) {
  931. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  932. return;
  933. }
  934. if (apos) {
  935. byte checksum = 0, count = 0;
  936. while (command[count] != '*') checksum ^= command[count++];
  937. if (strtol(apos + 1, NULL, 10) != checksum) {
  938. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  939. return;
  940. }
  941. // if no errors, continue parsing
  942. }
  943. else {
  944. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  945. return;
  946. }
  947. gcode_LastN = gcode_N;
  948. // if no errors, continue parsing
  949. }
  950. else if (apos) { // No '*' without 'N'
  951. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  952. return;
  953. }
  954. // Movement commands alert when stopped
  955. if (IsStopped()) {
  956. char* gpos = strchr(command, 'G');
  957. if (gpos) {
  958. const int codenum = strtol(gpos + 1, NULL, 10);
  959. switch (codenum) {
  960. case 0:
  961. case 1:
  962. case 2:
  963. case 3:
  964. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  965. LCD_MESSAGEPGM(MSG_STOPPED);
  966. break;
  967. }
  968. }
  969. }
  970. #if DISABLED(EMERGENCY_PARSER)
  971. // If command was e-stop process now
  972. if (strcmp(command, "M108") == 0) {
  973. wait_for_heatup = false;
  974. #if ENABLED(ULTIPANEL)
  975. wait_for_user = false;
  976. #endif
  977. }
  978. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  979. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  980. #endif
  981. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  982. last_command_time = ms;
  983. #endif
  984. // Add the command to the queue
  985. _enqueuecommand(serial_line_buffer, true);
  986. }
  987. else if (serial_count >= MAX_CMD_SIZE - 1) {
  988. // Keep fetching, but ignore normal characters beyond the max length
  989. // The command will be injected when EOL is reached
  990. }
  991. else if (serial_char == '\\') { // Handle escapes
  992. if (MYSERIAL.available() > 0) {
  993. // if we have one more character, copy it over
  994. serial_char = MYSERIAL.read();
  995. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  996. }
  997. // otherwise do nothing
  998. }
  999. else { // it's not a newline, carriage return or escape char
  1000. if (serial_char == ';') serial_comment_mode = true;
  1001. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1002. }
  1003. } // queue has space, serial has data
  1004. }
  1005. #if ENABLED(SDSUPPORT)
  1006. /**
  1007. * Get commands from the SD Card until the command buffer is full
  1008. * or until the end of the file is reached. The special character '#'
  1009. * can also interrupt buffering.
  1010. */
  1011. inline void get_sdcard_commands() {
  1012. static bool stop_buffering = false,
  1013. sd_comment_mode = false;
  1014. if (!card.sdprinting) return;
  1015. /**
  1016. * '#' stops reading from SD to the buffer prematurely, so procedural
  1017. * macro calls are possible. If it occurs, stop_buffering is triggered
  1018. * and the buffer is run dry; this character _can_ occur in serial com
  1019. * due to checksums, however, no checksums are used in SD printing.
  1020. */
  1021. if (commands_in_queue == 0) stop_buffering = false;
  1022. uint16_t sd_count = 0;
  1023. bool card_eof = card.eof();
  1024. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1025. const int16_t n = card.get();
  1026. char sd_char = (char)n;
  1027. card_eof = card.eof();
  1028. if (card_eof || n == -1
  1029. || sd_char == '\n' || sd_char == '\r'
  1030. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1031. ) {
  1032. if (card_eof) {
  1033. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1034. card.printingHasFinished();
  1035. #if ENABLED(PRINTER_EVENT_LEDS)
  1036. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1037. set_led_color(0, 255, 0); // Green
  1038. #if HAS_RESUME_CONTINUE
  1039. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1040. #else
  1041. safe_delay(1000);
  1042. #endif
  1043. set_led_color(0, 0, 0); // OFF
  1044. #endif
  1045. card.checkautostart(true);
  1046. }
  1047. else if (n == -1) {
  1048. SERIAL_ERROR_START();
  1049. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1050. }
  1051. if (sd_char == '#') stop_buffering = true;
  1052. sd_comment_mode = false; // for new command
  1053. if (!sd_count) continue; // skip empty lines (and comment lines)
  1054. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1055. sd_count = 0; // clear sd line buffer
  1056. _commit_command(false);
  1057. }
  1058. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1059. /**
  1060. * Keep fetching, but ignore normal characters beyond the max length
  1061. * The command will be injected when EOL is reached
  1062. */
  1063. }
  1064. else {
  1065. if (sd_char == ';') sd_comment_mode = true;
  1066. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1067. }
  1068. }
  1069. }
  1070. #endif // SDSUPPORT
  1071. /**
  1072. * Add to the circular command queue the next command from:
  1073. * - The command-injection queue (injected_commands_P)
  1074. * - The active serial input (usually USB)
  1075. * - The SD card file being actively printed
  1076. */
  1077. void get_available_commands() {
  1078. // if any immediate commands remain, don't get other commands yet
  1079. if (drain_injected_commands_P()) return;
  1080. get_serial_commands();
  1081. #if ENABLED(SDSUPPORT)
  1082. get_sdcard_commands();
  1083. #endif
  1084. }
  1085. /**
  1086. * Set target_extruder from the T parameter or the active_extruder
  1087. *
  1088. * Returns TRUE if the target is invalid
  1089. */
  1090. bool get_target_extruder_from_command(int code) {
  1091. if (parser.seen('T')) {
  1092. if (parser.value_byte() >= EXTRUDERS) {
  1093. SERIAL_ECHO_START();
  1094. SERIAL_CHAR('M');
  1095. SERIAL_ECHO(code);
  1096. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", parser.value_byte());
  1097. return true;
  1098. }
  1099. target_extruder = parser.value_byte();
  1100. }
  1101. else
  1102. target_extruder = active_extruder;
  1103. return false;
  1104. }
  1105. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1106. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1107. #endif
  1108. #if ENABLED(DUAL_X_CARRIAGE)
  1109. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1110. static float x_home_pos(const int extruder) {
  1111. if (extruder == 0)
  1112. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1113. else
  1114. /**
  1115. * In dual carriage mode the extruder offset provides an override of the
  1116. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1117. * This allows soft recalibration of the second extruder home position
  1118. * without firmware reflash (through the M218 command).
  1119. */
  1120. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1121. }
  1122. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1123. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1124. static bool active_extruder_parked = false; // used in mode 1 & 2
  1125. static float raised_parked_position[XYZE]; // used in mode 1
  1126. static millis_t delayed_move_time = 0; // used in mode 1
  1127. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1128. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1129. #endif // DUAL_X_CARRIAGE
  1130. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1131. /**
  1132. * Software endstops can be used to monitor the open end of
  1133. * an axis that has a hardware endstop on the other end. Or
  1134. * they can prevent axes from moving past endstops and grinding.
  1135. *
  1136. * To keep doing their job as the coordinate system changes,
  1137. * the software endstop positions must be refreshed to remain
  1138. * at the same positions relative to the machine.
  1139. */
  1140. void update_software_endstops(const AxisEnum axis) {
  1141. const float offs = 0.0
  1142. #if HAS_HOME_OFFSET
  1143. + home_offset[axis]
  1144. #endif
  1145. #if HAS_POSITION_SHIFT
  1146. + position_shift[axis]
  1147. #endif
  1148. ;
  1149. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1150. workspace_offset[axis] = offs;
  1151. #endif
  1152. #if ENABLED(DUAL_X_CARRIAGE)
  1153. if (axis == X_AXIS) {
  1154. // In Dual X mode hotend_offset[X] is T1's home position
  1155. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1156. if (active_extruder != 0) {
  1157. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1158. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1159. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1160. }
  1161. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1162. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1163. // but not so far to the right that T1 would move past the end
  1164. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1165. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1166. }
  1167. else {
  1168. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1169. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1170. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1171. }
  1172. }
  1173. #else
  1174. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1175. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1176. #endif
  1177. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1178. if (DEBUGGING(LEVELING)) {
  1179. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1180. #if HAS_HOME_OFFSET
  1181. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1182. #endif
  1183. #if HAS_POSITION_SHIFT
  1184. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1185. #endif
  1186. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1187. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1188. }
  1189. #endif
  1190. #if ENABLED(DELTA)
  1191. if (axis == Z_AXIS)
  1192. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1193. #endif
  1194. }
  1195. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1196. #if HAS_M206_COMMAND
  1197. /**
  1198. * Change the home offset for an axis, update the current
  1199. * position and the software endstops to retain the same
  1200. * relative distance to the new home.
  1201. *
  1202. * Since this changes the current_position, code should
  1203. * call sync_plan_position soon after this.
  1204. */
  1205. static void set_home_offset(const AxisEnum axis, const float v) {
  1206. current_position[axis] += v - home_offset[axis];
  1207. home_offset[axis] = v;
  1208. update_software_endstops(axis);
  1209. }
  1210. #endif // HAS_M206_COMMAND
  1211. /**
  1212. * Set an axis' current position to its home position (after homing).
  1213. *
  1214. * For Core and Cartesian robots this applies one-to-one when an
  1215. * individual axis has been homed.
  1216. *
  1217. * DELTA should wait until all homing is done before setting the XYZ
  1218. * current_position to home, because homing is a single operation.
  1219. * In the case where the axis positions are already known and previously
  1220. * homed, DELTA could home to X or Y individually by moving either one
  1221. * to the center. However, homing Z always homes XY and Z.
  1222. *
  1223. * SCARA should wait until all XY homing is done before setting the XY
  1224. * current_position to home, because neither X nor Y is at home until
  1225. * both are at home. Z can however be homed individually.
  1226. *
  1227. * Callers must sync the planner position after calling this!
  1228. */
  1229. static void set_axis_is_at_home(const AxisEnum axis) {
  1230. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1231. if (DEBUGGING(LEVELING)) {
  1232. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1233. SERIAL_CHAR(')');
  1234. SERIAL_EOL();
  1235. }
  1236. #endif
  1237. axis_known_position[axis] = axis_homed[axis] = true;
  1238. #if HAS_POSITION_SHIFT
  1239. position_shift[axis] = 0;
  1240. update_software_endstops(axis);
  1241. #endif
  1242. #if ENABLED(DUAL_X_CARRIAGE)
  1243. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1244. current_position[X_AXIS] = x_home_pos(active_extruder);
  1245. return;
  1246. }
  1247. #endif
  1248. #if ENABLED(MORGAN_SCARA)
  1249. /**
  1250. * Morgan SCARA homes XY at the same time
  1251. */
  1252. if (axis == X_AXIS || axis == Y_AXIS) {
  1253. float homeposition[XYZ];
  1254. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1255. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1256. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1257. /**
  1258. * Get Home position SCARA arm angles using inverse kinematics,
  1259. * and calculate homing offset using forward kinematics
  1260. */
  1261. inverse_kinematics(homeposition);
  1262. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1263. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1264. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1265. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1266. /**
  1267. * SCARA home positions are based on configuration since the actual
  1268. * limits are determined by the inverse kinematic transform.
  1269. */
  1270. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1271. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1272. }
  1273. else
  1274. #endif
  1275. {
  1276. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1277. }
  1278. /**
  1279. * Z Probe Z Homing? Account for the probe's Z offset.
  1280. */
  1281. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1282. if (axis == Z_AXIS) {
  1283. #if HOMING_Z_WITH_PROBE
  1284. current_position[Z_AXIS] -= zprobe_zoffset;
  1285. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1286. if (DEBUGGING(LEVELING)) {
  1287. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1288. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1289. }
  1290. #endif
  1291. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1292. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1293. #endif
  1294. }
  1295. #endif
  1296. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1297. if (DEBUGGING(LEVELING)) {
  1298. #if HAS_HOME_OFFSET
  1299. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1300. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1301. #endif
  1302. DEBUG_POS("", current_position);
  1303. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1304. SERIAL_CHAR(')');
  1305. SERIAL_EOL();
  1306. }
  1307. #endif
  1308. #if ENABLED(I2C_POSITION_ENCODERS)
  1309. I2CPEM.homed(axis);
  1310. #endif
  1311. }
  1312. /**
  1313. * Some planner shorthand inline functions
  1314. */
  1315. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1316. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1317. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1318. if (hbd < 1) {
  1319. hbd = 10;
  1320. SERIAL_ECHO_START();
  1321. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1322. }
  1323. return homing_feedrate(axis) / hbd;
  1324. }
  1325. /**
  1326. * Move the planner to the current position from wherever it last moved
  1327. * (or from wherever it has been told it is located).
  1328. */
  1329. inline void line_to_current_position() {
  1330. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1331. }
  1332. /**
  1333. * Move the planner to the position stored in the destination array, which is
  1334. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1335. */
  1336. inline void line_to_destination(const float fr_mm_s) {
  1337. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1338. }
  1339. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1340. inline void set_current_to_destination() { COPY(current_position, destination); }
  1341. inline void set_destination_to_current() { COPY(destination, current_position); }
  1342. #if IS_KINEMATIC
  1343. /**
  1344. * Calculate delta, start a line, and set current_position to destination
  1345. */
  1346. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1347. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1348. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1349. #endif
  1350. refresh_cmd_timeout();
  1351. #if UBL_DELTA
  1352. // ubl segmented line will do z-only moves in single segment
  1353. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1354. #else
  1355. if ( current_position[X_AXIS] == destination[X_AXIS]
  1356. && current_position[Y_AXIS] == destination[Y_AXIS]
  1357. && current_position[Z_AXIS] == destination[Z_AXIS]
  1358. && current_position[E_AXIS] == destination[E_AXIS]
  1359. ) return;
  1360. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1361. #endif
  1362. set_current_to_destination();
  1363. }
  1364. #endif // IS_KINEMATIC
  1365. /**
  1366. * Plan a move to (X, Y, Z) and set the current_position
  1367. * The final current_position may not be the one that was requested
  1368. */
  1369. void do_blocking_move_to(const float &lx, const float &ly, const float &lz, const float &fr_mm_s/*=0.0*/) {
  1370. const float old_feedrate_mm_s = feedrate_mm_s;
  1371. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1372. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, lx, ly, lz);
  1373. #endif
  1374. #if ENABLED(DELTA)
  1375. if (!position_is_reachable_xy(lx, ly)) return;
  1376. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1377. set_destination_to_current(); // sync destination at the start
  1378. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1379. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1380. #endif
  1381. // when in the danger zone
  1382. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1383. if (lz > delta_clip_start_height) { // staying in the danger zone
  1384. destination[X_AXIS] = lx; // move directly (uninterpolated)
  1385. destination[Y_AXIS] = ly;
  1386. destination[Z_AXIS] = lz;
  1387. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1388. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1389. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1390. #endif
  1391. return;
  1392. }
  1393. else {
  1394. destination[Z_AXIS] = delta_clip_start_height;
  1395. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1396. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1397. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1398. #endif
  1399. }
  1400. }
  1401. if (lz > current_position[Z_AXIS]) { // raising?
  1402. destination[Z_AXIS] = lz;
  1403. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1404. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1405. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1406. #endif
  1407. }
  1408. destination[X_AXIS] = lx;
  1409. destination[Y_AXIS] = ly;
  1410. prepare_move_to_destination(); // set_current_to_destination
  1411. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1412. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1413. #endif
  1414. if (lz < current_position[Z_AXIS]) { // lowering?
  1415. destination[Z_AXIS] = lz;
  1416. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1417. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1418. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1419. #endif
  1420. }
  1421. #elif IS_SCARA
  1422. if (!position_is_reachable_xy(lx, ly)) return;
  1423. set_destination_to_current();
  1424. // If Z needs to raise, do it before moving XY
  1425. if (destination[Z_AXIS] < lz) {
  1426. destination[Z_AXIS] = lz;
  1427. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1428. }
  1429. destination[X_AXIS] = lx;
  1430. destination[Y_AXIS] = ly;
  1431. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1432. // If Z needs to lower, do it after moving XY
  1433. if (destination[Z_AXIS] > lz) {
  1434. destination[Z_AXIS] = lz;
  1435. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1436. }
  1437. #else
  1438. // If Z needs to raise, do it before moving XY
  1439. if (current_position[Z_AXIS] < lz) {
  1440. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1441. current_position[Z_AXIS] = lz;
  1442. line_to_current_position();
  1443. }
  1444. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1445. current_position[X_AXIS] = lx;
  1446. current_position[Y_AXIS] = ly;
  1447. line_to_current_position();
  1448. // If Z needs to lower, do it after moving XY
  1449. if (current_position[Z_AXIS] > lz) {
  1450. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1451. current_position[Z_AXIS] = lz;
  1452. line_to_current_position();
  1453. }
  1454. #endif
  1455. stepper.synchronize();
  1456. feedrate_mm_s = old_feedrate_mm_s;
  1457. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1458. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1459. #endif
  1460. }
  1461. void do_blocking_move_to_x(const float &lx, const float &fr_mm_s/*=0.0*/) {
  1462. do_blocking_move_to(lx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1463. }
  1464. void do_blocking_move_to_z(const float &lz, const float &fr_mm_s/*=0.0*/) {
  1465. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], lz, fr_mm_s);
  1466. }
  1467. void do_blocking_move_to_xy(const float &lx, const float &ly, const float &fr_mm_s/*=0.0*/) {
  1468. do_blocking_move_to(lx, ly, current_position[Z_AXIS], fr_mm_s);
  1469. }
  1470. //
  1471. // Prepare to do endstop or probe moves
  1472. // with custom feedrates.
  1473. //
  1474. // - Save current feedrates
  1475. // - Reset the rate multiplier
  1476. // - Reset the command timeout
  1477. // - Enable the endstops (for endstop moves)
  1478. //
  1479. static void setup_for_endstop_or_probe_move() {
  1480. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1481. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1482. #endif
  1483. saved_feedrate_mm_s = feedrate_mm_s;
  1484. saved_feedrate_percentage = feedrate_percentage;
  1485. feedrate_percentage = 100;
  1486. refresh_cmd_timeout();
  1487. }
  1488. static void clean_up_after_endstop_or_probe_move() {
  1489. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1490. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1491. #endif
  1492. feedrate_mm_s = saved_feedrate_mm_s;
  1493. feedrate_percentage = saved_feedrate_percentage;
  1494. refresh_cmd_timeout();
  1495. }
  1496. #if HAS_BED_PROBE
  1497. /**
  1498. * Raise Z to a minimum height to make room for a probe to move
  1499. */
  1500. inline void do_probe_raise(const float z_raise) {
  1501. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1502. if (DEBUGGING(LEVELING)) {
  1503. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1504. SERIAL_CHAR(')');
  1505. SERIAL_EOL();
  1506. }
  1507. #endif
  1508. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1509. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1510. #if ENABLED(DELTA)
  1511. z_dest -= home_offset[Z_AXIS];
  1512. #endif
  1513. if (z_dest > current_position[Z_AXIS])
  1514. do_blocking_move_to_z(z_dest);
  1515. }
  1516. #endif // HAS_BED_PROBE
  1517. #if HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE) || ENABLED(DELTA_AUTO_CALIBRATION)
  1518. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1519. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1520. const bool xx = x && !axis_known_position[X_AXIS],
  1521. yy = y && !axis_known_position[Y_AXIS],
  1522. zz = z && !axis_known_position[Z_AXIS];
  1523. #else
  1524. const bool xx = x && !axis_homed[X_AXIS],
  1525. yy = y && !axis_homed[Y_AXIS],
  1526. zz = z && !axis_homed[Z_AXIS];
  1527. #endif
  1528. if (xx || yy || zz) {
  1529. SERIAL_ECHO_START();
  1530. SERIAL_ECHOPGM(MSG_HOME " ");
  1531. if (xx) SERIAL_ECHOPGM(MSG_X);
  1532. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1533. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1534. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1535. #if ENABLED(ULTRA_LCD)
  1536. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1537. #endif
  1538. return true;
  1539. }
  1540. return false;
  1541. }
  1542. #endif
  1543. #if ENABLED(Z_PROBE_SLED)
  1544. #ifndef SLED_DOCKING_OFFSET
  1545. #define SLED_DOCKING_OFFSET 0
  1546. #endif
  1547. /**
  1548. * Method to dock/undock a sled designed by Charles Bell.
  1549. *
  1550. * stow[in] If false, move to MAX_X and engage the solenoid
  1551. * If true, move to MAX_X and release the solenoid
  1552. */
  1553. static void dock_sled(bool stow) {
  1554. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1555. if (DEBUGGING(LEVELING)) {
  1556. SERIAL_ECHOPAIR("dock_sled(", stow);
  1557. SERIAL_CHAR(')');
  1558. SERIAL_EOL();
  1559. }
  1560. #endif
  1561. // Dock sled a bit closer to ensure proper capturing
  1562. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1563. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1564. WRITE(SOL1_PIN, !stow); // switch solenoid
  1565. #endif
  1566. }
  1567. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1568. FORCE_INLINE void do_blocking_move_to(const float logical[XYZ], const float &fr_mm_s) {
  1569. do_blocking_move_to(logical[X_AXIS], logical[Y_AXIS], logical[Z_AXIS], fr_mm_s);
  1570. }
  1571. void run_deploy_moves_script() {
  1572. #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)
  1573. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1574. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1575. #endif
  1576. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1577. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1578. #endif
  1579. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1580. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1581. #endif
  1582. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1583. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1584. #endif
  1585. 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 };
  1586. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1587. #endif
  1588. #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)
  1589. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1590. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1591. #endif
  1592. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1593. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1594. #endif
  1595. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1596. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1597. #endif
  1598. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1599. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1600. #endif
  1601. 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 };
  1602. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1603. #endif
  1604. #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)
  1605. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1606. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1607. #endif
  1608. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1609. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1610. #endif
  1611. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1612. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1613. #endif
  1614. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1615. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1616. #endif
  1617. 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 };
  1618. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1619. #endif
  1620. #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)
  1621. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1622. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1623. #endif
  1624. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1625. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1626. #endif
  1627. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1628. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1629. #endif
  1630. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1631. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1632. #endif
  1633. 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 };
  1634. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1635. #endif
  1636. #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)
  1637. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1638. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1639. #endif
  1640. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1641. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1642. #endif
  1643. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1644. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1645. #endif
  1646. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1647. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1648. #endif
  1649. 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 };
  1650. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1651. #endif
  1652. }
  1653. void run_stow_moves_script() {
  1654. #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)
  1655. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1656. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1657. #endif
  1658. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1659. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1660. #endif
  1661. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1662. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1663. #endif
  1664. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1665. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1666. #endif
  1667. 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 };
  1668. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1669. #endif
  1670. #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)
  1671. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1672. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1673. #endif
  1674. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1675. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1676. #endif
  1677. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1678. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1679. #endif
  1680. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1681. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1682. #endif
  1683. 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 };
  1684. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1685. #endif
  1686. #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)
  1687. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1688. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1689. #endif
  1690. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1691. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1692. #endif
  1693. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1694. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1695. #endif
  1696. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1697. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1698. #endif
  1699. 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 };
  1700. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1701. #endif
  1702. #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)
  1703. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1704. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1705. #endif
  1706. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1707. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1708. #endif
  1709. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1710. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1711. #endif
  1712. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1713. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1714. #endif
  1715. 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 };
  1716. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1717. #endif
  1718. #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)
  1719. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1720. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1721. #endif
  1722. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1723. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1724. #endif
  1725. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1726. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1727. #endif
  1728. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1729. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1730. #endif
  1731. 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 };
  1732. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1733. #endif
  1734. }
  1735. #endif
  1736. #if ENABLED(PROBING_FANS_OFF)
  1737. void fans_pause(const bool p) {
  1738. if (p != fans_paused) {
  1739. fans_paused = p;
  1740. if (p)
  1741. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1742. paused_fanSpeeds[x] = fanSpeeds[x];
  1743. fanSpeeds[x] = 0;
  1744. }
  1745. else
  1746. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1747. fanSpeeds[x] = paused_fanSpeeds[x];
  1748. }
  1749. }
  1750. #endif // PROBING_FANS_OFF
  1751. #if HAS_BED_PROBE
  1752. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1753. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1754. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1755. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1756. #else
  1757. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1758. #endif
  1759. #endif
  1760. #if QUIET_PROBING
  1761. void probing_pause(const bool p) {
  1762. #if ENABLED(PROBING_HEATERS_OFF)
  1763. thermalManager.pause(p);
  1764. #endif
  1765. #if ENABLED(PROBING_FANS_OFF)
  1766. fans_pause(p);
  1767. #endif
  1768. if (p) safe_delay(25);
  1769. }
  1770. #endif // QUIET_PROBING
  1771. #if ENABLED(BLTOUCH)
  1772. void bltouch_command(int angle) {
  1773. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1774. safe_delay(BLTOUCH_DELAY);
  1775. }
  1776. void set_bltouch_deployed(const bool deploy) {
  1777. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1778. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1779. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1780. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1781. safe_delay(1500); // Wait for internal self-test to complete.
  1782. // (Measured completion time was 0.65 seconds
  1783. // after reset, deploy, and stow sequence)
  1784. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1785. SERIAL_ERROR_START();
  1786. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1787. stop(); // punt!
  1788. }
  1789. }
  1790. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1791. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1792. if (DEBUGGING(LEVELING)) {
  1793. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1794. SERIAL_CHAR(')');
  1795. SERIAL_EOL();
  1796. }
  1797. #endif
  1798. }
  1799. #endif // BLTOUCH
  1800. // returns false for ok and true for failure
  1801. bool set_probe_deployed(bool deploy) {
  1802. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1803. if (DEBUGGING(LEVELING)) {
  1804. DEBUG_POS("set_probe_deployed", current_position);
  1805. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1806. }
  1807. #endif
  1808. if (endstops.z_probe_enabled == deploy) return false;
  1809. // Make room for probe
  1810. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1811. // When deploying make sure BLTOUCH is not already triggered
  1812. #if ENABLED(BLTOUCH)
  1813. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1814. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1815. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1816. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1817. safe_delay(1500); // wait for internal self test to complete
  1818. // measured completion time was 0.65 seconds
  1819. // after reset, deploy & stow sequence
  1820. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1821. SERIAL_ERROR_START();
  1822. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1823. stop(); // punt!
  1824. return true;
  1825. }
  1826. }
  1827. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1828. #if ENABLED(Z_PROBE_SLED)
  1829. #define _AUE_ARGS true, false, false
  1830. #else
  1831. #define _AUE_ARGS
  1832. #endif
  1833. if (axis_unhomed_error(_AUE_ARGS)) {
  1834. SERIAL_ERROR_START();
  1835. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1836. stop();
  1837. return true;
  1838. }
  1839. #endif
  1840. const float oldXpos = current_position[X_AXIS],
  1841. oldYpos = current_position[Y_AXIS];
  1842. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1843. // If endstop is already false, the Z probe is deployed
  1844. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1845. // Would a goto be less ugly?
  1846. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1847. // for a triggered when stowed manual probe.
  1848. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1849. // otherwise an Allen-Key probe can't be stowed.
  1850. #endif
  1851. #if ENABLED(SOLENOID_PROBE)
  1852. #if HAS_SOLENOID_1
  1853. WRITE(SOL1_PIN, deploy);
  1854. #endif
  1855. #elif ENABLED(Z_PROBE_SLED)
  1856. dock_sled(!deploy);
  1857. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1858. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1859. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1860. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1861. #endif
  1862. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1863. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1864. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1865. if (IsRunning()) {
  1866. SERIAL_ERROR_START();
  1867. SERIAL_ERRORLNPGM("Z-Probe failed");
  1868. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1869. }
  1870. stop();
  1871. return true;
  1872. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1873. #endif
  1874. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1875. endstops.enable_z_probe(deploy);
  1876. return false;
  1877. }
  1878. static void do_probe_move(float z, float fr_mm_m) {
  1879. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1880. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1881. #endif
  1882. // Deploy BLTouch at the start of any probe
  1883. #if ENABLED(BLTOUCH)
  1884. set_bltouch_deployed(true);
  1885. #endif
  1886. #if QUIET_PROBING
  1887. probing_pause(true);
  1888. #endif
  1889. // Move down until probe triggered
  1890. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1891. #if QUIET_PROBING
  1892. probing_pause(false);
  1893. #endif
  1894. // Retract BLTouch immediately after a probe
  1895. #if ENABLED(BLTOUCH)
  1896. set_bltouch_deployed(false);
  1897. #endif
  1898. // Clear endstop flags
  1899. endstops.hit_on_purpose();
  1900. // Get Z where the steppers were interrupted
  1901. set_current_from_steppers_for_axis(Z_AXIS);
  1902. // Tell the planner where we actually are
  1903. SYNC_PLAN_POSITION_KINEMATIC();
  1904. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1905. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1906. #endif
  1907. }
  1908. // Do a single Z probe and return with current_position[Z_AXIS]
  1909. // at the height where the probe triggered.
  1910. static float run_z_probe() {
  1911. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1912. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1913. #endif
  1914. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1915. refresh_cmd_timeout();
  1916. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1917. // Do a first probe at the fast speed
  1918. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1919. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1920. float first_probe_z = current_position[Z_AXIS];
  1921. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1922. #endif
  1923. // move up by the bump distance
  1924. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1925. #else
  1926. // If the nozzle is above the travel height then
  1927. // move down quickly before doing the slow probe
  1928. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1929. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1930. #if ENABLED(DELTA)
  1931. z -= home_offset[Z_AXIS];
  1932. #endif
  1933. if (z < current_position[Z_AXIS])
  1934. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1935. #endif
  1936. // move down slowly to find bed
  1937. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1938. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1939. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1940. #endif
  1941. // Debug: compare probe heights
  1942. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1943. if (DEBUGGING(LEVELING)) {
  1944. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1945. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1946. }
  1947. #endif
  1948. return current_position[Z_AXIS] + zprobe_zoffset;
  1949. }
  1950. /**
  1951. * - Move to the given XY
  1952. * - Deploy the probe, if not already deployed
  1953. * - Probe the bed, get the Z position
  1954. * - Depending on the 'stow' flag
  1955. * - Stow the probe, or
  1956. * - Raise to the BETWEEN height
  1957. * - Return the probed Z position
  1958. */
  1959. float probe_pt(const float &x, const float &y, const bool stow/*=true*/, const int verbose_level/*=1*/) {
  1960. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1961. if (DEBUGGING(LEVELING)) {
  1962. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1963. SERIAL_ECHOPAIR(", ", y);
  1964. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1965. SERIAL_ECHOLNPGM("stow)");
  1966. DEBUG_POS("", current_position);
  1967. }
  1968. #endif
  1969. if (!position_is_reachable_by_probe_xy(x, y)) return NAN;
  1970. const float old_feedrate_mm_s = feedrate_mm_s;
  1971. #if ENABLED(DELTA)
  1972. if (current_position[Z_AXIS] > delta_clip_start_height)
  1973. do_blocking_move_to_z(delta_clip_start_height);
  1974. #endif
  1975. // Ensure a minimum height before moving the probe
  1976. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1977. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1978. // Move the probe to the given XY
  1979. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1980. if (DEPLOY_PROBE()) return NAN;
  1981. const float measured_z = run_z_probe();
  1982. if (!stow)
  1983. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1984. else
  1985. if (STOW_PROBE()) return NAN;
  1986. if (verbose_level > 2) {
  1987. SERIAL_PROTOCOLPGM("Bed X: ");
  1988. SERIAL_PROTOCOL_F(x, 3);
  1989. SERIAL_PROTOCOLPGM(" Y: ");
  1990. SERIAL_PROTOCOL_F(y, 3);
  1991. SERIAL_PROTOCOLPGM(" Z: ");
  1992. SERIAL_PROTOCOL_F(measured_z, 3);
  1993. SERIAL_EOL();
  1994. }
  1995. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1996. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1997. #endif
  1998. feedrate_mm_s = old_feedrate_mm_s;
  1999. return measured_z;
  2000. }
  2001. #endif // HAS_BED_PROBE
  2002. #if HAS_LEVELING
  2003. bool leveling_is_valid() {
  2004. return
  2005. #if ENABLED(MESH_BED_LEVELING)
  2006. mbl.has_mesh()
  2007. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2008. !!bilinear_grid_spacing[X_AXIS]
  2009. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2010. true
  2011. #else // 3POINT, LINEAR
  2012. true
  2013. #endif
  2014. ;
  2015. }
  2016. bool leveling_is_active() {
  2017. return
  2018. #if ENABLED(MESH_BED_LEVELING)
  2019. mbl.active()
  2020. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2021. ubl.state.active
  2022. #else
  2023. planner.abl_enabled
  2024. #endif
  2025. ;
  2026. }
  2027. /**
  2028. * Turn bed leveling on or off, fixing the current
  2029. * position as-needed.
  2030. *
  2031. * Disable: Current position = physical position
  2032. * Enable: Current position = "unleveled" physical position
  2033. */
  2034. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2035. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2036. const bool can_change = (!enable || leveling_is_valid());
  2037. #else
  2038. constexpr bool can_change = true;
  2039. #endif
  2040. if (can_change && enable != leveling_is_active()) {
  2041. #if ENABLED(MESH_BED_LEVELING)
  2042. if (!enable)
  2043. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2044. const bool enabling = enable && leveling_is_valid();
  2045. mbl.set_active(enabling);
  2046. if (enabling) planner.unapply_leveling(current_position);
  2047. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2048. #if PLANNER_LEVELING
  2049. if (ubl.state.active) { // leveling from on to off
  2050. // change unleveled current_position to physical current_position without moving steppers.
  2051. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2052. ubl.state.active = false; // disable only AFTER calling apply_leveling
  2053. }
  2054. else { // leveling from off to on
  2055. ubl.state.active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2056. // change physical current_position to unleveled current_position without moving steppers.
  2057. planner.unapply_leveling(current_position);
  2058. }
  2059. #else
  2060. ubl.state.active = enable; // just flip the bit, current_position will be wrong until next move.
  2061. #endif
  2062. #else // ABL
  2063. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2064. // Force bilinear_z_offset to re-calculate next time
  2065. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2066. (void)bilinear_z_offset(reset);
  2067. #endif
  2068. // Enable or disable leveling compensation in the planner
  2069. planner.abl_enabled = enable;
  2070. if (!enable)
  2071. // When disabling just get the current position from the steppers.
  2072. // This will yield the smallest error when first converted back to steps.
  2073. set_current_from_steppers_for_axis(
  2074. #if ABL_PLANAR
  2075. ALL_AXES
  2076. #else
  2077. Z_AXIS
  2078. #endif
  2079. );
  2080. else
  2081. // When enabling, remove compensation from the current position,
  2082. // so compensation will give the right stepper counts.
  2083. planner.unapply_leveling(current_position);
  2084. #endif // ABL
  2085. }
  2086. }
  2087. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2088. void set_z_fade_height(const float zfh) {
  2089. const bool level_active = leveling_is_active();
  2090. #if ENABLED(AUTO_BED_LEVELING_UBL)
  2091. if (level_active)
  2092. set_bed_leveling_enabled(false); // turn off before changing fade height for proper apply/unapply leveling to maintain current_position
  2093. planner.z_fade_height = zfh;
  2094. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2095. if (level_active)
  2096. set_bed_leveling_enabled(true); // turn back on after changing fade height
  2097. #else
  2098. planner.z_fade_height = zfh;
  2099. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2100. if (level_active) {
  2101. set_current_from_steppers_for_axis(
  2102. #if ABL_PLANAR
  2103. ALL_AXES
  2104. #else
  2105. Z_AXIS
  2106. #endif
  2107. );
  2108. }
  2109. #endif
  2110. }
  2111. #endif // LEVELING_FADE_HEIGHT
  2112. /**
  2113. * Reset calibration results to zero.
  2114. */
  2115. void reset_bed_level() {
  2116. set_bed_leveling_enabled(false);
  2117. #if ENABLED(MESH_BED_LEVELING)
  2118. if (leveling_is_valid()) {
  2119. mbl.reset();
  2120. mbl.set_has_mesh(false);
  2121. }
  2122. #else
  2123. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2124. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2125. #endif
  2126. #if ABL_PLANAR
  2127. planner.bed_level_matrix.set_to_identity();
  2128. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2129. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2130. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2131. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2132. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2133. z_values[x][y] = NAN;
  2134. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2135. ubl.reset();
  2136. #endif
  2137. #endif
  2138. }
  2139. #endif // HAS_LEVELING
  2140. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2141. /**
  2142. * Enable to produce output in JSON format suitable
  2143. * for SCAD or JavaScript mesh visualizers.
  2144. *
  2145. * Visualize meshes in OpenSCAD using the included script.
  2146. *
  2147. * buildroot/shared/scripts/MarlinMesh.scad
  2148. */
  2149. //#define SCAD_MESH_OUTPUT
  2150. /**
  2151. * Print calibration results for plotting or manual frame adjustment.
  2152. */
  2153. static void print_2d_array(const uint8_t sx, const uint8_t sy, const uint8_t precision, float (*fn)(const uint8_t, const uint8_t)) {
  2154. #ifndef SCAD_MESH_OUTPUT
  2155. for (uint8_t x = 0; x < sx; x++) {
  2156. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2157. SERIAL_PROTOCOLCHAR(' ');
  2158. SERIAL_PROTOCOL((int)x);
  2159. }
  2160. SERIAL_EOL();
  2161. #endif
  2162. #ifdef SCAD_MESH_OUTPUT
  2163. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2164. #endif
  2165. for (uint8_t y = 0; y < sy; y++) {
  2166. #ifdef SCAD_MESH_OUTPUT
  2167. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2168. #else
  2169. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2170. SERIAL_PROTOCOL((int)y);
  2171. #endif
  2172. for (uint8_t x = 0; x < sx; x++) {
  2173. SERIAL_PROTOCOLCHAR(' ');
  2174. const float offset = fn(x, y);
  2175. if (!isnan(offset)) {
  2176. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2177. SERIAL_PROTOCOL_F(offset, precision);
  2178. }
  2179. else {
  2180. #ifdef SCAD_MESH_OUTPUT
  2181. for (uint8_t i = 3; i < precision + 3; i++)
  2182. SERIAL_PROTOCOLCHAR(' ');
  2183. SERIAL_PROTOCOLPGM("NAN");
  2184. #else
  2185. for (uint8_t i = 0; i < precision + 3; i++)
  2186. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2187. #endif
  2188. }
  2189. #ifdef SCAD_MESH_OUTPUT
  2190. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2191. #endif
  2192. }
  2193. #ifdef SCAD_MESH_OUTPUT
  2194. SERIAL_PROTOCOLCHAR(' ');
  2195. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2196. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2197. #endif
  2198. SERIAL_EOL();
  2199. }
  2200. #ifdef SCAD_MESH_OUTPUT
  2201. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2202. #endif
  2203. SERIAL_EOL();
  2204. }
  2205. #endif
  2206. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2207. /**
  2208. * Extrapolate a single point from its neighbors
  2209. */
  2210. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2211. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2212. if (DEBUGGING(LEVELING)) {
  2213. SERIAL_ECHOPGM("Extrapolate [");
  2214. if (x < 10) SERIAL_CHAR(' ');
  2215. SERIAL_ECHO((int)x);
  2216. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2217. SERIAL_CHAR(' ');
  2218. if (y < 10) SERIAL_CHAR(' ');
  2219. SERIAL_ECHO((int)y);
  2220. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2221. SERIAL_CHAR(']');
  2222. }
  2223. #endif
  2224. if (!isnan(z_values[x][y])) {
  2225. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2226. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2227. #endif
  2228. return; // Don't overwrite good values.
  2229. }
  2230. SERIAL_EOL();
  2231. // Get X neighbors, Y neighbors, and XY neighbors
  2232. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2233. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2234. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2235. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2236. // Treat far unprobed points as zero, near as equal to far
  2237. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2238. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2239. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2240. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2241. // Take the average instead of the median
  2242. z_values[x][y] = (a + b + c) / 3.0;
  2243. // Median is robust (ignores outliers).
  2244. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2245. // : ((c < b) ? b : (a < c) ? a : c);
  2246. }
  2247. //Enable this if your SCARA uses 180° of total area
  2248. //#define EXTRAPOLATE_FROM_EDGE
  2249. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2250. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2251. #define HALF_IN_X
  2252. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2253. #define HALF_IN_Y
  2254. #endif
  2255. #endif
  2256. /**
  2257. * Fill in the unprobed points (corners of circular print surface)
  2258. * using linear extrapolation, away from the center.
  2259. */
  2260. static void extrapolate_unprobed_bed_level() {
  2261. #ifdef HALF_IN_X
  2262. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2263. #else
  2264. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2265. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2266. xlen = ctrx1;
  2267. #endif
  2268. #ifdef HALF_IN_Y
  2269. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2270. #else
  2271. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2272. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2273. ylen = ctry1;
  2274. #endif
  2275. for (uint8_t xo = 0; xo <= xlen; xo++)
  2276. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2277. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2278. #ifndef HALF_IN_X
  2279. const uint8_t x1 = ctrx1 - xo;
  2280. #endif
  2281. #ifndef HALF_IN_Y
  2282. const uint8_t y1 = ctry1 - yo;
  2283. #ifndef HALF_IN_X
  2284. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2285. #endif
  2286. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2287. #endif
  2288. #ifndef HALF_IN_X
  2289. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2290. #endif
  2291. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2292. }
  2293. }
  2294. static void print_bilinear_leveling_grid() {
  2295. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2296. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2297. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2298. );
  2299. }
  2300. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2301. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2302. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2303. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2304. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2305. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2306. int bilinear_grid_spacing_virt[2] = { 0 };
  2307. float bilinear_grid_factor_virt[2] = { 0 };
  2308. static void bed_level_virt_print() {
  2309. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2310. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2311. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2312. );
  2313. }
  2314. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2315. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2316. uint8_t ep = 0, ip = 1;
  2317. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2318. if (x) {
  2319. ep = GRID_MAX_POINTS_X - 1;
  2320. ip = GRID_MAX_POINTS_X - 2;
  2321. }
  2322. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2323. return LINEAR_EXTRAPOLATION(
  2324. z_values[ep][y - 1],
  2325. z_values[ip][y - 1]
  2326. );
  2327. else
  2328. return LINEAR_EXTRAPOLATION(
  2329. bed_level_virt_coord(ep + 1, y),
  2330. bed_level_virt_coord(ip + 1, y)
  2331. );
  2332. }
  2333. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2334. if (y) {
  2335. ep = GRID_MAX_POINTS_Y - 1;
  2336. ip = GRID_MAX_POINTS_Y - 2;
  2337. }
  2338. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2339. return LINEAR_EXTRAPOLATION(
  2340. z_values[x - 1][ep],
  2341. z_values[x - 1][ip]
  2342. );
  2343. else
  2344. return LINEAR_EXTRAPOLATION(
  2345. bed_level_virt_coord(x, ep + 1),
  2346. bed_level_virt_coord(x, ip + 1)
  2347. );
  2348. }
  2349. return z_values[x - 1][y - 1];
  2350. }
  2351. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2352. return (
  2353. p[i-1] * -t * sq(1 - t)
  2354. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2355. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2356. - p[i+2] * sq(t) * (1 - t)
  2357. ) * 0.5;
  2358. }
  2359. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2360. float row[4], column[4];
  2361. for (uint8_t i = 0; i < 4; i++) {
  2362. for (uint8_t j = 0; j < 4; j++) {
  2363. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2364. }
  2365. row[i] = bed_level_virt_cmr(column, 1, ty);
  2366. }
  2367. return bed_level_virt_cmr(row, 1, tx);
  2368. }
  2369. void bed_level_virt_interpolate() {
  2370. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2371. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2372. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2373. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2374. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2375. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2376. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2377. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2378. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2379. continue;
  2380. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2381. bed_level_virt_2cmr(
  2382. x + 1,
  2383. y + 1,
  2384. (float)tx / (BILINEAR_SUBDIVISIONS),
  2385. (float)ty / (BILINEAR_SUBDIVISIONS)
  2386. );
  2387. }
  2388. }
  2389. #endif // ABL_BILINEAR_SUBDIVISION
  2390. // Refresh after other values have been updated
  2391. void refresh_bed_level() {
  2392. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2393. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2394. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2395. bed_level_virt_interpolate();
  2396. #endif
  2397. }
  2398. #endif // AUTO_BED_LEVELING_BILINEAR
  2399. /**
  2400. * Home an individual linear axis
  2401. */
  2402. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0.0) {
  2403. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2404. if (DEBUGGING(LEVELING)) {
  2405. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2406. SERIAL_ECHOPAIR(", ", distance);
  2407. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2408. SERIAL_CHAR(')');
  2409. SERIAL_EOL();
  2410. }
  2411. #endif
  2412. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2413. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2414. if (deploy_bltouch) set_bltouch_deployed(true);
  2415. #endif
  2416. #if QUIET_PROBING
  2417. if (axis == Z_AXIS) probing_pause(true);
  2418. #endif
  2419. // Tell the planner we're at Z=0
  2420. current_position[axis] = 0;
  2421. #if IS_SCARA
  2422. SYNC_PLAN_POSITION_KINEMATIC();
  2423. current_position[axis] = distance;
  2424. inverse_kinematics(current_position);
  2425. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2426. #else
  2427. sync_plan_position();
  2428. current_position[axis] = distance;
  2429. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate(axis), active_extruder);
  2430. #endif
  2431. stepper.synchronize();
  2432. #if QUIET_PROBING
  2433. if (axis == Z_AXIS) probing_pause(false);
  2434. #endif
  2435. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2436. if (deploy_bltouch) set_bltouch_deployed(false);
  2437. #endif
  2438. endstops.hit_on_purpose();
  2439. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2440. if (DEBUGGING(LEVELING)) {
  2441. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2442. SERIAL_CHAR(')');
  2443. SERIAL_EOL();
  2444. }
  2445. #endif
  2446. }
  2447. /**
  2448. * TMC2130 specific sensorless homing using stallGuard2.
  2449. * stallGuard2 only works when in spreadCycle mode.
  2450. * spreadCycle and stealthChop are mutually exclusive.
  2451. */
  2452. #if ENABLED(SENSORLESS_HOMING)
  2453. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2454. #if ENABLED(STEALTHCHOP)
  2455. if (enable) {
  2456. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2457. st.stealthChop(0);
  2458. }
  2459. else {
  2460. st.coolstep_min_speed(0);
  2461. st.stealthChop(1);
  2462. }
  2463. #endif
  2464. st.diag1_stall(enable ? 1 : 0);
  2465. }
  2466. #endif
  2467. /**
  2468. * Home an individual "raw axis" to its endstop.
  2469. * This applies to XYZ on Cartesian and Core robots, and
  2470. * to the individual ABC steppers on DELTA and SCARA.
  2471. *
  2472. * At the end of the procedure the axis is marked as
  2473. * homed and the current position of that axis is updated.
  2474. * Kinematic robots should wait till all axes are homed
  2475. * before updating the current position.
  2476. */
  2477. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2478. static void homeaxis(const AxisEnum axis) {
  2479. #if IS_SCARA
  2480. // Only Z homing (with probe) is permitted
  2481. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2482. #else
  2483. #define CAN_HOME(A) \
  2484. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2485. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2486. #endif
  2487. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2488. if (DEBUGGING(LEVELING)) {
  2489. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2490. SERIAL_CHAR(')');
  2491. SERIAL_EOL();
  2492. }
  2493. #endif
  2494. const int axis_home_dir =
  2495. #if ENABLED(DUAL_X_CARRIAGE)
  2496. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2497. #endif
  2498. home_dir(axis);
  2499. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2500. #if HOMING_Z_WITH_PROBE
  2501. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2502. #endif
  2503. // Set a flag for Z motor locking
  2504. #if ENABLED(Z_DUAL_ENDSTOPS)
  2505. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2506. #endif
  2507. // Disable stealthChop if used. Enable diag1 pin on driver.
  2508. #if ENABLED(SENSORLESS_HOMING)
  2509. #if ENABLED(X_IS_TMC2130)
  2510. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2511. #endif
  2512. #if ENABLED(Y_IS_TMC2130)
  2513. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2514. #endif
  2515. #endif
  2516. // Fast move towards endstop until triggered
  2517. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2518. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2519. #endif
  2520. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2521. // When homing Z with probe respect probe clearance
  2522. const float bump = axis_home_dir * (
  2523. #if HOMING_Z_WITH_PROBE
  2524. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2525. #endif
  2526. home_bump_mm(axis)
  2527. );
  2528. // If a second homing move is configured...
  2529. if (bump) {
  2530. // Move away from the endstop by the axis HOME_BUMP_MM
  2531. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2532. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2533. #endif
  2534. do_homing_move(axis, -bump);
  2535. // Slow move towards endstop until triggered
  2536. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2537. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2538. #endif
  2539. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2540. }
  2541. #if ENABLED(Z_DUAL_ENDSTOPS)
  2542. if (axis == Z_AXIS) {
  2543. float adj = fabs(z_endstop_adj);
  2544. bool lockZ1;
  2545. if (axis_home_dir > 0) {
  2546. adj = -adj;
  2547. lockZ1 = (z_endstop_adj > 0);
  2548. }
  2549. else
  2550. lockZ1 = (z_endstop_adj < 0);
  2551. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2552. // Move to the adjusted endstop height
  2553. do_homing_move(axis, adj);
  2554. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2555. stepper.set_homing_flag(false);
  2556. } // Z_AXIS
  2557. #endif
  2558. #if IS_SCARA
  2559. set_axis_is_at_home(axis);
  2560. SYNC_PLAN_POSITION_KINEMATIC();
  2561. #elif ENABLED(DELTA)
  2562. // Delta has already moved all three towers up in G28
  2563. // so here it re-homes each tower in turn.
  2564. // Delta homing treats the axes as normal linear axes.
  2565. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2566. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2567. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2568. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2569. #endif
  2570. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2571. }
  2572. #else
  2573. // For cartesian/core machines,
  2574. // set the axis to its home position
  2575. set_axis_is_at_home(axis);
  2576. sync_plan_position();
  2577. destination[axis] = current_position[axis];
  2578. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2579. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2580. #endif
  2581. #endif
  2582. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2583. #if ENABLED(SENSORLESS_HOMING)
  2584. #if ENABLED(X_IS_TMC2130)
  2585. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2586. #endif
  2587. #if ENABLED(Y_IS_TMC2130)
  2588. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2589. #endif
  2590. #endif
  2591. // Put away the Z probe
  2592. #if HOMING_Z_WITH_PROBE
  2593. if (axis == Z_AXIS && STOW_PROBE()) return;
  2594. #endif
  2595. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2596. if (DEBUGGING(LEVELING)) {
  2597. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2598. SERIAL_CHAR(')');
  2599. SERIAL_EOL();
  2600. }
  2601. #endif
  2602. } // homeaxis()
  2603. #if ENABLED(FWRETRACT)
  2604. void retract(const bool retracting, const bool swapping = false) {
  2605. static float hop_height;
  2606. if (retracting == retracted[active_extruder]) return;
  2607. const float old_feedrate_mm_s = feedrate_mm_s;
  2608. set_destination_to_current();
  2609. if (retracting) {
  2610. feedrate_mm_s = retract_feedrate_mm_s;
  2611. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2612. sync_plan_position_e();
  2613. prepare_move_to_destination();
  2614. if (retract_zlift > 0.01) {
  2615. hop_height = current_position[Z_AXIS];
  2616. // Pretend current position is lower
  2617. current_position[Z_AXIS] -= retract_zlift;
  2618. SYNC_PLAN_POSITION_KINEMATIC();
  2619. // Raise up to the old current_position
  2620. prepare_move_to_destination();
  2621. }
  2622. }
  2623. else {
  2624. // If the height hasn't been lowered, undo the Z hop
  2625. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2626. // Pretend current position is higher. Z will lower on the next move
  2627. current_position[Z_AXIS] += retract_zlift;
  2628. SYNC_PLAN_POSITION_KINEMATIC();
  2629. // Lower Z
  2630. prepare_move_to_destination();
  2631. }
  2632. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2633. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2634. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2635. sync_plan_position_e();
  2636. // Recover E
  2637. prepare_move_to_destination();
  2638. }
  2639. feedrate_mm_s = old_feedrate_mm_s;
  2640. retracted[active_extruder] = retracting;
  2641. } // retract()
  2642. #endif // FWRETRACT
  2643. #if ENABLED(MIXING_EXTRUDER)
  2644. void normalize_mix() {
  2645. float mix_total = 0.0;
  2646. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2647. // Scale all values if they don't add up to ~1.0
  2648. if (!NEAR(mix_total, 1.0)) {
  2649. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2650. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2651. }
  2652. }
  2653. #if ENABLED(DIRECT_MIXING_IN_G1)
  2654. // Get mixing parameters from the GCode
  2655. // The total "must" be 1.0 (but it will be normalized)
  2656. // If no mix factors are given, the old mix is preserved
  2657. void gcode_get_mix() {
  2658. const char* mixing_codes = "ABCDHI";
  2659. byte mix_bits = 0;
  2660. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2661. if (parser.seen(mixing_codes[i])) {
  2662. SBI(mix_bits, i);
  2663. float v = parser.value_float();
  2664. NOLESS(v, 0.0);
  2665. mixing_factor[i] = RECIPROCAL(v);
  2666. }
  2667. }
  2668. // If any mixing factors were included, clear the rest
  2669. // If none were included, preserve the last mix
  2670. if (mix_bits) {
  2671. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2672. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2673. normalize_mix();
  2674. }
  2675. }
  2676. #endif
  2677. #endif
  2678. /**
  2679. * ***************************************************************************
  2680. * ***************************** G-CODE HANDLING *****************************
  2681. * ***************************************************************************
  2682. */
  2683. /**
  2684. * Set XYZE destination and feedrate from the current GCode command
  2685. *
  2686. * - Set destination from included axis codes
  2687. * - Set to current for missing axis codes
  2688. * - Set the feedrate, if included
  2689. */
  2690. void gcode_get_destination() {
  2691. LOOP_XYZE(i) {
  2692. if (parser.seen(axis_codes[i]))
  2693. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2694. else
  2695. destination[i] = current_position[i];
  2696. }
  2697. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  2698. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2699. #if ENABLED(PRINTCOUNTER)
  2700. if (!DEBUGGING(DRYRUN))
  2701. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2702. #endif
  2703. // Get ABCDHI mixing factors
  2704. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2705. gcode_get_mix();
  2706. #endif
  2707. }
  2708. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2709. /**
  2710. * Output a "busy" message at regular intervals
  2711. * while the machine is not accepting commands.
  2712. */
  2713. void host_keepalive() {
  2714. const millis_t ms = millis();
  2715. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2716. if (PENDING(ms, next_busy_signal_ms)) return;
  2717. switch (busy_state) {
  2718. case IN_HANDLER:
  2719. case IN_PROCESS:
  2720. SERIAL_ECHO_START();
  2721. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2722. break;
  2723. case PAUSED_FOR_USER:
  2724. SERIAL_ECHO_START();
  2725. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2726. break;
  2727. case PAUSED_FOR_INPUT:
  2728. SERIAL_ECHO_START();
  2729. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2730. break;
  2731. default:
  2732. break;
  2733. }
  2734. }
  2735. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2736. }
  2737. #endif // HOST_KEEPALIVE_FEATURE
  2738. /**************************************************
  2739. ***************** GCode Handlers *****************
  2740. **************************************************/
  2741. /**
  2742. * G0, G1: Coordinated movement of X Y Z E axes
  2743. */
  2744. inline void gcode_G0_G1(
  2745. #if IS_SCARA
  2746. bool fast_move=false
  2747. #endif
  2748. ) {
  2749. if (IsRunning()) {
  2750. gcode_get_destination(); // For X Y Z E F
  2751. #if ENABLED(FWRETRACT)
  2752. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2753. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2754. // Is this move an attempt to retract or recover?
  2755. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2756. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2757. sync_plan_position_e(); // AND from the planner
  2758. retract(!retracted[active_extruder]);
  2759. return;
  2760. }
  2761. }
  2762. #endif // FWRETRACT
  2763. #if IS_SCARA
  2764. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2765. #else
  2766. prepare_move_to_destination();
  2767. #endif
  2768. }
  2769. }
  2770. /**
  2771. * G2: Clockwise Arc
  2772. * G3: Counterclockwise Arc
  2773. *
  2774. * This command has two forms: IJ-form and R-form.
  2775. *
  2776. * - I specifies an X offset. J specifies a Y offset.
  2777. * At least one of the IJ parameters is required.
  2778. * X and Y can be omitted to do a complete circle.
  2779. * The given XY is not error-checked. The arc ends
  2780. * based on the angle of the destination.
  2781. * Mixing I or J with R will throw an error.
  2782. *
  2783. * - R specifies the radius. X or Y is required.
  2784. * Omitting both X and Y will throw an error.
  2785. * X or Y must differ from the current XY.
  2786. * Mixing R with I or J will throw an error.
  2787. *
  2788. * Examples:
  2789. *
  2790. * G2 I10 ; CW circle centered at X+10
  2791. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2792. */
  2793. #if ENABLED(ARC_SUPPORT)
  2794. inline void gcode_G2_G3(bool clockwise) {
  2795. if (IsRunning()) {
  2796. #if ENABLED(SF_ARC_FIX)
  2797. const bool relative_mode_backup = relative_mode;
  2798. relative_mode = true;
  2799. #endif
  2800. gcode_get_destination();
  2801. #if ENABLED(SF_ARC_FIX)
  2802. relative_mode = relative_mode_backup;
  2803. #endif
  2804. float arc_offset[2] = { 0.0, 0.0 };
  2805. if (parser.seen('R')) {
  2806. const float r = parser.value_linear_units(),
  2807. x1 = current_position[X_AXIS], y1 = current_position[Y_AXIS],
  2808. x2 = destination[X_AXIS], y2 = destination[Y_AXIS];
  2809. if (r && (x2 != x1 || y2 != y1)) {
  2810. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2811. dx = x2 - x1, dy = y2 - y1, // X and Y differences
  2812. d = HYPOT(dx, dy), // Linear distance between the points
  2813. h = sqrt(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2814. mx = (x1 + x2) * 0.5, my = (y1 + y2) * 0.5, // Point between the two points
  2815. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2816. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2817. arc_offset[X_AXIS] = cx - x1;
  2818. arc_offset[Y_AXIS] = cy - y1;
  2819. }
  2820. }
  2821. else {
  2822. if (parser.seen('I')) arc_offset[X_AXIS] = parser.value_linear_units();
  2823. if (parser.seen('J')) arc_offset[Y_AXIS] = parser.value_linear_units();
  2824. }
  2825. if (arc_offset[0] || arc_offset[1]) {
  2826. // Send an arc to the planner
  2827. plan_arc(destination, arc_offset, clockwise);
  2828. refresh_cmd_timeout();
  2829. }
  2830. else {
  2831. // Bad arguments
  2832. SERIAL_ERROR_START();
  2833. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2834. }
  2835. }
  2836. }
  2837. #endif
  2838. /**
  2839. * G4: Dwell S<seconds> or P<milliseconds>
  2840. */
  2841. inline void gcode_G4() {
  2842. millis_t dwell_ms = 0;
  2843. if (parser.seen('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2844. if (parser.seen('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2845. stepper.synchronize();
  2846. refresh_cmd_timeout();
  2847. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2848. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2849. while (PENDING(millis(), dwell_ms)) idle();
  2850. }
  2851. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2852. /**
  2853. * Parameters interpreted according to:
  2854. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2855. * However I, J omission is not supported at this point; all
  2856. * parameters can be omitted and default to zero.
  2857. */
  2858. /**
  2859. * G5: Cubic B-spline
  2860. */
  2861. inline void gcode_G5() {
  2862. if (IsRunning()) {
  2863. gcode_get_destination();
  2864. const float offset[] = {
  2865. parser.seen('I') ? parser.value_linear_units() : 0.0,
  2866. parser.seen('J') ? parser.value_linear_units() : 0.0,
  2867. parser.seen('P') ? parser.value_linear_units() : 0.0,
  2868. parser.seen('Q') ? parser.value_linear_units() : 0.0
  2869. };
  2870. plan_cubic_move(offset);
  2871. }
  2872. }
  2873. #endif // BEZIER_CURVE_SUPPORT
  2874. #if ENABLED(FWRETRACT)
  2875. /**
  2876. * G10 - Retract filament according to settings of M207
  2877. * G11 - Recover filament according to settings of M208
  2878. */
  2879. inline void gcode_G10_G11(bool doRetract=false) {
  2880. #if EXTRUDERS > 1
  2881. if (doRetract) {
  2882. retracted_swap[active_extruder] = (parser.seen('S') && parser.value_bool()); // checks for swap retract argument
  2883. }
  2884. #endif
  2885. retract(doRetract
  2886. #if EXTRUDERS > 1
  2887. , retracted_swap[active_extruder]
  2888. #endif
  2889. );
  2890. }
  2891. #endif // FWRETRACT
  2892. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2893. /**
  2894. * G12: Clean the nozzle
  2895. */
  2896. inline void gcode_G12() {
  2897. // Don't allow nozzle cleaning without homing first
  2898. if (axis_unhomed_error()) return;
  2899. const uint8_t pattern = parser.seen('P') ? parser.value_ushort() : 0,
  2900. strokes = parser.seen('S') ? parser.value_ushort() : NOZZLE_CLEAN_STROKES,
  2901. objects = parser.seen('T') ? parser.value_ushort() : NOZZLE_CLEAN_TRIANGLES;
  2902. const float radius = parser.seen('R') ? parser.value_float() : NOZZLE_CLEAN_CIRCLE_RADIUS;
  2903. Nozzle::clean(pattern, strokes, radius, objects);
  2904. }
  2905. #endif
  2906. #if ENABLED(INCH_MODE_SUPPORT)
  2907. /**
  2908. * G20: Set input mode to inches
  2909. */
  2910. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2911. /**
  2912. * G21: Set input mode to millimeters
  2913. */
  2914. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2915. #endif
  2916. #if ENABLED(NOZZLE_PARK_FEATURE)
  2917. /**
  2918. * G27: Park the nozzle
  2919. */
  2920. inline void gcode_G27() {
  2921. // Don't allow nozzle parking without homing first
  2922. if (axis_unhomed_error()) return;
  2923. Nozzle::park(parser.seen('P') ? parser.value_ushort() : 0);
  2924. }
  2925. #endif // NOZZLE_PARK_FEATURE
  2926. #if ENABLED(QUICK_HOME)
  2927. static void quick_home_xy() {
  2928. // Pretend the current position is 0,0
  2929. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2930. sync_plan_position();
  2931. const int x_axis_home_dir =
  2932. #if ENABLED(DUAL_X_CARRIAGE)
  2933. x_home_dir(active_extruder)
  2934. #else
  2935. home_dir(X_AXIS)
  2936. #endif
  2937. ;
  2938. const float mlx = max_length(X_AXIS),
  2939. mly = max_length(Y_AXIS),
  2940. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2941. fr_mm_s = min(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * sqrt(sq(mlratio) + 1.0);
  2942. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2943. endstops.hit_on_purpose(); // clear endstop hit flags
  2944. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2945. }
  2946. #endif // QUICK_HOME
  2947. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2948. void log_machine_info() {
  2949. SERIAL_ECHOPGM("Machine Type: ");
  2950. #if ENABLED(DELTA)
  2951. SERIAL_ECHOLNPGM("Delta");
  2952. #elif IS_SCARA
  2953. SERIAL_ECHOLNPGM("SCARA");
  2954. #elif IS_CORE
  2955. SERIAL_ECHOLNPGM("Core");
  2956. #else
  2957. SERIAL_ECHOLNPGM("Cartesian");
  2958. #endif
  2959. SERIAL_ECHOPGM("Probe: ");
  2960. #if ENABLED(PROBE_MANUALLY)
  2961. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  2962. #elif ENABLED(FIX_MOUNTED_PROBE)
  2963. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  2964. #elif ENABLED(BLTOUCH)
  2965. SERIAL_ECHOLNPGM("BLTOUCH");
  2966. #elif HAS_Z_SERVO_ENDSTOP
  2967. SERIAL_ECHOLNPGM("SERVO PROBE");
  2968. #elif ENABLED(Z_PROBE_SLED)
  2969. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  2970. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2971. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  2972. #else
  2973. SERIAL_ECHOLNPGM("NONE");
  2974. #endif
  2975. #if HAS_BED_PROBE
  2976. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  2977. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  2978. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  2979. #if (X_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2980. SERIAL_ECHOPGM(" (Right");
  2981. #elif (X_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2982. SERIAL_ECHOPGM(" (Left");
  2983. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2984. SERIAL_ECHOPGM(" (Middle");
  2985. #else
  2986. SERIAL_ECHOPGM(" (Aligned With");
  2987. #endif
  2988. #if (Y_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2989. SERIAL_ECHOPGM("-Back");
  2990. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2991. SERIAL_ECHOPGM("-Front");
  2992. #elif (X_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2993. SERIAL_ECHOPGM("-Center");
  2994. #endif
  2995. if (zprobe_zoffset < 0)
  2996. SERIAL_ECHOPGM(" & Below");
  2997. else if (zprobe_zoffset > 0)
  2998. SERIAL_ECHOPGM(" & Above");
  2999. else
  3000. SERIAL_ECHOPGM(" & Same Z as");
  3001. SERIAL_ECHOLNPGM(" Nozzle)");
  3002. #endif
  3003. #if HAS_ABL
  3004. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3005. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3006. SERIAL_ECHOPGM("LINEAR");
  3007. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3008. SERIAL_ECHOPGM("BILINEAR");
  3009. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3010. SERIAL_ECHOPGM("3POINT");
  3011. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3012. SERIAL_ECHOPGM("UBL");
  3013. #endif
  3014. if (leveling_is_active()) {
  3015. SERIAL_ECHOLNPGM(" (enabled)");
  3016. #if ABL_PLANAR
  3017. float diff[XYZ] = {
  3018. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3019. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3020. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3021. };
  3022. SERIAL_ECHOPGM("ABL Adjustment X");
  3023. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3024. SERIAL_ECHO(diff[X_AXIS]);
  3025. SERIAL_ECHOPGM(" Y");
  3026. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3027. SERIAL_ECHO(diff[Y_AXIS]);
  3028. SERIAL_ECHOPGM(" Z");
  3029. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3030. SERIAL_ECHO(diff[Z_AXIS]);
  3031. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3032. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  3033. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3034. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  3035. #endif
  3036. }
  3037. else
  3038. SERIAL_ECHOLNPGM(" (disabled)");
  3039. SERIAL_EOL();
  3040. #elif ENABLED(MESH_BED_LEVELING)
  3041. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3042. if (leveling_is_active()) {
  3043. float lz = current_position[Z_AXIS];
  3044. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  3045. SERIAL_ECHOLNPGM(" (enabled)");
  3046. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  3047. }
  3048. else
  3049. SERIAL_ECHOPGM(" (disabled)");
  3050. SERIAL_EOL();
  3051. #endif // MESH_BED_LEVELING
  3052. }
  3053. #endif // DEBUG_LEVELING_FEATURE
  3054. #if ENABLED(DELTA)
  3055. /**
  3056. * A delta can only safely home all axes at the same time
  3057. * This is like quick_home_xy() but for 3 towers.
  3058. */
  3059. inline void home_delta() {
  3060. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3061. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3062. #endif
  3063. // Init the current position of all carriages to 0,0,0
  3064. ZERO(current_position);
  3065. sync_plan_position();
  3066. // Move all carriages together linearly until an endstop is hit.
  3067. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3068. feedrate_mm_s = homing_feedrate(X_AXIS);
  3069. line_to_current_position();
  3070. stepper.synchronize();
  3071. endstops.hit_on_purpose(); // clear endstop hit flags
  3072. // At least one carriage has reached the top.
  3073. // Now re-home each carriage separately.
  3074. HOMEAXIS(A);
  3075. HOMEAXIS(B);
  3076. HOMEAXIS(C);
  3077. // Set all carriages to their home positions
  3078. // Do this here all at once for Delta, because
  3079. // XYZ isn't ABC. Applying this per-tower would
  3080. // give the impression that they are the same.
  3081. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3082. SYNC_PLAN_POSITION_KINEMATIC();
  3083. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3084. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3085. #endif
  3086. }
  3087. #endif // DELTA
  3088. #if ENABLED(Z_SAFE_HOMING)
  3089. inline void home_z_safely() {
  3090. // Disallow Z homing if X or Y are unknown
  3091. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3092. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3093. SERIAL_ECHO_START();
  3094. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3095. return;
  3096. }
  3097. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3098. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3099. #endif
  3100. SYNC_PLAN_POSITION_KINEMATIC();
  3101. /**
  3102. * Move the Z probe (or just the nozzle) to the safe homing point
  3103. */
  3104. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3105. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3106. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3107. #if HOMING_Z_WITH_PROBE
  3108. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3109. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3110. #endif
  3111. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3112. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3113. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3114. #endif
  3115. // This causes the carriage on Dual X to unpark
  3116. #if ENABLED(DUAL_X_CARRIAGE)
  3117. active_extruder_parked = false;
  3118. #endif
  3119. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3120. HOMEAXIS(Z);
  3121. }
  3122. else {
  3123. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3124. SERIAL_ECHO_START();
  3125. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3126. }
  3127. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3128. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3129. #endif
  3130. }
  3131. #endif // Z_SAFE_HOMING
  3132. #if ENABLED(PROBE_MANUALLY)
  3133. bool g29_in_progress = false;
  3134. #else
  3135. constexpr bool g29_in_progress = false;
  3136. #endif
  3137. /**
  3138. * G28: Home all axes according to settings
  3139. *
  3140. * Parameters
  3141. *
  3142. * None Home to all axes with no parameters.
  3143. * With QUICK_HOME enabled XY will home together, then Z.
  3144. *
  3145. * Cartesian parameters
  3146. *
  3147. * X Home to the X endstop
  3148. * Y Home to the Y endstop
  3149. * Z Home to the Z endstop
  3150. *
  3151. */
  3152. inline void gcode_G28(const bool always_home_all) {
  3153. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3154. if (DEBUGGING(LEVELING)) {
  3155. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3156. log_machine_info();
  3157. }
  3158. #endif
  3159. // Wait for planner moves to finish!
  3160. stepper.synchronize();
  3161. // Cancel the active G29 session
  3162. #if ENABLED(PROBE_MANUALLY)
  3163. g29_in_progress = false;
  3164. #endif
  3165. // Disable the leveling matrix before homing
  3166. #if HAS_LEVELING
  3167. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3168. const bool ubl_state_at_entry = leveling_is_active();
  3169. #endif
  3170. set_bed_leveling_enabled(false);
  3171. #endif
  3172. // Always home with tool 0 active
  3173. #if HOTENDS > 1
  3174. const uint8_t old_tool_index = active_extruder;
  3175. tool_change(0, 0, true);
  3176. #endif
  3177. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3178. extruder_duplication_enabled = false;
  3179. #endif
  3180. setup_for_endstop_or_probe_move();
  3181. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3182. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3183. #endif
  3184. endstops.enable(true); // Enable endstops for next homing move
  3185. #if ENABLED(DELTA)
  3186. home_delta();
  3187. UNUSED(always_home_all);
  3188. #else // NOT DELTA
  3189. const bool homeX = always_home_all || parser.seen('X'),
  3190. homeY = always_home_all || parser.seen('Y'),
  3191. homeZ = always_home_all || parser.seen('Z'),
  3192. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3193. set_destination_to_current();
  3194. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3195. if (home_all || homeZ) {
  3196. HOMEAXIS(Z);
  3197. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3198. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3199. #endif
  3200. }
  3201. #else
  3202. if (home_all || homeX || homeY) {
  3203. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3204. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3205. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3206. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3207. if (DEBUGGING(LEVELING))
  3208. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3209. #endif
  3210. do_blocking_move_to_z(destination[Z_AXIS]);
  3211. }
  3212. }
  3213. #endif
  3214. #if ENABLED(QUICK_HOME)
  3215. if (home_all || (homeX && homeY)) quick_home_xy();
  3216. #endif
  3217. #if ENABLED(HOME_Y_BEFORE_X)
  3218. // Home Y
  3219. if (home_all || homeY) {
  3220. HOMEAXIS(Y);
  3221. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3222. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3223. #endif
  3224. }
  3225. #endif
  3226. // Home X
  3227. if (home_all || homeX) {
  3228. #if ENABLED(DUAL_X_CARRIAGE)
  3229. // Always home the 2nd (right) extruder first
  3230. active_extruder = 1;
  3231. HOMEAXIS(X);
  3232. // Remember this extruder's position for later tool change
  3233. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3234. // Home the 1st (left) extruder
  3235. active_extruder = 0;
  3236. HOMEAXIS(X);
  3237. // Consider the active extruder to be parked
  3238. COPY(raised_parked_position, current_position);
  3239. delayed_move_time = 0;
  3240. active_extruder_parked = true;
  3241. #else
  3242. HOMEAXIS(X);
  3243. #endif
  3244. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3245. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3246. #endif
  3247. }
  3248. #if DISABLED(HOME_Y_BEFORE_X)
  3249. // Home Y
  3250. if (home_all || homeY) {
  3251. HOMEAXIS(Y);
  3252. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3253. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3254. #endif
  3255. }
  3256. #endif
  3257. // Home Z last if homing towards the bed
  3258. #if Z_HOME_DIR < 0
  3259. if (home_all || homeZ) {
  3260. #if ENABLED(Z_SAFE_HOMING)
  3261. home_z_safely();
  3262. #else
  3263. HOMEAXIS(Z);
  3264. #endif
  3265. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3266. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3267. #endif
  3268. } // home_all || homeZ
  3269. #endif // Z_HOME_DIR < 0
  3270. SYNC_PLAN_POSITION_KINEMATIC();
  3271. #endif // !DELTA (gcode_G28)
  3272. endstops.not_homing();
  3273. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3274. // move to a height where we can use the full xy-area
  3275. do_blocking_move_to_z(delta_clip_start_height);
  3276. #endif
  3277. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3278. set_bed_leveling_enabled(ubl_state_at_entry);
  3279. #endif
  3280. clean_up_after_endstop_or_probe_move();
  3281. // Restore the active tool after homing
  3282. #if HOTENDS > 1
  3283. tool_change(old_tool_index, 0, true);
  3284. #endif
  3285. lcd_refresh();
  3286. report_current_position();
  3287. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3288. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3289. #endif
  3290. } // G28
  3291. void home_all_axes() { gcode_G28(true); }
  3292. #if HAS_PROBING_PROCEDURE
  3293. void out_of_range_error(const char* p_edge) {
  3294. SERIAL_PROTOCOLPGM("?Probe ");
  3295. serialprintPGM(p_edge);
  3296. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3297. }
  3298. #endif
  3299. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3300. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3301. extern bool lcd_wait_for_move;
  3302. #endif
  3303. inline void _manual_goto_xy(const float &x, const float &y) {
  3304. const float old_feedrate_mm_s = feedrate_mm_s;
  3305. #if MANUAL_PROBE_HEIGHT > 0
  3306. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3307. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3308. line_to_current_position();
  3309. #endif
  3310. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3311. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3312. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3313. line_to_current_position();
  3314. #if MANUAL_PROBE_HEIGHT > 0
  3315. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3316. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3317. line_to_current_position();
  3318. #endif
  3319. feedrate_mm_s = old_feedrate_mm_s;
  3320. stepper.synchronize();
  3321. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3322. lcd_wait_for_move = false;
  3323. #endif
  3324. }
  3325. #endif
  3326. #if ENABLED(MESH_BED_LEVELING)
  3327. // Save 130 bytes with non-duplication of PSTR
  3328. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3329. void mbl_mesh_report() {
  3330. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3331. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3332. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3333. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3334. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3335. );
  3336. }
  3337. void mesh_probing_done() {
  3338. mbl.set_has_mesh(true);
  3339. home_all_axes();
  3340. set_bed_leveling_enabled(true);
  3341. #if ENABLED(MESH_G28_REST_ORIGIN)
  3342. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3343. set_destination_to_current();
  3344. line_to_destination(homing_feedrate(Z_AXIS));
  3345. stepper.synchronize();
  3346. #endif
  3347. }
  3348. /**
  3349. * G29: Mesh-based Z probe, probes a grid and produces a
  3350. * mesh to compensate for variable bed height
  3351. *
  3352. * Parameters With MESH_BED_LEVELING:
  3353. *
  3354. * S0 Produce a mesh report
  3355. * S1 Start probing mesh points
  3356. * S2 Probe the next mesh point
  3357. * S3 Xn Yn Zn.nn Manually modify a single point
  3358. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3359. * S5 Reset and disable mesh
  3360. *
  3361. * The S0 report the points as below
  3362. *
  3363. * +----> X-axis 1-n
  3364. * |
  3365. * |
  3366. * v Y-axis 1-n
  3367. *
  3368. */
  3369. inline void gcode_G29() {
  3370. static int mbl_probe_index = -1;
  3371. #if HAS_SOFTWARE_ENDSTOPS
  3372. static bool enable_soft_endstops;
  3373. #endif
  3374. const MeshLevelingState state = parser.seen('S') ? (MeshLevelingState)parser.value_byte() : MeshReport;
  3375. if (!WITHIN(state, 0, 5)) {
  3376. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3377. return;
  3378. }
  3379. int8_t px, py;
  3380. switch (state) {
  3381. case MeshReport:
  3382. if (leveling_is_valid()) {
  3383. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3384. mbl_mesh_report();
  3385. }
  3386. else
  3387. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3388. break;
  3389. case MeshStart:
  3390. mbl.reset();
  3391. mbl_probe_index = 0;
  3392. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3393. break;
  3394. case MeshNext:
  3395. if (mbl_probe_index < 0) {
  3396. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3397. return;
  3398. }
  3399. // For each G29 S2...
  3400. if (mbl_probe_index == 0) {
  3401. #if HAS_SOFTWARE_ENDSTOPS
  3402. // For the initial G29 S2 save software endstop state
  3403. enable_soft_endstops = soft_endstops_enabled;
  3404. #endif
  3405. }
  3406. else {
  3407. // For G29 S2 after adjusting Z.
  3408. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3409. #if HAS_SOFTWARE_ENDSTOPS
  3410. soft_endstops_enabled = enable_soft_endstops;
  3411. #endif
  3412. }
  3413. // If there's another point to sample, move there with optional lift.
  3414. if (mbl_probe_index < GRID_MAX_POINTS) {
  3415. mbl.zigzag(mbl_probe_index, px, py);
  3416. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3417. #if HAS_SOFTWARE_ENDSTOPS
  3418. // Disable software endstops to allow manual adjustment
  3419. // If G29 is not completed, they will not be re-enabled
  3420. soft_endstops_enabled = false;
  3421. #endif
  3422. mbl_probe_index++;
  3423. }
  3424. else {
  3425. // One last "return to the bed" (as originally coded) at completion
  3426. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3427. line_to_current_position();
  3428. stepper.synchronize();
  3429. // After recording the last point, activate home and activate
  3430. mbl_probe_index = -1;
  3431. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3432. BUZZ(100, 659);
  3433. BUZZ(100, 698);
  3434. mesh_probing_done();
  3435. }
  3436. break;
  3437. case MeshSet:
  3438. if (parser.seen('X')) {
  3439. px = parser.value_int() - 1;
  3440. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3441. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3442. return;
  3443. }
  3444. }
  3445. else {
  3446. SERIAL_CHAR('X'); echo_not_entered();
  3447. return;
  3448. }
  3449. if (parser.seen('Y')) {
  3450. py = parser.value_int() - 1;
  3451. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3452. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3453. return;
  3454. }
  3455. }
  3456. else {
  3457. SERIAL_CHAR('Y'); echo_not_entered();
  3458. return;
  3459. }
  3460. if (parser.seen('Z')) {
  3461. mbl.z_values[px][py] = parser.value_linear_units();
  3462. }
  3463. else {
  3464. SERIAL_CHAR('Z'); echo_not_entered();
  3465. return;
  3466. }
  3467. break;
  3468. case MeshSetZOffset:
  3469. if (parser.seen('Z')) {
  3470. mbl.z_offset = parser.value_linear_units();
  3471. }
  3472. else {
  3473. SERIAL_CHAR('Z'); echo_not_entered();
  3474. return;
  3475. }
  3476. break;
  3477. case MeshReset:
  3478. reset_bed_level();
  3479. break;
  3480. } // switch(state)
  3481. report_current_position();
  3482. }
  3483. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3484. #if ABL_GRID
  3485. #if ENABLED(PROBE_Y_FIRST)
  3486. #define PR_OUTER_VAR xCount
  3487. #define PR_OUTER_END abl_grid_points_x
  3488. #define PR_INNER_VAR yCount
  3489. #define PR_INNER_END abl_grid_points_y
  3490. #else
  3491. #define PR_OUTER_VAR yCount
  3492. #define PR_OUTER_END abl_grid_points_y
  3493. #define PR_INNER_VAR xCount
  3494. #define PR_INNER_END abl_grid_points_x
  3495. #endif
  3496. #endif
  3497. /**
  3498. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3499. * Will fail if the printer has not been homed with G28.
  3500. *
  3501. * Enhanced G29 Auto Bed Leveling Probe Routine
  3502. *
  3503. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3504. * or alter the bed level data. Useful to check the topology
  3505. * after a first run of G29.
  3506. *
  3507. * J Jettison current bed leveling data
  3508. *
  3509. * V Set the verbose level (0-4). Example: "G29 V3"
  3510. *
  3511. * Parameters With LINEAR leveling only:
  3512. *
  3513. * P Set the size of the grid that will be probed (P x P points).
  3514. * Example: "G29 P4"
  3515. *
  3516. * X Set the X size of the grid that will be probed (X x Y points).
  3517. * Example: "G29 X7 Y5"
  3518. *
  3519. * Y Set the Y size of the grid that will be probed (X x Y points).
  3520. *
  3521. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3522. * This is useful for manual bed leveling and finding flaws in the bed (to
  3523. * assist with part placement).
  3524. * Not supported by non-linear delta printer bed leveling.
  3525. *
  3526. * Parameters With LINEAR and BILINEAR leveling only:
  3527. *
  3528. * S Set the XY travel speed between probe points (in units/min)
  3529. *
  3530. * F Set the Front limit of the probing grid
  3531. * B Set the Back limit of the probing grid
  3532. * L Set the Left limit of the probing grid
  3533. * R Set the Right limit of the probing grid
  3534. *
  3535. * Parameters with DEBUG_LEVELING_FEATURE only:
  3536. *
  3537. * C Make a totally fake grid with no actual probing.
  3538. * For use in testing when no probing is possible.
  3539. *
  3540. * Parameters with BILINEAR leveling only:
  3541. *
  3542. * Z Supply an additional Z probe offset
  3543. *
  3544. * Extra parameters with PROBE_MANUALLY:
  3545. *
  3546. * To do manual probing simply repeat G29 until the procedure is complete.
  3547. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3548. *
  3549. * Q Query leveling and G29 state
  3550. *
  3551. * A Abort current leveling procedure
  3552. *
  3553. * W Write a mesh point. (Ignored during leveling.)
  3554. * X Required X for mesh point
  3555. * Y Required Y for mesh point
  3556. * Z Required Z for mesh point
  3557. *
  3558. * Without PROBE_MANUALLY:
  3559. *
  3560. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3561. * Include "E" to engage/disengage the Z probe for each sample.
  3562. * There's no extra effect if you have a fixed Z probe.
  3563. *
  3564. */
  3565. inline void gcode_G29() {
  3566. // G29 Q is also available if debugging
  3567. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3568. const bool query = parser.seen('Q');
  3569. const uint8_t old_debug_flags = marlin_debug_flags;
  3570. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3571. if (DEBUGGING(LEVELING)) {
  3572. DEBUG_POS(">>> gcode_G29", current_position);
  3573. log_machine_info();
  3574. }
  3575. marlin_debug_flags = old_debug_flags;
  3576. #if DISABLED(PROBE_MANUALLY)
  3577. if (query) return;
  3578. #endif
  3579. #endif
  3580. #if ENABLED(PROBE_MANUALLY)
  3581. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q'), no_action = seenA || seenQ;
  3582. #endif
  3583. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3584. const bool faux = parser.seen('C') && parser.value_bool();
  3585. #elif ENABLED(PROBE_MANUALLY)
  3586. const bool faux = no_action;
  3587. #else
  3588. bool constexpr faux = false;
  3589. #endif
  3590. // Don't allow auto-leveling without homing first
  3591. if (axis_unhomed_error()) return;
  3592. // Define local vars 'static' for manual probing, 'auto' otherwise
  3593. #if ENABLED(PROBE_MANUALLY)
  3594. #define ABL_VAR static
  3595. #else
  3596. #define ABL_VAR
  3597. #endif
  3598. ABL_VAR int verbose_level;
  3599. ABL_VAR float xProbe, yProbe, measured_z;
  3600. ABL_VAR bool dryrun, abl_should_enable;
  3601. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3602. ABL_VAR int abl_probe_index;
  3603. #endif
  3604. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3605. ABL_VAR bool enable_soft_endstops = true;
  3606. #endif
  3607. #if ABL_GRID
  3608. #if ENABLED(PROBE_MANUALLY)
  3609. ABL_VAR uint8_t PR_OUTER_VAR;
  3610. ABL_VAR int8_t PR_INNER_VAR;
  3611. #endif
  3612. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3613. ABL_VAR float xGridSpacing, yGridSpacing;
  3614. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3615. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3616. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3617. ABL_VAR bool do_topography_map;
  3618. #else // Bilinear
  3619. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3620. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3621. #endif
  3622. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3623. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3624. ABL_VAR int abl2;
  3625. #else // Bilinear
  3626. int constexpr abl2 = GRID_MAX_POINTS;
  3627. #endif
  3628. #endif
  3629. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3630. ABL_VAR float zoffset;
  3631. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3632. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3633. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3634. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3635. mean;
  3636. #endif
  3637. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3638. int constexpr abl2 = 3;
  3639. // Probe at 3 arbitrary points
  3640. ABL_VAR vector_3 points[3] = {
  3641. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3642. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3643. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3644. };
  3645. #endif // AUTO_BED_LEVELING_3POINT
  3646. /**
  3647. * On the initial G29 fetch command parameters.
  3648. */
  3649. if (!g29_in_progress) {
  3650. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3651. abl_probe_index = -1;
  3652. #endif
  3653. abl_should_enable = leveling_is_active();
  3654. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3655. if (parser.seen('W')) {
  3656. if (!leveling_is_valid()) {
  3657. SERIAL_ERROR_START();
  3658. SERIAL_ERRORLNPGM("No bilinear grid");
  3659. return;
  3660. }
  3661. const float z = parser.seen('Z') && parser.has_value() ? parser.value_float() : NAN;
  3662. if (!isnan(z) || !WITHIN(z, -10, 10)) {
  3663. SERIAL_ERROR_START();
  3664. SERIAL_ERRORLNPGM("Bad Z value");
  3665. return;
  3666. }
  3667. const float x = parser.seen('X') && parser.has_value() ? parser.value_float() : NAN,
  3668. y = parser.seen('Y') && parser.has_value() ? parser.value_float() : NAN;
  3669. int8_t i = parser.seen('I') && parser.has_value() ? parser.value_byte() : -1,
  3670. j = parser.seen('J') && parser.has_value() ? parser.value_byte() : -1;
  3671. if (!isnan(x) && !isnan(y)) {
  3672. // Get nearest i / j from x / y
  3673. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3674. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3675. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3676. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3677. }
  3678. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3679. set_bed_leveling_enabled(false);
  3680. z_values[i][j] = z;
  3681. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3682. bed_level_virt_interpolate();
  3683. #endif
  3684. set_bed_leveling_enabled(abl_should_enable);
  3685. }
  3686. return;
  3687. } // parser.seen('W')
  3688. #endif
  3689. #if HAS_LEVELING
  3690. // Jettison bed leveling data
  3691. if (parser.seen('J')) {
  3692. reset_bed_level();
  3693. return;
  3694. }
  3695. #endif
  3696. verbose_level = parser.seen('V') && parser.has_value() ? parser.value_int() : 0;
  3697. if (!WITHIN(verbose_level, 0, 4)) {
  3698. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3699. return;
  3700. }
  3701. dryrun = (parser.seen('D') && parser.value_bool())
  3702. #if ENABLED(PROBE_MANUALLY)
  3703. || no_action
  3704. #endif
  3705. ;
  3706. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3707. do_topography_map = verbose_level > 2 || parser.seen('T');
  3708. // X and Y specify points in each direction, overriding the default
  3709. // These values may be saved with the completed mesh
  3710. abl_grid_points_x = parser.seen('X') ? parser.value_int() : GRID_MAX_POINTS_X;
  3711. abl_grid_points_y = parser.seen('Y') ? parser.value_int() : GRID_MAX_POINTS_Y;
  3712. if (parser.seen('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3713. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3714. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3715. return;
  3716. }
  3717. abl2 = abl_grid_points_x * abl_grid_points_y;
  3718. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3719. zoffset = parser.seen('Z') ? parser.value_linear_units() : 0;
  3720. #endif
  3721. #if ABL_GRID
  3722. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.seen('S') ? parser.value_linear_units() : XY_PROBE_SPEED);
  3723. left_probe_bed_position = parser.seen('L') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION);
  3724. right_probe_bed_position = parser.seen('R') ? (int)parser.value_linear_units() : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION);
  3725. front_probe_bed_position = parser.seen('F') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION);
  3726. back_probe_bed_position = parser.seen('B') ? (int)parser.value_linear_units() : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION);
  3727. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3728. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3729. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3730. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3731. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3732. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3733. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3734. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3735. if (left_out || right_out || front_out || back_out) {
  3736. if (left_out) {
  3737. out_of_range_error(PSTR("(L)eft"));
  3738. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3739. }
  3740. if (right_out) {
  3741. out_of_range_error(PSTR("(R)ight"));
  3742. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3743. }
  3744. if (front_out) {
  3745. out_of_range_error(PSTR("(F)ront"));
  3746. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3747. }
  3748. if (back_out) {
  3749. out_of_range_error(PSTR("(B)ack"));
  3750. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3751. }
  3752. return;
  3753. }
  3754. // probe at the points of a lattice grid
  3755. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3756. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3757. #endif // ABL_GRID
  3758. if (verbose_level > 0) {
  3759. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3760. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3761. }
  3762. stepper.synchronize();
  3763. // Disable auto bed leveling during G29
  3764. planner.abl_enabled = false;
  3765. if (!dryrun) {
  3766. // Re-orient the current position without leveling
  3767. // based on where the steppers are positioned.
  3768. set_current_from_steppers_for_axis(ALL_AXES);
  3769. // Sync the planner to where the steppers stopped
  3770. SYNC_PLAN_POSITION_KINEMATIC();
  3771. }
  3772. if (!faux) setup_for_endstop_or_probe_move();
  3773. //xProbe = yProbe = measured_z = 0;
  3774. #if HAS_BED_PROBE
  3775. // Deploy the probe. Probe will raise if needed.
  3776. if (DEPLOY_PROBE()) {
  3777. planner.abl_enabled = abl_should_enable;
  3778. return;
  3779. }
  3780. #endif
  3781. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3782. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3783. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3784. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3785. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3786. ) {
  3787. if (dryrun) {
  3788. // Before reset bed level, re-enable to correct the position
  3789. planner.abl_enabled = abl_should_enable;
  3790. }
  3791. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3792. reset_bed_level();
  3793. // Initialize a grid with the given dimensions
  3794. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3795. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3796. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3797. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3798. // Can't re-enable (on error) until the new grid is written
  3799. abl_should_enable = false;
  3800. }
  3801. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3802. mean = 0.0;
  3803. #endif // AUTO_BED_LEVELING_LINEAR
  3804. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3805. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3806. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3807. #endif
  3808. // Probe at 3 arbitrary points
  3809. points[0].z = points[1].z = points[2].z = 0;
  3810. #endif // AUTO_BED_LEVELING_3POINT
  3811. } // !g29_in_progress
  3812. #if ENABLED(PROBE_MANUALLY)
  3813. // For manual probing, get the next index to probe now.
  3814. // On the first probe this will be incremented to 0.
  3815. if (!no_action) {
  3816. ++abl_probe_index;
  3817. g29_in_progress = true;
  3818. }
  3819. // Abort current G29 procedure, go back to idle state
  3820. if (seenA && g29_in_progress) {
  3821. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3822. #if HAS_SOFTWARE_ENDSTOPS
  3823. soft_endstops_enabled = enable_soft_endstops;
  3824. #endif
  3825. planner.abl_enabled = abl_should_enable;
  3826. g29_in_progress = false;
  3827. #if ENABLED(LCD_BED_LEVELING)
  3828. lcd_wait_for_move = false;
  3829. #endif
  3830. }
  3831. // Query G29 status
  3832. if (verbose_level || seenQ) {
  3833. SERIAL_PROTOCOLPGM("Manual G29 ");
  3834. if (g29_in_progress) {
  3835. SERIAL_PROTOCOLPAIR("point ", min(abl_probe_index + 1, abl2));
  3836. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3837. }
  3838. else
  3839. SERIAL_PROTOCOLLNPGM("idle");
  3840. }
  3841. if (no_action) return;
  3842. if (abl_probe_index == 0) {
  3843. // For the initial G29 save software endstop state
  3844. #if HAS_SOFTWARE_ENDSTOPS
  3845. enable_soft_endstops = soft_endstops_enabled;
  3846. #endif
  3847. }
  3848. else {
  3849. // For G29 after adjusting Z.
  3850. // Save the previous Z before going to the next point
  3851. measured_z = current_position[Z_AXIS];
  3852. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3853. mean += measured_z;
  3854. eqnBVector[abl_probe_index] = measured_z;
  3855. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3856. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3857. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3858. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3859. z_values[xCount][yCount] = measured_z + zoffset;
  3860. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3861. if (DEBUGGING(LEVELING)) {
  3862. SERIAL_PROTOCOLPAIR("Save X", xCount);
  3863. SERIAL_PROTOCOLPAIR(" Y", yCount);
  3864. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  3865. }
  3866. #endif
  3867. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3868. points[abl_probe_index].z = measured_z;
  3869. #endif
  3870. }
  3871. //
  3872. // If there's another point to sample, move there with optional lift.
  3873. //
  3874. #if ABL_GRID
  3875. // Skip any unreachable points
  3876. while (abl_probe_index < abl2) {
  3877. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3878. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3879. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3880. // Probe in reverse order for every other row/column
  3881. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3882. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3883. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3884. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3885. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3886. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3887. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3888. indexIntoAB[xCount][yCount] = abl_probe_index;
  3889. #endif
  3890. // Keep looping till a reachable point is found
  3891. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3892. ++abl_probe_index;
  3893. }
  3894. // Is there a next point to move to?
  3895. if (abl_probe_index < abl2) {
  3896. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3897. #if HAS_SOFTWARE_ENDSTOPS
  3898. // Disable software endstops to allow manual adjustment
  3899. // If G29 is not completed, they will not be re-enabled
  3900. soft_endstops_enabled = false;
  3901. #endif
  3902. return;
  3903. }
  3904. else {
  3905. // Leveling done! Fall through to G29 finishing code below
  3906. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3907. // Re-enable software endstops, if needed
  3908. #if HAS_SOFTWARE_ENDSTOPS
  3909. soft_endstops_enabled = enable_soft_endstops;
  3910. #endif
  3911. }
  3912. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3913. // Probe at 3 arbitrary points
  3914. if (abl_probe_index < 3) {
  3915. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3916. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3917. #if HAS_SOFTWARE_ENDSTOPS
  3918. // Disable software endstops to allow manual adjustment
  3919. // If G29 is not completed, they will not be re-enabled
  3920. soft_endstops_enabled = false;
  3921. #endif
  3922. return;
  3923. }
  3924. else {
  3925. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3926. // Re-enable software endstops, if needed
  3927. #if HAS_SOFTWARE_ENDSTOPS
  3928. soft_endstops_enabled = enable_soft_endstops;
  3929. #endif
  3930. if (!dryrun) {
  3931. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3932. if (planeNormal.z < 0) {
  3933. planeNormal.x *= -1;
  3934. planeNormal.y *= -1;
  3935. planeNormal.z *= -1;
  3936. }
  3937. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3938. // Can't re-enable (on error) until the new grid is written
  3939. abl_should_enable = false;
  3940. }
  3941. }
  3942. #endif // AUTO_BED_LEVELING_3POINT
  3943. #else // !PROBE_MANUALLY
  3944. const bool stow_probe_after_each = parser.seen('E');
  3945. #if ABL_GRID
  3946. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3947. // Outer loop is Y with PROBE_Y_FIRST disabled
  3948. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  3949. int8_t inStart, inStop, inInc;
  3950. if (zig) { // away from origin
  3951. inStart = 0;
  3952. inStop = PR_INNER_END;
  3953. inInc = 1;
  3954. }
  3955. else { // towards origin
  3956. inStart = PR_INNER_END - 1;
  3957. inStop = -1;
  3958. inInc = -1;
  3959. }
  3960. zig ^= true; // zag
  3961. // Inner loop is Y with PROBE_Y_FIRST enabled
  3962. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  3963. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  3964. yBase = front_probe_bed_position + yGridSpacing * yCount;
  3965. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3966. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3967. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3968. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  3969. #endif
  3970. #if IS_KINEMATIC
  3971. // Avoid probing outside the round or hexagonal area
  3972. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  3973. #endif
  3974. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3975. if (isnan(measured_z)) {
  3976. planner.abl_enabled = abl_should_enable;
  3977. return;
  3978. }
  3979. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3980. mean += measured_z;
  3981. eqnBVector[abl_probe_index] = measured_z;
  3982. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3983. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3984. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3985. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3986. z_values[xCount][yCount] = measured_z + zoffset;
  3987. #endif
  3988. abl_should_enable = false;
  3989. idle();
  3990. } // inner
  3991. } // outer
  3992. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3993. // Probe at 3 arbitrary points
  3994. for (uint8_t i = 0; i < 3; ++i) {
  3995. // Retain the last probe position
  3996. xProbe = LOGICAL_X_POSITION(points[i].x);
  3997. yProbe = LOGICAL_Y_POSITION(points[i].y);
  3998. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3999. if (isnan(measured_z)) {
  4000. planner.abl_enabled = abl_should_enable;
  4001. return;
  4002. }
  4003. points[i].z = measured_z;
  4004. }
  4005. if (!dryrun) {
  4006. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4007. if (planeNormal.z < 0) {
  4008. planeNormal.x *= -1;
  4009. planeNormal.y *= -1;
  4010. planeNormal.z *= -1;
  4011. }
  4012. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4013. // Can't re-enable (on error) until the new grid is written
  4014. abl_should_enable = false;
  4015. }
  4016. #endif // AUTO_BED_LEVELING_3POINT
  4017. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  4018. if (STOW_PROBE()) {
  4019. planner.abl_enabled = abl_should_enable;
  4020. return;
  4021. }
  4022. #endif // !PROBE_MANUALLY
  4023. //
  4024. // G29 Finishing Code
  4025. //
  4026. // Unless this is a dry run, auto bed leveling will
  4027. // definitely be enabled after this point.
  4028. //
  4029. // If code above wants to continue leveling, it should
  4030. // return or loop before this point.
  4031. //
  4032. // Restore state after probing
  4033. if (!faux) clean_up_after_endstop_or_probe_move();
  4034. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4035. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4036. #endif
  4037. #if ENABLED(PROBE_MANUALLY)
  4038. g29_in_progress = false;
  4039. #if ENABLED(LCD_BED_LEVELING)
  4040. lcd_wait_for_move = false;
  4041. #endif
  4042. #endif
  4043. // Calculate leveling, print reports, correct the position
  4044. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4045. if (!dryrun) extrapolate_unprobed_bed_level();
  4046. print_bilinear_leveling_grid();
  4047. refresh_bed_level();
  4048. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4049. bed_level_virt_print();
  4050. #endif
  4051. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4052. // For LINEAR leveling calculate matrix, print reports, correct the position
  4053. /**
  4054. * solve the plane equation ax + by + d = z
  4055. * A is the matrix with rows [x y 1] for all the probed points
  4056. * B is the vector of the Z positions
  4057. * the normal vector to the plane is formed by the coefficients of the
  4058. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4059. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4060. */
  4061. float plane_equation_coefficients[3];
  4062. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  4063. mean /= abl2;
  4064. if (verbose_level) {
  4065. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4066. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4067. SERIAL_PROTOCOLPGM(" b: ");
  4068. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4069. SERIAL_PROTOCOLPGM(" d: ");
  4070. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4071. SERIAL_EOL();
  4072. if (verbose_level > 2) {
  4073. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4074. SERIAL_PROTOCOL_F(mean, 8);
  4075. SERIAL_EOL();
  4076. }
  4077. }
  4078. // Create the matrix but don't correct the position yet
  4079. if (!dryrun) {
  4080. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4081. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  4082. );
  4083. }
  4084. // Show the Topography map if enabled
  4085. if (do_topography_map) {
  4086. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4087. " +--- BACK --+\n"
  4088. " | |\n"
  4089. " L | (+) | R\n"
  4090. " E | | I\n"
  4091. " F | (-) N (+) | G\n"
  4092. " T | | H\n"
  4093. " | (-) | T\n"
  4094. " | |\n"
  4095. " O-- FRONT --+\n"
  4096. " (0,0)");
  4097. float min_diff = 999;
  4098. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4099. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4100. int ind = indexIntoAB[xx][yy];
  4101. float diff = eqnBVector[ind] - mean,
  4102. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4103. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4104. z_tmp = 0;
  4105. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4106. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4107. if (diff >= 0.0)
  4108. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4109. else
  4110. SERIAL_PROTOCOLCHAR(' ');
  4111. SERIAL_PROTOCOL_F(diff, 5);
  4112. } // xx
  4113. SERIAL_EOL();
  4114. } // yy
  4115. SERIAL_EOL();
  4116. if (verbose_level > 3) {
  4117. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4118. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4119. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4120. int ind = indexIntoAB[xx][yy];
  4121. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4122. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4123. z_tmp = 0;
  4124. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4125. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4126. if (diff >= 0.0)
  4127. SERIAL_PROTOCOLPGM(" +");
  4128. // Include + for column alignment
  4129. else
  4130. SERIAL_PROTOCOLCHAR(' ');
  4131. SERIAL_PROTOCOL_F(diff, 5);
  4132. } // xx
  4133. SERIAL_EOL();
  4134. } // yy
  4135. SERIAL_EOL();
  4136. }
  4137. } //do_topography_map
  4138. #endif // AUTO_BED_LEVELING_LINEAR
  4139. #if ABL_PLANAR
  4140. // For LINEAR and 3POINT leveling correct the current position
  4141. if (verbose_level > 0)
  4142. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4143. if (!dryrun) {
  4144. //
  4145. // Correct the current XYZ position based on the tilted plane.
  4146. //
  4147. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4148. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4149. #endif
  4150. float converted[XYZ];
  4151. COPY(converted, current_position);
  4152. planner.abl_enabled = true;
  4153. planner.unapply_leveling(converted); // use conversion machinery
  4154. planner.abl_enabled = false;
  4155. // Use the last measured distance to the bed, if possible
  4156. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4157. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4158. ) {
  4159. const float simple_z = current_position[Z_AXIS] - measured_z;
  4160. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4161. if (DEBUGGING(LEVELING)) {
  4162. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4163. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4164. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4165. }
  4166. #endif
  4167. converted[Z_AXIS] = simple_z;
  4168. }
  4169. // The rotated XY and corrected Z are now current_position
  4170. COPY(current_position, converted);
  4171. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4172. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4173. #endif
  4174. }
  4175. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4176. if (!dryrun) {
  4177. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4178. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4179. #endif
  4180. // Unapply the offset because it is going to be immediately applied
  4181. // and cause compensation movement in Z
  4182. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4183. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4184. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4185. #endif
  4186. }
  4187. #endif // ABL_PLANAR
  4188. #ifdef Z_PROBE_END_SCRIPT
  4189. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4190. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4191. #endif
  4192. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4193. stepper.synchronize();
  4194. #endif
  4195. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4196. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4197. #endif
  4198. report_current_position();
  4199. KEEPALIVE_STATE(IN_HANDLER);
  4200. // Auto Bed Leveling is complete! Enable if possible.
  4201. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4202. if (planner.abl_enabled)
  4203. SYNC_PLAN_POSITION_KINEMATIC();
  4204. }
  4205. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4206. #if HAS_BED_PROBE
  4207. /**
  4208. * G30: Do a single Z probe at the current XY
  4209. *
  4210. * Parameters:
  4211. *
  4212. * X Probe X position (default current X)
  4213. * Y Probe Y position (default current Y)
  4214. * S0 Leave the probe deployed
  4215. */
  4216. inline void gcode_G30() {
  4217. const float xpos = parser.seen('X') ? parser.value_linear_units() : current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  4218. ypos = parser.seen('Y') ? parser.value_linear_units() : current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4219. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4220. // Disable leveling so the planner won't mess with us
  4221. #if HAS_LEVELING
  4222. set_bed_leveling_enabled(false);
  4223. #endif
  4224. setup_for_endstop_or_probe_move();
  4225. const float measured_z = probe_pt(xpos, ypos, !parser.seen('S') || parser.value_bool(), 1);
  4226. if (!isnan(measured_z)) {
  4227. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4228. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4229. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4230. }
  4231. clean_up_after_endstop_or_probe_move();
  4232. report_current_position();
  4233. }
  4234. #if ENABLED(Z_PROBE_SLED)
  4235. /**
  4236. * G31: Deploy the Z probe
  4237. */
  4238. inline void gcode_G31() { DEPLOY_PROBE(); }
  4239. /**
  4240. * G32: Stow the Z probe
  4241. */
  4242. inline void gcode_G32() { STOW_PROBE(); }
  4243. #endif // Z_PROBE_SLED
  4244. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4245. /**
  4246. * G33 - Delta '1-4-7-point' Auto-Calibration
  4247. * Calibrate height, endstops, delta radius, and tower angles.
  4248. *
  4249. * Parameters:
  4250. *
  4251. * Pn Number of probe points:
  4252. *
  4253. * P1 Probe center and set height only.
  4254. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4255. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4256. * P4-P7 Probe all positions at different locations and average them.
  4257. *
  4258. * T Don't calibrate tower angle corrections
  4259. *
  4260. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4261. *
  4262. * Vn Verbose level:
  4263. *
  4264. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4265. * V1 Report settings
  4266. * V2 Report settings and probe results
  4267. *
  4268. * E Engage the probe for each point
  4269. */
  4270. inline void gcode_G33() {
  4271. const int8_t probe_points = parser.seen('P') ? parser.value_int() : DELTA_CALIBRATION_DEFAULT_POINTS;
  4272. if (!WITHIN(probe_points, 1, 7)) {
  4273. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1 to 7).");
  4274. return;
  4275. }
  4276. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  4277. if (!WITHIN(verbose_level, 0, 2)) {
  4278. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4279. return;
  4280. }
  4281. const float calibration_precision = parser.seen('C') ? parser.value_float() : 0.0;
  4282. if (calibration_precision < 0) {
  4283. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4284. return;
  4285. }
  4286. const bool towers_set = !parser.seen('T'),
  4287. stow_after_each = parser.seen('E'),
  4288. _1p_calibration = probe_points == 1,
  4289. _4p_calibration = probe_points == 2,
  4290. _4p_towers_points = _4p_calibration && towers_set,
  4291. _4p_opposite_points = _4p_calibration && !towers_set,
  4292. _7p_calibration = probe_points >= 3,
  4293. _7p_half_circle = probe_points == 3,
  4294. _7p_double_circle = probe_points == 5,
  4295. _7p_triple_circle = probe_points == 6,
  4296. _7p_quadruple_circle = probe_points == 7,
  4297. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4298. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4299. if (!_1p_calibration) { // test if the outer radius is reachable
  4300. const float circles = (_7p_quadruple_circle ? 1.5 :
  4301. _7p_triple_circle ? 1.0 :
  4302. _7p_double_circle ? 0.5 : 0),
  4303. radius = (1 + circles * 0.1) * delta_calibration_radius;
  4304. for (uint8_t axis = 1; axis < 13; ++axis) {
  4305. if (!position_is_reachable_xy(cos(RADIANS(180 + 30 * axis)) * radius, sin(RADIANS(180 + 30 * axis)) * radius)) {
  4306. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4307. return;
  4308. }
  4309. }
  4310. }
  4311. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4312. const float dx = (X_PROBE_OFFSET_FROM_EXTRUDER),
  4313. dy = (Y_PROBE_OFFSET_FROM_EXTRUDER);
  4314. int8_t iterations = 0;
  4315. float test_precision,
  4316. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4317. zero_std_dev_old = zero_std_dev,
  4318. e_old[XYZ] = {
  4319. endstop_adj[A_AXIS],
  4320. endstop_adj[B_AXIS],
  4321. endstop_adj[C_AXIS]
  4322. },
  4323. dr_old = delta_radius,
  4324. zh_old = home_offset[Z_AXIS],
  4325. alpha_old = delta_tower_angle_trim[A_AXIS],
  4326. beta_old = delta_tower_angle_trim[B_AXIS];
  4327. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4328. stepper.synchronize();
  4329. #if HAS_LEVELING
  4330. reset_bed_level(); // After calibration bed-level data is no longer valid
  4331. #endif
  4332. #if HOTENDS > 1
  4333. const uint8_t old_tool_index = active_extruder;
  4334. tool_change(0, 0, true);
  4335. #endif
  4336. setup_for_endstop_or_probe_move();
  4337. DEPLOY_PROBE();
  4338. endstops.enable(true);
  4339. home_delta();
  4340. endstops.not_homing();
  4341. // print settings
  4342. SERIAL_PROTOCOLPGM("Checking... AC");
  4343. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4344. SERIAL_EOL();
  4345. LCD_MESSAGEPGM("Checking... AC"); // TODO: Make translatable string
  4346. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4347. if (!_1p_calibration) {
  4348. SERIAL_PROTOCOLPGM(" Ex:");
  4349. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4350. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4351. SERIAL_PROTOCOLPGM(" Ey:");
  4352. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4353. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4354. SERIAL_PROTOCOLPGM(" Ez:");
  4355. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4356. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4357. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4358. }
  4359. SERIAL_EOL();
  4360. if (_7p_calibration && towers_set) {
  4361. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4362. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4363. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4364. SERIAL_PROTOCOLPGM(" Ty:");
  4365. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4366. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4367. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4368. SERIAL_EOL();
  4369. }
  4370. home_offset[Z_AXIS] -= probe_pt(dx, dy, stow_after_each, 1); // 1st probe to set height
  4371. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  4372. do {
  4373. float z_at_pt[13] = { 0.0 }, S1 = 0.0, S2 = 0.0;
  4374. int16_t N = 0;
  4375. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4376. iterations++;
  4377. // Probe the points
  4378. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4379. z_at_pt[0] += probe_pt(dx, dy, stow_after_each, 1);
  4380. }
  4381. if (_7p_calibration) { // probe extra center points
  4382. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4383. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4384. z_at_pt[0] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1);
  4385. }
  4386. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4387. }
  4388. if (!_1p_calibration) { // probe the radius
  4389. bool zig_zag = true;
  4390. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4391. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4392. for (uint8_t axis = start; axis < 13; axis += step) {
  4393. const float offset_circles = _7p_quadruple_circle ? (zig_zag ? 1.5 : 1.0) :
  4394. _7p_triple_circle ? (zig_zag ? 1.0 : 0.5) :
  4395. _7p_double_circle ? (zig_zag ? 0.5 : 0.0) : 0;
  4396. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4397. const float a = RADIANS(180 + 30 * axis),
  4398. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4399. z_at_pt[axis] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1);
  4400. }
  4401. zig_zag = !zig_zag;
  4402. z_at_pt[axis] /= (2 * offset_circles + 1);
  4403. }
  4404. }
  4405. if (_7p_intermed_points) // average intermediates to tower and opposites
  4406. for (uint8_t axis = 1; axis <= 11; axis += 2)
  4407. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4408. S1 += z_at_pt[0];
  4409. S2 += sq(z_at_pt[0]);
  4410. N++;
  4411. if (!_1p_calibration) // std dev from zero plane
  4412. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4413. S1 += z_at_pt[axis];
  4414. S2 += sq(z_at_pt[axis]);
  4415. N++;
  4416. }
  4417. zero_std_dev_old = zero_std_dev;
  4418. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4419. if (iterations == 1) home_offset[Z_AXIS] = zh_old; // reset height after 1st probe change
  4420. // Solve matrices
  4421. if (zero_std_dev < test_precision && zero_std_dev > calibration_precision) {
  4422. COPY(e_old, endstop_adj);
  4423. dr_old = delta_radius;
  4424. zh_old = home_offset[Z_AXIS];
  4425. alpha_old = delta_tower_angle_trim[A_AXIS];
  4426. beta_old = delta_tower_angle_trim[B_AXIS];
  4427. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4428. const float r_diff = delta_radius - delta_calibration_radius,
  4429. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4430. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4431. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4432. #define ZP(N,I) ((N) * z_at_pt[I])
  4433. #define Z1000(I) ZP(1.00, I)
  4434. #define Z1050(I) ZP(h_factor, I)
  4435. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4436. #define Z0350(I) ZP(h_factor / 3.00, I)
  4437. #define Z0175(I) ZP(h_factor / 6.00, I)
  4438. #define Z2250(I) ZP(r_factor, I)
  4439. #define Z0750(I) ZP(r_factor / 3.00, I)
  4440. #define Z0375(I) ZP(r_factor / 6.00, I)
  4441. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4442. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4443. switch (probe_points) {
  4444. case 1:
  4445. test_precision = 0.00;
  4446. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4447. break;
  4448. case 2:
  4449. if (towers_set) {
  4450. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4451. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4452. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4453. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4454. }
  4455. else {
  4456. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4457. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4458. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4459. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4460. }
  4461. break;
  4462. default:
  4463. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4464. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4465. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4466. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4467. if (towers_set) {
  4468. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4469. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4470. }
  4471. break;
  4472. }
  4473. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4474. delta_radius += r_delta;
  4475. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4476. delta_tower_angle_trim[B_AXIS] += t_beta;
  4477. // adjust delta_height and endstops by the max amount
  4478. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4479. home_offset[Z_AXIS] -= z_temp;
  4480. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4481. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4482. }
  4483. else if (zero_std_dev >= test_precision) { // step one back
  4484. COPY(endstop_adj, e_old);
  4485. delta_radius = dr_old;
  4486. home_offset[Z_AXIS] = zh_old;
  4487. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4488. delta_tower_angle_trim[B_AXIS] = beta_old;
  4489. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4490. }
  4491. // print report
  4492. if (verbose_level != 1) {
  4493. SERIAL_PROTOCOLPGM(". c:");
  4494. if (z_at_pt[0] > 0) SERIAL_CHAR('+');
  4495. SERIAL_PROTOCOL_F(z_at_pt[0], 2);
  4496. if (_4p_towers_points || _7p_calibration) {
  4497. SERIAL_PROTOCOLPGM(" x:");
  4498. if (z_at_pt[1] >= 0) SERIAL_CHAR('+');
  4499. SERIAL_PROTOCOL_F(z_at_pt[1], 2);
  4500. SERIAL_PROTOCOLPGM(" y:");
  4501. if (z_at_pt[5] >= 0) SERIAL_CHAR('+');
  4502. SERIAL_PROTOCOL_F(z_at_pt[5], 2);
  4503. SERIAL_PROTOCOLPGM(" z:");
  4504. if (z_at_pt[9] >= 0) SERIAL_CHAR('+');
  4505. SERIAL_PROTOCOL_F(z_at_pt[9], 2);
  4506. }
  4507. if (!_4p_opposite_points) SERIAL_EOL();
  4508. if ((_4p_opposite_points) || _7p_calibration) {
  4509. if (_7p_calibration) {
  4510. SERIAL_CHAR('.');
  4511. SERIAL_PROTOCOL_SP(13);
  4512. }
  4513. SERIAL_PROTOCOLPGM(" yz:");
  4514. if (z_at_pt[7] >= 0) SERIAL_CHAR('+');
  4515. SERIAL_PROTOCOL_F(z_at_pt[7], 2);
  4516. SERIAL_PROTOCOLPGM(" zx:");
  4517. if (z_at_pt[11] >= 0) SERIAL_CHAR('+');
  4518. SERIAL_PROTOCOL_F(z_at_pt[11], 2);
  4519. SERIAL_PROTOCOLPGM(" xy:");
  4520. if (z_at_pt[3] >= 0) SERIAL_CHAR('+');
  4521. SERIAL_PROTOCOL_F(z_at_pt[3], 2);
  4522. SERIAL_EOL();
  4523. }
  4524. }
  4525. if (test_precision != 0.0) { // !forced end
  4526. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) { // end iterations
  4527. SERIAL_PROTOCOLPGM("Calibration OK");
  4528. SERIAL_PROTOCOL_SP(36);
  4529. if (zero_std_dev >= test_precision)
  4530. SERIAL_PROTOCOLPGM("rolling back.");
  4531. else {
  4532. SERIAL_PROTOCOLPGM("std dev:");
  4533. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4534. }
  4535. SERIAL_EOL();
  4536. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4537. }
  4538. else { // !end iterations
  4539. char mess[15] = "No convergence";
  4540. if (iterations < 31)
  4541. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4542. SERIAL_PROTOCOL(mess);
  4543. SERIAL_PROTOCOL_SP(36);
  4544. SERIAL_PROTOCOLPGM("std dev:");
  4545. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4546. SERIAL_EOL();
  4547. lcd_setstatus(mess);
  4548. }
  4549. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4550. if (!_1p_calibration) {
  4551. SERIAL_PROTOCOLPGM(" Ex:");
  4552. if (endstop_adj[A_AXIS] >= 0) SERIAL_CHAR('+');
  4553. SERIAL_PROTOCOL_F(endstop_adj[A_AXIS], 2);
  4554. SERIAL_PROTOCOLPGM(" Ey:");
  4555. if (endstop_adj[B_AXIS] >= 0) SERIAL_CHAR('+');
  4556. SERIAL_PROTOCOL_F(endstop_adj[B_AXIS], 2);
  4557. SERIAL_PROTOCOLPGM(" Ez:");
  4558. if (endstop_adj[C_AXIS] >= 0) SERIAL_CHAR('+');
  4559. SERIAL_PROTOCOL_F(endstop_adj[C_AXIS], 2);
  4560. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4561. }
  4562. SERIAL_EOL();
  4563. if (_7p_calibration && towers_set) {
  4564. SERIAL_PROTOCOLPGM(".Tower angle : Tx:");
  4565. if (delta_tower_angle_trim[A_AXIS] >= 0) SERIAL_CHAR('+');
  4566. SERIAL_PROTOCOL_F(delta_tower_angle_trim[A_AXIS], 2);
  4567. SERIAL_PROTOCOLPGM(" Ty:");
  4568. if (delta_tower_angle_trim[B_AXIS] >= 0) SERIAL_CHAR('+');
  4569. SERIAL_PROTOCOL_F(delta_tower_angle_trim[B_AXIS], 2);
  4570. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4571. SERIAL_EOL();
  4572. }
  4573. if (zero_std_dev >= test_precision || zero_std_dev <= calibration_precision)
  4574. serialprintPGM(save_message);
  4575. SERIAL_EOL();
  4576. }
  4577. else { // forced end
  4578. if (verbose_level == 0) {
  4579. SERIAL_PROTOCOLPGM("End DRY-RUN");
  4580. SERIAL_PROTOCOL_SP(39);
  4581. SERIAL_PROTOCOLPGM("std dev:");
  4582. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4583. SERIAL_EOL();
  4584. }
  4585. else {
  4586. SERIAL_PROTOCOLLNPGM("Calibration OK");
  4587. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4588. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4589. SERIAL_EOL();
  4590. serialprintPGM(save_message);
  4591. SERIAL_EOL();
  4592. }
  4593. }
  4594. endstops.enable(true);
  4595. home_delta();
  4596. endstops.not_homing();
  4597. }
  4598. while (zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31);
  4599. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4600. do_blocking_move_to_z(delta_clip_start_height);
  4601. #endif
  4602. STOW_PROBE();
  4603. clean_up_after_endstop_or_probe_move();
  4604. #if HOTENDS > 1
  4605. tool_change(old_tool_index, 0, true);
  4606. #endif
  4607. }
  4608. #endif // DELTA_AUTO_CALIBRATION
  4609. #endif // HAS_BED_PROBE
  4610. #if ENABLED(G38_PROBE_TARGET)
  4611. static bool G38_run_probe() {
  4612. bool G38_pass_fail = false;
  4613. // Get direction of move and retract
  4614. float retract_mm[XYZ];
  4615. LOOP_XYZ(i) {
  4616. float dist = destination[i] - current_position[i];
  4617. retract_mm[i] = fabs(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4618. }
  4619. stepper.synchronize(); // wait until the machine is idle
  4620. // Move until destination reached or target hit
  4621. endstops.enable(true);
  4622. G38_move = true;
  4623. G38_endstop_hit = false;
  4624. prepare_move_to_destination();
  4625. stepper.synchronize();
  4626. G38_move = false;
  4627. endstops.hit_on_purpose();
  4628. set_current_from_steppers_for_axis(ALL_AXES);
  4629. SYNC_PLAN_POSITION_KINEMATIC();
  4630. if (G38_endstop_hit) {
  4631. G38_pass_fail = true;
  4632. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4633. // Move away by the retract distance
  4634. set_destination_to_current();
  4635. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4636. endstops.enable(false);
  4637. prepare_move_to_destination();
  4638. stepper.synchronize();
  4639. feedrate_mm_s /= 4;
  4640. // Bump the target more slowly
  4641. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4642. endstops.enable(true);
  4643. G38_move = true;
  4644. prepare_move_to_destination();
  4645. stepper.synchronize();
  4646. G38_move = false;
  4647. set_current_from_steppers_for_axis(ALL_AXES);
  4648. SYNC_PLAN_POSITION_KINEMATIC();
  4649. #endif
  4650. }
  4651. endstops.hit_on_purpose();
  4652. endstops.not_homing();
  4653. return G38_pass_fail;
  4654. }
  4655. /**
  4656. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4657. * G38.3 - probe toward workpiece, stop on contact
  4658. *
  4659. * Like G28 except uses Z min probe for all axes
  4660. */
  4661. inline void gcode_G38(bool is_38_2) {
  4662. // Get X Y Z E F
  4663. gcode_get_destination();
  4664. setup_for_endstop_or_probe_move();
  4665. // If any axis has enough movement, do the move
  4666. LOOP_XYZ(i)
  4667. if (fabs(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4668. if (!parser.seen('F')) feedrate_mm_s = homing_feedrate(i);
  4669. // If G38.2 fails throw an error
  4670. if (!G38_run_probe() && is_38_2) {
  4671. SERIAL_ERROR_START();
  4672. SERIAL_ERRORLNPGM("Failed to reach target");
  4673. }
  4674. break;
  4675. }
  4676. clean_up_after_endstop_or_probe_move();
  4677. }
  4678. #endif // G38_PROBE_TARGET
  4679. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4680. /**
  4681. * G42: Move X & Y axes to mesh coordinates (I & J)
  4682. */
  4683. inline void gcode_G42() {
  4684. if (IsRunning()) {
  4685. const bool hasI = parser.seen('I');
  4686. const int8_t ix = parser.has_value() ? parser.value_int() : 0;
  4687. const bool hasJ = parser.seen('J');
  4688. const int8_t iy = parser.has_value() ? parser.value_int() : 0;
  4689. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4690. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4691. return;
  4692. }
  4693. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4694. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4695. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4696. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4697. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4698. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4699. #elif ENABLED(MESH_BED_LEVELING)
  4700. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4701. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4702. #endif
  4703. set_destination_to_current();
  4704. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4705. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4706. if (parser.seen('P') && parser.value_bool()) {
  4707. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4708. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4709. }
  4710. if (parser.seen('F') && parser.value_linear_units() > 0.0)
  4711. feedrate_mm_s = MMM_TO_MMS(parser.value_linear_units());
  4712. // SCARA kinematic has "safe" XY raw moves
  4713. #if IS_SCARA
  4714. prepare_uninterpolated_move_to_destination();
  4715. #else
  4716. prepare_move_to_destination();
  4717. #endif
  4718. }
  4719. }
  4720. #endif // AUTO_BED_LEVELING_UBL
  4721. /**
  4722. * G92: Set current position to given X Y Z E
  4723. */
  4724. inline void gcode_G92() {
  4725. bool didXYZ = false,
  4726. didE = parser.seen('E');
  4727. if (!didE) stepper.synchronize();
  4728. LOOP_XYZE(i) {
  4729. if (parser.seen(axis_codes[i])) {
  4730. #if IS_SCARA
  4731. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4732. if (i != E_AXIS) didXYZ = true;
  4733. #else
  4734. #if HAS_POSITION_SHIFT
  4735. const float p = current_position[i];
  4736. #endif
  4737. float v = parser.value_axis_units((AxisEnum)i);
  4738. current_position[i] = v;
  4739. if (i != E_AXIS) {
  4740. didXYZ = true;
  4741. #if HAS_POSITION_SHIFT
  4742. position_shift[i] += v - p; // Offset the coordinate space
  4743. update_software_endstops((AxisEnum)i);
  4744. #if ENABLED(I2C_POSITION_ENCODERS)
  4745. I2CPEM.encoders[I2CPEM.idx_from_axis((AxisEnum) i)].set_axis_offset(position_shift[i]);
  4746. #endif
  4747. #endif
  4748. }
  4749. #endif
  4750. }
  4751. }
  4752. if (didXYZ)
  4753. SYNC_PLAN_POSITION_KINEMATIC();
  4754. else if (didE)
  4755. sync_plan_position_e();
  4756. report_current_position();
  4757. }
  4758. #if HAS_RESUME_CONTINUE
  4759. /**
  4760. * M0: Unconditional stop - Wait for user button press on LCD
  4761. * M1: Conditional stop - Wait for user button press on LCD
  4762. */
  4763. inline void gcode_M0_M1() {
  4764. const char * const args = parser.string_arg;
  4765. millis_t ms = 0;
  4766. bool hasP = false, hasS = false;
  4767. if (parser.seen('P')) {
  4768. ms = parser.value_millis(); // milliseconds to wait
  4769. hasP = ms > 0;
  4770. }
  4771. if (parser.seen('S')) {
  4772. ms = parser.value_millis_from_seconds(); // seconds to wait
  4773. hasS = ms > 0;
  4774. }
  4775. #if ENABLED(ULTIPANEL)
  4776. if (!hasP && !hasS && args && *args)
  4777. lcd_setstatus(args, true);
  4778. else {
  4779. LCD_MESSAGEPGM(MSG_USERWAIT);
  4780. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4781. dontExpireStatus();
  4782. #endif
  4783. }
  4784. #else
  4785. if (!hasP && !hasS && args && *args) {
  4786. SERIAL_ECHO_START();
  4787. SERIAL_ECHOLN(args);
  4788. }
  4789. #endif
  4790. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4791. wait_for_user = true;
  4792. stepper.synchronize();
  4793. refresh_cmd_timeout();
  4794. if (ms > 0) {
  4795. ms += previous_cmd_ms; // wait until this time for a click
  4796. while (PENDING(millis(), ms) && wait_for_user) idle();
  4797. }
  4798. else {
  4799. #if ENABLED(ULTIPANEL)
  4800. if (lcd_detected()) {
  4801. while (wait_for_user) idle();
  4802. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4803. }
  4804. #else
  4805. while (wait_for_user) idle();
  4806. #endif
  4807. }
  4808. wait_for_user = false;
  4809. KEEPALIVE_STATE(IN_HANDLER);
  4810. }
  4811. #endif // HAS_RESUME_CONTINUE
  4812. #if ENABLED(SPINDLE_LASER_ENABLE)
  4813. /**
  4814. * M3: Spindle Clockwise
  4815. * M4: Spindle Counter-clockwise
  4816. *
  4817. * S0 turns off spindle.
  4818. *
  4819. * If no speed PWM output is defined then M3/M4 just turns it on.
  4820. *
  4821. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4822. * Hardware PWM is required. ISRs are too slow.
  4823. *
  4824. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4825. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4826. *
  4827. * The system automatically sets WGM to Mode 1, so no special
  4828. * initialization is needed.
  4829. *
  4830. * WGM bits for timer 2 are automatically set by the system to
  4831. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4832. * No special initialization is needed.
  4833. *
  4834. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4835. * factors for timers 2, 3, 4, and 5 are acceptable.
  4836. *
  4837. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4838. * the spindle/laser during power-up or when connecting to the host
  4839. * (usually goes through a reset which sets all I/O pins to tri-state)
  4840. *
  4841. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4842. */
  4843. // Wait for spindle to come up to speed
  4844. inline void delay_for_power_up() {
  4845. refresh_cmd_timeout();
  4846. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4847. }
  4848. // Wait for spindle to stop turning
  4849. inline void delay_for_power_down() {
  4850. refresh_cmd_timeout();
  4851. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4852. }
  4853. /**
  4854. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4855. *
  4856. * it accepts inputs of 0-255
  4857. */
  4858. inline void ocr_val_mode() {
  4859. uint8_t spindle_laser_power = parser.value_byte();
  4860. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4861. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4862. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4863. }
  4864. inline void gcode_M3_M4(bool is_M3) {
  4865. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4866. #if SPINDLE_DIR_CHANGE
  4867. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4868. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4869. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4870. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4871. ) {
  4872. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4873. delay_for_power_down();
  4874. }
  4875. digitalWrite(SPINDLE_DIR_PIN, rotation_dir);
  4876. #endif
  4877. /**
  4878. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4879. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4880. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4881. */
  4882. #if ENABLED(SPINDLE_LASER_PWM)
  4883. if (parser.seen('O')) ocr_val_mode();
  4884. else {
  4885. const float spindle_laser_power = parser.seen('S') ? parser.value_float() : 0;
  4886. if (spindle_laser_power == 0) {
  4887. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4888. delay_for_power_down();
  4889. }
  4890. else {
  4891. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4892. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4893. if (spindle_laser_power <= SPEED_POWER_MIN)
  4894. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4895. if (spindle_laser_power >= SPEED_POWER_MAX)
  4896. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4897. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4898. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4899. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4900. delay_for_power_up();
  4901. }
  4902. }
  4903. #else
  4904. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4905. delay_for_power_up();
  4906. #endif
  4907. }
  4908. /**
  4909. * M5 turn off spindle
  4910. */
  4911. inline void gcode_M5() {
  4912. stepper.synchronize();
  4913. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4914. delay_for_power_down();
  4915. }
  4916. #endif // SPINDLE_LASER_ENABLE
  4917. /**
  4918. * M17: Enable power on all stepper motors
  4919. */
  4920. inline void gcode_M17() {
  4921. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4922. enable_all_steppers();
  4923. }
  4924. #if IS_KINEMATIC
  4925. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4926. #else
  4927. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4928. #endif
  4929. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4930. static float resume_position[XYZE];
  4931. static bool move_away_flag = false;
  4932. #if ENABLED(SDSUPPORT)
  4933. static bool sd_print_paused = false;
  4934. #endif
  4935. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4936. static millis_t next_buzz = 0;
  4937. static int8_t runout_beep = 0;
  4938. if (init) next_buzz = runout_beep = 0;
  4939. const millis_t ms = millis();
  4940. if (ELAPSED(ms, next_buzz)) {
  4941. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4942. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4943. BUZZ(300, 2000);
  4944. runout_beep++;
  4945. }
  4946. }
  4947. }
  4948. static void ensure_safe_temperature() {
  4949. bool heaters_heating = true;
  4950. wait_for_heatup = true; // M108 will clear this
  4951. while (wait_for_heatup && heaters_heating) {
  4952. idle();
  4953. heaters_heating = false;
  4954. HOTEND_LOOP() {
  4955. if (thermalManager.degTargetHotend(e) && abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > 3) {
  4956. heaters_heating = true;
  4957. #if ENABLED(ULTIPANEL)
  4958. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  4959. #endif
  4960. break;
  4961. }
  4962. }
  4963. }
  4964. }
  4965. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  4966. const float &unload_length = 0 , const int8_t max_beep_count = 0, const bool show_lcd = false
  4967. ) {
  4968. if (move_away_flag) return false; // already paused
  4969. if (!DEBUGGING(DRYRUN) && unload_length != 0) {
  4970. #if ENABLED(PREVENT_COLD_EXTRUSION)
  4971. if (!thermalManager.allow_cold_extrude &&
  4972. thermalManager.degTargetHotend(active_extruder) < thermalManager.extrude_min_temp) {
  4973. SERIAL_ERROR_START();
  4974. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  4975. return false;
  4976. }
  4977. #endif
  4978. ensure_safe_temperature(); // wait for extruder to heat up before unloading
  4979. }
  4980. // Indicate that the printer is paused
  4981. move_away_flag = true;
  4982. // Pause the print job and timer
  4983. #if ENABLED(SDSUPPORT)
  4984. if (card.sdprinting) {
  4985. card.pauseSDPrint();
  4986. sd_print_paused = true;
  4987. }
  4988. #endif
  4989. print_job_timer.pause();
  4990. // Show initial message and wait for synchronize steppers
  4991. if (show_lcd) {
  4992. #if ENABLED(ULTIPANEL)
  4993. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  4994. #endif
  4995. }
  4996. stepper.synchronize();
  4997. // Save current position
  4998. COPY(resume_position, current_position);
  4999. set_destination_to_current();
  5000. // Initial retract before move to filament change position
  5001. destination[E_AXIS] += retract;
  5002. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  5003. // Lift Z axis
  5004. if (z_lift > 0) {
  5005. destination[Z_AXIS] += z_lift;
  5006. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  5007. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5008. }
  5009. // Move XY axes to filament exchange position
  5010. destination[X_AXIS] = x_pos;
  5011. destination[Y_AXIS] = y_pos;
  5012. clamp_to_software_endstops(destination);
  5013. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5014. stepper.synchronize();
  5015. if (unload_length != 0) {
  5016. if (show_lcd) {
  5017. #if ENABLED(ULTIPANEL)
  5018. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  5019. idle();
  5020. #endif
  5021. }
  5022. // Unload filament
  5023. destination[E_AXIS] += unload_length;
  5024. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  5025. stepper.synchronize();
  5026. if (show_lcd) {
  5027. #if ENABLED(ULTIPANEL)
  5028. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5029. #endif
  5030. }
  5031. #if HAS_BUZZER
  5032. filament_change_beep(max_beep_count, true);
  5033. #endif
  5034. idle();
  5035. }
  5036. // Disable extruders steppers for manual filament changing
  5037. disable_e_steppers();
  5038. safe_delay(100);
  5039. // Start the heater idle timers
  5040. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5041. HOTEND_LOOP()
  5042. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5043. return true;
  5044. }
  5045. static void wait_for_filament_reload(const int8_t max_beep_count = 0) {
  5046. bool nozzle_timed_out = false;
  5047. // Wait for filament insert by user and press button
  5048. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5049. wait_for_user = true; // LCD click or M108 will clear this
  5050. while (wait_for_user) {
  5051. #if HAS_BUZZER
  5052. filament_change_beep(max_beep_count);
  5053. #endif
  5054. if (!nozzle_timed_out)
  5055. HOTEND_LOOP()
  5056. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5057. #if ENABLED(ULTIPANEL)
  5058. if (nozzle_timed_out)
  5059. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  5060. #endif
  5061. idle(true);
  5062. }
  5063. KEEPALIVE_STATE(IN_HANDLER);
  5064. }
  5065. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, const int8_t max_beep_count = 0) {
  5066. bool nozzle_timed_out = false;
  5067. if (!move_away_flag) return;
  5068. // Re-enable the heaters if they timed out
  5069. HOTEND_LOOP() {
  5070. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5071. thermalManager.reset_heater_idle_timer(e);
  5072. }
  5073. if (nozzle_timed_out) ensure_safe_temperature();
  5074. #if HAS_BUZZER
  5075. filament_change_beep(max_beep_count, true);
  5076. #endif
  5077. if (load_length != 0) {
  5078. #if ENABLED(ULTIPANEL)
  5079. // Show "insert filament"
  5080. if (nozzle_timed_out)
  5081. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5082. #endif
  5083. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5084. wait_for_user = true; // LCD click or M108 will clear this
  5085. while (wait_for_user && nozzle_timed_out) {
  5086. #if HAS_BUZZER
  5087. filament_change_beep(max_beep_count);
  5088. #endif
  5089. idle(true);
  5090. }
  5091. KEEPALIVE_STATE(IN_HANDLER);
  5092. #if ENABLED(ULTIPANEL)
  5093. // Show "load" message
  5094. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5095. #endif
  5096. // Load filament
  5097. destination[E_AXIS] += load_length;
  5098. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5099. stepper.synchronize();
  5100. }
  5101. #if ENABLED(ULTIPANEL) && defined(ADVANCED_PAUSE_EXTRUDE_LENGTH) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5102. float extrude_length = initial_extrude_length;
  5103. do {
  5104. if (extrude_length > 0) {
  5105. // "Wait for filament extrude"
  5106. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5107. // Extrude filament to get into hotend
  5108. destination[E_AXIS] += extrude_length;
  5109. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5110. stepper.synchronize();
  5111. }
  5112. // Show "Extrude More" / "Resume" menu and wait for reply
  5113. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5114. wait_for_user = false;
  5115. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5116. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5117. KEEPALIVE_STATE(IN_HANDLER);
  5118. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5119. // Keep looping if "Extrude More" was selected
  5120. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5121. #endif
  5122. #if ENABLED(ULTIPANEL)
  5123. // "Wait for print to resume"
  5124. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5125. #endif
  5126. // Set extruder to saved position
  5127. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5128. planner.set_e_position_mm(current_position[E_AXIS]);
  5129. #if IS_KINEMATIC
  5130. // Move XYZ to starting position
  5131. planner.buffer_line_kinematic(resume_position, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5132. #else
  5133. // Move XY to starting position, then Z
  5134. destination[X_AXIS] = resume_position[X_AXIS];
  5135. destination[Y_AXIS] = resume_position[Y_AXIS];
  5136. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5137. destination[Z_AXIS] = resume_position[Z_AXIS];
  5138. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5139. #endif
  5140. stepper.synchronize();
  5141. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5142. filament_ran_out = false;
  5143. #endif
  5144. set_current_to_destination();
  5145. #if ENABLED(ULTIPANEL)
  5146. // Show status screen
  5147. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5148. #endif
  5149. #if ENABLED(SDSUPPORT)
  5150. if (sd_print_paused) {
  5151. card.startFileprint();
  5152. sd_print_paused = false;
  5153. }
  5154. #endif
  5155. move_away_flag = false;
  5156. }
  5157. #endif // ADVANCED_PAUSE_FEATURE
  5158. #if ENABLED(SDSUPPORT)
  5159. /**
  5160. * M20: List SD card to serial output
  5161. */
  5162. inline void gcode_M20() {
  5163. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5164. card.ls();
  5165. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5166. }
  5167. /**
  5168. * M21: Init SD Card
  5169. */
  5170. inline void gcode_M21() { card.initsd(); }
  5171. /**
  5172. * M22: Release SD Card
  5173. */
  5174. inline void gcode_M22() { card.release(); }
  5175. /**
  5176. * M23: Open a file
  5177. */
  5178. inline void gcode_M23() { card.openFile(parser.string_arg, true); }
  5179. /**
  5180. * M24: Start or Resume SD Print
  5181. */
  5182. inline void gcode_M24() {
  5183. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5184. resume_print();
  5185. #endif
  5186. card.startFileprint();
  5187. print_job_timer.start();
  5188. }
  5189. /**
  5190. * M25: Pause SD Print
  5191. */
  5192. inline void gcode_M25() {
  5193. card.pauseSDPrint();
  5194. print_job_timer.pause();
  5195. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5196. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5197. #endif
  5198. }
  5199. /**
  5200. * M26: Set SD Card file index
  5201. */
  5202. inline void gcode_M26() {
  5203. if (card.cardOK && parser.seen('S'))
  5204. card.setIndex(parser.value_long());
  5205. }
  5206. /**
  5207. * M27: Get SD Card status
  5208. */
  5209. inline void gcode_M27() { card.getStatus(); }
  5210. /**
  5211. * M28: Start SD Write
  5212. */
  5213. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5214. /**
  5215. * M29: Stop SD Write
  5216. * Processed in write to file routine above
  5217. */
  5218. inline void gcode_M29() {
  5219. // card.saving = false;
  5220. }
  5221. /**
  5222. * M30 <filename>: Delete SD Card file
  5223. */
  5224. inline void gcode_M30() {
  5225. if (card.cardOK) {
  5226. card.closefile();
  5227. card.removeFile(parser.string_arg);
  5228. }
  5229. }
  5230. #endif // SDSUPPORT
  5231. /**
  5232. * M31: Get the time since the start of SD Print (or last M109)
  5233. */
  5234. inline void gcode_M31() {
  5235. char buffer[21];
  5236. duration_t elapsed = print_job_timer.duration();
  5237. elapsed.toString(buffer);
  5238. lcd_setstatus(buffer);
  5239. SERIAL_ECHO_START();
  5240. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5241. }
  5242. #if ENABLED(SDSUPPORT)
  5243. /**
  5244. * M32: Select file and start SD Print
  5245. */
  5246. inline void gcode_M32() {
  5247. if (card.sdprinting)
  5248. stepper.synchronize();
  5249. char* namestartpos = parser.string_arg;
  5250. bool call_procedure = parser.seen('P');
  5251. if (card.cardOK) {
  5252. card.openFile(namestartpos, true, call_procedure);
  5253. if (parser.seen('S'))
  5254. card.setIndex(parser.value_long());
  5255. card.startFileprint();
  5256. // Procedure calls count as normal print time.
  5257. if (!call_procedure) print_job_timer.start();
  5258. }
  5259. }
  5260. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5261. /**
  5262. * M33: Get the long full path of a file or folder
  5263. *
  5264. * Parameters:
  5265. * <dospath> Case-insensitive DOS-style path to a file or folder
  5266. *
  5267. * Example:
  5268. * M33 miscel~1/armchair/armcha~1.gco
  5269. *
  5270. * Output:
  5271. * /Miscellaneous/Armchair/Armchair.gcode
  5272. */
  5273. inline void gcode_M33() {
  5274. card.printLongPath(parser.string_arg);
  5275. }
  5276. #endif
  5277. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5278. /**
  5279. * M34: Set SD Card Sorting Options
  5280. */
  5281. inline void gcode_M34() {
  5282. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5283. if (parser.seen('F')) {
  5284. int v = parser.value_long();
  5285. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5286. }
  5287. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5288. }
  5289. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5290. /**
  5291. * M928: Start SD Write
  5292. */
  5293. inline void gcode_M928() {
  5294. card.openLogFile(parser.string_arg);
  5295. }
  5296. #endif // SDSUPPORT
  5297. /**
  5298. * Sensitive pin test for M42, M226
  5299. */
  5300. static bool pin_is_protected(const int8_t pin) {
  5301. static const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  5302. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5303. if (pin == (int8_t)pgm_read_byte(&sensitive_pins[i])) return true;
  5304. return false;
  5305. }
  5306. /**
  5307. * M42: Change pin status via GCode
  5308. *
  5309. * P<pin> Pin number (LED if omitted)
  5310. * S<byte> Pin status from 0 - 255
  5311. */
  5312. inline void gcode_M42() {
  5313. if (!parser.seen('S')) return;
  5314. int pin_status = parser.value_int();
  5315. if (!WITHIN(pin_status, 0, 255)) return;
  5316. int pin_number = parser.seen('P') ? parser.value_int() : LED_PIN;
  5317. if (pin_number < 0) return;
  5318. if (pin_is_protected(pin_number)) {
  5319. SERIAL_ERROR_START();
  5320. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5321. return;
  5322. }
  5323. pinMode(pin_number, OUTPUT);
  5324. digitalWrite(pin_number, pin_status);
  5325. analogWrite(pin_number, pin_status);
  5326. #if FAN_COUNT > 0
  5327. switch (pin_number) {
  5328. #if HAS_FAN0
  5329. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5330. #endif
  5331. #if HAS_FAN1
  5332. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5333. #endif
  5334. #if HAS_FAN2
  5335. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5336. #endif
  5337. }
  5338. #endif
  5339. }
  5340. #if ENABLED(PINS_DEBUGGING)
  5341. #include "pinsDebug.h"
  5342. inline void toggle_pins() {
  5343. const bool I_flag = parser.seen('I') && parser.value_bool();
  5344. const int repeat = parser.seen('R') ? parser.value_int() : 1,
  5345. start = parser.seen('S') ? parser.value_int() : 0,
  5346. end = parser.seen('E') ? parser.value_int() : NUM_DIGITAL_PINS - 1,
  5347. wait = parser.seen('W') ? parser.value_int() : 500;
  5348. for (uint8_t pin = start; pin <= end; pin++) {
  5349. //report_pin_state_extended(pin, I_flag, false);
  5350. if (!I_flag && pin_is_protected(pin)) {
  5351. report_pin_state_extended(pin, I_flag, true, "Untouched ");
  5352. SERIAL_EOL();
  5353. }
  5354. else {
  5355. report_pin_state_extended(pin, I_flag, true, "Pulsing ");
  5356. #ifdef AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  5357. if (pin == 46) {
  5358. SET_OUTPUT(46);
  5359. for (int16_t j = 0; j < repeat; j++) {
  5360. WRITE(46, 0); safe_delay(wait);
  5361. WRITE(46, 1); safe_delay(wait);
  5362. WRITE(46, 0); safe_delay(wait);
  5363. }
  5364. }
  5365. else if (pin == 47) {
  5366. SET_OUTPUT(47);
  5367. for (int16_t j = 0; j < repeat; j++) {
  5368. WRITE(47, 0); safe_delay(wait);
  5369. WRITE(47, 1); safe_delay(wait);
  5370. WRITE(47, 0); safe_delay(wait);
  5371. }
  5372. }
  5373. else
  5374. #endif
  5375. {
  5376. pinMode(pin, OUTPUT);
  5377. for (int16_t j = 0; j < repeat; j++) {
  5378. digitalWrite(pin, 0); safe_delay(wait);
  5379. digitalWrite(pin, 1); safe_delay(wait);
  5380. digitalWrite(pin, 0); safe_delay(wait);
  5381. }
  5382. }
  5383. }
  5384. SERIAL_EOL();
  5385. }
  5386. SERIAL_ECHOLNPGM("Done.");
  5387. } // toggle_pins
  5388. inline void servo_probe_test() {
  5389. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5390. SERIAL_ERROR_START();
  5391. SERIAL_ERRORLNPGM("SERVO not setup");
  5392. #elif !HAS_Z_SERVO_ENDSTOP
  5393. SERIAL_ERROR_START();
  5394. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5395. #else
  5396. const uint8_t probe_index = parser.seen('P') ? parser.value_byte() : Z_ENDSTOP_SERVO_NR;
  5397. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5398. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5399. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5400. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5401. bool probe_inverting;
  5402. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5403. #define PROBE_TEST_PIN Z_MIN_PIN
  5404. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5405. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5406. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5407. #if Z_MIN_ENDSTOP_INVERTING
  5408. SERIAL_PROTOCOLLNPGM("true");
  5409. #else
  5410. SERIAL_PROTOCOLLNPGM("false");
  5411. #endif
  5412. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5413. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5414. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5415. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5416. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5417. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5418. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5419. SERIAL_PROTOCOLLNPGM("true");
  5420. #else
  5421. SERIAL_PROTOCOLLNPGM("false");
  5422. #endif
  5423. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5424. #endif
  5425. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5426. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  5427. bool deploy_state, stow_state;
  5428. for (uint8_t i = 0; i < 4; i++) {
  5429. servo[probe_index].move(z_servo_angle[0]); //deploy
  5430. safe_delay(500);
  5431. deploy_state = digitalRead(PROBE_TEST_PIN);
  5432. servo[probe_index].move(z_servo_angle[1]); //stow
  5433. safe_delay(500);
  5434. stow_state = digitalRead(PROBE_TEST_PIN);
  5435. }
  5436. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5437. refresh_cmd_timeout();
  5438. if (deploy_state != stow_state) {
  5439. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5440. if (deploy_state) {
  5441. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5442. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5443. }
  5444. else {
  5445. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5446. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5447. }
  5448. #if ENABLED(BLTOUCH)
  5449. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5450. #endif
  5451. }
  5452. else { // measure active signal length
  5453. servo[probe_index].move(z_servo_angle[0]); // deploy
  5454. safe_delay(500);
  5455. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5456. uint16_t probe_counter = 0;
  5457. // Allow 30 seconds max for operator to trigger probe
  5458. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5459. safe_delay(2);
  5460. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5461. refresh_cmd_timeout();
  5462. if (deploy_state != digitalRead(PROBE_TEST_PIN)) { // probe triggered
  5463. for (probe_counter = 1; probe_counter < 50 && deploy_state != digitalRead(PROBE_TEST_PIN); ++probe_counter)
  5464. safe_delay(2);
  5465. if (probe_counter == 50)
  5466. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5467. else if (probe_counter >= 2)
  5468. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5469. else
  5470. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5471. servo[probe_index].move(z_servo_angle[1]); //stow
  5472. } // pulse detected
  5473. } // for loop waiting for trigger
  5474. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5475. } // measure active signal length
  5476. #endif
  5477. } // servo_probe_test
  5478. /**
  5479. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5480. *
  5481. * M43 - report name and state of pin(s)
  5482. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5483. * I Flag to ignore Marlin's pin protection.
  5484. *
  5485. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5486. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5487. * I Flag to ignore Marlin's pin protection.
  5488. *
  5489. * M43 E<bool> - Enable / disable background endstop monitoring
  5490. * - Machine continues to operate
  5491. * - Reports changes to endstops
  5492. * - Toggles LED_PIN when an endstop changes
  5493. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5494. *
  5495. * M43 T - Toggle pin(s) and report which pin is being toggled
  5496. * S<pin> - Start Pin number. If not given, will default to 0
  5497. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5498. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5499. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5500. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5501. *
  5502. * M43 S - Servo probe test
  5503. * P<index> - Probe index (optional - defaults to 0
  5504. */
  5505. inline void gcode_M43() {
  5506. if (parser.seen('T')) { // must be first or else it's "S" and "E" parameters will execute endstop or servo test
  5507. toggle_pins();
  5508. return;
  5509. }
  5510. // Enable or disable endstop monitoring
  5511. if (parser.seen('E')) {
  5512. endstop_monitor_flag = parser.value_bool();
  5513. SERIAL_PROTOCOLPGM("endstop monitor ");
  5514. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  5515. SERIAL_PROTOCOLLNPGM("abled");
  5516. return;
  5517. }
  5518. if (parser.seen('S')) {
  5519. servo_probe_test();
  5520. return;
  5521. }
  5522. // Get the range of pins to test or watch
  5523. const uint8_t first_pin = parser.seen('P') ? parser.value_byte() : 0,
  5524. last_pin = parser.seen('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5525. if (first_pin > last_pin) return;
  5526. const bool ignore_protection = parser.seen('I') && parser.value_bool();
  5527. // Watch until click, M108, or reset
  5528. if (parser.seen('W') && parser.value_bool()) {
  5529. SERIAL_PROTOCOLLNPGM("Watching pins");
  5530. byte pin_state[last_pin - first_pin + 1];
  5531. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5532. if (pin_is_protected(pin) && !ignore_protection) continue;
  5533. pinMode(pin, INPUT_PULLUP);
  5534. delay(1);
  5535. /*
  5536. if (IS_ANALOG(pin))
  5537. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5538. else
  5539. //*/
  5540. pin_state[pin - first_pin] = digitalRead(pin);
  5541. }
  5542. #if HAS_RESUME_CONTINUE
  5543. wait_for_user = true;
  5544. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5545. #endif
  5546. for (;;) {
  5547. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5548. if (pin_is_protected(pin) && !ignore_protection) continue;
  5549. const byte val =
  5550. /*
  5551. IS_ANALOG(pin)
  5552. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5553. :
  5554. //*/
  5555. digitalRead(pin);
  5556. if (val != pin_state[pin - first_pin]) {
  5557. report_pin_state_extended(pin, ignore_protection, false);
  5558. pin_state[pin - first_pin] = val;
  5559. }
  5560. }
  5561. #if HAS_RESUME_CONTINUE
  5562. if (!wait_for_user) {
  5563. KEEPALIVE_STATE(IN_HANDLER);
  5564. break;
  5565. }
  5566. #endif
  5567. safe_delay(200);
  5568. }
  5569. return;
  5570. }
  5571. // Report current state of selected pin(s)
  5572. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5573. report_pin_state_extended(pin, ignore_protection, true);
  5574. }
  5575. #endif // PINS_DEBUGGING
  5576. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5577. /**
  5578. * M48: Z probe repeatability measurement function.
  5579. *
  5580. * Usage:
  5581. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5582. * P = Number of sampled points (4-50, default 10)
  5583. * X = Sample X position
  5584. * Y = Sample Y position
  5585. * V = Verbose level (0-4, default=1)
  5586. * E = Engage Z probe for each reading
  5587. * L = Number of legs of movement before probe
  5588. * S = Schizoid (Or Star if you prefer)
  5589. *
  5590. * This function assumes the bed has been homed. Specifically, that a G28 command
  5591. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5592. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5593. * regenerated.
  5594. */
  5595. inline void gcode_M48() {
  5596. if (axis_unhomed_error()) return;
  5597. const int8_t verbose_level = parser.seen('V') ? parser.value_byte() : 1;
  5598. if (!WITHIN(verbose_level, 0, 4)) {
  5599. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5600. return;
  5601. }
  5602. if (verbose_level > 0)
  5603. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5604. int8_t n_samples = parser.seen('P') ? parser.value_byte() : 10;
  5605. if (!WITHIN(n_samples, 4, 50)) {
  5606. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5607. return;
  5608. }
  5609. const bool stow_probe_after_each = parser.seen('E');
  5610. float X_current = current_position[X_AXIS],
  5611. Y_current = current_position[Y_AXIS];
  5612. const float X_probe_location = parser.seen('X') ? parser.value_linear_units() : X_current + X_PROBE_OFFSET_FROM_EXTRUDER,
  5613. Y_probe_location = parser.seen('Y') ? parser.value_linear_units() : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  5614. #if DISABLED(DELTA)
  5615. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5616. out_of_range_error(PSTR("X"));
  5617. return;
  5618. }
  5619. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5620. out_of_range_error(PSTR("Y"));
  5621. return;
  5622. }
  5623. #else
  5624. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5625. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5626. return;
  5627. }
  5628. #endif
  5629. bool seen_L = parser.seen('L');
  5630. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5631. if (n_legs > 15) {
  5632. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5633. return;
  5634. }
  5635. if (n_legs == 1) n_legs = 2;
  5636. bool schizoid_flag = parser.seen('S');
  5637. if (schizoid_flag && !seen_L) n_legs = 7;
  5638. /**
  5639. * Now get everything to the specified probe point So we can safely do a
  5640. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5641. * we don't want to use that as a starting point for each probe.
  5642. */
  5643. if (verbose_level > 2)
  5644. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5645. // Disable bed level correction in M48 because we want the raw data when we probe
  5646. #if HAS_LEVELING
  5647. const bool was_enabled = leveling_is_active();
  5648. set_bed_leveling_enabled(false);
  5649. #endif
  5650. setup_for_endstop_or_probe_move();
  5651. // Move to the first point, deploy, and probe
  5652. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5653. if (isnan(t)) return;
  5654. randomSeed(millis());
  5655. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5656. for (uint8_t n = 0; n < n_samples; n++) {
  5657. if (n_legs) {
  5658. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5659. float angle = random(0.0, 360.0),
  5660. radius = random(
  5661. #if ENABLED(DELTA)
  5662. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5663. #else
  5664. 5, X_MAX_LENGTH / 8
  5665. #endif
  5666. );
  5667. if (verbose_level > 3) {
  5668. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5669. SERIAL_ECHOPAIR(" angle: ", angle);
  5670. SERIAL_ECHOPGM(" Direction: ");
  5671. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5672. SERIAL_ECHOLNPGM("Clockwise");
  5673. }
  5674. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5675. double delta_angle;
  5676. if (schizoid_flag)
  5677. // The points of a 5 point star are 72 degrees apart. We need to
  5678. // skip a point and go to the next one on the star.
  5679. delta_angle = dir * 2.0 * 72.0;
  5680. else
  5681. // If we do this line, we are just trying to move further
  5682. // around the circle.
  5683. delta_angle = dir * (float) random(25, 45);
  5684. angle += delta_angle;
  5685. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5686. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5687. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5688. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5689. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5690. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5691. #if DISABLED(DELTA)
  5692. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5693. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5694. #else
  5695. // If we have gone out too far, we can do a simple fix and scale the numbers
  5696. // back in closer to the origin.
  5697. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5698. X_current *= 0.8;
  5699. Y_current *= 0.8;
  5700. if (verbose_level > 3) {
  5701. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5702. SERIAL_ECHOLNPAIR(", ", Y_current);
  5703. }
  5704. }
  5705. #endif
  5706. if (verbose_level > 3) {
  5707. SERIAL_PROTOCOLPGM("Going to:");
  5708. SERIAL_ECHOPAIR(" X", X_current);
  5709. SERIAL_ECHOPAIR(" Y", Y_current);
  5710. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5711. }
  5712. do_blocking_move_to_xy(X_current, Y_current);
  5713. } // n_legs loop
  5714. } // n_legs
  5715. // Probe a single point
  5716. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5717. /**
  5718. * Get the current mean for the data points we have so far
  5719. */
  5720. double sum = 0.0;
  5721. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5722. mean = sum / (n + 1);
  5723. NOMORE(min, sample_set[n]);
  5724. NOLESS(max, sample_set[n]);
  5725. /**
  5726. * Now, use that mean to calculate the standard deviation for the
  5727. * data points we have so far
  5728. */
  5729. sum = 0.0;
  5730. for (uint8_t j = 0; j <= n; j++)
  5731. sum += sq(sample_set[j] - mean);
  5732. sigma = sqrt(sum / (n + 1));
  5733. if (verbose_level > 0) {
  5734. if (verbose_level > 1) {
  5735. SERIAL_PROTOCOL(n + 1);
  5736. SERIAL_PROTOCOLPGM(" of ");
  5737. SERIAL_PROTOCOL((int)n_samples);
  5738. SERIAL_PROTOCOLPGM(": z: ");
  5739. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5740. if (verbose_level > 2) {
  5741. SERIAL_PROTOCOLPGM(" mean: ");
  5742. SERIAL_PROTOCOL_F(mean, 4);
  5743. SERIAL_PROTOCOLPGM(" sigma: ");
  5744. SERIAL_PROTOCOL_F(sigma, 6);
  5745. SERIAL_PROTOCOLPGM(" min: ");
  5746. SERIAL_PROTOCOL_F(min, 3);
  5747. SERIAL_PROTOCOLPGM(" max: ");
  5748. SERIAL_PROTOCOL_F(max, 3);
  5749. SERIAL_PROTOCOLPGM(" range: ");
  5750. SERIAL_PROTOCOL_F(max-min, 3);
  5751. }
  5752. SERIAL_EOL();
  5753. }
  5754. }
  5755. } // End of probe loop
  5756. if (STOW_PROBE()) return;
  5757. SERIAL_PROTOCOLPGM("Finished!");
  5758. SERIAL_EOL();
  5759. if (verbose_level > 0) {
  5760. SERIAL_PROTOCOLPGM("Mean: ");
  5761. SERIAL_PROTOCOL_F(mean, 6);
  5762. SERIAL_PROTOCOLPGM(" Min: ");
  5763. SERIAL_PROTOCOL_F(min, 3);
  5764. SERIAL_PROTOCOLPGM(" Max: ");
  5765. SERIAL_PROTOCOL_F(max, 3);
  5766. SERIAL_PROTOCOLPGM(" Range: ");
  5767. SERIAL_PROTOCOL_F(max-min, 3);
  5768. SERIAL_EOL();
  5769. }
  5770. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5771. SERIAL_PROTOCOL_F(sigma, 6);
  5772. SERIAL_EOL();
  5773. SERIAL_EOL();
  5774. clean_up_after_endstop_or_probe_move();
  5775. // Re-enable bed level correction if it had been on
  5776. #if HAS_LEVELING
  5777. set_bed_leveling_enabled(was_enabled);
  5778. #endif
  5779. report_current_position();
  5780. }
  5781. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5782. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5783. inline void gcode_M49() {
  5784. ubl.g26_debug_flag ^= true;
  5785. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5786. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5787. }
  5788. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5789. /**
  5790. * M75: Start print timer
  5791. */
  5792. inline void gcode_M75() { print_job_timer.start(); }
  5793. /**
  5794. * M76: Pause print timer
  5795. */
  5796. inline void gcode_M76() { print_job_timer.pause(); }
  5797. /**
  5798. * M77: Stop print timer
  5799. */
  5800. inline void gcode_M77() { print_job_timer.stop(); }
  5801. #if ENABLED(PRINTCOUNTER)
  5802. /**
  5803. * M78: Show print statistics
  5804. */
  5805. inline void gcode_M78() {
  5806. // "M78 S78" will reset the statistics
  5807. if (parser.seen('S') && parser.value_int() == 78)
  5808. print_job_timer.initStats();
  5809. else
  5810. print_job_timer.showStats();
  5811. }
  5812. #endif
  5813. /**
  5814. * M104: Set hot end temperature
  5815. */
  5816. inline void gcode_M104() {
  5817. if (get_target_extruder_from_command(104)) return;
  5818. if (DEBUGGING(DRYRUN)) return;
  5819. #if ENABLED(SINGLENOZZLE)
  5820. if (target_extruder != active_extruder) return;
  5821. #endif
  5822. if (parser.seen('S')) {
  5823. const int16_t temp = parser.value_celsius();
  5824. thermalManager.setTargetHotend(temp, target_extruder);
  5825. #if ENABLED(DUAL_X_CARRIAGE)
  5826. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5827. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5828. #endif
  5829. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5830. /**
  5831. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5832. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5833. * standby mode, for instance in a dual extruder setup, without affecting
  5834. * the running print timer.
  5835. */
  5836. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5837. print_job_timer.stop();
  5838. LCD_MESSAGEPGM(WELCOME_MSG);
  5839. }
  5840. #endif
  5841. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5842. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5843. }
  5844. #if ENABLED(AUTOTEMP)
  5845. planner.autotemp_M104_M109();
  5846. #endif
  5847. }
  5848. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5849. void print_heater_state(const float &c, const float &t,
  5850. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5851. const float r,
  5852. #endif
  5853. const int8_t e=-2
  5854. ) {
  5855. SERIAL_PROTOCOLCHAR(' ');
  5856. SERIAL_PROTOCOLCHAR(
  5857. #if HAS_TEMP_BED && HAS_TEMP_HOTEND
  5858. e == -1 ? 'B' : 'T'
  5859. #elif HAS_TEMP_HOTEND
  5860. 'T'
  5861. #else
  5862. 'B'
  5863. #endif
  5864. );
  5865. #if HOTENDS > 1
  5866. if (e >= 0) SERIAL_PROTOCOLCHAR('0' + e);
  5867. #endif
  5868. SERIAL_PROTOCOLCHAR(':');
  5869. SERIAL_PROTOCOL(c);
  5870. SERIAL_PROTOCOLPAIR(" /" , t);
  5871. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5872. SERIAL_PROTOCOLPAIR(" (", r / OVERSAMPLENR);
  5873. SERIAL_PROTOCOLCHAR(')');
  5874. #endif
  5875. }
  5876. void print_heaterstates() {
  5877. #if HAS_TEMP_HOTEND
  5878. print_heater_state(thermalManager.degHotend(target_extruder), thermalManager.degTargetHotend(target_extruder)
  5879. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5880. , thermalManager.rawHotendTemp(target_extruder)
  5881. #endif
  5882. );
  5883. #endif
  5884. #if HAS_TEMP_BED
  5885. print_heater_state(thermalManager.degBed(), thermalManager.degTargetBed(),
  5886. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5887. thermalManager.rawBedTemp(),
  5888. #endif
  5889. -1 // BED
  5890. );
  5891. #endif
  5892. #if HOTENDS > 1
  5893. HOTEND_LOOP() print_heater_state(thermalManager.degHotend(e), thermalManager.degTargetHotend(e),
  5894. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5895. thermalManager.rawHotendTemp(e),
  5896. #endif
  5897. e
  5898. );
  5899. #endif
  5900. SERIAL_PROTOCOLPGM(" @:");
  5901. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5902. #if HAS_TEMP_BED
  5903. SERIAL_PROTOCOLPGM(" B@:");
  5904. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5905. #endif
  5906. #if HOTENDS > 1
  5907. HOTEND_LOOP() {
  5908. SERIAL_PROTOCOLPAIR(" @", e);
  5909. SERIAL_PROTOCOLCHAR(':');
  5910. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5911. }
  5912. #endif
  5913. }
  5914. #endif
  5915. /**
  5916. * M105: Read hot end and bed temperature
  5917. */
  5918. inline void gcode_M105() {
  5919. if (get_target_extruder_from_command(105)) return;
  5920. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5921. SERIAL_PROTOCOLPGM(MSG_OK);
  5922. print_heaterstates();
  5923. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  5924. SERIAL_ERROR_START();
  5925. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  5926. #endif
  5927. SERIAL_EOL();
  5928. }
  5929. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  5930. static uint8_t auto_report_temp_interval;
  5931. static millis_t next_temp_report_ms;
  5932. /**
  5933. * M155: Set temperature auto-report interval. M155 S<seconds>
  5934. */
  5935. inline void gcode_M155() {
  5936. if (parser.seen('S')) {
  5937. auto_report_temp_interval = parser.value_byte();
  5938. NOMORE(auto_report_temp_interval, 60);
  5939. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5940. }
  5941. }
  5942. inline void auto_report_temperatures() {
  5943. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  5944. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  5945. print_heaterstates();
  5946. SERIAL_EOL();
  5947. }
  5948. }
  5949. #endif // AUTO_REPORT_TEMPERATURES
  5950. #if FAN_COUNT > 0
  5951. /**
  5952. * M106: Set Fan Speed
  5953. *
  5954. * S<int> Speed between 0-255
  5955. * P<index> Fan index, if more than one fan
  5956. */
  5957. inline void gcode_M106() {
  5958. uint16_t s = parser.seen('S') ? parser.value_ushort() : 255,
  5959. p = parser.seen('P') ? parser.value_ushort() : 0;
  5960. NOMORE(s, 255);
  5961. if (p < FAN_COUNT) fanSpeeds[p] = s;
  5962. }
  5963. /**
  5964. * M107: Fan Off
  5965. */
  5966. inline void gcode_M107() {
  5967. uint16_t p = parser.seen('P') ? parser.value_ushort() : 0;
  5968. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  5969. }
  5970. #endif // FAN_COUNT > 0
  5971. #if DISABLED(EMERGENCY_PARSER)
  5972. /**
  5973. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  5974. */
  5975. inline void gcode_M108() { wait_for_heatup = false; }
  5976. /**
  5977. * M112: Emergency Stop
  5978. */
  5979. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  5980. /**
  5981. * M410: Quickstop - Abort all planned moves
  5982. *
  5983. * This will stop the carriages mid-move, so most likely they
  5984. * will be out of sync with the stepper position after this.
  5985. */
  5986. inline void gcode_M410() { quickstop_stepper(); }
  5987. #endif
  5988. /**
  5989. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  5990. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  5991. */
  5992. #ifndef MIN_COOLING_SLOPE_DEG
  5993. #define MIN_COOLING_SLOPE_DEG 1.50
  5994. #endif
  5995. #ifndef MIN_COOLING_SLOPE_TIME
  5996. #define MIN_COOLING_SLOPE_TIME 60
  5997. #endif
  5998. inline void gcode_M109() {
  5999. if (get_target_extruder_from_command(109)) return;
  6000. if (DEBUGGING(DRYRUN)) return;
  6001. #if ENABLED(SINGLENOZZLE)
  6002. if (target_extruder != active_extruder) return;
  6003. #endif
  6004. const bool no_wait_for_cooling = parser.seen('S');
  6005. if (no_wait_for_cooling || parser.seen('R')) {
  6006. const int16_t temp = parser.value_celsius();
  6007. thermalManager.setTargetHotend(temp, target_extruder);
  6008. #if ENABLED(DUAL_X_CARRIAGE)
  6009. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  6010. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  6011. #endif
  6012. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6013. /**
  6014. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  6015. * standby mode, (e.g., in a dual extruder setup) without affecting
  6016. * the running print timer.
  6017. */
  6018. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  6019. print_job_timer.stop();
  6020. LCD_MESSAGEPGM(WELCOME_MSG);
  6021. }
  6022. else
  6023. print_job_timer.start();
  6024. #endif
  6025. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  6026. }
  6027. else return;
  6028. #if ENABLED(AUTOTEMP)
  6029. planner.autotemp_M104_M109();
  6030. #endif
  6031. #if TEMP_RESIDENCY_TIME > 0
  6032. millis_t residency_start_ms = 0;
  6033. // Loop until the temperature has stabilized
  6034. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  6035. #else
  6036. // Loop until the temperature is very close target
  6037. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  6038. #endif
  6039. float target_temp = -1.0, old_temp = 9999.0;
  6040. bool wants_to_cool = false;
  6041. wait_for_heatup = true;
  6042. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6043. KEEPALIVE_STATE(NOT_BUSY);
  6044. #if ENABLED(PRINTER_EVENT_LEDS)
  6045. const float start_temp = thermalManager.degHotend(target_extruder);
  6046. uint8_t old_blue = 0;
  6047. #endif
  6048. do {
  6049. // Target temperature might be changed during the loop
  6050. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  6051. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  6052. target_temp = thermalManager.degTargetHotend(target_extruder);
  6053. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6054. if (no_wait_for_cooling && wants_to_cool) break;
  6055. }
  6056. now = millis();
  6057. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  6058. next_temp_ms = now + 1000UL;
  6059. print_heaterstates();
  6060. #if TEMP_RESIDENCY_TIME > 0
  6061. SERIAL_PROTOCOLPGM(" W:");
  6062. if (residency_start_ms)
  6063. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6064. else
  6065. SERIAL_PROTOCOLCHAR('?');
  6066. #endif
  6067. SERIAL_EOL();
  6068. }
  6069. idle();
  6070. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6071. const float temp = thermalManager.degHotend(target_extruder);
  6072. #if ENABLED(PRINTER_EVENT_LEDS)
  6073. // Gradually change LED strip from violet to red as nozzle heats up
  6074. if (!wants_to_cool) {
  6075. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  6076. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  6077. }
  6078. #endif
  6079. #if TEMP_RESIDENCY_TIME > 0
  6080. const float temp_diff = fabs(target_temp - temp);
  6081. if (!residency_start_ms) {
  6082. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  6083. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  6084. }
  6085. else if (temp_diff > TEMP_HYSTERESIS) {
  6086. // Restart the timer whenever the temperature falls outside the hysteresis.
  6087. residency_start_ms = now;
  6088. }
  6089. #endif
  6090. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  6091. if (wants_to_cool) {
  6092. // break after MIN_COOLING_SLOPE_TIME seconds
  6093. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  6094. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6095. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  6096. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  6097. old_temp = temp;
  6098. }
  6099. }
  6100. } while (wait_for_heatup && TEMP_CONDITIONS);
  6101. if (wait_for_heatup) {
  6102. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  6103. #if ENABLED(PRINTER_EVENT_LEDS)
  6104. #if ENABLED(RGBW_LED)
  6105. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  6106. #else
  6107. set_led_color(255, 255, 255); // Set LEDs All On
  6108. #endif
  6109. #endif
  6110. }
  6111. KEEPALIVE_STATE(IN_HANDLER);
  6112. }
  6113. #if HAS_TEMP_BED
  6114. #ifndef MIN_COOLING_SLOPE_DEG_BED
  6115. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6116. #endif
  6117. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6118. #define MIN_COOLING_SLOPE_TIME_BED 60
  6119. #endif
  6120. /**
  6121. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6122. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6123. */
  6124. inline void gcode_M190() {
  6125. if (DEBUGGING(DRYRUN)) return;
  6126. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6127. const bool no_wait_for_cooling = parser.seen('S');
  6128. if (no_wait_for_cooling || parser.seen('R')) {
  6129. thermalManager.setTargetBed(parser.value_celsius());
  6130. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6131. if (parser.value_celsius() > BED_MINTEMP)
  6132. print_job_timer.start();
  6133. #endif
  6134. }
  6135. else return;
  6136. #if TEMP_BED_RESIDENCY_TIME > 0
  6137. millis_t residency_start_ms = 0;
  6138. // Loop until the temperature has stabilized
  6139. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6140. #else
  6141. // Loop until the temperature is very close target
  6142. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6143. #endif
  6144. float target_temp = -1.0, old_temp = 9999.0;
  6145. bool wants_to_cool = false;
  6146. wait_for_heatup = true;
  6147. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6148. KEEPALIVE_STATE(NOT_BUSY);
  6149. target_extruder = active_extruder; // for print_heaterstates
  6150. #if ENABLED(PRINTER_EVENT_LEDS)
  6151. const float start_temp = thermalManager.degBed();
  6152. uint8_t old_red = 255;
  6153. #endif
  6154. do {
  6155. // Target temperature might be changed during the loop
  6156. if (target_temp != thermalManager.degTargetBed()) {
  6157. wants_to_cool = thermalManager.isCoolingBed();
  6158. target_temp = thermalManager.degTargetBed();
  6159. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6160. if (no_wait_for_cooling && wants_to_cool) break;
  6161. }
  6162. now = millis();
  6163. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6164. next_temp_ms = now + 1000UL;
  6165. print_heaterstates();
  6166. #if TEMP_BED_RESIDENCY_TIME > 0
  6167. SERIAL_PROTOCOLPGM(" W:");
  6168. if (residency_start_ms)
  6169. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6170. else
  6171. SERIAL_PROTOCOLCHAR('?');
  6172. #endif
  6173. SERIAL_EOL();
  6174. }
  6175. idle();
  6176. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6177. const float temp = thermalManager.degBed();
  6178. #if ENABLED(PRINTER_EVENT_LEDS)
  6179. // Gradually change LED strip from blue to violet as bed heats up
  6180. if (!wants_to_cool) {
  6181. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6182. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6183. }
  6184. #endif
  6185. #if TEMP_BED_RESIDENCY_TIME > 0
  6186. const float temp_diff = fabs(target_temp - temp);
  6187. if (!residency_start_ms) {
  6188. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6189. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6190. }
  6191. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6192. // Restart the timer whenever the temperature falls outside the hysteresis.
  6193. residency_start_ms = now;
  6194. }
  6195. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6196. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6197. if (wants_to_cool) {
  6198. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6199. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6200. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6201. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6202. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6203. old_temp = temp;
  6204. }
  6205. }
  6206. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6207. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6208. KEEPALIVE_STATE(IN_HANDLER);
  6209. }
  6210. #endif // HAS_TEMP_BED
  6211. /**
  6212. * M110: Set Current Line Number
  6213. */
  6214. inline void gcode_M110() {
  6215. if (parser.seen('N')) gcode_LastN = parser.value_long();
  6216. }
  6217. /**
  6218. * M111: Set the debug level
  6219. */
  6220. inline void gcode_M111() {
  6221. marlin_debug_flags = parser.seen('S') ? parser.value_byte() : (uint8_t)DEBUG_NONE;
  6222. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6223. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6224. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6225. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6226. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6227. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6228. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6229. #endif
  6230. const static char* const debug_strings[] PROGMEM = {
  6231. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6233. , str_debug_32
  6234. #endif
  6235. };
  6236. SERIAL_ECHO_START();
  6237. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6238. if (marlin_debug_flags) {
  6239. uint8_t comma = 0;
  6240. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6241. if (TEST(marlin_debug_flags, i)) {
  6242. if (comma++) SERIAL_CHAR(',');
  6243. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6244. }
  6245. }
  6246. }
  6247. else {
  6248. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6249. }
  6250. SERIAL_EOL();
  6251. }
  6252. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6253. /**
  6254. * M113: Get or set Host Keepalive interval (0 to disable)
  6255. *
  6256. * S<seconds> Optional. Set the keepalive interval.
  6257. */
  6258. inline void gcode_M113() {
  6259. if (parser.seen('S')) {
  6260. host_keepalive_interval = parser.value_byte();
  6261. NOMORE(host_keepalive_interval, 60);
  6262. }
  6263. else {
  6264. SERIAL_ECHO_START();
  6265. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6266. }
  6267. }
  6268. #endif
  6269. #if ENABLED(BARICUDA)
  6270. #if HAS_HEATER_1
  6271. /**
  6272. * M126: Heater 1 valve open
  6273. */
  6274. inline void gcode_M126() { baricuda_valve_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6275. /**
  6276. * M127: Heater 1 valve close
  6277. */
  6278. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6279. #endif
  6280. #if HAS_HEATER_2
  6281. /**
  6282. * M128: Heater 2 valve open
  6283. */
  6284. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.seen('S') ? parser.value_byte() : 255; }
  6285. /**
  6286. * M129: Heater 2 valve close
  6287. */
  6288. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6289. #endif
  6290. #endif // BARICUDA
  6291. /**
  6292. * M140: Set bed temperature
  6293. */
  6294. inline void gcode_M140() {
  6295. if (DEBUGGING(DRYRUN)) return;
  6296. if (parser.seen('S')) thermalManager.setTargetBed(parser.value_celsius());
  6297. }
  6298. #if ENABLED(ULTIPANEL)
  6299. /**
  6300. * M145: Set the heatup state for a material in the LCD menu
  6301. *
  6302. * S<material> (0=PLA, 1=ABS)
  6303. * H<hotend temp>
  6304. * B<bed temp>
  6305. * F<fan speed>
  6306. */
  6307. inline void gcode_M145() {
  6308. uint8_t material = parser.seen('S') ? (uint8_t)parser.value_int() : 0;
  6309. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6310. SERIAL_ERROR_START();
  6311. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6312. }
  6313. else {
  6314. int v;
  6315. if (parser.seen('H')) {
  6316. v = parser.value_int();
  6317. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6318. }
  6319. if (parser.seen('F')) {
  6320. v = parser.value_int();
  6321. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6322. }
  6323. #if TEMP_SENSOR_BED != 0
  6324. if (parser.seen('B')) {
  6325. v = parser.value_int();
  6326. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6327. }
  6328. #endif
  6329. }
  6330. }
  6331. #endif // ULTIPANEL
  6332. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6333. /**
  6334. * M149: Set temperature units
  6335. */
  6336. inline void gcode_M149() {
  6337. if (parser.seen('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6338. else if (parser.seen('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6339. else if (parser.seen('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6340. }
  6341. #endif
  6342. #if HAS_POWER_SWITCH
  6343. /**
  6344. * M80 : Turn on the Power Supply
  6345. * M80 S : Report the current state and exit
  6346. */
  6347. inline void gcode_M80() {
  6348. // S: Report the current power supply state and exit
  6349. if (parser.seen('S')) {
  6350. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6351. return;
  6352. }
  6353. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6354. /**
  6355. * If you have a switch on suicide pin, this is useful
  6356. * if you want to start another print with suicide feature after
  6357. * a print without suicide...
  6358. */
  6359. #if HAS_SUICIDE
  6360. OUT_WRITE(SUICIDE_PIN, HIGH);
  6361. #endif
  6362. #if ENABLED(HAVE_TMC2130)
  6363. delay(100);
  6364. tmc2130_init(); // Settings only stick when the driver has power
  6365. #endif
  6366. powersupply_on = true;
  6367. #if ENABLED(ULTIPANEL)
  6368. LCD_MESSAGEPGM(WELCOME_MSG);
  6369. #endif
  6370. }
  6371. #endif // HAS_POWER_SWITCH
  6372. /**
  6373. * M81: Turn off Power, including Power Supply, if there is one.
  6374. *
  6375. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6376. */
  6377. inline void gcode_M81() {
  6378. thermalManager.disable_all_heaters();
  6379. stepper.finish_and_disable();
  6380. #if FAN_COUNT > 0
  6381. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6382. #if ENABLED(PROBING_FANS_OFF)
  6383. fans_paused = false;
  6384. ZERO(paused_fanSpeeds);
  6385. #endif
  6386. #endif
  6387. safe_delay(1000); // Wait 1 second before switching off
  6388. #if HAS_SUICIDE
  6389. stepper.synchronize();
  6390. suicide();
  6391. #elif HAS_POWER_SWITCH
  6392. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6393. powersupply_on = false;
  6394. #endif
  6395. #if ENABLED(ULTIPANEL)
  6396. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6397. #endif
  6398. }
  6399. /**
  6400. * M82: Set E codes absolute (default)
  6401. */
  6402. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6403. /**
  6404. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6405. */
  6406. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6407. /**
  6408. * M18, M84: Disable stepper motors
  6409. */
  6410. inline void gcode_M18_M84() {
  6411. if (parser.seen('S')) {
  6412. stepper_inactive_time = parser.value_millis_from_seconds();
  6413. }
  6414. else {
  6415. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6416. if (all_axis) {
  6417. stepper.finish_and_disable();
  6418. }
  6419. else {
  6420. stepper.synchronize();
  6421. if (parser.seen('X')) disable_X();
  6422. if (parser.seen('Y')) disable_Y();
  6423. if (parser.seen('Z')) disable_Z();
  6424. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  6425. if (parser.seen('E')) disable_e_steppers();
  6426. #endif
  6427. }
  6428. }
  6429. }
  6430. /**
  6431. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6432. */
  6433. inline void gcode_M85() {
  6434. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6435. }
  6436. /**
  6437. * Multi-stepper support for M92, M201, M203
  6438. */
  6439. #if ENABLED(DISTINCT_E_FACTORS)
  6440. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6441. #define TARGET_EXTRUDER target_extruder
  6442. #else
  6443. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6444. #define TARGET_EXTRUDER 0
  6445. #endif
  6446. /**
  6447. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6448. * (Follows the same syntax as G92)
  6449. *
  6450. * With multiple extruders use T to specify which one.
  6451. */
  6452. inline void gcode_M92() {
  6453. GET_TARGET_EXTRUDER(92);
  6454. LOOP_XYZE(i) {
  6455. if (parser.seen(axis_codes[i])) {
  6456. if (i == E_AXIS) {
  6457. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6458. if (value < 20.0) {
  6459. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6460. planner.max_jerk[E_AXIS] *= factor;
  6461. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6462. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6463. }
  6464. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6465. }
  6466. else {
  6467. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6468. }
  6469. }
  6470. }
  6471. planner.refresh_positioning();
  6472. }
  6473. /**
  6474. * Output the current position to serial
  6475. */
  6476. void report_current_position() {
  6477. SERIAL_PROTOCOLPGM("X:");
  6478. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6479. SERIAL_PROTOCOLPGM(" Y:");
  6480. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6481. SERIAL_PROTOCOLPGM(" Z:");
  6482. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6483. SERIAL_PROTOCOLPGM(" E:");
  6484. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6485. stepper.report_positions();
  6486. #if IS_SCARA
  6487. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6488. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6489. SERIAL_EOL();
  6490. #endif
  6491. }
  6492. #ifdef M114_DETAIL
  6493. void report_xyze(const float pos[XYZE], const uint8_t n = 4, const uint8_t precision = 3) {
  6494. char str[12];
  6495. for (uint8_t i = 0; i < n; i++) {
  6496. SERIAL_CHAR(' ');
  6497. SERIAL_CHAR(axis_codes[i]);
  6498. SERIAL_CHAR(':');
  6499. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  6500. }
  6501. SERIAL_EOL();
  6502. }
  6503. inline void report_xyz(const float pos[XYZ]) { report_xyze(pos, 3); }
  6504. void report_current_position_detail() {
  6505. stepper.synchronize();
  6506. SERIAL_PROTOCOLPGM("\nLogical:");
  6507. report_xyze(current_position);
  6508. SERIAL_PROTOCOLPGM("Raw: ");
  6509. const float raw[XYZ] = { RAW_X_POSITION(current_position[X_AXIS]), RAW_Y_POSITION(current_position[Y_AXIS]), RAW_Z_POSITION(current_position[Z_AXIS]) };
  6510. report_xyz(raw);
  6511. SERIAL_PROTOCOLPGM("Leveled:");
  6512. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  6513. planner.apply_leveling(leveled);
  6514. report_xyz(leveled);
  6515. SERIAL_PROTOCOLPGM("UnLevel:");
  6516. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  6517. planner.unapply_leveling(unleveled);
  6518. report_xyz(unleveled);
  6519. #if IS_KINEMATIC
  6520. #if IS_SCARA
  6521. SERIAL_PROTOCOLPGM("ScaraK: ");
  6522. #else
  6523. SERIAL_PROTOCOLPGM("DeltaK: ");
  6524. #endif
  6525. inverse_kinematics(leveled); // writes delta[]
  6526. report_xyz(delta);
  6527. #endif
  6528. SERIAL_PROTOCOLPGM("Stepper:");
  6529. const float step_count[XYZE] = { stepper.position(X_AXIS), stepper.position(Y_AXIS), stepper.position(Z_AXIS), stepper.position(E_AXIS) };
  6530. report_xyze(step_count, 4, 0);
  6531. #if IS_SCARA
  6532. const float deg[XYZ] = {
  6533. stepper.get_axis_position_degrees(A_AXIS),
  6534. stepper.get_axis_position_degrees(B_AXIS)
  6535. };
  6536. SERIAL_PROTOCOLPGM("Degrees:");
  6537. report_xyze(deg, 2);
  6538. #endif
  6539. SERIAL_PROTOCOLPGM("FromStp:");
  6540. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  6541. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], stepper.get_axis_position_mm(E_AXIS) };
  6542. report_xyze(from_steppers);
  6543. const float diff[XYZE] = {
  6544. from_steppers[X_AXIS] - leveled[X_AXIS],
  6545. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  6546. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  6547. from_steppers[E_AXIS] - current_position[E_AXIS]
  6548. };
  6549. SERIAL_PROTOCOLPGM("Differ: ");
  6550. report_xyze(diff);
  6551. }
  6552. #endif // M114_DETAIL
  6553. /**
  6554. * M114: Report current position to host
  6555. */
  6556. inline void gcode_M114() {
  6557. #ifdef M114_DETAIL
  6558. if (parser.seen('D')) {
  6559. report_current_position_detail();
  6560. return;
  6561. }
  6562. #endif
  6563. stepper.synchronize();
  6564. report_current_position();
  6565. }
  6566. /**
  6567. * M115: Capabilities string
  6568. */
  6569. inline void gcode_M115() {
  6570. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6571. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6572. // EEPROM (M500, M501)
  6573. #if ENABLED(EEPROM_SETTINGS)
  6574. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6575. #else
  6576. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6577. #endif
  6578. // AUTOREPORT_TEMP (M155)
  6579. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6580. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6581. #else
  6582. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6583. #endif
  6584. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6585. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6586. // AUTOLEVEL (G29)
  6587. #if HAS_ABL
  6588. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6589. #else
  6590. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6591. #endif
  6592. // Z_PROBE (G30)
  6593. #if HAS_BED_PROBE
  6594. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6595. #else
  6596. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6597. #endif
  6598. // MESH_REPORT (M420 V)
  6599. #if HAS_LEVELING
  6600. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6601. #else
  6602. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6603. #endif
  6604. // SOFTWARE_POWER (G30)
  6605. #if HAS_POWER_SWITCH
  6606. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6607. #else
  6608. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6609. #endif
  6610. // CASE LIGHTS (M355)
  6611. #if HAS_CASE_LIGHT
  6612. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6613. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  6614. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:1");
  6615. }
  6616. else
  6617. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6618. #else
  6619. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6620. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6621. #endif
  6622. // EMERGENCY_PARSER (M108, M112, M410)
  6623. #if ENABLED(EMERGENCY_PARSER)
  6624. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6625. #else
  6626. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6627. #endif
  6628. #endif // EXTENDED_CAPABILITIES_REPORT
  6629. }
  6630. /**
  6631. * M117: Set LCD Status Message
  6632. */
  6633. inline void gcode_M117() { lcd_setstatus(parser.string_arg); }
  6634. /**
  6635. * M119: Output endstop states to serial output
  6636. */
  6637. inline void gcode_M119() { endstops.M119(); }
  6638. /**
  6639. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6640. */
  6641. inline void gcode_M120() { endstops.enable_globally(true); }
  6642. /**
  6643. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6644. */
  6645. inline void gcode_M121() { endstops.enable_globally(false); }
  6646. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6647. /**
  6648. * M125: Store current position and move to filament change position.
  6649. * Called on pause (by M25) to prevent material leaking onto the
  6650. * object. On resume (M24) the head will be moved back and the
  6651. * print will resume.
  6652. *
  6653. * If Marlin is compiled without SD Card support, M125 can be
  6654. * used directly to pause the print and move to park position,
  6655. * resuming with a button click or M108.
  6656. *
  6657. * L = override retract length
  6658. * X = override X
  6659. * Y = override Y
  6660. * Z = override Z raise
  6661. */
  6662. inline void gcode_M125() {
  6663. // Initial retract before move to filament change position
  6664. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6665. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6666. - (PAUSE_PARK_RETRACT_LENGTH)
  6667. #endif
  6668. ;
  6669. // Lift Z axis
  6670. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  6671. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  6672. PAUSE_PARK_Z_ADD
  6673. #else
  6674. 0
  6675. #endif
  6676. ;
  6677. // Move XY axes to filament change position or given position
  6678. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  6679. #ifdef PAUSE_PARK_X_POS
  6680. + PAUSE_PARK_X_POS
  6681. #endif
  6682. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6683. + (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0)
  6684. #endif
  6685. ;
  6686. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  6687. #ifdef PAUSE_PARK_Y_POS
  6688. + PAUSE_PARK_Y_POS
  6689. #endif
  6690. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6691. + (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0)
  6692. #endif
  6693. ;
  6694. const bool job_running = print_job_timer.isRunning();
  6695. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6696. #if DISABLED(SDSUPPORT)
  6697. // Wait for lcd click or M108
  6698. wait_for_filament_reload();
  6699. // Return to print position and continue
  6700. resume_print();
  6701. if (job_running) print_job_timer.start();
  6702. #endif
  6703. }
  6704. }
  6705. #endif // PARK_HEAD_ON_PAUSE
  6706. #if HAS_COLOR_LEDS
  6707. /**
  6708. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6709. *
  6710. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6711. *
  6712. * Examples:
  6713. *
  6714. * M150 R255 ; Turn LED red
  6715. * M150 R255 U127 ; Turn LED orange (PWM only)
  6716. * M150 ; Turn LED off
  6717. * M150 R U B ; Turn LED white
  6718. * M150 W ; Turn LED white using a white LED
  6719. *
  6720. */
  6721. inline void gcode_M150() {
  6722. set_led_color(
  6723. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6724. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6725. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6726. #if ENABLED(RGBW_LED)
  6727. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6728. #endif
  6729. );
  6730. }
  6731. #endif // BLINKM || RGB_LED
  6732. /**
  6733. * M200: Set filament diameter and set E axis units to cubic units
  6734. *
  6735. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6736. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6737. */
  6738. inline void gcode_M200() {
  6739. if (get_target_extruder_from_command(200)) return;
  6740. if (parser.seen('D')) {
  6741. // setting any extruder filament size disables volumetric on the assumption that
  6742. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6743. // for all extruders
  6744. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6745. if (volumetric_enabled) {
  6746. filament_size[target_extruder] = parser.value_linear_units();
  6747. // make sure all extruders have some sane value for the filament size
  6748. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6749. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6750. }
  6751. }
  6752. calculate_volumetric_multipliers();
  6753. }
  6754. /**
  6755. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6756. *
  6757. * With multiple extruders use T to specify which one.
  6758. */
  6759. inline void gcode_M201() {
  6760. GET_TARGET_EXTRUDER(201);
  6761. LOOP_XYZE(i) {
  6762. if (parser.seen(axis_codes[i])) {
  6763. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6764. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6765. }
  6766. }
  6767. // 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)
  6768. planner.reset_acceleration_rates();
  6769. }
  6770. #if 0 // Not used for Sprinter/grbl gen6
  6771. inline void gcode_M202() {
  6772. LOOP_XYZE(i) {
  6773. 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];
  6774. }
  6775. }
  6776. #endif
  6777. /**
  6778. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6779. *
  6780. * With multiple extruders use T to specify which one.
  6781. */
  6782. inline void gcode_M203() {
  6783. GET_TARGET_EXTRUDER(203);
  6784. LOOP_XYZE(i)
  6785. if (parser.seen(axis_codes[i])) {
  6786. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6787. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6788. }
  6789. }
  6790. /**
  6791. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6792. *
  6793. * P = Printing moves
  6794. * R = Retract only (no X, Y, Z) moves
  6795. * T = Travel (non printing) moves
  6796. *
  6797. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6798. */
  6799. inline void gcode_M204() {
  6800. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6801. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6802. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6803. }
  6804. if (parser.seen('P')) {
  6805. planner.acceleration = parser.value_linear_units();
  6806. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6807. }
  6808. if (parser.seen('R')) {
  6809. planner.retract_acceleration = parser.value_linear_units();
  6810. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6811. }
  6812. if (parser.seen('T')) {
  6813. planner.travel_acceleration = parser.value_linear_units();
  6814. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6815. }
  6816. }
  6817. /**
  6818. * M205: Set Advanced Settings
  6819. *
  6820. * S = Min Feed Rate (units/s)
  6821. * T = Min Travel Feed Rate (units/s)
  6822. * B = Min Segment Time (µs)
  6823. * X = Max X Jerk (units/sec^2)
  6824. * Y = Max Y Jerk (units/sec^2)
  6825. * Z = Max Z Jerk (units/sec^2)
  6826. * E = Max E Jerk (units/sec^2)
  6827. */
  6828. inline void gcode_M205() {
  6829. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6830. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6831. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6832. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6833. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6834. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6835. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6836. }
  6837. #if HAS_M206_COMMAND
  6838. /**
  6839. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6840. *
  6841. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6842. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6843. * *** In the next 1.2 release, it will simply be disabled by default.
  6844. */
  6845. inline void gcode_M206() {
  6846. LOOP_XYZ(i)
  6847. if (parser.seen(axis_codes[i]))
  6848. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6849. #if ENABLED(MORGAN_SCARA)
  6850. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6851. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6852. #endif
  6853. SYNC_PLAN_POSITION_KINEMATIC();
  6854. report_current_position();
  6855. }
  6856. #endif // HAS_M206_COMMAND
  6857. #if ENABLED(DELTA)
  6858. /**
  6859. * M665: Set delta configurations
  6860. *
  6861. * H = delta height
  6862. * L = diagonal rod
  6863. * R = delta radius
  6864. * S = segments per second
  6865. * B = delta calibration radius
  6866. * X = Alpha (Tower 1) angle trim
  6867. * Y = Beta (Tower 2) angle trim
  6868. * Z = Rotate A and B by this angle
  6869. */
  6870. inline void gcode_M665() {
  6871. if (parser.seen('H')) {
  6872. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6873. current_position[Z_AXIS] += parser.value_linear_units() - DELTA_HEIGHT - home_offset[Z_AXIS];
  6874. update_software_endstops(Z_AXIS);
  6875. }
  6876. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6877. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6878. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6879. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6880. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6881. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6882. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6883. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6884. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6885. }
  6886. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6887. }
  6888. /**
  6889. * M666: Set delta endstop adjustment
  6890. */
  6891. inline void gcode_M666() {
  6892. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6893. if (DEBUGGING(LEVELING)) {
  6894. SERIAL_ECHOLNPGM(">>> gcode_M666");
  6895. }
  6896. #endif
  6897. LOOP_XYZ(i) {
  6898. if (parser.seen(axis_codes[i])) {
  6899. endstop_adj[i] = parser.value_linear_units();
  6900. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6901. if (DEBUGGING(LEVELING)) {
  6902. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  6903. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  6904. }
  6905. #endif
  6906. }
  6907. }
  6908. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6909. if (DEBUGGING(LEVELING)) {
  6910. SERIAL_ECHOLNPGM("<<< gcode_M666");
  6911. }
  6912. #endif
  6913. // normalize endstops so all are <=0; set the residue to delta height
  6914. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  6915. home_offset[Z_AXIS] -= z_temp;
  6916. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  6917. }
  6918. #elif IS_SCARA
  6919. /**
  6920. * M665: Set SCARA settings
  6921. *
  6922. * Parameters:
  6923. *
  6924. * S[segments-per-second] - Segments-per-second
  6925. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  6926. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  6927. *
  6928. * A, P, and X are all aliases for the shoulder angle
  6929. * B, T, and Y are all aliases for the elbow angle
  6930. */
  6931. inline void gcode_M665() {
  6932. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6933. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  6934. const uint8_t sumAPX = hasA + hasP + hasX;
  6935. if (sumAPX == 1)
  6936. home_offset[A_AXIS] = parser.value_float();
  6937. else if (sumAPX > 1) {
  6938. SERIAL_ERROR_START();
  6939. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  6940. return;
  6941. }
  6942. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  6943. const uint8_t sumBTY = hasB + hasT + hasY;
  6944. if (sumBTY == 1)
  6945. home_offset[B_AXIS] = parser.value_float();
  6946. else if (sumBTY > 1) {
  6947. SERIAL_ERROR_START();
  6948. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  6949. return;
  6950. }
  6951. }
  6952. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  6953. /**
  6954. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  6955. */
  6956. inline void gcode_M666() {
  6957. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  6958. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  6959. }
  6960. #endif // !DELTA && Z_DUAL_ENDSTOPS
  6961. #if ENABLED(FWRETRACT)
  6962. /**
  6963. * M207: Set firmware retraction values
  6964. *
  6965. * S[+units] retract_length
  6966. * W[+units] retract_length_swap (multi-extruder)
  6967. * F[units/min] retract_feedrate_mm_s
  6968. * Z[units] retract_zlift
  6969. */
  6970. inline void gcode_M207() {
  6971. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  6972. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6973. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  6974. #if EXTRUDERS > 1
  6975. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  6976. #endif
  6977. }
  6978. /**
  6979. * M208: Set firmware un-retraction values
  6980. *
  6981. * S[+units] retract_recover_length (in addition to M207 S*)
  6982. * W[+units] retract_recover_length_swap (multi-extruder)
  6983. * F[units/min] retract_recover_feedrate_mm_s
  6984. */
  6985. inline void gcode_M208() {
  6986. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  6987. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  6988. #if EXTRUDERS > 1
  6989. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  6990. #endif
  6991. }
  6992. /**
  6993. * M209: Enable automatic retract (M209 S1)
  6994. * For slicers that don't support G10/11, reversed extrude-only
  6995. * moves will be classified as retraction.
  6996. */
  6997. inline void gcode_M209() {
  6998. if (parser.seen('S')) {
  6999. autoretract_enabled = parser.value_bool();
  7000. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  7001. }
  7002. }
  7003. #endif // FWRETRACT
  7004. /**
  7005. * M211: Enable, Disable, and/or Report software endstops
  7006. *
  7007. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  7008. */
  7009. inline void gcode_M211() {
  7010. SERIAL_ECHO_START();
  7011. #if HAS_SOFTWARE_ENDSTOPS
  7012. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  7013. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7014. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  7015. #else
  7016. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7017. SERIAL_ECHOPGM(MSG_OFF);
  7018. #endif
  7019. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  7020. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  7021. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  7022. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  7023. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  7024. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  7025. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  7026. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  7027. }
  7028. #if HOTENDS > 1
  7029. /**
  7030. * M218 - set hotend offset (in linear units)
  7031. *
  7032. * T<tool>
  7033. * X<xoffset>
  7034. * Y<yoffset>
  7035. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  7036. */
  7037. inline void gcode_M218() {
  7038. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  7039. if (parser.seen('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  7040. if (parser.seen('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  7041. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7042. if (parser.seen('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  7043. #endif
  7044. SERIAL_ECHO_START();
  7045. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7046. HOTEND_LOOP() {
  7047. SERIAL_CHAR(' ');
  7048. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  7049. SERIAL_CHAR(',');
  7050. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  7051. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7052. SERIAL_CHAR(',');
  7053. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  7054. #endif
  7055. }
  7056. SERIAL_EOL();
  7057. }
  7058. #endif // HOTENDS > 1
  7059. /**
  7060. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  7061. */
  7062. inline void gcode_M220() {
  7063. if (parser.seen('S')) feedrate_percentage = parser.value_int();
  7064. }
  7065. /**
  7066. * M221: Set extrusion percentage (M221 T0 S95)
  7067. */
  7068. inline void gcode_M221() {
  7069. if (get_target_extruder_from_command(221)) return;
  7070. if (parser.seen('S'))
  7071. flow_percentage[target_extruder] = parser.value_int();
  7072. }
  7073. /**
  7074. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  7075. */
  7076. inline void gcode_M226() {
  7077. if (parser.seen('P')) {
  7078. int pin_number = parser.value_int(),
  7079. pin_state = parser.seen('S') ? parser.value_int() : -1; // required pin state - default is inverted
  7080. if (pin_state >= -1 && pin_state <= 1 && pin_number > -1 && !pin_is_protected(pin_number)) {
  7081. int target = LOW;
  7082. stepper.synchronize();
  7083. pinMode(pin_number, INPUT);
  7084. switch (pin_state) {
  7085. case 1:
  7086. target = HIGH;
  7087. break;
  7088. case 0:
  7089. target = LOW;
  7090. break;
  7091. case -1:
  7092. target = !digitalRead(pin_number);
  7093. break;
  7094. }
  7095. while (digitalRead(pin_number) != target) idle();
  7096. } // pin_state -1 0 1 && pin_number > -1
  7097. } // parser.seen('P')
  7098. }
  7099. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7100. /**
  7101. * M260: Send data to a I2C slave device
  7102. *
  7103. * This is a PoC, the formating and arguments for the GCODE will
  7104. * change to be more compatible, the current proposal is:
  7105. *
  7106. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  7107. *
  7108. * M260 B<byte-1 value in base 10>
  7109. * M260 B<byte-2 value in base 10>
  7110. * M260 B<byte-3 value in base 10>
  7111. *
  7112. * M260 S1 ; Send the buffered data and reset the buffer
  7113. * M260 R1 ; Reset the buffer without sending data
  7114. *
  7115. */
  7116. inline void gcode_M260() {
  7117. // Set the target address
  7118. if (parser.seen('A')) i2c.address(parser.value_byte());
  7119. // Add a new byte to the buffer
  7120. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  7121. // Flush the buffer to the bus
  7122. if (parser.seen('S')) i2c.send();
  7123. // Reset and rewind the buffer
  7124. else if (parser.seen('R')) i2c.reset();
  7125. }
  7126. /**
  7127. * M261: Request X bytes from I2C slave device
  7128. *
  7129. * Usage: M261 A<slave device address base 10> B<number of bytes>
  7130. */
  7131. inline void gcode_M261() {
  7132. if (parser.seen('A')) i2c.address(parser.value_byte());
  7133. uint8_t bytes = parser.seen('B') ? parser.value_byte() : 1;
  7134. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  7135. i2c.relay(bytes);
  7136. }
  7137. else {
  7138. SERIAL_ERROR_START();
  7139. SERIAL_ERRORLN("Bad i2c request");
  7140. }
  7141. }
  7142. #endif // EXPERIMENTAL_I2CBUS
  7143. #if HAS_SERVOS
  7144. /**
  7145. * M280: Get or set servo position. P<index> [S<angle>]
  7146. */
  7147. inline void gcode_M280() {
  7148. if (!parser.seen('P')) return;
  7149. int servo_index = parser.value_int();
  7150. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  7151. if (parser.seen('S'))
  7152. MOVE_SERVO(servo_index, parser.value_int());
  7153. else {
  7154. SERIAL_ECHO_START();
  7155. SERIAL_ECHOPAIR(" Servo ", servo_index);
  7156. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  7157. }
  7158. }
  7159. else {
  7160. SERIAL_ERROR_START();
  7161. SERIAL_ECHOPAIR("Servo ", servo_index);
  7162. SERIAL_ECHOLNPGM(" out of range");
  7163. }
  7164. }
  7165. #endif // HAS_SERVOS
  7166. #if HAS_BUZZER
  7167. /**
  7168. * M300: Play beep sound S<frequency Hz> P<duration ms>
  7169. */
  7170. inline void gcode_M300() {
  7171. uint16_t const frequency = parser.seen('S') ? parser.value_ushort() : 260;
  7172. uint16_t duration = parser.seen('P') ? parser.value_ushort() : 1000;
  7173. // Limits the tone duration to 0-5 seconds.
  7174. NOMORE(duration, 5000);
  7175. BUZZ(duration, frequency);
  7176. }
  7177. #endif // HAS_BUZZER
  7178. #if ENABLED(PIDTEMP)
  7179. /**
  7180. * M301: Set PID parameters P I D (and optionally C, L)
  7181. *
  7182. * P[float] Kp term
  7183. * I[float] Ki term (unscaled)
  7184. * D[float] Kd term (unscaled)
  7185. *
  7186. * With PID_EXTRUSION_SCALING:
  7187. *
  7188. * C[float] Kc term
  7189. * L[float] LPQ length
  7190. */
  7191. inline void gcode_M301() {
  7192. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7193. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7194. int e = parser.seen('E') ? parser.value_int() : 0; // extruder being updated
  7195. if (e < HOTENDS) { // catch bad input value
  7196. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7197. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7198. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7199. #if ENABLED(PID_EXTRUSION_SCALING)
  7200. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7201. if (parser.seen('L')) lpq_len = parser.value_float();
  7202. NOMORE(lpq_len, LPQ_MAX_LEN);
  7203. #endif
  7204. thermalManager.updatePID();
  7205. SERIAL_ECHO_START();
  7206. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7207. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7208. #endif // PID_PARAMS_PER_HOTEND
  7209. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7210. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7211. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7212. #if ENABLED(PID_EXTRUSION_SCALING)
  7213. //Kc does not have scaling applied above, or in resetting defaults
  7214. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7215. #endif
  7216. SERIAL_EOL();
  7217. }
  7218. else {
  7219. SERIAL_ERROR_START();
  7220. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7221. }
  7222. }
  7223. #endif // PIDTEMP
  7224. #if ENABLED(PIDTEMPBED)
  7225. inline void gcode_M304() {
  7226. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7227. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7228. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7229. thermalManager.updatePID();
  7230. SERIAL_ECHO_START();
  7231. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7232. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7233. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7234. }
  7235. #endif // PIDTEMPBED
  7236. #if defined(CHDK) || HAS_PHOTOGRAPH
  7237. /**
  7238. * M240: Trigger a camera by emulating a Canon RC-1
  7239. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7240. */
  7241. inline void gcode_M240() {
  7242. #ifdef CHDK
  7243. OUT_WRITE(CHDK, HIGH);
  7244. chdkHigh = millis();
  7245. chdkActive = true;
  7246. #elif HAS_PHOTOGRAPH
  7247. const uint8_t NUM_PULSES = 16;
  7248. const float PULSE_LENGTH = 0.01524;
  7249. for (int i = 0; i < NUM_PULSES; i++) {
  7250. WRITE(PHOTOGRAPH_PIN, HIGH);
  7251. _delay_ms(PULSE_LENGTH);
  7252. WRITE(PHOTOGRAPH_PIN, LOW);
  7253. _delay_ms(PULSE_LENGTH);
  7254. }
  7255. delay(7.33);
  7256. for (int i = 0; i < NUM_PULSES; i++) {
  7257. WRITE(PHOTOGRAPH_PIN, HIGH);
  7258. _delay_ms(PULSE_LENGTH);
  7259. WRITE(PHOTOGRAPH_PIN, LOW);
  7260. _delay_ms(PULSE_LENGTH);
  7261. }
  7262. #endif // !CHDK && HAS_PHOTOGRAPH
  7263. }
  7264. #endif // CHDK || PHOTOGRAPH_PIN
  7265. #if HAS_LCD_CONTRAST
  7266. /**
  7267. * M250: Read and optionally set the LCD contrast
  7268. */
  7269. inline void gcode_M250() {
  7270. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7271. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7272. SERIAL_PROTOCOL(lcd_contrast);
  7273. SERIAL_EOL();
  7274. }
  7275. #endif // HAS_LCD_CONTRAST
  7276. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7277. /**
  7278. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7279. *
  7280. * S<temperature> sets the minimum extrude temperature
  7281. * P<bool> enables (1) or disables (0) cold extrusion
  7282. *
  7283. * Examples:
  7284. *
  7285. * M302 ; report current cold extrusion state
  7286. * M302 P0 ; enable cold extrusion checking
  7287. * M302 P1 ; disables cold extrusion checking
  7288. * M302 S0 ; always allow extrusion (disables checking)
  7289. * M302 S170 ; only allow extrusion above 170
  7290. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7291. */
  7292. inline void gcode_M302() {
  7293. bool seen_S = parser.seen('S');
  7294. if (seen_S) {
  7295. thermalManager.extrude_min_temp = parser.value_celsius();
  7296. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7297. }
  7298. if (parser.seen('P'))
  7299. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7300. else if (!seen_S) {
  7301. // Report current state
  7302. SERIAL_ECHO_START();
  7303. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7304. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7305. SERIAL_ECHOLNPGM("C)");
  7306. }
  7307. }
  7308. #endif // PREVENT_COLD_EXTRUSION
  7309. /**
  7310. * M303: PID relay autotune
  7311. *
  7312. * S<temperature> sets the target temperature. (default 150C)
  7313. * E<extruder> (-1 for the bed) (default 0)
  7314. * C<cycles>
  7315. * U<bool> with a non-zero value will apply the result to current settings
  7316. */
  7317. inline void gcode_M303() {
  7318. #if HAS_PID_HEATING
  7319. const int e = parser.seen('E') ? parser.value_int() : 0,
  7320. c = parser.seen('C') ? parser.value_int() : 5;
  7321. const bool u = parser.seen('U') && parser.value_bool();
  7322. int16_t temp = parser.seen('S') ? parser.value_celsius() : (e < 0 ? 70 : 150);
  7323. if (WITHIN(e, 0, HOTENDS - 1))
  7324. target_extruder = e;
  7325. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  7326. thermalManager.PID_autotune(temp, e, c, u);
  7327. KEEPALIVE_STATE(IN_HANDLER);
  7328. #else
  7329. SERIAL_ERROR_START();
  7330. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7331. #endif
  7332. }
  7333. #if ENABLED(MORGAN_SCARA)
  7334. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7335. if (IsRunning()) {
  7336. forward_kinematics_SCARA(delta_a, delta_b);
  7337. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7338. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7339. destination[Z_AXIS] = current_position[Z_AXIS];
  7340. prepare_move_to_destination();
  7341. return true;
  7342. }
  7343. return false;
  7344. }
  7345. /**
  7346. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7347. */
  7348. inline bool gcode_M360() {
  7349. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7350. return SCARA_move_to_cal(0, 120);
  7351. }
  7352. /**
  7353. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7354. */
  7355. inline bool gcode_M361() {
  7356. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7357. return SCARA_move_to_cal(90, 130);
  7358. }
  7359. /**
  7360. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7361. */
  7362. inline bool gcode_M362() {
  7363. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7364. return SCARA_move_to_cal(60, 180);
  7365. }
  7366. /**
  7367. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7368. */
  7369. inline bool gcode_M363() {
  7370. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7371. return SCARA_move_to_cal(50, 90);
  7372. }
  7373. /**
  7374. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7375. */
  7376. inline bool gcode_M364() {
  7377. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7378. return SCARA_move_to_cal(45, 135);
  7379. }
  7380. #endif // SCARA
  7381. #if ENABLED(EXT_SOLENOID)
  7382. void enable_solenoid(const uint8_t num) {
  7383. switch (num) {
  7384. case 0:
  7385. OUT_WRITE(SOL0_PIN, HIGH);
  7386. break;
  7387. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7388. case 1:
  7389. OUT_WRITE(SOL1_PIN, HIGH);
  7390. break;
  7391. #endif
  7392. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7393. case 2:
  7394. OUT_WRITE(SOL2_PIN, HIGH);
  7395. break;
  7396. #endif
  7397. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7398. case 3:
  7399. OUT_WRITE(SOL3_PIN, HIGH);
  7400. break;
  7401. #endif
  7402. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7403. case 4:
  7404. OUT_WRITE(SOL4_PIN, HIGH);
  7405. break;
  7406. #endif
  7407. default:
  7408. SERIAL_ECHO_START();
  7409. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7410. break;
  7411. }
  7412. }
  7413. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7414. void disable_all_solenoids() {
  7415. OUT_WRITE(SOL0_PIN, LOW);
  7416. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7417. OUT_WRITE(SOL1_PIN, LOW);
  7418. #endif
  7419. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7420. OUT_WRITE(SOL2_PIN, LOW);
  7421. #endif
  7422. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7423. OUT_WRITE(SOL3_PIN, LOW);
  7424. #endif
  7425. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7426. OUT_WRITE(SOL4_PIN, LOW);
  7427. #endif
  7428. }
  7429. /**
  7430. * M380: Enable solenoid on the active extruder
  7431. */
  7432. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7433. /**
  7434. * M381: Disable all solenoids
  7435. */
  7436. inline void gcode_M381() { disable_all_solenoids(); }
  7437. #endif // EXT_SOLENOID
  7438. /**
  7439. * M400: Finish all moves
  7440. */
  7441. inline void gcode_M400() { stepper.synchronize(); }
  7442. #if HAS_BED_PROBE
  7443. /**
  7444. * M401: Engage Z Servo endstop if available
  7445. */
  7446. inline void gcode_M401() { DEPLOY_PROBE(); }
  7447. /**
  7448. * M402: Retract Z Servo endstop if enabled
  7449. */
  7450. inline void gcode_M402() { STOW_PROBE(); }
  7451. #endif // HAS_BED_PROBE
  7452. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7453. /**
  7454. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7455. */
  7456. inline void gcode_M404() {
  7457. if (parser.seen('W')) {
  7458. filament_width_nominal = parser.value_linear_units();
  7459. }
  7460. else {
  7461. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7462. SERIAL_PROTOCOLLN(filament_width_nominal);
  7463. }
  7464. }
  7465. /**
  7466. * M405: Turn on filament sensor for control
  7467. */
  7468. inline void gcode_M405() {
  7469. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  7470. // everything else, it uses parser.value_int() instead of parser.value_linear_units().
  7471. if (parser.seen('D')) meas_delay_cm = parser.value_int();
  7472. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7473. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7474. const int temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7475. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7476. measurement_delay[i] = temp_ratio;
  7477. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7478. }
  7479. filament_sensor = true;
  7480. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7481. //SERIAL_PROTOCOL(filament_width_meas);
  7482. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7483. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7484. }
  7485. /**
  7486. * M406: Turn off filament sensor for control
  7487. */
  7488. inline void gcode_M406() { filament_sensor = false; }
  7489. /**
  7490. * M407: Get measured filament diameter on serial output
  7491. */
  7492. inline void gcode_M407() {
  7493. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7494. SERIAL_PROTOCOLLN(filament_width_meas);
  7495. }
  7496. #endif // FILAMENT_WIDTH_SENSOR
  7497. void quickstop_stepper() {
  7498. stepper.quick_stop();
  7499. stepper.synchronize();
  7500. set_current_from_steppers_for_axis(ALL_AXES);
  7501. SYNC_PLAN_POSITION_KINEMATIC();
  7502. }
  7503. #if HAS_LEVELING
  7504. /**
  7505. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7506. *
  7507. * S[bool] Turns leveling on or off
  7508. * Z[height] Sets the Z fade height (0 or none to disable)
  7509. * V[bool] Verbose - Print the leveling grid
  7510. *
  7511. * With AUTO_BED_LEVELING_UBL only:
  7512. *
  7513. * L[index] Load UBL mesh from index (0 is default)
  7514. */
  7515. inline void gcode_M420() {
  7516. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7517. // L to load a mesh from the EEPROM
  7518. if (parser.seen('L')) {
  7519. #if ENABLED(EEPROM_SETTINGS)
  7520. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7521. const int16_t a = settings.calc_num_meshes();
  7522. if (!a) {
  7523. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7524. return;
  7525. }
  7526. if (!WITHIN(storage_slot, 0, a - 1)) {
  7527. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7528. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7529. return;
  7530. }
  7531. settings.load_mesh(storage_slot);
  7532. ubl.state.storage_slot = storage_slot;
  7533. #else
  7534. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7535. return;
  7536. #endif
  7537. }
  7538. // L to load a mesh from the EEPROM
  7539. if (parser.seen('L') || parser.seen('V')) {
  7540. ubl.display_map(0); // Currently only supports one map type
  7541. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7542. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7543. }
  7544. #endif // AUTO_BED_LEVELING_UBL
  7545. // V to print the matrix or mesh
  7546. if (parser.seen('V')) {
  7547. #if ABL_PLANAR
  7548. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7549. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7550. if (leveling_is_valid()) {
  7551. print_bilinear_leveling_grid();
  7552. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7553. bed_level_virt_print();
  7554. #endif
  7555. }
  7556. #elif ENABLED(MESH_BED_LEVELING)
  7557. if (leveling_is_valid()) {
  7558. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7559. mbl_mesh_report();
  7560. }
  7561. #endif
  7562. }
  7563. bool to_enable = false;
  7564. if (parser.seen('S')) {
  7565. to_enable = parser.value_bool();
  7566. set_bed_leveling_enabled(to_enable);
  7567. }
  7568. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7569. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7570. #endif
  7571. const bool new_status = leveling_is_active();
  7572. if (to_enable && !new_status) {
  7573. SERIAL_ERROR_START();
  7574. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7575. }
  7576. SERIAL_ECHO_START();
  7577. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7578. }
  7579. #endif
  7580. #if ENABLED(MESH_BED_LEVELING)
  7581. /**
  7582. * M421: Set a single Mesh Bed Leveling Z coordinate
  7583. *
  7584. * Usage:
  7585. * M421 X<linear> Y<linear> Z<linear>
  7586. * M421 X<linear> Y<linear> Q<offset>
  7587. * M421 I<xindex> J<yindex> Z<linear>
  7588. * M421 I<xindex> J<yindex> Q<offset>
  7589. */
  7590. inline void gcode_M421() {
  7591. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7592. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7593. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7594. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7595. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7596. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7597. SERIAL_ERROR_START();
  7598. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7599. }
  7600. else if (ix < 0 || iy < 0) {
  7601. SERIAL_ERROR_START();
  7602. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7603. }
  7604. else
  7605. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7606. }
  7607. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7608. /**
  7609. * M421: Set a single Mesh Bed Leveling Z coordinate
  7610. *
  7611. * Usage:
  7612. * M421 I<xindex> J<yindex> Z<linear>
  7613. * M421 I<xindex> J<yindex> Q<offset>
  7614. */
  7615. inline void gcode_M421() {
  7616. const bool hasI = parser.seen('I');
  7617. const int8_t ix = hasI ? parser.value_int() : -1;
  7618. const bool hasJ = parser.seen('J');
  7619. const int8_t iy = hasJ ? parser.value_int() : -1;
  7620. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7621. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  7622. SERIAL_ERROR_START();
  7623. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7624. }
  7625. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7626. SERIAL_ERROR_START();
  7627. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7628. }
  7629. else {
  7630. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7631. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7632. bed_level_virt_interpolate();
  7633. #endif
  7634. }
  7635. }
  7636. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7637. /**
  7638. * M421: Set a single Mesh Bed Leveling Z coordinate
  7639. *
  7640. * Usage:
  7641. * M421 I<xindex> J<yindex> Z<linear>
  7642. * M421 I<xindex> J<yindex> Q<offset>
  7643. * M421 C Z<linear>
  7644. * M421 C Q<offset>
  7645. */
  7646. inline void gcode_M421() {
  7647. const bool hasC = parser.seen('C'), hasI = parser.seen('I');
  7648. int8_t ix = hasI ? parser.value_int() : -1;
  7649. const bool hasJ = parser.seen('J');
  7650. int8_t iy = hasJ ? parser.value_int() : -1;
  7651. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7652. if (hasC) {
  7653. const mesh_index_pair location = ubl.find_closest_mesh_point_of_type(REAL, current_position[X_AXIS], current_position[Y_AXIS], USE_NOZZLE_AS_REFERENCE, NULL, false);
  7654. ix = location.x_index;
  7655. iy = location.y_index;
  7656. }
  7657. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7658. SERIAL_ERROR_START();
  7659. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7660. }
  7661. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7662. SERIAL_ERROR_START();
  7663. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7664. }
  7665. else
  7666. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7667. }
  7668. #endif // AUTO_BED_LEVELING_UBL
  7669. #if HAS_M206_COMMAND
  7670. /**
  7671. * M428: Set home_offset based on the distance between the
  7672. * current_position and the nearest "reference point."
  7673. * If an axis is past center its endstop position
  7674. * is the reference-point. Otherwise it uses 0. This allows
  7675. * the Z offset to be set near the bed when using a max endstop.
  7676. *
  7677. * M428 can't be used more than 2cm away from 0 or an endstop.
  7678. *
  7679. * Use M206 to set these values directly.
  7680. */
  7681. inline void gcode_M428() {
  7682. bool err = false;
  7683. LOOP_XYZ(i) {
  7684. if (axis_homed[i]) {
  7685. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7686. diff = base - RAW_POSITION(current_position[i], i);
  7687. if (WITHIN(diff, -20, 20)) {
  7688. set_home_offset((AxisEnum)i, diff);
  7689. }
  7690. else {
  7691. SERIAL_ERROR_START();
  7692. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7693. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7694. BUZZ(200, 40);
  7695. err = true;
  7696. break;
  7697. }
  7698. }
  7699. }
  7700. if (!err) {
  7701. SYNC_PLAN_POSITION_KINEMATIC();
  7702. report_current_position();
  7703. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7704. BUZZ(100, 659);
  7705. BUZZ(100, 698);
  7706. }
  7707. }
  7708. #endif // HAS_M206_COMMAND
  7709. /**
  7710. * M500: Store settings in EEPROM
  7711. */
  7712. inline void gcode_M500() {
  7713. (void)settings.save();
  7714. }
  7715. /**
  7716. * M501: Read settings from EEPROM
  7717. */
  7718. inline void gcode_M501() {
  7719. (void)settings.load();
  7720. }
  7721. /**
  7722. * M502: Revert to default settings
  7723. */
  7724. inline void gcode_M502() {
  7725. (void)settings.reset();
  7726. }
  7727. /**
  7728. * M503: print settings currently in memory
  7729. */
  7730. inline void gcode_M503() {
  7731. (void)settings.report(parser.seen('S') && !parser.value_bool());
  7732. }
  7733. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7734. /**
  7735. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7736. */
  7737. inline void gcode_M540() {
  7738. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7739. }
  7740. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7741. #if HAS_BED_PROBE
  7742. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7743. static float last_zoffset = NAN;
  7744. if (!isnan(last_zoffset)) {
  7745. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7746. const float diff = zprobe_zoffset - last_zoffset;
  7747. #endif
  7748. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7749. // Correct bilinear grid for new probe offset
  7750. if (diff) {
  7751. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7752. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7753. z_values[x][y] -= diff;
  7754. }
  7755. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7756. bed_level_virt_interpolate();
  7757. #endif
  7758. #endif
  7759. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7760. if (!no_babystep && leveling_is_active())
  7761. thermalManager.babystep_axis(Z_AXIS, -lround(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7762. #else
  7763. UNUSED(no_babystep);
  7764. #endif
  7765. #if ENABLED(DELTA) // correct the delta_height
  7766. home_offset[Z_AXIS] -= diff;
  7767. #endif
  7768. }
  7769. last_zoffset = zprobe_zoffset;
  7770. }
  7771. inline void gcode_M851() {
  7772. SERIAL_ECHO_START();
  7773. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7774. if (parser.seen('Z')) {
  7775. const float value = parser.value_linear_units();
  7776. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7777. zprobe_zoffset = value;
  7778. refresh_zprobe_zoffset();
  7779. SERIAL_ECHO(zprobe_zoffset);
  7780. }
  7781. else
  7782. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7783. }
  7784. else
  7785. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7786. SERIAL_EOL();
  7787. }
  7788. #endif // HAS_BED_PROBE
  7789. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7790. /**
  7791. * M600: Pause for filament change
  7792. *
  7793. * E[distance] - Retract the filament this far (negative value)
  7794. * Z[distance] - Move the Z axis by this distance
  7795. * X[position] - Move to this X position, with Y
  7796. * Y[position] - Move to this Y position, with X
  7797. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7798. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7799. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7800. *
  7801. * Default values are used for omitted arguments.
  7802. *
  7803. */
  7804. inline void gcode_M600() {
  7805. // Initial retract before move to filament change position
  7806. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7807. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7808. - (PAUSE_PARK_RETRACT_LENGTH)
  7809. #endif
  7810. ;
  7811. // Lift Z axis
  7812. const float z_lift = parser.seen('Z') ? parser.value_linear_units() :
  7813. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7814. PAUSE_PARK_Z_ADD
  7815. #else
  7816. 0
  7817. #endif
  7818. ;
  7819. // Move XY axes to filament exchange position
  7820. const float x_pos = parser.seen('X') ? parser.value_linear_units() : 0
  7821. #ifdef PAUSE_PARK_X_POS
  7822. + PAUSE_PARK_X_POS
  7823. #endif
  7824. ;
  7825. const float y_pos = parser.seen('Y') ? parser.value_linear_units() : 0
  7826. #ifdef PAUSE_PARK_Y_POS
  7827. + PAUSE_PARK_Y_POS
  7828. #endif
  7829. ;
  7830. // Unload filament
  7831. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7832. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7833. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7834. #endif
  7835. ;
  7836. // Load filament
  7837. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7838. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7839. + FILAMENT_CHANGE_LOAD_LENGTH
  7840. #endif
  7841. ;
  7842. const int beep_count = parser.seen('B') ? parser.value_int() :
  7843. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7844. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7845. #else
  7846. -1
  7847. #endif
  7848. ;
  7849. const bool job_running = print_job_timer.isRunning();
  7850. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7851. wait_for_filament_reload(beep_count);
  7852. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7853. }
  7854. // Resume the print job timer if it was running
  7855. if (job_running) print_job_timer.start();
  7856. }
  7857. #endif // ADVANCED_PAUSE_FEATURE
  7858. #if ENABLED(DUAL_X_CARRIAGE)
  7859. /**
  7860. * M605: Set dual x-carriage movement mode
  7861. *
  7862. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  7863. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  7864. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  7865. * units x-offset and an optional differential hotend temperature of
  7866. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  7867. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  7868. *
  7869. * Note: the X axis should be homed after changing dual x-carriage mode.
  7870. */
  7871. inline void gcode_M605() {
  7872. stepper.synchronize();
  7873. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  7874. switch (dual_x_carriage_mode) {
  7875. case DXC_FULL_CONTROL_MODE:
  7876. case DXC_AUTO_PARK_MODE:
  7877. break;
  7878. case DXC_DUPLICATION_MODE:
  7879. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  7880. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  7881. SERIAL_ECHO_START();
  7882. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7883. SERIAL_CHAR(' ');
  7884. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  7885. SERIAL_CHAR(',');
  7886. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  7887. SERIAL_CHAR(' ');
  7888. SERIAL_ECHO(duplicate_extruder_x_offset);
  7889. SERIAL_CHAR(',');
  7890. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  7891. break;
  7892. default:
  7893. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  7894. break;
  7895. }
  7896. active_extruder_parked = false;
  7897. extruder_duplication_enabled = false;
  7898. delayed_move_time = 0;
  7899. }
  7900. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  7901. inline void gcode_M605() {
  7902. stepper.synchronize();
  7903. extruder_duplication_enabled = parser.seen('S') && parser.value_int() == (int)DXC_DUPLICATION_MODE;
  7904. SERIAL_ECHO_START();
  7905. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  7906. }
  7907. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  7908. #if ENABLED(LIN_ADVANCE)
  7909. /**
  7910. * M900: Set and/or Get advance K factor and WH/D ratio
  7911. *
  7912. * K<factor> Set advance K factor
  7913. * R<ratio> Set ratio directly (overrides WH/D)
  7914. * W<width> H<height> D<diam> Set ratio from WH/D
  7915. */
  7916. inline void gcode_M900() {
  7917. stepper.synchronize();
  7918. const float newK = parser.seen('K') ? parser.value_float() : -1;
  7919. if (newK >= 0) planner.extruder_advance_k = newK;
  7920. float newR = parser.seen('R') ? parser.value_float() : -1;
  7921. if (newR < 0) {
  7922. const float newD = parser.seen('D') ? parser.value_float() : -1,
  7923. newW = parser.seen('W') ? parser.value_float() : -1,
  7924. newH = parser.seen('H') ? parser.value_float() : -1;
  7925. if (newD >= 0 && newW >= 0 && newH >= 0)
  7926. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  7927. }
  7928. if (newR >= 0) planner.advance_ed_ratio = newR;
  7929. SERIAL_ECHO_START();
  7930. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  7931. SERIAL_ECHOPGM(" E/D=");
  7932. const float ratio = planner.advance_ed_ratio;
  7933. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  7934. SERIAL_EOL();
  7935. }
  7936. #endif // LIN_ADVANCE
  7937. #if ENABLED(HAVE_TMC2130)
  7938. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  7939. SERIAL_CHAR(name);
  7940. SERIAL_ECHOPGM(" axis driver current: ");
  7941. SERIAL_ECHOLN(st.getCurrent());
  7942. }
  7943. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  7944. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  7945. tmc2130_get_current(st, name);
  7946. }
  7947. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  7948. SERIAL_CHAR(name);
  7949. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  7950. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  7951. SERIAL_EOL();
  7952. }
  7953. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  7954. st.clear_otpw();
  7955. SERIAL_CHAR(name);
  7956. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  7957. }
  7958. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  7959. SERIAL_CHAR(name);
  7960. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  7961. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  7962. }
  7963. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  7964. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  7965. tmc2130_get_pwmthrs(st, name, spmm);
  7966. }
  7967. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  7968. SERIAL_CHAR(name);
  7969. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  7970. SERIAL_ECHOLN(st.sgt());
  7971. }
  7972. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  7973. st.sgt(sgt_val);
  7974. tmc2130_get_sgt(st, name);
  7975. }
  7976. /**
  7977. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  7978. * Report driver currents when no axis specified
  7979. *
  7980. * S1: Enable automatic current control
  7981. * S0: Disable
  7982. */
  7983. inline void gcode_M906() {
  7984. uint16_t values[XYZE];
  7985. LOOP_XYZE(i)
  7986. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  7987. #if ENABLED(X_IS_TMC2130)
  7988. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  7989. else tmc2130_get_current(stepperX, 'X');
  7990. #endif
  7991. #if ENABLED(Y_IS_TMC2130)
  7992. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  7993. else tmc2130_get_current(stepperY, 'Y');
  7994. #endif
  7995. #if ENABLED(Z_IS_TMC2130)
  7996. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  7997. else tmc2130_get_current(stepperZ, 'Z');
  7998. #endif
  7999. #if ENABLED(E0_IS_TMC2130)
  8000. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  8001. else tmc2130_get_current(stepperE0, 'E');
  8002. #endif
  8003. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8004. if (parser.seen('S')) auto_current_control = parser.value_bool();
  8005. #endif
  8006. }
  8007. /**
  8008. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  8009. * The flag is held by the library and persist until manually cleared by M912
  8010. */
  8011. inline void gcode_M911() {
  8012. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  8013. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  8014. #if ENABLED(X_IS_TMC2130)
  8015. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  8016. #endif
  8017. #if ENABLED(Y_IS_TMC2130)
  8018. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  8019. #endif
  8020. #if ENABLED(Z_IS_TMC2130)
  8021. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  8022. #endif
  8023. #if ENABLED(E0_IS_TMC2130)
  8024. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  8025. #endif
  8026. }
  8027. /**
  8028. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  8029. */
  8030. inline void gcode_M912() {
  8031. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  8032. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  8033. #if ENABLED(X_IS_TMC2130)
  8034. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  8035. #endif
  8036. #if ENABLED(Y_IS_TMC2130)
  8037. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  8038. #endif
  8039. #if ENABLED(Z_IS_TMC2130)
  8040. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  8041. #endif
  8042. #if ENABLED(E0_IS_TMC2130)
  8043. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  8044. #endif
  8045. }
  8046. /**
  8047. * M913: Set HYBRID_THRESHOLD speed.
  8048. */
  8049. #if ENABLED(HYBRID_THRESHOLD)
  8050. inline void gcode_M913() {
  8051. uint16_t values[XYZE];
  8052. LOOP_XYZE(i)
  8053. values[i] = parser.seen(axis_codes[i]) ? parser.value_int() : 0;
  8054. #if ENABLED(X_IS_TMC2130)
  8055. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  8056. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  8057. #endif
  8058. #if ENABLED(Y_IS_TMC2130)
  8059. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  8060. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  8061. #endif
  8062. #if ENABLED(Z_IS_TMC2130)
  8063. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  8064. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  8065. #endif
  8066. #if ENABLED(E0_IS_TMC2130)
  8067. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  8068. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  8069. #endif
  8070. }
  8071. #endif // HYBRID_THRESHOLD
  8072. /**
  8073. * M914: Set SENSORLESS_HOMING sensitivity.
  8074. */
  8075. #if ENABLED(SENSORLESS_HOMING)
  8076. inline void gcode_M914() {
  8077. #if ENABLED(X_IS_TMC2130)
  8078. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  8079. else tmc2130_get_sgt(stepperX, 'X');
  8080. #endif
  8081. #if ENABLED(Y_IS_TMC2130)
  8082. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  8083. else tmc2130_get_sgt(stepperY, 'Y');
  8084. #endif
  8085. }
  8086. #endif // SENSORLESS_HOMING
  8087. #endif // HAVE_TMC2130
  8088. /**
  8089. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  8090. */
  8091. inline void gcode_M907() {
  8092. #if HAS_DIGIPOTSS
  8093. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  8094. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  8095. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  8096. #elif HAS_MOTOR_CURRENT_PWM
  8097. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  8098. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  8099. #endif
  8100. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  8101. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  8102. #endif
  8103. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  8104. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  8105. #endif
  8106. #endif
  8107. #if ENABLED(DIGIPOT_I2C)
  8108. // this one uses actual amps in floating point
  8109. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  8110. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  8111. 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());
  8112. #endif
  8113. #if ENABLED(DAC_STEPPER_CURRENT)
  8114. if (parser.seen('S')) {
  8115. const float dac_percent = parser.value_float();
  8116. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  8117. }
  8118. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  8119. #endif
  8120. }
  8121. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  8122. /**
  8123. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  8124. */
  8125. inline void gcode_M908() {
  8126. #if HAS_DIGIPOTSS
  8127. stepper.digitalPotWrite(
  8128. parser.seen('P') ? parser.value_int() : 0,
  8129. parser.seen('S') ? parser.value_int() : 0
  8130. );
  8131. #endif
  8132. #ifdef DAC_STEPPER_CURRENT
  8133. dac_current_raw(
  8134. parser.seen('P') ? parser.value_byte() : -1,
  8135. parser.seen('S') ? parser.value_ushort() : 0
  8136. );
  8137. #endif
  8138. }
  8139. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  8140. inline void gcode_M909() { dac_print_values(); }
  8141. inline void gcode_M910() { dac_commit_eeprom(); }
  8142. #endif
  8143. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  8144. #if HAS_MICROSTEPS
  8145. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  8146. inline void gcode_M350() {
  8147. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  8148. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  8149. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  8150. stepper.microstep_readings();
  8151. }
  8152. /**
  8153. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  8154. * S# determines MS1 or MS2, X# sets the pin high/low.
  8155. */
  8156. inline void gcode_M351() {
  8157. if (parser.seen('S')) switch (parser.value_byte()) {
  8158. case 1:
  8159. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  8160. if (parser.seen('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  8161. break;
  8162. case 2:
  8163. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  8164. if (parser.seen('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  8165. break;
  8166. }
  8167. stepper.microstep_readings();
  8168. }
  8169. #endif // HAS_MICROSTEPS
  8170. #if HAS_CASE_LIGHT
  8171. #ifndef INVERT_CASE_LIGHT
  8172. #define INVERT_CASE_LIGHT false
  8173. #endif
  8174. int case_light_brightness; // LCD routine wants INT
  8175. bool case_light_on;
  8176. void update_case_light() {
  8177. pinMode(CASE_LIGHT_PIN, OUTPUT); // digitalWrite doesn't set the port mode
  8178. uint8_t case_light_bright = (uint8_t)case_light_brightness;
  8179. if (case_light_on) {
  8180. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  8181. analogWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? 255 - case_light_brightness : case_light_brightness );
  8182. }
  8183. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? LOW : HIGH );
  8184. }
  8185. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? HIGH : LOW);
  8186. }
  8187. #endif // HAS_CASE_LIGHT
  8188. /**
  8189. * M355: Turn case light on/off and set brightness
  8190. *
  8191. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  8192. *
  8193. * S<bool> Set case light on/off
  8194. *
  8195. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  8196. *
  8197. * M355 P200 S0 turns off the light & sets the brightness level
  8198. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  8199. */
  8200. inline void gcode_M355() {
  8201. #if HAS_CASE_LIGHT
  8202. uint8_t args = 0;
  8203. if (parser.seen('P')) ++args, case_light_brightness = parser.value_byte();
  8204. if (parser.seen('S')) ++args, case_light_on = parser.value_bool();
  8205. if (args) update_case_light();
  8206. // always report case light status
  8207. SERIAL_ECHO_START();
  8208. if (!case_light_on) {
  8209. SERIAL_ECHOLN("Case light: off");
  8210. }
  8211. else {
  8212. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLN("Case light: on");
  8213. else SERIAL_ECHOLNPAIR("Case light: ", case_light_brightness);
  8214. }
  8215. #else
  8216. SERIAL_ERROR_START();
  8217. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8218. #endif // HAS_CASE_LIGHT
  8219. }
  8220. #if ENABLED(MIXING_EXTRUDER)
  8221. /**
  8222. * M163: Set a single mix factor for a mixing extruder
  8223. * This is called "weight" by some systems.
  8224. *
  8225. * S[index] The channel index to set
  8226. * P[float] The mix value
  8227. *
  8228. */
  8229. inline void gcode_M163() {
  8230. const int mix_index = parser.seen('S') ? parser.value_int() : 0;
  8231. if (mix_index < MIXING_STEPPERS) {
  8232. float mix_value = parser.seen('P') ? parser.value_float() : 0.0;
  8233. NOLESS(mix_value, 0.0);
  8234. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8235. }
  8236. }
  8237. #if MIXING_VIRTUAL_TOOLS > 1
  8238. /**
  8239. * M164: Store the current mix factors as a virtual tool.
  8240. *
  8241. * S[index] The virtual tool to store
  8242. *
  8243. */
  8244. inline void gcode_M164() {
  8245. const int tool_index = parser.seen('S') ? parser.value_int() : 0;
  8246. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8247. normalize_mix();
  8248. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8249. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8250. }
  8251. }
  8252. #endif
  8253. #if ENABLED(DIRECT_MIXING_IN_G1)
  8254. /**
  8255. * M165: Set multiple mix factors for a mixing extruder.
  8256. * Factors that are left out will be set to 0.
  8257. * All factors together must add up to 1.0.
  8258. *
  8259. * A[factor] Mix factor for extruder stepper 1
  8260. * B[factor] Mix factor for extruder stepper 2
  8261. * C[factor] Mix factor for extruder stepper 3
  8262. * D[factor] Mix factor for extruder stepper 4
  8263. * H[factor] Mix factor for extruder stepper 5
  8264. * I[factor] Mix factor for extruder stepper 6
  8265. *
  8266. */
  8267. inline void gcode_M165() { gcode_get_mix(); }
  8268. #endif
  8269. #endif // MIXING_EXTRUDER
  8270. /**
  8271. * M999: Restart after being stopped
  8272. *
  8273. * Default behaviour is to flush the serial buffer and request
  8274. * a resend to the host starting on the last N line received.
  8275. *
  8276. * Sending "M999 S1" will resume printing without flushing the
  8277. * existing command buffer.
  8278. *
  8279. */
  8280. inline void gcode_M999() {
  8281. Running = true;
  8282. lcd_reset_alert_level();
  8283. if (parser.seen('S') && parser.value_bool()) return;
  8284. // gcode_LastN = Stopped_gcode_LastN;
  8285. FlushSerialRequestResend();
  8286. }
  8287. #if ENABLED(SWITCHING_EXTRUDER)
  8288. inline void move_extruder_servo(uint8_t e) {
  8289. const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8290. MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]);
  8291. safe_delay(500);
  8292. }
  8293. #endif
  8294. #if ENABLED(SWITCHING_NOZZLE)
  8295. inline void move_nozzle_servo(uint8_t e) {
  8296. const int angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8297. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8298. safe_delay(500);
  8299. }
  8300. #endif
  8301. inline void invalid_extruder_error(const uint8_t &e) {
  8302. SERIAL_ECHO_START();
  8303. SERIAL_CHAR('T');
  8304. SERIAL_ECHO_F(e, DEC);
  8305. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8306. }
  8307. /**
  8308. * Perform a tool-change, which may result in moving the
  8309. * previous tool out of the way and the new tool into place.
  8310. */
  8311. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8312. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8313. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8314. return invalid_extruder_error(tmp_extruder);
  8315. // T0-Tnnn: Switch virtual tool by changing the mix
  8316. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8317. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8318. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8319. #if HOTENDS > 1
  8320. if (tmp_extruder >= EXTRUDERS)
  8321. return invalid_extruder_error(tmp_extruder);
  8322. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8323. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8324. if (tmp_extruder != active_extruder) {
  8325. if (!no_move && axis_unhomed_error()) {
  8326. SERIAL_ECHOLNPGM("No move on toolchange");
  8327. no_move = true;
  8328. }
  8329. // Save current position to destination, for use later
  8330. set_destination_to_current();
  8331. #if ENABLED(DUAL_X_CARRIAGE)
  8332. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8333. if (DEBUGGING(LEVELING)) {
  8334. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8335. switch (dual_x_carriage_mode) {
  8336. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8337. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8338. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8339. }
  8340. }
  8341. #endif
  8342. const float xhome = x_home_pos(active_extruder);
  8343. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8344. && IsRunning()
  8345. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8346. ) {
  8347. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8348. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8349. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8350. #endif
  8351. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8352. if (DEBUGGING(LEVELING)) {
  8353. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8354. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8355. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8356. }
  8357. #endif
  8358. // Park old head: 1) raise 2) move to park position 3) lower
  8359. for (uint8_t i = 0; i < 3; i++)
  8360. planner.buffer_line(
  8361. i == 0 ? current_position[X_AXIS] : xhome,
  8362. current_position[Y_AXIS],
  8363. i == 2 ? current_position[Z_AXIS] : raised_z,
  8364. current_position[E_AXIS],
  8365. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8366. active_extruder
  8367. );
  8368. stepper.synchronize();
  8369. }
  8370. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8371. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8372. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8373. // Activate the new extruder
  8374. active_extruder = tmp_extruder;
  8375. // This function resets the max/min values - the current position may be overwritten below.
  8376. set_axis_is_at_home(X_AXIS);
  8377. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8378. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8379. #endif
  8380. // Only when auto-parking are carriages safe to move
  8381. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8382. switch (dual_x_carriage_mode) {
  8383. case DXC_FULL_CONTROL_MODE:
  8384. // New current position is the position of the activated extruder
  8385. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8386. // Save the inactive extruder's position (from the old current_position)
  8387. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8388. break;
  8389. case DXC_AUTO_PARK_MODE:
  8390. // record raised toolhead position for use by unpark
  8391. COPY(raised_parked_position, current_position);
  8392. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8393. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8394. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8395. #endif
  8396. active_extruder_parked = true;
  8397. delayed_move_time = 0;
  8398. break;
  8399. case DXC_DUPLICATION_MODE:
  8400. // If the new extruder is the left one, set it "parked"
  8401. // This triggers the second extruder to move into the duplication position
  8402. active_extruder_parked = (active_extruder == 0);
  8403. if (active_extruder_parked)
  8404. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8405. else
  8406. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8407. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8408. extruder_duplication_enabled = false;
  8409. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8410. if (DEBUGGING(LEVELING)) {
  8411. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8412. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8413. }
  8414. #endif
  8415. break;
  8416. }
  8417. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8418. if (DEBUGGING(LEVELING)) {
  8419. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8420. DEBUG_POS("New extruder (parked)", current_position);
  8421. }
  8422. #endif
  8423. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8424. #else // !DUAL_X_CARRIAGE
  8425. #if ENABLED(SWITCHING_NOZZLE)
  8426. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8427. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8428. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8429. // Always raise by some amount (destination copied from current_position earlier)
  8430. current_position[Z_AXIS] += z_raise;
  8431. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8432. stepper.synchronize();
  8433. move_nozzle_servo(active_extruder);
  8434. #endif
  8435. #if ENABLED(SWITCHING_EXTRUDER)
  8436. #if !(ENABLED(SWITCHING_NOZZLE) && (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR))
  8437. stepper.synchronize();
  8438. move_extruder_servo(active_extruder);
  8439. #endif
  8440. #endif
  8441. /**
  8442. * Set current_position to the position of the new nozzle.
  8443. * Offsets are based on linear distance, so we need to get
  8444. * the resulting position in coordinate space.
  8445. *
  8446. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8447. * - With mesh leveling, update Z for the new position
  8448. * - Otherwise, just use the raw linear distance
  8449. *
  8450. * Software endstops are altered here too. Consider a case where:
  8451. * E0 at X=0 ... E1 at X=10
  8452. * When we switch to E1 now X=10, but E1 can't move left.
  8453. * To express this we apply the change in XY to the software endstops.
  8454. * E1 can move farther right than E0, so the right limit is extended.
  8455. *
  8456. * Note that we don't adjust the Z software endstops. Why not?
  8457. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8458. * because the bed is 1mm lower at the new position. As long as
  8459. * the first nozzle is out of the way, the carriage should be
  8460. * allowed to move 1mm lower. This technically "breaks" the
  8461. * Z software endstop. But this is technically correct (and
  8462. * there is no viable alternative).
  8463. */
  8464. #if ABL_PLANAR
  8465. // Offset extruder, make sure to apply the bed level rotation matrix
  8466. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8467. hotend_offset[Y_AXIS][tmp_extruder],
  8468. 0),
  8469. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8470. hotend_offset[Y_AXIS][active_extruder],
  8471. 0),
  8472. offset_vec = tmp_offset_vec - act_offset_vec;
  8473. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8474. if (DEBUGGING(LEVELING)) {
  8475. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8476. act_offset_vec.debug(PSTR("act_offset_vec"));
  8477. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8478. }
  8479. #endif
  8480. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8481. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8482. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8483. #endif
  8484. // Adjustments to the current position
  8485. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8486. current_position[Z_AXIS] += offset_vec.z;
  8487. #else // !ABL_PLANAR
  8488. const float xydiff[2] = {
  8489. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8490. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8491. };
  8492. #if ENABLED(MESH_BED_LEVELING)
  8493. if (leveling_is_active()) {
  8494. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8495. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8496. #endif
  8497. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8498. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8499. z1 = current_position[Z_AXIS], z2 = z1;
  8500. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8501. planner.apply_leveling(x2, y2, z2);
  8502. current_position[Z_AXIS] += z2 - z1;
  8503. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8504. if (DEBUGGING(LEVELING))
  8505. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8506. #endif
  8507. }
  8508. #endif // MESH_BED_LEVELING
  8509. #endif // !HAS_ABL
  8510. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8511. if (DEBUGGING(LEVELING)) {
  8512. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8513. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8514. SERIAL_ECHOLNPGM(" }");
  8515. }
  8516. #endif
  8517. // The newly-selected extruder XY is actually at...
  8518. current_position[X_AXIS] += xydiff[X_AXIS];
  8519. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8520. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8521. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8522. #if HAS_POSITION_SHIFT
  8523. position_shift[i] += xydiff[i];
  8524. #endif
  8525. update_software_endstops((AxisEnum)i);
  8526. }
  8527. #endif
  8528. // Set the new active extruder
  8529. active_extruder = tmp_extruder;
  8530. #endif // !DUAL_X_CARRIAGE
  8531. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8532. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8533. #endif
  8534. // Tell the planner the new "current position"
  8535. SYNC_PLAN_POSITION_KINEMATIC();
  8536. // Move to the "old position" (move the extruder into place)
  8537. if (!no_move && IsRunning()) {
  8538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8539. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8540. #endif
  8541. prepare_move_to_destination();
  8542. }
  8543. #if ENABLED(SWITCHING_NOZZLE)
  8544. // Move back down, if needed. (Including when the new tool is higher.)
  8545. if (z_raise != z_diff) {
  8546. destination[Z_AXIS] += z_diff;
  8547. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8548. prepare_move_to_destination();
  8549. }
  8550. #endif
  8551. } // (tmp_extruder != active_extruder)
  8552. stepper.synchronize();
  8553. #if ENABLED(EXT_SOLENOID)
  8554. disable_all_solenoids();
  8555. enable_solenoid_on_active_extruder();
  8556. #endif // EXT_SOLENOID
  8557. feedrate_mm_s = old_feedrate_mm_s;
  8558. #else // HOTENDS <= 1
  8559. // Set the new active extruder
  8560. active_extruder = tmp_extruder;
  8561. UNUSED(fr_mm_s);
  8562. UNUSED(no_move);
  8563. #if ENABLED(SWITCHING_EXTRUDER)
  8564. stepper.synchronize();
  8565. move_extruder_servo(active_extruder);
  8566. #endif
  8567. #endif // HOTENDS <= 1
  8568. SERIAL_ECHO_START();
  8569. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8570. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8571. }
  8572. /**
  8573. * T0-T3: Switch tool, usually switching extruders
  8574. *
  8575. * F[units/min] Set the movement feedrate
  8576. * S1 Don't move the tool in XY after change
  8577. */
  8578. inline void gcode_T(uint8_t tmp_extruder) {
  8579. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8580. if (DEBUGGING(LEVELING)) {
  8581. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8582. SERIAL_CHAR(')');
  8583. SERIAL_EOL();
  8584. DEBUG_POS("BEFORE", current_position);
  8585. }
  8586. #endif
  8587. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8588. tool_change(tmp_extruder);
  8589. #elif HOTENDS > 1
  8590. tool_change(
  8591. tmp_extruder,
  8592. parser.seen('F') ? MMM_TO_MMS(parser.value_linear_units()) : 0.0,
  8593. (tmp_extruder == active_extruder) || (parser.seen('S') && parser.value_bool())
  8594. );
  8595. #endif
  8596. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8597. if (DEBUGGING(LEVELING)) {
  8598. DEBUG_POS("AFTER", current_position);
  8599. SERIAL_ECHOLNPGM("<<< gcode_T");
  8600. }
  8601. #endif
  8602. }
  8603. /**
  8604. * Process a single command and dispatch it to its handler
  8605. * This is called from the main loop()
  8606. */
  8607. void process_next_command() {
  8608. char * const current_command = command_queue[cmd_queue_index_r];
  8609. if (DEBUGGING(ECHO)) {
  8610. SERIAL_ECHO_START();
  8611. SERIAL_ECHOLN(current_command);
  8612. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8613. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8614. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8615. #endif
  8616. }
  8617. KEEPALIVE_STATE(IN_HANDLER);
  8618. // Parse the next command in the queue
  8619. parser.parse(current_command);
  8620. // Handle a known G, M, or T
  8621. switch (parser.command_letter) {
  8622. case 'G': switch (parser.codenum) {
  8623. // G0, G1
  8624. case 0:
  8625. case 1:
  8626. #if IS_SCARA
  8627. gcode_G0_G1(parser.codenum == 0);
  8628. #else
  8629. gcode_G0_G1();
  8630. #endif
  8631. break;
  8632. // G2, G3
  8633. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8634. case 2: // G2 - CW ARC
  8635. case 3: // G3 - CCW ARC
  8636. gcode_G2_G3(parser.codenum == 2);
  8637. break;
  8638. #endif
  8639. // G4 Dwell
  8640. case 4:
  8641. gcode_G4();
  8642. break;
  8643. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8644. // G5
  8645. case 5: // G5 - Cubic B_spline
  8646. gcode_G5();
  8647. break;
  8648. #endif // BEZIER_CURVE_SUPPORT
  8649. #if ENABLED(FWRETRACT)
  8650. case 10: // G10: retract
  8651. case 11: // G11: retract_recover
  8652. gcode_G10_G11(parser.codenum == 10);
  8653. break;
  8654. #endif // FWRETRACT
  8655. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8656. case 12:
  8657. gcode_G12(); // G12: Nozzle Clean
  8658. break;
  8659. #endif // NOZZLE_CLEAN_FEATURE
  8660. #if ENABLED(INCH_MODE_SUPPORT)
  8661. case 20: //G20: Inch Mode
  8662. gcode_G20();
  8663. break;
  8664. case 21: //G21: MM Mode
  8665. gcode_G21();
  8666. break;
  8667. #endif // INCH_MODE_SUPPORT
  8668. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8669. case 26: // G26: Mesh Validation Pattern generation
  8670. gcode_G26();
  8671. break;
  8672. #endif // AUTO_BED_LEVELING_UBL
  8673. #if ENABLED(NOZZLE_PARK_FEATURE)
  8674. case 27: // G27: Nozzle Park
  8675. gcode_G27();
  8676. break;
  8677. #endif // NOZZLE_PARK_FEATURE
  8678. case 28: // G28: Home all axes, one at a time
  8679. gcode_G28(false);
  8680. break;
  8681. #if HAS_LEVELING
  8682. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8683. // or provides access to the UBL System if enabled.
  8684. gcode_G29();
  8685. break;
  8686. #endif // HAS_LEVELING
  8687. #if HAS_BED_PROBE
  8688. case 30: // G30 Single Z probe
  8689. gcode_G30();
  8690. break;
  8691. #if ENABLED(Z_PROBE_SLED)
  8692. case 31: // G31: dock the sled
  8693. gcode_G31();
  8694. break;
  8695. case 32: // G32: undock the sled
  8696. gcode_G32();
  8697. break;
  8698. #endif // Z_PROBE_SLED
  8699. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8700. case 33: // G33: Delta Auto-Calibration
  8701. gcode_G33();
  8702. break;
  8703. #endif // DELTA_AUTO_CALIBRATION
  8704. #endif // HAS_BED_PROBE
  8705. #if ENABLED(G38_PROBE_TARGET)
  8706. case 38: // G38.2 & G38.3
  8707. if (subcode == 2 || subcode == 3)
  8708. gcode_G38(subcode == 2);
  8709. break;
  8710. #endif
  8711. case 90: // G90
  8712. relative_mode = false;
  8713. break;
  8714. case 91: // G91
  8715. relative_mode = true;
  8716. break;
  8717. case 92: // G92
  8718. gcode_G92();
  8719. break;
  8720. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8721. case 42:
  8722. gcode_G42();
  8723. break;
  8724. #endif
  8725. #if ENABLED(DEBUG_GCODE_PARSER)
  8726. case 800:
  8727. parser.debug(); // GCode Parser Test for G
  8728. break;
  8729. #endif
  8730. }
  8731. break;
  8732. case 'M': switch (parser.codenum) {
  8733. #if HAS_RESUME_CONTINUE
  8734. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8735. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8736. gcode_M0_M1();
  8737. break;
  8738. #endif // ULTIPANEL
  8739. #if ENABLED(SPINDLE_LASER_ENABLE)
  8740. case 3:
  8741. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8742. break; // synchronizes with movement commands
  8743. case 4:
  8744. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8745. break; // synchronizes with movement commands
  8746. case 5:
  8747. gcode_M5(); // M5 - turn spindle/laser off
  8748. break; // synchronizes with movement commands
  8749. #endif
  8750. case 17: // M17: Enable all stepper motors
  8751. gcode_M17();
  8752. break;
  8753. #if ENABLED(SDSUPPORT)
  8754. case 20: // M20: list SD card
  8755. gcode_M20(); break;
  8756. case 21: // M21: init SD card
  8757. gcode_M21(); break;
  8758. case 22: // M22: release SD card
  8759. gcode_M22(); break;
  8760. case 23: // M23: Select file
  8761. gcode_M23(); break;
  8762. case 24: // M24: Start SD print
  8763. gcode_M24(); break;
  8764. case 25: // M25: Pause SD print
  8765. gcode_M25(); break;
  8766. case 26: // M26: Set SD index
  8767. gcode_M26(); break;
  8768. case 27: // M27: Get SD status
  8769. gcode_M27(); break;
  8770. case 28: // M28: Start SD write
  8771. gcode_M28(); break;
  8772. case 29: // M29: Stop SD write
  8773. gcode_M29(); break;
  8774. case 30: // M30 <filename> Delete File
  8775. gcode_M30(); break;
  8776. case 32: // M32: Select file and start SD print
  8777. gcode_M32(); break;
  8778. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8779. case 33: // M33: Get the long full path to a file or folder
  8780. gcode_M33(); break;
  8781. #endif
  8782. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8783. case 34: //M34 - Set SD card sorting options
  8784. gcode_M34(); break;
  8785. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8786. case 928: // M928: Start SD write
  8787. gcode_M928(); break;
  8788. #endif // SDSUPPORT
  8789. case 31: // M31: Report time since the start of SD print or last M109
  8790. gcode_M31(); break;
  8791. case 42: // M42: Change pin state
  8792. gcode_M42(); break;
  8793. #if ENABLED(PINS_DEBUGGING)
  8794. case 43: // M43: Read pin state
  8795. gcode_M43(); break;
  8796. #endif
  8797. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8798. case 48: // M48: Z probe repeatability test
  8799. gcode_M48();
  8800. break;
  8801. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8802. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8803. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8804. gcode_M49();
  8805. break;
  8806. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8807. case 75: // M75: Start print timer
  8808. gcode_M75(); break;
  8809. case 76: // M76: Pause print timer
  8810. gcode_M76(); break;
  8811. case 77: // M77: Stop print timer
  8812. gcode_M77(); break;
  8813. #if ENABLED(PRINTCOUNTER)
  8814. case 78: // M78: Show print statistics
  8815. gcode_M78(); break;
  8816. #endif
  8817. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8818. case 100: // M100: Free Memory Report
  8819. gcode_M100();
  8820. break;
  8821. #endif
  8822. case 104: // M104: Set hot end temperature
  8823. gcode_M104();
  8824. break;
  8825. case 110: // M110: Set Current Line Number
  8826. gcode_M110();
  8827. break;
  8828. case 111: // M111: Set debug level
  8829. gcode_M111();
  8830. break;
  8831. #if DISABLED(EMERGENCY_PARSER)
  8832. case 108: // M108: Cancel Waiting
  8833. gcode_M108();
  8834. break;
  8835. case 112: // M112: Emergency Stop
  8836. gcode_M112();
  8837. break;
  8838. case 410: // M410 quickstop - Abort all the planned moves.
  8839. gcode_M410();
  8840. break;
  8841. #endif
  8842. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  8843. case 113: // M113: Set Host Keepalive interval
  8844. gcode_M113();
  8845. break;
  8846. #endif
  8847. case 140: // M140: Set bed temperature
  8848. gcode_M140();
  8849. break;
  8850. case 105: // M105: Report current temperature
  8851. gcode_M105();
  8852. KEEPALIVE_STATE(NOT_BUSY);
  8853. return; // "ok" already printed
  8854. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8855. case 155: // M155: Set temperature auto-report interval
  8856. gcode_M155();
  8857. break;
  8858. #endif
  8859. case 109: // M109: Wait for hotend temperature to reach target
  8860. gcode_M109();
  8861. break;
  8862. #if HAS_TEMP_BED
  8863. case 190: // M190: Wait for bed temperature to reach target
  8864. gcode_M190();
  8865. break;
  8866. #endif // HAS_TEMP_BED
  8867. #if FAN_COUNT > 0
  8868. case 106: // M106: Fan On
  8869. gcode_M106();
  8870. break;
  8871. case 107: // M107: Fan Off
  8872. gcode_M107();
  8873. break;
  8874. #endif // FAN_COUNT > 0
  8875. #if ENABLED(PARK_HEAD_ON_PAUSE)
  8876. case 125: // M125: Store current position and move to filament change position
  8877. gcode_M125(); break;
  8878. #endif
  8879. #if ENABLED(BARICUDA)
  8880. // PWM for HEATER_1_PIN
  8881. #if HAS_HEATER_1
  8882. case 126: // M126: valve open
  8883. gcode_M126();
  8884. break;
  8885. case 127: // M127: valve closed
  8886. gcode_M127();
  8887. break;
  8888. #endif // HAS_HEATER_1
  8889. // PWM for HEATER_2_PIN
  8890. #if HAS_HEATER_2
  8891. case 128: // M128: valve open
  8892. gcode_M128();
  8893. break;
  8894. case 129: // M129: valve closed
  8895. gcode_M129();
  8896. break;
  8897. #endif // HAS_HEATER_2
  8898. #endif // BARICUDA
  8899. #if HAS_POWER_SWITCH
  8900. case 80: // M80: Turn on Power Supply
  8901. gcode_M80();
  8902. break;
  8903. #endif // HAS_POWER_SWITCH
  8904. case 81: // M81: Turn off Power, including Power Supply, if possible
  8905. gcode_M81();
  8906. break;
  8907. case 82: // M82: Set E axis normal mode (same as other axes)
  8908. gcode_M82();
  8909. break;
  8910. case 83: // M83: Set E axis relative mode
  8911. gcode_M83();
  8912. break;
  8913. case 18: // M18 => M84
  8914. case 84: // M84: Disable all steppers or set timeout
  8915. gcode_M18_M84();
  8916. break;
  8917. case 85: // M85: Set inactivity stepper shutdown timeout
  8918. gcode_M85();
  8919. break;
  8920. case 92: // M92: Set the steps-per-unit for one or more axes
  8921. gcode_M92();
  8922. break;
  8923. case 114: // M114: Report current position
  8924. gcode_M114();
  8925. break;
  8926. case 115: // M115: Report capabilities
  8927. gcode_M115();
  8928. break;
  8929. case 117: // M117: Set LCD message text, if possible
  8930. gcode_M117();
  8931. break;
  8932. case 119: // M119: Report endstop states
  8933. gcode_M119();
  8934. break;
  8935. case 120: // M120: Enable endstops
  8936. gcode_M120();
  8937. break;
  8938. case 121: // M121: Disable endstops
  8939. gcode_M121();
  8940. break;
  8941. #if ENABLED(ULTIPANEL)
  8942. case 145: // M145: Set material heatup parameters
  8943. gcode_M145();
  8944. break;
  8945. #endif
  8946. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  8947. case 149: // M149: Set temperature units
  8948. gcode_M149();
  8949. break;
  8950. #endif
  8951. #if HAS_COLOR_LEDS
  8952. case 150: // M150: Set Status LED Color
  8953. gcode_M150();
  8954. break;
  8955. #endif // BLINKM
  8956. #if ENABLED(MIXING_EXTRUDER)
  8957. case 163: // M163: Set a component weight for mixing extruder
  8958. gcode_M163();
  8959. break;
  8960. #if MIXING_VIRTUAL_TOOLS > 1
  8961. case 164: // M164: Save current mix as a virtual extruder
  8962. gcode_M164();
  8963. break;
  8964. #endif
  8965. #if ENABLED(DIRECT_MIXING_IN_G1)
  8966. case 165: // M165: Set multiple mix weights
  8967. gcode_M165();
  8968. break;
  8969. #endif
  8970. #endif
  8971. case 200: // M200: Set filament diameter, E to cubic units
  8972. gcode_M200();
  8973. break;
  8974. case 201: // M201: Set max acceleration for print moves (units/s^2)
  8975. gcode_M201();
  8976. break;
  8977. #if 0 // Not used for Sprinter/grbl gen6
  8978. case 202: // M202
  8979. gcode_M202();
  8980. break;
  8981. #endif
  8982. case 203: // M203: Set max feedrate (units/sec)
  8983. gcode_M203();
  8984. break;
  8985. case 204: // M204: Set acceleration
  8986. gcode_M204();
  8987. break;
  8988. case 205: //M205: Set advanced settings
  8989. gcode_M205();
  8990. break;
  8991. #if HAS_M206_COMMAND
  8992. case 206: // M206: Set home offsets
  8993. gcode_M206();
  8994. break;
  8995. #endif
  8996. #if ENABLED(DELTA)
  8997. case 665: // M665: Set delta configurations
  8998. gcode_M665();
  8999. break;
  9000. #endif
  9001. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  9002. case 666: // M666: Set delta or dual endstop adjustment
  9003. gcode_M666();
  9004. break;
  9005. #endif
  9006. #if ENABLED(FWRETRACT)
  9007. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  9008. gcode_M207();
  9009. break;
  9010. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  9011. gcode_M208();
  9012. break;
  9013. case 209: // M209: Turn Automatic Retract Detection on/off
  9014. gcode_M209();
  9015. break;
  9016. #endif // FWRETRACT
  9017. case 211: // M211: Enable, Disable, and/or Report software endstops
  9018. gcode_M211();
  9019. break;
  9020. #if HOTENDS > 1
  9021. case 218: // M218: Set a tool offset
  9022. gcode_M218();
  9023. break;
  9024. #endif
  9025. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  9026. gcode_M220();
  9027. break;
  9028. case 221: // M221: Set Flow Percentage
  9029. gcode_M221();
  9030. break;
  9031. case 226: // M226: Wait until a pin reaches a state
  9032. gcode_M226();
  9033. break;
  9034. #if HAS_SERVOS
  9035. case 280: // M280: Set servo position absolute
  9036. gcode_M280();
  9037. break;
  9038. #endif // HAS_SERVOS
  9039. #if HAS_BUZZER
  9040. case 300: // M300: Play beep tone
  9041. gcode_M300();
  9042. break;
  9043. #endif // HAS_BUZZER
  9044. #if ENABLED(PIDTEMP)
  9045. case 301: // M301: Set hotend PID parameters
  9046. gcode_M301();
  9047. break;
  9048. #endif // PIDTEMP
  9049. #if ENABLED(PIDTEMPBED)
  9050. case 304: // M304: Set bed PID parameters
  9051. gcode_M304();
  9052. break;
  9053. #endif // PIDTEMPBED
  9054. #if defined(CHDK) || HAS_PHOTOGRAPH
  9055. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  9056. gcode_M240();
  9057. break;
  9058. #endif // CHDK || PHOTOGRAPH_PIN
  9059. #if HAS_LCD_CONTRAST
  9060. case 250: // M250: Set LCD contrast
  9061. gcode_M250();
  9062. break;
  9063. #endif // HAS_LCD_CONTRAST
  9064. #if ENABLED(EXPERIMENTAL_I2CBUS)
  9065. case 260: // M260: Send data to an i2c slave
  9066. gcode_M260();
  9067. break;
  9068. case 261: // M261: Request data from an i2c slave
  9069. gcode_M261();
  9070. break;
  9071. #endif // EXPERIMENTAL_I2CBUS
  9072. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9073. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  9074. gcode_M302();
  9075. break;
  9076. #endif // PREVENT_COLD_EXTRUSION
  9077. case 303: // M303: PID autotune
  9078. gcode_M303();
  9079. break;
  9080. #if ENABLED(MORGAN_SCARA)
  9081. case 360: // M360: SCARA Theta pos1
  9082. if (gcode_M360()) return;
  9083. break;
  9084. case 361: // M361: SCARA Theta pos2
  9085. if (gcode_M361()) return;
  9086. break;
  9087. case 362: // M362: SCARA Psi pos1
  9088. if (gcode_M362()) return;
  9089. break;
  9090. case 363: // M363: SCARA Psi pos2
  9091. if (gcode_M363()) return;
  9092. break;
  9093. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  9094. if (gcode_M364()) return;
  9095. break;
  9096. #endif // SCARA
  9097. case 400: // M400: Finish all moves
  9098. gcode_M400();
  9099. break;
  9100. #if HAS_BED_PROBE
  9101. case 401: // M401: Deploy probe
  9102. gcode_M401();
  9103. break;
  9104. case 402: // M402: Stow probe
  9105. gcode_M402();
  9106. break;
  9107. #endif // HAS_BED_PROBE
  9108. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  9109. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  9110. gcode_M404();
  9111. break;
  9112. case 405: // M405: Turn on filament sensor for control
  9113. gcode_M405();
  9114. break;
  9115. case 406: // M406: Turn off filament sensor for control
  9116. gcode_M406();
  9117. break;
  9118. case 407: // M407: Display measured filament diameter
  9119. gcode_M407();
  9120. break;
  9121. #endif // FILAMENT_WIDTH_SENSOR
  9122. #if HAS_LEVELING
  9123. case 420: // M420: Enable/Disable Bed Leveling
  9124. gcode_M420();
  9125. break;
  9126. #endif
  9127. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9128. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  9129. gcode_M421();
  9130. break;
  9131. #endif
  9132. #if HAS_M206_COMMAND
  9133. case 428: // M428: Apply current_position to home_offset
  9134. gcode_M428();
  9135. break;
  9136. #endif
  9137. case 500: // M500: Store settings in EEPROM
  9138. gcode_M500();
  9139. break;
  9140. case 501: // M501: Read settings from EEPROM
  9141. gcode_M501();
  9142. break;
  9143. case 502: // M502: Revert to default settings
  9144. gcode_M502();
  9145. break;
  9146. case 503: // M503: print settings currently in memory
  9147. gcode_M503();
  9148. break;
  9149. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9150. case 540: // M540: Set abort on endstop hit for SD printing
  9151. gcode_M540();
  9152. break;
  9153. #endif
  9154. #if HAS_BED_PROBE
  9155. case 851: // M851: Set Z Probe Z Offset
  9156. gcode_M851();
  9157. break;
  9158. #endif // HAS_BED_PROBE
  9159. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9160. case 600: // M600: Pause for filament change
  9161. gcode_M600();
  9162. break;
  9163. #endif // ADVANCED_PAUSE_FEATURE
  9164. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9165. case 605: // M605: Set Dual X Carriage movement mode
  9166. gcode_M605();
  9167. break;
  9168. #endif // DUAL_X_CARRIAGE
  9169. #if ENABLED(LIN_ADVANCE)
  9170. case 900: // M900: Set advance K factor.
  9171. gcode_M900();
  9172. break;
  9173. #endif
  9174. #if ENABLED(HAVE_TMC2130)
  9175. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9176. gcode_M906();
  9177. break;
  9178. #endif
  9179. case 907: // M907: Set digital trimpot motor current using axis codes.
  9180. gcode_M907();
  9181. break;
  9182. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  9183. case 908: // M908: Control digital trimpot directly.
  9184. gcode_M908();
  9185. break;
  9186. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  9187. case 909: // M909: Print digipot/DAC current value
  9188. gcode_M909();
  9189. break;
  9190. case 910: // M910: Commit digipot/DAC value to external EEPROM
  9191. gcode_M910();
  9192. break;
  9193. #endif
  9194. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  9195. #if ENABLED(HAVE_TMC2130)
  9196. case 911: // M911: Report TMC2130 prewarn triggered flags
  9197. gcode_M911();
  9198. break;
  9199. case 912: // M911: Clear TMC2130 prewarn triggered flags
  9200. gcode_M912();
  9201. break;
  9202. #if ENABLED(HYBRID_THRESHOLD)
  9203. case 913: // M913: Set HYBRID_THRESHOLD speed.
  9204. gcode_M913();
  9205. break;
  9206. #endif
  9207. #if ENABLED(SENSORLESS_HOMING)
  9208. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  9209. gcode_M914();
  9210. break;
  9211. #endif
  9212. #endif
  9213. #if HAS_MICROSTEPS
  9214. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9215. gcode_M350();
  9216. break;
  9217. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9218. gcode_M351();
  9219. break;
  9220. #endif // HAS_MICROSTEPS
  9221. case 355: // M355 set case light brightness
  9222. gcode_M355();
  9223. break;
  9224. #if ENABLED(DEBUG_GCODE_PARSER)
  9225. case 800:
  9226. parser.debug(); // GCode Parser Test for M
  9227. break;
  9228. #endif
  9229. #if ENABLED(I2C_POSITION_ENCODERS)
  9230. case 860: // M860 Report encoder module position
  9231. gcode_M860();
  9232. break;
  9233. case 861: // M861 Report encoder module status
  9234. gcode_M861();
  9235. break;
  9236. case 862: // M862 Perform axis test
  9237. gcode_M862();
  9238. break;
  9239. case 863: // M863 Calibrate steps/mm
  9240. gcode_M863();
  9241. break;
  9242. case 864: // M864 Change module address
  9243. gcode_M864();
  9244. break;
  9245. case 865: // M865 Check module firmware version
  9246. gcode_M865();
  9247. break;
  9248. case 866: // M866 Report axis error count
  9249. gcode_M866();
  9250. break;
  9251. case 867: // M867 Toggle error correction
  9252. gcode_M867();
  9253. break;
  9254. case 868: // M868 Set error correction threshold
  9255. gcode_M868();
  9256. break;
  9257. case 869: // M869 Report axis error
  9258. gcode_M869();
  9259. break;
  9260. #endif // I2C_POSITION_ENCODERS
  9261. case 999: // M999: Restart after being Stopped
  9262. gcode_M999();
  9263. break;
  9264. }
  9265. break;
  9266. case 'T':
  9267. gcode_T(parser.codenum);
  9268. break;
  9269. default: parser.unknown_command_error();
  9270. }
  9271. KEEPALIVE_STATE(NOT_BUSY);
  9272. ok_to_send();
  9273. }
  9274. /**
  9275. * Send a "Resend: nnn" message to the host to
  9276. * indicate that a command needs to be re-sent.
  9277. */
  9278. void FlushSerialRequestResend() {
  9279. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9280. MYSERIAL.flush();
  9281. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9282. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9283. ok_to_send();
  9284. }
  9285. /**
  9286. * Send an "ok" message to the host, indicating
  9287. * that a command was successfully processed.
  9288. *
  9289. * If ADVANCED_OK is enabled also include:
  9290. * N<int> Line number of the command, if any
  9291. * P<int> Planner space remaining
  9292. * B<int> Block queue space remaining
  9293. */
  9294. void ok_to_send() {
  9295. refresh_cmd_timeout();
  9296. if (!send_ok[cmd_queue_index_r]) return;
  9297. SERIAL_PROTOCOLPGM(MSG_OK);
  9298. #if ENABLED(ADVANCED_OK)
  9299. char* p = command_queue[cmd_queue_index_r];
  9300. if (*p == 'N') {
  9301. SERIAL_PROTOCOL(' ');
  9302. SERIAL_ECHO(*p++);
  9303. while (NUMERIC_SIGNED(*p))
  9304. SERIAL_ECHO(*p++);
  9305. }
  9306. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9307. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9308. #endif
  9309. SERIAL_EOL();
  9310. }
  9311. #if HAS_SOFTWARE_ENDSTOPS
  9312. /**
  9313. * Constrain the given coordinates to the software endstops.
  9314. */
  9315. // NOTE: This makes no sense for delta beds other than Z-axis.
  9316. // For delta the X/Y would need to be clamped at
  9317. // DELTA_PRINTABLE_RADIUS from center of bed, but delta
  9318. // now enforces is_position_reachable for X/Y regardless
  9319. // of HAS_SOFTWARE_ENDSTOPS, so that enforcement would be
  9320. // redundant here. Probably should #ifdef out the X/Y
  9321. // axis clamps here for delta and just leave the Z clamp.
  9322. void clamp_to_software_endstops(float target[XYZ]) {
  9323. if (!soft_endstops_enabled) return;
  9324. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9325. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9326. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9327. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9328. #endif
  9329. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9330. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9331. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9332. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9333. #endif
  9334. }
  9335. #endif
  9336. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9337. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9338. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9339. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9340. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9341. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9342. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9343. #else
  9344. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9345. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9346. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9347. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9348. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9349. #endif
  9350. // Get the Z adjustment for non-linear bed leveling
  9351. float bilinear_z_offset(const float logical[XYZ]) {
  9352. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9353. last_x = -999.999, last_y = -999.999;
  9354. // Whole units for the grid line indices. Constrained within bounds.
  9355. static int8_t gridx, gridy, nextx, nexty,
  9356. last_gridx = -99, last_gridy = -99;
  9357. // XY relative to the probed area
  9358. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9359. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9360. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9361. // Keep using the last grid box
  9362. #define FAR_EDGE_OR_BOX 2
  9363. #else
  9364. // Just use the grid far edge
  9365. #define FAR_EDGE_OR_BOX 1
  9366. #endif
  9367. if (last_x != x) {
  9368. last_x = x;
  9369. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9370. const float gx = constrain(floor(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9371. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9372. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9373. // Beyond the grid maintain height at grid edges
  9374. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9375. #endif
  9376. gridx = gx;
  9377. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9378. }
  9379. if (last_y != y || last_gridx != gridx) {
  9380. if (last_y != y) {
  9381. last_y = y;
  9382. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9383. const float gy = constrain(floor(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9384. ratio_y -= gy;
  9385. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9386. // Beyond the grid maintain height at grid edges
  9387. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9388. #endif
  9389. gridy = gy;
  9390. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9391. }
  9392. if (last_gridx != gridx || last_gridy != gridy) {
  9393. last_gridx = gridx;
  9394. last_gridy = gridy;
  9395. // Z at the box corners
  9396. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9397. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9398. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9399. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9400. }
  9401. // Bilinear interpolate. Needed since y or gridx has changed.
  9402. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9403. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9404. D = R - L;
  9405. }
  9406. const float offset = L + ratio_x * D; // the offset almost always changes
  9407. /*
  9408. static float last_offset = 0;
  9409. if (fabs(last_offset - offset) > 0.2) {
  9410. SERIAL_ECHOPGM("Sudden Shift at ");
  9411. SERIAL_ECHOPAIR("x=", x);
  9412. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9413. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9414. SERIAL_ECHOPAIR(" y=", y);
  9415. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9416. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9417. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9418. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9419. SERIAL_ECHOPAIR(" z1=", z1);
  9420. SERIAL_ECHOPAIR(" z2=", z2);
  9421. SERIAL_ECHOPAIR(" z3=", z3);
  9422. SERIAL_ECHOLNPAIR(" z4=", z4);
  9423. SERIAL_ECHOPAIR(" L=", L);
  9424. SERIAL_ECHOPAIR(" R=", R);
  9425. SERIAL_ECHOLNPAIR(" offset=", offset);
  9426. }
  9427. last_offset = offset;
  9428. //*/
  9429. return offset;
  9430. }
  9431. #endif // AUTO_BED_LEVELING_BILINEAR
  9432. #if ENABLED(DELTA)
  9433. /**
  9434. * Recalculate factors used for delta kinematics whenever
  9435. * settings have been changed (e.g., by M665).
  9436. */
  9437. void recalc_delta_settings(float radius, float diagonal_rod) {
  9438. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9439. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9440. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9441. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9442. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9443. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9444. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9445. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9446. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9447. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9448. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9449. }
  9450. #if ENABLED(DELTA_FAST_SQRT)
  9451. /**
  9452. * Fast inverse sqrt from Quake III Arena
  9453. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9454. */
  9455. float Q_rsqrt(float number) {
  9456. long i;
  9457. float x2, y;
  9458. const float threehalfs = 1.5f;
  9459. x2 = number * 0.5f;
  9460. y = number;
  9461. i = * ( long * ) &y; // evil floating point bit level hacking
  9462. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9463. y = * ( float * ) &i;
  9464. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9465. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9466. return y;
  9467. }
  9468. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9469. #else
  9470. #define _SQRT(n) sqrt(n)
  9471. #endif
  9472. /**
  9473. * Delta Inverse Kinematics
  9474. *
  9475. * Calculate the tower positions for a given logical
  9476. * position, storing the result in the delta[] array.
  9477. *
  9478. * This is an expensive calculation, requiring 3 square
  9479. * roots per segmented linear move, and strains the limits
  9480. * of a Mega2560 with a Graphical Display.
  9481. *
  9482. * Suggested optimizations include:
  9483. *
  9484. * - Disable the home_offset (M206) and/or position_shift (G92)
  9485. * features to remove up to 12 float additions.
  9486. *
  9487. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9488. * (see above)
  9489. */
  9490. // Macro to obtain the Z position of an individual tower
  9491. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9492. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9493. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9494. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9495. ) \
  9496. )
  9497. #define DELTA_RAW_IK() do { \
  9498. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9499. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9500. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9501. } while(0)
  9502. #define DELTA_LOGICAL_IK() do { \
  9503. const float raw[XYZ] = { \
  9504. RAW_X_POSITION(logical[X_AXIS]), \
  9505. RAW_Y_POSITION(logical[Y_AXIS]), \
  9506. RAW_Z_POSITION(logical[Z_AXIS]) \
  9507. }; \
  9508. DELTA_RAW_IK(); \
  9509. } while(0)
  9510. #define DELTA_DEBUG() do { \
  9511. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9512. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9513. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9514. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9515. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9516. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9517. } while(0)
  9518. void inverse_kinematics(const float logical[XYZ]) {
  9519. DELTA_LOGICAL_IK();
  9520. // DELTA_DEBUG();
  9521. }
  9522. /**
  9523. * Calculate the highest Z position where the
  9524. * effector has the full range of XY motion.
  9525. */
  9526. float delta_safe_distance_from_top() {
  9527. float cartesian[XYZ] = {
  9528. LOGICAL_X_POSITION(0),
  9529. LOGICAL_Y_POSITION(0),
  9530. LOGICAL_Z_POSITION(0)
  9531. };
  9532. inverse_kinematics(cartesian);
  9533. float distance = delta[A_AXIS];
  9534. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9535. inverse_kinematics(cartesian);
  9536. return abs(distance - delta[A_AXIS]);
  9537. }
  9538. /**
  9539. * Delta Forward Kinematics
  9540. *
  9541. * See the Wikipedia article "Trilateration"
  9542. * https://en.wikipedia.org/wiki/Trilateration
  9543. *
  9544. * Establish a new coordinate system in the plane of the
  9545. * three carriage points. This system has its origin at
  9546. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9547. * plane with a Z component of zero.
  9548. * We will define unit vectors in this coordinate system
  9549. * in our original coordinate system. Then when we calculate
  9550. * the Xnew, Ynew and Znew values, we can translate back into
  9551. * the original system by moving along those unit vectors
  9552. * by the corresponding values.
  9553. *
  9554. * Variable names matched to Marlin, c-version, and avoid the
  9555. * use of any vector library.
  9556. *
  9557. * by Andreas Hardtung 2016-06-07
  9558. * based on a Java function from "Delta Robot Kinematics V3"
  9559. * by Steve Graves
  9560. *
  9561. * The result is stored in the cartes[] array.
  9562. */
  9563. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9564. // Create a vector in old coordinates along x axis of new coordinate
  9565. float p12[3] = { delta_tower[B_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[B_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z2 - z1 };
  9566. // Get the Magnitude of vector.
  9567. float d = sqrt( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9568. // Create unit vector by dividing by magnitude.
  9569. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9570. // Get the vector from the origin of the new system to the third point.
  9571. float p13[3] = { delta_tower[C_AXIS][X_AXIS] - delta_tower[A_AXIS][X_AXIS], delta_tower[C_AXIS][Y_AXIS] - delta_tower[A_AXIS][Y_AXIS], z3 - z1 };
  9572. // Use the dot product to find the component of this vector on the X axis.
  9573. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9574. // Create a vector along the x axis that represents the x component of p13.
  9575. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9576. // Subtract the X component from the original vector leaving only Y. We use the
  9577. // variable that will be the unit vector after we scale it.
  9578. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9579. // The magnitude of Y component
  9580. float j = sqrt( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9581. // Convert to a unit vector
  9582. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9583. // The cross product of the unit x and y is the unit z
  9584. // float[] ez = vectorCrossProd(ex, ey);
  9585. float ez[3] = {
  9586. ex[1] * ey[2] - ex[2] * ey[1],
  9587. ex[2] * ey[0] - ex[0] * ey[2],
  9588. ex[0] * ey[1] - ex[1] * ey[0]
  9589. };
  9590. // We now have the d, i and j values defined in Wikipedia.
  9591. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9592. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9593. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9594. Znew = sqrt(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9595. // Start from the origin of the old coordinates and add vectors in the
  9596. // old coords that represent the Xnew, Ynew and Znew to find the point
  9597. // in the old system.
  9598. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9599. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9600. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9601. }
  9602. void forward_kinematics_DELTA(float point[ABC]) {
  9603. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9604. }
  9605. #endif // DELTA
  9606. /**
  9607. * Get the stepper positions in the cartes[] array.
  9608. * Forward kinematics are applied for DELTA and SCARA.
  9609. *
  9610. * The result is in the current coordinate space with
  9611. * leveling applied. The coordinates need to be run through
  9612. * unapply_leveling to obtain the "ideal" coordinates
  9613. * suitable for current_position, etc.
  9614. */
  9615. void get_cartesian_from_steppers() {
  9616. #if ENABLED(DELTA)
  9617. forward_kinematics_DELTA(
  9618. stepper.get_axis_position_mm(A_AXIS),
  9619. stepper.get_axis_position_mm(B_AXIS),
  9620. stepper.get_axis_position_mm(C_AXIS)
  9621. );
  9622. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9623. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9624. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9625. #elif IS_SCARA
  9626. forward_kinematics_SCARA(
  9627. stepper.get_axis_position_degrees(A_AXIS),
  9628. stepper.get_axis_position_degrees(B_AXIS)
  9629. );
  9630. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9631. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9632. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9633. #else
  9634. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9635. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9636. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9637. #endif
  9638. }
  9639. /**
  9640. * Set the current_position for an axis based on
  9641. * the stepper positions, removing any leveling that
  9642. * may have been applied.
  9643. */
  9644. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9645. get_cartesian_from_steppers();
  9646. #if PLANNER_LEVELING
  9647. planner.unapply_leveling(cartes);
  9648. #endif
  9649. if (axis == ALL_AXES)
  9650. COPY(current_position, cartes);
  9651. else
  9652. current_position[axis] = cartes[axis];
  9653. }
  9654. #if ENABLED(MESH_BED_LEVELING)
  9655. /**
  9656. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9657. * splitting the move where it crosses mesh borders.
  9658. */
  9659. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9660. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9661. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9662. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9663. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9664. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9665. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9666. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9667. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9668. if (cx1 == cx2 && cy1 == cy2) {
  9669. // Start and end on same mesh square
  9670. line_to_destination(fr_mm_s);
  9671. set_current_to_destination();
  9672. return;
  9673. }
  9674. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9675. float normalized_dist, end[XYZE];
  9676. // Split at the left/front border of the right/top square
  9677. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9678. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9679. COPY(end, destination);
  9680. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9681. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9682. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9683. CBI(x_splits, gcx);
  9684. }
  9685. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9686. COPY(end, destination);
  9687. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9688. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9689. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9690. CBI(y_splits, gcy);
  9691. }
  9692. else {
  9693. // Already split on a border
  9694. line_to_destination(fr_mm_s);
  9695. set_current_to_destination();
  9696. return;
  9697. }
  9698. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9699. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9700. // Do the split and look for more borders
  9701. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9702. // Restore destination from stack
  9703. COPY(destination, end);
  9704. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9705. }
  9706. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9707. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9708. /**
  9709. * Prepare a bilinear-leveled linear move on Cartesian,
  9710. * splitting the move where it crosses grid borders.
  9711. */
  9712. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9713. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9714. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9715. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9716. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9717. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9718. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9719. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9720. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9721. if (cx1 == cx2 && cy1 == cy2) {
  9722. // Start and end on same mesh square
  9723. line_to_destination(fr_mm_s);
  9724. set_current_to_destination();
  9725. return;
  9726. }
  9727. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9728. float normalized_dist, end[XYZE];
  9729. // Split at the left/front border of the right/top square
  9730. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9731. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9732. COPY(end, destination);
  9733. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9734. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9735. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9736. CBI(x_splits, gcx);
  9737. }
  9738. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9739. COPY(end, destination);
  9740. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9741. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9742. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9743. CBI(y_splits, gcy);
  9744. }
  9745. else {
  9746. // Already split on a border
  9747. line_to_destination(fr_mm_s);
  9748. set_current_to_destination();
  9749. return;
  9750. }
  9751. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9752. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9753. // Do the split and look for more borders
  9754. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9755. // Restore destination from stack
  9756. COPY(destination, end);
  9757. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9758. }
  9759. #endif // AUTO_BED_LEVELING_BILINEAR
  9760. #if IS_KINEMATIC && !UBL_DELTA
  9761. /**
  9762. * Prepare a linear move in a DELTA or SCARA setup.
  9763. *
  9764. * This calls planner.buffer_line several times, adding
  9765. * small incremental moves for DELTA or SCARA.
  9766. */
  9767. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9768. // Get the top feedrate of the move in the XY plane
  9769. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9770. // If the move is only in Z/E don't split up the move
  9771. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9772. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9773. return false;
  9774. }
  9775. // Fail if attempting move outside printable radius
  9776. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9777. // Get the cartesian distances moved in XYZE
  9778. const float difference[XYZE] = {
  9779. ltarget[X_AXIS] - current_position[X_AXIS],
  9780. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9781. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9782. ltarget[E_AXIS] - current_position[E_AXIS]
  9783. };
  9784. // Get the linear distance in XYZ
  9785. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9786. // If the move is very short, check the E move distance
  9787. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = abs(difference[E_AXIS]);
  9788. // No E move either? Game over.
  9789. if (UNEAR_ZERO(cartesian_mm)) return true;
  9790. // Minimum number of seconds to move the given distance
  9791. const float seconds = cartesian_mm / _feedrate_mm_s;
  9792. // The number of segments-per-second times the duration
  9793. // gives the number of segments
  9794. uint16_t segments = delta_segments_per_second * seconds;
  9795. // For SCARA minimum segment size is 0.25mm
  9796. #if IS_SCARA
  9797. NOMORE(segments, cartesian_mm * 4);
  9798. #endif
  9799. // At least one segment is required
  9800. NOLESS(segments, 1);
  9801. // The approximate length of each segment
  9802. const float inv_segments = 1.0 / float(segments),
  9803. segment_distance[XYZE] = {
  9804. difference[X_AXIS] * inv_segments,
  9805. difference[Y_AXIS] * inv_segments,
  9806. difference[Z_AXIS] * inv_segments,
  9807. difference[E_AXIS] * inv_segments
  9808. };
  9809. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9810. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9811. // SERIAL_ECHOLNPAIR(" segments=", segments);
  9812. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9813. // SCARA needs to scale the feed rate from mm/s to degrees/s
  9814. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  9815. feed_factor = inv_segment_length * _feedrate_mm_s;
  9816. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  9817. oldB = stepper.get_axis_position_degrees(B_AXIS);
  9818. #endif
  9819. // Get the logical current position as starting point
  9820. float logical[XYZE];
  9821. COPY(logical, current_position);
  9822. // Drop one segment so the last move is to the exact target.
  9823. // If there's only 1 segment, loops will be skipped entirely.
  9824. --segments;
  9825. // Calculate and execute the segments
  9826. for (uint16_t s = segments + 1; --s;) {
  9827. LOOP_XYZE(i) logical[i] += segment_distance[i];
  9828. #if ENABLED(DELTA)
  9829. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  9830. #else
  9831. inverse_kinematics(logical);
  9832. #endif
  9833. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  9834. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9835. // For SCARA scale the feed rate from mm/s to degrees/s
  9836. // Use ratio between the length of the move and the larger angle change
  9837. const float adiff = abs(delta[A_AXIS] - oldA),
  9838. bdiff = abs(delta[B_AXIS] - oldB);
  9839. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9840. oldA = delta[A_AXIS];
  9841. oldB = delta[B_AXIS];
  9842. #else
  9843. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  9844. #endif
  9845. }
  9846. // Since segment_distance is only approximate,
  9847. // the final move must be to the exact destination.
  9848. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9849. // For SCARA scale the feed rate from mm/s to degrees/s
  9850. // With segments > 1 length is 1 segment, otherwise total length
  9851. inverse_kinematics(ltarget);
  9852. ADJUST_DELTA(ltarget);
  9853. const float adiff = abs(delta[A_AXIS] - oldA),
  9854. bdiff = abs(delta[B_AXIS] - oldB);
  9855. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9856. #else
  9857. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9858. #endif
  9859. return false;
  9860. }
  9861. #else // !IS_KINEMATIC || UBL_DELTA
  9862. /**
  9863. * Prepare a linear move in a Cartesian setup.
  9864. * If Mesh Bed Leveling is enabled, perform a mesh move.
  9865. *
  9866. * Returns true if the caller didn't update current_position.
  9867. */
  9868. inline bool prepare_move_to_destination_cartesian() {
  9869. #if ENABLED(AUTO_BED_LEVELING_UBL)
  9870. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9871. if (ubl.state.active) { // direct use of ubl.state.active for speed
  9872. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  9873. return true;
  9874. }
  9875. else
  9876. line_to_destination(fr_scaled);
  9877. #else
  9878. // Do not use feedrate_percentage for E or Z only moves
  9879. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  9880. line_to_destination();
  9881. else {
  9882. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  9883. #if ENABLED(MESH_BED_LEVELING)
  9884. if (mbl.active()) { // direct used of mbl.active() for speed
  9885. mesh_line_to_destination(fr_scaled);
  9886. return true;
  9887. }
  9888. else
  9889. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9890. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  9891. bilinear_line_to_destination(fr_scaled);
  9892. return true;
  9893. }
  9894. else
  9895. #endif
  9896. line_to_destination(fr_scaled);
  9897. }
  9898. #endif
  9899. return false;
  9900. }
  9901. #endif // !IS_KINEMATIC || UBL_DELTA
  9902. #if ENABLED(DUAL_X_CARRIAGE)
  9903. /**
  9904. * Prepare a linear move in a dual X axis setup
  9905. */
  9906. inline bool prepare_move_to_destination_dualx() {
  9907. if (active_extruder_parked) {
  9908. switch (dual_x_carriage_mode) {
  9909. case DXC_FULL_CONTROL_MODE:
  9910. break;
  9911. case DXC_AUTO_PARK_MODE:
  9912. if (current_position[E_AXIS] == destination[E_AXIS]) {
  9913. // This is a travel move (with no extrusion)
  9914. // Skip it, but keep track of the current position
  9915. // (so it can be used as the start of the next non-travel move)
  9916. if (delayed_move_time != 0xFFFFFFFFUL) {
  9917. set_current_to_destination();
  9918. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  9919. delayed_move_time = millis();
  9920. return true;
  9921. }
  9922. }
  9923. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  9924. for (uint8_t i = 0; i < 3; i++)
  9925. planner.buffer_line(
  9926. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  9927. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  9928. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  9929. current_position[E_AXIS],
  9930. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  9931. active_extruder
  9932. );
  9933. delayed_move_time = 0;
  9934. active_extruder_parked = false;
  9935. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9936. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  9937. #endif
  9938. break;
  9939. case DXC_DUPLICATION_MODE:
  9940. if (active_extruder == 0) {
  9941. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9942. if (DEBUGGING(LEVELING)) {
  9943. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  9944. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  9945. }
  9946. #endif
  9947. // move duplicate extruder into correct duplication position.
  9948. planner.set_position_mm(
  9949. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  9950. current_position[Y_AXIS],
  9951. current_position[Z_AXIS],
  9952. current_position[E_AXIS]
  9953. );
  9954. planner.buffer_line(
  9955. current_position[X_AXIS] + duplicate_extruder_x_offset,
  9956. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  9957. planner.max_feedrate_mm_s[X_AXIS], 1
  9958. );
  9959. SYNC_PLAN_POSITION_KINEMATIC();
  9960. stepper.synchronize();
  9961. extruder_duplication_enabled = true;
  9962. active_extruder_parked = false;
  9963. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9964. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  9965. #endif
  9966. }
  9967. else {
  9968. #if ENABLED(DEBUG_LEVELING_FEATURE)
  9969. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  9970. #endif
  9971. }
  9972. break;
  9973. }
  9974. }
  9975. return false;
  9976. }
  9977. #endif // DUAL_X_CARRIAGE
  9978. /**
  9979. * Prepare a single move and get ready for the next one
  9980. *
  9981. * This may result in several calls to planner.buffer_line to
  9982. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  9983. */
  9984. void prepare_move_to_destination() {
  9985. clamp_to_software_endstops(destination);
  9986. refresh_cmd_timeout();
  9987. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9988. if (!DEBUGGING(DRYRUN)) {
  9989. if (destination[E_AXIS] != current_position[E_AXIS]) {
  9990. if (thermalManager.tooColdToExtrude(active_extruder)) {
  9991. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9992. SERIAL_ECHO_START();
  9993. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  9994. }
  9995. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  9996. if (labs(destination[E_AXIS] - current_position[E_AXIS]) > EXTRUDE_MAXLENGTH) {
  9997. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  9998. SERIAL_ECHO_START();
  9999. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  10000. }
  10001. #endif
  10002. }
  10003. }
  10004. #endif
  10005. if (
  10006. #if IS_KINEMATIC
  10007. #if UBL_DELTA
  10008. ubl.prepare_segmented_line_to(destination, feedrate_mm_s)
  10009. #else
  10010. prepare_kinematic_move_to(destination)
  10011. #endif
  10012. #elif ENABLED(DUAL_X_CARRIAGE)
  10013. prepare_move_to_destination_dualx()
  10014. #elif UBL_DELTA // will work for CARTESIAN too (smaller segments follow mesh more closely)
  10015. ubl.prepare_segmented_line_to(destination, feedrate_mm_s)
  10016. #else
  10017. prepare_move_to_destination_cartesian()
  10018. #endif
  10019. ) return;
  10020. set_current_to_destination();
  10021. }
  10022. #if ENABLED(ARC_SUPPORT)
  10023. /**
  10024. * Plan an arc in 2 dimensions
  10025. *
  10026. * The arc is approximated by generating many small linear segments.
  10027. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  10028. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  10029. * larger segments will tend to be more efficient. Your slicer should have
  10030. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  10031. */
  10032. void plan_arc(
  10033. float logical[XYZE], // Destination position
  10034. float *offset, // Center of rotation relative to current_position
  10035. uint8_t clockwise // Clockwise?
  10036. ) {
  10037. float r_X = -offset[X_AXIS], // Radius vector from center to current location
  10038. r_Y = -offset[Y_AXIS];
  10039. const float radius = HYPOT(r_X, r_Y),
  10040. center_X = current_position[X_AXIS] - r_X,
  10041. center_Y = current_position[Y_AXIS] - r_Y,
  10042. rt_X = logical[X_AXIS] - center_X,
  10043. rt_Y = logical[Y_AXIS] - center_Y,
  10044. linear_travel = logical[Z_AXIS] - current_position[Z_AXIS],
  10045. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  10046. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  10047. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  10048. if (angular_travel < 0) angular_travel += RADIANS(360);
  10049. if (clockwise) angular_travel -= RADIANS(360);
  10050. // Make a circle if the angular rotation is 0
  10051. if (angular_travel == 0 && current_position[X_AXIS] == logical[X_AXIS] && current_position[Y_AXIS] == logical[Y_AXIS])
  10052. angular_travel += RADIANS(360);
  10053. const float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel));
  10054. if (mm_of_travel < 0.001) return;
  10055. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  10056. if (segments == 0) segments = 1;
  10057. /**
  10058. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  10059. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  10060. * r_T = [cos(phi) -sin(phi);
  10061. * sin(phi) cos(phi)] * r ;
  10062. *
  10063. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  10064. * defined from the circle center to the initial position. Each line segment is formed by successive
  10065. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  10066. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  10067. * all double numbers are single precision on the Arduino. (True double precision will not have
  10068. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  10069. * tool precision in some cases. Therefore, arc path correction is implemented.
  10070. *
  10071. * Small angle approximation may be used to reduce computation overhead further. This approximation
  10072. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  10073. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  10074. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  10075. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  10076. * issue for CNC machines with the single precision Arduino calculations.
  10077. *
  10078. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  10079. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  10080. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  10081. * This is important when there are successive arc motions.
  10082. */
  10083. // Vector rotation matrix values
  10084. float arc_target[XYZE];
  10085. const float theta_per_segment = angular_travel / segments,
  10086. linear_per_segment = linear_travel / segments,
  10087. extruder_per_segment = extruder_travel / segments,
  10088. sin_T = theta_per_segment,
  10089. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  10090. // Initialize the linear axis
  10091. arc_target[Z_AXIS] = current_position[Z_AXIS];
  10092. // Initialize the extruder axis
  10093. arc_target[E_AXIS] = current_position[E_AXIS];
  10094. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  10095. millis_t next_idle_ms = millis() + 200UL;
  10096. int8_t count = 0;
  10097. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  10098. thermalManager.manage_heater();
  10099. if (ELAPSED(millis(), next_idle_ms)) {
  10100. next_idle_ms = millis() + 200UL;
  10101. idle();
  10102. }
  10103. if (++count < N_ARC_CORRECTION) {
  10104. // Apply vector rotation matrix to previous r_X / 1
  10105. const float r_new_Y = r_X * sin_T + r_Y * cos_T;
  10106. r_X = r_X * cos_T - r_Y * sin_T;
  10107. r_Y = r_new_Y;
  10108. }
  10109. else {
  10110. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  10111. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  10112. // To reduce stuttering, the sin and cos could be computed at different times.
  10113. // For now, compute both at the same time.
  10114. const float cos_Ti = cos(i * theta_per_segment),
  10115. sin_Ti = sin(i * theta_per_segment);
  10116. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  10117. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  10118. count = 0;
  10119. }
  10120. // Update arc_target location
  10121. arc_target[X_AXIS] = center_X + r_X;
  10122. arc_target[Y_AXIS] = center_Y + r_Y;
  10123. arc_target[Z_AXIS] += linear_per_segment;
  10124. arc_target[E_AXIS] += extruder_per_segment;
  10125. clamp_to_software_endstops(arc_target);
  10126. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  10127. }
  10128. // Ensure last segment arrives at target location.
  10129. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  10130. // As far as the parser is concerned, the position is now == target. In reality the
  10131. // motion control system might still be processing the action and the real tool position
  10132. // in any intermediate location.
  10133. set_current_to_destination();
  10134. }
  10135. #endif
  10136. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10137. void plan_cubic_move(const float offset[4]) {
  10138. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  10139. // As far as the parser is concerned, the position is now == destination. In reality the
  10140. // motion control system might still be processing the action and the real tool position
  10141. // in any intermediate location.
  10142. set_current_to_destination();
  10143. }
  10144. #endif // BEZIER_CURVE_SUPPORT
  10145. #if ENABLED(USE_CONTROLLER_FAN)
  10146. void controllerFan() {
  10147. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  10148. nextMotorCheck = 0; // Last time the state was checked
  10149. const millis_t ms = millis();
  10150. if (ELAPSED(ms, nextMotorCheck)) {
  10151. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  10152. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_amount_bed > 0
  10153. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  10154. #if E_STEPPERS > 1
  10155. || E1_ENABLE_READ == E_ENABLE_ON
  10156. #if HAS_X2_ENABLE
  10157. || X2_ENABLE_READ == X_ENABLE_ON
  10158. #endif
  10159. #if E_STEPPERS > 2
  10160. || E2_ENABLE_READ == E_ENABLE_ON
  10161. #if E_STEPPERS > 3
  10162. || E3_ENABLE_READ == E_ENABLE_ON
  10163. #if E_STEPPERS > 4
  10164. || E4_ENABLE_READ == E_ENABLE_ON
  10165. #endif // E_STEPPERS > 4
  10166. #endif // E_STEPPERS > 3
  10167. #endif // E_STEPPERS > 2
  10168. #endif // E_STEPPERS > 1
  10169. ) {
  10170. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  10171. }
  10172. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  10173. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  10174. // allows digital or PWM fan output to be used (see M42 handling)
  10175. WRITE(CONTROLLER_FAN_PIN, speed);
  10176. analogWrite(CONTROLLER_FAN_PIN, speed);
  10177. }
  10178. }
  10179. #endif // USE_CONTROLLER_FAN
  10180. #if ENABLED(MORGAN_SCARA)
  10181. /**
  10182. * Morgan SCARA Forward Kinematics. Results in cartes[].
  10183. * Maths and first version by QHARLEY.
  10184. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10185. */
  10186. void forward_kinematics_SCARA(const float &a, const float &b) {
  10187. float a_sin = sin(RADIANS(a)) * L1,
  10188. a_cos = cos(RADIANS(a)) * L1,
  10189. b_sin = sin(RADIANS(b)) * L2,
  10190. b_cos = cos(RADIANS(b)) * L2;
  10191. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  10192. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  10193. /*
  10194. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  10195. SERIAL_ECHOPAIR(" b=", b);
  10196. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  10197. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  10198. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  10199. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  10200. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  10201. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  10202. //*/
  10203. }
  10204. /**
  10205. * Morgan SCARA Inverse Kinematics. Results in delta[].
  10206. *
  10207. * See http://forums.reprap.org/read.php?185,283327
  10208. *
  10209. * Maths and first version by QHARLEY.
  10210. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10211. */
  10212. void inverse_kinematics(const float logical[XYZ]) {
  10213. static float C2, S2, SK1, SK2, THETA, PSI;
  10214. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  10215. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  10216. if (L1 == L2)
  10217. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  10218. else
  10219. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  10220. S2 = sqrt(1 - sq(C2));
  10221. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  10222. SK1 = L1 + L2 * C2;
  10223. // Rotated Arm2 gives the distance from Arm1 to Arm2
  10224. SK2 = L2 * S2;
  10225. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  10226. THETA = atan2(SK1, SK2) - atan2(sx, sy);
  10227. // Angle of Arm2
  10228. PSI = atan2(S2, C2);
  10229. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  10230. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  10231. delta[C_AXIS] = logical[Z_AXIS];
  10232. /*
  10233. DEBUG_POS("SCARA IK", logical);
  10234. DEBUG_POS("SCARA IK", delta);
  10235. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  10236. SERIAL_ECHOPAIR(",", sy);
  10237. SERIAL_ECHOPAIR(" C2=", C2);
  10238. SERIAL_ECHOPAIR(" S2=", S2);
  10239. SERIAL_ECHOPAIR(" Theta=", THETA);
  10240. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  10241. //*/
  10242. }
  10243. #endif // MORGAN_SCARA
  10244. #if ENABLED(TEMP_STAT_LEDS)
  10245. static bool red_led = false;
  10246. static millis_t next_status_led_update_ms = 0;
  10247. void handle_status_leds(void) {
  10248. if (ELAPSED(millis(), next_status_led_update_ms)) {
  10249. next_status_led_update_ms += 500; // Update every 0.5s
  10250. float max_temp = 0.0;
  10251. #if HAS_TEMP_BED
  10252. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10253. #endif
  10254. HOTEND_LOOP()
  10255. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10256. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10257. if (new_led != red_led) {
  10258. red_led = new_led;
  10259. #if PIN_EXISTS(STAT_LED_RED)
  10260. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10261. #if PIN_EXISTS(STAT_LED_BLUE)
  10262. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10263. #endif
  10264. #else
  10265. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10266. #endif
  10267. }
  10268. }
  10269. }
  10270. #endif
  10271. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10272. void handle_filament_runout() {
  10273. if (!filament_ran_out) {
  10274. filament_ran_out = true;
  10275. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10276. stepper.synchronize();
  10277. }
  10278. }
  10279. #endif // FILAMENT_RUNOUT_SENSOR
  10280. #if ENABLED(FAST_PWM_FAN)
  10281. void setPwmFrequency(uint8_t pin, int val) {
  10282. val &= 0x07;
  10283. switch (digitalPinToTimer(pin)) {
  10284. #ifdef TCCR0A
  10285. #if !AVR_AT90USB1286_FAMILY
  10286. case TIMER0A:
  10287. #endif
  10288. case TIMER0B:
  10289. //_SET_CS(0, val);
  10290. break;
  10291. #endif
  10292. #ifdef TCCR1A
  10293. case TIMER1A:
  10294. case TIMER1B:
  10295. //_SET_CS(1, val);
  10296. break;
  10297. #endif
  10298. #ifdef TCCR2
  10299. case TIMER2:
  10300. case TIMER2:
  10301. _SET_CS(2, val);
  10302. break;
  10303. #endif
  10304. #ifdef TCCR2A
  10305. case TIMER2A:
  10306. case TIMER2B:
  10307. _SET_CS(2, val);
  10308. break;
  10309. #endif
  10310. #ifdef TCCR3A
  10311. case TIMER3A:
  10312. case TIMER3B:
  10313. case TIMER3C:
  10314. _SET_CS(3, val);
  10315. break;
  10316. #endif
  10317. #ifdef TCCR4A
  10318. case TIMER4A:
  10319. case TIMER4B:
  10320. case TIMER4C:
  10321. _SET_CS(4, val);
  10322. break;
  10323. #endif
  10324. #ifdef TCCR5A
  10325. case TIMER5A:
  10326. case TIMER5B:
  10327. case TIMER5C:
  10328. _SET_CS(5, val);
  10329. break;
  10330. #endif
  10331. }
  10332. }
  10333. #endif // FAST_PWM_FAN
  10334. float calculate_volumetric_multiplier(float diameter) {
  10335. if (!volumetric_enabled || diameter == 0) return 1.0;
  10336. return 1.0 / (M_PI * sq(diameter * 0.5));
  10337. }
  10338. void calculate_volumetric_multipliers() {
  10339. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10340. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10341. }
  10342. void enable_all_steppers() {
  10343. enable_X();
  10344. enable_Y();
  10345. enable_Z();
  10346. enable_E0();
  10347. enable_E1();
  10348. enable_E2();
  10349. enable_E3();
  10350. enable_E4();
  10351. }
  10352. void disable_e_steppers() {
  10353. disable_E0();
  10354. disable_E1();
  10355. disable_E2();
  10356. disable_E3();
  10357. disable_E4();
  10358. }
  10359. void disable_all_steppers() {
  10360. disable_X();
  10361. disable_Y();
  10362. disable_Z();
  10363. disable_e_steppers();
  10364. }
  10365. #if ENABLED(HAVE_TMC2130)
  10366. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10367. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10368. const bool is_otpw = st.checkOT();
  10369. // Report if a warning was triggered
  10370. static bool previous_otpw = false;
  10371. if (is_otpw && !previous_otpw) {
  10372. char timestamp[10];
  10373. duration_t elapsed = print_job_timer.duration();
  10374. const bool has_days = (elapsed.value > 60*60*24L);
  10375. (void)elapsed.toDigital(timestamp, has_days);
  10376. SERIAL_ECHO(timestamp);
  10377. SERIAL_ECHOPGM(": ");
  10378. SERIAL_ECHO(axisID);
  10379. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10380. }
  10381. previous_otpw = is_otpw;
  10382. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10383. // Return if user has not enabled current control start with M906 S1.
  10384. if (!auto_current_control) return;
  10385. /**
  10386. * Decrease current if is_otpw is true.
  10387. * Bail out if driver is disabled.
  10388. * Increase current if OTPW has not been triggered yet.
  10389. */
  10390. uint16_t current = st.getCurrent();
  10391. if (is_otpw) {
  10392. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10393. #if ENABLED(REPORT_CURRENT_CHANGE)
  10394. SERIAL_ECHO(axisID);
  10395. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10396. #endif
  10397. }
  10398. else if (!st.isEnabled())
  10399. return;
  10400. else if (!is_otpw && !st.getOTPW()) {
  10401. current += CURRENT_STEP;
  10402. if (current <= AUTO_ADJUST_MAX) {
  10403. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10404. #if ENABLED(REPORT_CURRENT_CHANGE)
  10405. SERIAL_ECHO(axisID);
  10406. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10407. #endif
  10408. }
  10409. }
  10410. SERIAL_EOL();
  10411. #endif
  10412. }
  10413. void checkOverTemp() {
  10414. static millis_t next_cOT = 0;
  10415. if (ELAPSED(millis(), next_cOT)) {
  10416. next_cOT = millis() + 5000;
  10417. #if ENABLED(X_IS_TMC2130)
  10418. automatic_current_control(stepperX, "X");
  10419. #endif
  10420. #if ENABLED(Y_IS_TMC2130)
  10421. automatic_current_control(stepperY, "Y");
  10422. #endif
  10423. #if ENABLED(Z_IS_TMC2130)
  10424. automatic_current_control(stepperZ, "Z");
  10425. #endif
  10426. #if ENABLED(X2_IS_TMC2130)
  10427. automatic_current_control(stepperX2, "X2");
  10428. #endif
  10429. #if ENABLED(Y2_IS_TMC2130)
  10430. automatic_current_control(stepperY2, "Y2");
  10431. #endif
  10432. #if ENABLED(Z2_IS_TMC2130)
  10433. automatic_current_control(stepperZ2, "Z2");
  10434. #endif
  10435. #if ENABLED(E0_IS_TMC2130)
  10436. automatic_current_control(stepperE0, "E0");
  10437. #endif
  10438. #if ENABLED(E1_IS_TMC2130)
  10439. automatic_current_control(stepperE1, "E1");
  10440. #endif
  10441. #if ENABLED(E2_IS_TMC2130)
  10442. automatic_current_control(stepperE2, "E2");
  10443. #endif
  10444. #if ENABLED(E3_IS_TMC2130)
  10445. automatic_current_control(stepperE3, "E3");
  10446. #endif
  10447. #if ENABLED(E4_IS_TMC2130)
  10448. automatic_current_control(stepperE4, "E4");
  10449. #endif
  10450. #if ENABLED(E4_IS_TMC2130)
  10451. automatic_current_control(stepperE4);
  10452. #endif
  10453. }
  10454. }
  10455. #endif // HAVE_TMC2130
  10456. /**
  10457. * Manage several activities:
  10458. * - Check for Filament Runout
  10459. * - Keep the command buffer full
  10460. * - Check for maximum inactive time between commands
  10461. * - Check for maximum inactive time between stepper commands
  10462. * - Check if pin CHDK needs to go LOW
  10463. * - Check for KILL button held down
  10464. * - Check for HOME button held down
  10465. * - Check if cooling fan needs to be switched on
  10466. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10467. */
  10468. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10469. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10470. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10471. handle_filament_runout();
  10472. #endif
  10473. if (commands_in_queue < BUFSIZE) get_available_commands();
  10474. const millis_t ms = millis();
  10475. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10476. SERIAL_ERROR_START();
  10477. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10478. kill(PSTR(MSG_KILLED));
  10479. }
  10480. // Prevent steppers timing-out in the middle of M600
  10481. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10482. #define MOVE_AWAY_TEST !move_away_flag
  10483. #else
  10484. #define MOVE_AWAY_TEST true
  10485. #endif
  10486. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10487. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10488. #if ENABLED(DISABLE_INACTIVE_X)
  10489. disable_X();
  10490. #endif
  10491. #if ENABLED(DISABLE_INACTIVE_Y)
  10492. disable_Y();
  10493. #endif
  10494. #if ENABLED(DISABLE_INACTIVE_Z)
  10495. disable_Z();
  10496. #endif
  10497. #if ENABLED(DISABLE_INACTIVE_E)
  10498. disable_e_steppers();
  10499. #endif
  10500. }
  10501. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10502. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10503. chdkActive = false;
  10504. WRITE(CHDK, LOW);
  10505. }
  10506. #endif
  10507. #if HAS_KILL
  10508. // Check if the kill button was pressed and wait just in case it was an accidental
  10509. // key kill key press
  10510. // -------------------------------------------------------------------------------
  10511. static int killCount = 0; // make the inactivity button a bit less responsive
  10512. const int KILL_DELAY = 750;
  10513. if (!READ(KILL_PIN))
  10514. killCount++;
  10515. else if (killCount > 0)
  10516. killCount--;
  10517. // Exceeded threshold and we can confirm that it was not accidental
  10518. // KILL the machine
  10519. // ----------------------------------------------------------------
  10520. if (killCount >= KILL_DELAY) {
  10521. SERIAL_ERROR_START();
  10522. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10523. kill(PSTR(MSG_KILLED));
  10524. }
  10525. #endif
  10526. #if HAS_HOME
  10527. // Check to see if we have to home, use poor man's debouncer
  10528. // ---------------------------------------------------------
  10529. static int homeDebounceCount = 0; // poor man's debouncing count
  10530. const int HOME_DEBOUNCE_DELAY = 2500;
  10531. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10532. if (!homeDebounceCount) {
  10533. enqueue_and_echo_commands_P(PSTR("G28"));
  10534. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10535. }
  10536. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10537. homeDebounceCount++;
  10538. else
  10539. homeDebounceCount = 0;
  10540. }
  10541. #endif
  10542. #if ENABLED(USE_CONTROLLER_FAN)
  10543. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10544. #endif
  10545. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10546. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10547. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10548. bool oldstatus;
  10549. #if ENABLED(SWITCHING_EXTRUDER)
  10550. oldstatus = E0_ENABLE_READ;
  10551. enable_E0();
  10552. #else // !SWITCHING_EXTRUDER
  10553. switch (active_extruder) {
  10554. case 0: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10555. #if E_STEPPERS > 1
  10556. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10557. #if E_STEPPERS > 2
  10558. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10559. #if E_STEPPERS > 3
  10560. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10561. #if E_STEPPERS > 4
  10562. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10563. #endif // E_STEPPERS > 4
  10564. #endif // E_STEPPERS > 3
  10565. #endif // E_STEPPERS > 2
  10566. #endif // E_STEPPERS > 1
  10567. }
  10568. #endif // !SWITCHING_EXTRUDER
  10569. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10570. const float olde = current_position[E_AXIS];
  10571. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10572. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10573. current_position[E_AXIS] = olde;
  10574. planner.set_e_position_mm(olde);
  10575. stepper.synchronize();
  10576. #if ENABLED(SWITCHING_EXTRUDER)
  10577. E0_ENABLE_WRITE(oldstatus);
  10578. #else
  10579. switch (active_extruder) {
  10580. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10581. #if E_STEPPERS > 1
  10582. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10583. #if E_STEPPERS > 2
  10584. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10585. #if E_STEPPERS > 3
  10586. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10587. #if E_STEPPERS > 4
  10588. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10589. #endif // E_STEPPERS > 4
  10590. #endif // E_STEPPERS > 3
  10591. #endif // E_STEPPERS > 2
  10592. #endif // E_STEPPERS > 1
  10593. }
  10594. #endif // !SWITCHING_EXTRUDER
  10595. }
  10596. #endif // EXTRUDER_RUNOUT_PREVENT
  10597. #if ENABLED(DUAL_X_CARRIAGE)
  10598. // handle delayed move timeout
  10599. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10600. // travel moves have been received so enact them
  10601. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10602. set_destination_to_current();
  10603. prepare_move_to_destination();
  10604. }
  10605. #endif
  10606. #if ENABLED(TEMP_STAT_LEDS)
  10607. handle_status_leds();
  10608. #endif
  10609. #if ENABLED(HAVE_TMC2130)
  10610. checkOverTemp();
  10611. #endif
  10612. planner.check_axes_activity();
  10613. }
  10614. /**
  10615. * Standard idle routine keeps the machine alive
  10616. */
  10617. void idle(
  10618. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10619. bool no_stepper_sleep/*=false*/
  10620. #endif
  10621. ) {
  10622. lcd_update();
  10623. host_keepalive();
  10624. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10625. auto_report_temperatures();
  10626. #endif
  10627. manage_inactivity(
  10628. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10629. no_stepper_sleep
  10630. #endif
  10631. );
  10632. thermalManager.manage_heater();
  10633. #if ENABLED(PRINTCOUNTER)
  10634. print_job_timer.tick();
  10635. #endif
  10636. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10637. buzzer.tick();
  10638. #endif
  10639. #if ENABLED(I2C_POSITION_ENCODERS)
  10640. if (planner.blocks_queued() &&
  10641. ( (blockBufferIndexRef != planner.block_buffer_head) ||
  10642. ((lastUpdateMillis + I2CPE_MIN_UPD_TIME_MS) < millis())) ) {
  10643. blockBufferIndexRef = planner.block_buffer_head;
  10644. I2CPEM.update();
  10645. lastUpdateMillis = millis();
  10646. }
  10647. #endif
  10648. }
  10649. /**
  10650. * Kill all activity and lock the machine.
  10651. * After this the machine will need to be reset.
  10652. */
  10653. void kill(const char* lcd_msg) {
  10654. SERIAL_ERROR_START();
  10655. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10656. thermalManager.disable_all_heaters();
  10657. disable_all_steppers();
  10658. #if ENABLED(ULTRA_LCD)
  10659. kill_screen(lcd_msg);
  10660. #else
  10661. UNUSED(lcd_msg);
  10662. #endif
  10663. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10664. cli(); // Stop interrupts
  10665. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10666. thermalManager.disable_all_heaters(); //turn off heaters again
  10667. #if HAS_POWER_SWITCH
  10668. SET_INPUT(PS_ON_PIN);
  10669. #endif
  10670. suicide();
  10671. while (1) {
  10672. #if ENABLED(USE_WATCHDOG)
  10673. watchdog_reset();
  10674. #endif
  10675. } // Wait for reset
  10676. }
  10677. /**
  10678. * Turn off heaters and stop the print in progress
  10679. * After a stop the machine may be resumed with M999
  10680. */
  10681. void stop() {
  10682. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10683. #if ENABLED(PROBING_FANS_OFF)
  10684. if (fans_paused) fans_pause(false); // put things back the way they were
  10685. #endif
  10686. if (IsRunning()) {
  10687. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10688. SERIAL_ERROR_START();
  10689. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10690. LCD_MESSAGEPGM(MSG_STOPPED);
  10691. safe_delay(350); // allow enough time for messages to get out before stopping
  10692. Running = false;
  10693. }
  10694. }
  10695. /**
  10696. * Marlin entry-point: Set up before the program loop
  10697. * - Set up the kill pin, filament runout, power hold
  10698. * - Start the serial port
  10699. * - Print startup messages and diagnostics
  10700. * - Get EEPROM or default settings
  10701. * - Initialize managers for:
  10702. * • temperature
  10703. * • planner
  10704. * • watchdog
  10705. * • stepper
  10706. * • photo pin
  10707. * • servos
  10708. * • LCD controller
  10709. * • Digipot I2C
  10710. * • Z probe sled
  10711. * • status LEDs
  10712. */
  10713. void setup() {
  10714. #ifdef DISABLE_JTAG
  10715. // Disable JTAG on AT90USB chips to free up pins for IO
  10716. MCUCR = 0x80;
  10717. MCUCR = 0x80;
  10718. #endif
  10719. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10720. setup_filrunoutpin();
  10721. #endif
  10722. setup_killpin();
  10723. setup_powerhold();
  10724. #if HAS_STEPPER_RESET
  10725. disableStepperDrivers();
  10726. #endif
  10727. MYSERIAL.begin(BAUDRATE);
  10728. SERIAL_PROTOCOLLNPGM("start");
  10729. SERIAL_ECHO_START();
  10730. // Check startup - does nothing if bootloader sets MCUSR to 0
  10731. byte mcu = MCUSR;
  10732. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10733. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10734. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10735. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10736. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10737. MCUSR = 0;
  10738. SERIAL_ECHOPGM(MSG_MARLIN);
  10739. SERIAL_CHAR(' ');
  10740. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10741. SERIAL_EOL();
  10742. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10743. SERIAL_ECHO_START();
  10744. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10745. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10746. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10747. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10748. #endif
  10749. SERIAL_ECHO_START();
  10750. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10751. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10752. // Send "ok" after commands by default
  10753. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10754. // Load data from EEPROM if available (or use defaults)
  10755. // This also updates variables in the planner, elsewhere
  10756. (void)settings.load();
  10757. #if HAS_M206_COMMAND
  10758. // Initialize current position based on home_offset
  10759. COPY(current_position, home_offset);
  10760. #else
  10761. ZERO(current_position);
  10762. #endif
  10763. // Vital to init stepper/planner equivalent for current_position
  10764. SYNC_PLAN_POSITION_KINEMATIC();
  10765. thermalManager.init(); // Initialize temperature loop
  10766. #if ENABLED(USE_WATCHDOG)
  10767. watchdog_init();
  10768. #endif
  10769. stepper.init(); // Initialize stepper, this enables interrupts!
  10770. servo_init();
  10771. #if HAS_PHOTOGRAPH
  10772. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10773. #endif
  10774. #if HAS_CASE_LIGHT
  10775. case_light_on = CASE_LIGHT_DEFAULT_ON;
  10776. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  10777. update_case_light();
  10778. #endif
  10779. #if ENABLED(SPINDLE_LASER_ENABLE)
  10780. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10781. #if SPINDLE_DIR_CHANGE
  10782. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10783. #endif
  10784. #if ENABLED(SPINDLE_LASER_PWM)
  10785. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10786. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10787. #endif
  10788. #endif
  10789. #if HAS_BED_PROBE
  10790. endstops.enable_z_probe(false);
  10791. #endif
  10792. #if ENABLED(USE_CONTROLLER_FAN)
  10793. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  10794. #endif
  10795. #if HAS_STEPPER_RESET
  10796. enableStepperDrivers();
  10797. #endif
  10798. #if ENABLED(DIGIPOT_I2C)
  10799. digipot_i2c_init();
  10800. #endif
  10801. #if ENABLED(DAC_STEPPER_CURRENT)
  10802. dac_init();
  10803. #endif
  10804. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  10805. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  10806. #endif
  10807. setup_homepin();
  10808. #if PIN_EXISTS(STAT_LED_RED)
  10809. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  10810. #endif
  10811. #if PIN_EXISTS(STAT_LED_BLUE)
  10812. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  10813. #endif
  10814. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  10815. SET_OUTPUT(RGB_LED_R_PIN);
  10816. SET_OUTPUT(RGB_LED_G_PIN);
  10817. SET_OUTPUT(RGB_LED_B_PIN);
  10818. #if ENABLED(RGBW_LED)
  10819. SET_OUTPUT(RGB_LED_W_PIN);
  10820. #endif
  10821. #endif
  10822. lcd_init();
  10823. #if ENABLED(SHOW_BOOTSCREEN)
  10824. #if ENABLED(DOGLCD)
  10825. safe_delay(BOOTSCREEN_TIMEOUT);
  10826. #elif ENABLED(ULTRA_LCD)
  10827. bootscreen();
  10828. #if DISABLED(SDSUPPORT)
  10829. lcd_init();
  10830. #endif
  10831. #endif
  10832. #endif
  10833. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  10834. // Initialize mixing to 100% color 1
  10835. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10836. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  10837. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  10838. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  10839. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  10840. #endif
  10841. #if ENABLED(BLTOUCH)
  10842. // Make sure any BLTouch error condition is cleared
  10843. bltouch_command(BLTOUCH_RESET);
  10844. set_bltouch_deployed(true);
  10845. set_bltouch_deployed(false);
  10846. #endif
  10847. #if ENABLED(I2C_POSITION_ENCODERS)
  10848. I2CPEM.init();
  10849. #endif
  10850. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  10851. i2c.onReceive(i2c_on_receive);
  10852. i2c.onRequest(i2c_on_request);
  10853. #endif
  10854. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  10855. setup_endstop_interrupts();
  10856. #endif
  10857. #if ENABLED(SWITCHING_EXTRUDER)
  10858. move_extruder_servo(0); // Initialize extruder servo
  10859. #endif
  10860. #if ENABLED(SWITCHING_NOZZLE)
  10861. move_nozzle_servo(0); // Initialize nozzle servo
  10862. #endif
  10863. }
  10864. /**
  10865. * The main Marlin program loop
  10866. *
  10867. * - Save or log commands to SD
  10868. * - Process available commands (if not saving)
  10869. * - Call heater manager
  10870. * - Call inactivity manager
  10871. * - Call endstop manager
  10872. * - Call LCD update
  10873. */
  10874. void loop() {
  10875. if (commands_in_queue < BUFSIZE) get_available_commands();
  10876. #if ENABLED(SDSUPPORT)
  10877. card.checkautostart(false);
  10878. #endif
  10879. if (commands_in_queue) {
  10880. #if ENABLED(SDSUPPORT)
  10881. if (card.saving) {
  10882. char* command = command_queue[cmd_queue_index_r];
  10883. if (strstr_P(command, PSTR("M29"))) {
  10884. // M29 closes the file
  10885. card.closefile();
  10886. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  10887. ok_to_send();
  10888. }
  10889. else {
  10890. // Write the string from the read buffer to SD
  10891. card.write_command(command);
  10892. if (card.logging)
  10893. process_next_command(); // The card is saving because it's logging
  10894. else
  10895. ok_to_send();
  10896. }
  10897. }
  10898. else
  10899. process_next_command();
  10900. #else
  10901. process_next_command();
  10902. #endif // SDSUPPORT
  10903. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  10904. if (commands_in_queue) {
  10905. --commands_in_queue;
  10906. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  10907. }
  10908. }
  10909. endstops.report_state();
  10910. idle();
  10911. }