My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Marlin_main.cpp 417KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142
  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. * G17 - Select Plane XY (Requires CNC_WORKSPACE_PLANES)
  56. * G18 - Select Plane ZX (Requires CNC_WORKSPACE_PLANES)
  57. * G19 - Select Plane YZ (Requires CNC_WORKSPACE_PLANES)
  58. * G20 - Set input units to inches
  59. * G21 - Set input units to millimeters
  60. * G26 - Mesh Validation Pattern (Requires UBL_G26_MESH_VALIDATION)
  61. * G27 - Park Nozzle (Requires NOZZLE_PARK_FEATURE)
  62. * G28 - Home one or more axes
  63. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  64. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  65. * G31 - Dock sled (Z_PROBE_SLED only)
  66. * G32 - Undock sled (Z_PROBE_SLED only)
  67. * G33 - Delta Auto-Calibration (Requires DELTA_AUTO_CALIBRATION)
  68. * G38 - Probe target - similar to G28 except it uses the Z_MIN_PROBE for all three axes
  69. * G42 - Coordinated move to a mesh point (Requires AUTO_BED_LEVELING_UBL)
  70. * G90 - Use Absolute Coordinates
  71. * G91 - Use Relative Coordinates
  72. * G92 - Set current position to coordinates given
  73. *
  74. * "M" Codes
  75. *
  76. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  77. * M1 -> M0
  78. * M3 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to clockwise
  79. * M4 - Turn laser/spindle on, set spindle/laser speed/power, set rotation to counter-clockwise
  80. * M5 - Turn laser/spindle off
  81. * M17 - Enable/Power all stepper motors
  82. * M18 - Disable all stepper motors; same as M84
  83. * M20 - List SD card. (Requires SDSUPPORT)
  84. * M21 - Init SD card. (Requires SDSUPPORT)
  85. * M22 - Release SD card. (Requires SDSUPPORT)
  86. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  87. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  88. * M25 - Pause SD print. (Requires SDSUPPORT)
  89. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  90. * M27 - Report SD print status. (Requires SDSUPPORT)
  91. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  92. * M29 - Stop SD write. (Requires SDSUPPORT)
  93. * M30 - Delete file from SD: "M30 /path/file.gco"
  94. * M31 - Report time since last M109 or SD card start to serial.
  95. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  96. * Use P to run other files as sub-programs: "M32 P !filename#"
  97. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  98. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  99. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  100. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  101. * M43 - Display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
  102. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  103. * M75 - Start the print job timer.
  104. * M76 - Pause the print job timer.
  105. * M77 - Stop the print job timer.
  106. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  107. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY > 0)
  108. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY > 0)
  109. * M82 - Set E codes absolute (default).
  110. * M83 - Set E codes relative while in Absolute (G90) mode.
  111. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  112. * duration after which steppers should turn off. S0 disables the timeout.
  113. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  114. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  115. * M100 - Watch Free Memory (for debugging) (Requires M100_FREE_MEMORY_WATCHER)
  116. * M104 - Set extruder target temp.
  117. * M105 - Report current temperatures.
  118. * M106 - Fan on.
  119. * M107 - Fan off.
  120. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  121. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  122. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  123. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  124. * M110 - Set the current line number. (Used by host printing)
  125. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  126. * M112 - Emergency stop.
  127. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  128. * M114 - Report current position.
  129. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  130. * M117 - Display a message on the controller screen. (Requires an LCD)
  131. * M118 - Display a message in the host console.
  132. * M119 - Report endstops status.
  133. * M120 - Enable endstops detection.
  134. * M121 - Disable endstops detection.
  135. * M125 - Save current position and move to filament change position. (Requires PARK_HEAD_ON_PAUSE)
  136. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  137. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  138. * M128 - EtoP Open. (Requires BARICUDA)
  139. * M129 - EtoP Closed. (Requires BARICUDA)
  140. * M140 - Set bed target temp. S<temp>
  141. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  142. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  143. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM, RGB_LED, RGBW_LED, or PCA9632)
  144. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  145. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  146. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  147. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  148. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  149. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  150. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  151. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  152. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  153. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  154. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  155. * M205 - Set advanced settings. Current units apply:
  156. S<print> T<travel> minimum speeds
  157. B<minimum segment time>
  158. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  159. * M206 - Set additional homing offset. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  160. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  161. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  162. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  163. Every normal extrude-only move will be classified as retract depending on the direction.
  164. * M211 - Enable, Disable, and/or Report software endstops: S<0|1> (Requires MIN_SOFTWARE_ENDSTOPS or MAX_SOFTWARE_ENDSTOPS)
  165. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  166. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  167. * M221 - Set Flow Percentage: "M221 S<percent>"
  168. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  169. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  170. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  171. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  172. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  173. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  174. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  175. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  176. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  177. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  178. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  179. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  180. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  181. * M355 - Set Case Light on/off and set brightness. (Requires CASE_LIGHT_PIN)
  182. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  183. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  184. * M400 - Finish all moves.
  185. * M401 - Lower Z probe. (Requires a probe)
  186. * M402 - Raise Z probe. (Requires a probe)
  187. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  188. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  189. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  190. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  191. * M410 - Quickstop. Abort all planned moves.
  192. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  193. * 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)
  194. * M428 - Set the home_offset based on the current_position. Nearest edge applies. (Disabled by NO_WORKSPACE_OFFSETS or DELTA)
  195. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  196. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  197. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  198. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  199. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  200. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires ADVANCED_PAUSE_FEATURE)
  201. * 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)
  202. * M666 - Set delta endstop adjustment. (Requires DELTA)
  203. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  204. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  205. * M860 - Report the position of position encoder modules.
  206. * M861 - Report the status of position encoder modules.
  207. * M862 - Perform an axis continuity test for position encoder modules.
  208. * M863 - Perform steps-per-mm calibration for position encoder modules.
  209. * M864 - Change position encoder module I2C address.
  210. * M865 - Check position encoder module firmware version.
  211. * M866 - Report or reset position encoder module error count.
  212. * M867 - Enable/disable or toggle error correction for position encoder modules.
  213. * M868 - Report or set position encoder module error correction threshold.
  214. * M869 - Report position encoder module error.
  215. * M900 - Get and/or Set advance K factor and WH/D ratio. (Requires LIN_ADVANCE)
  216. * 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)
  217. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  218. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  219. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  220. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  221. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  222. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  223. * M913 - Set HYBRID_THRESHOLD speed. (Requires HYBRID_THRESHOLD)
  224. * M914 - Set SENSORLESS_HOMING sensitivity. (Requires SENSORLESS_HOMING)
  225. *
  226. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  227. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  228. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  229. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  230. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  231. *
  232. * ************ Custom codes - This can change to suit future G-code regulations
  233. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  234. * M999 - Restart after being stopped by error
  235. *
  236. * "T" Codes
  237. *
  238. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  239. *
  240. */
  241. #include "Marlin.h"
  242. #include "ultralcd.h"
  243. #include "planner.h"
  244. #include "stepper.h"
  245. #include "endstops.h"
  246. #include "temperature.h"
  247. #include "cardreader.h"
  248. #include "configuration_store.h"
  249. #include "language.h"
  250. #include "pins_arduino.h"
  251. #include "math.h"
  252. #include "nozzle.h"
  253. #include "duration_t.h"
  254. #include "types.h"
  255. #include "gcode.h"
  256. #if HAS_ABL
  257. #include "vector_3.h"
  258. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  259. #include "qr_solve.h"
  260. #endif
  261. #elif ENABLED(MESH_BED_LEVELING)
  262. #include "mesh_bed_leveling.h"
  263. #endif
  264. #if ENABLED(BEZIER_CURVE_SUPPORT)
  265. #include "planner_bezier.h"
  266. #endif
  267. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  268. #include "buzzer.h"
  269. #endif
  270. #if ENABLED(USE_WATCHDOG)
  271. #include "watchdog.h"
  272. #endif
  273. #if ENABLED(BLINKM)
  274. #include "blinkm.h"
  275. #include "Wire.h"
  276. #endif
  277. #if ENABLED(PCA9632)
  278. #include "pca9632.h"
  279. #endif
  280. #if HAS_SERVOS
  281. #include "servo.h"
  282. #endif
  283. #if HAS_DIGIPOTSS
  284. #include <SPI.h>
  285. #endif
  286. #if ENABLED(DAC_STEPPER_CURRENT)
  287. #include "stepper_dac.h"
  288. #endif
  289. #if ENABLED(EXPERIMENTAL_I2CBUS)
  290. #include "twibus.h"
  291. #endif
  292. #if ENABLED(I2C_POSITION_ENCODERS)
  293. #include "I2CPositionEncoder.h"
  294. #endif
  295. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  296. #include "endstop_interrupts.h"
  297. #endif
  298. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  299. void gcode_M100();
  300. void M100_dump_routine(const char * const title, const char *start, const char *end);
  301. #endif
  302. #if ENABLED(SDSUPPORT)
  303. CardReader card;
  304. #endif
  305. #if ENABLED(EXPERIMENTAL_I2CBUS)
  306. TWIBus i2c;
  307. #endif
  308. #if ENABLED(G38_PROBE_TARGET)
  309. bool G38_move = false,
  310. G38_endstop_hit = false;
  311. #endif
  312. #if ENABLED(AUTO_BED_LEVELING_UBL)
  313. #include "ubl.h"
  314. extern bool defer_return_to_status;
  315. unified_bed_leveling ubl;
  316. #define UBL_MESH_VALID !( ( ubl.z_values[0][0] == ubl.z_values[0][1] && ubl.z_values[0][1] == ubl.z_values[0][2] \
  317. && ubl.z_values[1][0] == ubl.z_values[1][1] && ubl.z_values[1][1] == ubl.z_values[1][2] \
  318. && ubl.z_values[2][0] == ubl.z_values[2][1] && ubl.z_values[2][1] == ubl.z_values[2][2] \
  319. && ubl.z_values[0][0] == 0 && ubl.z_values[1][0] == 0 && ubl.z_values[2][0] == 0 ) \
  320. || isnan(ubl.z_values[0][0]))
  321. #endif
  322. bool Running = true;
  323. uint8_t marlin_debug_flags = DEBUG_NONE;
  324. /**
  325. * Cartesian Current Position
  326. * Used to track the logical position as moves are queued.
  327. * Used by 'line_to_current_position' to do a move after changing it.
  328. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  329. */
  330. float current_position[XYZE] = { 0.0 };
  331. /**
  332. * Cartesian Destination
  333. * A temporary position, usually applied to 'current_position'.
  334. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  335. * 'line_to_destination' sets 'current_position' to 'destination'.
  336. */
  337. float destination[XYZE] = { 0.0 };
  338. /**
  339. * axis_homed
  340. * Flags that each linear axis was homed.
  341. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  342. *
  343. * axis_known_position
  344. * Flags that the position is known in each linear axis. Set when homed.
  345. * Cleared whenever a stepper powers off, potentially losing its position.
  346. */
  347. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  348. /**
  349. * GCode line number handling. Hosts may opt to include line numbers when
  350. * sending commands to Marlin, and lines will be checked for sequentiality.
  351. * M110 N<int> sets the current line number.
  352. */
  353. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  354. /**
  355. * GCode Command Queue
  356. * A simple ring buffer of BUFSIZE command strings.
  357. *
  358. * Commands are copied into this buffer by the command injectors
  359. * (immediate, serial, sd card) and they are processed sequentially by
  360. * the main loop. The process_next_command function parses the next
  361. * command and hands off execution to individual handler functions.
  362. */
  363. uint8_t commands_in_queue = 0; // Count of commands in the queue
  364. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  365. cmd_queue_index_w = 0; // Ring buffer write position
  366. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  367. char command_queue[BUFSIZE][MAX_CMD_SIZE]; // Necessary so M100 Free Memory Dumper can show us the commands and any corruption
  368. #else // This can be collapsed back to the way it was soon.
  369. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  370. #endif
  371. /**
  372. * Next Injected Command pointer. NULL if no commands are being injected.
  373. * Used by Marlin internally to ensure that commands initiated from within
  374. * are enqueued ahead of any pending serial or sd card commands.
  375. */
  376. static const char *injected_commands_P = NULL;
  377. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  378. TempUnit input_temp_units = TEMPUNIT_C;
  379. #endif
  380. /**
  381. * Feed rates are often configured with mm/m
  382. * but the planner and stepper like mm/s units.
  383. */
  384. static const float homing_feedrate_mm_s[] PROGMEM = {
  385. #if ENABLED(DELTA)
  386. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  387. #else
  388. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  389. #endif
  390. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  391. };
  392. FORCE_INLINE float homing_feedrate(const AxisEnum a) { return pgm_read_float(&homing_feedrate_mm_s[a]); }
  393. float feedrate_mm_s = MMM_TO_MMS(1500.0);
  394. static float saved_feedrate_mm_s;
  395. int16_t feedrate_percentage = 100, saved_feedrate_percentage,
  396. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  397. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  398. volumetric_enabled =
  399. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  400. true
  401. #else
  402. false
  403. #endif
  404. ;
  405. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  406. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  407. #if HAS_WORKSPACE_OFFSET
  408. #if HAS_POSITION_SHIFT
  409. // The distance that XYZ has been offset by G92. Reset by G28.
  410. float position_shift[XYZ] = { 0 };
  411. #endif
  412. #if HAS_HOME_OFFSET
  413. // This offset is added to the configured home position.
  414. // Set by M206, M428, or menu item. Saved to EEPROM.
  415. float home_offset[XYZ] = { 0 };
  416. #endif
  417. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  418. // The above two are combined to save on computes
  419. float workspace_offset[XYZ] = { 0 };
  420. #endif
  421. #endif
  422. // Software Endstops are based on the configured limits.
  423. #if HAS_SOFTWARE_ENDSTOPS
  424. bool soft_endstops_enabled = true;
  425. #endif
  426. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  427. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  428. #if FAN_COUNT > 0
  429. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  430. #if ENABLED(PROBING_FANS_OFF)
  431. bool fans_paused = false;
  432. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  433. #endif
  434. #endif
  435. // The active extruder (tool). Set with T<extruder> command.
  436. uint8_t active_extruder = 0;
  437. // Relative Mode. Enable with G91, disable with G90.
  438. static bool relative_mode = false;
  439. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  440. volatile bool wait_for_heatup = true;
  441. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  442. #if HAS_RESUME_CONTINUE
  443. volatile bool wait_for_user = false;
  444. #endif
  445. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  446. // Number of characters read in the current line of serial input
  447. static int serial_count = 0;
  448. // Inactivity shutdown
  449. millis_t previous_cmd_ms = 0;
  450. static millis_t max_inactive_time = 0;
  451. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  452. // Print Job Timer
  453. #if ENABLED(PRINTCOUNTER)
  454. PrintCounter print_job_timer = PrintCounter();
  455. #else
  456. Stopwatch print_job_timer = Stopwatch();
  457. #endif
  458. // Buzzer - I2C on the LCD or a BEEPER_PIN
  459. #if ENABLED(LCD_USE_I2C_BUZZER)
  460. #define BUZZ(d,f) lcd_buzz(d, f)
  461. #elif PIN_EXISTS(BEEPER)
  462. Buzzer buzzer;
  463. #define BUZZ(d,f) buzzer.tone(d, f)
  464. #else
  465. #define BUZZ(d,f) NOOP
  466. #endif
  467. static uint8_t target_extruder;
  468. #if HAS_BED_PROBE
  469. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  470. #endif
  471. #if HAS_ABL
  472. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  473. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  474. #elif defined(XY_PROBE_SPEED)
  475. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  476. #else
  477. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  478. #endif
  479. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  480. #if ENABLED(DELTA)
  481. #define ADJUST_DELTA(V) \
  482. if (planner.abl_enabled) { \
  483. const float zadj = bilinear_z_offset(V); \
  484. delta[A_AXIS] += zadj; \
  485. delta[B_AXIS] += zadj; \
  486. delta[C_AXIS] += zadj; \
  487. }
  488. #else
  489. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  490. #endif
  491. #elif IS_KINEMATIC
  492. #define ADJUST_DELTA(V) NOOP
  493. #endif
  494. #if ENABLED(Z_DUAL_ENDSTOPS)
  495. float z_endstop_adj =
  496. #ifdef Z_DUAL_ENDSTOPS_ADJUSTMENT
  497. Z_DUAL_ENDSTOPS_ADJUSTMENT
  498. #else
  499. 0
  500. #endif
  501. ;
  502. #endif
  503. // Extruder offsets
  504. #if HOTENDS > 1
  505. float hotend_offset[XYZ][HOTENDS];
  506. #endif
  507. #if HAS_Z_SERVO_ENDSTOP
  508. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  509. #endif
  510. #if ENABLED(BARICUDA)
  511. int baricuda_valve_pressure = 0;
  512. int baricuda_e_to_p_pressure = 0;
  513. #endif
  514. #if ENABLED(FWRETRACT)
  515. bool autoretract_enabled = false;
  516. bool retracted[EXTRUDERS] = { false };
  517. bool retracted_swap[EXTRUDERS] = { false };
  518. float retract_length = RETRACT_LENGTH;
  519. float retract_length_swap = RETRACT_LENGTH_SWAP;
  520. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  521. float retract_zlift = RETRACT_ZLIFT;
  522. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  523. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  524. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  525. #endif // FWRETRACT
  526. #if HAS_POWER_SWITCH
  527. bool powersupply_on =
  528. #if ENABLED(PS_DEFAULT_OFF)
  529. false
  530. #else
  531. true
  532. #endif
  533. ;
  534. #endif
  535. #if ENABLED(DELTA)
  536. float delta[ABC],
  537. endstop_adj[ABC] = { 0 };
  538. // These values are loaded or reset at boot time when setup() calls
  539. // settings.load(), which calls recalc_delta_settings().
  540. float delta_radius,
  541. delta_tower_angle_trim[2],
  542. delta_tower[ABC][2],
  543. delta_diagonal_rod,
  544. delta_calibration_radius,
  545. delta_diagonal_rod_2_tower[ABC],
  546. delta_segments_per_second,
  547. delta_clip_start_height = Z_MAX_POS;
  548. float delta_safe_distance_from_top();
  549. #endif
  550. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  551. int bilinear_grid_spacing[2], bilinear_start[2];
  552. float bilinear_grid_factor[2],
  553. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  554. #endif
  555. #if IS_SCARA
  556. // Float constants for SCARA calculations
  557. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  558. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  559. L2_2 = sq(float(L2));
  560. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  561. delta[ABC];
  562. #endif
  563. float cartes[XYZ] = { 0 };
  564. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  565. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  566. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  567. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  568. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM, // Distance delay setting
  569. measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  570. int8_t filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  571. #endif
  572. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  573. static bool filament_ran_out = false;
  574. #endif
  575. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  576. AdvancedPauseMenuResponse advanced_pause_menu_response;
  577. #endif
  578. #if ENABLED(MIXING_EXTRUDER)
  579. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  580. #if MIXING_VIRTUAL_TOOLS > 1
  581. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  582. #endif
  583. #endif
  584. static bool send_ok[BUFSIZE];
  585. #if HAS_SERVOS
  586. Servo servo[NUM_SERVOS];
  587. #define MOVE_SERVO(I, P) servo[I].move(P)
  588. #if HAS_Z_SERVO_ENDSTOP
  589. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  590. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  591. #endif
  592. #endif
  593. #ifdef CHDK
  594. millis_t chdkHigh = 0;
  595. bool chdkActive = false;
  596. #endif
  597. #ifdef AUTOMATIC_CURRENT_CONTROL
  598. bool auto_current_control = 0;
  599. #endif
  600. #if ENABLED(PID_EXTRUSION_SCALING)
  601. int lpq_len = 20;
  602. #endif
  603. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  604. MarlinBusyState busy_state = NOT_BUSY;
  605. static millis_t next_busy_signal_ms = 0;
  606. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  607. #else
  608. #define host_keepalive() NOOP
  609. #endif
  610. #if ENABLED(I2C_POSITION_ENCODERS)
  611. I2CPositionEncodersMgr I2CPEM;
  612. uint8_t blockBufferIndexRef = 0;
  613. millis_t lastUpdateMillis;
  614. #endif
  615. #if ENABLED(CNC_WORKSPACE_PLANES)
  616. static WorkspacePlane workspace_plane = PLANE_XY;
  617. #endif
  618. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  619. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  620. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  621. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  622. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  623. typedef void __void_##CONFIG##__
  624. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  625. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  626. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  627. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  628. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  629. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  630. /**
  631. * ***************************************************************************
  632. * ******************************** FUNCTIONS ********************************
  633. * ***************************************************************************
  634. */
  635. void stop();
  636. void get_available_commands();
  637. void process_next_command();
  638. void prepare_move_to_destination();
  639. void get_cartesian_from_steppers();
  640. void set_current_from_steppers_for_axis(const AxisEnum axis);
  641. #if ENABLED(ARC_SUPPORT)
  642. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  643. #endif
  644. #if ENABLED(BEZIER_CURVE_SUPPORT)
  645. void plan_cubic_move(const float offset[4]);
  646. #endif
  647. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  648. void report_current_position();
  649. void report_current_position_detail();
  650. #if ENABLED(DEBUG_LEVELING_FEATURE)
  651. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  652. serialprintPGM(prefix);
  653. SERIAL_CHAR('(');
  654. SERIAL_ECHO(x);
  655. SERIAL_ECHOPAIR(", ", y);
  656. SERIAL_ECHOPAIR(", ", z);
  657. SERIAL_CHAR(')');
  658. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  659. }
  660. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  661. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  662. }
  663. #if HAS_ABL
  664. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  665. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  666. }
  667. #endif
  668. #define DEBUG_POS(SUFFIX,VAR) do { \
  669. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  670. #endif
  671. /**
  672. * sync_plan_position
  673. *
  674. * Set the planner/stepper positions directly from current_position with
  675. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  676. */
  677. void sync_plan_position() {
  678. #if ENABLED(DEBUG_LEVELING_FEATURE)
  679. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  680. #endif
  681. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  682. }
  683. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  684. #if IS_KINEMATIC
  685. inline void sync_plan_position_kinematic() {
  686. #if ENABLED(DEBUG_LEVELING_FEATURE)
  687. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  688. #endif
  689. planner.set_position_mm_kinematic(current_position);
  690. }
  691. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  692. #else
  693. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  694. #endif
  695. #if ENABLED(SDSUPPORT)
  696. #include "SdFatUtil.h"
  697. int freeMemory() { return SdFatUtil::FreeRam(); }
  698. #else
  699. extern "C" {
  700. extern char __bss_end;
  701. extern char __heap_start;
  702. extern void* __brkval;
  703. int freeMemory() {
  704. int free_memory;
  705. if ((int)__brkval == 0)
  706. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  707. else
  708. free_memory = ((int)&free_memory) - ((int)__brkval);
  709. return free_memory;
  710. }
  711. }
  712. #endif // !SDSUPPORT
  713. #if ENABLED(DIGIPOT_I2C)
  714. extern void digipot_i2c_set_current(uint8_t channel, float current);
  715. extern void digipot_i2c_init();
  716. #endif
  717. /**
  718. * Inject the next "immediate" command, when possible, onto the front of the queue.
  719. * Return true if any immediate commands remain to inject.
  720. */
  721. static bool drain_injected_commands_P() {
  722. if (injected_commands_P != NULL) {
  723. size_t i = 0;
  724. char c, cmd[30];
  725. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  726. cmd[sizeof(cmd) - 1] = '\0';
  727. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  728. cmd[i] = '\0';
  729. if (enqueue_and_echo_command(cmd)) // success?
  730. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  731. }
  732. return (injected_commands_P != NULL); // return whether any more remain
  733. }
  734. /**
  735. * Record one or many commands to run from program memory.
  736. * Aborts the current queue, if any.
  737. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  738. */
  739. void enqueue_and_echo_commands_P(const char * const pgcode) {
  740. injected_commands_P = pgcode;
  741. drain_injected_commands_P(); // first command executed asap (when possible)
  742. }
  743. /**
  744. * Clear the Marlin command queue
  745. */
  746. void clear_command_queue() {
  747. cmd_queue_index_r = cmd_queue_index_w;
  748. commands_in_queue = 0;
  749. }
  750. /**
  751. * Once a new command is in the ring buffer, call this to commit it
  752. */
  753. inline void _commit_command(bool say_ok) {
  754. send_ok[cmd_queue_index_w] = say_ok;
  755. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  756. commands_in_queue++;
  757. }
  758. /**
  759. * Copy a command from RAM into the main command buffer.
  760. * Return true if the command was successfully added.
  761. * Return false for a full buffer, or if the 'command' is a comment.
  762. */
  763. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  764. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  765. strcpy(command_queue[cmd_queue_index_w], cmd);
  766. _commit_command(say_ok);
  767. return true;
  768. }
  769. /**
  770. * Enqueue with Serial Echo
  771. */
  772. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  773. if (_enqueuecommand(cmd, say_ok)) {
  774. SERIAL_ECHO_START();
  775. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  776. SERIAL_CHAR('"');
  777. SERIAL_EOL();
  778. return true;
  779. }
  780. return false;
  781. }
  782. void setup_killpin() {
  783. #if HAS_KILL
  784. SET_INPUT_PULLUP(KILL_PIN);
  785. #endif
  786. }
  787. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  788. void setup_filrunoutpin() {
  789. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  790. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  791. #else
  792. SET_INPUT(FIL_RUNOUT_PIN);
  793. #endif
  794. }
  795. #endif
  796. void setup_homepin(void) {
  797. #if HAS_HOME
  798. SET_INPUT_PULLUP(HOME_PIN);
  799. #endif
  800. }
  801. void setup_powerhold() {
  802. #if HAS_SUICIDE
  803. OUT_WRITE(SUICIDE_PIN, HIGH);
  804. #endif
  805. #if HAS_POWER_SWITCH
  806. #if ENABLED(PS_DEFAULT_OFF)
  807. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  808. #else
  809. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  810. #endif
  811. #endif
  812. }
  813. void suicide() {
  814. #if HAS_SUICIDE
  815. OUT_WRITE(SUICIDE_PIN, LOW);
  816. #endif
  817. }
  818. void servo_init() {
  819. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  820. servo[0].attach(SERVO0_PIN);
  821. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  822. #endif
  823. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  824. servo[1].attach(SERVO1_PIN);
  825. servo[1].detach();
  826. #endif
  827. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  828. servo[2].attach(SERVO2_PIN);
  829. servo[2].detach();
  830. #endif
  831. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  832. servo[3].attach(SERVO3_PIN);
  833. servo[3].detach();
  834. #endif
  835. #if HAS_Z_SERVO_ENDSTOP
  836. /**
  837. * Set position of Z Servo Endstop
  838. *
  839. * The servo might be deployed and positioned too low to stow
  840. * when starting up the machine or rebooting the board.
  841. * There's no way to know where the nozzle is positioned until
  842. * homing has been done - no homing with z-probe without init!
  843. *
  844. */
  845. STOW_Z_SERVO();
  846. #endif
  847. }
  848. /**
  849. * Stepper Reset (RigidBoard, et.al.)
  850. */
  851. #if HAS_STEPPER_RESET
  852. void disableStepperDrivers() {
  853. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  854. }
  855. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  856. #endif
  857. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  858. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  859. i2c.receive(bytes);
  860. }
  861. void i2c_on_request() { // just send dummy data for now
  862. i2c.reply("Hello World!\n");
  863. }
  864. #endif
  865. #if HAS_COLOR_LEDS
  866. void set_led_color(
  867. const uint8_t r, const uint8_t g, const uint8_t b
  868. #if ENABLED(RGBW_LED)
  869. , const uint8_t w=0
  870. #endif
  871. ) {
  872. #if ENABLED(BLINKM)
  873. // This variant uses i2c to send the RGB components to the device.
  874. SendColors(r, g, b);
  875. #endif
  876. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  877. // This variant uses 3 separate pins for the RGB components.
  878. // If the pins can do PWM then their intensity will be set.
  879. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  880. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  881. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  882. analogWrite(RGB_LED_R_PIN, r);
  883. analogWrite(RGB_LED_G_PIN, g);
  884. analogWrite(RGB_LED_B_PIN, b);
  885. #if ENABLED(RGBW_LED)
  886. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  887. analogWrite(RGB_LED_W_PIN, w);
  888. #endif
  889. #endif
  890. #if ENABLED(PCA9632)
  891. // Update I2C LED driver
  892. PCA9632_SetColor(r, g, b);
  893. #endif
  894. }
  895. #endif // HAS_COLOR_LEDS
  896. void gcode_line_error(const char* err, bool doFlush = true) {
  897. SERIAL_ERROR_START();
  898. serialprintPGM(err);
  899. SERIAL_ERRORLN(gcode_LastN);
  900. //Serial.println(gcode_N);
  901. if (doFlush) FlushSerialRequestResend();
  902. serial_count = 0;
  903. }
  904. /**
  905. * Get all commands waiting on the serial port and queue them.
  906. * Exit when the buffer is full or when no more characters are
  907. * left on the serial port.
  908. */
  909. inline void get_serial_commands() {
  910. static char serial_line_buffer[MAX_CMD_SIZE];
  911. static bool serial_comment_mode = false;
  912. // If the command buffer is empty for too long,
  913. // send "wait" to indicate Marlin is still waiting.
  914. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  915. static millis_t last_command_time = 0;
  916. const millis_t ms = millis();
  917. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  918. SERIAL_ECHOLNPGM(MSG_WAIT);
  919. last_command_time = ms;
  920. }
  921. #endif
  922. /**
  923. * Loop while serial characters are incoming and the queue is not full
  924. */
  925. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  926. char serial_char = MYSERIAL.read();
  927. /**
  928. * If the character ends the line
  929. */
  930. if (serial_char == '\n' || serial_char == '\r') {
  931. serial_comment_mode = false; // end of line == end of comment
  932. if (!serial_count) continue; // skip empty lines
  933. serial_line_buffer[serial_count] = 0; // terminate string
  934. serial_count = 0; //reset buffer
  935. char* command = serial_line_buffer;
  936. while (*command == ' ') command++; // skip any leading spaces
  937. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  938. *apos = strchr(command, '*');
  939. if (npos) {
  940. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  941. if (M110) {
  942. char* n2pos = strchr(command + 4, 'N');
  943. if (n2pos) npos = n2pos;
  944. }
  945. gcode_N = strtol(npos + 1, NULL, 10);
  946. if (gcode_N != gcode_LastN + 1 && !M110) {
  947. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  948. return;
  949. }
  950. if (apos) {
  951. byte checksum = 0, count = 0;
  952. while (command[count] != '*') checksum ^= command[count++];
  953. if (strtol(apos + 1, NULL, 10) != checksum) {
  954. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  955. return;
  956. }
  957. // if no errors, continue parsing
  958. }
  959. else {
  960. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  961. return;
  962. }
  963. gcode_LastN = gcode_N;
  964. // if no errors, continue parsing
  965. }
  966. else if (apos) { // No '*' without 'N'
  967. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  968. return;
  969. }
  970. // Movement commands alert when stopped
  971. if (IsStopped()) {
  972. char* gpos = strchr(command, 'G');
  973. if (gpos) {
  974. const int codenum = strtol(gpos + 1, NULL, 10);
  975. switch (codenum) {
  976. case 0:
  977. case 1:
  978. case 2:
  979. case 3:
  980. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  981. LCD_MESSAGEPGM(MSG_STOPPED);
  982. break;
  983. }
  984. }
  985. }
  986. #if DISABLED(EMERGENCY_PARSER)
  987. // If command was e-stop process now
  988. if (strcmp(command, "M108") == 0) {
  989. wait_for_heatup = false;
  990. #if ENABLED(ULTIPANEL)
  991. wait_for_user = false;
  992. #endif
  993. }
  994. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  995. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  996. #endif
  997. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  998. last_command_time = ms;
  999. #endif
  1000. // Add the command to the queue
  1001. _enqueuecommand(serial_line_buffer, true);
  1002. }
  1003. else if (serial_count >= MAX_CMD_SIZE - 1) {
  1004. // Keep fetching, but ignore normal characters beyond the max length
  1005. // The command will be injected when EOL is reached
  1006. }
  1007. else if (serial_char == '\\') { // Handle escapes
  1008. if (MYSERIAL.available() > 0) {
  1009. // if we have one more character, copy it over
  1010. serial_char = MYSERIAL.read();
  1011. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1012. }
  1013. // otherwise do nothing
  1014. }
  1015. else { // it's not a newline, carriage return or escape char
  1016. if (serial_char == ';') serial_comment_mode = true;
  1017. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1018. }
  1019. } // queue has space, serial has data
  1020. }
  1021. #if ENABLED(SDSUPPORT)
  1022. /**
  1023. * Get commands from the SD Card until the command buffer is full
  1024. * or until the end of the file is reached. The special character '#'
  1025. * can also interrupt buffering.
  1026. */
  1027. inline void get_sdcard_commands() {
  1028. static bool stop_buffering = false,
  1029. sd_comment_mode = false;
  1030. if (!card.sdprinting) return;
  1031. /**
  1032. * '#' stops reading from SD to the buffer prematurely, so procedural
  1033. * macro calls are possible. If it occurs, stop_buffering is triggered
  1034. * and the buffer is run dry; this character _can_ occur in serial com
  1035. * due to checksums, however, no checksums are used in SD printing.
  1036. */
  1037. if (commands_in_queue == 0) stop_buffering = false;
  1038. uint16_t sd_count = 0;
  1039. bool card_eof = card.eof();
  1040. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1041. const int16_t n = card.get();
  1042. char sd_char = (char)n;
  1043. card_eof = card.eof();
  1044. if (card_eof || n == -1
  1045. || sd_char == '\n' || sd_char == '\r'
  1046. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1047. ) {
  1048. if (card_eof) {
  1049. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1050. card.printingHasFinished();
  1051. #if ENABLED(PRINTER_EVENT_LEDS)
  1052. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1053. set_led_color(0, 255, 0); // Green
  1054. #if HAS_RESUME_CONTINUE
  1055. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1056. #else
  1057. safe_delay(1000);
  1058. #endif
  1059. set_led_color(0, 0, 0); // OFF
  1060. #endif
  1061. card.checkautostart(true);
  1062. }
  1063. else if (n == -1) {
  1064. SERIAL_ERROR_START();
  1065. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1066. }
  1067. if (sd_char == '#') stop_buffering = true;
  1068. sd_comment_mode = false; // for new command
  1069. if (!sd_count) continue; // skip empty lines (and comment lines)
  1070. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1071. sd_count = 0; // clear sd line buffer
  1072. _commit_command(false);
  1073. }
  1074. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1075. /**
  1076. * Keep fetching, but ignore normal characters beyond the max length
  1077. * The command will be injected when EOL is reached
  1078. */
  1079. }
  1080. else {
  1081. if (sd_char == ';') sd_comment_mode = true;
  1082. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1083. }
  1084. }
  1085. }
  1086. #endif // SDSUPPORT
  1087. /**
  1088. * Add to the circular command queue the next command from:
  1089. * - The command-injection queue (injected_commands_P)
  1090. * - The active serial input (usually USB)
  1091. * - The SD card file being actively printed
  1092. */
  1093. void get_available_commands() {
  1094. // if any immediate commands remain, don't get other commands yet
  1095. if (drain_injected_commands_P()) return;
  1096. get_serial_commands();
  1097. #if ENABLED(SDSUPPORT)
  1098. get_sdcard_commands();
  1099. #endif
  1100. }
  1101. /**
  1102. * Set target_extruder from the T parameter or the active_extruder
  1103. *
  1104. * Returns TRUE if the target is invalid
  1105. */
  1106. bool get_target_extruder_from_command(const uint16_t code) {
  1107. if (parser.seenval('T')) {
  1108. const int8_t e = parser.value_byte();
  1109. if (e >= EXTRUDERS) {
  1110. SERIAL_ECHO_START();
  1111. SERIAL_CHAR('M');
  1112. SERIAL_ECHO(code);
  1113. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1114. return true;
  1115. }
  1116. target_extruder = e;
  1117. }
  1118. else
  1119. target_extruder = active_extruder;
  1120. return false;
  1121. }
  1122. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1123. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1124. #endif
  1125. #if ENABLED(DUAL_X_CARRIAGE)
  1126. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1127. static float x_home_pos(const int extruder) {
  1128. if (extruder == 0)
  1129. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1130. else
  1131. /**
  1132. * In dual carriage mode the extruder offset provides an override of the
  1133. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1134. * This allows soft recalibration of the second extruder home position
  1135. * without firmware reflash (through the M218 command).
  1136. */
  1137. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1138. }
  1139. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1140. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1141. static bool active_extruder_parked = false; // used in mode 1 & 2
  1142. static float raised_parked_position[XYZE]; // used in mode 1
  1143. static millis_t delayed_move_time = 0; // used in mode 1
  1144. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1145. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1146. #endif // DUAL_X_CARRIAGE
  1147. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1148. /**
  1149. * Software endstops can be used to monitor the open end of
  1150. * an axis that has a hardware endstop on the other end. Or
  1151. * they can prevent axes from moving past endstops and grinding.
  1152. *
  1153. * To keep doing their job as the coordinate system changes,
  1154. * the software endstop positions must be refreshed to remain
  1155. * at the same positions relative to the machine.
  1156. */
  1157. void update_software_endstops(const AxisEnum axis) {
  1158. const float offs = 0.0
  1159. #if HAS_HOME_OFFSET
  1160. + home_offset[axis]
  1161. #endif
  1162. #if HAS_POSITION_SHIFT
  1163. + position_shift[axis]
  1164. #endif
  1165. ;
  1166. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1167. workspace_offset[axis] = offs;
  1168. #endif
  1169. #if ENABLED(DUAL_X_CARRIAGE)
  1170. if (axis == X_AXIS) {
  1171. // In Dual X mode hotend_offset[X] is T1's home position
  1172. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1173. if (active_extruder != 0) {
  1174. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1175. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1176. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1177. }
  1178. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1179. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1180. // but not so far to the right that T1 would move past the end
  1181. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1182. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1183. }
  1184. else {
  1185. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1186. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1187. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1188. }
  1189. }
  1190. #else
  1191. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1192. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1193. #endif
  1194. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1195. if (DEBUGGING(LEVELING)) {
  1196. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1197. #if HAS_HOME_OFFSET
  1198. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1199. #endif
  1200. #if HAS_POSITION_SHIFT
  1201. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1202. #endif
  1203. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1204. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1205. }
  1206. #endif
  1207. #if ENABLED(DELTA)
  1208. if (axis == Z_AXIS)
  1209. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1210. #endif
  1211. }
  1212. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1213. #if HAS_M206_COMMAND
  1214. /**
  1215. * Change the home offset for an axis, update the current
  1216. * position and the software endstops to retain the same
  1217. * relative distance to the new home.
  1218. *
  1219. * Since this changes the current_position, code should
  1220. * call sync_plan_position soon after this.
  1221. */
  1222. static void set_home_offset(const AxisEnum axis, const float v) {
  1223. current_position[axis] += v - home_offset[axis];
  1224. home_offset[axis] = v;
  1225. update_software_endstops(axis);
  1226. }
  1227. #endif // HAS_M206_COMMAND
  1228. /**
  1229. * Set an axis' current position to its home position (after homing).
  1230. *
  1231. * For Core and Cartesian robots this applies one-to-one when an
  1232. * individual axis has been homed.
  1233. *
  1234. * DELTA should wait until all homing is done before setting the XYZ
  1235. * current_position to home, because homing is a single operation.
  1236. * In the case where the axis positions are already known and previously
  1237. * homed, DELTA could home to X or Y individually by moving either one
  1238. * to the center. However, homing Z always homes XY and Z.
  1239. *
  1240. * SCARA should wait until all XY homing is done before setting the XY
  1241. * current_position to home, because neither X nor Y is at home until
  1242. * both are at home. Z can however be homed individually.
  1243. *
  1244. * Callers must sync the planner position after calling this!
  1245. */
  1246. static void set_axis_is_at_home(const AxisEnum axis) {
  1247. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1248. if (DEBUGGING(LEVELING)) {
  1249. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1250. SERIAL_CHAR(')');
  1251. SERIAL_EOL();
  1252. }
  1253. #endif
  1254. axis_known_position[axis] = axis_homed[axis] = true;
  1255. #if HAS_POSITION_SHIFT
  1256. position_shift[axis] = 0;
  1257. update_software_endstops(axis);
  1258. #endif
  1259. #if ENABLED(DUAL_X_CARRIAGE)
  1260. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1261. current_position[X_AXIS] = x_home_pos(active_extruder);
  1262. return;
  1263. }
  1264. #endif
  1265. #if ENABLED(MORGAN_SCARA)
  1266. /**
  1267. * Morgan SCARA homes XY at the same time
  1268. */
  1269. if (axis == X_AXIS || axis == Y_AXIS) {
  1270. float homeposition[XYZ];
  1271. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1272. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1273. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1274. /**
  1275. * Get Home position SCARA arm angles using inverse kinematics,
  1276. * and calculate homing offset using forward kinematics
  1277. */
  1278. inverse_kinematics(homeposition);
  1279. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1280. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1281. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1282. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1283. /**
  1284. * SCARA home positions are based on configuration since the actual
  1285. * limits are determined by the inverse kinematic transform.
  1286. */
  1287. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1288. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1289. }
  1290. else
  1291. #endif
  1292. {
  1293. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1294. }
  1295. /**
  1296. * Z Probe Z Homing? Account for the probe's Z offset.
  1297. */
  1298. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1299. if (axis == Z_AXIS) {
  1300. #if HOMING_Z_WITH_PROBE
  1301. current_position[Z_AXIS] -= zprobe_zoffset;
  1302. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1303. if (DEBUGGING(LEVELING)) {
  1304. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1305. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1306. }
  1307. #endif
  1308. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1309. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1310. #endif
  1311. }
  1312. #endif
  1313. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1314. if (DEBUGGING(LEVELING)) {
  1315. #if HAS_HOME_OFFSET
  1316. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1317. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1318. #endif
  1319. DEBUG_POS("", current_position);
  1320. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1321. SERIAL_CHAR(')');
  1322. SERIAL_EOL();
  1323. }
  1324. #endif
  1325. #if ENABLED(I2C_POSITION_ENCODERS)
  1326. I2CPEM.homed(axis);
  1327. #endif
  1328. }
  1329. /**
  1330. * Some planner shorthand inline functions
  1331. */
  1332. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1333. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1334. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1335. if (hbd < 1) {
  1336. hbd = 10;
  1337. SERIAL_ECHO_START();
  1338. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1339. }
  1340. return homing_feedrate(axis) / hbd;
  1341. }
  1342. /**
  1343. * Move the planner to the current position from wherever it last moved
  1344. * (or from wherever it has been told it is located).
  1345. */
  1346. inline void line_to_current_position() {
  1347. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1348. }
  1349. /**
  1350. * Move the planner to the position stored in the destination array, which is
  1351. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1352. */
  1353. inline void line_to_destination(const float fr_mm_s) {
  1354. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1355. }
  1356. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1357. inline void set_current_to_destination() { COPY(current_position, destination); }
  1358. inline void set_destination_to_current() { COPY(destination, current_position); }
  1359. #if IS_KINEMATIC
  1360. /**
  1361. * Calculate delta, start a line, and set current_position to destination
  1362. */
  1363. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1364. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1365. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1366. #endif
  1367. refresh_cmd_timeout();
  1368. #if UBL_DELTA
  1369. // ubl segmented line will do z-only moves in single segment
  1370. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1371. #else
  1372. if ( current_position[X_AXIS] == destination[X_AXIS]
  1373. && current_position[Y_AXIS] == destination[Y_AXIS]
  1374. && current_position[Z_AXIS] == destination[Z_AXIS]
  1375. && current_position[E_AXIS] == destination[E_AXIS]
  1376. ) return;
  1377. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1378. #endif
  1379. set_current_to_destination();
  1380. }
  1381. #endif // IS_KINEMATIC
  1382. /**
  1383. * Plan a move to (X, Y, Z) and set the current_position
  1384. * The final current_position may not be the one that was requested
  1385. */
  1386. void do_blocking_move_to(const float &lx, const float &ly, const float &lz, const float &fr_mm_s/*=0.0*/) {
  1387. const float old_feedrate_mm_s = feedrate_mm_s;
  1388. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1389. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, lx, ly, lz);
  1390. #endif
  1391. #if ENABLED(DELTA)
  1392. if (!position_is_reachable_xy(lx, ly)) return;
  1393. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1394. set_destination_to_current(); // sync destination at the start
  1395. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1396. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1397. #endif
  1398. // when in the danger zone
  1399. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1400. if (lz > delta_clip_start_height) { // staying in the danger zone
  1401. destination[X_AXIS] = lx; // move directly (uninterpolated)
  1402. destination[Y_AXIS] = ly;
  1403. destination[Z_AXIS] = lz;
  1404. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1405. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1406. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1407. #endif
  1408. return;
  1409. }
  1410. else {
  1411. destination[Z_AXIS] = delta_clip_start_height;
  1412. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1413. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1414. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1415. #endif
  1416. }
  1417. }
  1418. if (lz > current_position[Z_AXIS]) { // raising?
  1419. destination[Z_AXIS] = lz;
  1420. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1421. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1422. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1423. #endif
  1424. }
  1425. destination[X_AXIS] = lx;
  1426. destination[Y_AXIS] = ly;
  1427. prepare_move_to_destination(); // set_current_to_destination
  1428. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1429. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1430. #endif
  1431. if (lz < current_position[Z_AXIS]) { // lowering?
  1432. destination[Z_AXIS] = lz;
  1433. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1434. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1435. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1436. #endif
  1437. }
  1438. #elif IS_SCARA
  1439. if (!position_is_reachable_xy(lx, ly)) return;
  1440. set_destination_to_current();
  1441. // If Z needs to raise, do it before moving XY
  1442. if (destination[Z_AXIS] < lz) {
  1443. destination[Z_AXIS] = lz;
  1444. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1445. }
  1446. destination[X_AXIS] = lx;
  1447. destination[Y_AXIS] = ly;
  1448. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1449. // If Z needs to lower, do it after moving XY
  1450. if (destination[Z_AXIS] > lz) {
  1451. destination[Z_AXIS] = lz;
  1452. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1453. }
  1454. #else
  1455. // If Z needs to raise, do it before moving XY
  1456. if (current_position[Z_AXIS] < lz) {
  1457. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1458. current_position[Z_AXIS] = lz;
  1459. line_to_current_position();
  1460. }
  1461. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1462. current_position[X_AXIS] = lx;
  1463. current_position[Y_AXIS] = ly;
  1464. line_to_current_position();
  1465. // If Z needs to lower, do it after moving XY
  1466. if (current_position[Z_AXIS] > lz) {
  1467. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1468. current_position[Z_AXIS] = lz;
  1469. line_to_current_position();
  1470. }
  1471. #endif
  1472. stepper.synchronize();
  1473. feedrate_mm_s = old_feedrate_mm_s;
  1474. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1475. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1476. #endif
  1477. }
  1478. void do_blocking_move_to_x(const float &lx, const float &fr_mm_s/*=0.0*/) {
  1479. do_blocking_move_to(lx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1480. }
  1481. void do_blocking_move_to_z(const float &lz, const float &fr_mm_s/*=0.0*/) {
  1482. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], lz, fr_mm_s);
  1483. }
  1484. void do_blocking_move_to_xy(const float &lx, const float &ly, const float &fr_mm_s/*=0.0*/) {
  1485. do_blocking_move_to(lx, ly, current_position[Z_AXIS], fr_mm_s);
  1486. }
  1487. //
  1488. // Prepare to do endstop or probe moves
  1489. // with custom feedrates.
  1490. //
  1491. // - Save current feedrates
  1492. // - Reset the rate multiplier
  1493. // - Reset the command timeout
  1494. // - Enable the endstops (for endstop moves)
  1495. //
  1496. static void setup_for_endstop_or_probe_move() {
  1497. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1498. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1499. #endif
  1500. saved_feedrate_mm_s = feedrate_mm_s;
  1501. saved_feedrate_percentage = feedrate_percentage;
  1502. feedrate_percentage = 100;
  1503. refresh_cmd_timeout();
  1504. }
  1505. static void clean_up_after_endstop_or_probe_move() {
  1506. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1507. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1508. #endif
  1509. feedrate_mm_s = saved_feedrate_mm_s;
  1510. feedrate_percentage = saved_feedrate_percentage;
  1511. refresh_cmd_timeout();
  1512. }
  1513. #if HAS_BED_PROBE
  1514. /**
  1515. * Raise Z to a minimum height to make room for a probe to move
  1516. */
  1517. inline void do_probe_raise(const float z_raise) {
  1518. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1519. if (DEBUGGING(LEVELING)) {
  1520. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1521. SERIAL_CHAR(')');
  1522. SERIAL_EOL();
  1523. }
  1524. #endif
  1525. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1526. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1527. #if ENABLED(DELTA)
  1528. z_dest -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1529. #endif
  1530. if (z_dest > current_position[Z_AXIS])
  1531. do_blocking_move_to_z(z_dest);
  1532. }
  1533. #endif // HAS_BED_PROBE
  1534. #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)
  1535. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1536. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1537. const bool xx = x && !axis_known_position[X_AXIS],
  1538. yy = y && !axis_known_position[Y_AXIS],
  1539. zz = z && !axis_known_position[Z_AXIS];
  1540. #else
  1541. const bool xx = x && !axis_homed[X_AXIS],
  1542. yy = y && !axis_homed[Y_AXIS],
  1543. zz = z && !axis_homed[Z_AXIS];
  1544. #endif
  1545. if (xx || yy || zz) {
  1546. SERIAL_ECHO_START();
  1547. SERIAL_ECHOPGM(MSG_HOME " ");
  1548. if (xx) SERIAL_ECHOPGM(MSG_X);
  1549. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1550. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1551. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1552. #if ENABLED(ULTRA_LCD)
  1553. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1554. #endif
  1555. return true;
  1556. }
  1557. return false;
  1558. }
  1559. #endif
  1560. #if ENABLED(Z_PROBE_SLED)
  1561. #ifndef SLED_DOCKING_OFFSET
  1562. #define SLED_DOCKING_OFFSET 0
  1563. #endif
  1564. /**
  1565. * Method to dock/undock a sled designed by Charles Bell.
  1566. *
  1567. * stow[in] If false, move to MAX_X and engage the solenoid
  1568. * If true, move to MAX_X and release the solenoid
  1569. */
  1570. static void dock_sled(bool stow) {
  1571. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1572. if (DEBUGGING(LEVELING)) {
  1573. SERIAL_ECHOPAIR("dock_sled(", stow);
  1574. SERIAL_CHAR(')');
  1575. SERIAL_EOL();
  1576. }
  1577. #endif
  1578. // Dock sled a bit closer to ensure proper capturing
  1579. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1580. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1581. WRITE(SOL1_PIN, !stow); // switch solenoid
  1582. #endif
  1583. }
  1584. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1585. FORCE_INLINE void do_blocking_move_to(const float logical[XYZ], const float &fr_mm_s) {
  1586. do_blocking_move_to(logical[X_AXIS], logical[Y_AXIS], logical[Z_AXIS], fr_mm_s);
  1587. }
  1588. void run_deploy_moves_script() {
  1589. #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)
  1590. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1591. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1592. #endif
  1593. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1594. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1595. #endif
  1596. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1597. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1598. #endif
  1599. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1600. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1601. #endif
  1602. 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 };
  1603. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1604. #endif
  1605. #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)
  1606. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1607. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1608. #endif
  1609. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1610. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1611. #endif
  1612. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1613. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1614. #endif
  1615. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1616. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1617. #endif
  1618. 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 };
  1619. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1620. #endif
  1621. #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)
  1622. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1623. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1624. #endif
  1625. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1626. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1627. #endif
  1628. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1629. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1630. #endif
  1631. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1632. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1633. #endif
  1634. 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 };
  1635. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1636. #endif
  1637. #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)
  1638. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1639. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1640. #endif
  1641. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1642. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1643. #endif
  1644. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1645. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1646. #endif
  1647. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1648. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1649. #endif
  1650. 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 };
  1651. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1652. #endif
  1653. #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)
  1654. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1655. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1656. #endif
  1657. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1658. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1659. #endif
  1660. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1661. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1662. #endif
  1663. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1664. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1665. #endif
  1666. 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 };
  1667. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1668. #endif
  1669. }
  1670. void run_stow_moves_script() {
  1671. #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)
  1672. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1673. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1674. #endif
  1675. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1676. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1677. #endif
  1678. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1679. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1680. #endif
  1681. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1682. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1683. #endif
  1684. 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 };
  1685. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1686. #endif
  1687. #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)
  1688. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1689. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1690. #endif
  1691. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1692. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1693. #endif
  1694. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1695. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1696. #endif
  1697. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1698. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1699. #endif
  1700. 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 };
  1701. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1702. #endif
  1703. #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)
  1704. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1705. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1706. #endif
  1707. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1708. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1709. #endif
  1710. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1711. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1712. #endif
  1713. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1714. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1715. #endif
  1716. 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 };
  1717. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1718. #endif
  1719. #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)
  1720. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1721. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1722. #endif
  1723. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1724. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1725. #endif
  1726. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1727. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1728. #endif
  1729. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1730. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1731. #endif
  1732. 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 };
  1733. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1734. #endif
  1735. #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)
  1736. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1737. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1738. #endif
  1739. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1740. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1741. #endif
  1742. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1743. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1744. #endif
  1745. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1746. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1747. #endif
  1748. 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 };
  1749. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1750. #endif
  1751. }
  1752. #endif
  1753. #if ENABLED(PROBING_FANS_OFF)
  1754. void fans_pause(const bool p) {
  1755. if (p != fans_paused) {
  1756. fans_paused = p;
  1757. if (p)
  1758. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1759. paused_fanSpeeds[x] = fanSpeeds[x];
  1760. fanSpeeds[x] = 0;
  1761. }
  1762. else
  1763. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1764. fanSpeeds[x] = paused_fanSpeeds[x];
  1765. }
  1766. }
  1767. #endif // PROBING_FANS_OFF
  1768. #if HAS_BED_PROBE
  1769. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1770. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1771. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1772. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1773. #else
  1774. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1775. #endif
  1776. #endif
  1777. #if QUIET_PROBING
  1778. void probing_pause(const bool p) {
  1779. #if ENABLED(PROBING_HEATERS_OFF)
  1780. thermalManager.pause(p);
  1781. #endif
  1782. #if ENABLED(PROBING_FANS_OFF)
  1783. fans_pause(p);
  1784. #endif
  1785. if (p) safe_delay(25);
  1786. }
  1787. #endif // QUIET_PROBING
  1788. #if ENABLED(BLTOUCH)
  1789. void bltouch_command(int angle) {
  1790. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1791. safe_delay(BLTOUCH_DELAY);
  1792. }
  1793. void set_bltouch_deployed(const bool deploy) {
  1794. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1795. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1796. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1797. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1798. safe_delay(1500); // Wait for internal self-test to complete.
  1799. // (Measured completion time was 0.65 seconds
  1800. // after reset, deploy, and stow sequence)
  1801. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1802. SERIAL_ERROR_START();
  1803. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1804. stop(); // punt!
  1805. }
  1806. }
  1807. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1808. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1809. if (DEBUGGING(LEVELING)) {
  1810. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1811. SERIAL_CHAR(')');
  1812. SERIAL_EOL();
  1813. }
  1814. #endif
  1815. }
  1816. #endif // BLTOUCH
  1817. // returns false for ok and true for failure
  1818. bool set_probe_deployed(bool deploy) {
  1819. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1820. if (DEBUGGING(LEVELING)) {
  1821. DEBUG_POS("set_probe_deployed", current_position);
  1822. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1823. }
  1824. #endif
  1825. if (endstops.z_probe_enabled == deploy) return false;
  1826. // Make room for probe
  1827. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1828. // When deploying make sure BLTOUCH is not already triggered
  1829. #if ENABLED(BLTOUCH)
  1830. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1831. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1832. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1833. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1834. safe_delay(1500); // wait for internal self test to complete
  1835. // measured completion time was 0.65 seconds
  1836. // after reset, deploy & stow sequence
  1837. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1838. SERIAL_ERROR_START();
  1839. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1840. stop(); // punt!
  1841. return true;
  1842. }
  1843. }
  1844. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1845. #if ENABLED(Z_PROBE_SLED)
  1846. #define _AUE_ARGS true, false, false
  1847. #else
  1848. #define _AUE_ARGS
  1849. #endif
  1850. if (axis_unhomed_error(_AUE_ARGS)) {
  1851. SERIAL_ERROR_START();
  1852. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1853. stop();
  1854. return true;
  1855. }
  1856. #endif
  1857. const float oldXpos = current_position[X_AXIS],
  1858. oldYpos = current_position[Y_AXIS];
  1859. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1860. // If endstop is already false, the Z probe is deployed
  1861. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1862. // Would a goto be less ugly?
  1863. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1864. // for a triggered when stowed manual probe.
  1865. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1866. // otherwise an Allen-Key probe can't be stowed.
  1867. #endif
  1868. #if ENABLED(SOLENOID_PROBE)
  1869. #if HAS_SOLENOID_1
  1870. WRITE(SOL1_PIN, deploy);
  1871. #endif
  1872. #elif ENABLED(Z_PROBE_SLED)
  1873. dock_sled(!deploy);
  1874. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1875. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1876. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1877. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1878. #endif
  1879. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1880. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1881. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1882. if (IsRunning()) {
  1883. SERIAL_ERROR_START();
  1884. SERIAL_ERRORLNPGM("Z-Probe failed");
  1885. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1886. }
  1887. stop();
  1888. return true;
  1889. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1890. #endif
  1891. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1892. endstops.enable_z_probe(deploy);
  1893. return false;
  1894. }
  1895. static void do_probe_move(float z, float fr_mm_m) {
  1896. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1897. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1898. #endif
  1899. // Deploy BLTouch at the start of any probe
  1900. #if ENABLED(BLTOUCH)
  1901. set_bltouch_deployed(true);
  1902. #endif
  1903. #if QUIET_PROBING
  1904. probing_pause(true);
  1905. #endif
  1906. // Move down until probe triggered
  1907. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1908. #if QUIET_PROBING
  1909. probing_pause(false);
  1910. #endif
  1911. // Retract BLTouch immediately after a probe
  1912. #if ENABLED(BLTOUCH)
  1913. set_bltouch_deployed(false);
  1914. #endif
  1915. // Clear endstop flags
  1916. endstops.hit_on_purpose();
  1917. // Get Z where the steppers were interrupted
  1918. set_current_from_steppers_for_axis(Z_AXIS);
  1919. // Tell the planner where we actually are
  1920. SYNC_PLAN_POSITION_KINEMATIC();
  1921. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1922. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1923. #endif
  1924. }
  1925. // Do a single Z probe and return with current_position[Z_AXIS]
  1926. // at the height where the probe triggered.
  1927. static float run_z_probe() {
  1928. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1929. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1930. #endif
  1931. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1932. refresh_cmd_timeout();
  1933. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1934. // Do a first probe at the fast speed
  1935. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1936. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1937. float first_probe_z = current_position[Z_AXIS];
  1938. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1939. #endif
  1940. // move up by the bump distance
  1941. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1942. #else
  1943. // If the nozzle is above the travel height then
  1944. // move down quickly before doing the slow probe
  1945. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1946. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1947. #if ENABLED(DELTA)
  1948. z -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1949. #endif
  1950. if (z < current_position[Z_AXIS])
  1951. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1952. #endif
  1953. // move down slowly to find bed
  1954. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1955. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1956. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1957. #endif
  1958. // Debug: compare probe heights
  1959. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1960. if (DEBUGGING(LEVELING)) {
  1961. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1962. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1963. }
  1964. #endif
  1965. return RAW_CURRENT_POSITION(Z) + zprobe_zoffset
  1966. #if ENABLED(DELTA)
  1967. + home_offset[Z_AXIS] // Account for delta height adjustment
  1968. #endif
  1969. ;
  1970. }
  1971. /**
  1972. * - Move to the given XY
  1973. * - Deploy the probe, if not already deployed
  1974. * - Probe the bed, get the Z position
  1975. * - Depending on the 'stow' flag
  1976. * - Stow the probe, or
  1977. * - Raise to the BETWEEN height
  1978. * - Return the probed Z position
  1979. */
  1980. float probe_pt(const float &x, const float &y, const bool stow/*=true*/, const int verbose_level/*=1*/) {
  1981. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1982. if (DEBUGGING(LEVELING)) {
  1983. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1984. SERIAL_ECHOPAIR(", ", y);
  1985. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1986. SERIAL_ECHOLNPGM("stow)");
  1987. DEBUG_POS("", current_position);
  1988. }
  1989. #endif
  1990. if (!position_is_reachable_by_probe_xy(x, y)) return NAN;
  1991. const float old_feedrate_mm_s = feedrate_mm_s;
  1992. #if ENABLED(DELTA)
  1993. if (current_position[Z_AXIS] > delta_clip_start_height)
  1994. do_blocking_move_to_z(delta_clip_start_height);
  1995. #endif
  1996. // Ensure a minimum height before moving the probe
  1997. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1998. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1999. // Move the probe to the given XY
  2000. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  2001. if (DEPLOY_PROBE()) return NAN;
  2002. const float measured_z = run_z_probe();
  2003. if (!stow)
  2004. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  2005. else
  2006. if (STOW_PROBE()) return NAN;
  2007. if (verbose_level > 2) {
  2008. SERIAL_PROTOCOLPGM("Bed X: ");
  2009. SERIAL_PROTOCOL_F(x, 3);
  2010. SERIAL_PROTOCOLPGM(" Y: ");
  2011. SERIAL_PROTOCOL_F(y, 3);
  2012. SERIAL_PROTOCOLPGM(" Z: ");
  2013. SERIAL_PROTOCOL_F(measured_z, 3);
  2014. SERIAL_EOL();
  2015. }
  2016. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2017. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2018. #endif
  2019. feedrate_mm_s = old_feedrate_mm_s;
  2020. return measured_z;
  2021. }
  2022. #endif // HAS_BED_PROBE
  2023. #if HAS_LEVELING
  2024. bool leveling_is_valid() {
  2025. return
  2026. #if ENABLED(MESH_BED_LEVELING)
  2027. mbl.has_mesh()
  2028. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2029. !!bilinear_grid_spacing[X_AXIS]
  2030. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2031. true
  2032. #else // 3POINT, LINEAR
  2033. true
  2034. #endif
  2035. ;
  2036. }
  2037. bool leveling_is_active() {
  2038. return
  2039. #if ENABLED(MESH_BED_LEVELING)
  2040. mbl.active()
  2041. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2042. ubl.state.active
  2043. #else
  2044. planner.abl_enabled
  2045. #endif
  2046. ;
  2047. }
  2048. /**
  2049. * Turn bed leveling on or off, fixing the current
  2050. * position as-needed.
  2051. *
  2052. * Disable: Current position = physical position
  2053. * Enable: Current position = "unleveled" physical position
  2054. */
  2055. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2056. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2057. const bool can_change = (!enable || leveling_is_valid());
  2058. #else
  2059. constexpr bool can_change = true;
  2060. #endif
  2061. if (can_change && enable != leveling_is_active()) {
  2062. #if ENABLED(MESH_BED_LEVELING)
  2063. if (!enable)
  2064. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2065. const bool enabling = enable && leveling_is_valid();
  2066. mbl.set_active(enabling);
  2067. if (enabling) planner.unapply_leveling(current_position);
  2068. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2069. #if PLANNER_LEVELING
  2070. if (ubl.state.active) { // leveling from on to off
  2071. // change unleveled current_position to physical current_position without moving steppers.
  2072. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2073. ubl.state.active = false; // disable only AFTER calling apply_leveling
  2074. }
  2075. else { // leveling from off to on
  2076. ubl.state.active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2077. // change physical current_position to unleveled current_position without moving steppers.
  2078. planner.unapply_leveling(current_position);
  2079. }
  2080. #else
  2081. ubl.state.active = enable; // just flip the bit, current_position will be wrong until next move.
  2082. #endif
  2083. #else // ABL
  2084. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2085. // Force bilinear_z_offset to re-calculate next time
  2086. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2087. (void)bilinear_z_offset(reset);
  2088. #endif
  2089. // Enable or disable leveling compensation in the planner
  2090. planner.abl_enabled = enable;
  2091. if (!enable)
  2092. // When disabling just get the current position from the steppers.
  2093. // This will yield the smallest error when first converted back to steps.
  2094. set_current_from_steppers_for_axis(
  2095. #if ABL_PLANAR
  2096. ALL_AXES
  2097. #else
  2098. Z_AXIS
  2099. #endif
  2100. );
  2101. else
  2102. // When enabling, remove compensation from the current position,
  2103. // so compensation will give the right stepper counts.
  2104. planner.unapply_leveling(current_position);
  2105. #endif // ABL
  2106. }
  2107. }
  2108. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2109. void set_z_fade_height(const float zfh) {
  2110. const bool level_active = leveling_is_active();
  2111. #if ENABLED(AUTO_BED_LEVELING_UBL)
  2112. if (level_active)
  2113. set_bed_leveling_enabled(false); // turn off before changing fade height for proper apply/unapply leveling to maintain current_position
  2114. planner.z_fade_height = zfh;
  2115. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2116. if (level_active)
  2117. set_bed_leveling_enabled(true); // turn back on after changing fade height
  2118. #else
  2119. planner.z_fade_height = zfh;
  2120. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2121. if (level_active) {
  2122. set_current_from_steppers_for_axis(
  2123. #if ABL_PLANAR
  2124. ALL_AXES
  2125. #else
  2126. Z_AXIS
  2127. #endif
  2128. );
  2129. }
  2130. #endif
  2131. }
  2132. #endif // LEVELING_FADE_HEIGHT
  2133. /**
  2134. * Reset calibration results to zero.
  2135. */
  2136. void reset_bed_level() {
  2137. set_bed_leveling_enabled(false);
  2138. #if ENABLED(MESH_BED_LEVELING)
  2139. if (leveling_is_valid()) {
  2140. mbl.reset();
  2141. mbl.set_has_mesh(false);
  2142. }
  2143. #else
  2144. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2145. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2146. #endif
  2147. #if ABL_PLANAR
  2148. planner.bed_level_matrix.set_to_identity();
  2149. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2150. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2151. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2152. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2153. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2154. z_values[x][y] = NAN;
  2155. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2156. ubl.reset();
  2157. #endif
  2158. #endif
  2159. }
  2160. #endif // HAS_LEVELING
  2161. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2162. /**
  2163. * Enable to produce output in JSON format suitable
  2164. * for SCAD or JavaScript mesh visualizers.
  2165. *
  2166. * Visualize meshes in OpenSCAD using the included script.
  2167. *
  2168. * buildroot/shared/scripts/MarlinMesh.scad
  2169. */
  2170. //#define SCAD_MESH_OUTPUT
  2171. /**
  2172. * Print calibration results for plotting or manual frame adjustment.
  2173. */
  2174. 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)) {
  2175. #ifndef SCAD_MESH_OUTPUT
  2176. for (uint8_t x = 0; x < sx; x++) {
  2177. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2178. SERIAL_PROTOCOLCHAR(' ');
  2179. SERIAL_PROTOCOL((int)x);
  2180. }
  2181. SERIAL_EOL();
  2182. #endif
  2183. #ifdef SCAD_MESH_OUTPUT
  2184. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2185. #endif
  2186. for (uint8_t y = 0; y < sy; y++) {
  2187. #ifdef SCAD_MESH_OUTPUT
  2188. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2189. #else
  2190. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2191. SERIAL_PROTOCOL((int)y);
  2192. #endif
  2193. for (uint8_t x = 0; x < sx; x++) {
  2194. SERIAL_PROTOCOLCHAR(' ');
  2195. const float offset = fn(x, y);
  2196. if (!isnan(offset)) {
  2197. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2198. SERIAL_PROTOCOL_F(offset, precision);
  2199. }
  2200. else {
  2201. #ifdef SCAD_MESH_OUTPUT
  2202. for (uint8_t i = 3; i < precision + 3; i++)
  2203. SERIAL_PROTOCOLCHAR(' ');
  2204. SERIAL_PROTOCOLPGM("NAN");
  2205. #else
  2206. for (uint8_t i = 0; i < precision + 3; i++)
  2207. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2208. #endif
  2209. }
  2210. #ifdef SCAD_MESH_OUTPUT
  2211. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2212. #endif
  2213. }
  2214. #ifdef SCAD_MESH_OUTPUT
  2215. SERIAL_PROTOCOLCHAR(' ');
  2216. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2217. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2218. #endif
  2219. SERIAL_EOL();
  2220. }
  2221. #ifdef SCAD_MESH_OUTPUT
  2222. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2223. #endif
  2224. SERIAL_EOL();
  2225. }
  2226. #endif
  2227. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2228. /**
  2229. * Extrapolate a single point from its neighbors
  2230. */
  2231. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2233. if (DEBUGGING(LEVELING)) {
  2234. SERIAL_ECHOPGM("Extrapolate [");
  2235. if (x < 10) SERIAL_CHAR(' ');
  2236. SERIAL_ECHO((int)x);
  2237. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2238. SERIAL_CHAR(' ');
  2239. if (y < 10) SERIAL_CHAR(' ');
  2240. SERIAL_ECHO((int)y);
  2241. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2242. SERIAL_CHAR(']');
  2243. }
  2244. #endif
  2245. if (!isnan(z_values[x][y])) {
  2246. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2247. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2248. #endif
  2249. return; // Don't overwrite good values.
  2250. }
  2251. SERIAL_EOL();
  2252. // Get X neighbors, Y neighbors, and XY neighbors
  2253. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2254. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2255. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2256. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2257. // Treat far unprobed points as zero, near as equal to far
  2258. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2259. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2260. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2261. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2262. // Take the average instead of the median
  2263. z_values[x][y] = (a + b + c) / 3.0;
  2264. // Median is robust (ignores outliers).
  2265. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2266. // : ((c < b) ? b : (a < c) ? a : c);
  2267. }
  2268. //Enable this if your SCARA uses 180° of total area
  2269. //#define EXTRAPOLATE_FROM_EDGE
  2270. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2271. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2272. #define HALF_IN_X
  2273. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2274. #define HALF_IN_Y
  2275. #endif
  2276. #endif
  2277. /**
  2278. * Fill in the unprobed points (corners of circular print surface)
  2279. * using linear extrapolation, away from the center.
  2280. */
  2281. static void extrapolate_unprobed_bed_level() {
  2282. #ifdef HALF_IN_X
  2283. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2284. #else
  2285. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2286. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2287. xlen = ctrx1;
  2288. #endif
  2289. #ifdef HALF_IN_Y
  2290. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2291. #else
  2292. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2293. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2294. ylen = ctry1;
  2295. #endif
  2296. for (uint8_t xo = 0; xo <= xlen; xo++)
  2297. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2298. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2299. #ifndef HALF_IN_X
  2300. const uint8_t x1 = ctrx1 - xo;
  2301. #endif
  2302. #ifndef HALF_IN_Y
  2303. const uint8_t y1 = ctry1 - yo;
  2304. #ifndef HALF_IN_X
  2305. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2306. #endif
  2307. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2308. #endif
  2309. #ifndef HALF_IN_X
  2310. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2311. #endif
  2312. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2313. }
  2314. }
  2315. static void print_bilinear_leveling_grid() {
  2316. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2317. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2318. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2319. );
  2320. }
  2321. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2322. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2323. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2324. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2325. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2326. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2327. int bilinear_grid_spacing_virt[2] = { 0 };
  2328. float bilinear_grid_factor_virt[2] = { 0 };
  2329. static void bed_level_virt_print() {
  2330. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2331. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2332. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2333. );
  2334. }
  2335. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2336. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2337. uint8_t ep = 0, ip = 1;
  2338. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2339. if (x) {
  2340. ep = GRID_MAX_POINTS_X - 1;
  2341. ip = GRID_MAX_POINTS_X - 2;
  2342. }
  2343. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2344. return LINEAR_EXTRAPOLATION(
  2345. z_values[ep][y - 1],
  2346. z_values[ip][y - 1]
  2347. );
  2348. else
  2349. return LINEAR_EXTRAPOLATION(
  2350. bed_level_virt_coord(ep + 1, y),
  2351. bed_level_virt_coord(ip + 1, y)
  2352. );
  2353. }
  2354. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2355. if (y) {
  2356. ep = GRID_MAX_POINTS_Y - 1;
  2357. ip = GRID_MAX_POINTS_Y - 2;
  2358. }
  2359. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2360. return LINEAR_EXTRAPOLATION(
  2361. z_values[x - 1][ep],
  2362. z_values[x - 1][ip]
  2363. );
  2364. else
  2365. return LINEAR_EXTRAPOLATION(
  2366. bed_level_virt_coord(x, ep + 1),
  2367. bed_level_virt_coord(x, ip + 1)
  2368. );
  2369. }
  2370. return z_values[x - 1][y - 1];
  2371. }
  2372. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2373. return (
  2374. p[i-1] * -t * sq(1 - t)
  2375. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2376. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2377. - p[i+2] * sq(t) * (1 - t)
  2378. ) * 0.5;
  2379. }
  2380. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2381. float row[4], column[4];
  2382. for (uint8_t i = 0; i < 4; i++) {
  2383. for (uint8_t j = 0; j < 4; j++) {
  2384. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2385. }
  2386. row[i] = bed_level_virt_cmr(column, 1, ty);
  2387. }
  2388. return bed_level_virt_cmr(row, 1, tx);
  2389. }
  2390. void bed_level_virt_interpolate() {
  2391. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2392. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2393. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2394. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2395. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2396. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2397. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2398. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2399. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2400. continue;
  2401. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2402. bed_level_virt_2cmr(
  2403. x + 1,
  2404. y + 1,
  2405. (float)tx / (BILINEAR_SUBDIVISIONS),
  2406. (float)ty / (BILINEAR_SUBDIVISIONS)
  2407. );
  2408. }
  2409. }
  2410. #endif // ABL_BILINEAR_SUBDIVISION
  2411. // Refresh after other values have been updated
  2412. void refresh_bed_level() {
  2413. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2414. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2415. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2416. bed_level_virt_interpolate();
  2417. #endif
  2418. }
  2419. #endif // AUTO_BED_LEVELING_BILINEAR
  2420. /**
  2421. * Home an individual linear axis
  2422. */
  2423. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0.0) {
  2424. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2425. if (DEBUGGING(LEVELING)) {
  2426. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2427. SERIAL_ECHOPAIR(", ", distance);
  2428. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2429. SERIAL_CHAR(')');
  2430. SERIAL_EOL();
  2431. }
  2432. #endif
  2433. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2434. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2435. if (deploy_bltouch) set_bltouch_deployed(true);
  2436. #endif
  2437. #if QUIET_PROBING
  2438. if (axis == Z_AXIS) probing_pause(true);
  2439. #endif
  2440. // Tell the planner we're at Z=0
  2441. current_position[axis] = 0;
  2442. #if IS_SCARA
  2443. SYNC_PLAN_POSITION_KINEMATIC();
  2444. current_position[axis] = distance;
  2445. inverse_kinematics(current_position);
  2446. 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);
  2447. #else
  2448. sync_plan_position();
  2449. current_position[axis] = distance;
  2450. 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);
  2451. #endif
  2452. stepper.synchronize();
  2453. #if QUIET_PROBING
  2454. if (axis == Z_AXIS) probing_pause(false);
  2455. #endif
  2456. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2457. if (deploy_bltouch) set_bltouch_deployed(false);
  2458. #endif
  2459. endstops.hit_on_purpose();
  2460. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2461. if (DEBUGGING(LEVELING)) {
  2462. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2463. SERIAL_CHAR(')');
  2464. SERIAL_EOL();
  2465. }
  2466. #endif
  2467. }
  2468. /**
  2469. * TMC2130 specific sensorless homing using stallGuard2.
  2470. * stallGuard2 only works when in spreadCycle mode.
  2471. * spreadCycle and stealthChop are mutually exclusive.
  2472. */
  2473. #if ENABLED(SENSORLESS_HOMING)
  2474. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2475. #if ENABLED(STEALTHCHOP)
  2476. if (enable) {
  2477. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2478. st.stealthChop(0);
  2479. }
  2480. else {
  2481. st.coolstep_min_speed(0);
  2482. st.stealthChop(1);
  2483. }
  2484. #endif
  2485. st.diag1_stall(enable ? 1 : 0);
  2486. }
  2487. #endif
  2488. /**
  2489. * Home an individual "raw axis" to its endstop.
  2490. * This applies to XYZ on Cartesian and Core robots, and
  2491. * to the individual ABC steppers on DELTA and SCARA.
  2492. *
  2493. * At the end of the procedure the axis is marked as
  2494. * homed and the current position of that axis is updated.
  2495. * Kinematic robots should wait till all axes are homed
  2496. * before updating the current position.
  2497. */
  2498. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2499. static void homeaxis(const AxisEnum axis) {
  2500. #if IS_SCARA
  2501. // Only Z homing (with probe) is permitted
  2502. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2503. #else
  2504. #define CAN_HOME(A) \
  2505. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2506. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2507. #endif
  2508. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2509. if (DEBUGGING(LEVELING)) {
  2510. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2511. SERIAL_CHAR(')');
  2512. SERIAL_EOL();
  2513. }
  2514. #endif
  2515. const int axis_home_dir =
  2516. #if ENABLED(DUAL_X_CARRIAGE)
  2517. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2518. #endif
  2519. home_dir(axis);
  2520. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2521. #if HOMING_Z_WITH_PROBE
  2522. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2523. #endif
  2524. // Set a flag for Z motor locking
  2525. #if ENABLED(Z_DUAL_ENDSTOPS)
  2526. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2527. #endif
  2528. // Disable stealthChop if used. Enable diag1 pin on driver.
  2529. #if ENABLED(SENSORLESS_HOMING)
  2530. #if ENABLED(X_IS_TMC2130)
  2531. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2532. #endif
  2533. #if ENABLED(Y_IS_TMC2130)
  2534. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2535. #endif
  2536. #endif
  2537. // Fast move towards endstop until triggered
  2538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2539. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2540. #endif
  2541. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2542. // When homing Z with probe respect probe clearance
  2543. const float bump = axis_home_dir * (
  2544. #if HOMING_Z_WITH_PROBE
  2545. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2546. #endif
  2547. home_bump_mm(axis)
  2548. );
  2549. // If a second homing move is configured...
  2550. if (bump) {
  2551. // Move away from the endstop by the axis HOME_BUMP_MM
  2552. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2553. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2554. #endif
  2555. do_homing_move(axis, -bump);
  2556. // Slow move towards endstop until triggered
  2557. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2558. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2559. #endif
  2560. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2561. }
  2562. #if ENABLED(Z_DUAL_ENDSTOPS)
  2563. if (axis == Z_AXIS) {
  2564. float adj = FABS(z_endstop_adj);
  2565. bool lockZ1;
  2566. if (axis_home_dir > 0) {
  2567. adj = -adj;
  2568. lockZ1 = (z_endstop_adj > 0);
  2569. }
  2570. else
  2571. lockZ1 = (z_endstop_adj < 0);
  2572. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2573. // Move to the adjusted endstop height
  2574. do_homing_move(axis, adj);
  2575. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2576. stepper.set_homing_flag(false);
  2577. } // Z_AXIS
  2578. #endif
  2579. #if IS_SCARA
  2580. set_axis_is_at_home(axis);
  2581. SYNC_PLAN_POSITION_KINEMATIC();
  2582. #elif ENABLED(DELTA)
  2583. // Delta has already moved all three towers up in G28
  2584. // so here it re-homes each tower in turn.
  2585. // Delta homing treats the axes as normal linear axes.
  2586. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2587. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2588. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2589. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2590. #endif
  2591. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2592. }
  2593. #else
  2594. // For cartesian/core machines,
  2595. // set the axis to its home position
  2596. set_axis_is_at_home(axis);
  2597. sync_plan_position();
  2598. destination[axis] = current_position[axis];
  2599. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2600. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2601. #endif
  2602. #endif
  2603. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2604. #if ENABLED(SENSORLESS_HOMING)
  2605. #if ENABLED(X_IS_TMC2130)
  2606. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2607. #endif
  2608. #if ENABLED(Y_IS_TMC2130)
  2609. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2610. #endif
  2611. #endif
  2612. // Put away the Z probe
  2613. #if HOMING_Z_WITH_PROBE
  2614. if (axis == Z_AXIS && STOW_PROBE()) return;
  2615. #endif
  2616. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2617. if (DEBUGGING(LEVELING)) {
  2618. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2619. SERIAL_CHAR(')');
  2620. SERIAL_EOL();
  2621. }
  2622. #endif
  2623. } // homeaxis()
  2624. #if ENABLED(FWRETRACT)
  2625. void retract(const bool retracting, const bool swapping = false) {
  2626. static float hop_height;
  2627. if (retracting == retracted[active_extruder]) return;
  2628. const float old_feedrate_mm_s = feedrate_mm_s;
  2629. set_destination_to_current();
  2630. if (retracting) {
  2631. feedrate_mm_s = retract_feedrate_mm_s;
  2632. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2633. sync_plan_position_e();
  2634. prepare_move_to_destination();
  2635. if (retract_zlift > 0.01) {
  2636. hop_height = current_position[Z_AXIS];
  2637. // Pretend current position is lower
  2638. current_position[Z_AXIS] -= retract_zlift;
  2639. SYNC_PLAN_POSITION_KINEMATIC();
  2640. // Raise up to the old current_position
  2641. prepare_move_to_destination();
  2642. }
  2643. }
  2644. else {
  2645. // If the height hasn't been lowered, undo the Z hop
  2646. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2647. // Pretend current position is higher. Z will lower on the next move
  2648. current_position[Z_AXIS] += retract_zlift;
  2649. SYNC_PLAN_POSITION_KINEMATIC();
  2650. // Lower Z
  2651. prepare_move_to_destination();
  2652. }
  2653. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2654. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2655. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2656. sync_plan_position_e();
  2657. // Recover E
  2658. prepare_move_to_destination();
  2659. }
  2660. feedrate_mm_s = old_feedrate_mm_s;
  2661. retracted[active_extruder] = retracting;
  2662. } // retract()
  2663. #endif // FWRETRACT
  2664. #if ENABLED(MIXING_EXTRUDER)
  2665. void normalize_mix() {
  2666. float mix_total = 0.0;
  2667. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2668. // Scale all values if they don't add up to ~1.0
  2669. if (!NEAR(mix_total, 1.0)) {
  2670. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2671. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2672. }
  2673. }
  2674. #if ENABLED(DIRECT_MIXING_IN_G1)
  2675. // Get mixing parameters from the GCode
  2676. // The total "must" be 1.0 (but it will be normalized)
  2677. // If no mix factors are given, the old mix is preserved
  2678. void gcode_get_mix() {
  2679. const char* mixing_codes = "ABCDHI";
  2680. byte mix_bits = 0;
  2681. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2682. if (parser.seenval(mixing_codes[i])) {
  2683. SBI(mix_bits, i);
  2684. float v = parser.value_float();
  2685. NOLESS(v, 0.0);
  2686. mixing_factor[i] = RECIPROCAL(v);
  2687. }
  2688. }
  2689. // If any mixing factors were included, clear the rest
  2690. // If none were included, preserve the last mix
  2691. if (mix_bits) {
  2692. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2693. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2694. normalize_mix();
  2695. }
  2696. }
  2697. #endif
  2698. #endif
  2699. /**
  2700. * ***************************************************************************
  2701. * ***************************** G-CODE HANDLING *****************************
  2702. * ***************************************************************************
  2703. */
  2704. /**
  2705. * Set XYZE destination and feedrate from the current GCode command
  2706. *
  2707. * - Set destination from included axis codes
  2708. * - Set to current for missing axis codes
  2709. * - Set the feedrate, if included
  2710. */
  2711. void gcode_get_destination() {
  2712. LOOP_XYZE(i) {
  2713. if (parser.seen(axis_codes[i]))
  2714. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2715. else
  2716. destination[i] = current_position[i];
  2717. }
  2718. if (parser.linearval('F') > 0.0)
  2719. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2720. #if ENABLED(PRINTCOUNTER)
  2721. if (!DEBUGGING(DRYRUN))
  2722. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2723. #endif
  2724. // Get ABCDHI mixing factors
  2725. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2726. gcode_get_mix();
  2727. #endif
  2728. }
  2729. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2730. /**
  2731. * Output a "busy" message at regular intervals
  2732. * while the machine is not accepting commands.
  2733. */
  2734. void host_keepalive() {
  2735. const millis_t ms = millis();
  2736. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2737. if (PENDING(ms, next_busy_signal_ms)) return;
  2738. switch (busy_state) {
  2739. case IN_HANDLER:
  2740. case IN_PROCESS:
  2741. SERIAL_ECHO_START();
  2742. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2743. break;
  2744. case PAUSED_FOR_USER:
  2745. SERIAL_ECHO_START();
  2746. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2747. break;
  2748. case PAUSED_FOR_INPUT:
  2749. SERIAL_ECHO_START();
  2750. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2751. break;
  2752. default:
  2753. break;
  2754. }
  2755. }
  2756. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2757. }
  2758. #endif // HOST_KEEPALIVE_FEATURE
  2759. /**************************************************
  2760. ***************** GCode Handlers *****************
  2761. **************************************************/
  2762. /**
  2763. * G0, G1: Coordinated movement of X Y Z E axes
  2764. */
  2765. inline void gcode_G0_G1(
  2766. #if IS_SCARA
  2767. bool fast_move=false
  2768. #endif
  2769. ) {
  2770. if (IsRunning()) {
  2771. gcode_get_destination(); // For X Y Z E F
  2772. #if ENABLED(FWRETRACT)
  2773. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2774. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2775. // Is this move an attempt to retract or recover?
  2776. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2777. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2778. sync_plan_position_e(); // AND from the planner
  2779. retract(!retracted[active_extruder]);
  2780. return;
  2781. }
  2782. }
  2783. #endif // FWRETRACT
  2784. #if IS_SCARA
  2785. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2786. #else
  2787. prepare_move_to_destination();
  2788. #endif
  2789. }
  2790. }
  2791. /**
  2792. * G2: Clockwise Arc
  2793. * G3: Counterclockwise Arc
  2794. *
  2795. * This command has two forms: IJ-form and R-form.
  2796. *
  2797. * - I specifies an X offset. J specifies a Y offset.
  2798. * At least one of the IJ parameters is required.
  2799. * X and Y can be omitted to do a complete circle.
  2800. * The given XY is not error-checked. The arc ends
  2801. * based on the angle of the destination.
  2802. * Mixing I or J with R will throw an error.
  2803. *
  2804. * - R specifies the radius. X or Y is required.
  2805. * Omitting both X and Y will throw an error.
  2806. * X or Y must differ from the current XY.
  2807. * Mixing R with I or J will throw an error.
  2808. *
  2809. * - P specifies the number of full circles to do
  2810. * before the specified arc move.
  2811. *
  2812. * Examples:
  2813. *
  2814. * G2 I10 ; CW circle centered at X+10
  2815. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2816. */
  2817. #if ENABLED(ARC_SUPPORT)
  2818. inline void gcode_G2_G3(bool clockwise) {
  2819. if (IsRunning()) {
  2820. #if ENABLED(SF_ARC_FIX)
  2821. const bool relative_mode_backup = relative_mode;
  2822. relative_mode = true;
  2823. #endif
  2824. gcode_get_destination();
  2825. #if ENABLED(SF_ARC_FIX)
  2826. relative_mode = relative_mode_backup;
  2827. #endif
  2828. float arc_offset[2] = { 0.0, 0.0 };
  2829. if (parser.seenval('R')) {
  2830. const float r = parser.value_linear_units(),
  2831. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  2832. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  2833. if (r && (p2 != p1 || q2 != q1)) {
  2834. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2835. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  2836. d = HYPOT(dx, dy), // Linear distance between the points
  2837. h = SQRT(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2838. mx = (p1 + p2) * 0.5, my = (q1 + q2) * 0.5, // Point between the two points
  2839. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2840. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2841. arc_offset[0] = cx - p1;
  2842. arc_offset[1] = cy - q1;
  2843. }
  2844. }
  2845. else {
  2846. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  2847. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  2848. }
  2849. if (arc_offset[0] || arc_offset[1]) {
  2850. #if ENABLED(ARC_P_CIRCLES)
  2851. // P indicates number of circles to do
  2852. int8_t circles_to_do = parser.byteval('P');
  2853. if (!WITHIN(circles_to_do, 0, 100)) {
  2854. SERIAL_ERROR_START();
  2855. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2856. }
  2857. while (circles_to_do--)
  2858. plan_arc(current_position, arc_offset, clockwise);
  2859. #endif
  2860. // Send the arc to the planner
  2861. plan_arc(destination, arc_offset, clockwise);
  2862. refresh_cmd_timeout();
  2863. }
  2864. else {
  2865. // Bad arguments
  2866. SERIAL_ERROR_START();
  2867. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2868. }
  2869. }
  2870. }
  2871. #endif // ARC_SUPPORT
  2872. /**
  2873. * G4: Dwell S<seconds> or P<milliseconds>
  2874. */
  2875. inline void gcode_G4() {
  2876. millis_t dwell_ms = 0;
  2877. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2878. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2879. stepper.synchronize();
  2880. refresh_cmd_timeout();
  2881. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2882. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2883. while (PENDING(millis(), dwell_ms)) idle();
  2884. }
  2885. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2886. /**
  2887. * Parameters interpreted according to:
  2888. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2889. * However I, J omission is not supported at this point; all
  2890. * parameters can be omitted and default to zero.
  2891. */
  2892. /**
  2893. * G5: Cubic B-spline
  2894. */
  2895. inline void gcode_G5() {
  2896. if (IsRunning()) {
  2897. gcode_get_destination();
  2898. const float offset[] = {
  2899. parser.linearval('I'),
  2900. parser.linearval('J'),
  2901. parser.linearval('P'),
  2902. parser.linearval('Q')
  2903. };
  2904. plan_cubic_move(offset);
  2905. }
  2906. }
  2907. #endif // BEZIER_CURVE_SUPPORT
  2908. #if ENABLED(FWRETRACT)
  2909. /**
  2910. * G10 - Retract filament according to settings of M207
  2911. * G11 - Recover filament according to settings of M208
  2912. */
  2913. inline void gcode_G10_G11(bool doRetract=false) {
  2914. #if EXTRUDERS > 1
  2915. if (doRetract)
  2916. retracted_swap[active_extruder] = parser.boolval('S'); // checks for swap retract argument
  2917. #endif
  2918. retract(doRetract
  2919. #if EXTRUDERS > 1
  2920. , retracted_swap[active_extruder]
  2921. #endif
  2922. );
  2923. }
  2924. #endif // FWRETRACT
  2925. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2926. /**
  2927. * G12: Clean the nozzle
  2928. */
  2929. inline void gcode_G12() {
  2930. // Don't allow nozzle cleaning without homing first
  2931. if (axis_unhomed_error()) return;
  2932. const uint8_t pattern = parser.ushortval('P', 0),
  2933. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  2934. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  2935. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  2936. Nozzle::clean(pattern, strokes, radius, objects);
  2937. }
  2938. #endif
  2939. #if ENABLED(CNC_WORKSPACE_PLANES)
  2940. void report_workspace_plane() {
  2941. SERIAL_ECHO_START();
  2942. SERIAL_ECHOPGM("Workspace Plane ");
  2943. serialprintPGM(workspace_plane == PLANE_YZ ? PSTR("YZ\n") : workspace_plane == PLANE_ZX ? PSTR("ZX\n") : PSTR("XY\n"));
  2944. }
  2945. /**
  2946. * G17: Select Plane XY
  2947. * G18: Select Plane ZX
  2948. * G19: Select Plane YZ
  2949. */
  2950. inline void gcode_G17() { workspace_plane = PLANE_XY; }
  2951. inline void gcode_G18() { workspace_plane = PLANE_ZX; }
  2952. inline void gcode_G19() { workspace_plane = PLANE_YZ; }
  2953. #endif // CNC_WORKSPACE_PLANES
  2954. #if ENABLED(INCH_MODE_SUPPORT)
  2955. /**
  2956. * G20: Set input mode to inches
  2957. */
  2958. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2959. /**
  2960. * G21: Set input mode to millimeters
  2961. */
  2962. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2963. #endif
  2964. #if ENABLED(NOZZLE_PARK_FEATURE)
  2965. /**
  2966. * G27: Park the nozzle
  2967. */
  2968. inline void gcode_G27() {
  2969. // Don't allow nozzle parking without homing first
  2970. if (axis_unhomed_error()) return;
  2971. Nozzle::park(parser.ushortval('P'));
  2972. }
  2973. #endif // NOZZLE_PARK_FEATURE
  2974. #if ENABLED(QUICK_HOME)
  2975. static void quick_home_xy() {
  2976. // Pretend the current position is 0,0
  2977. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2978. sync_plan_position();
  2979. const int x_axis_home_dir =
  2980. #if ENABLED(DUAL_X_CARRIAGE)
  2981. x_home_dir(active_extruder)
  2982. #else
  2983. home_dir(X_AXIS)
  2984. #endif
  2985. ;
  2986. const float mlx = max_length(X_AXIS),
  2987. mly = max_length(Y_AXIS),
  2988. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2989. fr_mm_s = min(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  2990. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2991. endstops.hit_on_purpose(); // clear endstop hit flags
  2992. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2993. }
  2994. #endif // QUICK_HOME
  2995. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2996. void log_machine_info() {
  2997. SERIAL_ECHOPGM("Machine Type: ");
  2998. #if ENABLED(DELTA)
  2999. SERIAL_ECHOLNPGM("Delta");
  3000. #elif IS_SCARA
  3001. SERIAL_ECHOLNPGM("SCARA");
  3002. #elif IS_CORE
  3003. SERIAL_ECHOLNPGM("Core");
  3004. #else
  3005. SERIAL_ECHOLNPGM("Cartesian");
  3006. #endif
  3007. SERIAL_ECHOPGM("Probe: ");
  3008. #if ENABLED(PROBE_MANUALLY)
  3009. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  3010. #elif ENABLED(FIX_MOUNTED_PROBE)
  3011. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3012. #elif ENABLED(BLTOUCH)
  3013. SERIAL_ECHOLNPGM("BLTOUCH");
  3014. #elif HAS_Z_SERVO_ENDSTOP
  3015. SERIAL_ECHOLNPGM("SERVO PROBE");
  3016. #elif ENABLED(Z_PROBE_SLED)
  3017. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3018. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3019. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3020. #else
  3021. SERIAL_ECHOLNPGM("NONE");
  3022. #endif
  3023. #if HAS_BED_PROBE
  3024. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3025. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3026. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3027. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3028. SERIAL_ECHOPGM(" (Right");
  3029. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3030. SERIAL_ECHOPGM(" (Left");
  3031. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3032. SERIAL_ECHOPGM(" (Middle");
  3033. #else
  3034. SERIAL_ECHOPGM(" (Aligned With");
  3035. #endif
  3036. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3037. SERIAL_ECHOPGM("-Back");
  3038. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3039. SERIAL_ECHOPGM("-Front");
  3040. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3041. SERIAL_ECHOPGM("-Center");
  3042. #endif
  3043. if (zprobe_zoffset < 0)
  3044. SERIAL_ECHOPGM(" & Below");
  3045. else if (zprobe_zoffset > 0)
  3046. SERIAL_ECHOPGM(" & Above");
  3047. else
  3048. SERIAL_ECHOPGM(" & Same Z as");
  3049. SERIAL_ECHOLNPGM(" Nozzle)");
  3050. #endif
  3051. #if HAS_ABL
  3052. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3053. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3054. SERIAL_ECHOPGM("LINEAR");
  3055. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3056. SERIAL_ECHOPGM("BILINEAR");
  3057. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3058. SERIAL_ECHOPGM("3POINT");
  3059. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3060. SERIAL_ECHOPGM("UBL");
  3061. #endif
  3062. if (leveling_is_active()) {
  3063. SERIAL_ECHOLNPGM(" (enabled)");
  3064. #if ABL_PLANAR
  3065. const float diff[XYZ] = {
  3066. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3067. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3068. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3069. };
  3070. SERIAL_ECHOPGM("ABL Adjustment X");
  3071. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3072. SERIAL_ECHO(diff[X_AXIS]);
  3073. SERIAL_ECHOPGM(" Y");
  3074. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3075. SERIAL_ECHO(diff[Y_AXIS]);
  3076. SERIAL_ECHOPGM(" Z");
  3077. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3078. SERIAL_ECHO(diff[Z_AXIS]);
  3079. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3080. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  3081. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3082. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  3083. #endif
  3084. }
  3085. else
  3086. SERIAL_ECHOLNPGM(" (disabled)");
  3087. SERIAL_EOL();
  3088. #elif ENABLED(MESH_BED_LEVELING)
  3089. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3090. if (leveling_is_active()) {
  3091. float lz = current_position[Z_AXIS];
  3092. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  3093. SERIAL_ECHOLNPGM(" (enabled)");
  3094. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  3095. }
  3096. else
  3097. SERIAL_ECHOPGM(" (disabled)");
  3098. SERIAL_EOL();
  3099. #endif // MESH_BED_LEVELING
  3100. }
  3101. #endif // DEBUG_LEVELING_FEATURE
  3102. #if ENABLED(DELTA)
  3103. /**
  3104. * A delta can only safely home all axes at the same time
  3105. * This is like quick_home_xy() but for 3 towers.
  3106. */
  3107. inline void home_delta() {
  3108. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3109. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3110. #endif
  3111. // Init the current position of all carriages to 0,0,0
  3112. ZERO(current_position);
  3113. sync_plan_position();
  3114. // Move all carriages together linearly until an endstop is hit.
  3115. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3116. feedrate_mm_s = homing_feedrate(X_AXIS);
  3117. line_to_current_position();
  3118. stepper.synchronize();
  3119. endstops.hit_on_purpose(); // clear endstop hit flags
  3120. // At least one carriage has reached the top.
  3121. // Now re-home each carriage separately.
  3122. HOMEAXIS(A);
  3123. HOMEAXIS(B);
  3124. HOMEAXIS(C);
  3125. // Set all carriages to their home positions
  3126. // Do this here all at once for Delta, because
  3127. // XYZ isn't ABC. Applying this per-tower would
  3128. // give the impression that they are the same.
  3129. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3130. SYNC_PLAN_POSITION_KINEMATIC();
  3131. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3132. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3133. #endif
  3134. }
  3135. #endif // DELTA
  3136. #if ENABLED(Z_SAFE_HOMING)
  3137. inline void home_z_safely() {
  3138. // Disallow Z homing if X or Y are unknown
  3139. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3140. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3141. SERIAL_ECHO_START();
  3142. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3143. return;
  3144. }
  3145. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3146. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3147. #endif
  3148. SYNC_PLAN_POSITION_KINEMATIC();
  3149. /**
  3150. * Move the Z probe (or just the nozzle) to the safe homing point
  3151. */
  3152. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3153. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3154. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3155. #if HOMING_Z_WITH_PROBE
  3156. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3157. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3158. #endif
  3159. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3160. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3161. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3162. #endif
  3163. // This causes the carriage on Dual X to unpark
  3164. #if ENABLED(DUAL_X_CARRIAGE)
  3165. active_extruder_parked = false;
  3166. #endif
  3167. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3168. HOMEAXIS(Z);
  3169. }
  3170. else {
  3171. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3172. SERIAL_ECHO_START();
  3173. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3174. }
  3175. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3176. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3177. #endif
  3178. }
  3179. #endif // Z_SAFE_HOMING
  3180. #if ENABLED(PROBE_MANUALLY)
  3181. bool g29_in_progress = false;
  3182. #else
  3183. constexpr bool g29_in_progress = false;
  3184. #endif
  3185. /**
  3186. * G28: Home all axes according to settings
  3187. *
  3188. * Parameters
  3189. *
  3190. * None Home to all axes with no parameters.
  3191. * With QUICK_HOME enabled XY will home together, then Z.
  3192. *
  3193. * Cartesian parameters
  3194. *
  3195. * X Home to the X endstop
  3196. * Y Home to the Y endstop
  3197. * Z Home to the Z endstop
  3198. *
  3199. */
  3200. inline void gcode_G28(const bool always_home_all) {
  3201. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3202. if (DEBUGGING(LEVELING)) {
  3203. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3204. log_machine_info();
  3205. }
  3206. #endif
  3207. // Wait for planner moves to finish!
  3208. stepper.synchronize();
  3209. // Cancel the active G29 session
  3210. #if ENABLED(PROBE_MANUALLY)
  3211. g29_in_progress = false;
  3212. #endif
  3213. // Disable the leveling matrix before homing
  3214. #if HAS_LEVELING
  3215. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3216. const bool ubl_state_at_entry = leveling_is_active();
  3217. #endif
  3218. set_bed_leveling_enabled(false);
  3219. #endif
  3220. #if ENABLED(CNC_WORKSPACE_PLANES)
  3221. workspace_plane = PLANE_XY;
  3222. #endif
  3223. // Always home with tool 0 active
  3224. #if HOTENDS > 1
  3225. const uint8_t old_tool_index = active_extruder;
  3226. tool_change(0, 0, true);
  3227. #endif
  3228. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3229. extruder_duplication_enabled = false;
  3230. #endif
  3231. setup_for_endstop_or_probe_move();
  3232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3233. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3234. #endif
  3235. endstops.enable(true); // Enable endstops for next homing move
  3236. #if ENABLED(DELTA)
  3237. home_delta();
  3238. UNUSED(always_home_all);
  3239. #else // NOT DELTA
  3240. const bool homeX = always_home_all || parser.seen('X'),
  3241. homeY = always_home_all || parser.seen('Y'),
  3242. homeZ = always_home_all || parser.seen('Z'),
  3243. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3244. set_destination_to_current();
  3245. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3246. if (home_all || homeZ) {
  3247. HOMEAXIS(Z);
  3248. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3249. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3250. #endif
  3251. }
  3252. #else
  3253. if (home_all || homeX || homeY) {
  3254. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3255. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3256. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3257. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3258. if (DEBUGGING(LEVELING))
  3259. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3260. #endif
  3261. do_blocking_move_to_z(destination[Z_AXIS]);
  3262. }
  3263. }
  3264. #endif
  3265. #if ENABLED(QUICK_HOME)
  3266. if (home_all || (homeX && homeY)) quick_home_xy();
  3267. #endif
  3268. #if ENABLED(HOME_Y_BEFORE_X)
  3269. // Home Y
  3270. if (home_all || homeY) {
  3271. HOMEAXIS(Y);
  3272. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3273. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3274. #endif
  3275. }
  3276. #endif
  3277. // Home X
  3278. if (home_all || homeX) {
  3279. #if ENABLED(DUAL_X_CARRIAGE)
  3280. // Always home the 2nd (right) extruder first
  3281. active_extruder = 1;
  3282. HOMEAXIS(X);
  3283. // Remember this extruder's position for later tool change
  3284. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3285. // Home the 1st (left) extruder
  3286. active_extruder = 0;
  3287. HOMEAXIS(X);
  3288. // Consider the active extruder to be parked
  3289. COPY(raised_parked_position, current_position);
  3290. delayed_move_time = 0;
  3291. active_extruder_parked = true;
  3292. #else
  3293. HOMEAXIS(X);
  3294. #endif
  3295. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3296. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3297. #endif
  3298. }
  3299. #if DISABLED(HOME_Y_BEFORE_X)
  3300. // Home Y
  3301. if (home_all || homeY) {
  3302. HOMEAXIS(Y);
  3303. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3304. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3305. #endif
  3306. }
  3307. #endif
  3308. // Home Z last if homing towards the bed
  3309. #if Z_HOME_DIR < 0
  3310. if (home_all || homeZ) {
  3311. #if ENABLED(Z_SAFE_HOMING)
  3312. home_z_safely();
  3313. #else
  3314. HOMEAXIS(Z);
  3315. #endif
  3316. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3317. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3318. #endif
  3319. } // home_all || homeZ
  3320. #endif // Z_HOME_DIR < 0
  3321. SYNC_PLAN_POSITION_KINEMATIC();
  3322. #endif // !DELTA (gcode_G28)
  3323. endstops.not_homing();
  3324. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3325. // move to a height where we can use the full xy-area
  3326. do_blocking_move_to_z(delta_clip_start_height);
  3327. #endif
  3328. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3329. set_bed_leveling_enabled(ubl_state_at_entry);
  3330. #endif
  3331. clean_up_after_endstop_or_probe_move();
  3332. // Restore the active tool after homing
  3333. #if HOTENDS > 1
  3334. tool_change(old_tool_index, 0, true);
  3335. #endif
  3336. lcd_refresh();
  3337. report_current_position();
  3338. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3339. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3340. #endif
  3341. } // G28
  3342. void home_all_axes() { gcode_G28(true); }
  3343. #if HAS_PROBING_PROCEDURE
  3344. void out_of_range_error(const char* p_edge) {
  3345. SERIAL_PROTOCOLPGM("?Probe ");
  3346. serialprintPGM(p_edge);
  3347. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3348. }
  3349. #endif
  3350. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3351. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3352. extern bool lcd_wait_for_move;
  3353. #endif
  3354. inline void _manual_goto_xy(const float &x, const float &y) {
  3355. const float old_feedrate_mm_s = feedrate_mm_s;
  3356. #if MANUAL_PROBE_HEIGHT > 0
  3357. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3358. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3359. line_to_current_position();
  3360. #endif
  3361. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3362. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3363. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3364. line_to_current_position();
  3365. #if MANUAL_PROBE_HEIGHT > 0
  3366. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3367. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3368. line_to_current_position();
  3369. #endif
  3370. feedrate_mm_s = old_feedrate_mm_s;
  3371. stepper.synchronize();
  3372. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3373. lcd_wait_for_move = false;
  3374. #endif
  3375. }
  3376. #endif
  3377. #if ENABLED(MESH_BED_LEVELING)
  3378. // Save 130 bytes with non-duplication of PSTR
  3379. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3380. void mbl_mesh_report() {
  3381. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3382. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3383. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3384. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3385. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3386. );
  3387. }
  3388. void mesh_probing_done() {
  3389. mbl.set_has_mesh(true);
  3390. home_all_axes();
  3391. set_bed_leveling_enabled(true);
  3392. #if ENABLED(MESH_G28_REST_ORIGIN)
  3393. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3394. set_destination_to_current();
  3395. line_to_destination(homing_feedrate(Z_AXIS));
  3396. stepper.synchronize();
  3397. #endif
  3398. }
  3399. /**
  3400. * G29: Mesh-based Z probe, probes a grid and produces a
  3401. * mesh to compensate for variable bed height
  3402. *
  3403. * Parameters With MESH_BED_LEVELING:
  3404. *
  3405. * S0 Produce a mesh report
  3406. * S1 Start probing mesh points
  3407. * S2 Probe the next mesh point
  3408. * S3 Xn Yn Zn.nn Manually modify a single point
  3409. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3410. * S5 Reset and disable mesh
  3411. *
  3412. * The S0 report the points as below
  3413. *
  3414. * +----> X-axis 1-n
  3415. * |
  3416. * |
  3417. * v Y-axis 1-n
  3418. *
  3419. */
  3420. inline void gcode_G29() {
  3421. static int mbl_probe_index = -1;
  3422. #if HAS_SOFTWARE_ENDSTOPS
  3423. static bool enable_soft_endstops;
  3424. #endif
  3425. const MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  3426. if (!WITHIN(state, 0, 5)) {
  3427. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3428. return;
  3429. }
  3430. int8_t px, py;
  3431. switch (state) {
  3432. case MeshReport:
  3433. if (leveling_is_valid()) {
  3434. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3435. mbl_mesh_report();
  3436. }
  3437. else
  3438. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3439. break;
  3440. case MeshStart:
  3441. mbl.reset();
  3442. mbl_probe_index = 0;
  3443. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3444. break;
  3445. case MeshNext:
  3446. if (mbl_probe_index < 0) {
  3447. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3448. return;
  3449. }
  3450. // For each G29 S2...
  3451. if (mbl_probe_index == 0) {
  3452. #if HAS_SOFTWARE_ENDSTOPS
  3453. // For the initial G29 S2 save software endstop state
  3454. enable_soft_endstops = soft_endstops_enabled;
  3455. #endif
  3456. }
  3457. else {
  3458. // For G29 S2 after adjusting Z.
  3459. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3460. #if HAS_SOFTWARE_ENDSTOPS
  3461. soft_endstops_enabled = enable_soft_endstops;
  3462. #endif
  3463. }
  3464. // If there's another point to sample, move there with optional lift.
  3465. if (mbl_probe_index < GRID_MAX_POINTS) {
  3466. mbl.zigzag(mbl_probe_index, px, py);
  3467. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3468. #if HAS_SOFTWARE_ENDSTOPS
  3469. // Disable software endstops to allow manual adjustment
  3470. // If G29 is not completed, they will not be re-enabled
  3471. soft_endstops_enabled = false;
  3472. #endif
  3473. mbl_probe_index++;
  3474. }
  3475. else {
  3476. // One last "return to the bed" (as originally coded) at completion
  3477. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3478. line_to_current_position();
  3479. stepper.synchronize();
  3480. // After recording the last point, activate home and activate
  3481. mbl_probe_index = -1;
  3482. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3483. BUZZ(100, 659);
  3484. BUZZ(100, 698);
  3485. mesh_probing_done();
  3486. }
  3487. break;
  3488. case MeshSet:
  3489. if (parser.seenval('X')) {
  3490. px = parser.value_int() - 1;
  3491. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3492. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3493. return;
  3494. }
  3495. }
  3496. else {
  3497. SERIAL_CHAR('X'); echo_not_entered();
  3498. return;
  3499. }
  3500. if (parser.seenval('Y')) {
  3501. py = parser.value_int() - 1;
  3502. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3503. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3504. return;
  3505. }
  3506. }
  3507. else {
  3508. SERIAL_CHAR('Y'); echo_not_entered();
  3509. return;
  3510. }
  3511. if (parser.seenval('Z')) {
  3512. mbl.z_values[px][py] = parser.value_linear_units();
  3513. }
  3514. else {
  3515. SERIAL_CHAR('Z'); echo_not_entered();
  3516. return;
  3517. }
  3518. break;
  3519. case MeshSetZOffset:
  3520. if (parser.seenval('Z')) {
  3521. mbl.z_offset = parser.value_linear_units();
  3522. }
  3523. else {
  3524. SERIAL_CHAR('Z'); echo_not_entered();
  3525. return;
  3526. }
  3527. break;
  3528. case MeshReset:
  3529. reset_bed_level();
  3530. break;
  3531. } // switch(state)
  3532. report_current_position();
  3533. }
  3534. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3535. #if ABL_GRID
  3536. #if ENABLED(PROBE_Y_FIRST)
  3537. #define PR_OUTER_VAR xCount
  3538. #define PR_OUTER_END abl_grid_points_x
  3539. #define PR_INNER_VAR yCount
  3540. #define PR_INNER_END abl_grid_points_y
  3541. #else
  3542. #define PR_OUTER_VAR yCount
  3543. #define PR_OUTER_END abl_grid_points_y
  3544. #define PR_INNER_VAR xCount
  3545. #define PR_INNER_END abl_grid_points_x
  3546. #endif
  3547. #endif
  3548. /**
  3549. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3550. * Will fail if the printer has not been homed with G28.
  3551. *
  3552. * Enhanced G29 Auto Bed Leveling Probe Routine
  3553. *
  3554. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3555. * or alter the bed level data. Useful to check the topology
  3556. * after a first run of G29.
  3557. *
  3558. * J Jettison current bed leveling data
  3559. *
  3560. * V Set the verbose level (0-4). Example: "G29 V3"
  3561. *
  3562. * Parameters With LINEAR leveling only:
  3563. *
  3564. * P Set the size of the grid that will be probed (P x P points).
  3565. * Example: "G29 P4"
  3566. *
  3567. * X Set the X size of the grid that will be probed (X x Y points).
  3568. * Example: "G29 X7 Y5"
  3569. *
  3570. * Y Set the Y size of the grid that will be probed (X x Y points).
  3571. *
  3572. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3573. * This is useful for manual bed leveling and finding flaws in the bed (to
  3574. * assist with part placement).
  3575. * Not supported by non-linear delta printer bed leveling.
  3576. *
  3577. * Parameters With LINEAR and BILINEAR leveling only:
  3578. *
  3579. * S Set the XY travel speed between probe points (in units/min)
  3580. *
  3581. * F Set the Front limit of the probing grid
  3582. * B Set the Back limit of the probing grid
  3583. * L Set the Left limit of the probing grid
  3584. * R Set the Right limit of the probing grid
  3585. *
  3586. * Parameters with DEBUG_LEVELING_FEATURE only:
  3587. *
  3588. * C Make a totally fake grid with no actual probing.
  3589. * For use in testing when no probing is possible.
  3590. *
  3591. * Parameters with BILINEAR leveling only:
  3592. *
  3593. * Z Supply an additional Z probe offset
  3594. *
  3595. * Extra parameters with PROBE_MANUALLY:
  3596. *
  3597. * To do manual probing simply repeat G29 until the procedure is complete.
  3598. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3599. *
  3600. * Q Query leveling and G29 state
  3601. *
  3602. * A Abort current leveling procedure
  3603. *
  3604. * W Write a mesh point. (Ignored during leveling.)
  3605. * X Required X for mesh point
  3606. * Y Required Y for mesh point
  3607. * Z Z for mesh point. Otherwise, current Z minus Z probe offset.
  3608. *
  3609. * Without PROBE_MANUALLY:
  3610. *
  3611. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3612. * Include "E" to engage/disengage the Z probe for each sample.
  3613. * There's no extra effect if you have a fixed Z probe.
  3614. *
  3615. */
  3616. inline void gcode_G29() {
  3617. // G29 Q is also available if debugging
  3618. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3619. const bool query = parser.seen('Q');
  3620. const uint8_t old_debug_flags = marlin_debug_flags;
  3621. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3622. if (DEBUGGING(LEVELING)) {
  3623. DEBUG_POS(">>> gcode_G29", current_position);
  3624. log_machine_info();
  3625. }
  3626. marlin_debug_flags = old_debug_flags;
  3627. #if DISABLED(PROBE_MANUALLY)
  3628. if (query) return;
  3629. #endif
  3630. #endif
  3631. #if ENABLED(PROBE_MANUALLY)
  3632. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q'), no_action = seenA || seenQ;
  3633. #endif
  3634. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3635. const bool faux = parser.boolval('C');
  3636. #elif ENABLED(PROBE_MANUALLY)
  3637. const bool faux = no_action;
  3638. #else
  3639. bool constexpr faux = false;
  3640. #endif
  3641. // Don't allow auto-leveling without homing first
  3642. if (axis_unhomed_error()) return;
  3643. // Define local vars 'static' for manual probing, 'auto' otherwise
  3644. #if ENABLED(PROBE_MANUALLY)
  3645. #define ABL_VAR static
  3646. #else
  3647. #define ABL_VAR
  3648. #endif
  3649. ABL_VAR int verbose_level;
  3650. ABL_VAR float xProbe, yProbe, measured_z;
  3651. ABL_VAR bool dryrun, abl_should_enable;
  3652. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3653. ABL_VAR int abl_probe_index;
  3654. #endif
  3655. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3656. ABL_VAR bool enable_soft_endstops = true;
  3657. #endif
  3658. #if ABL_GRID
  3659. #if ENABLED(PROBE_MANUALLY)
  3660. ABL_VAR uint8_t PR_OUTER_VAR;
  3661. ABL_VAR int8_t PR_INNER_VAR;
  3662. #endif
  3663. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3664. ABL_VAR float xGridSpacing, yGridSpacing;
  3665. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3666. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3667. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3668. ABL_VAR bool do_topography_map;
  3669. #else // Bilinear
  3670. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3671. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3672. #endif
  3673. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3674. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3675. ABL_VAR int abl2;
  3676. #else // Bilinear
  3677. int constexpr abl2 = GRID_MAX_POINTS;
  3678. #endif
  3679. #endif
  3680. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3681. ABL_VAR float zoffset;
  3682. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3683. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3684. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3685. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3686. mean;
  3687. #endif
  3688. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3689. int constexpr abl2 = 3;
  3690. // Probe at 3 arbitrary points
  3691. ABL_VAR vector_3 points[3] = {
  3692. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3693. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3694. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3695. };
  3696. #endif // AUTO_BED_LEVELING_3POINT
  3697. /**
  3698. * On the initial G29 fetch command parameters.
  3699. */
  3700. if (!g29_in_progress) {
  3701. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3702. abl_probe_index = -1;
  3703. #endif
  3704. abl_should_enable = leveling_is_active();
  3705. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3706. if (parser.seen('W')) {
  3707. if (!leveling_is_valid()) {
  3708. SERIAL_ERROR_START();
  3709. SERIAL_ERRORLNPGM("No bilinear grid");
  3710. return;
  3711. }
  3712. const float z = parser.floatval('Z', RAW_CURRENT_POSITION(Z));
  3713. if (!WITHIN(z, -10, 10)) {
  3714. SERIAL_ERROR_START();
  3715. SERIAL_ERRORLNPGM("Bad Z value");
  3716. return;
  3717. }
  3718. const float x = parser.floatval('X', NAN),
  3719. y = parser.floatval('Y', NAN);
  3720. int8_t i = parser.byteval('I', -1),
  3721. j = parser.byteval('J', -1);
  3722. if (!isnan(x) && !isnan(y)) {
  3723. // Get nearest i / j from x / y
  3724. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3725. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3726. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3727. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3728. }
  3729. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3730. set_bed_leveling_enabled(false);
  3731. z_values[i][j] = z;
  3732. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3733. bed_level_virt_interpolate();
  3734. #endif
  3735. set_bed_leveling_enabled(abl_should_enable);
  3736. }
  3737. return;
  3738. } // parser.seen('W')
  3739. #endif
  3740. #if HAS_LEVELING
  3741. // Jettison bed leveling data
  3742. if (parser.seen('J')) {
  3743. reset_bed_level();
  3744. return;
  3745. }
  3746. #endif
  3747. verbose_level = parser.intval('V');
  3748. if (!WITHIN(verbose_level, 0, 4)) {
  3749. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3750. return;
  3751. }
  3752. dryrun = parser.boolval('D')
  3753. #if ENABLED(PROBE_MANUALLY)
  3754. || no_action
  3755. #endif
  3756. ;
  3757. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3758. do_topography_map = verbose_level > 2 || parser.boolval('T');
  3759. // X and Y specify points in each direction, overriding the default
  3760. // These values may be saved with the completed mesh
  3761. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  3762. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  3763. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3764. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3765. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3766. return;
  3767. }
  3768. abl2 = abl_grid_points_x * abl_grid_points_y;
  3769. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3770. zoffset = parser.linearval('Z');
  3771. #endif
  3772. #if ABL_GRID
  3773. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  3774. left_probe_bed_position = (int)parser.linearval('L', LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION));
  3775. right_probe_bed_position = (int)parser.linearval('R', LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION));
  3776. front_probe_bed_position = (int)parser.linearval('F', LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION));
  3777. back_probe_bed_position = (int)parser.linearval('B', LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION));
  3778. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3779. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3780. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3781. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3782. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3783. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3784. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3785. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3786. if (left_out || right_out || front_out || back_out) {
  3787. if (left_out) {
  3788. out_of_range_error(PSTR("(L)eft"));
  3789. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3790. }
  3791. if (right_out) {
  3792. out_of_range_error(PSTR("(R)ight"));
  3793. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3794. }
  3795. if (front_out) {
  3796. out_of_range_error(PSTR("(F)ront"));
  3797. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3798. }
  3799. if (back_out) {
  3800. out_of_range_error(PSTR("(B)ack"));
  3801. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3802. }
  3803. return;
  3804. }
  3805. // probe at the points of a lattice grid
  3806. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3807. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3808. #endif // ABL_GRID
  3809. if (verbose_level > 0) {
  3810. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3811. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3812. }
  3813. stepper.synchronize();
  3814. // Disable auto bed leveling during G29
  3815. planner.abl_enabled = false;
  3816. if (!dryrun) {
  3817. // Re-orient the current position without leveling
  3818. // based on where the steppers are positioned.
  3819. set_current_from_steppers_for_axis(ALL_AXES);
  3820. // Sync the planner to where the steppers stopped
  3821. SYNC_PLAN_POSITION_KINEMATIC();
  3822. }
  3823. if (!faux) setup_for_endstop_or_probe_move();
  3824. //xProbe = yProbe = measured_z = 0;
  3825. #if HAS_BED_PROBE
  3826. // Deploy the probe. Probe will raise if needed.
  3827. if (DEPLOY_PROBE()) {
  3828. planner.abl_enabled = abl_should_enable;
  3829. return;
  3830. }
  3831. #endif
  3832. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3833. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3834. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3835. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3836. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3837. ) {
  3838. if (dryrun) {
  3839. // Before reset bed level, re-enable to correct the position
  3840. planner.abl_enabled = abl_should_enable;
  3841. }
  3842. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3843. reset_bed_level();
  3844. // Initialize a grid with the given dimensions
  3845. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3846. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3847. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3848. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3849. // Can't re-enable (on error) until the new grid is written
  3850. abl_should_enable = false;
  3851. }
  3852. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3853. mean = 0.0;
  3854. #endif // AUTO_BED_LEVELING_LINEAR
  3855. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3856. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3857. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3858. #endif
  3859. // Probe at 3 arbitrary points
  3860. points[0].z = points[1].z = points[2].z = 0;
  3861. #endif // AUTO_BED_LEVELING_3POINT
  3862. } // !g29_in_progress
  3863. #if ENABLED(PROBE_MANUALLY)
  3864. // For manual probing, get the next index to probe now.
  3865. // On the first probe this will be incremented to 0.
  3866. if (!no_action) {
  3867. ++abl_probe_index;
  3868. g29_in_progress = true;
  3869. }
  3870. // Abort current G29 procedure, go back to idle state
  3871. if (seenA && g29_in_progress) {
  3872. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3873. #if HAS_SOFTWARE_ENDSTOPS
  3874. soft_endstops_enabled = enable_soft_endstops;
  3875. #endif
  3876. planner.abl_enabled = abl_should_enable;
  3877. g29_in_progress = false;
  3878. #if ENABLED(LCD_BED_LEVELING)
  3879. lcd_wait_for_move = false;
  3880. #endif
  3881. }
  3882. // Query G29 status
  3883. if (verbose_level || seenQ) {
  3884. SERIAL_PROTOCOLPGM("Manual G29 ");
  3885. if (g29_in_progress) {
  3886. SERIAL_PROTOCOLPAIR("point ", min(abl_probe_index + 1, abl2));
  3887. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3888. }
  3889. else
  3890. SERIAL_PROTOCOLLNPGM("idle");
  3891. }
  3892. if (no_action) return;
  3893. if (abl_probe_index == 0) {
  3894. // For the initial G29 save software endstop state
  3895. #if HAS_SOFTWARE_ENDSTOPS
  3896. enable_soft_endstops = soft_endstops_enabled;
  3897. #endif
  3898. }
  3899. else {
  3900. // For G29 after adjusting Z.
  3901. // Save the previous Z before going to the next point
  3902. measured_z = current_position[Z_AXIS];
  3903. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3904. mean += measured_z;
  3905. eqnBVector[abl_probe_index] = measured_z;
  3906. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3907. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3908. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3909. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3910. z_values[xCount][yCount] = measured_z + zoffset;
  3911. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3912. if (DEBUGGING(LEVELING)) {
  3913. SERIAL_PROTOCOLPAIR("Save X", xCount);
  3914. SERIAL_PROTOCOLPAIR(" Y", yCount);
  3915. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  3916. }
  3917. #endif
  3918. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3919. points[abl_probe_index].z = measured_z;
  3920. #endif
  3921. }
  3922. //
  3923. // If there's another point to sample, move there with optional lift.
  3924. //
  3925. #if ABL_GRID
  3926. // Skip any unreachable points
  3927. while (abl_probe_index < abl2) {
  3928. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3929. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3930. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3931. // Probe in reverse order for every other row/column
  3932. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3933. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3934. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3935. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3936. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  3937. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  3938. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3939. indexIntoAB[xCount][yCount] = abl_probe_index;
  3940. #endif
  3941. // Keep looping till a reachable point is found
  3942. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3943. ++abl_probe_index;
  3944. }
  3945. // Is there a next point to move to?
  3946. if (abl_probe_index < abl2) {
  3947. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3948. #if HAS_SOFTWARE_ENDSTOPS
  3949. // Disable software endstops to allow manual adjustment
  3950. // If G29 is not completed, they will not be re-enabled
  3951. soft_endstops_enabled = false;
  3952. #endif
  3953. return;
  3954. }
  3955. else {
  3956. // Leveling done! Fall through to G29 finishing code below
  3957. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3958. // Re-enable software endstops, if needed
  3959. #if HAS_SOFTWARE_ENDSTOPS
  3960. soft_endstops_enabled = enable_soft_endstops;
  3961. #endif
  3962. }
  3963. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3964. // Probe at 3 arbitrary points
  3965. if (abl_probe_index < 3) {
  3966. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3967. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3968. #if HAS_SOFTWARE_ENDSTOPS
  3969. // Disable software endstops to allow manual adjustment
  3970. // If G29 is not completed, they will not be re-enabled
  3971. soft_endstops_enabled = false;
  3972. #endif
  3973. return;
  3974. }
  3975. else {
  3976. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3977. // Re-enable software endstops, if needed
  3978. #if HAS_SOFTWARE_ENDSTOPS
  3979. soft_endstops_enabled = enable_soft_endstops;
  3980. #endif
  3981. if (!dryrun) {
  3982. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3983. if (planeNormal.z < 0) {
  3984. planeNormal.x *= -1;
  3985. planeNormal.y *= -1;
  3986. planeNormal.z *= -1;
  3987. }
  3988. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3989. // Can't re-enable (on error) until the new grid is written
  3990. abl_should_enable = false;
  3991. }
  3992. }
  3993. #endif // AUTO_BED_LEVELING_3POINT
  3994. #else // !PROBE_MANUALLY
  3995. const bool stow_probe_after_each = parser.boolval('E');
  3996. #if ABL_GRID
  3997. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3998. // Outer loop is Y with PROBE_Y_FIRST disabled
  3999. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  4000. int8_t inStart, inStop, inInc;
  4001. if (zig) { // away from origin
  4002. inStart = 0;
  4003. inStop = PR_INNER_END;
  4004. inInc = 1;
  4005. }
  4006. else { // towards origin
  4007. inStart = PR_INNER_END - 1;
  4008. inStop = -1;
  4009. inInc = -1;
  4010. }
  4011. zig ^= true; // zag
  4012. // Inner loop is Y with PROBE_Y_FIRST enabled
  4013. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4014. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4015. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4016. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4017. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4018. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4019. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4020. #endif
  4021. #if IS_KINEMATIC
  4022. // Avoid probing outside the round or hexagonal area
  4023. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  4024. #endif
  4025. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4026. if (isnan(measured_z)) {
  4027. planner.abl_enabled = abl_should_enable;
  4028. return;
  4029. }
  4030. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4031. mean += measured_z;
  4032. eqnBVector[abl_probe_index] = measured_z;
  4033. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  4034. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  4035. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  4036. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4037. z_values[xCount][yCount] = measured_z + zoffset;
  4038. #endif
  4039. abl_should_enable = false;
  4040. idle();
  4041. } // inner
  4042. } // outer
  4043. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4044. // Probe at 3 arbitrary points
  4045. for (uint8_t i = 0; i < 3; ++i) {
  4046. // Retain the last probe position
  4047. xProbe = LOGICAL_X_POSITION(points[i].x);
  4048. yProbe = LOGICAL_Y_POSITION(points[i].y);
  4049. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4050. if (isnan(measured_z)) {
  4051. planner.abl_enabled = abl_should_enable;
  4052. return;
  4053. }
  4054. points[i].z = measured_z;
  4055. }
  4056. if (!dryrun) {
  4057. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4058. if (planeNormal.z < 0) {
  4059. planeNormal.x *= -1;
  4060. planeNormal.y *= -1;
  4061. planeNormal.z *= -1;
  4062. }
  4063. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4064. // Can't re-enable (on error) until the new grid is written
  4065. abl_should_enable = false;
  4066. }
  4067. #endif // AUTO_BED_LEVELING_3POINT
  4068. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  4069. if (STOW_PROBE()) {
  4070. planner.abl_enabled = abl_should_enable;
  4071. return;
  4072. }
  4073. #endif // !PROBE_MANUALLY
  4074. //
  4075. // G29 Finishing Code
  4076. //
  4077. // Unless this is a dry run, auto bed leveling will
  4078. // definitely be enabled after this point.
  4079. //
  4080. // If code above wants to continue leveling, it should
  4081. // return or loop before this point.
  4082. //
  4083. // Restore state after probing
  4084. if (!faux) clean_up_after_endstop_or_probe_move();
  4085. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4086. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4087. #endif
  4088. #if ENABLED(PROBE_MANUALLY)
  4089. g29_in_progress = false;
  4090. #if ENABLED(LCD_BED_LEVELING)
  4091. lcd_wait_for_move = false;
  4092. #endif
  4093. #endif
  4094. // Calculate leveling, print reports, correct the position
  4095. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4096. if (!dryrun) extrapolate_unprobed_bed_level();
  4097. print_bilinear_leveling_grid();
  4098. refresh_bed_level();
  4099. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4100. bed_level_virt_print();
  4101. #endif
  4102. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4103. // For LINEAR leveling calculate matrix, print reports, correct the position
  4104. /**
  4105. * solve the plane equation ax + by + d = z
  4106. * A is the matrix with rows [x y 1] for all the probed points
  4107. * B is the vector of the Z positions
  4108. * the normal vector to the plane is formed by the coefficients of the
  4109. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4110. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4111. */
  4112. float plane_equation_coefficients[3];
  4113. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  4114. mean /= abl2;
  4115. if (verbose_level) {
  4116. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  4117. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  4118. SERIAL_PROTOCOLPGM(" b: ");
  4119. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  4120. SERIAL_PROTOCOLPGM(" d: ");
  4121. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  4122. SERIAL_EOL();
  4123. if (verbose_level > 2) {
  4124. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  4125. SERIAL_PROTOCOL_F(mean, 8);
  4126. SERIAL_EOL();
  4127. }
  4128. }
  4129. // Create the matrix but don't correct the position yet
  4130. if (!dryrun) {
  4131. planner.bed_level_matrix = matrix_3x3::create_look_at(
  4132. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  4133. );
  4134. }
  4135. // Show the Topography map if enabled
  4136. if (do_topography_map) {
  4137. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4138. " +--- BACK --+\n"
  4139. " | |\n"
  4140. " L | (+) | R\n"
  4141. " E | | I\n"
  4142. " F | (-) N (+) | G\n"
  4143. " T | | H\n"
  4144. " | (-) | T\n"
  4145. " | |\n"
  4146. " O-- FRONT --+\n"
  4147. " (0,0)");
  4148. float min_diff = 999;
  4149. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4150. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4151. int ind = indexIntoAB[xx][yy];
  4152. float diff = eqnBVector[ind] - mean,
  4153. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4154. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4155. z_tmp = 0;
  4156. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4157. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4158. if (diff >= 0.0)
  4159. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4160. else
  4161. SERIAL_PROTOCOLCHAR(' ');
  4162. SERIAL_PROTOCOL_F(diff, 5);
  4163. } // xx
  4164. SERIAL_EOL();
  4165. } // yy
  4166. SERIAL_EOL();
  4167. if (verbose_level > 3) {
  4168. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4169. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4170. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4171. int ind = indexIntoAB[xx][yy];
  4172. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4173. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4174. z_tmp = 0;
  4175. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4176. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4177. if (diff >= 0.0)
  4178. SERIAL_PROTOCOLPGM(" +");
  4179. // Include + for column alignment
  4180. else
  4181. SERIAL_PROTOCOLCHAR(' ');
  4182. SERIAL_PROTOCOL_F(diff, 5);
  4183. } // xx
  4184. SERIAL_EOL();
  4185. } // yy
  4186. SERIAL_EOL();
  4187. }
  4188. } //do_topography_map
  4189. #endif // AUTO_BED_LEVELING_LINEAR
  4190. #if ABL_PLANAR
  4191. // For LINEAR and 3POINT leveling correct the current position
  4192. if (verbose_level > 0)
  4193. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4194. if (!dryrun) {
  4195. //
  4196. // Correct the current XYZ position based on the tilted plane.
  4197. //
  4198. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4199. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4200. #endif
  4201. float converted[XYZ];
  4202. COPY(converted, current_position);
  4203. planner.abl_enabled = true;
  4204. planner.unapply_leveling(converted); // use conversion machinery
  4205. planner.abl_enabled = false;
  4206. // Use the last measured distance to the bed, if possible
  4207. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4208. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4209. ) {
  4210. const float simple_z = current_position[Z_AXIS] - measured_z;
  4211. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4212. if (DEBUGGING(LEVELING)) {
  4213. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4214. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4215. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4216. }
  4217. #endif
  4218. converted[Z_AXIS] = simple_z;
  4219. }
  4220. // The rotated XY and corrected Z are now current_position
  4221. COPY(current_position, converted);
  4222. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4223. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4224. #endif
  4225. }
  4226. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4227. if (!dryrun) {
  4228. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4229. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4230. #endif
  4231. // Unapply the offset because it is going to be immediately applied
  4232. // and cause compensation movement in Z
  4233. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4234. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4235. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4236. #endif
  4237. }
  4238. #endif // ABL_PLANAR
  4239. #ifdef Z_PROBE_END_SCRIPT
  4240. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4241. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4242. #endif
  4243. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4244. stepper.synchronize();
  4245. #endif
  4246. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4247. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4248. #endif
  4249. report_current_position();
  4250. KEEPALIVE_STATE(IN_HANDLER);
  4251. // Auto Bed Leveling is complete! Enable if possible.
  4252. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4253. if (planner.abl_enabled)
  4254. SYNC_PLAN_POSITION_KINEMATIC();
  4255. }
  4256. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4257. #if HAS_BED_PROBE
  4258. /**
  4259. * G30: Do a single Z probe at the current XY
  4260. *
  4261. * Parameters:
  4262. *
  4263. * X Probe X position (default current X)
  4264. * Y Probe Y position (default current Y)
  4265. * S0 Leave the probe deployed
  4266. */
  4267. inline void gcode_G30() {
  4268. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4269. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4270. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4271. // Disable leveling so the planner won't mess with us
  4272. #if HAS_LEVELING
  4273. set_bed_leveling_enabled(false);
  4274. #endif
  4275. setup_for_endstop_or_probe_move();
  4276. const float measured_z = probe_pt(xpos, ypos, parser.boolval('S', true), 1);
  4277. if (!isnan(measured_z)) {
  4278. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4279. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4280. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4281. }
  4282. clean_up_after_endstop_or_probe_move();
  4283. report_current_position();
  4284. }
  4285. #if ENABLED(Z_PROBE_SLED)
  4286. /**
  4287. * G31: Deploy the Z probe
  4288. */
  4289. inline void gcode_G31() { DEPLOY_PROBE(); }
  4290. /**
  4291. * G32: Stow the Z probe
  4292. */
  4293. inline void gcode_G32() { STOW_PROBE(); }
  4294. #endif // Z_PROBE_SLED
  4295. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4296. /**
  4297. * G33 - Delta '1-4-7-point' Auto-Calibration
  4298. * Calibrate height, endstops, delta radius, and tower angles.
  4299. *
  4300. * Parameters:
  4301. *
  4302. * Pn Number of probe points:
  4303. *
  4304. * P1 Probe center and set height only.
  4305. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4306. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4307. * P4-P7 Probe all positions at different locations and average them.
  4308. *
  4309. * T Don't calibrate tower angle corrections
  4310. *
  4311. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4312. *
  4313. * Fn Force to run at least n iterations and takes the best result
  4314. *
  4315. * Vn Verbose level:
  4316. *
  4317. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4318. * V1 Report settings
  4319. * V2 Report settings and probe results
  4320. *
  4321. * E Engage the probe for each point
  4322. */
  4323. void print_signed_float(const char * const prefix, const float &f) {
  4324. SERIAL_PROTOCOLPGM(" ");
  4325. serialprintPGM(prefix);
  4326. SERIAL_PROTOCOLCHAR(':');
  4327. if (f >= 0) SERIAL_CHAR('+');
  4328. SERIAL_PROTOCOL_F(f, 2);
  4329. }
  4330. inline void gcode_G33() {
  4331. const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  4332. if (!WITHIN(probe_points, 1, 7)) {
  4333. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1 to 7).");
  4334. return;
  4335. }
  4336. const int8_t verbose_level = parser.byteval('V', 1);
  4337. if (!WITHIN(verbose_level, 0, 2)) {
  4338. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4339. return;
  4340. }
  4341. const float calibration_precision = parser.floatval('C');
  4342. if (calibration_precision < 0) {
  4343. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4344. return;
  4345. }
  4346. const int8_t force_iterations = parser.intval('F', 1);
  4347. if (!WITHIN(force_iterations, 1, 30)) {
  4348. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (1-30).");
  4349. return;
  4350. }
  4351. const bool towers_set = !parser.boolval('T'),
  4352. stow_after_each = parser.boolval('E'),
  4353. _1p_calibration = probe_points == 1,
  4354. _4p_calibration = probe_points == 2,
  4355. _4p_towers_points = _4p_calibration && towers_set,
  4356. _4p_opposite_points = _4p_calibration && !towers_set,
  4357. _7p_calibration = probe_points >= 3,
  4358. _7p_half_circle = probe_points == 3,
  4359. _7p_double_circle = probe_points == 5,
  4360. _7p_triple_circle = probe_points == 6,
  4361. _7p_quadruple_circle = probe_points == 7,
  4362. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4363. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4364. if (!_1p_calibration) { // test if the outer radius is reachable
  4365. const float circles = (_7p_quadruple_circle ? 1.5 :
  4366. _7p_triple_circle ? 1.0 :
  4367. _7p_double_circle ? 0.5 : 0),
  4368. radius = (1 + circles * 0.1) * delta_calibration_radius;
  4369. for (uint8_t axis = 1; axis < 13; ++axis) {
  4370. if (!position_is_reachable_xy(cos(RADIANS(180 + 30 * axis)) * radius, sin(RADIANS(180 + 30 * axis)) * radius)) {
  4371. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4372. return;
  4373. }
  4374. }
  4375. }
  4376. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4377. const float dx = (X_PROBE_OFFSET_FROM_EXTRUDER),
  4378. dy = (Y_PROBE_OFFSET_FROM_EXTRUDER);
  4379. int8_t iterations = 0;
  4380. float test_precision,
  4381. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4382. zero_std_dev_old = zero_std_dev,
  4383. zero_std_dev_min = zero_std_dev,
  4384. e_old[XYZ] = {
  4385. endstop_adj[A_AXIS],
  4386. endstop_adj[B_AXIS],
  4387. endstop_adj[C_AXIS]
  4388. },
  4389. dr_old = delta_radius,
  4390. zh_old = home_offset[Z_AXIS],
  4391. alpha_old = delta_tower_angle_trim[A_AXIS],
  4392. beta_old = delta_tower_angle_trim[B_AXIS];
  4393. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4394. stepper.synchronize();
  4395. #if HAS_LEVELING
  4396. reset_bed_level(); // After calibration bed-level data is no longer valid
  4397. #endif
  4398. #if HOTENDS > 1
  4399. const uint8_t old_tool_index = active_extruder;
  4400. tool_change(0, 0, true);
  4401. #endif
  4402. setup_for_endstop_or_probe_move();
  4403. DEPLOY_PROBE();
  4404. endstops.enable(true);
  4405. home_delta();
  4406. endstops.not_homing();
  4407. // print settings
  4408. SERIAL_PROTOCOLPGM("Checking... AC");
  4409. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4410. SERIAL_EOL();
  4411. LCD_MESSAGEPGM("Checking... AC"); // TODO: Make translatable string
  4412. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4413. if (!_1p_calibration) {
  4414. print_signed_float(PSTR(" Ex"), endstop_adj[A_AXIS]);
  4415. print_signed_float(PSTR("Ey"), endstop_adj[B_AXIS]);
  4416. print_signed_float(PSTR("Ez"), endstop_adj[C_AXIS]);
  4417. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4418. }
  4419. SERIAL_EOL();
  4420. if (_7p_calibration && towers_set) {
  4421. SERIAL_PROTOCOLPGM(".Tower angle : ");
  4422. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4423. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4424. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4425. SERIAL_EOL();
  4426. }
  4427. home_offset[Z_AXIS] -= probe_pt(dx, dy, stow_after_each, 1); // 1st probe to set height
  4428. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  4429. do {
  4430. float z_at_pt[13] = { 0.0 }, S1 = 0.0, S2 = 0.0;
  4431. int16_t N = 0;
  4432. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4433. iterations++;
  4434. // Probe the points
  4435. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4436. z_at_pt[0] += probe_pt(dx, dy, stow_after_each, 1);
  4437. }
  4438. if (_7p_calibration) { // probe extra center points
  4439. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4440. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4441. z_at_pt[0] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1);
  4442. }
  4443. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4444. }
  4445. if (!_1p_calibration) { // probe the radius
  4446. bool zig_zag = true;
  4447. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4448. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4449. for (uint8_t axis = start; axis < 13; axis += step) {
  4450. const float zigadd = (zig_zag ? 0.5 : 0.0),
  4451. offset_circles = _7p_quadruple_circle ? zigadd + 1.0 :
  4452. _7p_triple_circle ? zigadd + 0.5 :
  4453. _7p_double_circle ? zigadd : 0;
  4454. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4455. const float a = RADIANS(180 + 30 * axis),
  4456. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4457. z_at_pt[axis] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1);
  4458. }
  4459. zig_zag = !zig_zag;
  4460. z_at_pt[axis] /= (2 * offset_circles + 1);
  4461. }
  4462. }
  4463. if (_7p_intermed_points) // average intermediates to tower and opposites
  4464. for (uint8_t axis = 1; axis <= 11; axis += 2)
  4465. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4466. S1 += z_at_pt[0];
  4467. S2 += sq(z_at_pt[0]);
  4468. N++;
  4469. if (!_1p_calibration) // std dev from zero plane
  4470. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4471. S1 += z_at_pt[axis];
  4472. S2 += sq(z_at_pt[axis]);
  4473. N++;
  4474. }
  4475. zero_std_dev_old = zero_std_dev;
  4476. NOMORE(zero_std_dev_min, zero_std_dev);
  4477. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4478. // Solve matrices
  4479. if ((zero_std_dev < test_precision && zero_std_dev > calibration_precision) || iterations <= force_iterations) {
  4480. if (zero_std_dev < zero_std_dev_min) {
  4481. COPY(e_old, endstop_adj);
  4482. dr_old = delta_radius;
  4483. zh_old = home_offset[Z_AXIS];
  4484. alpha_old = delta_tower_angle_trim[A_AXIS];
  4485. beta_old = delta_tower_angle_trim[B_AXIS];
  4486. }
  4487. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4488. const float r_diff = delta_radius - delta_calibration_radius,
  4489. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4490. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4491. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4492. #define ZP(N,I) ((N) * z_at_pt[I])
  4493. #define Z1000(I) ZP(1.00, I)
  4494. #define Z1050(I) ZP(h_factor, I)
  4495. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4496. #define Z0350(I) ZP(h_factor / 3.00, I)
  4497. #define Z0175(I) ZP(h_factor / 6.00, I)
  4498. #define Z2250(I) ZP(r_factor, I)
  4499. #define Z0750(I) ZP(r_factor / 3.00, I)
  4500. #define Z0375(I) ZP(r_factor / 6.00, I)
  4501. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4502. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4503. switch (probe_points) {
  4504. case 1:
  4505. test_precision = 0.00;
  4506. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4507. break;
  4508. case 2:
  4509. if (towers_set) {
  4510. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4511. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4512. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4513. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4514. }
  4515. else {
  4516. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4517. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4518. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4519. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4520. }
  4521. break;
  4522. default:
  4523. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4524. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4525. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4526. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4527. if (towers_set) {
  4528. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4529. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4530. }
  4531. break;
  4532. }
  4533. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4534. delta_radius += r_delta;
  4535. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4536. delta_tower_angle_trim[B_AXIS] += t_beta;
  4537. // adjust delta_height and endstops by the max amount
  4538. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4539. home_offset[Z_AXIS] -= z_temp;
  4540. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4541. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4542. }
  4543. else if (zero_std_dev >= test_precision) { // step one back
  4544. COPY(endstop_adj, e_old);
  4545. delta_radius = dr_old;
  4546. home_offset[Z_AXIS] = zh_old;
  4547. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4548. delta_tower_angle_trim[B_AXIS] = beta_old;
  4549. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4550. }
  4551. // print report
  4552. if (verbose_level != 1) {
  4553. SERIAL_PROTOCOLPGM(". ");
  4554. print_signed_float(PSTR("c"), z_at_pt[0]);
  4555. if (_4p_towers_points || _7p_calibration) {
  4556. print_signed_float(PSTR(" x"), z_at_pt[1]);
  4557. print_signed_float(PSTR(" y"), z_at_pt[5]);
  4558. print_signed_float(PSTR(" z"), z_at_pt[9]);
  4559. }
  4560. if (!_4p_opposite_points) SERIAL_EOL();
  4561. if ((_4p_opposite_points) || _7p_calibration) {
  4562. if (_7p_calibration) {
  4563. SERIAL_CHAR('.');
  4564. SERIAL_PROTOCOL_SP(13);
  4565. }
  4566. print_signed_float(PSTR(" yz"), z_at_pt[7]);
  4567. print_signed_float(PSTR("zx"), z_at_pt[11]);
  4568. print_signed_float(PSTR("xy"), z_at_pt[3]);
  4569. SERIAL_EOL();
  4570. }
  4571. }
  4572. if (test_precision != 0.0) { // !forced end
  4573. if ((zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) && iterations > force_iterations) { // end iterations
  4574. SERIAL_PROTOCOLPGM("Calibration OK");
  4575. SERIAL_PROTOCOL_SP(36);
  4576. if (zero_std_dev >= test_precision)
  4577. SERIAL_PROTOCOLPGM("rolling back.");
  4578. else {
  4579. SERIAL_PROTOCOLPGM("std dev:");
  4580. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4581. }
  4582. SERIAL_EOL();
  4583. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4584. }
  4585. else { // !end iterations
  4586. char mess[15] = "No convergence";
  4587. if (iterations < 31)
  4588. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4589. SERIAL_PROTOCOL(mess);
  4590. SERIAL_PROTOCOL_SP(36);
  4591. SERIAL_PROTOCOLPGM("std dev:");
  4592. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4593. SERIAL_EOL();
  4594. lcd_setstatus(mess);
  4595. }
  4596. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4597. if (!_1p_calibration) {
  4598. print_signed_float(PSTR(" Ex"), endstop_adj[A_AXIS]);
  4599. print_signed_float(PSTR("Ey"), endstop_adj[B_AXIS]);
  4600. print_signed_float(PSTR("Ez"), endstop_adj[C_AXIS]);
  4601. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4602. }
  4603. SERIAL_EOL();
  4604. if (_7p_calibration && towers_set) {
  4605. SERIAL_PROTOCOLPGM(".Tower angle : ");
  4606. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4607. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4608. SERIAL_PROTOCOLPGM(" Tz:+0.00");
  4609. SERIAL_EOL();
  4610. }
  4611. if ((zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) && iterations > force_iterations)
  4612. serialprintPGM(save_message);
  4613. SERIAL_EOL();
  4614. }
  4615. else { // forced end
  4616. if (verbose_level == 0) {
  4617. SERIAL_PROTOCOLPGM("End DRY-RUN");
  4618. SERIAL_PROTOCOL_SP(39);
  4619. SERIAL_PROTOCOLPGM("std dev:");
  4620. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4621. SERIAL_EOL();
  4622. }
  4623. else {
  4624. SERIAL_PROTOCOLLNPGM("Calibration OK");
  4625. LCD_MESSAGEPGM("Calibration OK"); // TODO: Make translatable string
  4626. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4627. SERIAL_EOL();
  4628. serialprintPGM(save_message);
  4629. SERIAL_EOL();
  4630. }
  4631. }
  4632. endstops.enable(true);
  4633. home_delta();
  4634. endstops.not_homing();
  4635. }
  4636. while ((zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31) || iterations <= force_iterations);
  4637. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4638. do_blocking_move_to_z(delta_clip_start_height);
  4639. #endif
  4640. STOW_PROBE();
  4641. clean_up_after_endstop_or_probe_move();
  4642. #if HOTENDS > 1
  4643. tool_change(old_tool_index, 0, true);
  4644. #endif
  4645. }
  4646. #endif // DELTA_AUTO_CALIBRATION
  4647. #endif // HAS_BED_PROBE
  4648. #if ENABLED(G38_PROBE_TARGET)
  4649. static bool G38_run_probe() {
  4650. bool G38_pass_fail = false;
  4651. // Get direction of move and retract
  4652. float retract_mm[XYZ];
  4653. LOOP_XYZ(i) {
  4654. float dist = destination[i] - current_position[i];
  4655. retract_mm[i] = FABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4656. }
  4657. stepper.synchronize(); // wait until the machine is idle
  4658. // Move until destination reached or target hit
  4659. endstops.enable(true);
  4660. G38_move = true;
  4661. G38_endstop_hit = false;
  4662. prepare_move_to_destination();
  4663. stepper.synchronize();
  4664. G38_move = false;
  4665. endstops.hit_on_purpose();
  4666. set_current_from_steppers_for_axis(ALL_AXES);
  4667. SYNC_PLAN_POSITION_KINEMATIC();
  4668. if (G38_endstop_hit) {
  4669. G38_pass_fail = true;
  4670. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4671. // Move away by the retract distance
  4672. set_destination_to_current();
  4673. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4674. endstops.enable(false);
  4675. prepare_move_to_destination();
  4676. stepper.synchronize();
  4677. feedrate_mm_s /= 4;
  4678. // Bump the target more slowly
  4679. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4680. endstops.enable(true);
  4681. G38_move = true;
  4682. prepare_move_to_destination();
  4683. stepper.synchronize();
  4684. G38_move = false;
  4685. set_current_from_steppers_for_axis(ALL_AXES);
  4686. SYNC_PLAN_POSITION_KINEMATIC();
  4687. #endif
  4688. }
  4689. endstops.hit_on_purpose();
  4690. endstops.not_homing();
  4691. return G38_pass_fail;
  4692. }
  4693. /**
  4694. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4695. * G38.3 - probe toward workpiece, stop on contact
  4696. *
  4697. * Like G28 except uses Z min probe for all axes
  4698. */
  4699. inline void gcode_G38(bool is_38_2) {
  4700. // Get X Y Z E F
  4701. gcode_get_destination();
  4702. setup_for_endstop_or_probe_move();
  4703. // If any axis has enough movement, do the move
  4704. LOOP_XYZ(i)
  4705. if (FABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4706. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate(i);
  4707. // If G38.2 fails throw an error
  4708. if (!G38_run_probe() && is_38_2) {
  4709. SERIAL_ERROR_START();
  4710. SERIAL_ERRORLNPGM("Failed to reach target");
  4711. }
  4712. break;
  4713. }
  4714. clean_up_after_endstop_or_probe_move();
  4715. }
  4716. #endif // G38_PROBE_TARGET
  4717. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4718. /**
  4719. * G42: Move X & Y axes to mesh coordinates (I & J)
  4720. */
  4721. inline void gcode_G42() {
  4722. if (IsRunning()) {
  4723. const bool hasI = parser.seenval('I');
  4724. const int8_t ix = hasI ? parser.value_int() : 0;
  4725. const bool hasJ = parser.seenval('J');
  4726. const int8_t iy = hasJ ? parser.value_int() : 0;
  4727. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4728. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4729. return;
  4730. }
  4731. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4732. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4733. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4734. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4735. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4736. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4737. #elif ENABLED(MESH_BED_LEVELING)
  4738. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4739. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4740. #endif
  4741. set_destination_to_current();
  4742. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4743. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4744. if (parser.boolval('P')) {
  4745. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4746. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4747. }
  4748. const float fval = parser.linearval('F');
  4749. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  4750. // SCARA kinematic has "safe" XY raw moves
  4751. #if IS_SCARA
  4752. prepare_uninterpolated_move_to_destination();
  4753. #else
  4754. prepare_move_to_destination();
  4755. #endif
  4756. }
  4757. }
  4758. #endif // AUTO_BED_LEVELING_UBL
  4759. /**
  4760. * G92: Set current position to given X Y Z E
  4761. */
  4762. inline void gcode_G92() {
  4763. bool didXYZ = false,
  4764. didE = parser.seenval('E');
  4765. if (!didE) stepper.synchronize();
  4766. LOOP_XYZE(i) {
  4767. if (parser.seenval(axis_codes[i])) {
  4768. #if IS_SCARA
  4769. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4770. if (i != E_AXIS) didXYZ = true;
  4771. #else
  4772. #if HAS_POSITION_SHIFT
  4773. const float p = current_position[i];
  4774. #endif
  4775. const float v = parser.value_axis_units((AxisEnum)i);
  4776. current_position[i] = v;
  4777. if (i != E_AXIS) {
  4778. didXYZ = true;
  4779. #if HAS_POSITION_SHIFT
  4780. position_shift[i] += v - p; // Offset the coordinate space
  4781. update_software_endstops((AxisEnum)i);
  4782. #if ENABLED(I2C_POSITION_ENCODERS)
  4783. I2CPEM.encoders[I2CPEM.idx_from_axis((AxisEnum)i)].set_axis_offset(position_shift[i]);
  4784. #endif
  4785. #endif
  4786. }
  4787. #endif
  4788. }
  4789. }
  4790. if (didXYZ)
  4791. SYNC_PLAN_POSITION_KINEMATIC();
  4792. else if (didE)
  4793. sync_plan_position_e();
  4794. report_current_position();
  4795. }
  4796. #if HAS_RESUME_CONTINUE
  4797. /**
  4798. * M0: Unconditional stop - Wait for user button press on LCD
  4799. * M1: Conditional stop - Wait for user button press on LCD
  4800. */
  4801. inline void gcode_M0_M1() {
  4802. const char * const args = parser.string_arg;
  4803. millis_t ms = 0;
  4804. bool hasP = false, hasS = false;
  4805. if (parser.seenval('P')) {
  4806. ms = parser.value_millis(); // milliseconds to wait
  4807. hasP = ms > 0;
  4808. }
  4809. if (parser.seenval('S')) {
  4810. ms = parser.value_millis_from_seconds(); // seconds to wait
  4811. hasS = ms > 0;
  4812. }
  4813. #if ENABLED(ULTIPANEL)
  4814. if (!hasP && !hasS && args && *args)
  4815. lcd_setstatus(args, true);
  4816. else {
  4817. LCD_MESSAGEPGM(MSG_USERWAIT);
  4818. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4819. dontExpireStatus();
  4820. #endif
  4821. }
  4822. #else
  4823. if (!hasP && !hasS && args && *args) {
  4824. SERIAL_ECHO_START();
  4825. SERIAL_ECHOLN(args);
  4826. }
  4827. #endif
  4828. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4829. wait_for_user = true;
  4830. stepper.synchronize();
  4831. refresh_cmd_timeout();
  4832. if (ms > 0) {
  4833. ms += previous_cmd_ms; // wait until this time for a click
  4834. while (PENDING(millis(), ms) && wait_for_user) idle();
  4835. }
  4836. else {
  4837. #if ENABLED(ULTIPANEL)
  4838. if (lcd_detected()) {
  4839. while (wait_for_user) idle();
  4840. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4841. }
  4842. #else
  4843. while (wait_for_user) idle();
  4844. #endif
  4845. }
  4846. wait_for_user = false;
  4847. KEEPALIVE_STATE(IN_HANDLER);
  4848. }
  4849. #endif // HAS_RESUME_CONTINUE
  4850. #if ENABLED(SPINDLE_LASER_ENABLE)
  4851. /**
  4852. * M3: Spindle Clockwise
  4853. * M4: Spindle Counter-clockwise
  4854. *
  4855. * S0 turns off spindle.
  4856. *
  4857. * If no speed PWM output is defined then M3/M4 just turns it on.
  4858. *
  4859. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4860. * Hardware PWM is required. ISRs are too slow.
  4861. *
  4862. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4863. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4864. *
  4865. * The system automatically sets WGM to Mode 1, so no special
  4866. * initialization is needed.
  4867. *
  4868. * WGM bits for timer 2 are automatically set by the system to
  4869. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4870. * No special initialization is needed.
  4871. *
  4872. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4873. * factors for timers 2, 3, 4, and 5 are acceptable.
  4874. *
  4875. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4876. * the spindle/laser during power-up or when connecting to the host
  4877. * (usually goes through a reset which sets all I/O pins to tri-state)
  4878. *
  4879. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4880. */
  4881. // Wait for spindle to come up to speed
  4882. inline void delay_for_power_up() {
  4883. refresh_cmd_timeout();
  4884. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4885. }
  4886. // Wait for spindle to stop turning
  4887. inline void delay_for_power_down() {
  4888. refresh_cmd_timeout();
  4889. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4890. }
  4891. /**
  4892. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4893. *
  4894. * it accepts inputs of 0-255
  4895. */
  4896. inline void ocr_val_mode() {
  4897. uint8_t spindle_laser_power = parser.value_byte();
  4898. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4899. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4900. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4901. }
  4902. inline void gcode_M3_M4(bool is_M3) {
  4903. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4904. #if SPINDLE_DIR_CHANGE
  4905. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4906. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4907. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4908. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4909. ) {
  4910. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4911. delay_for_power_down();
  4912. }
  4913. digitalWrite(SPINDLE_DIR_PIN, rotation_dir);
  4914. #endif
  4915. /**
  4916. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4917. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4918. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4919. */
  4920. #if ENABLED(SPINDLE_LASER_PWM)
  4921. if (parser.seen('O')) ocr_val_mode();
  4922. else {
  4923. const float spindle_laser_power = parser.floatval('S');
  4924. if (spindle_laser_power == 0) {
  4925. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4926. delay_for_power_down();
  4927. }
  4928. else {
  4929. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4930. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4931. if (spindle_laser_power <= SPEED_POWER_MIN)
  4932. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4933. if (spindle_laser_power >= SPEED_POWER_MAX)
  4934. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4935. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4936. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4937. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4938. delay_for_power_up();
  4939. }
  4940. }
  4941. #else
  4942. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4943. delay_for_power_up();
  4944. #endif
  4945. }
  4946. /**
  4947. * M5 turn off spindle
  4948. */
  4949. inline void gcode_M5() {
  4950. stepper.synchronize();
  4951. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4952. delay_for_power_down();
  4953. }
  4954. #endif // SPINDLE_LASER_ENABLE
  4955. /**
  4956. * M17: Enable power on all stepper motors
  4957. */
  4958. inline void gcode_M17() {
  4959. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4960. enable_all_steppers();
  4961. }
  4962. #if IS_KINEMATIC
  4963. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4964. #else
  4965. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4966. #endif
  4967. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4968. static float resume_position[XYZE];
  4969. static bool move_away_flag = false;
  4970. #if ENABLED(SDSUPPORT)
  4971. static bool sd_print_paused = false;
  4972. #endif
  4973. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4974. static millis_t next_buzz = 0;
  4975. static int8_t runout_beep = 0;
  4976. if (init) next_buzz = runout_beep = 0;
  4977. const millis_t ms = millis();
  4978. if (ELAPSED(ms, next_buzz)) {
  4979. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4980. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4981. BUZZ(300, 2000);
  4982. runout_beep++;
  4983. }
  4984. }
  4985. }
  4986. static void ensure_safe_temperature() {
  4987. bool heaters_heating = true;
  4988. wait_for_heatup = true; // M108 will clear this
  4989. while (wait_for_heatup && heaters_heating) {
  4990. idle();
  4991. heaters_heating = false;
  4992. HOTEND_LOOP() {
  4993. if (thermalManager.degTargetHotend(e) && abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > TEMP_HYSTERESIS) {
  4994. heaters_heating = true;
  4995. #if ENABLED(ULTIPANEL)
  4996. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  4997. #endif
  4998. break;
  4999. }
  5000. }
  5001. }
  5002. }
  5003. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  5004. const float &unload_length = 0 , const int8_t max_beep_count = 0, const bool show_lcd = false
  5005. ) {
  5006. if (move_away_flag) return false; // already paused
  5007. if (!DEBUGGING(DRYRUN) && (unload_length != 0 || retract != 0)) {
  5008. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5009. if (!thermalManager.allow_cold_extrude &&
  5010. thermalManager.degTargetHotend(active_extruder) < thermalManager.extrude_min_temp) {
  5011. SERIAL_ERROR_START();
  5012. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  5013. return false;
  5014. }
  5015. #endif
  5016. ensure_safe_temperature(); // wait for extruder to heat up before unloading
  5017. }
  5018. // Indicate that the printer is paused
  5019. move_away_flag = true;
  5020. // Pause the print job and timer
  5021. #if ENABLED(SDSUPPORT)
  5022. if (card.sdprinting) {
  5023. card.pauseSDPrint();
  5024. sd_print_paused = true;
  5025. }
  5026. #endif
  5027. print_job_timer.pause();
  5028. // Show initial message and wait for synchronize steppers
  5029. if (show_lcd) {
  5030. #if ENABLED(ULTIPANEL)
  5031. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  5032. #endif
  5033. }
  5034. stepper.synchronize();
  5035. // Save current position
  5036. COPY(resume_position, current_position);
  5037. set_destination_to_current();
  5038. if (retract) {
  5039. // Initial retract before move to filament change position
  5040. destination[E_AXIS] += retract;
  5041. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  5042. }
  5043. // Lift Z axis
  5044. if (z_lift > 0) {
  5045. destination[Z_AXIS] += z_lift;
  5046. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  5047. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5048. }
  5049. // Move XY axes to filament exchange position
  5050. destination[X_AXIS] = x_pos;
  5051. destination[Y_AXIS] = y_pos;
  5052. clamp_to_software_endstops(destination);
  5053. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5054. stepper.synchronize();
  5055. if (unload_length != 0) {
  5056. if (show_lcd) {
  5057. #if ENABLED(ULTIPANEL)
  5058. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  5059. idle();
  5060. #endif
  5061. }
  5062. // Unload filament
  5063. destination[E_AXIS] += unload_length;
  5064. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  5065. stepper.synchronize();
  5066. }
  5067. if (show_lcd) {
  5068. #if ENABLED(ULTIPANEL)
  5069. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5070. #endif
  5071. }
  5072. #if HAS_BUZZER
  5073. filament_change_beep(max_beep_count, true);
  5074. #endif
  5075. idle();
  5076. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  5077. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  5078. disable_e_steppers();
  5079. safe_delay(100);
  5080. #endif
  5081. // Start the heater idle timers
  5082. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5083. HOTEND_LOOP()
  5084. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5085. return true;
  5086. }
  5087. static void wait_for_filament_reload(const int8_t max_beep_count = 0) {
  5088. bool nozzle_timed_out = false;
  5089. // Wait for filament insert by user and press button
  5090. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5091. wait_for_user = true; // LCD click or M108 will clear this
  5092. while (wait_for_user) {
  5093. #if HAS_BUZZER
  5094. filament_change_beep(max_beep_count);
  5095. #endif
  5096. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  5097. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  5098. if (!nozzle_timed_out)
  5099. HOTEND_LOOP()
  5100. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5101. if (nozzle_timed_out) {
  5102. #if ENABLED(ULTIPANEL)
  5103. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  5104. #endif
  5105. // Wait for LCD click or M108
  5106. while (wait_for_user) idle(true);
  5107. // Re-enable the heaters if they timed out
  5108. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  5109. // Wait for the heaters to reach the target temperatures
  5110. ensure_safe_temperature();
  5111. #if ENABLED(ULTIPANEL)
  5112. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5113. #endif
  5114. // Start the heater idle timers
  5115. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5116. HOTEND_LOOP()
  5117. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5118. wait_for_user = true; /* Wait for user to load filament */
  5119. nozzle_timed_out = false;
  5120. #if HAS_BUZZER
  5121. filament_change_beep(max_beep_count, true);
  5122. #endif
  5123. }
  5124. idle(true);
  5125. }
  5126. KEEPALIVE_STATE(IN_HANDLER);
  5127. }
  5128. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, const int8_t max_beep_count = 0) {
  5129. bool nozzle_timed_out = false;
  5130. if (!move_away_flag) return;
  5131. // Re-enable the heaters if they timed out
  5132. HOTEND_LOOP() {
  5133. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5134. thermalManager.reset_heater_idle_timer(e);
  5135. }
  5136. if (nozzle_timed_out) ensure_safe_temperature();
  5137. #if HAS_BUZZER
  5138. filament_change_beep(max_beep_count, true);
  5139. #endif
  5140. if (load_length != 0) {
  5141. #if ENABLED(ULTIPANEL)
  5142. // Show "insert filament"
  5143. if (nozzle_timed_out)
  5144. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5145. #endif
  5146. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5147. wait_for_user = true; // LCD click or M108 will clear this
  5148. while (wait_for_user && nozzle_timed_out) {
  5149. #if HAS_BUZZER
  5150. filament_change_beep(max_beep_count);
  5151. #endif
  5152. idle(true);
  5153. }
  5154. KEEPALIVE_STATE(IN_HANDLER);
  5155. #if ENABLED(ULTIPANEL)
  5156. // Show "load" message
  5157. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5158. #endif
  5159. // Load filament
  5160. destination[E_AXIS] += load_length;
  5161. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5162. stepper.synchronize();
  5163. }
  5164. #if ENABLED(ULTIPANEL) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5165. float extrude_length = initial_extrude_length;
  5166. do {
  5167. if (extrude_length > 0) {
  5168. // "Wait for filament extrude"
  5169. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5170. // Extrude filament to get into hotend
  5171. destination[E_AXIS] += extrude_length;
  5172. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5173. stepper.synchronize();
  5174. }
  5175. // Show "Extrude More" / "Resume" menu and wait for reply
  5176. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5177. wait_for_user = false;
  5178. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5179. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5180. KEEPALIVE_STATE(IN_HANDLER);
  5181. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5182. // Keep looping if "Extrude More" was selected
  5183. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5184. #endif
  5185. #if ENABLED(ULTIPANEL)
  5186. // "Wait for print to resume"
  5187. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5188. #endif
  5189. // Set extruder to saved position
  5190. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5191. planner.set_e_position_mm(current_position[E_AXIS]);
  5192. #if IS_KINEMATIC
  5193. // Move XYZ to starting position
  5194. planner.buffer_line_kinematic(resume_position, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5195. #else
  5196. // Move XY to starting position, then Z
  5197. destination[X_AXIS] = resume_position[X_AXIS];
  5198. destination[Y_AXIS] = resume_position[Y_AXIS];
  5199. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5200. destination[Z_AXIS] = resume_position[Z_AXIS];
  5201. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5202. #endif
  5203. stepper.synchronize();
  5204. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5205. filament_ran_out = false;
  5206. #endif
  5207. #if ENABLED(ULTIPANEL)
  5208. // Show status screen
  5209. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5210. #endif
  5211. #if ENABLED(SDSUPPORT)
  5212. if (sd_print_paused) {
  5213. card.startFileprint();
  5214. sd_print_paused = false;
  5215. }
  5216. #endif
  5217. move_away_flag = false;
  5218. }
  5219. #endif // ADVANCED_PAUSE_FEATURE
  5220. #if ENABLED(SDSUPPORT)
  5221. /**
  5222. * M20: List SD card to serial output
  5223. */
  5224. inline void gcode_M20() {
  5225. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5226. card.ls();
  5227. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5228. }
  5229. /**
  5230. * M21: Init SD Card
  5231. */
  5232. inline void gcode_M21() { card.initsd(); }
  5233. /**
  5234. * M22: Release SD Card
  5235. */
  5236. inline void gcode_M22() { card.release(); }
  5237. /**
  5238. * M23: Open a file
  5239. */
  5240. inline void gcode_M23() { card.openFile(parser.string_arg, true); }
  5241. /**
  5242. * M24: Start or Resume SD Print
  5243. */
  5244. inline void gcode_M24() {
  5245. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5246. resume_print();
  5247. #endif
  5248. card.startFileprint();
  5249. print_job_timer.start();
  5250. }
  5251. /**
  5252. * M25: Pause SD Print
  5253. */
  5254. inline void gcode_M25() {
  5255. card.pauseSDPrint();
  5256. print_job_timer.pause();
  5257. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5258. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5259. #endif
  5260. }
  5261. /**
  5262. * M26: Set SD Card file index
  5263. */
  5264. inline void gcode_M26() {
  5265. if (card.cardOK && parser.seenval('S'))
  5266. card.setIndex(parser.value_long());
  5267. }
  5268. /**
  5269. * M27: Get SD Card status
  5270. */
  5271. inline void gcode_M27() { card.getStatus(); }
  5272. /**
  5273. * M28: Start SD Write
  5274. */
  5275. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5276. /**
  5277. * M29: Stop SD Write
  5278. * Processed in write to file routine above
  5279. */
  5280. inline void gcode_M29() {
  5281. // card.saving = false;
  5282. }
  5283. /**
  5284. * M30 <filename>: Delete SD Card file
  5285. */
  5286. inline void gcode_M30() {
  5287. if (card.cardOK) {
  5288. card.closefile();
  5289. card.removeFile(parser.string_arg);
  5290. }
  5291. }
  5292. #endif // SDSUPPORT
  5293. /**
  5294. * M31: Get the time since the start of SD Print (or last M109)
  5295. */
  5296. inline void gcode_M31() {
  5297. char buffer[21];
  5298. duration_t elapsed = print_job_timer.duration();
  5299. elapsed.toString(buffer);
  5300. lcd_setstatus(buffer);
  5301. SERIAL_ECHO_START();
  5302. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5303. }
  5304. #if ENABLED(SDSUPPORT)
  5305. /**
  5306. * M32: Select file and start SD Print
  5307. */
  5308. inline void gcode_M32() {
  5309. if (card.sdprinting)
  5310. stepper.synchronize();
  5311. char* namestartpos = parser.string_arg;
  5312. const bool call_procedure = parser.boolval('P');
  5313. if (card.cardOK) {
  5314. card.openFile(namestartpos, true, call_procedure);
  5315. if (parser.seenval('S'))
  5316. card.setIndex(parser.value_long());
  5317. card.startFileprint();
  5318. // Procedure calls count as normal print time.
  5319. if (!call_procedure) print_job_timer.start();
  5320. }
  5321. }
  5322. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5323. /**
  5324. * M33: Get the long full path of a file or folder
  5325. *
  5326. * Parameters:
  5327. * <dospath> Case-insensitive DOS-style path to a file or folder
  5328. *
  5329. * Example:
  5330. * M33 miscel~1/armchair/armcha~1.gco
  5331. *
  5332. * Output:
  5333. * /Miscellaneous/Armchair/Armchair.gcode
  5334. */
  5335. inline void gcode_M33() {
  5336. card.printLongPath(parser.string_arg);
  5337. }
  5338. #endif
  5339. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5340. /**
  5341. * M34: Set SD Card Sorting Options
  5342. */
  5343. inline void gcode_M34() {
  5344. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5345. if (parser.seenval('F')) {
  5346. const int v = parser.value_long();
  5347. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5348. }
  5349. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5350. }
  5351. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5352. /**
  5353. * M928: Start SD Write
  5354. */
  5355. inline void gcode_M928() {
  5356. card.openLogFile(parser.string_arg);
  5357. }
  5358. #endif // SDSUPPORT
  5359. /**
  5360. * Sensitive pin test for M42, M226
  5361. */
  5362. static bool pin_is_protected(const int8_t pin) {
  5363. static const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  5364. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5365. if (pin == (int8_t)pgm_read_byte(&sensitive_pins[i])) return true;
  5366. return false;
  5367. }
  5368. /**
  5369. * M42: Change pin status via GCode
  5370. *
  5371. * P<pin> Pin number (LED if omitted)
  5372. * S<byte> Pin status from 0 - 255
  5373. */
  5374. inline void gcode_M42() {
  5375. if (!parser.seenval('S')) return;
  5376. const byte pin_status = parser.value_byte();
  5377. const int pin_number = parser.intval('P', LED_PIN);
  5378. if (pin_number < 0) return;
  5379. if (pin_is_protected(pin_number)) {
  5380. SERIAL_ERROR_START();
  5381. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5382. return;
  5383. }
  5384. pinMode(pin_number, OUTPUT);
  5385. digitalWrite(pin_number, pin_status);
  5386. analogWrite(pin_number, pin_status);
  5387. #if FAN_COUNT > 0
  5388. switch (pin_number) {
  5389. #if HAS_FAN0
  5390. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5391. #endif
  5392. #if HAS_FAN1
  5393. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5394. #endif
  5395. #if HAS_FAN2
  5396. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5397. #endif
  5398. }
  5399. #endif
  5400. }
  5401. #if ENABLED(PINS_DEBUGGING)
  5402. #include "pinsDebug.h"
  5403. inline void toggle_pins() {
  5404. const bool I_flag = parser.boolval('I');
  5405. const int repeat = parser.intval('R', 1),
  5406. start = parser.intval('S'),
  5407. end = parser.intval('E', NUM_DIGITAL_PINS - 1),
  5408. wait = parser.intval('W', 500);
  5409. for (uint8_t pin = start; pin <= end; pin++) {
  5410. //report_pin_state_extended(pin, I_flag, false);
  5411. if (!I_flag && pin_is_protected(pin)) {
  5412. report_pin_state_extended(pin, I_flag, true, "Untouched ");
  5413. SERIAL_EOL();
  5414. }
  5415. else {
  5416. report_pin_state_extended(pin, I_flag, true, "Pulsing ");
  5417. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  5418. if (pin == 46) {
  5419. SET_OUTPUT(46);
  5420. for (int16_t j = 0; j < repeat; j++) {
  5421. WRITE(46, 0); safe_delay(wait);
  5422. WRITE(46, 1); safe_delay(wait);
  5423. WRITE(46, 0); safe_delay(wait);
  5424. }
  5425. }
  5426. else if (pin == 47) {
  5427. SET_OUTPUT(47);
  5428. for (int16_t j = 0; j < repeat; j++) {
  5429. WRITE(47, 0); safe_delay(wait);
  5430. WRITE(47, 1); safe_delay(wait);
  5431. WRITE(47, 0); safe_delay(wait);
  5432. }
  5433. }
  5434. else
  5435. #endif
  5436. {
  5437. pinMode(pin, OUTPUT);
  5438. for (int16_t j = 0; j < repeat; j++) {
  5439. digitalWrite(pin, 0); safe_delay(wait);
  5440. digitalWrite(pin, 1); safe_delay(wait);
  5441. digitalWrite(pin, 0); safe_delay(wait);
  5442. }
  5443. }
  5444. }
  5445. SERIAL_EOL();
  5446. }
  5447. SERIAL_ECHOLNPGM("Done.");
  5448. } // toggle_pins
  5449. inline void servo_probe_test() {
  5450. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5451. SERIAL_ERROR_START();
  5452. SERIAL_ERRORLNPGM("SERVO not setup");
  5453. #elif !HAS_Z_SERVO_ENDSTOP
  5454. SERIAL_ERROR_START();
  5455. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5456. #else
  5457. const uint8_t probe_index = parser.byteval('P', Z_ENDSTOP_SERVO_NR);
  5458. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5459. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5460. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5461. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5462. bool probe_inverting;
  5463. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5464. #define PROBE_TEST_PIN Z_MIN_PIN
  5465. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5466. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5467. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5468. #if Z_MIN_ENDSTOP_INVERTING
  5469. SERIAL_PROTOCOLLNPGM("true");
  5470. #else
  5471. SERIAL_PROTOCOLLNPGM("false");
  5472. #endif
  5473. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5474. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5475. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5476. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5477. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5478. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5479. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5480. SERIAL_PROTOCOLLNPGM("true");
  5481. #else
  5482. SERIAL_PROTOCOLLNPGM("false");
  5483. #endif
  5484. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5485. #endif
  5486. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5487. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  5488. bool deploy_state, stow_state;
  5489. for (uint8_t i = 0; i < 4; i++) {
  5490. servo[probe_index].move(z_servo_angle[0]); //deploy
  5491. safe_delay(500);
  5492. deploy_state = digitalRead(PROBE_TEST_PIN);
  5493. servo[probe_index].move(z_servo_angle[1]); //stow
  5494. safe_delay(500);
  5495. stow_state = digitalRead(PROBE_TEST_PIN);
  5496. }
  5497. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5498. refresh_cmd_timeout();
  5499. if (deploy_state != stow_state) {
  5500. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5501. if (deploy_state) {
  5502. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5503. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5504. }
  5505. else {
  5506. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5507. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5508. }
  5509. #if ENABLED(BLTOUCH)
  5510. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5511. #endif
  5512. }
  5513. else { // measure active signal length
  5514. servo[probe_index].move(z_servo_angle[0]); // deploy
  5515. safe_delay(500);
  5516. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5517. uint16_t probe_counter = 0;
  5518. // Allow 30 seconds max for operator to trigger probe
  5519. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5520. safe_delay(2);
  5521. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5522. refresh_cmd_timeout();
  5523. if (deploy_state != digitalRead(PROBE_TEST_PIN)) { // probe triggered
  5524. for (probe_counter = 1; probe_counter < 50 && deploy_state != digitalRead(PROBE_TEST_PIN); ++probe_counter)
  5525. safe_delay(2);
  5526. if (probe_counter == 50)
  5527. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5528. else if (probe_counter >= 2)
  5529. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5530. else
  5531. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5532. servo[probe_index].move(z_servo_angle[1]); //stow
  5533. } // pulse detected
  5534. } // for loop waiting for trigger
  5535. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5536. } // measure active signal length
  5537. #endif
  5538. } // servo_probe_test
  5539. /**
  5540. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5541. *
  5542. * M43 - report name and state of pin(s)
  5543. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5544. * I Flag to ignore Marlin's pin protection.
  5545. *
  5546. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5547. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5548. * I Flag to ignore Marlin's pin protection.
  5549. *
  5550. * M43 E<bool> - Enable / disable background endstop monitoring
  5551. * - Machine continues to operate
  5552. * - Reports changes to endstops
  5553. * - Toggles LED_PIN when an endstop changes
  5554. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5555. *
  5556. * M43 T - Toggle pin(s) and report which pin is being toggled
  5557. * S<pin> - Start Pin number. If not given, will default to 0
  5558. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5559. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5560. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5561. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5562. *
  5563. * M43 S - Servo probe test
  5564. * P<index> - Probe index (optional - defaults to 0
  5565. */
  5566. inline void gcode_M43() {
  5567. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  5568. toggle_pins();
  5569. return;
  5570. }
  5571. // Enable or disable endstop monitoring
  5572. if (parser.seen('E')) {
  5573. endstop_monitor_flag = parser.value_bool();
  5574. SERIAL_PROTOCOLPGM("endstop monitor ");
  5575. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  5576. SERIAL_PROTOCOLLNPGM("abled");
  5577. return;
  5578. }
  5579. if (parser.seen('S')) {
  5580. servo_probe_test();
  5581. return;
  5582. }
  5583. // Get the range of pins to test or watch
  5584. const uint8_t first_pin = parser.byteval('P'),
  5585. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5586. if (first_pin > last_pin) return;
  5587. const bool ignore_protection = parser.boolval('I');
  5588. // Watch until click, M108, or reset
  5589. if (parser.boolval('W')) {
  5590. SERIAL_PROTOCOLLNPGM("Watching pins");
  5591. byte pin_state[last_pin - first_pin + 1];
  5592. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5593. if (pin_is_protected(pin) && !ignore_protection) continue;
  5594. pinMode(pin, INPUT_PULLUP);
  5595. delay(1);
  5596. /*
  5597. if (IS_ANALOG(pin))
  5598. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5599. else
  5600. //*/
  5601. pin_state[pin - first_pin] = digitalRead(pin);
  5602. }
  5603. #if HAS_RESUME_CONTINUE
  5604. wait_for_user = true;
  5605. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5606. #endif
  5607. for (;;) {
  5608. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5609. if (pin_is_protected(pin) && !ignore_protection) continue;
  5610. const byte val =
  5611. /*
  5612. IS_ANALOG(pin)
  5613. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5614. :
  5615. //*/
  5616. digitalRead(pin);
  5617. if (val != pin_state[pin - first_pin]) {
  5618. report_pin_state_extended(pin, ignore_protection, false);
  5619. pin_state[pin - first_pin] = val;
  5620. }
  5621. }
  5622. #if HAS_RESUME_CONTINUE
  5623. if (!wait_for_user) {
  5624. KEEPALIVE_STATE(IN_HANDLER);
  5625. break;
  5626. }
  5627. #endif
  5628. safe_delay(200);
  5629. }
  5630. return;
  5631. }
  5632. // Report current state of selected pin(s)
  5633. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5634. report_pin_state_extended(pin, ignore_protection, true);
  5635. }
  5636. #endif // PINS_DEBUGGING
  5637. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5638. /**
  5639. * M48: Z probe repeatability measurement function.
  5640. *
  5641. * Usage:
  5642. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5643. * P = Number of sampled points (4-50, default 10)
  5644. * X = Sample X position
  5645. * Y = Sample Y position
  5646. * V = Verbose level (0-4, default=1)
  5647. * E = Engage Z probe for each reading
  5648. * L = Number of legs of movement before probe
  5649. * S = Schizoid (Or Star if you prefer)
  5650. *
  5651. * This function assumes the bed has been homed. Specifically, that a G28 command
  5652. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5653. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5654. * regenerated.
  5655. */
  5656. inline void gcode_M48() {
  5657. if (axis_unhomed_error()) return;
  5658. const int8_t verbose_level = parser.byteval('V', 1);
  5659. if (!WITHIN(verbose_level, 0, 4)) {
  5660. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5661. return;
  5662. }
  5663. if (verbose_level > 0)
  5664. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5665. const int8_t n_samples = parser.byteval('P', 10);
  5666. if (!WITHIN(n_samples, 4, 50)) {
  5667. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5668. return;
  5669. }
  5670. const bool stow_probe_after_each = parser.boolval('E');
  5671. float X_current = current_position[X_AXIS],
  5672. Y_current = current_position[Y_AXIS];
  5673. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  5674. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  5675. #if DISABLED(DELTA)
  5676. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5677. out_of_range_error(PSTR("X"));
  5678. return;
  5679. }
  5680. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5681. out_of_range_error(PSTR("Y"));
  5682. return;
  5683. }
  5684. #else
  5685. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5686. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5687. return;
  5688. }
  5689. #endif
  5690. bool seen_L = parser.seen('L');
  5691. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5692. if (n_legs > 15) {
  5693. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5694. return;
  5695. }
  5696. if (n_legs == 1) n_legs = 2;
  5697. const bool schizoid_flag = parser.boolval('S');
  5698. if (schizoid_flag && !seen_L) n_legs = 7;
  5699. /**
  5700. * Now get everything to the specified probe point So we can safely do a
  5701. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5702. * we don't want to use that as a starting point for each probe.
  5703. */
  5704. if (verbose_level > 2)
  5705. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5706. // Disable bed level correction in M48 because we want the raw data when we probe
  5707. #if HAS_LEVELING
  5708. const bool was_enabled = leveling_is_active();
  5709. set_bed_leveling_enabled(false);
  5710. #endif
  5711. setup_for_endstop_or_probe_move();
  5712. // Move to the first point, deploy, and probe
  5713. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5714. if (isnan(t)) return;
  5715. randomSeed(millis());
  5716. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5717. for (uint8_t n = 0; n < n_samples; n++) {
  5718. if (n_legs) {
  5719. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5720. float angle = random(0.0, 360.0),
  5721. radius = random(
  5722. #if ENABLED(DELTA)
  5723. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5724. #else
  5725. 5, X_MAX_LENGTH / 8
  5726. #endif
  5727. );
  5728. if (verbose_level > 3) {
  5729. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5730. SERIAL_ECHOPAIR(" angle: ", angle);
  5731. SERIAL_ECHOPGM(" Direction: ");
  5732. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5733. SERIAL_ECHOLNPGM("Clockwise");
  5734. }
  5735. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5736. double delta_angle;
  5737. if (schizoid_flag)
  5738. // The points of a 5 point star are 72 degrees apart. We need to
  5739. // skip a point and go to the next one on the star.
  5740. delta_angle = dir * 2.0 * 72.0;
  5741. else
  5742. // If we do this line, we are just trying to move further
  5743. // around the circle.
  5744. delta_angle = dir * (float) random(25, 45);
  5745. angle += delta_angle;
  5746. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5747. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5748. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5749. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5750. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5751. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5752. #if DISABLED(DELTA)
  5753. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5754. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5755. #else
  5756. // If we have gone out too far, we can do a simple fix and scale the numbers
  5757. // back in closer to the origin.
  5758. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5759. X_current *= 0.8;
  5760. Y_current *= 0.8;
  5761. if (verbose_level > 3) {
  5762. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5763. SERIAL_ECHOLNPAIR(", ", Y_current);
  5764. }
  5765. }
  5766. #endif
  5767. if (verbose_level > 3) {
  5768. SERIAL_PROTOCOLPGM("Going to:");
  5769. SERIAL_ECHOPAIR(" X", X_current);
  5770. SERIAL_ECHOPAIR(" Y", Y_current);
  5771. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5772. }
  5773. do_blocking_move_to_xy(X_current, Y_current);
  5774. } // n_legs loop
  5775. } // n_legs
  5776. // Probe a single point
  5777. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5778. /**
  5779. * Get the current mean for the data points we have so far
  5780. */
  5781. double sum = 0.0;
  5782. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5783. mean = sum / (n + 1);
  5784. NOMORE(min, sample_set[n]);
  5785. NOLESS(max, sample_set[n]);
  5786. /**
  5787. * Now, use that mean to calculate the standard deviation for the
  5788. * data points we have so far
  5789. */
  5790. sum = 0.0;
  5791. for (uint8_t j = 0; j <= n; j++)
  5792. sum += sq(sample_set[j] - mean);
  5793. sigma = SQRT(sum / (n + 1));
  5794. if (verbose_level > 0) {
  5795. if (verbose_level > 1) {
  5796. SERIAL_PROTOCOL(n + 1);
  5797. SERIAL_PROTOCOLPGM(" of ");
  5798. SERIAL_PROTOCOL((int)n_samples);
  5799. SERIAL_PROTOCOLPGM(": z: ");
  5800. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5801. if (verbose_level > 2) {
  5802. SERIAL_PROTOCOLPGM(" mean: ");
  5803. SERIAL_PROTOCOL_F(mean, 4);
  5804. SERIAL_PROTOCOLPGM(" sigma: ");
  5805. SERIAL_PROTOCOL_F(sigma, 6);
  5806. SERIAL_PROTOCOLPGM(" min: ");
  5807. SERIAL_PROTOCOL_F(min, 3);
  5808. SERIAL_PROTOCOLPGM(" max: ");
  5809. SERIAL_PROTOCOL_F(max, 3);
  5810. SERIAL_PROTOCOLPGM(" range: ");
  5811. SERIAL_PROTOCOL_F(max-min, 3);
  5812. }
  5813. SERIAL_EOL();
  5814. }
  5815. }
  5816. } // End of probe loop
  5817. if (STOW_PROBE()) return;
  5818. SERIAL_PROTOCOLPGM("Finished!");
  5819. SERIAL_EOL();
  5820. if (verbose_level > 0) {
  5821. SERIAL_PROTOCOLPGM("Mean: ");
  5822. SERIAL_PROTOCOL_F(mean, 6);
  5823. SERIAL_PROTOCOLPGM(" Min: ");
  5824. SERIAL_PROTOCOL_F(min, 3);
  5825. SERIAL_PROTOCOLPGM(" Max: ");
  5826. SERIAL_PROTOCOL_F(max, 3);
  5827. SERIAL_PROTOCOLPGM(" Range: ");
  5828. SERIAL_PROTOCOL_F(max-min, 3);
  5829. SERIAL_EOL();
  5830. }
  5831. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5832. SERIAL_PROTOCOL_F(sigma, 6);
  5833. SERIAL_EOL();
  5834. SERIAL_EOL();
  5835. clean_up_after_endstop_or_probe_move();
  5836. // Re-enable bed level correction if it had been on
  5837. #if HAS_LEVELING
  5838. set_bed_leveling_enabled(was_enabled);
  5839. #endif
  5840. report_current_position();
  5841. }
  5842. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5843. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5844. inline void gcode_M49() {
  5845. ubl.g26_debug_flag ^= true;
  5846. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5847. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5848. }
  5849. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5850. /**
  5851. * M75: Start print timer
  5852. */
  5853. inline void gcode_M75() { print_job_timer.start(); }
  5854. /**
  5855. * M76: Pause print timer
  5856. */
  5857. inline void gcode_M76() { print_job_timer.pause(); }
  5858. /**
  5859. * M77: Stop print timer
  5860. */
  5861. inline void gcode_M77() { print_job_timer.stop(); }
  5862. #if ENABLED(PRINTCOUNTER)
  5863. /**
  5864. * M78: Show print statistics
  5865. */
  5866. inline void gcode_M78() {
  5867. // "M78 S78" will reset the statistics
  5868. if (parser.intval('S') == 78)
  5869. print_job_timer.initStats();
  5870. else
  5871. print_job_timer.showStats();
  5872. }
  5873. #endif
  5874. /**
  5875. * M104: Set hot end temperature
  5876. */
  5877. inline void gcode_M104() {
  5878. if (get_target_extruder_from_command(104)) return;
  5879. if (DEBUGGING(DRYRUN)) return;
  5880. #if ENABLED(SINGLENOZZLE)
  5881. if (target_extruder != active_extruder) return;
  5882. #endif
  5883. if (parser.seenval('S')) {
  5884. const int16_t temp = parser.value_celsius();
  5885. thermalManager.setTargetHotend(temp, target_extruder);
  5886. #if ENABLED(DUAL_X_CARRIAGE)
  5887. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5888. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5889. #endif
  5890. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5891. /**
  5892. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5893. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5894. * standby mode, for instance in a dual extruder setup, without affecting
  5895. * the running print timer.
  5896. */
  5897. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5898. print_job_timer.stop();
  5899. LCD_MESSAGEPGM(WELCOME_MSG);
  5900. }
  5901. #endif
  5902. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5903. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5904. }
  5905. #if ENABLED(AUTOTEMP)
  5906. planner.autotemp_M104_M109();
  5907. #endif
  5908. }
  5909. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5910. void print_heater_state(const float &c, const float &t,
  5911. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5912. const float r,
  5913. #endif
  5914. const int8_t e=-2
  5915. ) {
  5916. SERIAL_PROTOCOLCHAR(' ');
  5917. SERIAL_PROTOCOLCHAR(
  5918. #if HAS_TEMP_BED && HAS_TEMP_HOTEND
  5919. e == -1 ? 'B' : 'T'
  5920. #elif HAS_TEMP_HOTEND
  5921. 'T'
  5922. #else
  5923. 'B'
  5924. #endif
  5925. );
  5926. #if HOTENDS > 1
  5927. if (e >= 0) SERIAL_PROTOCOLCHAR('0' + e);
  5928. #endif
  5929. SERIAL_PROTOCOLCHAR(':');
  5930. SERIAL_PROTOCOL(c);
  5931. SERIAL_PROTOCOLPAIR(" /" , t);
  5932. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5933. SERIAL_PROTOCOLPAIR(" (", r / OVERSAMPLENR);
  5934. SERIAL_PROTOCOLCHAR(')');
  5935. #endif
  5936. }
  5937. void print_heaterstates() {
  5938. #if HAS_TEMP_HOTEND
  5939. print_heater_state(thermalManager.degHotend(target_extruder), thermalManager.degTargetHotend(target_extruder)
  5940. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5941. , thermalManager.rawHotendTemp(target_extruder)
  5942. #endif
  5943. );
  5944. #endif
  5945. #if HAS_TEMP_BED
  5946. print_heater_state(thermalManager.degBed(), thermalManager.degTargetBed(),
  5947. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5948. thermalManager.rawBedTemp(),
  5949. #endif
  5950. -1 // BED
  5951. );
  5952. #endif
  5953. #if HOTENDS > 1
  5954. HOTEND_LOOP() print_heater_state(thermalManager.degHotend(e), thermalManager.degTargetHotend(e),
  5955. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5956. thermalManager.rawHotendTemp(e),
  5957. #endif
  5958. e
  5959. );
  5960. #endif
  5961. SERIAL_PROTOCOLPGM(" @:");
  5962. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5963. #if HAS_TEMP_BED
  5964. SERIAL_PROTOCOLPGM(" B@:");
  5965. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5966. #endif
  5967. #if HOTENDS > 1
  5968. HOTEND_LOOP() {
  5969. SERIAL_PROTOCOLPAIR(" @", e);
  5970. SERIAL_PROTOCOLCHAR(':');
  5971. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5972. }
  5973. #endif
  5974. }
  5975. #endif
  5976. /**
  5977. * M105: Read hot end and bed temperature
  5978. */
  5979. inline void gcode_M105() {
  5980. if (get_target_extruder_from_command(105)) return;
  5981. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5982. SERIAL_PROTOCOLPGM(MSG_OK);
  5983. print_heaterstates();
  5984. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  5985. SERIAL_ERROR_START();
  5986. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  5987. #endif
  5988. SERIAL_EOL();
  5989. }
  5990. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  5991. static uint8_t auto_report_temp_interval;
  5992. static millis_t next_temp_report_ms;
  5993. /**
  5994. * M155: Set temperature auto-report interval. M155 S<seconds>
  5995. */
  5996. inline void gcode_M155() {
  5997. if (parser.seenval('S')) {
  5998. auto_report_temp_interval = parser.value_byte();
  5999. NOMORE(auto_report_temp_interval, 60);
  6000. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6001. }
  6002. }
  6003. inline void auto_report_temperatures() {
  6004. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  6005. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6006. print_heaterstates();
  6007. SERIAL_EOL();
  6008. }
  6009. }
  6010. #endif // AUTO_REPORT_TEMPERATURES
  6011. #if FAN_COUNT > 0
  6012. /**
  6013. * M106: Set Fan Speed
  6014. *
  6015. * S<int> Speed between 0-255
  6016. * P<index> Fan index, if more than one fan
  6017. */
  6018. inline void gcode_M106() {
  6019. uint16_t s = parser.ushortval('S', 255);
  6020. NOMORE(s, 255);
  6021. const uint8_t p = parser.byteval('P', 0);
  6022. if (p < FAN_COUNT) fanSpeeds[p] = s;
  6023. }
  6024. /**
  6025. * M107: Fan Off
  6026. */
  6027. inline void gcode_M107() {
  6028. const uint16_t p = parser.ushortval('P');
  6029. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  6030. }
  6031. #endif // FAN_COUNT > 0
  6032. #if DISABLED(EMERGENCY_PARSER)
  6033. /**
  6034. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  6035. */
  6036. inline void gcode_M108() { wait_for_heatup = false; }
  6037. /**
  6038. * M112: Emergency Stop
  6039. */
  6040. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  6041. /**
  6042. * M410: Quickstop - Abort all planned moves
  6043. *
  6044. * This will stop the carriages mid-move, so most likely they
  6045. * will be out of sync with the stepper position after this.
  6046. */
  6047. inline void gcode_M410() { quickstop_stepper(); }
  6048. #endif
  6049. /**
  6050. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  6051. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  6052. */
  6053. #ifndef MIN_COOLING_SLOPE_DEG
  6054. #define MIN_COOLING_SLOPE_DEG 1.50
  6055. #endif
  6056. #ifndef MIN_COOLING_SLOPE_TIME
  6057. #define MIN_COOLING_SLOPE_TIME 60
  6058. #endif
  6059. inline void gcode_M109() {
  6060. if (get_target_extruder_from_command(109)) return;
  6061. if (DEBUGGING(DRYRUN)) return;
  6062. #if ENABLED(SINGLENOZZLE)
  6063. if (target_extruder != active_extruder) return;
  6064. #endif
  6065. const bool no_wait_for_cooling = parser.seenval('S');
  6066. if (no_wait_for_cooling || parser.seenval('R')) {
  6067. const int16_t temp = parser.value_celsius();
  6068. thermalManager.setTargetHotend(temp, target_extruder);
  6069. #if ENABLED(DUAL_X_CARRIAGE)
  6070. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  6071. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  6072. #endif
  6073. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6074. /**
  6075. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  6076. * standby mode, (e.g., in a dual extruder setup) without affecting
  6077. * the running print timer.
  6078. */
  6079. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  6080. print_job_timer.stop();
  6081. LCD_MESSAGEPGM(WELCOME_MSG);
  6082. }
  6083. else
  6084. print_job_timer.start();
  6085. #endif
  6086. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  6087. }
  6088. else return;
  6089. #if ENABLED(AUTOTEMP)
  6090. planner.autotemp_M104_M109();
  6091. #endif
  6092. #if TEMP_RESIDENCY_TIME > 0
  6093. millis_t residency_start_ms = 0;
  6094. // Loop until the temperature has stabilized
  6095. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  6096. #else
  6097. // Loop until the temperature is very close target
  6098. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  6099. #endif
  6100. float target_temp = -1.0, old_temp = 9999.0;
  6101. bool wants_to_cool = false;
  6102. wait_for_heatup = true;
  6103. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6104. KEEPALIVE_STATE(NOT_BUSY);
  6105. #if ENABLED(PRINTER_EVENT_LEDS)
  6106. const float start_temp = thermalManager.degHotend(target_extruder);
  6107. uint8_t old_blue = 0;
  6108. #endif
  6109. do {
  6110. // Target temperature might be changed during the loop
  6111. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  6112. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  6113. target_temp = thermalManager.degTargetHotend(target_extruder);
  6114. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6115. if (no_wait_for_cooling && wants_to_cool) break;
  6116. }
  6117. now = millis();
  6118. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  6119. next_temp_ms = now + 1000UL;
  6120. print_heaterstates();
  6121. #if TEMP_RESIDENCY_TIME > 0
  6122. SERIAL_PROTOCOLPGM(" W:");
  6123. if (residency_start_ms)
  6124. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6125. else
  6126. SERIAL_PROTOCOLCHAR('?');
  6127. #endif
  6128. SERIAL_EOL();
  6129. }
  6130. idle();
  6131. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6132. const float temp = thermalManager.degHotend(target_extruder);
  6133. #if ENABLED(PRINTER_EVENT_LEDS)
  6134. // Gradually change LED strip from violet to red as nozzle heats up
  6135. if (!wants_to_cool) {
  6136. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  6137. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  6138. }
  6139. #endif
  6140. #if TEMP_RESIDENCY_TIME > 0
  6141. const float temp_diff = FABS(target_temp - temp);
  6142. if (!residency_start_ms) {
  6143. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  6144. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  6145. }
  6146. else if (temp_diff > TEMP_HYSTERESIS) {
  6147. // Restart the timer whenever the temperature falls outside the hysteresis.
  6148. residency_start_ms = now;
  6149. }
  6150. #endif
  6151. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  6152. if (wants_to_cool) {
  6153. // break after MIN_COOLING_SLOPE_TIME seconds
  6154. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  6155. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6156. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  6157. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  6158. old_temp = temp;
  6159. }
  6160. }
  6161. } while (wait_for_heatup && TEMP_CONDITIONS);
  6162. if (wait_for_heatup) {
  6163. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  6164. #if ENABLED(PRINTER_EVENT_LEDS)
  6165. #if ENABLED(RGBW_LED)
  6166. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  6167. #else
  6168. set_led_color(255, 255, 255); // Set LEDs All On
  6169. #endif
  6170. #endif
  6171. }
  6172. KEEPALIVE_STATE(IN_HANDLER);
  6173. }
  6174. #if HAS_TEMP_BED
  6175. #ifndef MIN_COOLING_SLOPE_DEG_BED
  6176. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6177. #endif
  6178. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6179. #define MIN_COOLING_SLOPE_TIME_BED 60
  6180. #endif
  6181. /**
  6182. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6183. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6184. */
  6185. inline void gcode_M190() {
  6186. if (DEBUGGING(DRYRUN)) return;
  6187. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6188. const bool no_wait_for_cooling = parser.seenval('S');
  6189. if (no_wait_for_cooling || parser.seenval('R')) {
  6190. thermalManager.setTargetBed(parser.value_celsius());
  6191. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6192. if (parser.value_celsius() > BED_MINTEMP)
  6193. print_job_timer.start();
  6194. #endif
  6195. }
  6196. else return;
  6197. #if TEMP_BED_RESIDENCY_TIME > 0
  6198. millis_t residency_start_ms = 0;
  6199. // Loop until the temperature has stabilized
  6200. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6201. #else
  6202. // Loop until the temperature is very close target
  6203. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6204. #endif
  6205. float target_temp = -1.0, old_temp = 9999.0;
  6206. bool wants_to_cool = false;
  6207. wait_for_heatup = true;
  6208. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6209. KEEPALIVE_STATE(NOT_BUSY);
  6210. target_extruder = active_extruder; // for print_heaterstates
  6211. #if ENABLED(PRINTER_EVENT_LEDS)
  6212. const float start_temp = thermalManager.degBed();
  6213. uint8_t old_red = 255;
  6214. #endif
  6215. do {
  6216. // Target temperature might be changed during the loop
  6217. if (target_temp != thermalManager.degTargetBed()) {
  6218. wants_to_cool = thermalManager.isCoolingBed();
  6219. target_temp = thermalManager.degTargetBed();
  6220. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6221. if (no_wait_for_cooling && wants_to_cool) break;
  6222. }
  6223. now = millis();
  6224. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6225. next_temp_ms = now + 1000UL;
  6226. print_heaterstates();
  6227. #if TEMP_BED_RESIDENCY_TIME > 0
  6228. SERIAL_PROTOCOLPGM(" W:");
  6229. if (residency_start_ms)
  6230. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6231. else
  6232. SERIAL_PROTOCOLCHAR('?');
  6233. #endif
  6234. SERIAL_EOL();
  6235. }
  6236. idle();
  6237. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6238. const float temp = thermalManager.degBed();
  6239. #if ENABLED(PRINTER_EVENT_LEDS)
  6240. // Gradually change LED strip from blue to violet as bed heats up
  6241. if (!wants_to_cool) {
  6242. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6243. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6244. }
  6245. #endif
  6246. #if TEMP_BED_RESIDENCY_TIME > 0
  6247. const float temp_diff = FABS(target_temp - temp);
  6248. if (!residency_start_ms) {
  6249. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6250. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6251. }
  6252. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6253. // Restart the timer whenever the temperature falls outside the hysteresis.
  6254. residency_start_ms = now;
  6255. }
  6256. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6257. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6258. if (wants_to_cool) {
  6259. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6260. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6261. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6262. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6263. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6264. old_temp = temp;
  6265. }
  6266. }
  6267. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6268. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6269. KEEPALIVE_STATE(IN_HANDLER);
  6270. }
  6271. #endif // HAS_TEMP_BED
  6272. /**
  6273. * M110: Set Current Line Number
  6274. */
  6275. inline void gcode_M110() {
  6276. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  6277. }
  6278. /**
  6279. * M111: Set the debug level
  6280. */
  6281. inline void gcode_M111() {
  6282. marlin_debug_flags = parser.byteval('S', (uint8_t)DEBUG_NONE);
  6283. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6284. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6285. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6286. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6287. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6288. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6289. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6290. #endif
  6291. const static char* const debug_strings[] PROGMEM = {
  6292. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6293. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6294. , str_debug_32
  6295. #endif
  6296. };
  6297. SERIAL_ECHO_START();
  6298. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6299. if (marlin_debug_flags) {
  6300. uint8_t comma = 0;
  6301. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6302. if (TEST(marlin_debug_flags, i)) {
  6303. if (comma++) SERIAL_CHAR(',');
  6304. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6305. }
  6306. }
  6307. }
  6308. else {
  6309. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6310. }
  6311. SERIAL_EOL();
  6312. }
  6313. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6314. /**
  6315. * M113: Get or set Host Keepalive interval (0 to disable)
  6316. *
  6317. * S<seconds> Optional. Set the keepalive interval.
  6318. */
  6319. inline void gcode_M113() {
  6320. if (parser.seenval('S')) {
  6321. host_keepalive_interval = parser.value_byte();
  6322. NOMORE(host_keepalive_interval, 60);
  6323. }
  6324. else {
  6325. SERIAL_ECHO_START();
  6326. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6327. }
  6328. }
  6329. #endif
  6330. #if ENABLED(BARICUDA)
  6331. #if HAS_HEATER_1
  6332. /**
  6333. * M126: Heater 1 valve open
  6334. */
  6335. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  6336. /**
  6337. * M127: Heater 1 valve close
  6338. */
  6339. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6340. #endif
  6341. #if HAS_HEATER_2
  6342. /**
  6343. * M128: Heater 2 valve open
  6344. */
  6345. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  6346. /**
  6347. * M129: Heater 2 valve close
  6348. */
  6349. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6350. #endif
  6351. #endif // BARICUDA
  6352. /**
  6353. * M140: Set bed temperature
  6354. */
  6355. inline void gcode_M140() {
  6356. if (DEBUGGING(DRYRUN)) return;
  6357. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  6358. }
  6359. #if ENABLED(ULTIPANEL)
  6360. /**
  6361. * M145: Set the heatup state for a material in the LCD menu
  6362. *
  6363. * S<material> (0=PLA, 1=ABS)
  6364. * H<hotend temp>
  6365. * B<bed temp>
  6366. * F<fan speed>
  6367. */
  6368. inline void gcode_M145() {
  6369. const uint8_t material = (uint8_t)parser.intval('S');
  6370. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6371. SERIAL_ERROR_START();
  6372. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6373. }
  6374. else {
  6375. int v;
  6376. if (parser.seenval('H')) {
  6377. v = parser.value_int();
  6378. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6379. }
  6380. if (parser.seenval('F')) {
  6381. v = parser.value_int();
  6382. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6383. }
  6384. #if TEMP_SENSOR_BED != 0
  6385. if (parser.seenval('B')) {
  6386. v = parser.value_int();
  6387. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6388. }
  6389. #endif
  6390. }
  6391. }
  6392. #endif // ULTIPANEL
  6393. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6394. /**
  6395. * M149: Set temperature units
  6396. */
  6397. inline void gcode_M149() {
  6398. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6399. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6400. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6401. }
  6402. #endif
  6403. #if HAS_POWER_SWITCH
  6404. /**
  6405. * M80 : Turn on the Power Supply
  6406. * M80 S : Report the current state and exit
  6407. */
  6408. inline void gcode_M80() {
  6409. // S: Report the current power supply state and exit
  6410. if (parser.seen('S')) {
  6411. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6412. return;
  6413. }
  6414. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6415. /**
  6416. * If you have a switch on suicide pin, this is useful
  6417. * if you want to start another print with suicide feature after
  6418. * a print without suicide...
  6419. */
  6420. #if HAS_SUICIDE
  6421. OUT_WRITE(SUICIDE_PIN, HIGH);
  6422. #endif
  6423. #if ENABLED(HAVE_TMC2130)
  6424. delay(100);
  6425. tmc2130_init(); // Settings only stick when the driver has power
  6426. #endif
  6427. powersupply_on = true;
  6428. #if ENABLED(ULTIPANEL)
  6429. LCD_MESSAGEPGM(WELCOME_MSG);
  6430. #endif
  6431. }
  6432. #endif // HAS_POWER_SWITCH
  6433. /**
  6434. * M81: Turn off Power, including Power Supply, if there is one.
  6435. *
  6436. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6437. */
  6438. inline void gcode_M81() {
  6439. thermalManager.disable_all_heaters();
  6440. stepper.finish_and_disable();
  6441. #if FAN_COUNT > 0
  6442. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6443. #if ENABLED(PROBING_FANS_OFF)
  6444. fans_paused = false;
  6445. ZERO(paused_fanSpeeds);
  6446. #endif
  6447. #endif
  6448. safe_delay(1000); // Wait 1 second before switching off
  6449. #if HAS_SUICIDE
  6450. stepper.synchronize();
  6451. suicide();
  6452. #elif HAS_POWER_SWITCH
  6453. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6454. powersupply_on = false;
  6455. #endif
  6456. #if ENABLED(ULTIPANEL)
  6457. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6458. #endif
  6459. }
  6460. /**
  6461. * M82: Set E codes absolute (default)
  6462. */
  6463. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6464. /**
  6465. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6466. */
  6467. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6468. /**
  6469. * M18, M84: Disable stepper motors
  6470. */
  6471. inline void gcode_M18_M84() {
  6472. if (parser.seenval('S')) {
  6473. stepper_inactive_time = parser.value_millis_from_seconds();
  6474. }
  6475. else {
  6476. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6477. if (all_axis) {
  6478. stepper.finish_and_disable();
  6479. }
  6480. else {
  6481. stepper.synchronize();
  6482. if (parser.seen('X')) disable_X();
  6483. if (parser.seen('Y')) disable_Y();
  6484. if (parser.seen('Z')) disable_Z();
  6485. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only enable on boards that have separate ENABLE_PINS
  6486. if (parser.seen('E')) disable_e_steppers();
  6487. #endif
  6488. }
  6489. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  6490. ubl_lcd_map_control = defer_return_to_status = false;
  6491. #endif
  6492. }
  6493. }
  6494. /**
  6495. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6496. */
  6497. inline void gcode_M85() {
  6498. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6499. }
  6500. /**
  6501. * Multi-stepper support for M92, M201, M203
  6502. */
  6503. #if ENABLED(DISTINCT_E_FACTORS)
  6504. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6505. #define TARGET_EXTRUDER target_extruder
  6506. #else
  6507. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6508. #define TARGET_EXTRUDER 0
  6509. #endif
  6510. /**
  6511. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6512. * (Follows the same syntax as G92)
  6513. *
  6514. * With multiple extruders use T to specify which one.
  6515. */
  6516. inline void gcode_M92() {
  6517. GET_TARGET_EXTRUDER(92);
  6518. LOOP_XYZE(i) {
  6519. if (parser.seen(axis_codes[i])) {
  6520. if (i == E_AXIS) {
  6521. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6522. if (value < 20.0) {
  6523. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6524. planner.max_jerk[E_AXIS] *= factor;
  6525. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6526. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6527. }
  6528. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6529. }
  6530. else {
  6531. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6532. }
  6533. }
  6534. }
  6535. planner.refresh_positioning();
  6536. }
  6537. /**
  6538. * Output the current position to serial
  6539. */
  6540. void report_current_position() {
  6541. SERIAL_PROTOCOLPGM("X:");
  6542. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6543. SERIAL_PROTOCOLPGM(" Y:");
  6544. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6545. SERIAL_PROTOCOLPGM(" Z:");
  6546. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6547. SERIAL_PROTOCOLPGM(" E:");
  6548. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6549. stepper.report_positions();
  6550. #if IS_SCARA
  6551. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6552. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6553. SERIAL_EOL();
  6554. #endif
  6555. }
  6556. #ifdef M114_DETAIL
  6557. void report_xyze(const float pos[XYZE], const uint8_t n = 4, const uint8_t precision = 3) {
  6558. char str[12];
  6559. for (uint8_t i = 0; i < n; i++) {
  6560. SERIAL_CHAR(' ');
  6561. SERIAL_CHAR(axis_codes[i]);
  6562. SERIAL_CHAR(':');
  6563. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  6564. }
  6565. SERIAL_EOL();
  6566. }
  6567. inline void report_xyz(const float pos[XYZ]) { report_xyze(pos, 3); }
  6568. void report_current_position_detail() {
  6569. stepper.synchronize();
  6570. SERIAL_PROTOCOLPGM("\nLogical:");
  6571. report_xyze(current_position);
  6572. SERIAL_PROTOCOLPGM("Raw: ");
  6573. 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]) };
  6574. report_xyz(raw);
  6575. SERIAL_PROTOCOLPGM("Leveled:");
  6576. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  6577. planner.apply_leveling(leveled);
  6578. report_xyz(leveled);
  6579. SERIAL_PROTOCOLPGM("UnLevel:");
  6580. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  6581. planner.unapply_leveling(unleveled);
  6582. report_xyz(unleveled);
  6583. #if IS_KINEMATIC
  6584. #if IS_SCARA
  6585. SERIAL_PROTOCOLPGM("ScaraK: ");
  6586. #else
  6587. SERIAL_PROTOCOLPGM("DeltaK: ");
  6588. #endif
  6589. inverse_kinematics(leveled); // writes delta[]
  6590. report_xyz(delta);
  6591. #endif
  6592. SERIAL_PROTOCOLPGM("Stepper:");
  6593. const float step_count[XYZE] = { stepper.position(X_AXIS), stepper.position(Y_AXIS), stepper.position(Z_AXIS), stepper.position(E_AXIS) };
  6594. report_xyze(step_count, 4, 0);
  6595. #if IS_SCARA
  6596. const float deg[XYZ] = {
  6597. stepper.get_axis_position_degrees(A_AXIS),
  6598. stepper.get_axis_position_degrees(B_AXIS)
  6599. };
  6600. SERIAL_PROTOCOLPGM("Degrees:");
  6601. report_xyze(deg, 2);
  6602. #endif
  6603. SERIAL_PROTOCOLPGM("FromStp:");
  6604. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  6605. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], stepper.get_axis_position_mm(E_AXIS) };
  6606. report_xyze(from_steppers);
  6607. const float diff[XYZE] = {
  6608. from_steppers[X_AXIS] - leveled[X_AXIS],
  6609. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  6610. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  6611. from_steppers[E_AXIS] - current_position[E_AXIS]
  6612. };
  6613. SERIAL_PROTOCOLPGM("Differ: ");
  6614. report_xyze(diff);
  6615. }
  6616. #endif // M114_DETAIL
  6617. /**
  6618. * M114: Report current position to host
  6619. */
  6620. inline void gcode_M114() {
  6621. #ifdef M114_DETAIL
  6622. if (parser.seen('D')) {
  6623. report_current_position_detail();
  6624. return;
  6625. }
  6626. #endif
  6627. stepper.synchronize();
  6628. report_current_position();
  6629. }
  6630. /**
  6631. * M115: Capabilities string
  6632. */
  6633. inline void gcode_M115() {
  6634. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6635. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6636. // EEPROM (M500, M501)
  6637. #if ENABLED(EEPROM_SETTINGS)
  6638. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6639. #else
  6640. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6641. #endif
  6642. // AUTOREPORT_TEMP (M155)
  6643. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6644. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6645. #else
  6646. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6647. #endif
  6648. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6649. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6650. // AUTOLEVEL (G29)
  6651. #if HAS_ABL
  6652. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6653. #else
  6654. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6655. #endif
  6656. // Z_PROBE (G30)
  6657. #if HAS_BED_PROBE
  6658. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6659. #else
  6660. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6661. #endif
  6662. // MESH_REPORT (M420 V)
  6663. #if HAS_LEVELING
  6664. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6665. #else
  6666. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6667. #endif
  6668. // SOFTWARE_POWER (M80, M81)
  6669. #if HAS_POWER_SWITCH
  6670. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6671. #else
  6672. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6673. #endif
  6674. // CASE LIGHTS (M355)
  6675. #if HAS_CASE_LIGHT
  6676. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6677. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  6678. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:1");
  6679. }
  6680. else
  6681. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6682. #else
  6683. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6684. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6685. #endif
  6686. // EMERGENCY_PARSER (M108, M112, M410)
  6687. #if ENABLED(EMERGENCY_PARSER)
  6688. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6689. #else
  6690. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6691. #endif
  6692. #endif // EXTENDED_CAPABILITIES_REPORT
  6693. }
  6694. /**
  6695. * M117: Set LCD Status Message
  6696. */
  6697. inline void gcode_M117() { lcd_setstatus(parser.string_arg); }
  6698. /**
  6699. * M118: Display a message in the host console.
  6700. *
  6701. * A Append '// ' for an action command, as in OctoPrint
  6702. * E Have the host 'echo:' the text
  6703. */
  6704. inline void gcode_M118() {
  6705. if (parser.boolval('E')) SERIAL_ECHO_START();
  6706. if (parser.boolval('A')) SERIAL_ECHOPGM("// ");
  6707. SERIAL_ECHOLN(parser.string_arg);
  6708. }
  6709. /**
  6710. * M119: Output endstop states to serial output
  6711. */
  6712. inline void gcode_M119() { endstops.M119(); }
  6713. /**
  6714. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6715. */
  6716. inline void gcode_M120() { endstops.enable_globally(true); }
  6717. /**
  6718. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6719. */
  6720. inline void gcode_M121() { endstops.enable_globally(false); }
  6721. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6722. /**
  6723. * M125: Store current position and move to filament change position.
  6724. * Called on pause (by M25) to prevent material leaking onto the
  6725. * object. On resume (M24) the head will be moved back and the
  6726. * print will resume.
  6727. *
  6728. * If Marlin is compiled without SD Card support, M125 can be
  6729. * used directly to pause the print and move to park position,
  6730. * resuming with a button click or M108.
  6731. *
  6732. * L = override retract length
  6733. * X = override X
  6734. * Y = override Y
  6735. * Z = override Z raise
  6736. */
  6737. inline void gcode_M125() {
  6738. // Initial retract before move to filament change position
  6739. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6740. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6741. - (PAUSE_PARK_RETRACT_LENGTH)
  6742. #endif
  6743. ;
  6744. // Lift Z axis
  6745. const float z_lift = parser.linearval('Z')
  6746. #if PAUSE_PARK_Z_ADD > 0
  6747. + PAUSE_PARK_Z_ADD
  6748. #endif
  6749. ;
  6750. // Move XY axes to filament change position or given position
  6751. const float x_pos = parser.linearval('X')
  6752. #ifdef PAUSE_PARK_X_POS
  6753. + PAUSE_PARK_X_POS
  6754. #endif
  6755. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6756. + (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0)
  6757. #endif
  6758. ;
  6759. const float y_pos = parser.linearval('Y')
  6760. #ifdef PAUSE_PARK_Y_POS
  6761. + PAUSE_PARK_Y_POS
  6762. #endif
  6763. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6764. + (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0)
  6765. #endif
  6766. ;
  6767. const bool job_running = print_job_timer.isRunning();
  6768. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6769. #if DISABLED(SDSUPPORT)
  6770. // Wait for lcd click or M108
  6771. wait_for_filament_reload();
  6772. // Return to print position and continue
  6773. resume_print();
  6774. if (job_running) print_job_timer.start();
  6775. #endif
  6776. }
  6777. }
  6778. #endif // PARK_HEAD_ON_PAUSE
  6779. #if HAS_COLOR_LEDS
  6780. /**
  6781. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6782. *
  6783. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6784. *
  6785. * Examples:
  6786. *
  6787. * M150 R255 ; Turn LED red
  6788. * M150 R255 U127 ; Turn LED orange (PWM only)
  6789. * M150 ; Turn LED off
  6790. * M150 R U B ; Turn LED white
  6791. * M150 W ; Turn LED white using a white LED
  6792. *
  6793. */
  6794. inline void gcode_M150() {
  6795. set_led_color(
  6796. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6797. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6798. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6799. #if ENABLED(RGBW_LED)
  6800. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6801. #endif
  6802. );
  6803. }
  6804. #endif // HAS_COLOR_LEDS
  6805. /**
  6806. * M200: Set filament diameter and set E axis units to cubic units
  6807. *
  6808. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6809. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6810. */
  6811. inline void gcode_M200() {
  6812. if (get_target_extruder_from_command(200)) return;
  6813. if (parser.seen('D')) {
  6814. // setting any extruder filament size disables volumetric on the assumption that
  6815. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6816. // for all extruders
  6817. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6818. if (volumetric_enabled) {
  6819. filament_size[target_extruder] = parser.value_linear_units();
  6820. // make sure all extruders have some sane value for the filament size
  6821. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6822. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6823. }
  6824. }
  6825. calculate_volumetric_multipliers();
  6826. }
  6827. /**
  6828. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6829. *
  6830. * With multiple extruders use T to specify which one.
  6831. */
  6832. inline void gcode_M201() {
  6833. GET_TARGET_EXTRUDER(201);
  6834. LOOP_XYZE(i) {
  6835. if (parser.seen(axis_codes[i])) {
  6836. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6837. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6838. }
  6839. }
  6840. // 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)
  6841. planner.reset_acceleration_rates();
  6842. }
  6843. #if 0 // Not used for Sprinter/grbl gen6
  6844. inline void gcode_M202() {
  6845. LOOP_XYZE(i) {
  6846. 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];
  6847. }
  6848. }
  6849. #endif
  6850. /**
  6851. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6852. *
  6853. * With multiple extruders use T to specify which one.
  6854. */
  6855. inline void gcode_M203() {
  6856. GET_TARGET_EXTRUDER(203);
  6857. LOOP_XYZE(i)
  6858. if (parser.seen(axis_codes[i])) {
  6859. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6860. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6861. }
  6862. }
  6863. /**
  6864. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6865. *
  6866. * P = Printing moves
  6867. * R = Retract only (no X, Y, Z) moves
  6868. * T = Travel (non printing) moves
  6869. *
  6870. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6871. */
  6872. inline void gcode_M204() {
  6873. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6874. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6875. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6876. }
  6877. if (parser.seen('P')) {
  6878. planner.acceleration = parser.value_linear_units();
  6879. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6880. }
  6881. if (parser.seen('R')) {
  6882. planner.retract_acceleration = parser.value_linear_units();
  6883. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6884. }
  6885. if (parser.seen('T')) {
  6886. planner.travel_acceleration = parser.value_linear_units();
  6887. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6888. }
  6889. }
  6890. /**
  6891. * M205: Set Advanced Settings
  6892. *
  6893. * S = Min Feed Rate (units/s)
  6894. * T = Min Travel Feed Rate (units/s)
  6895. * B = Min Segment Time (µs)
  6896. * X = Max X Jerk (units/sec^2)
  6897. * Y = Max Y Jerk (units/sec^2)
  6898. * Z = Max Z Jerk (units/sec^2)
  6899. * E = Max E Jerk (units/sec^2)
  6900. */
  6901. inline void gcode_M205() {
  6902. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6903. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6904. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6905. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6906. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6907. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6908. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6909. }
  6910. #if HAS_M206_COMMAND
  6911. /**
  6912. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6913. *
  6914. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6915. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6916. * *** In the next 1.2 release, it will simply be disabled by default.
  6917. */
  6918. inline void gcode_M206() {
  6919. LOOP_XYZ(i)
  6920. if (parser.seen(axis_codes[i]))
  6921. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6922. #if ENABLED(MORGAN_SCARA)
  6923. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6924. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6925. #endif
  6926. SYNC_PLAN_POSITION_KINEMATIC();
  6927. report_current_position();
  6928. }
  6929. #endif // HAS_M206_COMMAND
  6930. #if ENABLED(DELTA)
  6931. /**
  6932. * M665: Set delta configurations
  6933. *
  6934. * H = delta height
  6935. * L = diagonal rod
  6936. * R = delta radius
  6937. * S = segments per second
  6938. * B = delta calibration radius
  6939. * X = Alpha (Tower 1) angle trim
  6940. * Y = Beta (Tower 2) angle trim
  6941. * Z = Rotate A and B by this angle
  6942. */
  6943. inline void gcode_M665() {
  6944. if (parser.seen('H')) {
  6945. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6946. update_software_endstops(Z_AXIS);
  6947. }
  6948. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6949. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6950. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6951. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6952. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6953. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6954. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6955. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6956. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6957. }
  6958. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6959. }
  6960. /**
  6961. * M666: Set delta endstop adjustment
  6962. */
  6963. inline void gcode_M666() {
  6964. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6965. if (DEBUGGING(LEVELING)) {
  6966. SERIAL_ECHOLNPGM(">>> gcode_M666");
  6967. }
  6968. #endif
  6969. LOOP_XYZ(i) {
  6970. if (parser.seen(axis_codes[i])) {
  6971. endstop_adj[i] = parser.value_linear_units();
  6972. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6973. if (DEBUGGING(LEVELING)) {
  6974. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  6975. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  6976. }
  6977. #endif
  6978. }
  6979. }
  6980. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6981. if (DEBUGGING(LEVELING)) {
  6982. SERIAL_ECHOLNPGM("<<< gcode_M666");
  6983. }
  6984. #endif
  6985. // normalize endstops so all are <=0; set the residue to delta height
  6986. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  6987. home_offset[Z_AXIS] -= z_temp;
  6988. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  6989. }
  6990. #elif IS_SCARA
  6991. /**
  6992. * M665: Set SCARA settings
  6993. *
  6994. * Parameters:
  6995. *
  6996. * S[segments-per-second] - Segments-per-second
  6997. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  6998. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  6999. *
  7000. * A, P, and X are all aliases for the shoulder angle
  7001. * B, T, and Y are all aliases for the elbow angle
  7002. */
  7003. inline void gcode_M665() {
  7004. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  7005. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  7006. const uint8_t sumAPX = hasA + hasP + hasX;
  7007. if (sumAPX == 1)
  7008. home_offset[A_AXIS] = parser.value_float();
  7009. else if (sumAPX > 1) {
  7010. SERIAL_ERROR_START();
  7011. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  7012. return;
  7013. }
  7014. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  7015. const uint8_t sumBTY = hasB + hasT + hasY;
  7016. if (sumBTY == 1)
  7017. home_offset[B_AXIS] = parser.value_float();
  7018. else if (sumBTY > 1) {
  7019. SERIAL_ERROR_START();
  7020. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  7021. return;
  7022. }
  7023. }
  7024. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  7025. /**
  7026. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  7027. */
  7028. inline void gcode_M666() {
  7029. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  7030. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  7031. }
  7032. #endif // !DELTA && Z_DUAL_ENDSTOPS
  7033. #if ENABLED(FWRETRACT)
  7034. /**
  7035. * M207: Set firmware retraction values
  7036. *
  7037. * S[+units] retract_length
  7038. * W[+units] retract_length_swap (multi-extruder)
  7039. * F[units/min] retract_feedrate_mm_s
  7040. * Z[units] retract_zlift
  7041. */
  7042. inline void gcode_M207() {
  7043. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  7044. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7045. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  7046. #if EXTRUDERS > 1
  7047. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  7048. #endif
  7049. }
  7050. /**
  7051. * M208: Set firmware un-retraction values
  7052. *
  7053. * S[+units] retract_recover_length (in addition to M207 S*)
  7054. * W[+units] retract_recover_length_swap (multi-extruder)
  7055. * F[units/min] retract_recover_feedrate_mm_s
  7056. */
  7057. inline void gcode_M208() {
  7058. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  7059. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7060. #if EXTRUDERS > 1
  7061. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  7062. #endif
  7063. }
  7064. /**
  7065. * M209: Enable automatic retract (M209 S1)
  7066. * For slicers that don't support G10/11, reversed extrude-only
  7067. * moves will be classified as retraction.
  7068. */
  7069. inline void gcode_M209() {
  7070. if (parser.seen('S')) {
  7071. autoretract_enabled = parser.value_bool();
  7072. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  7073. }
  7074. }
  7075. #endif // FWRETRACT
  7076. /**
  7077. * M211: Enable, Disable, and/or Report software endstops
  7078. *
  7079. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  7080. */
  7081. inline void gcode_M211() {
  7082. SERIAL_ECHO_START();
  7083. #if HAS_SOFTWARE_ENDSTOPS
  7084. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  7085. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7086. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  7087. #else
  7088. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7089. SERIAL_ECHOPGM(MSG_OFF);
  7090. #endif
  7091. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  7092. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  7093. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  7094. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  7095. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  7096. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  7097. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  7098. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  7099. }
  7100. #if HOTENDS > 1
  7101. /**
  7102. * M218 - set hotend offset (in linear units)
  7103. *
  7104. * T<tool>
  7105. * X<xoffset>
  7106. * Y<yoffset>
  7107. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  7108. */
  7109. inline void gcode_M218() {
  7110. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  7111. if (parser.seenval('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  7112. if (parser.seenval('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  7113. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7114. if (parser.seenval('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  7115. #endif
  7116. SERIAL_ECHO_START();
  7117. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7118. HOTEND_LOOP() {
  7119. SERIAL_CHAR(' ');
  7120. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  7121. SERIAL_CHAR(',');
  7122. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  7123. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7124. SERIAL_CHAR(',');
  7125. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  7126. #endif
  7127. }
  7128. SERIAL_EOL();
  7129. }
  7130. #endif // HOTENDS > 1
  7131. /**
  7132. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  7133. */
  7134. inline void gcode_M220() {
  7135. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  7136. }
  7137. /**
  7138. * M221: Set extrusion percentage (M221 T0 S95)
  7139. */
  7140. inline void gcode_M221() {
  7141. if (get_target_extruder_from_command(221)) return;
  7142. if (parser.seenval('S'))
  7143. flow_percentage[target_extruder] = parser.value_int();
  7144. }
  7145. /**
  7146. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  7147. */
  7148. inline void gcode_M226() {
  7149. if (parser.seen('P')) {
  7150. const int pin_number = parser.value_int(),
  7151. pin_state = parser.intval('S', -1); // required pin state - default is inverted
  7152. if (WITHIN(pin_state, -1, 1) && pin_number > -1 && !pin_is_protected(pin_number)) {
  7153. int target = LOW;
  7154. stepper.synchronize();
  7155. pinMode(pin_number, INPUT);
  7156. switch (pin_state) {
  7157. case 1:
  7158. target = HIGH;
  7159. break;
  7160. case 0:
  7161. target = LOW;
  7162. break;
  7163. case -1:
  7164. target = !digitalRead(pin_number);
  7165. break;
  7166. }
  7167. while (digitalRead(pin_number) != target) idle();
  7168. } // pin_state -1 0 1 && pin_number > -1
  7169. } // parser.seen('P')
  7170. }
  7171. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7172. /**
  7173. * M260: Send data to a I2C slave device
  7174. *
  7175. * This is a PoC, the formating and arguments for the GCODE will
  7176. * change to be more compatible, the current proposal is:
  7177. *
  7178. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  7179. *
  7180. * M260 B<byte-1 value in base 10>
  7181. * M260 B<byte-2 value in base 10>
  7182. * M260 B<byte-3 value in base 10>
  7183. *
  7184. * M260 S1 ; Send the buffered data and reset the buffer
  7185. * M260 R1 ; Reset the buffer without sending data
  7186. *
  7187. */
  7188. inline void gcode_M260() {
  7189. // Set the target address
  7190. if (parser.seen('A')) i2c.address(parser.value_byte());
  7191. // Add a new byte to the buffer
  7192. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  7193. // Flush the buffer to the bus
  7194. if (parser.seen('S')) i2c.send();
  7195. // Reset and rewind the buffer
  7196. else if (parser.seen('R')) i2c.reset();
  7197. }
  7198. /**
  7199. * M261: Request X bytes from I2C slave device
  7200. *
  7201. * Usage: M261 A<slave device address base 10> B<number of bytes>
  7202. */
  7203. inline void gcode_M261() {
  7204. if (parser.seen('A')) i2c.address(parser.value_byte());
  7205. uint8_t bytes = parser.byteval('B', 1);
  7206. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  7207. i2c.relay(bytes);
  7208. }
  7209. else {
  7210. SERIAL_ERROR_START();
  7211. SERIAL_ERRORLN("Bad i2c request");
  7212. }
  7213. }
  7214. #endif // EXPERIMENTAL_I2CBUS
  7215. #if HAS_SERVOS
  7216. /**
  7217. * M280: Get or set servo position. P<index> [S<angle>]
  7218. */
  7219. inline void gcode_M280() {
  7220. if (!parser.seen('P')) return;
  7221. const int servo_index = parser.value_int();
  7222. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  7223. if (parser.seen('S'))
  7224. MOVE_SERVO(servo_index, parser.value_int());
  7225. else {
  7226. SERIAL_ECHO_START();
  7227. SERIAL_ECHOPAIR(" Servo ", servo_index);
  7228. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  7229. }
  7230. }
  7231. else {
  7232. SERIAL_ERROR_START();
  7233. SERIAL_ECHOPAIR("Servo ", servo_index);
  7234. SERIAL_ECHOLNPGM(" out of range");
  7235. }
  7236. }
  7237. #endif // HAS_SERVOS
  7238. #if HAS_BUZZER
  7239. /**
  7240. * M300: Play beep sound S<frequency Hz> P<duration ms>
  7241. */
  7242. inline void gcode_M300() {
  7243. uint16_t const frequency = parser.ushortval('S', 260);
  7244. uint16_t duration = parser.ushortval('P', 1000);
  7245. // Limits the tone duration to 0-5 seconds.
  7246. NOMORE(duration, 5000);
  7247. BUZZ(duration, frequency);
  7248. }
  7249. #endif // HAS_BUZZER
  7250. #if ENABLED(PIDTEMP)
  7251. /**
  7252. * M301: Set PID parameters P I D (and optionally C, L)
  7253. *
  7254. * P[float] Kp term
  7255. * I[float] Ki term (unscaled)
  7256. * D[float] Kd term (unscaled)
  7257. *
  7258. * With PID_EXTRUSION_SCALING:
  7259. *
  7260. * C[float] Kc term
  7261. * L[float] LPQ length
  7262. */
  7263. inline void gcode_M301() {
  7264. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7265. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7266. const uint8_t e = parser.byteval('E'); // extruder being updated
  7267. if (e < HOTENDS) { // catch bad input value
  7268. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7269. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7270. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7271. #if ENABLED(PID_EXTRUSION_SCALING)
  7272. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7273. if (parser.seen('L')) lpq_len = parser.value_float();
  7274. NOMORE(lpq_len, LPQ_MAX_LEN);
  7275. #endif
  7276. thermalManager.updatePID();
  7277. SERIAL_ECHO_START();
  7278. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7279. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7280. #endif // PID_PARAMS_PER_HOTEND
  7281. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7282. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7283. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7284. #if ENABLED(PID_EXTRUSION_SCALING)
  7285. //Kc does not have scaling applied above, or in resetting defaults
  7286. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7287. #endif
  7288. SERIAL_EOL();
  7289. }
  7290. else {
  7291. SERIAL_ERROR_START();
  7292. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7293. }
  7294. }
  7295. #endif // PIDTEMP
  7296. #if ENABLED(PIDTEMPBED)
  7297. inline void gcode_M304() {
  7298. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7299. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7300. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7301. thermalManager.updatePID();
  7302. SERIAL_ECHO_START();
  7303. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7304. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7305. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7306. }
  7307. #endif // PIDTEMPBED
  7308. #if defined(CHDK) || HAS_PHOTOGRAPH
  7309. /**
  7310. * M240: Trigger a camera by emulating a Canon RC-1
  7311. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7312. */
  7313. inline void gcode_M240() {
  7314. #ifdef CHDK
  7315. OUT_WRITE(CHDK, HIGH);
  7316. chdkHigh = millis();
  7317. chdkActive = true;
  7318. #elif HAS_PHOTOGRAPH
  7319. const uint8_t NUM_PULSES = 16;
  7320. const float PULSE_LENGTH = 0.01524;
  7321. for (int i = 0; i < NUM_PULSES; i++) {
  7322. WRITE(PHOTOGRAPH_PIN, HIGH);
  7323. _delay_ms(PULSE_LENGTH);
  7324. WRITE(PHOTOGRAPH_PIN, LOW);
  7325. _delay_ms(PULSE_LENGTH);
  7326. }
  7327. delay(7.33);
  7328. for (int i = 0; i < NUM_PULSES; i++) {
  7329. WRITE(PHOTOGRAPH_PIN, HIGH);
  7330. _delay_ms(PULSE_LENGTH);
  7331. WRITE(PHOTOGRAPH_PIN, LOW);
  7332. _delay_ms(PULSE_LENGTH);
  7333. }
  7334. #endif // !CHDK && HAS_PHOTOGRAPH
  7335. }
  7336. #endif // CHDK || PHOTOGRAPH_PIN
  7337. #if HAS_LCD_CONTRAST
  7338. /**
  7339. * M250: Read and optionally set the LCD contrast
  7340. */
  7341. inline void gcode_M250() {
  7342. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7343. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7344. SERIAL_PROTOCOL(lcd_contrast);
  7345. SERIAL_EOL();
  7346. }
  7347. #endif // HAS_LCD_CONTRAST
  7348. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7349. /**
  7350. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7351. *
  7352. * S<temperature> sets the minimum extrude temperature
  7353. * P<bool> enables (1) or disables (0) cold extrusion
  7354. *
  7355. * Examples:
  7356. *
  7357. * M302 ; report current cold extrusion state
  7358. * M302 P0 ; enable cold extrusion checking
  7359. * M302 P1 ; disables cold extrusion checking
  7360. * M302 S0 ; always allow extrusion (disables checking)
  7361. * M302 S170 ; only allow extrusion above 170
  7362. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7363. */
  7364. inline void gcode_M302() {
  7365. const bool seen_S = parser.seen('S');
  7366. if (seen_S) {
  7367. thermalManager.extrude_min_temp = parser.value_celsius();
  7368. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7369. }
  7370. if (parser.seen('P'))
  7371. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7372. else if (!seen_S) {
  7373. // Report current state
  7374. SERIAL_ECHO_START();
  7375. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7376. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7377. SERIAL_ECHOLNPGM("C)");
  7378. }
  7379. }
  7380. #endif // PREVENT_COLD_EXTRUSION
  7381. /**
  7382. * M303: PID relay autotune
  7383. *
  7384. * S<temperature> sets the target temperature. (default 150C)
  7385. * E<extruder> (-1 for the bed) (default 0)
  7386. * C<cycles>
  7387. * U<bool> with a non-zero value will apply the result to current settings
  7388. */
  7389. inline void gcode_M303() {
  7390. #if HAS_PID_HEATING
  7391. const int e = parser.intval('E'), c = parser.intval('C', 5);
  7392. const bool u = parser.boolval('U');
  7393. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  7394. if (WITHIN(e, 0, HOTENDS - 1))
  7395. target_extruder = e;
  7396. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  7397. thermalManager.PID_autotune(temp, e, c, u);
  7398. KEEPALIVE_STATE(IN_HANDLER);
  7399. #else
  7400. SERIAL_ERROR_START();
  7401. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7402. #endif
  7403. }
  7404. #if ENABLED(MORGAN_SCARA)
  7405. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7406. if (IsRunning()) {
  7407. forward_kinematics_SCARA(delta_a, delta_b);
  7408. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7409. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7410. destination[Z_AXIS] = current_position[Z_AXIS];
  7411. prepare_move_to_destination();
  7412. return true;
  7413. }
  7414. return false;
  7415. }
  7416. /**
  7417. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7418. */
  7419. inline bool gcode_M360() {
  7420. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7421. return SCARA_move_to_cal(0, 120);
  7422. }
  7423. /**
  7424. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7425. */
  7426. inline bool gcode_M361() {
  7427. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7428. return SCARA_move_to_cal(90, 130);
  7429. }
  7430. /**
  7431. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7432. */
  7433. inline bool gcode_M362() {
  7434. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7435. return SCARA_move_to_cal(60, 180);
  7436. }
  7437. /**
  7438. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7439. */
  7440. inline bool gcode_M363() {
  7441. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7442. return SCARA_move_to_cal(50, 90);
  7443. }
  7444. /**
  7445. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7446. */
  7447. inline bool gcode_M364() {
  7448. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7449. return SCARA_move_to_cal(45, 135);
  7450. }
  7451. #endif // SCARA
  7452. #if ENABLED(EXT_SOLENOID)
  7453. void enable_solenoid(const uint8_t num) {
  7454. switch (num) {
  7455. case 0:
  7456. OUT_WRITE(SOL0_PIN, HIGH);
  7457. break;
  7458. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7459. case 1:
  7460. OUT_WRITE(SOL1_PIN, HIGH);
  7461. break;
  7462. #endif
  7463. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7464. case 2:
  7465. OUT_WRITE(SOL2_PIN, HIGH);
  7466. break;
  7467. #endif
  7468. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7469. case 3:
  7470. OUT_WRITE(SOL3_PIN, HIGH);
  7471. break;
  7472. #endif
  7473. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7474. case 4:
  7475. OUT_WRITE(SOL4_PIN, HIGH);
  7476. break;
  7477. #endif
  7478. default:
  7479. SERIAL_ECHO_START();
  7480. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7481. break;
  7482. }
  7483. }
  7484. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7485. void disable_all_solenoids() {
  7486. OUT_WRITE(SOL0_PIN, LOW);
  7487. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7488. OUT_WRITE(SOL1_PIN, LOW);
  7489. #endif
  7490. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7491. OUT_WRITE(SOL2_PIN, LOW);
  7492. #endif
  7493. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7494. OUT_WRITE(SOL3_PIN, LOW);
  7495. #endif
  7496. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7497. OUT_WRITE(SOL4_PIN, LOW);
  7498. #endif
  7499. }
  7500. /**
  7501. * M380: Enable solenoid on the active extruder
  7502. */
  7503. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7504. /**
  7505. * M381: Disable all solenoids
  7506. */
  7507. inline void gcode_M381() { disable_all_solenoids(); }
  7508. #endif // EXT_SOLENOID
  7509. /**
  7510. * M400: Finish all moves
  7511. */
  7512. inline void gcode_M400() { stepper.synchronize(); }
  7513. #if HAS_BED_PROBE
  7514. /**
  7515. * M401: Engage Z Servo endstop if available
  7516. */
  7517. inline void gcode_M401() { DEPLOY_PROBE(); }
  7518. /**
  7519. * M402: Retract Z Servo endstop if enabled
  7520. */
  7521. inline void gcode_M402() { STOW_PROBE(); }
  7522. #endif // HAS_BED_PROBE
  7523. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7524. /**
  7525. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7526. */
  7527. inline void gcode_M404() {
  7528. if (parser.seen('W')) {
  7529. filament_width_nominal = parser.value_linear_units();
  7530. }
  7531. else {
  7532. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7533. SERIAL_PROTOCOLLN(filament_width_nominal);
  7534. }
  7535. }
  7536. /**
  7537. * M405: Turn on filament sensor for control
  7538. */
  7539. inline void gcode_M405() {
  7540. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  7541. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  7542. if (parser.seen('D')) {
  7543. meas_delay_cm = parser.value_byte();
  7544. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7545. }
  7546. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7547. const uint8_t temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7548. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7549. measurement_delay[i] = temp_ratio;
  7550. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7551. }
  7552. filament_sensor = true;
  7553. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7554. //SERIAL_PROTOCOL(filament_width_meas);
  7555. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7556. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7557. }
  7558. /**
  7559. * M406: Turn off filament sensor for control
  7560. */
  7561. inline void gcode_M406() { filament_sensor = false; }
  7562. /**
  7563. * M407: Get measured filament diameter on serial output
  7564. */
  7565. inline void gcode_M407() {
  7566. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7567. SERIAL_PROTOCOLLN(filament_width_meas);
  7568. }
  7569. #endif // FILAMENT_WIDTH_SENSOR
  7570. void quickstop_stepper() {
  7571. stepper.quick_stop();
  7572. stepper.synchronize();
  7573. set_current_from_steppers_for_axis(ALL_AXES);
  7574. SYNC_PLAN_POSITION_KINEMATIC();
  7575. }
  7576. #if HAS_LEVELING
  7577. /**
  7578. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7579. *
  7580. * S[bool] Turns leveling on or off
  7581. * Z[height] Sets the Z fade height (0 or none to disable)
  7582. * V[bool] Verbose - Print the leveling grid
  7583. *
  7584. * With AUTO_BED_LEVELING_UBL only:
  7585. *
  7586. * L[index] Load UBL mesh from index (0 is default)
  7587. */
  7588. inline void gcode_M420() {
  7589. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7590. // L to load a mesh from the EEPROM
  7591. if (parser.seen('L')) {
  7592. #if ENABLED(EEPROM_SETTINGS)
  7593. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7594. const int16_t a = settings.calc_num_meshes();
  7595. if (!a) {
  7596. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7597. return;
  7598. }
  7599. if (!WITHIN(storage_slot, 0, a - 1)) {
  7600. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7601. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7602. return;
  7603. }
  7604. settings.load_mesh(storage_slot);
  7605. ubl.state.storage_slot = storage_slot;
  7606. #else
  7607. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7608. return;
  7609. #endif
  7610. }
  7611. // L to load a mesh from the EEPROM
  7612. if (parser.seen('L') || parser.seen('V')) {
  7613. ubl.display_map(0); // Currently only supports one map type
  7614. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7615. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7616. }
  7617. #endif // AUTO_BED_LEVELING_UBL
  7618. // V to print the matrix or mesh
  7619. if (parser.seen('V')) {
  7620. #if ABL_PLANAR
  7621. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7622. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7623. if (leveling_is_valid()) {
  7624. print_bilinear_leveling_grid();
  7625. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7626. bed_level_virt_print();
  7627. #endif
  7628. }
  7629. #elif ENABLED(MESH_BED_LEVELING)
  7630. if (leveling_is_valid()) {
  7631. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7632. mbl_mesh_report();
  7633. }
  7634. #endif
  7635. }
  7636. const bool to_enable = parser.boolval('S');
  7637. if (parser.seen('S'))
  7638. set_bed_leveling_enabled(to_enable);
  7639. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7640. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7641. #endif
  7642. const bool new_status = leveling_is_active();
  7643. if (to_enable && !new_status) {
  7644. SERIAL_ERROR_START();
  7645. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7646. }
  7647. SERIAL_ECHO_START();
  7648. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7649. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7650. SERIAL_ECHO_START();
  7651. SERIAL_ECHOPGM("Fade Height ");
  7652. if (planner.z_fade_height > 0.0)
  7653. SERIAL_ECHOLN(planner.z_fade_height);
  7654. else
  7655. SERIAL_ECHOLNPGM(MSG_OFF);
  7656. #endif
  7657. }
  7658. #endif
  7659. #if ENABLED(MESH_BED_LEVELING)
  7660. /**
  7661. * M421: Set a single Mesh Bed Leveling Z coordinate
  7662. *
  7663. * Usage:
  7664. * M421 X<linear> Y<linear> Z<linear>
  7665. * M421 X<linear> Y<linear> Q<offset>
  7666. * M421 I<xindex> J<yindex> Z<linear>
  7667. * M421 I<xindex> J<yindex> Q<offset>
  7668. */
  7669. inline void gcode_M421() {
  7670. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7671. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7672. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7673. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7674. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7675. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7676. SERIAL_ERROR_START();
  7677. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7678. }
  7679. else if (ix < 0 || iy < 0) {
  7680. SERIAL_ERROR_START();
  7681. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7682. }
  7683. else
  7684. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7685. }
  7686. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7687. /**
  7688. * M421: Set a single Mesh Bed Leveling Z coordinate
  7689. *
  7690. * Usage:
  7691. * M421 I<xindex> J<yindex> Z<linear>
  7692. * M421 I<xindex> J<yindex> Q<offset>
  7693. */
  7694. inline void gcode_M421() {
  7695. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7696. const bool hasI = ix >= 0,
  7697. hasJ = iy >= 0,
  7698. hasZ = parser.seen('Z'),
  7699. hasQ = !hasZ && parser.seen('Q');
  7700. if (!hasI || !hasJ || !(hasZ || hasQ)) {
  7701. SERIAL_ERROR_START();
  7702. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7703. }
  7704. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7705. SERIAL_ERROR_START();
  7706. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7707. }
  7708. else {
  7709. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7710. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7711. bed_level_virt_interpolate();
  7712. #endif
  7713. }
  7714. }
  7715. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7716. /**
  7717. * M421: Set a single Mesh Bed Leveling Z coordinate
  7718. *
  7719. * Usage:
  7720. * M421 I<xindex> J<yindex> Z<linear>
  7721. * M421 I<xindex> J<yindex> Q<offset>
  7722. * M421 C Z<linear>
  7723. * M421 C Q<offset>
  7724. */
  7725. inline void gcode_M421() {
  7726. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7727. const bool hasI = ix >= 0,
  7728. hasJ = iy >= 0,
  7729. hasC = parser.seen('C'),
  7730. hasZ = parser.seen('Z'),
  7731. hasQ = !hasZ && parser.seen('Q');
  7732. if (hasC) {
  7733. 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);
  7734. ix = location.x_index;
  7735. iy = location.y_index;
  7736. }
  7737. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7738. SERIAL_ERROR_START();
  7739. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7740. }
  7741. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7742. SERIAL_ERROR_START();
  7743. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7744. }
  7745. else
  7746. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7747. }
  7748. #endif // AUTO_BED_LEVELING_UBL
  7749. #if HAS_M206_COMMAND
  7750. /**
  7751. * M428: Set home_offset based on the distance between the
  7752. * current_position and the nearest "reference point."
  7753. * If an axis is past center its endstop position
  7754. * is the reference-point. Otherwise it uses 0. This allows
  7755. * the Z offset to be set near the bed when using a max endstop.
  7756. *
  7757. * M428 can't be used more than 2cm away from 0 or an endstop.
  7758. *
  7759. * Use M206 to set these values directly.
  7760. */
  7761. inline void gcode_M428() {
  7762. bool err = false;
  7763. LOOP_XYZ(i) {
  7764. if (axis_homed[i]) {
  7765. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7766. diff = base - RAW_POSITION(current_position[i], i);
  7767. if (WITHIN(diff, -20, 20)) {
  7768. set_home_offset((AxisEnum)i, diff);
  7769. }
  7770. else {
  7771. SERIAL_ERROR_START();
  7772. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7773. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7774. BUZZ(200, 40);
  7775. err = true;
  7776. break;
  7777. }
  7778. }
  7779. }
  7780. if (!err) {
  7781. SYNC_PLAN_POSITION_KINEMATIC();
  7782. report_current_position();
  7783. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7784. BUZZ(100, 659);
  7785. BUZZ(100, 698);
  7786. }
  7787. }
  7788. #endif // HAS_M206_COMMAND
  7789. /**
  7790. * M500: Store settings in EEPROM
  7791. */
  7792. inline void gcode_M500() {
  7793. (void)settings.save();
  7794. }
  7795. /**
  7796. * M501: Read settings from EEPROM
  7797. */
  7798. inline void gcode_M501() {
  7799. (void)settings.load();
  7800. }
  7801. /**
  7802. * M502: Revert to default settings
  7803. */
  7804. inline void gcode_M502() {
  7805. (void)settings.reset();
  7806. }
  7807. #if DISABLED(DISABLE_M503)
  7808. /**
  7809. * M503: print settings currently in memory
  7810. */
  7811. inline void gcode_M503() {
  7812. (void)settings.report(!parser.boolval('S', true));
  7813. }
  7814. #endif
  7815. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7816. /**
  7817. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7818. */
  7819. inline void gcode_M540() {
  7820. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7821. }
  7822. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7823. #if HAS_BED_PROBE
  7824. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7825. static float last_zoffset = NAN;
  7826. if (!isnan(last_zoffset)) {
  7827. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7828. const float diff = zprobe_zoffset - last_zoffset;
  7829. #endif
  7830. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7831. // Correct bilinear grid for new probe offset
  7832. if (diff) {
  7833. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7834. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7835. z_values[x][y] -= diff;
  7836. }
  7837. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7838. bed_level_virt_interpolate();
  7839. #endif
  7840. #endif
  7841. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7842. if (!no_babystep && leveling_is_active())
  7843. thermalManager.babystep_axis(Z_AXIS, -LROUND(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7844. #else
  7845. UNUSED(no_babystep);
  7846. #endif
  7847. #if ENABLED(DELTA) // correct the delta_height
  7848. home_offset[Z_AXIS] -= diff;
  7849. #endif
  7850. }
  7851. last_zoffset = zprobe_zoffset;
  7852. }
  7853. inline void gcode_M851() {
  7854. SERIAL_ECHO_START();
  7855. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7856. if (parser.seen('Z')) {
  7857. const float value = parser.value_linear_units();
  7858. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7859. zprobe_zoffset = value;
  7860. refresh_zprobe_zoffset();
  7861. SERIAL_ECHO(zprobe_zoffset);
  7862. }
  7863. else
  7864. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7865. }
  7866. else
  7867. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7868. SERIAL_EOL();
  7869. }
  7870. #endif // HAS_BED_PROBE
  7871. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7872. /**
  7873. * M600: Pause for filament change
  7874. *
  7875. * E[distance] - Retract the filament this far (negative value)
  7876. * Z[distance] - Move the Z axis by this distance
  7877. * X[position] - Move to this X position, with Y
  7878. * Y[position] - Move to this Y position, with X
  7879. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7880. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7881. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7882. *
  7883. * Default values are used for omitted arguments.
  7884. *
  7885. */
  7886. inline void gcode_M600() {
  7887. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  7888. // Don't allow filament change without homing first
  7889. if (axis_unhomed_error()) home_all_axes();
  7890. #endif
  7891. // Initial retract before move to filament change position
  7892. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7893. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7894. - (PAUSE_PARK_RETRACT_LENGTH)
  7895. #endif
  7896. ;
  7897. // Lift Z axis
  7898. const float z_lift = parser.linearval('Z', 0
  7899. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7900. + PAUSE_PARK_Z_ADD
  7901. #endif
  7902. );
  7903. // Move XY axes to filament exchange position
  7904. const float x_pos = parser.linearval('X', 0
  7905. #ifdef PAUSE_PARK_X_POS
  7906. + PAUSE_PARK_X_POS
  7907. #endif
  7908. );
  7909. const float y_pos = parser.linearval('Y', 0
  7910. #ifdef PAUSE_PARK_Y_POS
  7911. + PAUSE_PARK_Y_POS
  7912. #endif
  7913. );
  7914. // Unload filament
  7915. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7916. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7917. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7918. #endif
  7919. ;
  7920. // Load filament
  7921. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7922. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7923. + FILAMENT_CHANGE_LOAD_LENGTH
  7924. #endif
  7925. ;
  7926. const int beep_count = parser.intval('B',
  7927. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7928. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7929. #else
  7930. -1
  7931. #endif
  7932. );
  7933. const bool job_running = print_job_timer.isRunning();
  7934. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7935. wait_for_filament_reload(beep_count);
  7936. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7937. }
  7938. // Resume the print job timer if it was running
  7939. if (job_running) print_job_timer.start();
  7940. }
  7941. #endif // ADVANCED_PAUSE_FEATURE
  7942. #if ENABLED(MK2_MULTIPLEXER)
  7943. inline void select_multiplexed_stepper(const uint8_t e) {
  7944. stepper.synchronize();
  7945. disable_e_steppers();
  7946. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  7947. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  7948. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  7949. safe_delay(100);
  7950. }
  7951. /**
  7952. * M702: Unload all extruders
  7953. */
  7954. inline void gcode_M702() {
  7955. for (uint8_t s = 0; s < E_STEPPERS; s++) {
  7956. select_multiplexed_stepper(e);
  7957. // TODO: standard unload filament function
  7958. // MK2 firmware behavior:
  7959. // - Make sure temperature is high enough
  7960. // - Raise Z to at least 15 to make room
  7961. // - Extrude 1cm of filament in 1 second
  7962. // - Under 230C quickly purge ~12mm, over 230C purge ~10mm
  7963. // - Change E max feedrate to 80, eject the filament from the tube. Sync.
  7964. // - Restore E max feedrate to 50
  7965. }
  7966. // Go back to the last active extruder
  7967. select_multiplexed_stepper(active_extruder);
  7968. disable_e_steppers();
  7969. }
  7970. #endif // MK2_MULTIPLEXER
  7971. #if ENABLED(DUAL_X_CARRIAGE)
  7972. /**
  7973. * M605: Set dual x-carriage movement mode
  7974. *
  7975. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  7976. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  7977. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  7978. * units x-offset and an optional differential hotend temperature of
  7979. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  7980. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  7981. *
  7982. * Note: the X axis should be homed after changing dual x-carriage mode.
  7983. */
  7984. inline void gcode_M605() {
  7985. stepper.synchronize();
  7986. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  7987. switch (dual_x_carriage_mode) {
  7988. case DXC_FULL_CONTROL_MODE:
  7989. case DXC_AUTO_PARK_MODE:
  7990. break;
  7991. case DXC_DUPLICATION_MODE:
  7992. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  7993. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  7994. SERIAL_ECHO_START();
  7995. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7996. SERIAL_CHAR(' ');
  7997. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  7998. SERIAL_CHAR(',');
  7999. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  8000. SERIAL_CHAR(' ');
  8001. SERIAL_ECHO(duplicate_extruder_x_offset);
  8002. SERIAL_CHAR(',');
  8003. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  8004. break;
  8005. default:
  8006. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  8007. break;
  8008. }
  8009. active_extruder_parked = false;
  8010. extruder_duplication_enabled = false;
  8011. delayed_move_time = 0;
  8012. }
  8013. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  8014. inline void gcode_M605() {
  8015. stepper.synchronize();
  8016. extruder_duplication_enabled = parser.intval('S') == (int)DXC_DUPLICATION_MODE;
  8017. SERIAL_ECHO_START();
  8018. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  8019. }
  8020. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  8021. #if ENABLED(LIN_ADVANCE)
  8022. /**
  8023. * M900: Set and/or Get advance K factor and WH/D ratio
  8024. *
  8025. * K<factor> Set advance K factor
  8026. * R<ratio> Set ratio directly (overrides WH/D)
  8027. * W<width> H<height> D<diam> Set ratio from WH/D
  8028. */
  8029. inline void gcode_M900() {
  8030. stepper.synchronize();
  8031. const float newK = parser.floatval('K', -1);
  8032. if (newK >= 0) planner.extruder_advance_k = newK;
  8033. float newR = parser.floatval('R', -1);
  8034. if (newR < 0) {
  8035. const float newD = parser.floatval('D', -1),
  8036. newW = parser.floatval('W', -1),
  8037. newH = parser.floatval('H', -1);
  8038. if (newD >= 0 && newW >= 0 && newH >= 0)
  8039. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  8040. }
  8041. if (newR >= 0) planner.advance_ed_ratio = newR;
  8042. SERIAL_ECHO_START();
  8043. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  8044. SERIAL_ECHOPGM(" E/D=");
  8045. const float ratio = planner.advance_ed_ratio;
  8046. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  8047. SERIAL_EOL();
  8048. }
  8049. #endif // LIN_ADVANCE
  8050. #if ENABLED(HAVE_TMC2130)
  8051. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  8052. SERIAL_CHAR(name);
  8053. SERIAL_ECHOPGM(" axis driver current: ");
  8054. SERIAL_ECHOLN(st.getCurrent());
  8055. }
  8056. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  8057. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  8058. tmc2130_get_current(st, name);
  8059. }
  8060. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  8061. SERIAL_CHAR(name);
  8062. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  8063. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  8064. SERIAL_EOL();
  8065. }
  8066. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  8067. st.clear_otpw();
  8068. SERIAL_CHAR(name);
  8069. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  8070. }
  8071. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  8072. SERIAL_CHAR(name);
  8073. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  8074. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  8075. }
  8076. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  8077. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  8078. tmc2130_get_pwmthrs(st, name, spmm);
  8079. }
  8080. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  8081. SERIAL_CHAR(name);
  8082. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  8083. SERIAL_ECHOLN(st.sgt());
  8084. }
  8085. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  8086. st.sgt(sgt_val);
  8087. tmc2130_get_sgt(st, name);
  8088. }
  8089. /**
  8090. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  8091. * Report driver currents when no axis specified
  8092. *
  8093. * S1: Enable automatic current control
  8094. * S0: Disable
  8095. */
  8096. inline void gcode_M906() {
  8097. uint16_t values[XYZE];
  8098. LOOP_XYZE(i)
  8099. values[i] = parser.intval(axis_codes[i]);
  8100. #if ENABLED(X_IS_TMC2130)
  8101. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  8102. else tmc2130_get_current(stepperX, 'X');
  8103. #endif
  8104. #if ENABLED(Y_IS_TMC2130)
  8105. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  8106. else tmc2130_get_current(stepperY, 'Y');
  8107. #endif
  8108. #if ENABLED(Z_IS_TMC2130)
  8109. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  8110. else tmc2130_get_current(stepperZ, 'Z');
  8111. #endif
  8112. #if ENABLED(E0_IS_TMC2130)
  8113. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  8114. else tmc2130_get_current(stepperE0, 'E');
  8115. #endif
  8116. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8117. if (parser.seen('S')) auto_current_control = parser.value_bool();
  8118. #endif
  8119. }
  8120. /**
  8121. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  8122. * The flag is held by the library and persist until manually cleared by M912
  8123. */
  8124. inline void gcode_M911() {
  8125. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  8126. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  8127. #if ENABLED(X_IS_TMC2130)
  8128. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  8129. #endif
  8130. #if ENABLED(Y_IS_TMC2130)
  8131. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  8132. #endif
  8133. #if ENABLED(Z_IS_TMC2130)
  8134. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  8135. #endif
  8136. #if ENABLED(E0_IS_TMC2130)
  8137. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  8138. #endif
  8139. }
  8140. /**
  8141. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  8142. */
  8143. inline void gcode_M912() {
  8144. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  8145. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  8146. #if ENABLED(X_IS_TMC2130)
  8147. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  8148. #endif
  8149. #if ENABLED(Y_IS_TMC2130)
  8150. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  8151. #endif
  8152. #if ENABLED(Z_IS_TMC2130)
  8153. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  8154. #endif
  8155. #if ENABLED(E0_IS_TMC2130)
  8156. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  8157. #endif
  8158. }
  8159. /**
  8160. * M913: Set HYBRID_THRESHOLD speed.
  8161. */
  8162. #if ENABLED(HYBRID_THRESHOLD)
  8163. inline void gcode_M913() {
  8164. uint16_t values[XYZE];
  8165. LOOP_XYZE(i)
  8166. values[i] = parser.intval(axis_codes[i]);
  8167. #if ENABLED(X_IS_TMC2130)
  8168. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  8169. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  8170. #endif
  8171. #if ENABLED(Y_IS_TMC2130)
  8172. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  8173. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  8174. #endif
  8175. #if ENABLED(Z_IS_TMC2130)
  8176. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  8177. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  8178. #endif
  8179. #if ENABLED(E0_IS_TMC2130)
  8180. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  8181. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  8182. #endif
  8183. }
  8184. #endif // HYBRID_THRESHOLD
  8185. /**
  8186. * M914: Set SENSORLESS_HOMING sensitivity.
  8187. */
  8188. #if ENABLED(SENSORLESS_HOMING)
  8189. inline void gcode_M914() {
  8190. #if ENABLED(X_IS_TMC2130)
  8191. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  8192. else tmc2130_get_sgt(stepperX, 'X');
  8193. #endif
  8194. #if ENABLED(Y_IS_TMC2130)
  8195. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  8196. else tmc2130_get_sgt(stepperY, 'Y');
  8197. #endif
  8198. }
  8199. #endif // SENSORLESS_HOMING
  8200. #endif // HAVE_TMC2130
  8201. /**
  8202. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  8203. */
  8204. inline void gcode_M907() {
  8205. #if HAS_DIGIPOTSS
  8206. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  8207. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  8208. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  8209. #elif HAS_MOTOR_CURRENT_PWM
  8210. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  8211. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  8212. #endif
  8213. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  8214. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  8215. #endif
  8216. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  8217. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  8218. #endif
  8219. #endif
  8220. #if ENABLED(DIGIPOT_I2C)
  8221. // this one uses actual amps in floating point
  8222. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  8223. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  8224. 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());
  8225. #endif
  8226. #if ENABLED(DAC_STEPPER_CURRENT)
  8227. if (parser.seen('S')) {
  8228. const float dac_percent = parser.value_float();
  8229. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  8230. }
  8231. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  8232. #endif
  8233. }
  8234. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  8235. /**
  8236. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  8237. */
  8238. inline void gcode_M908() {
  8239. #if HAS_DIGIPOTSS
  8240. stepper.digitalPotWrite(
  8241. parser.intval('P'),
  8242. parser.intval('S')
  8243. );
  8244. #endif
  8245. #ifdef DAC_STEPPER_CURRENT
  8246. dac_current_raw(
  8247. parser.byteval('P', -1),
  8248. parser.ushortval('S', 0)
  8249. );
  8250. #endif
  8251. }
  8252. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  8253. inline void gcode_M909() { dac_print_values(); }
  8254. inline void gcode_M910() { dac_commit_eeprom(); }
  8255. #endif
  8256. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  8257. #if HAS_MICROSTEPS
  8258. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  8259. inline void gcode_M350() {
  8260. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  8261. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  8262. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  8263. stepper.microstep_readings();
  8264. }
  8265. /**
  8266. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  8267. * S# determines MS1 or MS2, X# sets the pin high/low.
  8268. */
  8269. inline void gcode_M351() {
  8270. if (parser.seenval('S')) switch (parser.value_byte()) {
  8271. case 1:
  8272. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  8273. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  8274. break;
  8275. case 2:
  8276. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  8277. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  8278. break;
  8279. }
  8280. stepper.microstep_readings();
  8281. }
  8282. #endif // HAS_MICROSTEPS
  8283. #if HAS_CASE_LIGHT
  8284. #ifndef INVERT_CASE_LIGHT
  8285. #define INVERT_CASE_LIGHT false
  8286. #endif
  8287. int case_light_brightness; // LCD routine wants INT
  8288. bool case_light_on;
  8289. void update_case_light() {
  8290. pinMode(CASE_LIGHT_PIN, OUTPUT); // digitalWrite doesn't set the port mode
  8291. uint8_t case_light_bright = (uint8_t)case_light_brightness;
  8292. if (case_light_on) {
  8293. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  8294. analogWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? 255 - case_light_brightness : case_light_brightness );
  8295. }
  8296. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? LOW : HIGH );
  8297. }
  8298. else digitalWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? HIGH : LOW);
  8299. }
  8300. #endif // HAS_CASE_LIGHT
  8301. /**
  8302. * M355: Turn case light on/off and set brightness
  8303. *
  8304. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  8305. *
  8306. * S<bool> Set case light on/off
  8307. *
  8308. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  8309. *
  8310. * M355 P200 S0 turns off the light & sets the brightness level
  8311. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  8312. */
  8313. inline void gcode_M355() {
  8314. #if HAS_CASE_LIGHT
  8315. uint8_t args = 0;
  8316. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  8317. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  8318. if (args) update_case_light();
  8319. // always report case light status
  8320. SERIAL_ECHO_START();
  8321. if (!case_light_on) {
  8322. SERIAL_ECHOLN("Case light: off");
  8323. }
  8324. else {
  8325. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLN("Case light: on");
  8326. else SERIAL_ECHOLNPAIR("Case light: ", case_light_brightness);
  8327. }
  8328. #else
  8329. SERIAL_ERROR_START();
  8330. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8331. #endif // HAS_CASE_LIGHT
  8332. }
  8333. #if ENABLED(MIXING_EXTRUDER)
  8334. /**
  8335. * M163: Set a single mix factor for a mixing extruder
  8336. * This is called "weight" by some systems.
  8337. *
  8338. * S[index] The channel index to set
  8339. * P[float] The mix value
  8340. *
  8341. */
  8342. inline void gcode_M163() {
  8343. const int mix_index = parser.intval('S');
  8344. if (mix_index < MIXING_STEPPERS) {
  8345. float mix_value = parser.floatval('P');
  8346. NOLESS(mix_value, 0.0);
  8347. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8348. }
  8349. }
  8350. #if MIXING_VIRTUAL_TOOLS > 1
  8351. /**
  8352. * M164: Store the current mix factors as a virtual tool.
  8353. *
  8354. * S[index] The virtual tool to store
  8355. *
  8356. */
  8357. inline void gcode_M164() {
  8358. const int tool_index = parser.intval('S');
  8359. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8360. normalize_mix();
  8361. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8362. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8363. }
  8364. }
  8365. #endif
  8366. #if ENABLED(DIRECT_MIXING_IN_G1)
  8367. /**
  8368. * M165: Set multiple mix factors for a mixing extruder.
  8369. * Factors that are left out will be set to 0.
  8370. * All factors together must add up to 1.0.
  8371. *
  8372. * A[factor] Mix factor for extruder stepper 1
  8373. * B[factor] Mix factor for extruder stepper 2
  8374. * C[factor] Mix factor for extruder stepper 3
  8375. * D[factor] Mix factor for extruder stepper 4
  8376. * H[factor] Mix factor for extruder stepper 5
  8377. * I[factor] Mix factor for extruder stepper 6
  8378. *
  8379. */
  8380. inline void gcode_M165() { gcode_get_mix(); }
  8381. #endif
  8382. #endif // MIXING_EXTRUDER
  8383. /**
  8384. * M999: Restart after being stopped
  8385. *
  8386. * Default behaviour is to flush the serial buffer and request
  8387. * a resend to the host starting on the last N line received.
  8388. *
  8389. * Sending "M999 S1" will resume printing without flushing the
  8390. * existing command buffer.
  8391. *
  8392. */
  8393. inline void gcode_M999() {
  8394. Running = true;
  8395. lcd_reset_alert_level();
  8396. if (parser.boolval('S')) return;
  8397. // gcode_LastN = Stopped_gcode_LastN;
  8398. FlushSerialRequestResend();
  8399. }
  8400. #if ENABLED(SWITCHING_EXTRUDER)
  8401. #if EXTRUDERS > 3
  8402. #define REQ_ANGLES 4
  8403. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  8404. #else
  8405. #define REQ_ANGLES 2
  8406. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  8407. #endif
  8408. inline void move_extruder_servo(const uint8_t e) {
  8409. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8410. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  8411. stepper.synchronize();
  8412. #if EXTRUDERS & 1
  8413. if (e < EXTRUDERS - 1)
  8414. #endif
  8415. {
  8416. MOVE_SERVO(_SERVO_NR, angles[e]);
  8417. safe_delay(500);
  8418. }
  8419. }
  8420. #endif // SWITCHING_EXTRUDER
  8421. #if ENABLED(SWITCHING_NOZZLE)
  8422. inline void move_nozzle_servo(const uint8_t e) {
  8423. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8424. stepper.synchronize();
  8425. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8426. safe_delay(500);
  8427. }
  8428. #endif
  8429. inline void invalid_extruder_error(const uint8_t e) {
  8430. SERIAL_ECHO_START();
  8431. SERIAL_CHAR('T');
  8432. SERIAL_ECHO_F(e, DEC);
  8433. SERIAL_CHAR(' ');
  8434. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8435. }
  8436. /**
  8437. * Perform a tool-change, which may result in moving the
  8438. * previous tool out of the way and the new tool into place.
  8439. */
  8440. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8441. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8442. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8443. return invalid_extruder_error(tmp_extruder);
  8444. // T0-Tnnn: Switch virtual tool by changing the mix
  8445. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8446. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8447. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8448. if (tmp_extruder >= EXTRUDERS)
  8449. return invalid_extruder_error(tmp_extruder);
  8450. #if HOTENDS > 1
  8451. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8452. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8453. if (tmp_extruder != active_extruder) {
  8454. if (!no_move && axis_unhomed_error()) {
  8455. SERIAL_ECHOLNPGM("No move on toolchange");
  8456. no_move = true;
  8457. }
  8458. // Save current position to destination, for use later
  8459. set_destination_to_current();
  8460. #if ENABLED(DUAL_X_CARRIAGE)
  8461. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8462. if (DEBUGGING(LEVELING)) {
  8463. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8464. switch (dual_x_carriage_mode) {
  8465. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8466. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8467. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8468. }
  8469. }
  8470. #endif
  8471. const float xhome = x_home_pos(active_extruder);
  8472. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8473. && IsRunning()
  8474. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8475. ) {
  8476. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8477. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8478. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8479. #endif
  8480. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8481. if (DEBUGGING(LEVELING)) {
  8482. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8483. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8484. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8485. }
  8486. #endif
  8487. // Park old head: 1) raise 2) move to park position 3) lower
  8488. for (uint8_t i = 0; i < 3; i++)
  8489. planner.buffer_line(
  8490. i == 0 ? current_position[X_AXIS] : xhome,
  8491. current_position[Y_AXIS],
  8492. i == 2 ? current_position[Z_AXIS] : raised_z,
  8493. current_position[E_AXIS],
  8494. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8495. active_extruder
  8496. );
  8497. stepper.synchronize();
  8498. }
  8499. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8500. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8501. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8502. // Activate the new extruder
  8503. active_extruder = tmp_extruder;
  8504. // This function resets the max/min values - the current position may be overwritten below.
  8505. set_axis_is_at_home(X_AXIS);
  8506. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8507. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8508. #endif
  8509. // Only when auto-parking are carriages safe to move
  8510. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8511. switch (dual_x_carriage_mode) {
  8512. case DXC_FULL_CONTROL_MODE:
  8513. // New current position is the position of the activated extruder
  8514. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8515. // Save the inactive extruder's position (from the old current_position)
  8516. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8517. break;
  8518. case DXC_AUTO_PARK_MODE:
  8519. // record raised toolhead position for use by unpark
  8520. COPY(raised_parked_position, current_position);
  8521. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8522. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8523. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8524. #endif
  8525. active_extruder_parked = true;
  8526. delayed_move_time = 0;
  8527. break;
  8528. case DXC_DUPLICATION_MODE:
  8529. // If the new extruder is the left one, set it "parked"
  8530. // This triggers the second extruder to move into the duplication position
  8531. active_extruder_parked = (active_extruder == 0);
  8532. if (active_extruder_parked)
  8533. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8534. else
  8535. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8536. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8537. extruder_duplication_enabled = false;
  8538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8539. if (DEBUGGING(LEVELING)) {
  8540. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8541. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8542. }
  8543. #endif
  8544. break;
  8545. }
  8546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8547. if (DEBUGGING(LEVELING)) {
  8548. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8549. DEBUG_POS("New extruder (parked)", current_position);
  8550. }
  8551. #endif
  8552. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8553. #else // !DUAL_X_CARRIAGE
  8554. #if ENABLED(SWITCHING_NOZZLE)
  8555. #define DONT_SWITCH (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR)
  8556. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8557. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8558. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8559. // Always raise by some amount (destination copied from current_position earlier)
  8560. current_position[Z_AXIS] += z_raise;
  8561. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8562. move_nozzle_servo(tmp_extruder);
  8563. #endif
  8564. /**
  8565. * Set current_position to the position of the new nozzle.
  8566. * Offsets are based on linear distance, so we need to get
  8567. * the resulting position in coordinate space.
  8568. *
  8569. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8570. * - With mesh leveling, update Z for the new position
  8571. * - Otherwise, just use the raw linear distance
  8572. *
  8573. * Software endstops are altered here too. Consider a case where:
  8574. * E0 at X=0 ... E1 at X=10
  8575. * When we switch to E1 now X=10, but E1 can't move left.
  8576. * To express this we apply the change in XY to the software endstops.
  8577. * E1 can move farther right than E0, so the right limit is extended.
  8578. *
  8579. * Note that we don't adjust the Z software endstops. Why not?
  8580. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8581. * because the bed is 1mm lower at the new position. As long as
  8582. * the first nozzle is out of the way, the carriage should be
  8583. * allowed to move 1mm lower. This technically "breaks" the
  8584. * Z software endstop. But this is technically correct (and
  8585. * there is no viable alternative).
  8586. */
  8587. #if ABL_PLANAR
  8588. // Offset extruder, make sure to apply the bed level rotation matrix
  8589. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8590. hotend_offset[Y_AXIS][tmp_extruder],
  8591. 0),
  8592. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8593. hotend_offset[Y_AXIS][active_extruder],
  8594. 0),
  8595. offset_vec = tmp_offset_vec - act_offset_vec;
  8596. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8597. if (DEBUGGING(LEVELING)) {
  8598. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8599. act_offset_vec.debug(PSTR("act_offset_vec"));
  8600. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8601. }
  8602. #endif
  8603. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8604. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8605. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8606. #endif
  8607. // Adjustments to the current position
  8608. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8609. current_position[Z_AXIS] += offset_vec.z;
  8610. #else // !ABL_PLANAR
  8611. const float xydiff[2] = {
  8612. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8613. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8614. };
  8615. #if ENABLED(MESH_BED_LEVELING)
  8616. if (leveling_is_active()) {
  8617. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8618. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8619. #endif
  8620. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8621. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8622. z1 = current_position[Z_AXIS], z2 = z1;
  8623. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8624. planner.apply_leveling(x2, y2, z2);
  8625. current_position[Z_AXIS] += z2 - z1;
  8626. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8627. if (DEBUGGING(LEVELING))
  8628. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8629. #endif
  8630. }
  8631. #endif // MESH_BED_LEVELING
  8632. #endif // !HAS_ABL
  8633. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8634. if (DEBUGGING(LEVELING)) {
  8635. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8636. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8637. SERIAL_ECHOLNPGM(" }");
  8638. }
  8639. #endif
  8640. // The newly-selected extruder XY is actually at...
  8641. current_position[X_AXIS] += xydiff[X_AXIS];
  8642. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8643. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8644. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8645. #if HAS_POSITION_SHIFT
  8646. position_shift[i] += xydiff[i];
  8647. #endif
  8648. update_software_endstops((AxisEnum)i);
  8649. }
  8650. #endif
  8651. // Set the new active extruder
  8652. active_extruder = tmp_extruder;
  8653. #endif // !DUAL_X_CARRIAGE
  8654. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8655. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8656. #endif
  8657. // Tell the planner the new "current position"
  8658. SYNC_PLAN_POSITION_KINEMATIC();
  8659. // Move to the "old position" (move the extruder into place)
  8660. if (!no_move && IsRunning()) {
  8661. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8662. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8663. #endif
  8664. prepare_move_to_destination();
  8665. }
  8666. #if ENABLED(SWITCHING_NOZZLE)
  8667. // Move back down, if needed. (Including when the new tool is higher.)
  8668. if (z_raise != z_diff) {
  8669. destination[Z_AXIS] += z_diff;
  8670. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8671. prepare_move_to_destination();
  8672. }
  8673. #endif
  8674. } // (tmp_extruder != active_extruder)
  8675. stepper.synchronize();
  8676. #if ENABLED(EXT_SOLENOID)
  8677. disable_all_solenoids();
  8678. enable_solenoid_on_active_extruder();
  8679. #endif // EXT_SOLENOID
  8680. feedrate_mm_s = old_feedrate_mm_s;
  8681. #else // HOTENDS <= 1
  8682. UNUSED(fr_mm_s);
  8683. UNUSED(no_move);
  8684. #if ENABLED(SWITCHING_EXTRUDER) && !DONT_SWITCH
  8685. stepper.synchronize();
  8686. move_extruder_servo(tmp_extruder);
  8687. #elif ENABLED(MK2_MULTIPLEXER)
  8688. if (tmp_extruder >= E_STEPPERS)
  8689. return invalid_extruder_error(tmp_extruder);
  8690. select_multiplexed_stepper(tmp_extruder);
  8691. #endif
  8692. #endif // HOTENDS <= 1
  8693. active_extruder = tmp_extruder;
  8694. SERIAL_ECHO_START();
  8695. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8696. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8697. }
  8698. /**
  8699. * T0-T3: Switch tool, usually switching extruders
  8700. *
  8701. * F[units/min] Set the movement feedrate
  8702. * S1 Don't move the tool in XY after change
  8703. */
  8704. inline void gcode_T(uint8_t tmp_extruder) {
  8705. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8706. if (DEBUGGING(LEVELING)) {
  8707. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8708. SERIAL_CHAR(')');
  8709. SERIAL_EOL();
  8710. DEBUG_POS("BEFORE", current_position);
  8711. }
  8712. #endif
  8713. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8714. tool_change(tmp_extruder);
  8715. #elif HOTENDS > 1
  8716. tool_change(
  8717. tmp_extruder,
  8718. MMM_TO_MMS(parser.linearval('F')),
  8719. (tmp_extruder == active_extruder) || parser.boolval('S')
  8720. );
  8721. #endif
  8722. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8723. if (DEBUGGING(LEVELING)) {
  8724. DEBUG_POS("AFTER", current_position);
  8725. SERIAL_ECHOLNPGM("<<< gcode_T");
  8726. }
  8727. #endif
  8728. }
  8729. /**
  8730. * Process a single command and dispatch it to its handler
  8731. * This is called from the main loop()
  8732. */
  8733. void process_next_command() {
  8734. char * const current_command = command_queue[cmd_queue_index_r];
  8735. if (DEBUGGING(ECHO)) {
  8736. SERIAL_ECHO_START();
  8737. SERIAL_ECHOLN(current_command);
  8738. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8739. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8740. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8741. #endif
  8742. }
  8743. KEEPALIVE_STATE(IN_HANDLER);
  8744. // Parse the next command in the queue
  8745. parser.parse(current_command);
  8746. // Handle a known G, M, or T
  8747. switch (parser.command_letter) {
  8748. case 'G': switch (parser.codenum) {
  8749. // G0, G1
  8750. case 0:
  8751. case 1:
  8752. #if IS_SCARA
  8753. gcode_G0_G1(parser.codenum == 0);
  8754. #else
  8755. gcode_G0_G1();
  8756. #endif
  8757. break;
  8758. // G2, G3
  8759. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8760. case 2: // G2 - CW ARC
  8761. case 3: // G3 - CCW ARC
  8762. gcode_G2_G3(parser.codenum == 2);
  8763. break;
  8764. #endif
  8765. // G4 Dwell
  8766. case 4:
  8767. gcode_G4();
  8768. break;
  8769. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8770. // G5
  8771. case 5: // G5 - Cubic B_spline
  8772. gcode_G5();
  8773. break;
  8774. #endif // BEZIER_CURVE_SUPPORT
  8775. #if ENABLED(FWRETRACT)
  8776. case 10: // G10: retract
  8777. case 11: // G11: retract_recover
  8778. gcode_G10_G11(parser.codenum == 10);
  8779. break;
  8780. #endif // FWRETRACT
  8781. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8782. case 12:
  8783. gcode_G12(); // G12: Nozzle Clean
  8784. break;
  8785. #endif // NOZZLE_CLEAN_FEATURE
  8786. #if ENABLED(CNC_WORKSPACE_PLANES)
  8787. case 17: // G17: Select Plane XY
  8788. gcode_G17();
  8789. break;
  8790. case 18: // G18: Select Plane ZX
  8791. gcode_G18();
  8792. break;
  8793. case 19: // G19: Select Plane YZ
  8794. gcode_G19();
  8795. break;
  8796. #endif // CNC_WORKSPACE_PLANES
  8797. #if ENABLED(INCH_MODE_SUPPORT)
  8798. case 20: //G20: Inch Mode
  8799. gcode_G20();
  8800. break;
  8801. case 21: //G21: MM Mode
  8802. gcode_G21();
  8803. break;
  8804. #endif // INCH_MODE_SUPPORT
  8805. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8806. case 26: // G26: Mesh Validation Pattern generation
  8807. gcode_G26();
  8808. break;
  8809. #endif // AUTO_BED_LEVELING_UBL
  8810. #if ENABLED(NOZZLE_PARK_FEATURE)
  8811. case 27: // G27: Nozzle Park
  8812. gcode_G27();
  8813. break;
  8814. #endif // NOZZLE_PARK_FEATURE
  8815. case 28: // G28: Home all axes, one at a time
  8816. gcode_G28(false);
  8817. break;
  8818. #if HAS_LEVELING
  8819. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8820. // or provides access to the UBL System if enabled.
  8821. gcode_G29();
  8822. break;
  8823. #endif // HAS_LEVELING
  8824. #if HAS_BED_PROBE
  8825. case 30: // G30 Single Z probe
  8826. gcode_G30();
  8827. break;
  8828. #if ENABLED(Z_PROBE_SLED)
  8829. case 31: // G31: dock the sled
  8830. gcode_G31();
  8831. break;
  8832. case 32: // G32: undock the sled
  8833. gcode_G32();
  8834. break;
  8835. #endif // Z_PROBE_SLED
  8836. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8837. case 33: // G33: Delta Auto-Calibration
  8838. gcode_G33();
  8839. break;
  8840. #endif // DELTA_AUTO_CALIBRATION
  8841. #endif // HAS_BED_PROBE
  8842. #if ENABLED(G38_PROBE_TARGET)
  8843. case 38: // G38.2 & G38.3
  8844. if (subcode == 2 || subcode == 3)
  8845. gcode_G38(subcode == 2);
  8846. break;
  8847. #endif
  8848. case 90: // G90
  8849. relative_mode = false;
  8850. break;
  8851. case 91: // G91
  8852. relative_mode = true;
  8853. break;
  8854. case 92: // G92
  8855. gcode_G92();
  8856. break;
  8857. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8858. case 42:
  8859. gcode_G42();
  8860. break;
  8861. #endif
  8862. #if ENABLED(DEBUG_GCODE_PARSER)
  8863. case 800:
  8864. parser.debug(); // GCode Parser Test for G
  8865. break;
  8866. #endif
  8867. }
  8868. break;
  8869. case 'M': switch (parser.codenum) {
  8870. #if HAS_RESUME_CONTINUE
  8871. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8872. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8873. gcode_M0_M1();
  8874. break;
  8875. #endif // ULTIPANEL
  8876. #if ENABLED(SPINDLE_LASER_ENABLE)
  8877. case 3:
  8878. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8879. break; // synchronizes with movement commands
  8880. case 4:
  8881. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8882. break; // synchronizes with movement commands
  8883. case 5:
  8884. gcode_M5(); // M5 - turn spindle/laser off
  8885. break; // synchronizes with movement commands
  8886. #endif
  8887. case 17: // M17: Enable all stepper motors
  8888. gcode_M17();
  8889. break;
  8890. #if ENABLED(SDSUPPORT)
  8891. case 20: // M20: list SD card
  8892. gcode_M20(); break;
  8893. case 21: // M21: init SD card
  8894. gcode_M21(); break;
  8895. case 22: // M22: release SD card
  8896. gcode_M22(); break;
  8897. case 23: // M23: Select file
  8898. gcode_M23(); break;
  8899. case 24: // M24: Start SD print
  8900. gcode_M24(); break;
  8901. case 25: // M25: Pause SD print
  8902. gcode_M25(); break;
  8903. case 26: // M26: Set SD index
  8904. gcode_M26(); break;
  8905. case 27: // M27: Get SD status
  8906. gcode_M27(); break;
  8907. case 28: // M28: Start SD write
  8908. gcode_M28(); break;
  8909. case 29: // M29: Stop SD write
  8910. gcode_M29(); break;
  8911. case 30: // M30 <filename> Delete File
  8912. gcode_M30(); break;
  8913. case 32: // M32: Select file and start SD print
  8914. gcode_M32(); break;
  8915. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8916. case 33: // M33: Get the long full path to a file or folder
  8917. gcode_M33(); break;
  8918. #endif
  8919. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8920. case 34: //M34 - Set SD card sorting options
  8921. gcode_M34(); break;
  8922. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8923. case 928: // M928: Start SD write
  8924. gcode_M928(); break;
  8925. #endif // SDSUPPORT
  8926. case 31: // M31: Report time since the start of SD print or last M109
  8927. gcode_M31(); break;
  8928. case 42: // M42: Change pin state
  8929. gcode_M42(); break;
  8930. #if ENABLED(PINS_DEBUGGING)
  8931. case 43: // M43: Read pin state
  8932. gcode_M43(); break;
  8933. #endif
  8934. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8935. case 48: // M48: Z probe repeatability test
  8936. gcode_M48();
  8937. break;
  8938. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8939. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8940. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8941. gcode_M49();
  8942. break;
  8943. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8944. case 75: // M75: Start print timer
  8945. gcode_M75(); break;
  8946. case 76: // M76: Pause print timer
  8947. gcode_M76(); break;
  8948. case 77: // M77: Stop print timer
  8949. gcode_M77(); break;
  8950. #if ENABLED(PRINTCOUNTER)
  8951. case 78: // M78: Show print statistics
  8952. gcode_M78(); break;
  8953. #endif
  8954. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8955. case 100: // M100: Free Memory Report
  8956. gcode_M100();
  8957. break;
  8958. #endif
  8959. case 104: // M104: Set hot end temperature
  8960. gcode_M104();
  8961. break;
  8962. case 110: // M110: Set Current Line Number
  8963. gcode_M110();
  8964. break;
  8965. case 111: // M111: Set debug level
  8966. gcode_M111();
  8967. break;
  8968. #if DISABLED(EMERGENCY_PARSER)
  8969. case 108: // M108: Cancel Waiting
  8970. gcode_M108();
  8971. break;
  8972. case 112: // M112: Emergency Stop
  8973. gcode_M112();
  8974. break;
  8975. case 410: // M410 quickstop - Abort all the planned moves.
  8976. gcode_M410();
  8977. break;
  8978. #endif
  8979. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  8980. case 113: // M113: Set Host Keepalive interval
  8981. gcode_M113();
  8982. break;
  8983. #endif
  8984. case 140: // M140: Set bed temperature
  8985. gcode_M140();
  8986. break;
  8987. case 105: // M105: Report current temperature
  8988. gcode_M105();
  8989. KEEPALIVE_STATE(NOT_BUSY);
  8990. return; // "ok" already printed
  8991. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8992. case 155: // M155: Set temperature auto-report interval
  8993. gcode_M155();
  8994. break;
  8995. #endif
  8996. case 109: // M109: Wait for hotend temperature to reach target
  8997. gcode_M109();
  8998. break;
  8999. #if HAS_TEMP_BED
  9000. case 190: // M190: Wait for bed temperature to reach target
  9001. gcode_M190();
  9002. break;
  9003. #endif // HAS_TEMP_BED
  9004. #if FAN_COUNT > 0
  9005. case 106: // M106: Fan On
  9006. gcode_M106();
  9007. break;
  9008. case 107: // M107: Fan Off
  9009. gcode_M107();
  9010. break;
  9011. #endif // FAN_COUNT > 0
  9012. #if ENABLED(PARK_HEAD_ON_PAUSE)
  9013. case 125: // M125: Store current position and move to filament change position
  9014. gcode_M125(); break;
  9015. #endif
  9016. #if ENABLED(BARICUDA)
  9017. // PWM for HEATER_1_PIN
  9018. #if HAS_HEATER_1
  9019. case 126: // M126: valve open
  9020. gcode_M126();
  9021. break;
  9022. case 127: // M127: valve closed
  9023. gcode_M127();
  9024. break;
  9025. #endif // HAS_HEATER_1
  9026. // PWM for HEATER_2_PIN
  9027. #if HAS_HEATER_2
  9028. case 128: // M128: valve open
  9029. gcode_M128();
  9030. break;
  9031. case 129: // M129: valve closed
  9032. gcode_M129();
  9033. break;
  9034. #endif // HAS_HEATER_2
  9035. #endif // BARICUDA
  9036. #if HAS_POWER_SWITCH
  9037. case 80: // M80: Turn on Power Supply
  9038. gcode_M80();
  9039. break;
  9040. #endif // HAS_POWER_SWITCH
  9041. case 81: // M81: Turn off Power, including Power Supply, if possible
  9042. gcode_M81();
  9043. break;
  9044. case 82: // M82: Set E axis normal mode (same as other axes)
  9045. gcode_M82();
  9046. break;
  9047. case 83: // M83: Set E axis relative mode
  9048. gcode_M83();
  9049. break;
  9050. case 18: // M18 => M84
  9051. case 84: // M84: Disable all steppers or set timeout
  9052. gcode_M18_M84();
  9053. break;
  9054. case 85: // M85: Set inactivity stepper shutdown timeout
  9055. gcode_M85();
  9056. break;
  9057. case 92: // M92: Set the steps-per-unit for one or more axes
  9058. gcode_M92();
  9059. break;
  9060. case 114: // M114: Report current position
  9061. gcode_M114();
  9062. break;
  9063. case 115: // M115: Report capabilities
  9064. gcode_M115();
  9065. break;
  9066. case 117: // M117: Set LCD message text, if possible
  9067. gcode_M117();
  9068. break;
  9069. case 118: // M118: Display a message in the host console
  9070. gcode_M118();
  9071. break;
  9072. case 119: // M119: Report endstop states
  9073. gcode_M119();
  9074. break;
  9075. case 120: // M120: Enable endstops
  9076. gcode_M120();
  9077. break;
  9078. case 121: // M121: Disable endstops
  9079. gcode_M121();
  9080. break;
  9081. #if ENABLED(ULTIPANEL)
  9082. case 145: // M145: Set material heatup parameters
  9083. gcode_M145();
  9084. break;
  9085. #endif
  9086. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  9087. case 149: // M149: Set temperature units
  9088. gcode_M149();
  9089. break;
  9090. #endif
  9091. #if HAS_COLOR_LEDS
  9092. case 150: // M150: Set Status LED Color
  9093. gcode_M150();
  9094. break;
  9095. #endif // HAS_COLOR_LEDS
  9096. #if ENABLED(MIXING_EXTRUDER)
  9097. case 163: // M163: Set a component weight for mixing extruder
  9098. gcode_M163();
  9099. break;
  9100. #if MIXING_VIRTUAL_TOOLS > 1
  9101. case 164: // M164: Save current mix as a virtual extruder
  9102. gcode_M164();
  9103. break;
  9104. #endif
  9105. #if ENABLED(DIRECT_MIXING_IN_G1)
  9106. case 165: // M165: Set multiple mix weights
  9107. gcode_M165();
  9108. break;
  9109. #endif
  9110. #endif
  9111. case 200: // M200: Set filament diameter, E to cubic units
  9112. gcode_M200();
  9113. break;
  9114. case 201: // M201: Set max acceleration for print moves (units/s^2)
  9115. gcode_M201();
  9116. break;
  9117. #if 0 // Not used for Sprinter/grbl gen6
  9118. case 202: // M202
  9119. gcode_M202();
  9120. break;
  9121. #endif
  9122. case 203: // M203: Set max feedrate (units/sec)
  9123. gcode_M203();
  9124. break;
  9125. case 204: // M204: Set acceleration
  9126. gcode_M204();
  9127. break;
  9128. case 205: //M205: Set advanced settings
  9129. gcode_M205();
  9130. break;
  9131. #if HAS_M206_COMMAND
  9132. case 206: // M206: Set home offsets
  9133. gcode_M206();
  9134. break;
  9135. #endif
  9136. #if ENABLED(DELTA)
  9137. case 665: // M665: Set delta configurations
  9138. gcode_M665();
  9139. break;
  9140. #endif
  9141. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  9142. case 666: // M666: Set delta or dual endstop adjustment
  9143. gcode_M666();
  9144. break;
  9145. #endif
  9146. #if ENABLED(FWRETRACT)
  9147. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  9148. gcode_M207();
  9149. break;
  9150. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  9151. gcode_M208();
  9152. break;
  9153. case 209: // M209: Turn Automatic Retract Detection on/off
  9154. gcode_M209();
  9155. break;
  9156. #endif // FWRETRACT
  9157. case 211: // M211: Enable, Disable, and/or Report software endstops
  9158. gcode_M211();
  9159. break;
  9160. #if HOTENDS > 1
  9161. case 218: // M218: Set a tool offset
  9162. gcode_M218();
  9163. break;
  9164. #endif
  9165. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  9166. gcode_M220();
  9167. break;
  9168. case 221: // M221: Set Flow Percentage
  9169. gcode_M221();
  9170. break;
  9171. case 226: // M226: Wait until a pin reaches a state
  9172. gcode_M226();
  9173. break;
  9174. #if HAS_SERVOS
  9175. case 280: // M280: Set servo position absolute
  9176. gcode_M280();
  9177. break;
  9178. #endif // HAS_SERVOS
  9179. #if HAS_BUZZER
  9180. case 300: // M300: Play beep tone
  9181. gcode_M300();
  9182. break;
  9183. #endif // HAS_BUZZER
  9184. #if ENABLED(PIDTEMP)
  9185. case 301: // M301: Set hotend PID parameters
  9186. gcode_M301();
  9187. break;
  9188. #endif // PIDTEMP
  9189. #if ENABLED(PIDTEMPBED)
  9190. case 304: // M304: Set bed PID parameters
  9191. gcode_M304();
  9192. break;
  9193. #endif // PIDTEMPBED
  9194. #if defined(CHDK) || HAS_PHOTOGRAPH
  9195. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  9196. gcode_M240();
  9197. break;
  9198. #endif // CHDK || PHOTOGRAPH_PIN
  9199. #if HAS_LCD_CONTRAST
  9200. case 250: // M250: Set LCD contrast
  9201. gcode_M250();
  9202. break;
  9203. #endif // HAS_LCD_CONTRAST
  9204. #if ENABLED(EXPERIMENTAL_I2CBUS)
  9205. case 260: // M260: Send data to an i2c slave
  9206. gcode_M260();
  9207. break;
  9208. case 261: // M261: Request data from an i2c slave
  9209. gcode_M261();
  9210. break;
  9211. #endif // EXPERIMENTAL_I2CBUS
  9212. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9213. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  9214. gcode_M302();
  9215. break;
  9216. #endif // PREVENT_COLD_EXTRUSION
  9217. case 303: // M303: PID autotune
  9218. gcode_M303();
  9219. break;
  9220. #if ENABLED(MORGAN_SCARA)
  9221. case 360: // M360: SCARA Theta pos1
  9222. if (gcode_M360()) return;
  9223. break;
  9224. case 361: // M361: SCARA Theta pos2
  9225. if (gcode_M361()) return;
  9226. break;
  9227. case 362: // M362: SCARA Psi pos1
  9228. if (gcode_M362()) return;
  9229. break;
  9230. case 363: // M363: SCARA Psi pos2
  9231. if (gcode_M363()) return;
  9232. break;
  9233. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  9234. if (gcode_M364()) return;
  9235. break;
  9236. #endif // SCARA
  9237. case 400: // M400: Finish all moves
  9238. gcode_M400();
  9239. break;
  9240. #if HAS_BED_PROBE
  9241. case 401: // M401: Deploy probe
  9242. gcode_M401();
  9243. break;
  9244. case 402: // M402: Stow probe
  9245. gcode_M402();
  9246. break;
  9247. #endif // HAS_BED_PROBE
  9248. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  9249. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  9250. gcode_M404();
  9251. break;
  9252. case 405: // M405: Turn on filament sensor for control
  9253. gcode_M405();
  9254. break;
  9255. case 406: // M406: Turn off filament sensor for control
  9256. gcode_M406();
  9257. break;
  9258. case 407: // M407: Display measured filament diameter
  9259. gcode_M407();
  9260. break;
  9261. #endif // FILAMENT_WIDTH_SENSOR
  9262. #if HAS_LEVELING
  9263. case 420: // M420: Enable/Disable Bed Leveling
  9264. gcode_M420();
  9265. break;
  9266. #endif
  9267. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9268. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  9269. gcode_M421();
  9270. break;
  9271. #endif
  9272. #if HAS_M206_COMMAND
  9273. case 428: // M428: Apply current_position to home_offset
  9274. gcode_M428();
  9275. break;
  9276. #endif
  9277. case 500: // M500: Store settings in EEPROM
  9278. gcode_M500();
  9279. break;
  9280. case 501: // M501: Read settings from EEPROM
  9281. gcode_M501();
  9282. break;
  9283. case 502: // M502: Revert to default settings
  9284. gcode_M502();
  9285. break;
  9286. #if DISABLED(DISABLE_M503)
  9287. case 503: // M503: print settings currently in memory
  9288. gcode_M503();
  9289. break;
  9290. #endif
  9291. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9292. case 540: // M540: Set abort on endstop hit for SD printing
  9293. gcode_M540();
  9294. break;
  9295. #endif
  9296. #if HAS_BED_PROBE
  9297. case 851: // M851: Set Z Probe Z Offset
  9298. gcode_M851();
  9299. break;
  9300. #endif // HAS_BED_PROBE
  9301. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9302. case 600: // M600: Pause for filament change
  9303. gcode_M600();
  9304. break;
  9305. #endif // ADVANCED_PAUSE_FEATURE
  9306. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9307. case 605: // M605: Set Dual X Carriage movement mode
  9308. gcode_M605();
  9309. break;
  9310. #endif // DUAL_X_CARRIAGE
  9311. #if ENABLED(MK2_MULTIPLEXER)
  9312. case 702: // M702: Unload all extruders
  9313. gcode_M702();
  9314. break;
  9315. #endif
  9316. #if ENABLED(LIN_ADVANCE)
  9317. case 900: // M900: Set advance K factor.
  9318. gcode_M900();
  9319. break;
  9320. #endif
  9321. #if ENABLED(HAVE_TMC2130)
  9322. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9323. gcode_M906();
  9324. break;
  9325. #endif
  9326. case 907: // M907: Set digital trimpot motor current using axis codes.
  9327. gcode_M907();
  9328. break;
  9329. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  9330. case 908: // M908: Control digital trimpot directly.
  9331. gcode_M908();
  9332. break;
  9333. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  9334. case 909: // M909: Print digipot/DAC current value
  9335. gcode_M909();
  9336. break;
  9337. case 910: // M910: Commit digipot/DAC value to external EEPROM
  9338. gcode_M910();
  9339. break;
  9340. #endif
  9341. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  9342. #if ENABLED(HAVE_TMC2130)
  9343. case 911: // M911: Report TMC2130 prewarn triggered flags
  9344. gcode_M911();
  9345. break;
  9346. case 912: // M911: Clear TMC2130 prewarn triggered flags
  9347. gcode_M912();
  9348. break;
  9349. #if ENABLED(HYBRID_THRESHOLD)
  9350. case 913: // M913: Set HYBRID_THRESHOLD speed.
  9351. gcode_M913();
  9352. break;
  9353. #endif
  9354. #if ENABLED(SENSORLESS_HOMING)
  9355. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  9356. gcode_M914();
  9357. break;
  9358. #endif
  9359. #endif
  9360. #if HAS_MICROSTEPS
  9361. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9362. gcode_M350();
  9363. break;
  9364. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9365. gcode_M351();
  9366. break;
  9367. #endif // HAS_MICROSTEPS
  9368. case 355: // M355 set case light brightness
  9369. gcode_M355();
  9370. break;
  9371. #if ENABLED(DEBUG_GCODE_PARSER)
  9372. case 800:
  9373. parser.debug(); // GCode Parser Test for M
  9374. break;
  9375. #endif
  9376. #if ENABLED(I2C_POSITION_ENCODERS)
  9377. case 860: // M860 Report encoder module position
  9378. gcode_M860();
  9379. break;
  9380. case 861: // M861 Report encoder module status
  9381. gcode_M861();
  9382. break;
  9383. case 862: // M862 Perform axis test
  9384. gcode_M862();
  9385. break;
  9386. case 863: // M863 Calibrate steps/mm
  9387. gcode_M863();
  9388. break;
  9389. case 864: // M864 Change module address
  9390. gcode_M864();
  9391. break;
  9392. case 865: // M865 Check module firmware version
  9393. gcode_M865();
  9394. break;
  9395. case 866: // M866 Report axis error count
  9396. gcode_M866();
  9397. break;
  9398. case 867: // M867 Toggle error correction
  9399. gcode_M867();
  9400. break;
  9401. case 868: // M868 Set error correction threshold
  9402. gcode_M868();
  9403. break;
  9404. case 869: // M869 Report axis error
  9405. gcode_M869();
  9406. break;
  9407. #endif // I2C_POSITION_ENCODERS
  9408. case 999: // M999: Restart after being Stopped
  9409. gcode_M999();
  9410. break;
  9411. }
  9412. break;
  9413. case 'T':
  9414. gcode_T(parser.codenum);
  9415. break;
  9416. default: parser.unknown_command_error();
  9417. }
  9418. KEEPALIVE_STATE(NOT_BUSY);
  9419. ok_to_send();
  9420. }
  9421. /**
  9422. * Send a "Resend: nnn" message to the host to
  9423. * indicate that a command needs to be re-sent.
  9424. */
  9425. void FlushSerialRequestResend() {
  9426. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9427. MYSERIAL.flush();
  9428. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9429. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9430. ok_to_send();
  9431. }
  9432. /**
  9433. * Send an "ok" message to the host, indicating
  9434. * that a command was successfully processed.
  9435. *
  9436. * If ADVANCED_OK is enabled also include:
  9437. * N<int> Line number of the command, if any
  9438. * P<int> Planner space remaining
  9439. * B<int> Block queue space remaining
  9440. */
  9441. void ok_to_send() {
  9442. refresh_cmd_timeout();
  9443. if (!send_ok[cmd_queue_index_r]) return;
  9444. SERIAL_PROTOCOLPGM(MSG_OK);
  9445. #if ENABLED(ADVANCED_OK)
  9446. char* p = command_queue[cmd_queue_index_r];
  9447. if (*p == 'N') {
  9448. SERIAL_PROTOCOL(' ');
  9449. SERIAL_ECHO(*p++);
  9450. while (NUMERIC_SIGNED(*p))
  9451. SERIAL_ECHO(*p++);
  9452. }
  9453. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9454. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9455. #endif
  9456. SERIAL_EOL();
  9457. }
  9458. #if HAS_SOFTWARE_ENDSTOPS
  9459. /**
  9460. * Constrain the given coordinates to the software endstops.
  9461. */
  9462. // NOTE: This makes no sense for delta beds other than Z-axis.
  9463. // For delta the X/Y would need to be clamped at
  9464. // DELTA_PRINTABLE_RADIUS from center of bed, but delta
  9465. // now enforces is_position_reachable for X/Y regardless
  9466. // of HAS_SOFTWARE_ENDSTOPS, so that enforcement would be
  9467. // redundant here. Probably should #ifdef out the X/Y
  9468. // axis clamps here for delta and just leave the Z clamp.
  9469. void clamp_to_software_endstops(float target[XYZ]) {
  9470. if (!soft_endstops_enabled) return;
  9471. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9472. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9473. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9474. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9475. #endif
  9476. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9477. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9478. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9479. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9480. #endif
  9481. }
  9482. #endif
  9483. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9484. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9485. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9486. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9487. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9488. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9489. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9490. #else
  9491. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9492. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9493. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9494. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9495. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9496. #endif
  9497. // Get the Z adjustment for non-linear bed leveling
  9498. float bilinear_z_offset(const float logical[XYZ]) {
  9499. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9500. last_x = -999.999, last_y = -999.999;
  9501. // Whole units for the grid line indices. Constrained within bounds.
  9502. static int8_t gridx, gridy, nextx, nexty,
  9503. last_gridx = -99, last_gridy = -99;
  9504. // XY relative to the probed area
  9505. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9506. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9507. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9508. // Keep using the last grid box
  9509. #define FAR_EDGE_OR_BOX 2
  9510. #else
  9511. // Just use the grid far edge
  9512. #define FAR_EDGE_OR_BOX 1
  9513. #endif
  9514. if (last_x != x) {
  9515. last_x = x;
  9516. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9517. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9518. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9519. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9520. // Beyond the grid maintain height at grid edges
  9521. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9522. #endif
  9523. gridx = gx;
  9524. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9525. }
  9526. if (last_y != y || last_gridx != gridx) {
  9527. if (last_y != y) {
  9528. last_y = y;
  9529. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9530. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9531. ratio_y -= gy;
  9532. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9533. // Beyond the grid maintain height at grid edges
  9534. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9535. #endif
  9536. gridy = gy;
  9537. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9538. }
  9539. if (last_gridx != gridx || last_gridy != gridy) {
  9540. last_gridx = gridx;
  9541. last_gridy = gridy;
  9542. // Z at the box corners
  9543. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9544. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9545. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9546. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9547. }
  9548. // Bilinear interpolate. Needed since y or gridx has changed.
  9549. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9550. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9551. D = R - L;
  9552. }
  9553. const float offset = L + ratio_x * D; // the offset almost always changes
  9554. /*
  9555. static float last_offset = 0;
  9556. if (FABS(last_offset - offset) > 0.2) {
  9557. SERIAL_ECHOPGM("Sudden Shift at ");
  9558. SERIAL_ECHOPAIR("x=", x);
  9559. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9560. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9561. SERIAL_ECHOPAIR(" y=", y);
  9562. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9563. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9564. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9565. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9566. SERIAL_ECHOPAIR(" z1=", z1);
  9567. SERIAL_ECHOPAIR(" z2=", z2);
  9568. SERIAL_ECHOPAIR(" z3=", z3);
  9569. SERIAL_ECHOLNPAIR(" z4=", z4);
  9570. SERIAL_ECHOPAIR(" L=", L);
  9571. SERIAL_ECHOPAIR(" R=", R);
  9572. SERIAL_ECHOLNPAIR(" offset=", offset);
  9573. }
  9574. last_offset = offset;
  9575. //*/
  9576. return offset;
  9577. }
  9578. #endif // AUTO_BED_LEVELING_BILINEAR
  9579. #if ENABLED(DELTA)
  9580. /**
  9581. * Recalculate factors used for delta kinematics whenever
  9582. * settings have been changed (e.g., by M665).
  9583. */
  9584. void recalc_delta_settings(float radius, float diagonal_rod) {
  9585. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9586. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9587. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9588. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9589. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9590. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9591. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9592. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9593. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9594. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9595. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9596. }
  9597. #if ENABLED(DELTA_FAST_SQRT)
  9598. /**
  9599. * Fast inverse sqrt from Quake III Arena
  9600. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9601. */
  9602. float Q_rsqrt(float number) {
  9603. long i;
  9604. float x2, y;
  9605. const float threehalfs = 1.5f;
  9606. x2 = number * 0.5f;
  9607. y = number;
  9608. i = * ( long * ) &y; // evil floating point bit level hacking
  9609. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9610. y = * ( float * ) &i;
  9611. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9612. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9613. return y;
  9614. }
  9615. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9616. #else
  9617. #define _SQRT(n) SQRT(n)
  9618. #endif
  9619. /**
  9620. * Delta Inverse Kinematics
  9621. *
  9622. * Calculate the tower positions for a given logical
  9623. * position, storing the result in the delta[] array.
  9624. *
  9625. * This is an expensive calculation, requiring 3 square
  9626. * roots per segmented linear move, and strains the limits
  9627. * of a Mega2560 with a Graphical Display.
  9628. *
  9629. * Suggested optimizations include:
  9630. *
  9631. * - Disable the home_offset (M206) and/or position_shift (G92)
  9632. * features to remove up to 12 float additions.
  9633. *
  9634. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9635. * (see above)
  9636. */
  9637. // Macro to obtain the Z position of an individual tower
  9638. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9639. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9640. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9641. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9642. ) \
  9643. )
  9644. #define DELTA_RAW_IK() do { \
  9645. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9646. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9647. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9648. }while(0)
  9649. #define DELTA_LOGICAL_IK() do { \
  9650. const float raw[XYZ] = { \
  9651. RAW_X_POSITION(logical[X_AXIS]), \
  9652. RAW_Y_POSITION(logical[Y_AXIS]), \
  9653. RAW_Z_POSITION(logical[Z_AXIS]) \
  9654. }; \
  9655. DELTA_RAW_IK(); \
  9656. }while(0)
  9657. #define DELTA_DEBUG() do { \
  9658. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9659. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9660. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9661. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9662. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9663. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9664. }while(0)
  9665. void inverse_kinematics(const float logical[XYZ]) {
  9666. DELTA_LOGICAL_IK();
  9667. // DELTA_DEBUG();
  9668. }
  9669. /**
  9670. * Calculate the highest Z position where the
  9671. * effector has the full range of XY motion.
  9672. */
  9673. float delta_safe_distance_from_top() {
  9674. float cartesian[XYZ] = {
  9675. LOGICAL_X_POSITION(0),
  9676. LOGICAL_Y_POSITION(0),
  9677. LOGICAL_Z_POSITION(0)
  9678. };
  9679. inverse_kinematics(cartesian);
  9680. float distance = delta[A_AXIS];
  9681. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9682. inverse_kinematics(cartesian);
  9683. return FABS(distance - delta[A_AXIS]);
  9684. }
  9685. /**
  9686. * Delta Forward Kinematics
  9687. *
  9688. * See the Wikipedia article "Trilateration"
  9689. * https://en.wikipedia.org/wiki/Trilateration
  9690. *
  9691. * Establish a new coordinate system in the plane of the
  9692. * three carriage points. This system has its origin at
  9693. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9694. * plane with a Z component of zero.
  9695. * We will define unit vectors in this coordinate system
  9696. * in our original coordinate system. Then when we calculate
  9697. * the Xnew, Ynew and Znew values, we can translate back into
  9698. * the original system by moving along those unit vectors
  9699. * by the corresponding values.
  9700. *
  9701. * Variable names matched to Marlin, c-version, and avoid the
  9702. * use of any vector library.
  9703. *
  9704. * by Andreas Hardtung 2016-06-07
  9705. * based on a Java function from "Delta Robot Kinematics V3"
  9706. * by Steve Graves
  9707. *
  9708. * The result is stored in the cartes[] array.
  9709. */
  9710. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9711. // Create a vector in old coordinates along x axis of new coordinate
  9712. 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 };
  9713. // Get the Magnitude of vector.
  9714. float d = SQRT( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9715. // Create unit vector by dividing by magnitude.
  9716. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9717. // Get the vector from the origin of the new system to the third point.
  9718. 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 };
  9719. // Use the dot product to find the component of this vector on the X axis.
  9720. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9721. // Create a vector along the x axis that represents the x component of p13.
  9722. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9723. // Subtract the X component from the original vector leaving only Y. We use the
  9724. // variable that will be the unit vector after we scale it.
  9725. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9726. // The magnitude of Y component
  9727. float j = SQRT( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9728. // Convert to a unit vector
  9729. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9730. // The cross product of the unit x and y is the unit z
  9731. // float[] ez = vectorCrossProd(ex, ey);
  9732. float ez[3] = {
  9733. ex[1] * ey[2] - ex[2] * ey[1],
  9734. ex[2] * ey[0] - ex[0] * ey[2],
  9735. ex[0] * ey[1] - ex[1] * ey[0]
  9736. };
  9737. // We now have the d, i and j values defined in Wikipedia.
  9738. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9739. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9740. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9741. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9742. // Start from the origin of the old coordinates and add vectors in the
  9743. // old coords that represent the Xnew, Ynew and Znew to find the point
  9744. // in the old system.
  9745. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9746. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9747. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9748. }
  9749. void forward_kinematics_DELTA(float point[ABC]) {
  9750. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9751. }
  9752. #endif // DELTA
  9753. /**
  9754. * Get the stepper positions in the cartes[] array.
  9755. * Forward kinematics are applied for DELTA and SCARA.
  9756. *
  9757. * The result is in the current coordinate space with
  9758. * leveling applied. The coordinates need to be run through
  9759. * unapply_leveling to obtain the "ideal" coordinates
  9760. * suitable for current_position, etc.
  9761. */
  9762. void get_cartesian_from_steppers() {
  9763. #if ENABLED(DELTA)
  9764. forward_kinematics_DELTA(
  9765. stepper.get_axis_position_mm(A_AXIS),
  9766. stepper.get_axis_position_mm(B_AXIS),
  9767. stepper.get_axis_position_mm(C_AXIS)
  9768. );
  9769. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9770. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9771. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9772. #elif IS_SCARA
  9773. forward_kinematics_SCARA(
  9774. stepper.get_axis_position_degrees(A_AXIS),
  9775. stepper.get_axis_position_degrees(B_AXIS)
  9776. );
  9777. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9778. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9779. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9780. #else
  9781. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9782. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9783. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9784. #endif
  9785. }
  9786. /**
  9787. * Set the current_position for an axis based on
  9788. * the stepper positions, removing any leveling that
  9789. * may have been applied.
  9790. */
  9791. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9792. get_cartesian_from_steppers();
  9793. #if PLANNER_LEVELING
  9794. planner.unapply_leveling(cartes);
  9795. #endif
  9796. if (axis == ALL_AXES)
  9797. COPY(current_position, cartes);
  9798. else
  9799. current_position[axis] = cartes[axis];
  9800. }
  9801. #if ENABLED(MESH_BED_LEVELING)
  9802. /**
  9803. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9804. * splitting the move where it crosses mesh borders.
  9805. */
  9806. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9807. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9808. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9809. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9810. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9811. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9812. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9813. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9814. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9815. if (cx1 == cx2 && cy1 == cy2) {
  9816. // Start and end on same mesh square
  9817. line_to_destination(fr_mm_s);
  9818. set_current_to_destination();
  9819. return;
  9820. }
  9821. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9822. float normalized_dist, end[XYZE];
  9823. // Split at the left/front border of the right/top square
  9824. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9825. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9826. COPY(end, destination);
  9827. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9828. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9829. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9830. CBI(x_splits, gcx);
  9831. }
  9832. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9833. COPY(end, destination);
  9834. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9835. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9836. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9837. CBI(y_splits, gcy);
  9838. }
  9839. else {
  9840. // Already split on a border
  9841. line_to_destination(fr_mm_s);
  9842. set_current_to_destination();
  9843. return;
  9844. }
  9845. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9846. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9847. // Do the split and look for more borders
  9848. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9849. // Restore destination from stack
  9850. COPY(destination, end);
  9851. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9852. }
  9853. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9854. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9855. /**
  9856. * Prepare a bilinear-leveled linear move on Cartesian,
  9857. * splitting the move where it crosses grid borders.
  9858. */
  9859. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9860. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9861. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9862. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9863. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9864. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9865. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9866. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9867. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9868. if (cx1 == cx2 && cy1 == cy2) {
  9869. // Start and end on same mesh square
  9870. line_to_destination(fr_mm_s);
  9871. set_current_to_destination();
  9872. return;
  9873. }
  9874. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9875. float normalized_dist, end[XYZE];
  9876. // Split at the left/front border of the right/top square
  9877. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9878. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9879. COPY(end, destination);
  9880. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9881. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9882. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9883. CBI(x_splits, gcx);
  9884. }
  9885. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9886. COPY(end, destination);
  9887. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9888. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9889. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9890. CBI(y_splits, gcy);
  9891. }
  9892. else {
  9893. // Already split on a border
  9894. line_to_destination(fr_mm_s);
  9895. set_current_to_destination();
  9896. return;
  9897. }
  9898. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9899. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9900. // Do the split and look for more borders
  9901. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9902. // Restore destination from stack
  9903. COPY(destination, end);
  9904. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9905. }
  9906. #endif // AUTO_BED_LEVELING_BILINEAR
  9907. #if IS_KINEMATIC && !UBL_DELTA
  9908. /**
  9909. * Prepare a linear move in a DELTA or SCARA setup.
  9910. *
  9911. * This calls planner.buffer_line several times, adding
  9912. * small incremental moves for DELTA or SCARA.
  9913. */
  9914. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9915. // Get the top feedrate of the move in the XY plane
  9916. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9917. // If the move is only in Z/E don't split up the move
  9918. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9919. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9920. return false;
  9921. }
  9922. // Fail if attempting move outside printable radius
  9923. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9924. // Get the cartesian distances moved in XYZE
  9925. const float difference[XYZE] = {
  9926. ltarget[X_AXIS] - current_position[X_AXIS],
  9927. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9928. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9929. ltarget[E_AXIS] - current_position[E_AXIS]
  9930. };
  9931. // Get the linear distance in XYZ
  9932. float cartesian_mm = SQRT(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9933. // If the move is very short, check the E move distance
  9934. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = FABS(difference[E_AXIS]);
  9935. // No E move either? Game over.
  9936. if (UNEAR_ZERO(cartesian_mm)) return true;
  9937. // Minimum number of seconds to move the given distance
  9938. const float seconds = cartesian_mm / _feedrate_mm_s;
  9939. // The number of segments-per-second times the duration
  9940. // gives the number of segments
  9941. uint16_t segments = delta_segments_per_second * seconds;
  9942. // For SCARA minimum segment size is 0.25mm
  9943. #if IS_SCARA
  9944. NOMORE(segments, cartesian_mm * 4);
  9945. #endif
  9946. // At least one segment is required
  9947. NOLESS(segments, 1);
  9948. // The approximate length of each segment
  9949. const float inv_segments = 1.0 / float(segments),
  9950. segment_distance[XYZE] = {
  9951. difference[X_AXIS] * inv_segments,
  9952. difference[Y_AXIS] * inv_segments,
  9953. difference[Z_AXIS] * inv_segments,
  9954. difference[E_AXIS] * inv_segments
  9955. };
  9956. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9957. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9958. // SERIAL_ECHOLNPAIR(" segments=", segments);
  9959. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9960. // SCARA needs to scale the feed rate from mm/s to degrees/s
  9961. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  9962. feed_factor = inv_segment_length * _feedrate_mm_s;
  9963. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  9964. oldB = stepper.get_axis_position_degrees(B_AXIS);
  9965. #endif
  9966. // Get the logical current position as starting point
  9967. float logical[XYZE];
  9968. COPY(logical, current_position);
  9969. // Drop one segment so the last move is to the exact target.
  9970. // If there's only 1 segment, loops will be skipped entirely.
  9971. --segments;
  9972. // Calculate and execute the segments
  9973. for (uint16_t s = segments + 1; --s;) {
  9974. LOOP_XYZE(i) logical[i] += segment_distance[i];
  9975. #if ENABLED(DELTA)
  9976. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  9977. #else
  9978. inverse_kinematics(logical);
  9979. #endif
  9980. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  9981. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9982. // For SCARA scale the feed rate from mm/s to degrees/s
  9983. // Use ratio between the length of the move and the larger angle change
  9984. const float adiff = abs(delta[A_AXIS] - oldA),
  9985. bdiff = abs(delta[B_AXIS] - oldB);
  9986. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  9987. oldA = delta[A_AXIS];
  9988. oldB = delta[B_AXIS];
  9989. #else
  9990. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  9991. #endif
  9992. }
  9993. // Since segment_distance is only approximate,
  9994. // the final move must be to the exact destination.
  9995. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  9996. // For SCARA scale the feed rate from mm/s to degrees/s
  9997. // With segments > 1 length is 1 segment, otherwise total length
  9998. inverse_kinematics(ltarget);
  9999. ADJUST_DELTA(ltarget);
  10000. const float adiff = abs(delta[A_AXIS] - oldA),
  10001. bdiff = abs(delta[B_AXIS] - oldB);
  10002. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  10003. #else
  10004. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  10005. #endif
  10006. return false;
  10007. }
  10008. #else // !IS_KINEMATIC || UBL_DELTA
  10009. /**
  10010. * Prepare a linear move in a Cartesian setup.
  10011. * If Mesh Bed Leveling is enabled, perform a mesh move.
  10012. *
  10013. * Returns true if the caller didn't update current_position.
  10014. */
  10015. inline bool prepare_move_to_destination_cartesian() {
  10016. #if ENABLED(AUTO_BED_LEVELING_UBL)
  10017. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10018. if (ubl.state.active) { // direct use of ubl.state.active for speed
  10019. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  10020. return true;
  10021. }
  10022. else
  10023. line_to_destination(fr_scaled);
  10024. #else
  10025. // Do not use feedrate_percentage for E or Z only moves
  10026. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  10027. line_to_destination();
  10028. else {
  10029. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10030. #if ENABLED(MESH_BED_LEVELING)
  10031. if (mbl.active()) { // direct used of mbl.active() for speed
  10032. mesh_line_to_destination(fr_scaled);
  10033. return true;
  10034. }
  10035. else
  10036. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  10037. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  10038. bilinear_line_to_destination(fr_scaled);
  10039. return true;
  10040. }
  10041. else
  10042. #endif
  10043. line_to_destination(fr_scaled);
  10044. }
  10045. #endif
  10046. return false;
  10047. }
  10048. #endif // !IS_KINEMATIC || UBL_DELTA
  10049. #if ENABLED(DUAL_X_CARRIAGE)
  10050. /**
  10051. * Prepare a linear move in a dual X axis setup
  10052. */
  10053. inline bool prepare_move_to_destination_dualx() {
  10054. if (active_extruder_parked) {
  10055. switch (dual_x_carriage_mode) {
  10056. case DXC_FULL_CONTROL_MODE:
  10057. break;
  10058. case DXC_AUTO_PARK_MODE:
  10059. if (current_position[E_AXIS] == destination[E_AXIS]) {
  10060. // This is a travel move (with no extrusion)
  10061. // Skip it, but keep track of the current position
  10062. // (so it can be used as the start of the next non-travel move)
  10063. if (delayed_move_time != 0xFFFFFFFFUL) {
  10064. set_current_to_destination();
  10065. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  10066. delayed_move_time = millis();
  10067. return true;
  10068. }
  10069. }
  10070. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  10071. for (uint8_t i = 0; i < 3; i++)
  10072. planner.buffer_line(
  10073. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  10074. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  10075. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  10076. current_position[E_AXIS],
  10077. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  10078. active_extruder
  10079. );
  10080. delayed_move_time = 0;
  10081. active_extruder_parked = false;
  10082. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10083. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  10084. #endif
  10085. break;
  10086. case DXC_DUPLICATION_MODE:
  10087. if (active_extruder == 0) {
  10088. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10089. if (DEBUGGING(LEVELING)) {
  10090. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  10091. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  10092. }
  10093. #endif
  10094. // move duplicate extruder into correct duplication position.
  10095. planner.set_position_mm(
  10096. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  10097. current_position[Y_AXIS],
  10098. current_position[Z_AXIS],
  10099. current_position[E_AXIS]
  10100. );
  10101. planner.buffer_line(
  10102. current_position[X_AXIS] + duplicate_extruder_x_offset,
  10103. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  10104. planner.max_feedrate_mm_s[X_AXIS], 1
  10105. );
  10106. SYNC_PLAN_POSITION_KINEMATIC();
  10107. stepper.synchronize();
  10108. extruder_duplication_enabled = true;
  10109. active_extruder_parked = false;
  10110. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10111. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  10112. #endif
  10113. }
  10114. else {
  10115. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10116. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  10117. #endif
  10118. }
  10119. break;
  10120. }
  10121. }
  10122. return false;
  10123. }
  10124. #endif // DUAL_X_CARRIAGE
  10125. /**
  10126. * Prepare a single move and get ready for the next one
  10127. *
  10128. * This may result in several calls to planner.buffer_line to
  10129. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  10130. */
  10131. void prepare_move_to_destination() {
  10132. clamp_to_software_endstops(destination);
  10133. refresh_cmd_timeout();
  10134. #if ENABLED(PREVENT_COLD_EXTRUSION)
  10135. if (!DEBUGGING(DRYRUN)) {
  10136. if (destination[E_AXIS] != current_position[E_AXIS]) {
  10137. if (thermalManager.tooColdToExtrude(active_extruder)) {
  10138. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10139. SERIAL_ECHO_START();
  10140. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  10141. }
  10142. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  10143. if (destination[E_AXIS] - current_position[E_AXIS] > EXTRUDE_MAXLENGTH) {
  10144. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10145. SERIAL_ECHO_START();
  10146. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  10147. }
  10148. #endif
  10149. }
  10150. }
  10151. #endif
  10152. if (
  10153. #if UBL_DELTA // Also works for CARTESIAN (smaller segments follow mesh more closely)
  10154. ubl.prepare_segmented_line_to(destination, feedrate_mm_s)
  10155. #elif IS_KINEMATIC
  10156. prepare_kinematic_move_to(destination)
  10157. #elif ENABLED(DUAL_X_CARRIAGE)
  10158. prepare_move_to_destination_dualx()
  10159. #else
  10160. prepare_move_to_destination_cartesian()
  10161. #endif
  10162. ) return;
  10163. set_current_to_destination();
  10164. }
  10165. #if ENABLED(ARC_SUPPORT)
  10166. #if N_ARC_CORRECTION < 1
  10167. #undef N_ARC_CORRECTION
  10168. #define N_ARC_CORRECTION 1
  10169. #endif
  10170. /**
  10171. * Plan an arc in 2 dimensions
  10172. *
  10173. * The arc is approximated by generating many small linear segments.
  10174. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  10175. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  10176. * larger segments will tend to be more efficient. Your slicer should have
  10177. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  10178. */
  10179. void plan_arc(
  10180. float logical[XYZE], // Destination position
  10181. float *offset, // Center of rotation relative to current_position
  10182. uint8_t clockwise // Clockwise?
  10183. ) {
  10184. #if ENABLED(CNC_WORKSPACE_PLANES)
  10185. AxisEnum p_axis, q_axis, l_axis;
  10186. switch (workspace_plane) {
  10187. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  10188. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  10189. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  10190. }
  10191. #else
  10192. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  10193. #endif
  10194. // Radius vector from center to current location
  10195. float r_P = -offset[0], r_Q = -offset[1];
  10196. const float radius = HYPOT(r_P, r_Q),
  10197. center_P = current_position[p_axis] - r_P,
  10198. center_Q = current_position[q_axis] - r_Q,
  10199. rt_X = logical[p_axis] - center_P,
  10200. rt_Y = logical[q_axis] - center_Q,
  10201. linear_travel = logical[l_axis] - current_position[l_axis],
  10202. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  10203. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  10204. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  10205. if (angular_travel < 0) angular_travel += RADIANS(360);
  10206. if (clockwise) angular_travel -= RADIANS(360);
  10207. // Make a circle if the angular rotation is 0 and the target is current position
  10208. if (angular_travel == 0 && current_position[p_axis] == logical[p_axis] && current_position[q_axis] == logical[q_axis])
  10209. angular_travel = RADIANS(360);
  10210. const float mm_of_travel = HYPOT(angular_travel * radius, FABS(linear_travel));
  10211. if (mm_of_travel < 0.001) return;
  10212. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  10213. if (segments == 0) segments = 1;
  10214. /**
  10215. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  10216. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  10217. * r_T = [cos(phi) -sin(phi);
  10218. * sin(phi) cos(phi)] * r ;
  10219. *
  10220. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  10221. * defined from the circle center to the initial position. Each line segment is formed by successive
  10222. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  10223. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  10224. * all double numbers are single precision on the Arduino. (True double precision will not have
  10225. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  10226. * tool precision in some cases. Therefore, arc path correction is implemented.
  10227. *
  10228. * Small angle approximation may be used to reduce computation overhead further. This approximation
  10229. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  10230. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  10231. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  10232. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  10233. * issue for CNC machines with the single precision Arduino calculations.
  10234. *
  10235. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  10236. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  10237. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  10238. * This is important when there are successive arc motions.
  10239. */
  10240. // Vector rotation matrix values
  10241. float arc_target[XYZE];
  10242. const float theta_per_segment = angular_travel / segments,
  10243. linear_per_segment = linear_travel / segments,
  10244. extruder_per_segment = extruder_travel / segments,
  10245. sin_T = theta_per_segment,
  10246. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  10247. // Initialize the linear axis
  10248. arc_target[l_axis] = current_position[l_axis];
  10249. // Initialize the extruder axis
  10250. arc_target[E_AXIS] = current_position[E_AXIS];
  10251. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  10252. millis_t next_idle_ms = millis() + 200UL;
  10253. #if N_ARC_CORRECTION > 1
  10254. int8_t count = N_ARC_CORRECTION;
  10255. #endif
  10256. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  10257. thermalManager.manage_heater();
  10258. if (ELAPSED(millis(), next_idle_ms)) {
  10259. next_idle_ms = millis() + 200UL;
  10260. idle();
  10261. }
  10262. #if N_ARC_CORRECTION > 1
  10263. if (--count) {
  10264. // Apply vector rotation matrix to previous r_P / 1
  10265. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  10266. r_P = r_P * cos_T - r_Q * sin_T;
  10267. r_Q = r_new_Y;
  10268. }
  10269. else
  10270. #endif
  10271. {
  10272. #if N_ARC_CORRECTION > 1
  10273. count = N_ARC_CORRECTION;
  10274. #endif
  10275. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  10276. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  10277. // To reduce stuttering, the sin and cos could be computed at different times.
  10278. // For now, compute both at the same time.
  10279. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  10280. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  10281. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  10282. }
  10283. // Update arc_target location
  10284. arc_target[p_axis] = center_P + r_P;
  10285. arc_target[q_axis] = center_Q + r_Q;
  10286. arc_target[l_axis] += linear_per_segment;
  10287. arc_target[E_AXIS] += extruder_per_segment;
  10288. clamp_to_software_endstops(arc_target);
  10289. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  10290. }
  10291. // Ensure last segment arrives at target location.
  10292. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  10293. // As far as the parser is concerned, the position is now == target. In reality the
  10294. // motion control system might still be processing the action and the real tool position
  10295. // in any intermediate location.
  10296. set_current_to_destination();
  10297. }
  10298. #endif
  10299. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10300. void plan_cubic_move(const float offset[4]) {
  10301. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  10302. // As far as the parser is concerned, the position is now == destination. In reality the
  10303. // motion control system might still be processing the action and the real tool position
  10304. // in any intermediate location.
  10305. set_current_to_destination();
  10306. }
  10307. #endif // BEZIER_CURVE_SUPPORT
  10308. #if ENABLED(USE_CONTROLLER_FAN)
  10309. void controllerFan() {
  10310. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  10311. nextMotorCheck = 0; // Last time the state was checked
  10312. const millis_t ms = millis();
  10313. if (ELAPSED(ms, nextMotorCheck)) {
  10314. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  10315. 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
  10316. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  10317. #if E_STEPPERS > 1
  10318. || E1_ENABLE_READ == E_ENABLE_ON
  10319. #if HAS_X2_ENABLE
  10320. || X2_ENABLE_READ == X_ENABLE_ON
  10321. #endif
  10322. #if E_STEPPERS > 2
  10323. || E2_ENABLE_READ == E_ENABLE_ON
  10324. #if E_STEPPERS > 3
  10325. || E3_ENABLE_READ == E_ENABLE_ON
  10326. #if E_STEPPERS > 4
  10327. || E4_ENABLE_READ == E_ENABLE_ON
  10328. #endif // E_STEPPERS > 4
  10329. #endif // E_STEPPERS > 3
  10330. #endif // E_STEPPERS > 2
  10331. #endif // E_STEPPERS > 1
  10332. ) {
  10333. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  10334. }
  10335. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  10336. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  10337. // allows digital or PWM fan output to be used (see M42 handling)
  10338. WRITE(CONTROLLER_FAN_PIN, speed);
  10339. analogWrite(CONTROLLER_FAN_PIN, speed);
  10340. }
  10341. }
  10342. #endif // USE_CONTROLLER_FAN
  10343. #if ENABLED(MORGAN_SCARA)
  10344. /**
  10345. * Morgan SCARA Forward Kinematics. Results in cartes[].
  10346. * Maths and first version by QHARLEY.
  10347. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10348. */
  10349. void forward_kinematics_SCARA(const float &a, const float &b) {
  10350. float a_sin = sin(RADIANS(a)) * L1,
  10351. a_cos = cos(RADIANS(a)) * L1,
  10352. b_sin = sin(RADIANS(b)) * L2,
  10353. b_cos = cos(RADIANS(b)) * L2;
  10354. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  10355. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  10356. /*
  10357. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  10358. SERIAL_ECHOPAIR(" b=", b);
  10359. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  10360. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  10361. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  10362. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  10363. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  10364. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  10365. //*/
  10366. }
  10367. /**
  10368. * Morgan SCARA Inverse Kinematics. Results in delta[].
  10369. *
  10370. * See http://forums.reprap.org/read.php?185,283327
  10371. *
  10372. * Maths and first version by QHARLEY.
  10373. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10374. */
  10375. void inverse_kinematics(const float logical[XYZ]) {
  10376. static float C2, S2, SK1, SK2, THETA, PSI;
  10377. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  10378. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  10379. if (L1 == L2)
  10380. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  10381. else
  10382. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  10383. S2 = SQRT(1 - sq(C2));
  10384. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  10385. SK1 = L1 + L2 * C2;
  10386. // Rotated Arm2 gives the distance from Arm1 to Arm2
  10387. SK2 = L2 * S2;
  10388. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  10389. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  10390. // Angle of Arm2
  10391. PSI = ATAN2(S2, C2);
  10392. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  10393. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  10394. delta[C_AXIS] = logical[Z_AXIS];
  10395. /*
  10396. DEBUG_POS("SCARA IK", logical);
  10397. DEBUG_POS("SCARA IK", delta);
  10398. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  10399. SERIAL_ECHOPAIR(",", sy);
  10400. SERIAL_ECHOPAIR(" C2=", C2);
  10401. SERIAL_ECHOPAIR(" S2=", S2);
  10402. SERIAL_ECHOPAIR(" Theta=", THETA);
  10403. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  10404. //*/
  10405. }
  10406. #endif // MORGAN_SCARA
  10407. #if ENABLED(TEMP_STAT_LEDS)
  10408. static bool red_led = false;
  10409. static millis_t next_status_led_update_ms = 0;
  10410. void handle_status_leds(void) {
  10411. if (ELAPSED(millis(), next_status_led_update_ms)) {
  10412. next_status_led_update_ms += 500; // Update every 0.5s
  10413. float max_temp = 0.0;
  10414. #if HAS_TEMP_BED
  10415. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10416. #endif
  10417. HOTEND_LOOP()
  10418. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10419. const bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10420. if (new_led != red_led) {
  10421. red_led = new_led;
  10422. #if PIN_EXISTS(STAT_LED_RED)
  10423. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10424. #if PIN_EXISTS(STAT_LED_BLUE)
  10425. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10426. #endif
  10427. #else
  10428. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10429. #endif
  10430. }
  10431. }
  10432. }
  10433. #endif
  10434. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10435. void handle_filament_runout() {
  10436. if (!filament_ran_out) {
  10437. filament_ran_out = true;
  10438. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10439. stepper.synchronize();
  10440. }
  10441. }
  10442. #endif // FILAMENT_RUNOUT_SENSOR
  10443. #if ENABLED(FAST_PWM_FAN)
  10444. void setPwmFrequency(uint8_t pin, int val) {
  10445. val &= 0x07;
  10446. switch (digitalPinToTimer(pin)) {
  10447. #ifdef TCCR0A
  10448. #if !AVR_AT90USB1286_FAMILY
  10449. case TIMER0A:
  10450. #endif
  10451. case TIMER0B:
  10452. //_SET_CS(0, val);
  10453. break;
  10454. #endif
  10455. #ifdef TCCR1A
  10456. case TIMER1A:
  10457. case TIMER1B:
  10458. //_SET_CS(1, val);
  10459. break;
  10460. #endif
  10461. #ifdef TCCR2
  10462. case TIMER2:
  10463. case TIMER2:
  10464. _SET_CS(2, val);
  10465. break;
  10466. #endif
  10467. #ifdef TCCR2A
  10468. case TIMER2A:
  10469. case TIMER2B:
  10470. _SET_CS(2, val);
  10471. break;
  10472. #endif
  10473. #ifdef TCCR3A
  10474. case TIMER3A:
  10475. case TIMER3B:
  10476. case TIMER3C:
  10477. _SET_CS(3, val);
  10478. break;
  10479. #endif
  10480. #ifdef TCCR4A
  10481. case TIMER4A:
  10482. case TIMER4B:
  10483. case TIMER4C:
  10484. _SET_CS(4, val);
  10485. break;
  10486. #endif
  10487. #ifdef TCCR5A
  10488. case TIMER5A:
  10489. case TIMER5B:
  10490. case TIMER5C:
  10491. _SET_CS(5, val);
  10492. break;
  10493. #endif
  10494. }
  10495. }
  10496. #endif // FAST_PWM_FAN
  10497. float calculate_volumetric_multiplier(float diameter) {
  10498. if (!volumetric_enabled || diameter == 0) return 1.0;
  10499. return 1.0 / (M_PI * sq(diameter * 0.5));
  10500. }
  10501. void calculate_volumetric_multipliers() {
  10502. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10503. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10504. }
  10505. void enable_all_steppers() {
  10506. enable_X();
  10507. enable_Y();
  10508. enable_Z();
  10509. enable_E0();
  10510. enable_E1();
  10511. enable_E2();
  10512. enable_E3();
  10513. enable_E4();
  10514. }
  10515. void disable_e_steppers() {
  10516. disable_E0();
  10517. disable_E1();
  10518. disable_E2();
  10519. disable_E3();
  10520. disable_E4();
  10521. }
  10522. void disable_all_steppers() {
  10523. disable_X();
  10524. disable_Y();
  10525. disable_Z();
  10526. disable_e_steppers();
  10527. }
  10528. #if ENABLED(HAVE_TMC2130)
  10529. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10530. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10531. const bool is_otpw = st.checkOT();
  10532. // Report if a warning was triggered
  10533. static bool previous_otpw = false;
  10534. if (is_otpw && !previous_otpw) {
  10535. char timestamp[10];
  10536. duration_t elapsed = print_job_timer.duration();
  10537. const bool has_days = (elapsed.value > 60*60*24L);
  10538. (void)elapsed.toDigital(timestamp, has_days);
  10539. SERIAL_ECHO(timestamp);
  10540. SERIAL_ECHOPGM(": ");
  10541. SERIAL_ECHO(axisID);
  10542. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10543. }
  10544. previous_otpw = is_otpw;
  10545. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10546. // Return if user has not enabled current control start with M906 S1.
  10547. if (!auto_current_control) return;
  10548. /**
  10549. * Decrease current if is_otpw is true.
  10550. * Bail out if driver is disabled.
  10551. * Increase current if OTPW has not been triggered yet.
  10552. */
  10553. uint16_t current = st.getCurrent();
  10554. if (is_otpw) {
  10555. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10556. #if ENABLED(REPORT_CURRENT_CHANGE)
  10557. SERIAL_ECHO(axisID);
  10558. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10559. #endif
  10560. }
  10561. else if (!st.isEnabled())
  10562. return;
  10563. else if (!is_otpw && !st.getOTPW()) {
  10564. current += CURRENT_STEP;
  10565. if (current <= AUTO_ADJUST_MAX) {
  10566. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10567. #if ENABLED(REPORT_CURRENT_CHANGE)
  10568. SERIAL_ECHO(axisID);
  10569. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10570. #endif
  10571. }
  10572. }
  10573. SERIAL_EOL();
  10574. #endif
  10575. }
  10576. void checkOverTemp() {
  10577. static millis_t next_cOT = 0;
  10578. if (ELAPSED(millis(), next_cOT)) {
  10579. next_cOT = millis() + 5000;
  10580. #if ENABLED(X_IS_TMC2130)
  10581. automatic_current_control(stepperX, "X");
  10582. #endif
  10583. #if ENABLED(Y_IS_TMC2130)
  10584. automatic_current_control(stepperY, "Y");
  10585. #endif
  10586. #if ENABLED(Z_IS_TMC2130)
  10587. automatic_current_control(stepperZ, "Z");
  10588. #endif
  10589. #if ENABLED(X2_IS_TMC2130)
  10590. automatic_current_control(stepperX2, "X2");
  10591. #endif
  10592. #if ENABLED(Y2_IS_TMC2130)
  10593. automatic_current_control(stepperY2, "Y2");
  10594. #endif
  10595. #if ENABLED(Z2_IS_TMC2130)
  10596. automatic_current_control(stepperZ2, "Z2");
  10597. #endif
  10598. #if ENABLED(E0_IS_TMC2130)
  10599. automatic_current_control(stepperE0, "E0");
  10600. #endif
  10601. #if ENABLED(E1_IS_TMC2130)
  10602. automatic_current_control(stepperE1, "E1");
  10603. #endif
  10604. #if ENABLED(E2_IS_TMC2130)
  10605. automatic_current_control(stepperE2, "E2");
  10606. #endif
  10607. #if ENABLED(E3_IS_TMC2130)
  10608. automatic_current_control(stepperE3, "E3");
  10609. #endif
  10610. #if ENABLED(E4_IS_TMC2130)
  10611. automatic_current_control(stepperE4, "E4");
  10612. #endif
  10613. #if ENABLED(E4_IS_TMC2130)
  10614. automatic_current_control(stepperE4);
  10615. #endif
  10616. }
  10617. }
  10618. #endif // HAVE_TMC2130
  10619. /**
  10620. * Manage several activities:
  10621. * - Check for Filament Runout
  10622. * - Keep the command buffer full
  10623. * - Check for maximum inactive time between commands
  10624. * - Check for maximum inactive time between stepper commands
  10625. * - Check if pin CHDK needs to go LOW
  10626. * - Check for KILL button held down
  10627. * - Check for HOME button held down
  10628. * - Check if cooling fan needs to be switched on
  10629. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10630. */
  10631. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10632. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10633. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10634. handle_filament_runout();
  10635. #endif
  10636. if (commands_in_queue < BUFSIZE) get_available_commands();
  10637. const millis_t ms = millis();
  10638. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10639. SERIAL_ERROR_START();
  10640. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10641. kill(PSTR(MSG_KILLED));
  10642. }
  10643. // Prevent steppers timing-out in the middle of M600
  10644. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10645. #define MOVE_AWAY_TEST !move_away_flag
  10646. #else
  10647. #define MOVE_AWAY_TEST true
  10648. #endif
  10649. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10650. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10651. #if ENABLED(DISABLE_INACTIVE_X)
  10652. disable_X();
  10653. #endif
  10654. #if ENABLED(DISABLE_INACTIVE_Y)
  10655. disable_Y();
  10656. #endif
  10657. #if ENABLED(DISABLE_INACTIVE_Z)
  10658. disable_Z();
  10659. #endif
  10660. #if ENABLED(DISABLE_INACTIVE_E)
  10661. disable_e_steppers();
  10662. #endif
  10663. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  10664. ubl_lcd_map_control = defer_return_to_status = false;
  10665. #endif
  10666. }
  10667. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10668. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10669. chdkActive = false;
  10670. WRITE(CHDK, LOW);
  10671. }
  10672. #endif
  10673. #if HAS_KILL
  10674. // Check if the kill button was pressed and wait just in case it was an accidental
  10675. // key kill key press
  10676. // -------------------------------------------------------------------------------
  10677. static int killCount = 0; // make the inactivity button a bit less responsive
  10678. const int KILL_DELAY = 750;
  10679. if (!READ(KILL_PIN))
  10680. killCount++;
  10681. else if (killCount > 0)
  10682. killCount--;
  10683. // Exceeded threshold and we can confirm that it was not accidental
  10684. // KILL the machine
  10685. // ----------------------------------------------------------------
  10686. if (killCount >= KILL_DELAY) {
  10687. SERIAL_ERROR_START();
  10688. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10689. kill(PSTR(MSG_KILLED));
  10690. }
  10691. #endif
  10692. #if HAS_HOME
  10693. // Check to see if we have to home, use poor man's debouncer
  10694. // ---------------------------------------------------------
  10695. static int homeDebounceCount = 0; // poor man's debouncing count
  10696. const int HOME_DEBOUNCE_DELAY = 2500;
  10697. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10698. if (!homeDebounceCount) {
  10699. enqueue_and_echo_commands_P(PSTR("G28"));
  10700. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10701. }
  10702. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10703. homeDebounceCount++;
  10704. else
  10705. homeDebounceCount = 0;
  10706. }
  10707. #endif
  10708. #if ENABLED(USE_CONTROLLER_FAN)
  10709. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10710. #endif
  10711. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10712. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10713. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10714. bool oldstatus;
  10715. #if ENABLED(SWITCHING_EXTRUDER)
  10716. oldstatus = E0_ENABLE_READ;
  10717. enable_E0();
  10718. #else // !SWITCHING_EXTRUDER
  10719. switch (active_extruder) {
  10720. case 0: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10721. #if E_STEPPERS > 1
  10722. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10723. #if E_STEPPERS > 2
  10724. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10725. #if E_STEPPERS > 3
  10726. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10727. #if E_STEPPERS > 4
  10728. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10729. #endif // E_STEPPERS > 4
  10730. #endif // E_STEPPERS > 3
  10731. #endif // E_STEPPERS > 2
  10732. #endif // E_STEPPERS > 1
  10733. }
  10734. #endif // !SWITCHING_EXTRUDER
  10735. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10736. const float olde = current_position[E_AXIS];
  10737. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10738. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10739. current_position[E_AXIS] = olde;
  10740. planner.set_e_position_mm(olde);
  10741. stepper.synchronize();
  10742. #if ENABLED(SWITCHING_EXTRUDER)
  10743. E0_ENABLE_WRITE(oldstatus);
  10744. #else
  10745. switch (active_extruder) {
  10746. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10747. #if E_STEPPERS > 1
  10748. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10749. #if E_STEPPERS > 2
  10750. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10751. #if E_STEPPERS > 3
  10752. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10753. #if E_STEPPERS > 4
  10754. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10755. #endif // E_STEPPERS > 4
  10756. #endif // E_STEPPERS > 3
  10757. #endif // E_STEPPERS > 2
  10758. #endif // E_STEPPERS > 1
  10759. }
  10760. #endif // !SWITCHING_EXTRUDER
  10761. }
  10762. #endif // EXTRUDER_RUNOUT_PREVENT
  10763. #if ENABLED(DUAL_X_CARRIAGE)
  10764. // handle delayed move timeout
  10765. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10766. // travel moves have been received so enact them
  10767. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10768. set_destination_to_current();
  10769. prepare_move_to_destination();
  10770. }
  10771. #endif
  10772. #if ENABLED(TEMP_STAT_LEDS)
  10773. handle_status_leds();
  10774. #endif
  10775. #if ENABLED(HAVE_TMC2130)
  10776. checkOverTemp();
  10777. #endif
  10778. planner.check_axes_activity();
  10779. }
  10780. /**
  10781. * Standard idle routine keeps the machine alive
  10782. */
  10783. void idle(
  10784. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10785. bool no_stepper_sleep/*=false*/
  10786. #endif
  10787. ) {
  10788. lcd_update();
  10789. host_keepalive();
  10790. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10791. auto_report_temperatures();
  10792. #endif
  10793. manage_inactivity(
  10794. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10795. no_stepper_sleep
  10796. #endif
  10797. );
  10798. thermalManager.manage_heater();
  10799. #if ENABLED(PRINTCOUNTER)
  10800. print_job_timer.tick();
  10801. #endif
  10802. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10803. buzzer.tick();
  10804. #endif
  10805. #if ENABLED(I2C_POSITION_ENCODERS)
  10806. if (planner.blocks_queued() &&
  10807. ( (blockBufferIndexRef != planner.block_buffer_head) ||
  10808. ((lastUpdateMillis + I2CPE_MIN_UPD_TIME_MS) < millis())) ) {
  10809. blockBufferIndexRef = planner.block_buffer_head;
  10810. I2CPEM.update();
  10811. lastUpdateMillis = millis();
  10812. }
  10813. #endif
  10814. }
  10815. /**
  10816. * Kill all activity and lock the machine.
  10817. * After this the machine will need to be reset.
  10818. */
  10819. void kill(const char* lcd_msg) {
  10820. SERIAL_ERROR_START();
  10821. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10822. thermalManager.disable_all_heaters();
  10823. disable_all_steppers();
  10824. #if ENABLED(ULTRA_LCD)
  10825. kill_screen(lcd_msg);
  10826. #else
  10827. UNUSED(lcd_msg);
  10828. #endif
  10829. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10830. cli(); // Stop interrupts
  10831. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10832. thermalManager.disable_all_heaters(); //turn off heaters again
  10833. #if HAS_POWER_SWITCH
  10834. SET_INPUT(PS_ON_PIN);
  10835. #endif
  10836. suicide();
  10837. while (1) {
  10838. #if ENABLED(USE_WATCHDOG)
  10839. watchdog_reset();
  10840. #endif
  10841. } // Wait for reset
  10842. }
  10843. /**
  10844. * Turn off heaters and stop the print in progress
  10845. * After a stop the machine may be resumed with M999
  10846. */
  10847. void stop() {
  10848. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10849. #if ENABLED(PROBING_FANS_OFF)
  10850. if (fans_paused) fans_pause(false); // put things back the way they were
  10851. #endif
  10852. if (IsRunning()) {
  10853. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10854. SERIAL_ERROR_START();
  10855. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10856. LCD_MESSAGEPGM(MSG_STOPPED);
  10857. safe_delay(350); // allow enough time for messages to get out before stopping
  10858. Running = false;
  10859. }
  10860. }
  10861. /**
  10862. * Marlin entry-point: Set up before the program loop
  10863. * - Set up the kill pin, filament runout, power hold
  10864. * - Start the serial port
  10865. * - Print startup messages and diagnostics
  10866. * - Get EEPROM or default settings
  10867. * - Initialize managers for:
  10868. * • temperature
  10869. * • planner
  10870. * • watchdog
  10871. * • stepper
  10872. * • photo pin
  10873. * • servos
  10874. * • LCD controller
  10875. * • Digipot I2C
  10876. * • Z probe sled
  10877. * • status LEDs
  10878. */
  10879. void setup() {
  10880. #ifdef DISABLE_JTAG
  10881. // Disable JTAG on AT90USB chips to free up pins for IO
  10882. MCUCR = 0x80;
  10883. MCUCR = 0x80;
  10884. #endif
  10885. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10886. setup_filrunoutpin();
  10887. #endif
  10888. setup_killpin();
  10889. setup_powerhold();
  10890. #if HAS_STEPPER_RESET
  10891. disableStepperDrivers();
  10892. #endif
  10893. MYSERIAL.begin(BAUDRATE);
  10894. SERIAL_PROTOCOLLNPGM("start");
  10895. SERIAL_ECHO_START();
  10896. // Check startup - does nothing if bootloader sets MCUSR to 0
  10897. byte mcu = MCUSR;
  10898. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10899. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10900. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10901. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10902. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10903. MCUSR = 0;
  10904. SERIAL_ECHOPGM(MSG_MARLIN);
  10905. SERIAL_CHAR(' ');
  10906. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10907. SERIAL_EOL();
  10908. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10909. SERIAL_ECHO_START();
  10910. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10911. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10912. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10913. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10914. #endif
  10915. SERIAL_ECHO_START();
  10916. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10917. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10918. // Send "ok" after commands by default
  10919. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10920. // Load data from EEPROM if available (or use defaults)
  10921. // This also updates variables in the planner, elsewhere
  10922. (void)settings.load();
  10923. #if HAS_M206_COMMAND
  10924. // Initialize current position based on home_offset
  10925. COPY(current_position, home_offset);
  10926. #else
  10927. ZERO(current_position);
  10928. #endif
  10929. // Vital to init stepper/planner equivalent for current_position
  10930. SYNC_PLAN_POSITION_KINEMATIC();
  10931. thermalManager.init(); // Initialize temperature loop
  10932. #if ENABLED(USE_WATCHDOG)
  10933. watchdog_init();
  10934. #endif
  10935. stepper.init(); // Initialize stepper, this enables interrupts!
  10936. servo_init();
  10937. #if HAS_PHOTOGRAPH
  10938. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10939. #endif
  10940. #if HAS_CASE_LIGHT
  10941. case_light_on = CASE_LIGHT_DEFAULT_ON;
  10942. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  10943. update_case_light();
  10944. #endif
  10945. #if ENABLED(SPINDLE_LASER_ENABLE)
  10946. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10947. #if SPINDLE_DIR_CHANGE
  10948. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10949. #endif
  10950. #if ENABLED(SPINDLE_LASER_PWM)
  10951. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10952. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10953. #endif
  10954. #endif
  10955. #if HAS_BED_PROBE
  10956. endstops.enable_z_probe(false);
  10957. #endif
  10958. #if ENABLED(USE_CONTROLLER_FAN)
  10959. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  10960. #endif
  10961. #if HAS_STEPPER_RESET
  10962. enableStepperDrivers();
  10963. #endif
  10964. #if ENABLED(DIGIPOT_I2C)
  10965. digipot_i2c_init();
  10966. #endif
  10967. #if ENABLED(DAC_STEPPER_CURRENT)
  10968. dac_init();
  10969. #endif
  10970. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  10971. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  10972. #endif
  10973. setup_homepin();
  10974. #if PIN_EXISTS(STAT_LED_RED)
  10975. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  10976. #endif
  10977. #if PIN_EXISTS(STAT_LED_BLUE)
  10978. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  10979. #endif
  10980. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  10981. SET_OUTPUT(RGB_LED_R_PIN);
  10982. SET_OUTPUT(RGB_LED_G_PIN);
  10983. SET_OUTPUT(RGB_LED_B_PIN);
  10984. #if ENABLED(RGBW_LED)
  10985. SET_OUTPUT(RGB_LED_W_PIN);
  10986. #endif
  10987. #endif
  10988. #if ENABLED(MK2_MULTIPLEXER)
  10989. SET_OUTPUT(E_MUX0_PIN);
  10990. SET_OUTPUT(E_MUX1_PIN);
  10991. SET_OUTPUT(E_MUX2_PIN);
  10992. #endif
  10993. lcd_init();
  10994. #if ENABLED(SHOW_BOOTSCREEN)
  10995. #if ENABLED(DOGLCD)
  10996. safe_delay(BOOTSCREEN_TIMEOUT);
  10997. #elif ENABLED(ULTRA_LCD)
  10998. bootscreen();
  10999. #if DISABLED(SDSUPPORT)
  11000. lcd_init();
  11001. #endif
  11002. #endif
  11003. #endif
  11004. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  11005. // Initialize mixing to 100% color 1
  11006. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11007. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  11008. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  11009. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11010. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  11011. #endif
  11012. #if ENABLED(BLTOUCH)
  11013. // Make sure any BLTouch error condition is cleared
  11014. bltouch_command(BLTOUCH_RESET);
  11015. set_bltouch_deployed(true);
  11016. set_bltouch_deployed(false);
  11017. #endif
  11018. #if ENABLED(I2C_POSITION_ENCODERS)
  11019. I2CPEM.init();
  11020. #endif
  11021. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  11022. i2c.onReceive(i2c_on_receive);
  11023. i2c.onRequest(i2c_on_request);
  11024. #endif
  11025. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  11026. setup_endstop_interrupts();
  11027. #endif
  11028. #if ENABLED(SWITCHING_EXTRUDER)
  11029. move_extruder_servo(0); // Initialize extruder servo
  11030. #endif
  11031. #if ENABLED(SWITCHING_NOZZLE)
  11032. move_nozzle_servo(0); // Initialize nozzle servo
  11033. #endif
  11034. }
  11035. /**
  11036. * The main Marlin program loop
  11037. *
  11038. * - Save or log commands to SD
  11039. * - Process available commands (if not saving)
  11040. * - Call heater manager
  11041. * - Call inactivity manager
  11042. * - Call endstop manager
  11043. * - Call LCD update
  11044. */
  11045. void loop() {
  11046. if (commands_in_queue < BUFSIZE) get_available_commands();
  11047. #if ENABLED(SDSUPPORT)
  11048. card.checkautostart(false);
  11049. #endif
  11050. if (commands_in_queue) {
  11051. #if ENABLED(SDSUPPORT)
  11052. if (card.saving) {
  11053. char* command = command_queue[cmd_queue_index_r];
  11054. if (strstr_P(command, PSTR("M29"))) {
  11055. // M29 closes the file
  11056. card.closefile();
  11057. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  11058. ok_to_send();
  11059. }
  11060. else {
  11061. // Write the string from the read buffer to SD
  11062. card.write_command(command);
  11063. if (card.logging)
  11064. process_next_command(); // The card is saving because it's logging
  11065. else
  11066. ok_to_send();
  11067. }
  11068. }
  11069. else
  11070. process_next_command();
  11071. #else
  11072. process_next_command();
  11073. #endif // SDSUPPORT
  11074. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  11075. if (commands_in_queue) {
  11076. --commands_in_queue;
  11077. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  11078. }
  11079. }
  11080. endstops.report_state();
  11081. idle();
  11082. }