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 419KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205
  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 (Requires FWRETRACT)
  53. * G11 - Retract recover filament according to settings of M208 (Requires FWRETRACT)
  54. * G12 - Clean tool (Requires NOZZLE_CLEAN_FEATURE)
  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 (Requires INCH_MODE_SUPPORT)
  59. * G21 - Set input units to millimeters (Requires INCH_MODE_SUPPORT)
  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 - Start or continue the bed leveling probe procedure (Requires bed leveling)
  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 in any direction using the Z_MIN_PROBE (Requires G38_PROBE_TARGET)
  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 "least_squares_fit.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. // Initialized by settings.load()
  398. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  399. volumetric_enabled;
  400. float filament_size[EXTRUDERS], volumetric_multiplier[EXTRUDERS];
  401. #if HAS_WORKSPACE_OFFSET
  402. #if HAS_POSITION_SHIFT
  403. // The distance that XYZ has been offset by G92. Reset by G28.
  404. float position_shift[XYZ] = { 0 };
  405. #endif
  406. #if HAS_HOME_OFFSET
  407. // This offset is added to the configured home position.
  408. // Set by M206, M428, or menu item. Saved to EEPROM.
  409. float home_offset[XYZ] = { 0 };
  410. #endif
  411. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  412. // The above two are combined to save on computes
  413. float workspace_offset[XYZ] = { 0 };
  414. #endif
  415. #endif
  416. // Software Endstops are based on the configured limits.
  417. #if HAS_SOFTWARE_ENDSTOPS
  418. bool soft_endstops_enabled = true;
  419. #endif
  420. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  421. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  422. #if FAN_COUNT > 0
  423. int16_t fanSpeeds[FAN_COUNT] = { 0 };
  424. #if ENABLED(PROBING_FANS_OFF)
  425. bool fans_paused = false;
  426. int16_t paused_fanSpeeds[FAN_COUNT] = { 0 };
  427. #endif
  428. #endif
  429. // The active extruder (tool). Set with T<extruder> command.
  430. uint8_t active_extruder = 0;
  431. // Relative Mode. Enable with G91, disable with G90.
  432. static bool relative_mode = false;
  433. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  434. volatile bool wait_for_heatup = true;
  435. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  436. #if HAS_RESUME_CONTINUE
  437. volatile bool wait_for_user = false;
  438. #endif
  439. const char axis_codes[XYZE] = { 'X', 'Y', 'Z', 'E' };
  440. // Number of characters read in the current line of serial input
  441. static int serial_count = 0;
  442. // Inactivity shutdown
  443. millis_t previous_cmd_ms = 0;
  444. static millis_t max_inactive_time = 0;
  445. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  446. // Print Job Timer
  447. #if ENABLED(PRINTCOUNTER)
  448. PrintCounter print_job_timer = PrintCounter();
  449. #else
  450. Stopwatch print_job_timer = Stopwatch();
  451. #endif
  452. // Buzzer - I2C on the LCD or a BEEPER_PIN
  453. #if ENABLED(LCD_USE_I2C_BUZZER)
  454. #define BUZZ(d,f) lcd_buzz(d, f)
  455. #elif PIN_EXISTS(BEEPER)
  456. Buzzer buzzer;
  457. #define BUZZ(d,f) buzzer.tone(d, f)
  458. #else
  459. #define BUZZ(d,f) NOOP
  460. #endif
  461. static uint8_t target_extruder;
  462. #if HAS_BED_PROBE
  463. float zprobe_zoffset; // Initialized by settings.load()
  464. #endif
  465. #if HAS_ABL
  466. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  467. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  468. #elif defined(XY_PROBE_SPEED)
  469. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  470. #else
  471. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  472. #endif
  473. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  474. #if ENABLED(DELTA)
  475. #define ADJUST_DELTA(V) \
  476. if (planner.abl_enabled) { \
  477. const float zadj = bilinear_z_offset(V); \
  478. delta[A_AXIS] += zadj; \
  479. delta[B_AXIS] += zadj; \
  480. delta[C_AXIS] += zadj; \
  481. }
  482. #else
  483. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  484. #endif
  485. #elif IS_KINEMATIC
  486. #define ADJUST_DELTA(V) NOOP
  487. #endif
  488. #if ENABLED(Z_DUAL_ENDSTOPS)
  489. float z_endstop_adj;
  490. #endif
  491. // Extruder offsets
  492. #if HOTENDS > 1
  493. float hotend_offset[XYZ][HOTENDS]; // Initialized by settings.load()
  494. #endif
  495. #if HAS_Z_SERVO_ENDSTOP
  496. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  497. #endif
  498. #if ENABLED(BARICUDA)
  499. uint8_t baricuda_valve_pressure = 0,
  500. baricuda_e_to_p_pressure = 0;
  501. #endif
  502. #if ENABLED(FWRETRACT)
  503. bool autoretract_enabled = false;
  504. bool retracted[EXTRUDERS] = { false };
  505. bool retracted_swap[EXTRUDERS] = { false };
  506. float retract_length = RETRACT_LENGTH;
  507. float retract_length_swap = RETRACT_LENGTH_SWAP;
  508. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  509. float retract_zlift = RETRACT_ZLIFT;
  510. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  511. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  512. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  513. #endif // FWRETRACT
  514. #if HAS_POWER_SWITCH
  515. bool powersupply_on =
  516. #if ENABLED(PS_DEFAULT_OFF)
  517. false
  518. #else
  519. true
  520. #endif
  521. ;
  522. #endif
  523. #if ENABLED(DELTA)
  524. float delta[ABC],
  525. endstop_adj[ABC] = { 0 };
  526. // Initialized by settings.load()
  527. float delta_radius,
  528. delta_tower_angle_trim[2],
  529. delta_tower[ABC][2],
  530. delta_diagonal_rod,
  531. delta_calibration_radius,
  532. delta_diagonal_rod_2_tower[ABC],
  533. delta_segments_per_second,
  534. delta_clip_start_height = Z_MAX_POS;
  535. float delta_safe_distance_from_top();
  536. #endif
  537. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  538. int bilinear_grid_spacing[2], bilinear_start[2];
  539. float bilinear_grid_factor[2],
  540. z_values[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  541. #endif
  542. #if IS_SCARA
  543. // Float constants for SCARA calculations
  544. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  545. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  546. L2_2 = sq(float(L2));
  547. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  548. delta[ABC];
  549. #endif
  550. float cartes[XYZ] = { 0 };
  551. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  552. bool filament_sensor = false; // M405 turns on filament sensor control. M406 turns it off.
  553. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404.
  554. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  555. uint8_t meas_delay_cm = MEASUREMENT_DELAY_CM, // Distance delay setting
  556. measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  557. int8_t filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  558. #endif
  559. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  560. static bool filament_ran_out = false;
  561. #endif
  562. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  563. AdvancedPauseMenuResponse advanced_pause_menu_response;
  564. #endif
  565. #if ENABLED(MIXING_EXTRUDER)
  566. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  567. #if MIXING_VIRTUAL_TOOLS > 1
  568. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  569. #endif
  570. #endif
  571. static bool send_ok[BUFSIZE];
  572. #if HAS_SERVOS
  573. Servo servo[NUM_SERVOS];
  574. #define MOVE_SERVO(I, P) servo[I].move(P)
  575. #if HAS_Z_SERVO_ENDSTOP
  576. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  577. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  578. #endif
  579. #endif
  580. #ifdef CHDK
  581. millis_t chdkHigh = 0;
  582. bool chdkActive = false;
  583. #endif
  584. #ifdef AUTOMATIC_CURRENT_CONTROL
  585. bool auto_current_control = 0;
  586. #endif
  587. #if ENABLED(PID_EXTRUSION_SCALING)
  588. int lpq_len = 20;
  589. #endif
  590. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  591. MarlinBusyState busy_state = NOT_BUSY;
  592. static millis_t next_busy_signal_ms = 0;
  593. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  594. #else
  595. #define host_keepalive() NOOP
  596. #endif
  597. #if ENABLED(I2C_POSITION_ENCODERS)
  598. I2CPositionEncodersMgr I2CPEM;
  599. uint8_t blockBufferIndexRef = 0;
  600. millis_t lastUpdateMillis;
  601. #endif
  602. #if ENABLED(CNC_WORKSPACE_PLANES)
  603. static WorkspacePlane workspace_plane = PLANE_XY;
  604. #endif
  605. FORCE_INLINE float pgm_read_any(const float *p) { return pgm_read_float_near(p); }
  606. FORCE_INLINE signed char pgm_read_any(const signed char *p) { return pgm_read_byte_near(p); }
  607. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  608. static const PROGMEM type array##_P[XYZ] = { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  609. static inline type array(AxisEnum axis) { return pgm_read_any(&array##_P[axis]); } \
  610. typedef void __void_##CONFIG##__
  611. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS);
  612. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS);
  613. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS);
  614. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH);
  615. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM);
  616. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR);
  617. /**
  618. * ***************************************************************************
  619. * ******************************** FUNCTIONS ********************************
  620. * ***************************************************************************
  621. */
  622. void stop();
  623. void get_available_commands();
  624. void process_next_command();
  625. void prepare_move_to_destination();
  626. void get_cartesian_from_steppers();
  627. void set_current_from_steppers_for_axis(const AxisEnum axis);
  628. #if ENABLED(ARC_SUPPORT)
  629. void plan_arc(float target[XYZE], float* offset, uint8_t clockwise);
  630. #endif
  631. #if ENABLED(BEZIER_CURVE_SUPPORT)
  632. void plan_cubic_move(const float offset[4]);
  633. #endif
  634. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  635. void report_current_position();
  636. void report_current_position_detail();
  637. #if ENABLED(DEBUG_LEVELING_FEATURE)
  638. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  639. serialprintPGM(prefix);
  640. SERIAL_CHAR('(');
  641. SERIAL_ECHO(x);
  642. SERIAL_ECHOPAIR(", ", y);
  643. SERIAL_ECHOPAIR(", ", z);
  644. SERIAL_CHAR(')');
  645. if (suffix) serialprintPGM(suffix); else SERIAL_EOL();
  646. }
  647. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  648. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  649. }
  650. #if HAS_ABL
  651. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  652. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  653. }
  654. #endif
  655. #define DEBUG_POS(SUFFIX,VAR) do { \
  656. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); }while(0)
  657. #endif
  658. /**
  659. * sync_plan_position
  660. *
  661. * Set the planner/stepper positions directly from current_position with
  662. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  663. */
  664. void sync_plan_position() {
  665. #if ENABLED(DEBUG_LEVELING_FEATURE)
  666. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  667. #endif
  668. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  669. }
  670. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  671. #if IS_KINEMATIC
  672. inline void sync_plan_position_kinematic() {
  673. #if ENABLED(DEBUG_LEVELING_FEATURE)
  674. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  675. #endif
  676. planner.set_position_mm_kinematic(current_position);
  677. }
  678. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  679. #else
  680. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  681. #endif
  682. #if ENABLED(SDSUPPORT)
  683. #include "SdFatUtil.h"
  684. int freeMemory() { return SdFatUtil::FreeRam(); }
  685. #else
  686. extern "C" {
  687. extern char __bss_end;
  688. extern char __heap_start;
  689. extern void* __brkval;
  690. int freeMemory() {
  691. int free_memory;
  692. if ((int)__brkval == 0)
  693. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  694. else
  695. free_memory = ((int)&free_memory) - ((int)__brkval);
  696. return free_memory;
  697. }
  698. }
  699. #endif // !SDSUPPORT
  700. #if ENABLED(DIGIPOT_I2C)
  701. extern void digipot_i2c_set_current(uint8_t channel, float current);
  702. extern void digipot_i2c_init();
  703. #endif
  704. /**
  705. * Inject the next "immediate" command, when possible, onto the front of the queue.
  706. * Return true if any immediate commands remain to inject.
  707. */
  708. static bool drain_injected_commands_P() {
  709. if (injected_commands_P != NULL) {
  710. size_t i = 0;
  711. char c, cmd[30];
  712. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  713. cmd[sizeof(cmd) - 1] = '\0';
  714. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  715. cmd[i] = '\0';
  716. if (enqueue_and_echo_command(cmd)) // success?
  717. injected_commands_P = c ? injected_commands_P + i + 1 : NULL; // next command or done
  718. }
  719. return (injected_commands_P != NULL); // return whether any more remain
  720. }
  721. /**
  722. * Record one or many commands to run from program memory.
  723. * Aborts the current queue, if any.
  724. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  725. */
  726. void enqueue_and_echo_commands_P(const char * const pgcode) {
  727. injected_commands_P = pgcode;
  728. drain_injected_commands_P(); // first command executed asap (when possible)
  729. }
  730. /**
  731. * Clear the Marlin command queue
  732. */
  733. void clear_command_queue() {
  734. cmd_queue_index_r = cmd_queue_index_w;
  735. commands_in_queue = 0;
  736. }
  737. /**
  738. * Once a new command is in the ring buffer, call this to commit it
  739. */
  740. inline void _commit_command(bool say_ok) {
  741. send_ok[cmd_queue_index_w] = say_ok;
  742. if (++cmd_queue_index_w >= BUFSIZE) cmd_queue_index_w = 0;
  743. commands_in_queue++;
  744. }
  745. /**
  746. * Copy a command from RAM into the main command buffer.
  747. * Return true if the command was successfully added.
  748. * Return false for a full buffer, or if the 'command' is a comment.
  749. */
  750. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  751. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  752. strcpy(command_queue[cmd_queue_index_w], cmd);
  753. _commit_command(say_ok);
  754. return true;
  755. }
  756. /**
  757. * Enqueue with Serial Echo
  758. */
  759. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  760. if (_enqueuecommand(cmd, say_ok)) {
  761. SERIAL_ECHO_START();
  762. SERIAL_ECHOPAIR(MSG_ENQUEUEING, cmd);
  763. SERIAL_CHAR('"');
  764. SERIAL_EOL();
  765. return true;
  766. }
  767. return false;
  768. }
  769. void setup_killpin() {
  770. #if HAS_KILL
  771. SET_INPUT_PULLUP(KILL_PIN);
  772. #endif
  773. }
  774. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  775. void setup_filrunoutpin() {
  776. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  777. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  778. #else
  779. SET_INPUT(FIL_RUNOUT_PIN);
  780. #endif
  781. }
  782. #endif
  783. void setup_powerhold() {
  784. #if HAS_SUICIDE
  785. OUT_WRITE(SUICIDE_PIN, HIGH);
  786. #endif
  787. #if HAS_POWER_SWITCH
  788. #if ENABLED(PS_DEFAULT_OFF)
  789. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  790. #else
  791. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  792. #endif
  793. #endif
  794. }
  795. void suicide() {
  796. #if HAS_SUICIDE
  797. OUT_WRITE(SUICIDE_PIN, LOW);
  798. #endif
  799. }
  800. void servo_init() {
  801. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  802. servo[0].attach(SERVO0_PIN);
  803. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  804. #endif
  805. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  806. servo[1].attach(SERVO1_PIN);
  807. servo[1].detach();
  808. #endif
  809. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  810. servo[2].attach(SERVO2_PIN);
  811. servo[2].detach();
  812. #endif
  813. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  814. servo[3].attach(SERVO3_PIN);
  815. servo[3].detach();
  816. #endif
  817. #if HAS_Z_SERVO_ENDSTOP
  818. /**
  819. * Set position of Z Servo Endstop
  820. *
  821. * The servo might be deployed and positioned too low to stow
  822. * when starting up the machine or rebooting the board.
  823. * There's no way to know where the nozzle is positioned until
  824. * homing has been done - no homing with z-probe without init!
  825. *
  826. */
  827. STOW_Z_SERVO();
  828. #endif
  829. }
  830. /**
  831. * Stepper Reset (RigidBoard, et.al.)
  832. */
  833. #if HAS_STEPPER_RESET
  834. void disableStepperDrivers() {
  835. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  836. }
  837. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  838. #endif
  839. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  840. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  841. i2c.receive(bytes);
  842. }
  843. void i2c_on_request() { // just send dummy data for now
  844. i2c.reply("Hello World!\n");
  845. }
  846. #endif
  847. #if HAS_COLOR_LEDS
  848. void set_led_color(
  849. const uint8_t r, const uint8_t g, const uint8_t b
  850. #if ENABLED(RGBW_LED)
  851. , const uint8_t w=0
  852. #endif
  853. ) {
  854. #if ENABLED(BLINKM)
  855. // This variant uses i2c to send the RGB components to the device.
  856. SendColors(r, g, b);
  857. #endif
  858. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  859. // This variant uses 3 separate pins for the RGB components.
  860. // If the pins can do PWM then their intensity will be set.
  861. WRITE(RGB_LED_R_PIN, r ? HIGH : LOW);
  862. WRITE(RGB_LED_G_PIN, g ? HIGH : LOW);
  863. WRITE(RGB_LED_B_PIN, b ? HIGH : LOW);
  864. analogWrite(RGB_LED_R_PIN, r);
  865. analogWrite(RGB_LED_G_PIN, g);
  866. analogWrite(RGB_LED_B_PIN, b);
  867. #if ENABLED(RGBW_LED)
  868. WRITE(RGB_LED_W_PIN, w ? HIGH : LOW);
  869. analogWrite(RGB_LED_W_PIN, w);
  870. #endif
  871. #endif
  872. #if ENABLED(PCA9632)
  873. // Update I2C LED driver
  874. PCA9632_SetColor(r, g, b);
  875. #endif
  876. }
  877. #endif // HAS_COLOR_LEDS
  878. void gcode_line_error(const char* err, bool doFlush = true) {
  879. SERIAL_ERROR_START();
  880. serialprintPGM(err);
  881. SERIAL_ERRORLN(gcode_LastN);
  882. //Serial.println(gcode_N);
  883. if (doFlush) FlushSerialRequestResend();
  884. serial_count = 0;
  885. }
  886. /**
  887. * Get all commands waiting on the serial port and queue them.
  888. * Exit when the buffer is full or when no more characters are
  889. * left on the serial port.
  890. */
  891. inline void get_serial_commands() {
  892. static char serial_line_buffer[MAX_CMD_SIZE];
  893. static bool serial_comment_mode = false;
  894. // If the command buffer is empty for too long,
  895. // send "wait" to indicate Marlin is still waiting.
  896. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  897. static millis_t last_command_time = 0;
  898. const millis_t ms = millis();
  899. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  900. SERIAL_ECHOLNPGM(MSG_WAIT);
  901. last_command_time = ms;
  902. }
  903. #endif
  904. /**
  905. * Loop while serial characters are incoming and the queue is not full
  906. */
  907. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  908. char serial_char = MYSERIAL.read();
  909. /**
  910. * If the character ends the line
  911. */
  912. if (serial_char == '\n' || serial_char == '\r') {
  913. serial_comment_mode = false; // end of line == end of comment
  914. if (!serial_count) continue; // skip empty lines
  915. serial_line_buffer[serial_count] = 0; // terminate string
  916. serial_count = 0; //reset buffer
  917. char* command = serial_line_buffer;
  918. while (*command == ' ') command++; // skip any leading spaces
  919. char *npos = (*command == 'N') ? command : NULL, // Require the N parameter to start the line
  920. *apos = strchr(command, '*');
  921. if (npos) {
  922. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  923. if (M110) {
  924. char* n2pos = strchr(command + 4, 'N');
  925. if (n2pos) npos = n2pos;
  926. }
  927. gcode_N = strtol(npos + 1, NULL, 10);
  928. if (gcode_N != gcode_LastN + 1 && !M110) {
  929. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  930. return;
  931. }
  932. if (apos) {
  933. byte checksum = 0, count = 0;
  934. while (command[count] != '*') checksum ^= command[count++];
  935. if (strtol(apos + 1, NULL, 10) != checksum) {
  936. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  937. return;
  938. }
  939. // if no errors, continue parsing
  940. }
  941. else {
  942. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  943. return;
  944. }
  945. gcode_LastN = gcode_N;
  946. // if no errors, continue parsing
  947. }
  948. else if (apos) { // No '*' without 'N'
  949. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  950. return;
  951. }
  952. // Movement commands alert when stopped
  953. if (IsStopped()) {
  954. char* gpos = strchr(command, 'G');
  955. if (gpos) {
  956. const int codenum = strtol(gpos + 1, NULL, 10);
  957. switch (codenum) {
  958. case 0:
  959. case 1:
  960. case 2:
  961. case 3:
  962. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  963. LCD_MESSAGEPGM(MSG_STOPPED);
  964. break;
  965. }
  966. }
  967. }
  968. #if DISABLED(EMERGENCY_PARSER)
  969. // If command was e-stop process now
  970. if (strcmp(command, "M108") == 0) {
  971. wait_for_heatup = false;
  972. #if ENABLED(ULTIPANEL)
  973. wait_for_user = false;
  974. #endif
  975. }
  976. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  977. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  978. #endif
  979. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  980. last_command_time = ms;
  981. #endif
  982. // Add the command to the queue
  983. _enqueuecommand(serial_line_buffer, true);
  984. }
  985. else if (serial_count >= MAX_CMD_SIZE - 1) {
  986. // Keep fetching, but ignore normal characters beyond the max length
  987. // The command will be injected when EOL is reached
  988. }
  989. else if (serial_char == '\\') { // Handle escapes
  990. if (MYSERIAL.available() > 0) {
  991. // if we have one more character, copy it over
  992. serial_char = MYSERIAL.read();
  993. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  994. }
  995. // otherwise do nothing
  996. }
  997. else { // it's not a newline, carriage return or escape char
  998. if (serial_char == ';') serial_comment_mode = true;
  999. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  1000. }
  1001. } // queue has space, serial has data
  1002. }
  1003. #if ENABLED(SDSUPPORT)
  1004. /**
  1005. * Get commands from the SD Card until the command buffer is full
  1006. * or until the end of the file is reached. The special character '#'
  1007. * can also interrupt buffering.
  1008. */
  1009. inline void get_sdcard_commands() {
  1010. static bool stop_buffering = false,
  1011. sd_comment_mode = false;
  1012. if (!card.sdprinting) return;
  1013. /**
  1014. * '#' stops reading from SD to the buffer prematurely, so procedural
  1015. * macro calls are possible. If it occurs, stop_buffering is triggered
  1016. * and the buffer is run dry; this character _can_ occur in serial com
  1017. * due to checksums, however, no checksums are used in SD printing.
  1018. */
  1019. if (commands_in_queue == 0) stop_buffering = false;
  1020. uint16_t sd_count = 0;
  1021. bool card_eof = card.eof();
  1022. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  1023. const int16_t n = card.get();
  1024. char sd_char = (char)n;
  1025. card_eof = card.eof();
  1026. if (card_eof || n == -1
  1027. || sd_char == '\n' || sd_char == '\r'
  1028. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  1029. ) {
  1030. if (card_eof) {
  1031. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  1032. card.printingHasFinished();
  1033. #if ENABLED(PRINTER_EVENT_LEDS)
  1034. LCD_MESSAGEPGM(MSG_INFO_COMPLETED_PRINTS);
  1035. set_led_color(0, 255, 0); // Green
  1036. #if HAS_RESUME_CONTINUE
  1037. enqueue_and_echo_commands_P(PSTR("M0")); // end of the queue!
  1038. #else
  1039. safe_delay(1000);
  1040. #endif
  1041. set_led_color(0, 0, 0); // OFF
  1042. #endif
  1043. card.checkautostart(true);
  1044. }
  1045. else if (n == -1) {
  1046. SERIAL_ERROR_START();
  1047. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  1048. }
  1049. if (sd_char == '#') stop_buffering = true;
  1050. sd_comment_mode = false; // for new command
  1051. if (!sd_count) continue; // skip empty lines (and comment lines)
  1052. command_queue[cmd_queue_index_w][sd_count] = '\0'; // terminate string
  1053. sd_count = 0; // clear sd line buffer
  1054. _commit_command(false);
  1055. }
  1056. else if (sd_count >= MAX_CMD_SIZE - 1) {
  1057. /**
  1058. * Keep fetching, but ignore normal characters beyond the max length
  1059. * The command will be injected when EOL is reached
  1060. */
  1061. }
  1062. else {
  1063. if (sd_char == ';') sd_comment_mode = true;
  1064. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1065. }
  1066. }
  1067. }
  1068. #endif // SDSUPPORT
  1069. /**
  1070. * Add to the circular command queue the next command from:
  1071. * - The command-injection queue (injected_commands_P)
  1072. * - The active serial input (usually USB)
  1073. * - The SD card file being actively printed
  1074. */
  1075. void get_available_commands() {
  1076. // if any immediate commands remain, don't get other commands yet
  1077. if (drain_injected_commands_P()) return;
  1078. get_serial_commands();
  1079. #if ENABLED(SDSUPPORT)
  1080. get_sdcard_commands();
  1081. #endif
  1082. }
  1083. /**
  1084. * Set target_extruder from the T parameter or the active_extruder
  1085. *
  1086. * Returns TRUE if the target is invalid
  1087. */
  1088. bool get_target_extruder_from_command(const uint16_t code) {
  1089. if (parser.seenval('T')) {
  1090. const int8_t e = parser.value_byte();
  1091. if (e >= EXTRUDERS) {
  1092. SERIAL_ECHO_START();
  1093. SERIAL_CHAR('M');
  1094. SERIAL_ECHO(code);
  1095. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", e);
  1096. return true;
  1097. }
  1098. target_extruder = e;
  1099. }
  1100. else
  1101. target_extruder = active_extruder;
  1102. return false;
  1103. }
  1104. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1105. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1106. #endif
  1107. #if ENABLED(DUAL_X_CARRIAGE)
  1108. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1109. static float x_home_pos(const int extruder) {
  1110. if (extruder == 0)
  1111. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1112. else
  1113. /**
  1114. * In dual carriage mode the extruder offset provides an override of the
  1115. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1116. * This allows soft recalibration of the second extruder home position
  1117. * without firmware reflash (through the M218 command).
  1118. */
  1119. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1120. }
  1121. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1122. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1123. static bool active_extruder_parked = false; // used in mode 1 & 2
  1124. static float raised_parked_position[XYZE]; // used in mode 1
  1125. static millis_t delayed_move_time = 0; // used in mode 1
  1126. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1127. static int16_t duplicate_extruder_temp_offset = 0; // used in mode 2
  1128. #endif // DUAL_X_CARRIAGE
  1129. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  1130. /**
  1131. * Software endstops can be used to monitor the open end of
  1132. * an axis that has a hardware endstop on the other end. Or
  1133. * they can prevent axes from moving past endstops and grinding.
  1134. *
  1135. * To keep doing their job as the coordinate system changes,
  1136. * the software endstop positions must be refreshed to remain
  1137. * at the same positions relative to the machine.
  1138. */
  1139. void update_software_endstops(const AxisEnum axis) {
  1140. const float offs = 0.0
  1141. #if HAS_HOME_OFFSET
  1142. + home_offset[axis]
  1143. #endif
  1144. #if HAS_POSITION_SHIFT
  1145. + position_shift[axis]
  1146. #endif
  1147. ;
  1148. #if HAS_HOME_OFFSET && HAS_POSITION_SHIFT
  1149. workspace_offset[axis] = offs;
  1150. #endif
  1151. #if ENABLED(DUAL_X_CARRIAGE)
  1152. if (axis == X_AXIS) {
  1153. // In Dual X mode hotend_offset[X] is T1's home position
  1154. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1155. if (active_extruder != 0) {
  1156. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1157. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1158. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1159. }
  1160. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1161. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1162. // but not so far to the right that T1 would move past the end
  1163. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1164. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1165. }
  1166. else {
  1167. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1168. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1169. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1170. }
  1171. }
  1172. #else
  1173. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1174. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1175. #endif
  1176. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1177. if (DEBUGGING(LEVELING)) {
  1178. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1179. #if HAS_HOME_OFFSET
  1180. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1181. #endif
  1182. #if HAS_POSITION_SHIFT
  1183. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1184. #endif
  1185. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1186. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1187. }
  1188. #endif
  1189. #if ENABLED(DELTA)
  1190. if (axis == Z_AXIS)
  1191. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1192. #endif
  1193. }
  1194. #endif // HAS_WORKSPACE_OFFSET || DUAL_X_CARRIAGE
  1195. #if HAS_M206_COMMAND
  1196. /**
  1197. * Change the home offset for an axis, update the current
  1198. * position and the software endstops to retain the same
  1199. * relative distance to the new home.
  1200. *
  1201. * Since this changes the current_position, code should
  1202. * call sync_plan_position soon after this.
  1203. */
  1204. static void set_home_offset(const AxisEnum axis, const float v) {
  1205. current_position[axis] += v - home_offset[axis];
  1206. home_offset[axis] = v;
  1207. update_software_endstops(axis);
  1208. }
  1209. #endif // HAS_M206_COMMAND
  1210. /**
  1211. * Set an axis' current position to its home position (after homing).
  1212. *
  1213. * For Core and Cartesian robots this applies one-to-one when an
  1214. * individual axis has been homed.
  1215. *
  1216. * DELTA should wait until all homing is done before setting the XYZ
  1217. * current_position to home, because homing is a single operation.
  1218. * In the case where the axis positions are already known and previously
  1219. * homed, DELTA could home to X or Y individually by moving either one
  1220. * to the center. However, homing Z always homes XY and Z.
  1221. *
  1222. * SCARA should wait until all XY homing is done before setting the XY
  1223. * current_position to home, because neither X nor Y is at home until
  1224. * both are at home. Z can however be homed individually.
  1225. *
  1226. * Callers must sync the planner position after calling this!
  1227. */
  1228. static void set_axis_is_at_home(const AxisEnum axis) {
  1229. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1230. if (DEBUGGING(LEVELING)) {
  1231. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1232. SERIAL_CHAR(')');
  1233. SERIAL_EOL();
  1234. }
  1235. #endif
  1236. axis_known_position[axis] = axis_homed[axis] = true;
  1237. #if HAS_POSITION_SHIFT
  1238. position_shift[axis] = 0;
  1239. update_software_endstops(axis);
  1240. #endif
  1241. #if ENABLED(DUAL_X_CARRIAGE)
  1242. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1243. current_position[X_AXIS] = x_home_pos(active_extruder);
  1244. return;
  1245. }
  1246. #endif
  1247. #if ENABLED(MORGAN_SCARA)
  1248. /**
  1249. * Morgan SCARA homes XY at the same time
  1250. */
  1251. if (axis == X_AXIS || axis == Y_AXIS) {
  1252. float homeposition[XYZ];
  1253. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1254. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1255. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1256. /**
  1257. * Get Home position SCARA arm angles using inverse kinematics,
  1258. * and calculate homing offset using forward kinematics
  1259. */
  1260. inverse_kinematics(homeposition);
  1261. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1262. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1263. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1264. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1265. /**
  1266. * SCARA home positions are based on configuration since the actual
  1267. * limits are determined by the inverse kinematic transform.
  1268. */
  1269. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1270. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1271. }
  1272. else
  1273. #endif
  1274. {
  1275. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1276. }
  1277. /**
  1278. * Z Probe Z Homing? Account for the probe's Z offset.
  1279. */
  1280. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1281. if (axis == Z_AXIS) {
  1282. #if HOMING_Z_WITH_PROBE
  1283. current_position[Z_AXIS] -= zprobe_zoffset;
  1284. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1285. if (DEBUGGING(LEVELING)) {
  1286. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1287. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1288. }
  1289. #endif
  1290. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1291. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1292. #endif
  1293. }
  1294. #endif
  1295. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1296. if (DEBUGGING(LEVELING)) {
  1297. #if HAS_HOME_OFFSET
  1298. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1299. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1300. #endif
  1301. DEBUG_POS("", current_position);
  1302. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1303. SERIAL_CHAR(')');
  1304. SERIAL_EOL();
  1305. }
  1306. #endif
  1307. #if ENABLED(I2C_POSITION_ENCODERS)
  1308. I2CPEM.homed(axis);
  1309. #endif
  1310. }
  1311. /**
  1312. * Some planner shorthand inline functions
  1313. */
  1314. inline float get_homing_bump_feedrate(const AxisEnum axis) {
  1315. static const uint8_t homing_bump_divisor[] PROGMEM = HOMING_BUMP_DIVISOR;
  1316. uint8_t hbd = pgm_read_byte(&homing_bump_divisor[axis]);
  1317. if (hbd < 1) {
  1318. hbd = 10;
  1319. SERIAL_ECHO_START();
  1320. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1321. }
  1322. return homing_feedrate(axis) / hbd;
  1323. }
  1324. /**
  1325. * Move the planner to the current position from wherever it last moved
  1326. * (or from wherever it has been told it is located).
  1327. */
  1328. inline void line_to_current_position() {
  1329. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1330. }
  1331. /**
  1332. * Move the planner to the position stored in the destination array, which is
  1333. * used by G0/G1/G2/G3/G5 and many other functions to set a destination.
  1334. */
  1335. inline void line_to_destination(const float fr_mm_s) {
  1336. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1337. }
  1338. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1339. inline void set_current_to_destination() { COPY(current_position, destination); }
  1340. inline void set_destination_to_current() { COPY(destination, current_position); }
  1341. #if IS_KINEMATIC
  1342. /**
  1343. * Calculate delta, start a line, and set current_position to destination
  1344. */
  1345. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1346. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1347. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1348. #endif
  1349. refresh_cmd_timeout();
  1350. #if UBL_DELTA
  1351. // ubl segmented line will do z-only moves in single segment
  1352. ubl.prepare_segmented_line_to(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s));
  1353. #else
  1354. if ( current_position[X_AXIS] == destination[X_AXIS]
  1355. && current_position[Y_AXIS] == destination[Y_AXIS]
  1356. && current_position[Z_AXIS] == destination[Z_AXIS]
  1357. && current_position[E_AXIS] == destination[E_AXIS]
  1358. ) return;
  1359. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1360. #endif
  1361. set_current_to_destination();
  1362. }
  1363. #endif // IS_KINEMATIC
  1364. /**
  1365. * Plan a move to (X, Y, Z) and set the current_position
  1366. * The final current_position may not be the one that was requested
  1367. */
  1368. void do_blocking_move_to(const float &lx, const float &ly, const float &lz, const float &fr_mm_s/*=0.0*/) {
  1369. const float old_feedrate_mm_s = feedrate_mm_s;
  1370. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1371. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, lx, ly, lz);
  1372. #endif
  1373. #if ENABLED(DELTA)
  1374. if (!position_is_reachable_xy(lx, ly)) return;
  1375. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1376. set_destination_to_current(); // sync destination at the start
  1377. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1378. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1379. #endif
  1380. // when in the danger zone
  1381. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1382. if (lz > delta_clip_start_height) { // staying in the danger zone
  1383. destination[X_AXIS] = lx; // move directly (uninterpolated)
  1384. destination[Y_AXIS] = ly;
  1385. destination[Z_AXIS] = lz;
  1386. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1387. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1388. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1389. #endif
  1390. return;
  1391. }
  1392. else {
  1393. destination[Z_AXIS] = delta_clip_start_height;
  1394. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1395. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1396. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1397. #endif
  1398. }
  1399. }
  1400. if (lz > current_position[Z_AXIS]) { // raising?
  1401. destination[Z_AXIS] = lz;
  1402. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1403. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1404. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1405. #endif
  1406. }
  1407. destination[X_AXIS] = lx;
  1408. destination[Y_AXIS] = ly;
  1409. prepare_move_to_destination(); // set_current_to_destination
  1410. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1411. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1412. #endif
  1413. if (lz < current_position[Z_AXIS]) { // lowering?
  1414. destination[Z_AXIS] = lz;
  1415. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1416. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1417. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1418. #endif
  1419. }
  1420. #elif IS_SCARA
  1421. if (!position_is_reachable_xy(lx, ly)) return;
  1422. set_destination_to_current();
  1423. // If Z needs to raise, do it before moving XY
  1424. if (destination[Z_AXIS] < lz) {
  1425. destination[Z_AXIS] = lz;
  1426. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1427. }
  1428. destination[X_AXIS] = lx;
  1429. destination[Y_AXIS] = ly;
  1430. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1431. // If Z needs to lower, do it after moving XY
  1432. if (destination[Z_AXIS] > lz) {
  1433. destination[Z_AXIS] = lz;
  1434. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS));
  1435. }
  1436. #else
  1437. // If Z needs to raise, do it before moving XY
  1438. if (current_position[Z_AXIS] < lz) {
  1439. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1440. current_position[Z_AXIS] = lz;
  1441. line_to_current_position();
  1442. }
  1443. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1444. current_position[X_AXIS] = lx;
  1445. current_position[Y_AXIS] = ly;
  1446. line_to_current_position();
  1447. // If Z needs to lower, do it after moving XY
  1448. if (current_position[Z_AXIS] > lz) {
  1449. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate(Z_AXIS);
  1450. current_position[Z_AXIS] = lz;
  1451. line_to_current_position();
  1452. }
  1453. #endif
  1454. stepper.synchronize();
  1455. feedrate_mm_s = old_feedrate_mm_s;
  1456. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1457. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1458. #endif
  1459. }
  1460. void do_blocking_move_to_x(const float &lx, const float &fr_mm_s/*=0.0*/) {
  1461. do_blocking_move_to(lx, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1462. }
  1463. void do_blocking_move_to_z(const float &lz, const float &fr_mm_s/*=0.0*/) {
  1464. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], lz, fr_mm_s);
  1465. }
  1466. void do_blocking_move_to_xy(const float &lx, const float &ly, const float &fr_mm_s/*=0.0*/) {
  1467. do_blocking_move_to(lx, ly, current_position[Z_AXIS], fr_mm_s);
  1468. }
  1469. //
  1470. // Prepare to do endstop or probe moves
  1471. // with custom feedrates.
  1472. //
  1473. // - Save current feedrates
  1474. // - Reset the rate multiplier
  1475. // - Reset the command timeout
  1476. // - Enable the endstops (for endstop moves)
  1477. //
  1478. static void setup_for_endstop_or_probe_move() {
  1479. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1480. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1481. #endif
  1482. saved_feedrate_mm_s = feedrate_mm_s;
  1483. saved_feedrate_percentage = feedrate_percentage;
  1484. feedrate_percentage = 100;
  1485. refresh_cmd_timeout();
  1486. }
  1487. static void clean_up_after_endstop_or_probe_move() {
  1488. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1489. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1490. #endif
  1491. feedrate_mm_s = saved_feedrate_mm_s;
  1492. feedrate_percentage = saved_feedrate_percentage;
  1493. refresh_cmd_timeout();
  1494. }
  1495. #if HAS_BED_PROBE
  1496. /**
  1497. * Raise Z to a minimum height to make room for a probe to move
  1498. */
  1499. inline void do_probe_raise(const float z_raise) {
  1500. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1501. if (DEBUGGING(LEVELING)) {
  1502. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1503. SERIAL_CHAR(')');
  1504. SERIAL_EOL();
  1505. }
  1506. #endif
  1507. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1508. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1509. #if ENABLED(DELTA)
  1510. z_dest -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1511. #endif
  1512. if (z_dest > current_position[Z_AXIS])
  1513. do_blocking_move_to_z(z_dest);
  1514. }
  1515. #endif // HAS_BED_PROBE
  1516. #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)
  1517. bool axis_unhomed_error(const bool x/*=true*/, const bool y/*=true*/, const bool z/*=true*/) {
  1518. #if ENABLED(HOME_AFTER_DEACTIVATE)
  1519. const bool xx = x && !axis_known_position[X_AXIS],
  1520. yy = y && !axis_known_position[Y_AXIS],
  1521. zz = z && !axis_known_position[Z_AXIS];
  1522. #else
  1523. const bool xx = x && !axis_homed[X_AXIS],
  1524. yy = y && !axis_homed[Y_AXIS],
  1525. zz = z && !axis_homed[Z_AXIS];
  1526. #endif
  1527. if (xx || yy || zz) {
  1528. SERIAL_ECHO_START();
  1529. SERIAL_ECHOPGM(MSG_HOME " ");
  1530. if (xx) SERIAL_ECHOPGM(MSG_X);
  1531. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1532. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1533. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1534. #if ENABLED(ULTRA_LCD)
  1535. lcd_status_printf_P(0, PSTR(MSG_HOME " %s%s%s " MSG_FIRST), xx ? MSG_X : "", yy ? MSG_Y : "", zz ? MSG_Z : "");
  1536. #endif
  1537. return true;
  1538. }
  1539. return false;
  1540. }
  1541. #endif
  1542. #if ENABLED(Z_PROBE_SLED)
  1543. #ifndef SLED_DOCKING_OFFSET
  1544. #define SLED_DOCKING_OFFSET 0
  1545. #endif
  1546. /**
  1547. * Method to dock/undock a sled designed by Charles Bell.
  1548. *
  1549. * stow[in] If false, move to MAX_X and engage the solenoid
  1550. * If true, move to MAX_X and release the solenoid
  1551. */
  1552. static void dock_sled(bool stow) {
  1553. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1554. if (DEBUGGING(LEVELING)) {
  1555. SERIAL_ECHOPAIR("dock_sled(", stow);
  1556. SERIAL_CHAR(')');
  1557. SERIAL_EOL();
  1558. }
  1559. #endif
  1560. // Dock sled a bit closer to ensure proper capturing
  1561. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1562. #if HAS_SOLENOID_1 && DISABLED(EXT_SOLENOID)
  1563. WRITE(SOL1_PIN, !stow); // switch solenoid
  1564. #endif
  1565. }
  1566. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1567. FORCE_INLINE void do_blocking_move_to(const float logical[XYZ], const float &fr_mm_s) {
  1568. do_blocking_move_to(logical[X_AXIS], logical[Y_AXIS], logical[Z_AXIS], fr_mm_s);
  1569. }
  1570. void run_deploy_moves_script() {
  1571. #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)
  1572. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1573. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1574. #endif
  1575. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1576. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1577. #endif
  1578. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1579. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1580. #endif
  1581. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1582. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1583. #endif
  1584. 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 };
  1585. do_blocking_move_to(deploy_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1586. #endif
  1587. #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)
  1588. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1589. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1590. #endif
  1591. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1592. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1593. #endif
  1594. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1595. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1596. #endif
  1597. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1598. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1599. #endif
  1600. 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 };
  1601. do_blocking_move_to(deploy_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1602. #endif
  1603. #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)
  1604. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1605. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1606. #endif
  1607. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1608. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1609. #endif
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1615. #endif
  1616. 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 };
  1617. do_blocking_move_to(deploy_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1618. #endif
  1619. #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)
  1620. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1621. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1622. #endif
  1623. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1624. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1625. #endif
  1626. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1627. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1628. #endif
  1629. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1630. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1631. #endif
  1632. 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 };
  1633. do_blocking_move_to(deploy_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1634. #endif
  1635. #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)
  1636. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1637. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1638. #endif
  1639. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1640. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1641. #endif
  1642. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1643. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1646. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1647. #endif
  1648. 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 };
  1649. do_blocking_move_to(deploy_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1650. #endif
  1651. }
  1652. void run_stow_moves_script() {
  1653. #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)
  1654. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1655. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1656. #endif
  1657. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1658. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1659. #endif
  1660. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1661. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1662. #endif
  1663. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1664. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1665. #endif
  1666. 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 };
  1667. do_blocking_move_to(stow_1, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1668. #endif
  1669. #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)
  1670. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1671. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1672. #endif
  1673. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1674. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1675. #endif
  1676. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1677. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1678. #endif
  1679. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1680. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1681. #endif
  1682. 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 };
  1683. do_blocking_move_to(stow_2, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1684. #endif
  1685. #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)
  1686. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1687. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1688. #endif
  1689. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1690. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1691. #endif
  1692. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1693. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1694. #endif
  1695. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1696. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1697. #endif
  1698. 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 };
  1699. do_blocking_move_to(stow_3, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1700. #endif
  1701. #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)
  1702. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1703. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1704. #endif
  1705. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1706. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1707. #endif
  1708. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1709. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1710. #endif
  1711. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1712. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1713. #endif
  1714. 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 };
  1715. do_blocking_move_to(stow_4, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1716. #endif
  1717. #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)
  1718. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1719. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1720. #endif
  1721. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1722. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1723. #endif
  1724. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1725. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1726. #endif
  1727. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1728. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1729. #endif
  1730. 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 };
  1731. do_blocking_move_to(stow_5, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1732. #endif
  1733. }
  1734. #endif
  1735. #if ENABLED(PROBING_FANS_OFF)
  1736. void fans_pause(const bool p) {
  1737. if (p != fans_paused) {
  1738. fans_paused = p;
  1739. if (p)
  1740. for (uint8_t x = 0; x < FAN_COUNT; x++) {
  1741. paused_fanSpeeds[x] = fanSpeeds[x];
  1742. fanSpeeds[x] = 0;
  1743. }
  1744. else
  1745. for (uint8_t x = 0; x < FAN_COUNT; x++)
  1746. fanSpeeds[x] = paused_fanSpeeds[x];
  1747. }
  1748. }
  1749. #endif // PROBING_FANS_OFF
  1750. #if HAS_BED_PROBE
  1751. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1752. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1753. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1754. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1755. #else
  1756. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1757. #endif
  1758. #endif
  1759. #if QUIET_PROBING
  1760. void probing_pause(const bool p) {
  1761. #if ENABLED(PROBING_HEATERS_OFF)
  1762. thermalManager.pause(p);
  1763. #endif
  1764. #if ENABLED(PROBING_FANS_OFF)
  1765. fans_pause(p);
  1766. #endif
  1767. if (p) safe_delay(25);
  1768. }
  1769. #endif // QUIET_PROBING
  1770. #if ENABLED(BLTOUCH)
  1771. void bltouch_command(int angle) {
  1772. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1773. safe_delay(BLTOUCH_DELAY);
  1774. }
  1775. void set_bltouch_deployed(const bool deploy) {
  1776. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1777. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1778. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1779. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1780. safe_delay(1500); // Wait for internal self-test to complete.
  1781. // (Measured completion time was 0.65 seconds
  1782. // after reset, deploy, and stow sequence)
  1783. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1784. SERIAL_ERROR_START();
  1785. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1786. stop(); // punt!
  1787. }
  1788. }
  1789. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1790. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1791. if (DEBUGGING(LEVELING)) {
  1792. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1793. SERIAL_CHAR(')');
  1794. SERIAL_EOL();
  1795. }
  1796. #endif
  1797. }
  1798. #endif // BLTOUCH
  1799. // returns false for ok and true for failure
  1800. bool set_probe_deployed(bool deploy) {
  1801. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1802. if (DEBUGGING(LEVELING)) {
  1803. DEBUG_POS("set_probe_deployed", current_position);
  1804. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1805. }
  1806. #endif
  1807. if (endstops.z_probe_enabled == deploy) return false;
  1808. // Make room for probe
  1809. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1810. // When deploying make sure BLTOUCH is not already triggered
  1811. #if ENABLED(BLTOUCH)
  1812. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1813. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1814. bltouch_command(BLTOUCH_DEPLOY); // Also needs to deploy and stow to
  1815. bltouch_command(BLTOUCH_STOW); // clear the triggered condition.
  1816. safe_delay(1500); // wait for internal self test to complete
  1817. // measured completion time was 0.65 seconds
  1818. // after reset, deploy & stow sequence
  1819. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1820. SERIAL_ERROR_START();
  1821. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1822. stop(); // punt!
  1823. return true;
  1824. }
  1825. }
  1826. #elif ENABLED(Z_PROBE_SLED) || ENABLED(Z_PROBE_ALLEN_KEY)
  1827. #if ENABLED(Z_PROBE_SLED)
  1828. #define _AUE_ARGS true, false, false
  1829. #else
  1830. #define _AUE_ARGS
  1831. #endif
  1832. if (axis_unhomed_error(_AUE_ARGS)) {
  1833. SERIAL_ERROR_START();
  1834. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1835. stop();
  1836. return true;
  1837. }
  1838. #endif
  1839. const float oldXpos = current_position[X_AXIS],
  1840. oldYpos = current_position[Y_AXIS];
  1841. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1842. // If endstop is already false, the Z probe is deployed
  1843. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1844. // Would a goto be less ugly?
  1845. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1846. // for a triggered when stowed manual probe.
  1847. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1848. // otherwise an Allen-Key probe can't be stowed.
  1849. #endif
  1850. #if ENABLED(SOLENOID_PROBE)
  1851. #if HAS_SOLENOID_1
  1852. WRITE(SOL1_PIN, deploy);
  1853. #endif
  1854. #elif ENABLED(Z_PROBE_SLED)
  1855. dock_sled(!deploy);
  1856. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1857. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1858. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1859. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1860. #endif
  1861. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1862. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1863. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1864. if (IsRunning()) {
  1865. SERIAL_ERROR_START();
  1866. SERIAL_ERRORLNPGM("Z-Probe failed");
  1867. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1868. }
  1869. stop();
  1870. return true;
  1871. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1872. #endif
  1873. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1874. endstops.enable_z_probe(deploy);
  1875. return false;
  1876. }
  1877. static void do_probe_move(float z, float fr_mm_m) {
  1878. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1879. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1880. #endif
  1881. // Deploy BLTouch at the start of any probe
  1882. #if ENABLED(BLTOUCH)
  1883. set_bltouch_deployed(true);
  1884. #endif
  1885. #if QUIET_PROBING
  1886. probing_pause(true);
  1887. #endif
  1888. // Move down until probe triggered
  1889. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1890. #if QUIET_PROBING
  1891. probing_pause(false);
  1892. #endif
  1893. // Retract BLTouch immediately after a probe
  1894. #if ENABLED(BLTOUCH)
  1895. set_bltouch_deployed(false);
  1896. #endif
  1897. // Clear endstop flags
  1898. endstops.hit_on_purpose();
  1899. // Get Z where the steppers were interrupted
  1900. set_current_from_steppers_for_axis(Z_AXIS);
  1901. // Tell the planner where we actually are
  1902. SYNC_PLAN_POSITION_KINEMATIC();
  1903. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1904. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1905. #endif
  1906. }
  1907. // Do a single Z probe and return with current_position[Z_AXIS]
  1908. // at the height where the probe triggered.
  1909. static float run_z_probe() {
  1910. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1911. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1912. #endif
  1913. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1914. refresh_cmd_timeout();
  1915. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1916. // Do a first probe at the fast speed
  1917. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1918. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1919. float first_probe_z = current_position[Z_AXIS];
  1920. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1921. #endif
  1922. // move up by the bump distance
  1923. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1924. #else
  1925. // If the nozzle is above the travel height then
  1926. // move down quickly before doing the slow probe
  1927. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1928. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1929. #if ENABLED(DELTA)
  1930. z -= home_offset[Z_AXIS]; // Account for delta height adjustment
  1931. #endif
  1932. if (z < current_position[Z_AXIS])
  1933. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1934. #endif
  1935. // move down slowly to find bed
  1936. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1937. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1938. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1939. #endif
  1940. // Debug: compare probe heights
  1941. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1942. if (DEBUGGING(LEVELING)) {
  1943. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1944. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1945. }
  1946. #endif
  1947. return RAW_CURRENT_POSITION(Z) + zprobe_zoffset
  1948. #if ENABLED(DELTA)
  1949. + home_offset[Z_AXIS] // Account for delta height adjustment
  1950. #endif
  1951. ;
  1952. }
  1953. /**
  1954. * - Move to the given XY
  1955. * - Deploy the probe, if not already deployed
  1956. * - Probe the bed, get the Z position
  1957. * - Depending on the 'stow' flag
  1958. * - Stow the probe, or
  1959. * - Raise to the BETWEEN height
  1960. * - Return the probed Z position
  1961. */
  1962. float probe_pt(const float &lx, const float &ly, const bool stow, const uint8_t verbose_level, const bool printable=true) {
  1963. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1964. if (DEBUGGING(LEVELING)) {
  1965. SERIAL_ECHOPAIR(">>> probe_pt(", lx);
  1966. SERIAL_ECHOPAIR(", ", ly);
  1967. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1968. SERIAL_ECHOLNPGM("stow)");
  1969. DEBUG_POS("", current_position);
  1970. }
  1971. #endif
  1972. const float nx = lx - (X_PROBE_OFFSET_FROM_EXTRUDER), ny = ly - (Y_PROBE_OFFSET_FROM_EXTRUDER);
  1973. if (printable) {
  1974. if (!position_is_reachable_by_probe_xy(lx, ly)) return NAN;
  1975. }
  1976. else if (!position_is_reachable_xy(nx, ny)) return NAN;
  1977. const float old_feedrate_mm_s = feedrate_mm_s;
  1978. #if ENABLED(DELTA)
  1979. if (current_position[Z_AXIS] > delta_clip_start_height)
  1980. do_blocking_move_to_z(delta_clip_start_height);
  1981. #endif
  1982. // Ensure a minimum height before moving the probe
  1983. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1984. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1985. // Move the probe to the given XY
  1986. do_blocking_move_to_xy(nx, ny);
  1987. if (DEPLOY_PROBE()) return NAN;
  1988. const float measured_z = run_z_probe();
  1989. if (!stow)
  1990. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1991. else
  1992. if (STOW_PROBE()) return NAN;
  1993. if (verbose_level > 2) {
  1994. SERIAL_PROTOCOLPGM("Bed X: ");
  1995. SERIAL_PROTOCOL_F(lx, 3);
  1996. SERIAL_PROTOCOLPGM(" Y: ");
  1997. SERIAL_PROTOCOL_F(ly, 3);
  1998. SERIAL_PROTOCOLPGM(" Z: ");
  1999. SERIAL_PROTOCOL_F(measured_z, 3);
  2000. SERIAL_EOL();
  2001. }
  2002. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2003. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  2004. #endif
  2005. feedrate_mm_s = old_feedrate_mm_s;
  2006. return measured_z;
  2007. }
  2008. #endif // HAS_BED_PROBE
  2009. #if HAS_LEVELING
  2010. bool leveling_is_valid() {
  2011. return
  2012. #if ENABLED(MESH_BED_LEVELING)
  2013. mbl.has_mesh()
  2014. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2015. !!bilinear_grid_spacing[X_AXIS]
  2016. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2017. true
  2018. #else // 3POINT, LINEAR
  2019. true
  2020. #endif
  2021. ;
  2022. }
  2023. bool leveling_is_active() {
  2024. return
  2025. #if ENABLED(MESH_BED_LEVELING)
  2026. mbl.active()
  2027. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2028. ubl.state.active
  2029. #else
  2030. planner.abl_enabled
  2031. #endif
  2032. ;
  2033. }
  2034. /**
  2035. * Turn bed leveling on or off, fixing the current
  2036. * position as-needed.
  2037. *
  2038. * Disable: Current position = physical position
  2039. * Enable: Current position = "unleveled" physical position
  2040. */
  2041. void set_bed_leveling_enabled(const bool enable/*=true*/) {
  2042. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2043. const bool can_change = (!enable || leveling_is_valid());
  2044. #else
  2045. constexpr bool can_change = true;
  2046. #endif
  2047. if (can_change && enable != leveling_is_active()) {
  2048. #if ENABLED(MESH_BED_LEVELING)
  2049. if (!enable)
  2050. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2051. const bool enabling = enable && leveling_is_valid();
  2052. mbl.set_active(enabling);
  2053. if (enabling) planner.unapply_leveling(current_position);
  2054. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2055. #if PLANNER_LEVELING
  2056. if (ubl.state.active) { // leveling from on to off
  2057. // change unleveled current_position to physical current_position without moving steppers.
  2058. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  2059. ubl.state.active = false; // disable only AFTER calling apply_leveling
  2060. }
  2061. else { // leveling from off to on
  2062. ubl.state.active = true; // enable BEFORE calling unapply_leveling, otherwise ignored
  2063. // change physical current_position to unleveled current_position without moving steppers.
  2064. planner.unapply_leveling(current_position);
  2065. }
  2066. #else
  2067. ubl.state.active = enable; // just flip the bit, current_position will be wrong until next move.
  2068. #endif
  2069. #else // ABL
  2070. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2071. // Force bilinear_z_offset to re-calculate next time
  2072. const float reset[XYZ] = { -9999.999, -9999.999, 0 };
  2073. (void)bilinear_z_offset(reset);
  2074. #endif
  2075. // Enable or disable leveling compensation in the planner
  2076. planner.abl_enabled = enable;
  2077. if (!enable)
  2078. // When disabling just get the current position from the steppers.
  2079. // This will yield the smallest error when first converted back to steps.
  2080. set_current_from_steppers_for_axis(
  2081. #if ABL_PLANAR
  2082. ALL_AXES
  2083. #else
  2084. Z_AXIS
  2085. #endif
  2086. );
  2087. else
  2088. // When enabling, remove compensation from the current position,
  2089. // so compensation will give the right stepper counts.
  2090. planner.unapply_leveling(current_position);
  2091. #endif // ABL
  2092. }
  2093. }
  2094. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  2095. void set_z_fade_height(const float zfh) {
  2096. const bool level_active = leveling_is_active();
  2097. #if ENABLED(AUTO_BED_LEVELING_UBL)
  2098. if (level_active)
  2099. set_bed_leveling_enabled(false); // turn off before changing fade height for proper apply/unapply leveling to maintain current_position
  2100. planner.z_fade_height = zfh;
  2101. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2102. if (level_active)
  2103. set_bed_leveling_enabled(true); // turn back on after changing fade height
  2104. #else
  2105. planner.z_fade_height = zfh;
  2106. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  2107. if (level_active) {
  2108. set_current_from_steppers_for_axis(
  2109. #if ABL_PLANAR
  2110. ALL_AXES
  2111. #else
  2112. Z_AXIS
  2113. #endif
  2114. );
  2115. }
  2116. #endif
  2117. }
  2118. #endif // LEVELING_FADE_HEIGHT
  2119. /**
  2120. * Reset calibration results to zero.
  2121. */
  2122. void reset_bed_level() {
  2123. set_bed_leveling_enabled(false);
  2124. #if ENABLED(MESH_BED_LEVELING)
  2125. if (leveling_is_valid()) {
  2126. mbl.reset();
  2127. mbl.set_has_mesh(false);
  2128. }
  2129. #else
  2130. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2131. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2132. #endif
  2133. #if ABL_PLANAR
  2134. planner.bed_level_matrix.set_to_identity();
  2135. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2136. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2137. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2138. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2139. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2140. z_values[x][y] = NAN;
  2141. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2142. ubl.reset();
  2143. #endif
  2144. #endif
  2145. }
  2146. #endif // HAS_LEVELING
  2147. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(MESH_BED_LEVELING)
  2148. /**
  2149. * Enable to produce output in JSON format suitable
  2150. * for SCAD or JavaScript mesh visualizers.
  2151. *
  2152. * Visualize meshes in OpenSCAD using the included script.
  2153. *
  2154. * buildroot/shared/scripts/MarlinMesh.scad
  2155. */
  2156. //#define SCAD_MESH_OUTPUT
  2157. /**
  2158. * Print calibration results for plotting or manual frame adjustment.
  2159. */
  2160. 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)) {
  2161. #ifndef SCAD_MESH_OUTPUT
  2162. for (uint8_t x = 0; x < sx; x++) {
  2163. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2164. SERIAL_PROTOCOLCHAR(' ');
  2165. SERIAL_PROTOCOL((int)x);
  2166. }
  2167. SERIAL_EOL();
  2168. #endif
  2169. #ifdef SCAD_MESH_OUTPUT
  2170. SERIAL_PROTOCOLLNPGM("measured_z = ["); // open 2D array
  2171. #endif
  2172. for (uint8_t y = 0; y < sy; y++) {
  2173. #ifdef SCAD_MESH_OUTPUT
  2174. SERIAL_PROTOCOLPGM(" ["); // open sub-array
  2175. #else
  2176. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2177. SERIAL_PROTOCOL((int)y);
  2178. #endif
  2179. for (uint8_t x = 0; x < sx; x++) {
  2180. SERIAL_PROTOCOLCHAR(' ');
  2181. const float offset = fn(x, y);
  2182. if (!isnan(offset)) {
  2183. if (offset >= 0) SERIAL_PROTOCOLCHAR('+');
  2184. SERIAL_PROTOCOL_F(offset, precision);
  2185. }
  2186. else {
  2187. #ifdef SCAD_MESH_OUTPUT
  2188. for (uint8_t i = 3; i < precision + 3; i++)
  2189. SERIAL_PROTOCOLCHAR(' ');
  2190. SERIAL_PROTOCOLPGM("NAN");
  2191. #else
  2192. for (uint8_t i = 0; i < precision + 3; i++)
  2193. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2194. #endif
  2195. }
  2196. #ifdef SCAD_MESH_OUTPUT
  2197. if (x < sx - 1) SERIAL_PROTOCOLCHAR(',');
  2198. #endif
  2199. }
  2200. #ifdef SCAD_MESH_OUTPUT
  2201. SERIAL_PROTOCOLCHAR(' ');
  2202. SERIAL_PROTOCOLCHAR(']'); // close sub-array
  2203. if (y < sy - 1) SERIAL_PROTOCOLCHAR(',');
  2204. #endif
  2205. SERIAL_EOL();
  2206. }
  2207. #ifdef SCAD_MESH_OUTPUT
  2208. SERIAL_PROTOCOLPGM("];"); // close 2D array
  2209. #endif
  2210. SERIAL_EOL();
  2211. }
  2212. #endif
  2213. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2214. /**
  2215. * Extrapolate a single point from its neighbors
  2216. */
  2217. static void extrapolate_one_point(const uint8_t x, const uint8_t y, const int8_t xdir, const int8_t ydir) {
  2218. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2219. if (DEBUGGING(LEVELING)) {
  2220. SERIAL_ECHOPGM("Extrapolate [");
  2221. if (x < 10) SERIAL_CHAR(' ');
  2222. SERIAL_ECHO((int)x);
  2223. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2224. SERIAL_CHAR(' ');
  2225. if (y < 10) SERIAL_CHAR(' ');
  2226. SERIAL_ECHO((int)y);
  2227. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2228. SERIAL_CHAR(']');
  2229. }
  2230. #endif
  2231. if (!isnan(z_values[x][y])) {
  2232. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2233. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2234. #endif
  2235. return; // Don't overwrite good values.
  2236. }
  2237. SERIAL_EOL();
  2238. // Get X neighbors, Y neighbors, and XY neighbors
  2239. const uint8_t x1 = x + xdir, y1 = y + ydir, x2 = x1 + xdir, y2 = y1 + ydir;
  2240. float a1 = z_values[x1][y ], a2 = z_values[x2][y ],
  2241. b1 = z_values[x ][y1], b2 = z_values[x ][y2],
  2242. c1 = z_values[x1][y1], c2 = z_values[x2][y2];
  2243. // Treat far unprobed points as zero, near as equal to far
  2244. if (isnan(a2)) a2 = 0.0; if (isnan(a1)) a1 = a2;
  2245. if (isnan(b2)) b2 = 0.0; if (isnan(b1)) b1 = b2;
  2246. if (isnan(c2)) c2 = 0.0; if (isnan(c1)) c1 = c2;
  2247. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2248. // Take the average instead of the median
  2249. z_values[x][y] = (a + b + c) / 3.0;
  2250. // Median is robust (ignores outliers).
  2251. // z_values[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2252. // : ((c < b) ? b : (a < c) ? a : c);
  2253. }
  2254. //Enable this if your SCARA uses 180° of total area
  2255. //#define EXTRAPOLATE_FROM_EDGE
  2256. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2257. #if GRID_MAX_POINTS_X < GRID_MAX_POINTS_Y
  2258. #define HALF_IN_X
  2259. #elif GRID_MAX_POINTS_Y < GRID_MAX_POINTS_X
  2260. #define HALF_IN_Y
  2261. #endif
  2262. #endif
  2263. /**
  2264. * Fill in the unprobed points (corners of circular print surface)
  2265. * using linear extrapolation, away from the center.
  2266. */
  2267. static void extrapolate_unprobed_bed_level() {
  2268. #ifdef HALF_IN_X
  2269. constexpr uint8_t ctrx2 = 0, xlen = GRID_MAX_POINTS_X - 1;
  2270. #else
  2271. constexpr uint8_t ctrx1 = (GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2272. ctrx2 = (GRID_MAX_POINTS_X) / 2, // right-of-center
  2273. xlen = ctrx1;
  2274. #endif
  2275. #ifdef HALF_IN_Y
  2276. constexpr uint8_t ctry2 = 0, ylen = GRID_MAX_POINTS_Y - 1;
  2277. #else
  2278. constexpr uint8_t ctry1 = (GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2279. ctry2 = (GRID_MAX_POINTS_Y) / 2, // bottom-of-center
  2280. ylen = ctry1;
  2281. #endif
  2282. for (uint8_t xo = 0; xo <= xlen; xo++)
  2283. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2284. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2285. #ifndef HALF_IN_X
  2286. const uint8_t x1 = ctrx1 - xo;
  2287. #endif
  2288. #ifndef HALF_IN_Y
  2289. const uint8_t y1 = ctry1 - yo;
  2290. #ifndef HALF_IN_X
  2291. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2292. #endif
  2293. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2294. #endif
  2295. #ifndef HALF_IN_X
  2296. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2297. #endif
  2298. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2299. }
  2300. }
  2301. static void print_bilinear_leveling_grid() {
  2302. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2303. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 3,
  2304. [](const uint8_t ix, const uint8_t iy) { return z_values[ix][iy]; }
  2305. );
  2306. }
  2307. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2308. #define ABL_GRID_POINTS_VIRT_X (GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2309. #define ABL_GRID_POINTS_VIRT_Y (GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2310. #define ABL_TEMP_POINTS_X (GRID_MAX_POINTS_X + 2)
  2311. #define ABL_TEMP_POINTS_Y (GRID_MAX_POINTS_Y + 2)
  2312. float z_values_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2313. int bilinear_grid_spacing_virt[2] = { 0 };
  2314. float bilinear_grid_factor_virt[2] = { 0 };
  2315. static void bed_level_virt_print() {
  2316. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2317. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2318. [](const uint8_t ix, const uint8_t iy) { return z_values_virt[ix][iy]; }
  2319. );
  2320. }
  2321. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2322. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2323. uint8_t ep = 0, ip = 1;
  2324. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2325. if (x) {
  2326. ep = GRID_MAX_POINTS_X - 1;
  2327. ip = GRID_MAX_POINTS_X - 2;
  2328. }
  2329. if (WITHIN(y, 1, ABL_TEMP_POINTS_Y - 2))
  2330. return LINEAR_EXTRAPOLATION(
  2331. z_values[ep][y - 1],
  2332. z_values[ip][y - 1]
  2333. );
  2334. else
  2335. return LINEAR_EXTRAPOLATION(
  2336. bed_level_virt_coord(ep + 1, y),
  2337. bed_level_virt_coord(ip + 1, y)
  2338. );
  2339. }
  2340. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2341. if (y) {
  2342. ep = GRID_MAX_POINTS_Y - 1;
  2343. ip = GRID_MAX_POINTS_Y - 2;
  2344. }
  2345. if (WITHIN(x, 1, ABL_TEMP_POINTS_X - 2))
  2346. return LINEAR_EXTRAPOLATION(
  2347. z_values[x - 1][ep],
  2348. z_values[x - 1][ip]
  2349. );
  2350. else
  2351. return LINEAR_EXTRAPOLATION(
  2352. bed_level_virt_coord(x, ep + 1),
  2353. bed_level_virt_coord(x, ip + 1)
  2354. );
  2355. }
  2356. return z_values[x - 1][y - 1];
  2357. }
  2358. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2359. return (
  2360. p[i-1] * -t * sq(1 - t)
  2361. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2362. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2363. - p[i+2] * sq(t) * (1 - t)
  2364. ) * 0.5;
  2365. }
  2366. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2367. float row[4], column[4];
  2368. for (uint8_t i = 0; i < 4; i++) {
  2369. for (uint8_t j = 0; j < 4; j++) {
  2370. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2371. }
  2372. row[i] = bed_level_virt_cmr(column, 1, ty);
  2373. }
  2374. return bed_level_virt_cmr(row, 1, tx);
  2375. }
  2376. void bed_level_virt_interpolate() {
  2377. bilinear_grid_spacing_virt[X_AXIS] = bilinear_grid_spacing[X_AXIS] / (BILINEAR_SUBDIVISIONS);
  2378. bilinear_grid_spacing_virt[Y_AXIS] = bilinear_grid_spacing[Y_AXIS] / (BILINEAR_SUBDIVISIONS);
  2379. bilinear_grid_factor_virt[X_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[X_AXIS]);
  2380. bilinear_grid_factor_virt[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing_virt[Y_AXIS]);
  2381. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  2382. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  2383. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2384. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2385. if ((ty && y == GRID_MAX_POINTS_Y - 1) || (tx && x == GRID_MAX_POINTS_X - 1))
  2386. continue;
  2387. z_values_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2388. bed_level_virt_2cmr(
  2389. x + 1,
  2390. y + 1,
  2391. (float)tx / (BILINEAR_SUBDIVISIONS),
  2392. (float)ty / (BILINEAR_SUBDIVISIONS)
  2393. );
  2394. }
  2395. }
  2396. #endif // ABL_BILINEAR_SUBDIVISION
  2397. // Refresh after other values have been updated
  2398. void refresh_bed_level() {
  2399. bilinear_grid_factor[X_AXIS] = RECIPROCAL(bilinear_grid_spacing[X_AXIS]);
  2400. bilinear_grid_factor[Y_AXIS] = RECIPROCAL(bilinear_grid_spacing[Y_AXIS]);
  2401. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2402. bed_level_virt_interpolate();
  2403. #endif
  2404. }
  2405. #endif // AUTO_BED_LEVELING_BILINEAR
  2406. /**
  2407. * Home an individual linear axis
  2408. */
  2409. static void do_homing_move(const AxisEnum axis, const float distance, const float fr_mm_s=0.0) {
  2410. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2411. if (DEBUGGING(LEVELING)) {
  2412. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2413. SERIAL_ECHOPAIR(", ", distance);
  2414. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2415. SERIAL_CHAR(')');
  2416. SERIAL_EOL();
  2417. }
  2418. #endif
  2419. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2420. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2421. if (deploy_bltouch) set_bltouch_deployed(true);
  2422. #endif
  2423. #if QUIET_PROBING
  2424. if (axis == Z_AXIS) probing_pause(true);
  2425. #endif
  2426. // Tell the planner we're at Z=0
  2427. current_position[axis] = 0;
  2428. #if IS_SCARA
  2429. SYNC_PLAN_POSITION_KINEMATIC();
  2430. current_position[axis] = distance;
  2431. inverse_kinematics(current_position);
  2432. 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);
  2433. #else
  2434. sync_plan_position();
  2435. current_position[axis] = distance;
  2436. 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);
  2437. #endif
  2438. stepper.synchronize();
  2439. #if QUIET_PROBING
  2440. if (axis == Z_AXIS) probing_pause(false);
  2441. #endif
  2442. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2443. if (deploy_bltouch) set_bltouch_deployed(false);
  2444. #endif
  2445. endstops.hit_on_purpose();
  2446. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2447. if (DEBUGGING(LEVELING)) {
  2448. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2449. SERIAL_CHAR(')');
  2450. SERIAL_EOL();
  2451. }
  2452. #endif
  2453. }
  2454. /**
  2455. * TMC2130 specific sensorless homing using stallGuard2.
  2456. * stallGuard2 only works when in spreadCycle mode.
  2457. * spreadCycle and stealthChop are mutually exclusive.
  2458. */
  2459. #if ENABLED(SENSORLESS_HOMING)
  2460. void tmc2130_sensorless_homing(TMC2130Stepper &st, bool enable=true) {
  2461. #if ENABLED(STEALTHCHOP)
  2462. if (enable) {
  2463. st.coolstep_min_speed(1024UL * 1024UL - 1UL);
  2464. st.stealthChop(0);
  2465. }
  2466. else {
  2467. st.coolstep_min_speed(0);
  2468. st.stealthChop(1);
  2469. }
  2470. #endif
  2471. st.diag1_stall(enable ? 1 : 0);
  2472. }
  2473. #endif
  2474. /**
  2475. * Home an individual "raw axis" to its endstop.
  2476. * This applies to XYZ on Cartesian and Core robots, and
  2477. * to the individual ABC steppers on DELTA and SCARA.
  2478. *
  2479. * At the end of the procedure the axis is marked as
  2480. * homed and the current position of that axis is updated.
  2481. * Kinematic robots should wait till all axes are homed
  2482. * before updating the current position.
  2483. */
  2484. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2485. static void homeaxis(const AxisEnum axis) {
  2486. #if IS_SCARA
  2487. // Only Z homing (with probe) is permitted
  2488. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2489. #else
  2490. #define CAN_HOME(A) \
  2491. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2492. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2493. #endif
  2494. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2495. if (DEBUGGING(LEVELING)) {
  2496. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2497. SERIAL_CHAR(')');
  2498. SERIAL_EOL();
  2499. }
  2500. #endif
  2501. const int axis_home_dir =
  2502. #if ENABLED(DUAL_X_CARRIAGE)
  2503. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2504. #endif
  2505. home_dir(axis);
  2506. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2507. #if HOMING_Z_WITH_PROBE
  2508. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2509. #endif
  2510. // Set a flag for Z motor locking
  2511. #if ENABLED(Z_DUAL_ENDSTOPS)
  2512. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2513. #endif
  2514. // Disable stealthChop if used. Enable diag1 pin on driver.
  2515. #if ENABLED(SENSORLESS_HOMING)
  2516. #if ENABLED(X_IS_TMC2130)
  2517. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX);
  2518. #endif
  2519. #if ENABLED(Y_IS_TMC2130)
  2520. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY);
  2521. #endif
  2522. #endif
  2523. // Fast move towards endstop until triggered
  2524. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2525. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2526. #endif
  2527. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2528. // When homing Z with probe respect probe clearance
  2529. const float bump = axis_home_dir * (
  2530. #if HOMING_Z_WITH_PROBE
  2531. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2532. #endif
  2533. home_bump_mm(axis)
  2534. );
  2535. // If a second homing move is configured...
  2536. if (bump) {
  2537. // Move away from the endstop by the axis HOME_BUMP_MM
  2538. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2539. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2540. #endif
  2541. do_homing_move(axis, -bump);
  2542. // Slow move towards endstop until triggered
  2543. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2544. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2545. #endif
  2546. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2547. }
  2548. #if ENABLED(Z_DUAL_ENDSTOPS)
  2549. if (axis == Z_AXIS) {
  2550. float adj = FABS(z_endstop_adj);
  2551. bool lockZ1;
  2552. if (axis_home_dir > 0) {
  2553. adj = -adj;
  2554. lockZ1 = (z_endstop_adj > 0);
  2555. }
  2556. else
  2557. lockZ1 = (z_endstop_adj < 0);
  2558. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2559. // Move to the adjusted endstop height
  2560. do_homing_move(axis, adj);
  2561. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2562. stepper.set_homing_flag(false);
  2563. } // Z_AXIS
  2564. #endif
  2565. #if IS_SCARA
  2566. set_axis_is_at_home(axis);
  2567. SYNC_PLAN_POSITION_KINEMATIC();
  2568. #elif ENABLED(DELTA)
  2569. // Delta has already moved all three towers up in G28
  2570. // so here it re-homes each tower in turn.
  2571. // Delta homing treats the axes as normal linear axes.
  2572. // retrace by the amount specified in endstop_adj + additional 0.1mm in order to have minimum steps
  2573. if (endstop_adj[axis] * Z_HOME_DIR <= 0) {
  2574. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2575. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2576. #endif
  2577. do_homing_move(axis, endstop_adj[axis] - 0.1);
  2578. }
  2579. #else
  2580. // For cartesian/core machines,
  2581. // set the axis to its home position
  2582. set_axis_is_at_home(axis);
  2583. sync_plan_position();
  2584. destination[axis] = current_position[axis];
  2585. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2586. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2587. #endif
  2588. #endif
  2589. // Re-enable stealthChop if used. Disable diag1 pin on driver.
  2590. #if ENABLED(SENSORLESS_HOMING)
  2591. #if ENABLED(X_IS_TMC2130)
  2592. if (axis == X_AXIS) tmc2130_sensorless_homing(stepperX, false);
  2593. #endif
  2594. #if ENABLED(Y_IS_TMC2130)
  2595. if (axis == Y_AXIS) tmc2130_sensorless_homing(stepperY, false);
  2596. #endif
  2597. #endif
  2598. // Put away the Z probe
  2599. #if HOMING_Z_WITH_PROBE
  2600. if (axis == Z_AXIS && STOW_PROBE()) return;
  2601. #endif
  2602. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2603. if (DEBUGGING(LEVELING)) {
  2604. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2605. SERIAL_CHAR(')');
  2606. SERIAL_EOL();
  2607. }
  2608. #endif
  2609. } // homeaxis()
  2610. #if ENABLED(FWRETRACT)
  2611. void retract(const bool retracting, const bool swapping = false) {
  2612. static float hop_height;
  2613. if (retracting == retracted[active_extruder]) return;
  2614. const float old_feedrate_mm_s = feedrate_mm_s;
  2615. set_destination_to_current();
  2616. if (retracting) {
  2617. feedrate_mm_s = retract_feedrate_mm_s;
  2618. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2619. sync_plan_position_e();
  2620. prepare_move_to_destination();
  2621. if (retract_zlift > 0.01) {
  2622. hop_height = current_position[Z_AXIS];
  2623. // Pretend current position is lower
  2624. current_position[Z_AXIS] -= retract_zlift;
  2625. SYNC_PLAN_POSITION_KINEMATIC();
  2626. // Raise up to the old current_position
  2627. prepare_move_to_destination();
  2628. }
  2629. }
  2630. else {
  2631. // If the height hasn't been lowered, undo the Z hop
  2632. if (retract_zlift > 0.01 && hop_height <= current_position[Z_AXIS]) {
  2633. // Pretend current position is higher. Z will lower on the next move
  2634. current_position[Z_AXIS] += retract_zlift;
  2635. SYNC_PLAN_POSITION_KINEMATIC();
  2636. // Lower Z
  2637. prepare_move_to_destination();
  2638. }
  2639. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2640. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2641. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2642. sync_plan_position_e();
  2643. // Recover E
  2644. prepare_move_to_destination();
  2645. }
  2646. feedrate_mm_s = old_feedrate_mm_s;
  2647. retracted[active_extruder] = retracting;
  2648. } // retract()
  2649. #endif // FWRETRACT
  2650. #if ENABLED(MIXING_EXTRUDER)
  2651. void normalize_mix() {
  2652. float mix_total = 0.0;
  2653. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2654. // Scale all values if they don't add up to ~1.0
  2655. if (!NEAR(mix_total, 1.0)) {
  2656. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2657. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2658. }
  2659. }
  2660. #if ENABLED(DIRECT_MIXING_IN_G1)
  2661. // Get mixing parameters from the GCode
  2662. // The total "must" be 1.0 (but it will be normalized)
  2663. // If no mix factors are given, the old mix is preserved
  2664. void gcode_get_mix() {
  2665. const char* mixing_codes = "ABCDHI";
  2666. byte mix_bits = 0;
  2667. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2668. if (parser.seenval(mixing_codes[i])) {
  2669. SBI(mix_bits, i);
  2670. float v = parser.value_float();
  2671. NOLESS(v, 0.0);
  2672. mixing_factor[i] = RECIPROCAL(v);
  2673. }
  2674. }
  2675. // If any mixing factors were included, clear the rest
  2676. // If none were included, preserve the last mix
  2677. if (mix_bits) {
  2678. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2679. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2680. normalize_mix();
  2681. }
  2682. }
  2683. #endif
  2684. #endif
  2685. /**
  2686. * ***************************************************************************
  2687. * ***************************** G-CODE HANDLING *****************************
  2688. * ***************************************************************************
  2689. */
  2690. /**
  2691. * Set XYZE destination and feedrate from the current GCode command
  2692. *
  2693. * - Set destination from included axis codes
  2694. * - Set to current for missing axis codes
  2695. * - Set the feedrate, if included
  2696. */
  2697. void gcode_get_destination() {
  2698. LOOP_XYZE(i) {
  2699. if (parser.seen(axis_codes[i]))
  2700. destination[i] = parser.value_axis_units((AxisEnum)i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2701. else
  2702. destination[i] = current_position[i];
  2703. }
  2704. if (parser.linearval('F') > 0.0)
  2705. feedrate_mm_s = MMM_TO_MMS(parser.value_feedrate());
  2706. #if ENABLED(PRINTCOUNTER)
  2707. if (!DEBUGGING(DRYRUN))
  2708. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2709. #endif
  2710. // Get ABCDHI mixing factors
  2711. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2712. gcode_get_mix();
  2713. #endif
  2714. }
  2715. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2716. /**
  2717. * Output a "busy" message at regular intervals
  2718. * while the machine is not accepting commands.
  2719. */
  2720. void host_keepalive() {
  2721. const millis_t ms = millis();
  2722. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2723. if (PENDING(ms, next_busy_signal_ms)) return;
  2724. switch (busy_state) {
  2725. case IN_HANDLER:
  2726. case IN_PROCESS:
  2727. SERIAL_ECHO_START();
  2728. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2729. break;
  2730. case PAUSED_FOR_USER:
  2731. SERIAL_ECHO_START();
  2732. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2733. break;
  2734. case PAUSED_FOR_INPUT:
  2735. SERIAL_ECHO_START();
  2736. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2737. break;
  2738. default:
  2739. break;
  2740. }
  2741. }
  2742. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2743. }
  2744. #endif // HOST_KEEPALIVE_FEATURE
  2745. /**************************************************
  2746. ***************** GCode Handlers *****************
  2747. **************************************************/
  2748. /**
  2749. * G0, G1: Coordinated movement of X Y Z E axes
  2750. */
  2751. inline void gcode_G0_G1(
  2752. #if IS_SCARA
  2753. bool fast_move=false
  2754. #endif
  2755. ) {
  2756. if (IsRunning()) {
  2757. gcode_get_destination(); // For X Y Z E F
  2758. #if ENABLED(FWRETRACT)
  2759. if (autoretract_enabled && !(parser.seen('X') || parser.seen('Y') || parser.seen('Z')) && parser.seen('E')) {
  2760. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2761. // Is this move an attempt to retract or recover?
  2762. if ((echange < -(MIN_RETRACT) && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2763. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2764. sync_plan_position_e(); // AND from the planner
  2765. retract(!retracted[active_extruder]);
  2766. return;
  2767. }
  2768. }
  2769. #endif // FWRETRACT
  2770. #if IS_SCARA
  2771. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2772. #else
  2773. prepare_move_to_destination();
  2774. #endif
  2775. }
  2776. }
  2777. /**
  2778. * G2: Clockwise Arc
  2779. * G3: Counterclockwise Arc
  2780. *
  2781. * This command has two forms: IJ-form and R-form.
  2782. *
  2783. * - I specifies an X offset. J specifies a Y offset.
  2784. * At least one of the IJ parameters is required.
  2785. * X and Y can be omitted to do a complete circle.
  2786. * The given XY is not error-checked. The arc ends
  2787. * based on the angle of the destination.
  2788. * Mixing I or J with R will throw an error.
  2789. *
  2790. * - R specifies the radius. X or Y is required.
  2791. * Omitting both X and Y will throw an error.
  2792. * X or Y must differ from the current XY.
  2793. * Mixing R with I or J will throw an error.
  2794. *
  2795. * - P specifies the number of full circles to do
  2796. * before the specified arc move.
  2797. *
  2798. * Examples:
  2799. *
  2800. * G2 I10 ; CW circle centered at X+10
  2801. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2802. */
  2803. #if ENABLED(ARC_SUPPORT)
  2804. inline void gcode_G2_G3(bool clockwise) {
  2805. if (IsRunning()) {
  2806. #if ENABLED(SF_ARC_FIX)
  2807. const bool relative_mode_backup = relative_mode;
  2808. relative_mode = true;
  2809. #endif
  2810. gcode_get_destination();
  2811. #if ENABLED(SF_ARC_FIX)
  2812. relative_mode = relative_mode_backup;
  2813. #endif
  2814. float arc_offset[2] = { 0.0, 0.0 };
  2815. if (parser.seenval('R')) {
  2816. const float r = parser.value_linear_units(),
  2817. p1 = current_position[X_AXIS], q1 = current_position[Y_AXIS],
  2818. p2 = destination[X_AXIS], q2 = destination[Y_AXIS];
  2819. if (r && (p2 != p1 || q2 != q1)) {
  2820. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2821. dx = p2 - p1, dy = q2 - q1, // X and Y differences
  2822. d = HYPOT(dx, dy), // Linear distance between the points
  2823. h = SQRT(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2824. mx = (p1 + p2) * 0.5, my = (q1 + q2) * 0.5, // Point between the two points
  2825. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2826. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2827. arc_offset[0] = cx - p1;
  2828. arc_offset[1] = cy - q1;
  2829. }
  2830. }
  2831. else {
  2832. if (parser.seenval('I')) arc_offset[0] = parser.value_linear_units();
  2833. if (parser.seenval('J')) arc_offset[1] = parser.value_linear_units();
  2834. }
  2835. if (arc_offset[0] || arc_offset[1]) {
  2836. #if ENABLED(ARC_P_CIRCLES)
  2837. // P indicates number of circles to do
  2838. int8_t circles_to_do = parser.byteval('P');
  2839. if (!WITHIN(circles_to_do, 0, 100)) {
  2840. SERIAL_ERROR_START();
  2841. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2842. }
  2843. while (circles_to_do--)
  2844. plan_arc(current_position, arc_offset, clockwise);
  2845. #endif
  2846. // Send the arc to the planner
  2847. plan_arc(destination, arc_offset, clockwise);
  2848. refresh_cmd_timeout();
  2849. }
  2850. else {
  2851. // Bad arguments
  2852. SERIAL_ERROR_START();
  2853. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2854. }
  2855. }
  2856. }
  2857. #endif // ARC_SUPPORT
  2858. /**
  2859. * G4: Dwell S<seconds> or P<milliseconds>
  2860. */
  2861. inline void gcode_G4() {
  2862. millis_t dwell_ms = 0;
  2863. if (parser.seenval('P')) dwell_ms = parser.value_millis(); // milliseconds to wait
  2864. if (parser.seenval('S')) dwell_ms = parser.value_millis_from_seconds(); // seconds to wait
  2865. stepper.synchronize();
  2866. refresh_cmd_timeout();
  2867. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2868. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2869. while (PENDING(millis(), dwell_ms)) idle();
  2870. }
  2871. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2872. /**
  2873. * Parameters interpreted according to:
  2874. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2875. * However I, J omission is not supported at this point; all
  2876. * parameters can be omitted and default to zero.
  2877. */
  2878. /**
  2879. * G5: Cubic B-spline
  2880. */
  2881. inline void gcode_G5() {
  2882. if (IsRunning()) {
  2883. gcode_get_destination();
  2884. const float offset[] = {
  2885. parser.linearval('I'),
  2886. parser.linearval('J'),
  2887. parser.linearval('P'),
  2888. parser.linearval('Q')
  2889. };
  2890. plan_cubic_move(offset);
  2891. }
  2892. }
  2893. #endif // BEZIER_CURVE_SUPPORT
  2894. #if ENABLED(FWRETRACT)
  2895. /**
  2896. * G10 - Retract filament according to settings of M207
  2897. */
  2898. inline void gcode_G10() {
  2899. #if EXTRUDERS > 1
  2900. const bool rs = parser.boolval('S');
  2901. retracted_swap[active_extruder] = rs; // Use 'S' for swap, default to false
  2902. #endif
  2903. retract(true
  2904. #if EXTRUDERS > 1
  2905. , rs
  2906. #endif
  2907. );
  2908. }
  2909. /**
  2910. * G11 - Recover filament according to settings of M208
  2911. */
  2912. inline void gcode_G11() { retract(false); }
  2913. #endif // FWRETRACT
  2914. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2915. /**
  2916. * G12: Clean the nozzle
  2917. */
  2918. inline void gcode_G12() {
  2919. // Don't allow nozzle cleaning without homing first
  2920. if (axis_unhomed_error()) return;
  2921. const uint8_t pattern = parser.ushortval('P', 0),
  2922. strokes = parser.ushortval('S', NOZZLE_CLEAN_STROKES),
  2923. objects = parser.ushortval('T', NOZZLE_CLEAN_TRIANGLES);
  2924. const float radius = parser.floatval('R', NOZZLE_CLEAN_CIRCLE_RADIUS);
  2925. Nozzle::clean(pattern, strokes, radius, objects);
  2926. }
  2927. #endif
  2928. #if ENABLED(CNC_WORKSPACE_PLANES)
  2929. void report_workspace_plane() {
  2930. SERIAL_ECHO_START();
  2931. SERIAL_ECHOPGM("Workspace Plane ");
  2932. serialprintPGM(workspace_plane == PLANE_YZ ? PSTR("YZ\n") : workspace_plane == PLANE_ZX ? PSTR("ZX\n") : PSTR("XY\n"));
  2933. }
  2934. /**
  2935. * G17: Select Plane XY
  2936. * G18: Select Plane ZX
  2937. * G19: Select Plane YZ
  2938. */
  2939. inline void gcode_G17() { workspace_plane = PLANE_XY; }
  2940. inline void gcode_G18() { workspace_plane = PLANE_ZX; }
  2941. inline void gcode_G19() { workspace_plane = PLANE_YZ; }
  2942. #endif // CNC_WORKSPACE_PLANES
  2943. #if ENABLED(INCH_MODE_SUPPORT)
  2944. /**
  2945. * G20: Set input mode to inches
  2946. */
  2947. inline void gcode_G20() { parser.set_input_linear_units(LINEARUNIT_INCH); }
  2948. /**
  2949. * G21: Set input mode to millimeters
  2950. */
  2951. inline void gcode_G21() { parser.set_input_linear_units(LINEARUNIT_MM); }
  2952. #endif
  2953. #if ENABLED(NOZZLE_PARK_FEATURE)
  2954. /**
  2955. * G27: Park the nozzle
  2956. */
  2957. inline void gcode_G27() {
  2958. // Don't allow nozzle parking without homing first
  2959. if (axis_unhomed_error()) return;
  2960. Nozzle::park(parser.ushortval('P'));
  2961. }
  2962. #endif // NOZZLE_PARK_FEATURE
  2963. #if ENABLED(QUICK_HOME)
  2964. static void quick_home_xy() {
  2965. // Pretend the current position is 0,0
  2966. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2967. sync_plan_position();
  2968. const int x_axis_home_dir =
  2969. #if ENABLED(DUAL_X_CARRIAGE)
  2970. x_home_dir(active_extruder)
  2971. #else
  2972. home_dir(X_AXIS)
  2973. #endif
  2974. ;
  2975. const float mlx = max_length(X_AXIS),
  2976. mly = max_length(Y_AXIS),
  2977. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2978. fr_mm_s = min(homing_feedrate(X_AXIS), homing_feedrate(Y_AXIS)) * SQRT(sq(mlratio) + 1.0);
  2979. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2980. endstops.hit_on_purpose(); // clear endstop hit flags
  2981. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2982. }
  2983. #endif // QUICK_HOME
  2984. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2985. void log_machine_info() {
  2986. SERIAL_ECHOPGM("Machine Type: ");
  2987. #if ENABLED(DELTA)
  2988. SERIAL_ECHOLNPGM("Delta");
  2989. #elif IS_SCARA
  2990. SERIAL_ECHOLNPGM("SCARA");
  2991. #elif IS_CORE
  2992. SERIAL_ECHOLNPGM("Core");
  2993. #else
  2994. SERIAL_ECHOLNPGM("Cartesian");
  2995. #endif
  2996. SERIAL_ECHOPGM("Probe: ");
  2997. #if ENABLED(PROBE_MANUALLY)
  2998. SERIAL_ECHOLNPGM("PROBE_MANUALLY");
  2999. #elif ENABLED(FIX_MOUNTED_PROBE)
  3000. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  3001. #elif ENABLED(BLTOUCH)
  3002. SERIAL_ECHOLNPGM("BLTOUCH");
  3003. #elif HAS_Z_SERVO_ENDSTOP
  3004. SERIAL_ECHOLNPGM("SERVO PROBE");
  3005. #elif ENABLED(Z_PROBE_SLED)
  3006. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  3007. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  3008. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  3009. #else
  3010. SERIAL_ECHOLNPGM("NONE");
  3011. #endif
  3012. #if HAS_BED_PROBE
  3013. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  3014. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  3015. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  3016. #if X_PROBE_OFFSET_FROM_EXTRUDER > 0
  3017. SERIAL_ECHOPGM(" (Right");
  3018. #elif X_PROBE_OFFSET_FROM_EXTRUDER < 0
  3019. SERIAL_ECHOPGM(" (Left");
  3020. #elif Y_PROBE_OFFSET_FROM_EXTRUDER != 0
  3021. SERIAL_ECHOPGM(" (Middle");
  3022. #else
  3023. SERIAL_ECHOPGM(" (Aligned With");
  3024. #endif
  3025. #if Y_PROBE_OFFSET_FROM_EXTRUDER > 0
  3026. SERIAL_ECHOPGM("-Back");
  3027. #elif Y_PROBE_OFFSET_FROM_EXTRUDER < 0
  3028. SERIAL_ECHOPGM("-Front");
  3029. #elif X_PROBE_OFFSET_FROM_EXTRUDER != 0
  3030. SERIAL_ECHOPGM("-Center");
  3031. #endif
  3032. if (zprobe_zoffset < 0)
  3033. SERIAL_ECHOPGM(" & Below");
  3034. else if (zprobe_zoffset > 0)
  3035. SERIAL_ECHOPGM(" & Above");
  3036. else
  3037. SERIAL_ECHOPGM(" & Same Z as");
  3038. SERIAL_ECHOLNPGM(" Nozzle)");
  3039. #endif
  3040. #if HAS_ABL
  3041. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  3042. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3043. SERIAL_ECHOPGM("LINEAR");
  3044. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3045. SERIAL_ECHOPGM("BILINEAR");
  3046. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3047. SERIAL_ECHOPGM("3POINT");
  3048. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3049. SERIAL_ECHOPGM("UBL");
  3050. #endif
  3051. if (leveling_is_active()) {
  3052. SERIAL_ECHOLNPGM(" (enabled)");
  3053. #if ABL_PLANAR
  3054. const float diff[XYZ] = {
  3055. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  3056. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  3057. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  3058. };
  3059. SERIAL_ECHOPGM("ABL Adjustment X");
  3060. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  3061. SERIAL_ECHO(diff[X_AXIS]);
  3062. SERIAL_ECHOPGM(" Y");
  3063. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  3064. SERIAL_ECHO(diff[Y_AXIS]);
  3065. SERIAL_ECHOPGM(" Z");
  3066. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  3067. SERIAL_ECHO(diff[Z_AXIS]);
  3068. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  3069. SERIAL_ECHOPAIR("UBL Adjustment Z", stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]);
  3070. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3071. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  3072. #endif
  3073. }
  3074. else
  3075. SERIAL_ECHOLNPGM(" (disabled)");
  3076. SERIAL_EOL();
  3077. #elif ENABLED(MESH_BED_LEVELING)
  3078. SERIAL_ECHOPGM("Mesh Bed Leveling");
  3079. if (leveling_is_active()) {
  3080. float lz = current_position[Z_AXIS];
  3081. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  3082. SERIAL_ECHOLNPGM(" (enabled)");
  3083. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  3084. }
  3085. else
  3086. SERIAL_ECHOPGM(" (disabled)");
  3087. SERIAL_EOL();
  3088. #endif // MESH_BED_LEVELING
  3089. }
  3090. #endif // DEBUG_LEVELING_FEATURE
  3091. #if ENABLED(DELTA)
  3092. /**
  3093. * A delta can only safely home all axes at the same time
  3094. * This is like quick_home_xy() but for 3 towers.
  3095. */
  3096. inline void home_delta() {
  3097. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3098. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  3099. #endif
  3100. // Init the current position of all carriages to 0,0,0
  3101. ZERO(current_position);
  3102. sync_plan_position();
  3103. // Move all carriages together linearly until an endstop is hit.
  3104. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  3105. feedrate_mm_s = homing_feedrate(X_AXIS);
  3106. line_to_current_position();
  3107. stepper.synchronize();
  3108. endstops.hit_on_purpose(); // clear endstop hit flags
  3109. // At least one carriage has reached the top.
  3110. // Now re-home each carriage separately.
  3111. HOMEAXIS(A);
  3112. HOMEAXIS(B);
  3113. HOMEAXIS(C);
  3114. // Set all carriages to their home positions
  3115. // Do this here all at once for Delta, because
  3116. // XYZ isn't ABC. Applying this per-tower would
  3117. // give the impression that they are the same.
  3118. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  3119. SYNC_PLAN_POSITION_KINEMATIC();
  3120. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3121. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  3122. #endif
  3123. }
  3124. #endif // DELTA
  3125. #if ENABLED(Z_SAFE_HOMING)
  3126. inline void home_z_safely() {
  3127. // Disallow Z homing if X or Y are unknown
  3128. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  3129. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  3130. SERIAL_ECHO_START();
  3131. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  3132. return;
  3133. }
  3134. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3135. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  3136. #endif
  3137. SYNC_PLAN_POSITION_KINEMATIC();
  3138. /**
  3139. * Move the Z probe (or just the nozzle) to the safe homing point
  3140. */
  3141. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  3142. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  3143. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  3144. #if HOMING_Z_WITH_PROBE
  3145. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  3146. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  3147. #endif
  3148. if (position_is_reachable_xy(destination[X_AXIS], destination[Y_AXIS])) {
  3149. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3150. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  3151. #endif
  3152. // This causes the carriage on Dual X to unpark
  3153. #if ENABLED(DUAL_X_CARRIAGE)
  3154. active_extruder_parked = false;
  3155. #endif
  3156. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  3157. HOMEAXIS(Z);
  3158. }
  3159. else {
  3160. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  3161. SERIAL_ECHO_START();
  3162. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  3163. }
  3164. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3165. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  3166. #endif
  3167. }
  3168. #endif // Z_SAFE_HOMING
  3169. #if ENABLED(PROBE_MANUALLY)
  3170. bool g29_in_progress = false;
  3171. #else
  3172. constexpr bool g29_in_progress = false;
  3173. #endif
  3174. /**
  3175. * G28: Home all axes according to settings
  3176. *
  3177. * Parameters
  3178. *
  3179. * None Home to all axes with no parameters.
  3180. * With QUICK_HOME enabled XY will home together, then Z.
  3181. *
  3182. * Cartesian parameters
  3183. *
  3184. * X Home to the X endstop
  3185. * Y Home to the Y endstop
  3186. * Z Home to the Z endstop
  3187. *
  3188. */
  3189. inline void gcode_G28(const bool always_home_all) {
  3190. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3191. if (DEBUGGING(LEVELING)) {
  3192. SERIAL_ECHOLNPGM(">>> gcode_G28");
  3193. log_machine_info();
  3194. }
  3195. #endif
  3196. // Wait for planner moves to finish!
  3197. stepper.synchronize();
  3198. // Cancel the active G29 session
  3199. #if ENABLED(PROBE_MANUALLY)
  3200. g29_in_progress = false;
  3201. #endif
  3202. // Disable the leveling matrix before homing
  3203. #if HAS_LEVELING
  3204. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3205. const bool ubl_state_at_entry = leveling_is_active();
  3206. #endif
  3207. set_bed_leveling_enabled(false);
  3208. #endif
  3209. #if ENABLED(CNC_WORKSPACE_PLANES)
  3210. workspace_plane = PLANE_XY;
  3211. #endif
  3212. // Always home with tool 0 active
  3213. #if HOTENDS > 1
  3214. const uint8_t old_tool_index = active_extruder;
  3215. tool_change(0, 0, true);
  3216. #endif
  3217. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  3218. extruder_duplication_enabled = false;
  3219. #endif
  3220. setup_for_endstop_or_probe_move();
  3221. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3222. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  3223. #endif
  3224. endstops.enable(true); // Enable endstops for next homing move
  3225. #if ENABLED(DELTA)
  3226. home_delta();
  3227. UNUSED(always_home_all);
  3228. #else // NOT DELTA
  3229. const bool homeX = always_home_all || parser.seen('X'),
  3230. homeY = always_home_all || parser.seen('Y'),
  3231. homeZ = always_home_all || parser.seen('Z'),
  3232. home_all = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  3233. set_destination_to_current();
  3234. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  3235. if (home_all || homeZ) {
  3236. HOMEAXIS(Z);
  3237. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3238. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  3239. #endif
  3240. }
  3241. #else
  3242. if (home_all || homeX || homeY) {
  3243. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  3244. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  3245. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3246. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3247. if (DEBUGGING(LEVELING))
  3248. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3249. #endif
  3250. do_blocking_move_to_z(destination[Z_AXIS]);
  3251. }
  3252. }
  3253. #endif
  3254. #if ENABLED(QUICK_HOME)
  3255. if (home_all || (homeX && homeY)) quick_home_xy();
  3256. #endif
  3257. #if ENABLED(HOME_Y_BEFORE_X)
  3258. // Home Y
  3259. if (home_all || homeY) {
  3260. HOMEAXIS(Y);
  3261. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3262. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3263. #endif
  3264. }
  3265. #endif
  3266. // Home X
  3267. if (home_all || homeX) {
  3268. #if ENABLED(DUAL_X_CARRIAGE)
  3269. // Always home the 2nd (right) extruder first
  3270. active_extruder = 1;
  3271. HOMEAXIS(X);
  3272. // Remember this extruder's position for later tool change
  3273. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3274. // Home the 1st (left) extruder
  3275. active_extruder = 0;
  3276. HOMEAXIS(X);
  3277. // Consider the active extruder to be parked
  3278. COPY(raised_parked_position, current_position);
  3279. delayed_move_time = 0;
  3280. active_extruder_parked = true;
  3281. #else
  3282. HOMEAXIS(X);
  3283. #endif
  3284. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3285. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3286. #endif
  3287. }
  3288. #if DISABLED(HOME_Y_BEFORE_X)
  3289. // Home Y
  3290. if (home_all || homeY) {
  3291. HOMEAXIS(Y);
  3292. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3293. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3294. #endif
  3295. }
  3296. #endif
  3297. // Home Z last if homing towards the bed
  3298. #if Z_HOME_DIR < 0
  3299. if (home_all || homeZ) {
  3300. #if ENABLED(Z_SAFE_HOMING)
  3301. home_z_safely();
  3302. #else
  3303. HOMEAXIS(Z);
  3304. #endif
  3305. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3306. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all || homeZ) > final", current_position);
  3307. #endif
  3308. } // home_all || homeZ
  3309. #endif // Z_HOME_DIR < 0
  3310. SYNC_PLAN_POSITION_KINEMATIC();
  3311. #endif // !DELTA (gcode_G28)
  3312. endstops.not_homing();
  3313. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3314. // move to a height where we can use the full xy-area
  3315. do_blocking_move_to_z(delta_clip_start_height);
  3316. #endif
  3317. #if ENABLED(AUTO_BED_LEVELING_UBL)
  3318. set_bed_leveling_enabled(ubl_state_at_entry);
  3319. #endif
  3320. clean_up_after_endstop_or_probe_move();
  3321. // Restore the active tool after homing
  3322. #if HOTENDS > 1
  3323. tool_change(old_tool_index, 0, true);
  3324. #endif
  3325. lcd_refresh();
  3326. report_current_position();
  3327. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3328. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3329. #endif
  3330. } // G28
  3331. void home_all_axes() { gcode_G28(true); }
  3332. #if HAS_PROBING_PROCEDURE
  3333. void out_of_range_error(const char* p_edge) {
  3334. SERIAL_PROTOCOLPGM("?Probe ");
  3335. serialprintPGM(p_edge);
  3336. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3337. }
  3338. #endif
  3339. #if ENABLED(MESH_BED_LEVELING) || ENABLED(PROBE_MANUALLY)
  3340. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3341. extern bool lcd_wait_for_move;
  3342. #endif
  3343. inline void _manual_goto_xy(const float &x, const float &y) {
  3344. const float old_feedrate_mm_s = feedrate_mm_s;
  3345. #if MANUAL_PROBE_HEIGHT > 0
  3346. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3347. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3348. line_to_current_position();
  3349. #endif
  3350. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3351. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3352. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3353. line_to_current_position();
  3354. #if MANUAL_PROBE_HEIGHT > 0
  3355. feedrate_mm_s = homing_feedrate(Z_AXIS);
  3356. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS); // just slightly over the bed
  3357. line_to_current_position();
  3358. #endif
  3359. feedrate_mm_s = old_feedrate_mm_s;
  3360. stepper.synchronize();
  3361. #if ENABLED(PROBE_MANUALLY) && ENABLED(LCD_BED_LEVELING)
  3362. lcd_wait_for_move = false;
  3363. #endif
  3364. }
  3365. #endif
  3366. #if ENABLED(MESH_BED_LEVELING)
  3367. // Save 130 bytes with non-duplication of PSTR
  3368. void echo_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3369. void mbl_mesh_report() {
  3370. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(GRID_MAX_POINTS_X) "," STRINGIFY(GRID_MAX_POINTS_Y));
  3371. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3372. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3373. print_2d_array(GRID_MAX_POINTS_X, GRID_MAX_POINTS_Y, 5,
  3374. [](const uint8_t ix, const uint8_t iy) { return mbl.z_values[ix][iy]; }
  3375. );
  3376. }
  3377. void mesh_probing_done() {
  3378. mbl.set_has_mesh(true);
  3379. home_all_axes();
  3380. set_bed_leveling_enabled(true);
  3381. #if ENABLED(MESH_G28_REST_ORIGIN)
  3382. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3383. set_destination_to_current();
  3384. line_to_destination(homing_feedrate(Z_AXIS));
  3385. stepper.synchronize();
  3386. #endif
  3387. }
  3388. /**
  3389. * G29: Mesh-based Z probe, probes a grid and produces a
  3390. * mesh to compensate for variable bed height
  3391. *
  3392. * Parameters With MESH_BED_LEVELING:
  3393. *
  3394. * S0 Produce a mesh report
  3395. * S1 Start probing mesh points
  3396. * S2 Probe the next mesh point
  3397. * S3 Xn Yn Zn.nn Manually modify a single point
  3398. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3399. * S5 Reset and disable mesh
  3400. *
  3401. * The S0 report the points as below
  3402. *
  3403. * +----> X-axis 1-n
  3404. * |
  3405. * |
  3406. * v Y-axis 1-n
  3407. *
  3408. */
  3409. inline void gcode_G29() {
  3410. static int mbl_probe_index = -1;
  3411. #if HAS_SOFTWARE_ENDSTOPS
  3412. static bool enable_soft_endstops;
  3413. #endif
  3414. const MeshLevelingState state = (MeshLevelingState)parser.byteval('S', (int8_t)MeshReport);
  3415. if (!WITHIN(state, 0, 5)) {
  3416. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3417. return;
  3418. }
  3419. int8_t px, py;
  3420. switch (state) {
  3421. case MeshReport:
  3422. if (leveling_is_valid()) {
  3423. SERIAL_PROTOCOLLNPAIR("State: ", leveling_is_active() ? MSG_ON : MSG_OFF);
  3424. mbl_mesh_report();
  3425. }
  3426. else
  3427. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3428. break;
  3429. case MeshStart:
  3430. mbl.reset();
  3431. mbl_probe_index = 0;
  3432. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3433. break;
  3434. case MeshNext:
  3435. if (mbl_probe_index < 0) {
  3436. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3437. return;
  3438. }
  3439. // For each G29 S2...
  3440. if (mbl_probe_index == 0) {
  3441. #if HAS_SOFTWARE_ENDSTOPS
  3442. // For the initial G29 S2 save software endstop state
  3443. enable_soft_endstops = soft_endstops_enabled;
  3444. #endif
  3445. }
  3446. else {
  3447. // For G29 S2 after adjusting Z.
  3448. mbl.set_zigzag_z(mbl_probe_index - 1, current_position[Z_AXIS]);
  3449. #if HAS_SOFTWARE_ENDSTOPS
  3450. soft_endstops_enabled = enable_soft_endstops;
  3451. #endif
  3452. }
  3453. // If there's another point to sample, move there with optional lift.
  3454. if (mbl_probe_index < GRID_MAX_POINTS) {
  3455. mbl.zigzag(mbl_probe_index, px, py);
  3456. _manual_goto_xy(mbl.index_to_xpos[px], mbl.index_to_ypos[py]);
  3457. #if HAS_SOFTWARE_ENDSTOPS
  3458. // Disable software endstops to allow manual adjustment
  3459. // If G29 is not completed, they will not be re-enabled
  3460. soft_endstops_enabled = false;
  3461. #endif
  3462. mbl_probe_index++;
  3463. }
  3464. else {
  3465. // One last "return to the bed" (as originally coded) at completion
  3466. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3467. line_to_current_position();
  3468. stepper.synchronize();
  3469. // After recording the last point, activate home and activate
  3470. mbl_probe_index = -1;
  3471. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3472. BUZZ(100, 659);
  3473. BUZZ(100, 698);
  3474. mesh_probing_done();
  3475. }
  3476. break;
  3477. case MeshSet:
  3478. if (parser.seenval('X')) {
  3479. px = parser.value_int() - 1;
  3480. if (!WITHIN(px, 0, GRID_MAX_POINTS_X - 1)) {
  3481. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(GRID_MAX_POINTS_X) ").");
  3482. return;
  3483. }
  3484. }
  3485. else {
  3486. SERIAL_CHAR('X'); echo_not_entered();
  3487. return;
  3488. }
  3489. if (parser.seenval('Y')) {
  3490. py = parser.value_int() - 1;
  3491. if (!WITHIN(py, 0, GRID_MAX_POINTS_Y - 1)) {
  3492. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(GRID_MAX_POINTS_Y) ").");
  3493. return;
  3494. }
  3495. }
  3496. else {
  3497. SERIAL_CHAR('Y'); echo_not_entered();
  3498. return;
  3499. }
  3500. if (parser.seenval('Z')) {
  3501. mbl.z_values[px][py] = parser.value_linear_units();
  3502. }
  3503. else {
  3504. SERIAL_CHAR('Z'); echo_not_entered();
  3505. return;
  3506. }
  3507. break;
  3508. case MeshSetZOffset:
  3509. if (parser.seenval('Z')) {
  3510. mbl.z_offset = parser.value_linear_units();
  3511. }
  3512. else {
  3513. SERIAL_CHAR('Z'); echo_not_entered();
  3514. return;
  3515. }
  3516. break;
  3517. case MeshReset:
  3518. reset_bed_level();
  3519. break;
  3520. } // switch(state)
  3521. report_current_position();
  3522. }
  3523. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3524. #if ABL_GRID
  3525. #if ENABLED(PROBE_Y_FIRST)
  3526. #define PR_OUTER_VAR xCount
  3527. #define PR_OUTER_END abl_grid_points_x
  3528. #define PR_INNER_VAR yCount
  3529. #define PR_INNER_END abl_grid_points_y
  3530. #else
  3531. #define PR_OUTER_VAR yCount
  3532. #define PR_OUTER_END abl_grid_points_y
  3533. #define PR_INNER_VAR xCount
  3534. #define PR_INNER_END abl_grid_points_x
  3535. #endif
  3536. #endif
  3537. /**
  3538. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3539. * Will fail if the printer has not been homed with G28.
  3540. *
  3541. * Enhanced G29 Auto Bed Leveling Probe Routine
  3542. *
  3543. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3544. * or alter the bed level data. Useful to check the topology
  3545. * after a first run of G29.
  3546. *
  3547. * J Jettison current bed leveling data
  3548. *
  3549. * V Set the verbose level (0-4). Example: "G29 V3"
  3550. *
  3551. * Parameters With LINEAR leveling only:
  3552. *
  3553. * P Set the size of the grid that will be probed (P x P points).
  3554. * Example: "G29 P4"
  3555. *
  3556. * X Set the X size of the grid that will be probed (X x Y points).
  3557. * Example: "G29 X7 Y5"
  3558. *
  3559. * Y Set the Y size of the grid that will be probed (X x Y points).
  3560. *
  3561. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3562. * This is useful for manual bed leveling and finding flaws in the bed (to
  3563. * assist with part placement).
  3564. * Not supported by non-linear delta printer bed leveling.
  3565. *
  3566. * Parameters With LINEAR and BILINEAR leveling only:
  3567. *
  3568. * S Set the XY travel speed between probe points (in units/min)
  3569. *
  3570. * F Set the Front limit of the probing grid
  3571. * B Set the Back limit of the probing grid
  3572. * L Set the Left limit of the probing grid
  3573. * R Set the Right limit of the probing grid
  3574. *
  3575. * Parameters with DEBUG_LEVELING_FEATURE only:
  3576. *
  3577. * C Make a totally fake grid with no actual probing.
  3578. * For use in testing when no probing is possible.
  3579. *
  3580. * Parameters with BILINEAR leveling only:
  3581. *
  3582. * Z Supply an additional Z probe offset
  3583. *
  3584. * Extra parameters with PROBE_MANUALLY:
  3585. *
  3586. * To do manual probing simply repeat G29 until the procedure is complete.
  3587. * The first G29 accepts parameters. 'G29 Q' for status, 'G29 A' to abort.
  3588. *
  3589. * Q Query leveling and G29 state
  3590. *
  3591. * A Abort current leveling procedure
  3592. *
  3593. * Extra parameters with BILINEAR only:
  3594. *
  3595. * W Write a mesh point. (If G29 is idle.)
  3596. * I X index for mesh point
  3597. * J Y index for mesh point
  3598. * X X for mesh point, overrides I
  3599. * Y Y for mesh point, overrides J
  3600. * Z Z for mesh point. Otherwise, raw current Z.
  3601. *
  3602. * Without PROBE_MANUALLY:
  3603. *
  3604. * E By default G29 will engage the Z probe, test the bed, then disengage.
  3605. * Include "E" to engage/disengage the Z probe for each sample.
  3606. * There's no extra effect if you have a fixed Z probe.
  3607. *
  3608. */
  3609. inline void gcode_G29() {
  3610. // G29 Q is also available if debugging
  3611. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3612. const bool query = parser.seen('Q');
  3613. const uint8_t old_debug_flags = marlin_debug_flags;
  3614. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3615. if (DEBUGGING(LEVELING)) {
  3616. DEBUG_POS(">>> gcode_G29", current_position);
  3617. log_machine_info();
  3618. }
  3619. marlin_debug_flags = old_debug_flags;
  3620. #if DISABLED(PROBE_MANUALLY)
  3621. if (query) return;
  3622. #endif
  3623. #endif
  3624. #if ENABLED(PROBE_MANUALLY)
  3625. const bool seenA = parser.seen('A'), seenQ = parser.seen('Q'), no_action = seenA || seenQ;
  3626. #endif
  3627. #if ENABLED(DEBUG_LEVELING_FEATURE) && DISABLED(PROBE_MANUALLY)
  3628. const bool faux = parser.boolval('C');
  3629. #elif ENABLED(PROBE_MANUALLY)
  3630. const bool faux = no_action;
  3631. #else
  3632. bool constexpr faux = false;
  3633. #endif
  3634. // Don't allow auto-leveling without homing first
  3635. if (axis_unhomed_error()) return;
  3636. // Define local vars 'static' for manual probing, 'auto' otherwise
  3637. #if ENABLED(PROBE_MANUALLY)
  3638. #define ABL_VAR static
  3639. #else
  3640. #define ABL_VAR
  3641. #endif
  3642. ABL_VAR int verbose_level;
  3643. ABL_VAR float xProbe, yProbe, measured_z;
  3644. ABL_VAR bool dryrun, abl_should_enable;
  3645. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3646. ABL_VAR int abl_probe_index;
  3647. #endif
  3648. #if HAS_SOFTWARE_ENDSTOPS && ENABLED(PROBE_MANUALLY)
  3649. ABL_VAR bool enable_soft_endstops = true;
  3650. #endif
  3651. #if ABL_GRID
  3652. #if ENABLED(PROBE_MANUALLY)
  3653. ABL_VAR uint8_t PR_OUTER_VAR;
  3654. ABL_VAR int8_t PR_INNER_VAR;
  3655. #endif
  3656. ABL_VAR int left_probe_bed_position, right_probe_bed_position, front_probe_bed_position, back_probe_bed_position;
  3657. ABL_VAR float xGridSpacing = 0, yGridSpacing = 0;
  3658. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3659. ABL_VAR uint8_t abl_grid_points_x = GRID_MAX_POINTS_X,
  3660. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3661. ABL_VAR bool do_topography_map;
  3662. #else // Bilinear
  3663. uint8_t constexpr abl_grid_points_x = GRID_MAX_POINTS_X,
  3664. abl_grid_points_y = GRID_MAX_POINTS_Y;
  3665. #endif
  3666. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(PROBE_MANUALLY)
  3667. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3668. ABL_VAR int abl2;
  3669. #else // Bilinear
  3670. int constexpr abl2 = GRID_MAX_POINTS;
  3671. #endif
  3672. #endif
  3673. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3674. ABL_VAR float zoffset;
  3675. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3676. ABL_VAR int indexIntoAB[GRID_MAX_POINTS_X][GRID_MAX_POINTS_Y];
  3677. ABL_VAR float eqnAMatrix[GRID_MAX_POINTS * 3], // "A" matrix of the linear system of equations
  3678. eqnBVector[GRID_MAX_POINTS], // "B" vector of Z points
  3679. mean;
  3680. #endif
  3681. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3682. int constexpr abl2 = 3;
  3683. // Probe at 3 arbitrary points
  3684. ABL_VAR vector_3 points[3] = {
  3685. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3686. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3687. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3688. };
  3689. #endif // AUTO_BED_LEVELING_3POINT
  3690. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3691. struct linear_fit_data lsf_results;
  3692. incremental_LSF_reset(&lsf_results);
  3693. #endif
  3694. /**
  3695. * On the initial G29 fetch command parameters.
  3696. */
  3697. if (!g29_in_progress) {
  3698. #if ENABLED(PROBE_MANUALLY) || ENABLED(AUTO_BED_LEVELING_LINEAR)
  3699. abl_probe_index = -1;
  3700. #endif
  3701. abl_should_enable = leveling_is_active();
  3702. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3703. if (parser.seen('W')) {
  3704. if (!leveling_is_valid()) {
  3705. SERIAL_ERROR_START();
  3706. SERIAL_ERRORLNPGM("No bilinear grid");
  3707. return;
  3708. }
  3709. const float z = parser.floatval('Z', RAW_CURRENT_POSITION(Z));
  3710. if (!WITHIN(z, -10, 10)) {
  3711. SERIAL_ERROR_START();
  3712. SERIAL_ERRORLNPGM("Bad Z value");
  3713. return;
  3714. }
  3715. const float x = parser.floatval('X', NAN),
  3716. y = parser.floatval('Y', NAN);
  3717. int8_t i = parser.byteval('I', -1),
  3718. j = parser.byteval('J', -1);
  3719. if (!isnan(x) && !isnan(y)) {
  3720. // Get nearest i / j from x / y
  3721. i = (x - LOGICAL_X_POSITION(bilinear_start[X_AXIS]) + 0.5 * xGridSpacing) / xGridSpacing;
  3722. j = (y - LOGICAL_Y_POSITION(bilinear_start[Y_AXIS]) + 0.5 * yGridSpacing) / yGridSpacing;
  3723. i = constrain(i, 0, GRID_MAX_POINTS_X - 1);
  3724. j = constrain(j, 0, GRID_MAX_POINTS_Y - 1);
  3725. }
  3726. if (WITHIN(i, 0, GRID_MAX_POINTS_X - 1) && WITHIN(j, 0, GRID_MAX_POINTS_Y)) {
  3727. set_bed_leveling_enabled(false);
  3728. z_values[i][j] = z;
  3729. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3730. bed_level_virt_interpolate();
  3731. #endif
  3732. set_bed_leveling_enabled(abl_should_enable);
  3733. }
  3734. return;
  3735. } // parser.seen('W')
  3736. #endif
  3737. #if HAS_LEVELING
  3738. // Jettison bed leveling data
  3739. if (parser.seen('J')) {
  3740. reset_bed_level();
  3741. return;
  3742. }
  3743. #endif
  3744. verbose_level = parser.intval('V');
  3745. if (!WITHIN(verbose_level, 0, 4)) {
  3746. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  3747. return;
  3748. }
  3749. dryrun = parser.boolval('D')
  3750. #if ENABLED(PROBE_MANUALLY)
  3751. || no_action
  3752. #endif
  3753. ;
  3754. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3755. do_topography_map = verbose_level > 2 || parser.boolval('T');
  3756. // X and Y specify points in each direction, overriding the default
  3757. // These values may be saved with the completed mesh
  3758. abl_grid_points_x = parser.intval('X', GRID_MAX_POINTS_X);
  3759. abl_grid_points_y = parser.intval('Y', GRID_MAX_POINTS_Y);
  3760. if (parser.seenval('P')) abl_grid_points_x = abl_grid_points_y = parser.value_int();
  3761. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3762. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3763. return;
  3764. }
  3765. abl2 = abl_grid_points_x * abl_grid_points_y;
  3766. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3767. zoffset = parser.linearval('Z');
  3768. #endif
  3769. #if ABL_GRID
  3770. xy_probe_feedrate_mm_s = MMM_TO_MMS(parser.linearval('S', XY_PROBE_SPEED));
  3771. left_probe_bed_position = (int)parser.linearval('L', LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION));
  3772. right_probe_bed_position = (int)parser.linearval('R', LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION));
  3773. front_probe_bed_position = (int)parser.linearval('F', LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION));
  3774. back_probe_bed_position = (int)parser.linearval('B', LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION));
  3775. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3776. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3777. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3778. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3779. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3780. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3781. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3782. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3783. if (left_out || right_out || front_out || back_out) {
  3784. if (left_out) {
  3785. out_of_range_error(PSTR("(L)eft"));
  3786. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3787. }
  3788. if (right_out) {
  3789. out_of_range_error(PSTR("(R)ight"));
  3790. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3791. }
  3792. if (front_out) {
  3793. out_of_range_error(PSTR("(F)ront"));
  3794. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3795. }
  3796. if (back_out) {
  3797. out_of_range_error(PSTR("(B)ack"));
  3798. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3799. }
  3800. return;
  3801. }
  3802. // probe at the points of a lattice grid
  3803. xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1);
  3804. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3805. #endif // ABL_GRID
  3806. if (verbose_level > 0) {
  3807. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3808. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3809. }
  3810. stepper.synchronize();
  3811. // Disable auto bed leveling during G29
  3812. planner.abl_enabled = false;
  3813. if (!dryrun) {
  3814. // Re-orient the current position without leveling
  3815. // based on where the steppers are positioned.
  3816. set_current_from_steppers_for_axis(ALL_AXES);
  3817. // Sync the planner to where the steppers stopped
  3818. SYNC_PLAN_POSITION_KINEMATIC();
  3819. }
  3820. if (!faux) setup_for_endstop_or_probe_move();
  3821. //xProbe = yProbe = measured_z = 0;
  3822. #if HAS_BED_PROBE
  3823. // Deploy the probe. Probe will raise if needed.
  3824. if (DEPLOY_PROBE()) {
  3825. planner.abl_enabled = abl_should_enable;
  3826. return;
  3827. }
  3828. #endif
  3829. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3830. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3831. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3832. || left_probe_bed_position != LOGICAL_X_POSITION(bilinear_start[X_AXIS])
  3833. || front_probe_bed_position != LOGICAL_Y_POSITION(bilinear_start[Y_AXIS])
  3834. ) {
  3835. if (dryrun) {
  3836. // Before reset bed level, re-enable to correct the position
  3837. planner.abl_enabled = abl_should_enable;
  3838. }
  3839. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3840. reset_bed_level();
  3841. // Initialize a grid with the given dimensions
  3842. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3843. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3844. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3845. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3846. // Can't re-enable (on error) until the new grid is written
  3847. abl_should_enable = false;
  3848. }
  3849. #endif // AUTO_BED_LEVELING_BILINEAR
  3850. #if ENABLED(AUTO_BED_LEVELING_3POINT)
  3851. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3852. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3853. #endif
  3854. // Probe at 3 arbitrary points
  3855. points[0].z = points[1].z = points[2].z = 0;
  3856. #endif // AUTO_BED_LEVELING_3POINT
  3857. } // !g29_in_progress
  3858. #if ENABLED(PROBE_MANUALLY)
  3859. // For manual probing, get the next index to probe now.
  3860. // On the first probe this will be incremented to 0.
  3861. if (!no_action) {
  3862. ++abl_probe_index;
  3863. g29_in_progress = true;
  3864. }
  3865. // Abort current G29 procedure, go back to idle state
  3866. if (seenA && g29_in_progress) {
  3867. SERIAL_PROTOCOLLNPGM("Manual G29 aborted");
  3868. #if HAS_SOFTWARE_ENDSTOPS
  3869. soft_endstops_enabled = enable_soft_endstops;
  3870. #endif
  3871. planner.abl_enabled = abl_should_enable;
  3872. g29_in_progress = false;
  3873. #if ENABLED(LCD_BED_LEVELING)
  3874. lcd_wait_for_move = false;
  3875. #endif
  3876. }
  3877. // Query G29 status
  3878. if (verbose_level || seenQ) {
  3879. SERIAL_PROTOCOLPGM("Manual G29 ");
  3880. if (g29_in_progress) {
  3881. SERIAL_PROTOCOLPAIR("point ", min(abl_probe_index + 1, abl2));
  3882. SERIAL_PROTOCOLLNPAIR(" of ", abl2);
  3883. }
  3884. else
  3885. SERIAL_PROTOCOLLNPGM("idle");
  3886. }
  3887. if (no_action) return;
  3888. if (abl_probe_index == 0) {
  3889. // For the initial G29 save software endstop state
  3890. #if HAS_SOFTWARE_ENDSTOPS
  3891. enable_soft_endstops = soft_endstops_enabled;
  3892. #endif
  3893. }
  3894. else {
  3895. // For G29 after adjusting Z.
  3896. // Save the previous Z before going to the next point
  3897. measured_z = current_position[Z_AXIS];
  3898. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3899. mean += measured_z;
  3900. eqnBVector[abl_probe_index] = measured_z;
  3901. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  3902. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  3903. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  3904. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  3905. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3906. z_values[xCount][yCount] = measured_z + zoffset;
  3907. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3908. if (DEBUGGING(LEVELING)) {
  3909. SERIAL_PROTOCOLPAIR("Save X", xCount);
  3910. SERIAL_PROTOCOLPAIR(" Y", yCount);
  3911. SERIAL_PROTOCOLLNPAIR(" Z", measured_z + zoffset);
  3912. }
  3913. #endif
  3914. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3915. points[abl_probe_index].z = measured_z;
  3916. #endif
  3917. }
  3918. //
  3919. // If there's another point to sample, move there with optional lift.
  3920. //
  3921. #if ABL_GRID
  3922. // Skip any unreachable points
  3923. while (abl_probe_index < abl2) {
  3924. // Set xCount, yCount based on abl_probe_index, with zig-zag
  3925. PR_OUTER_VAR = abl_probe_index / PR_INNER_END;
  3926. PR_INNER_VAR = abl_probe_index - (PR_OUTER_VAR * PR_INNER_END);
  3927. // Probe in reverse order for every other row/column
  3928. bool zig = (PR_OUTER_VAR & 1); // != ((PR_OUTER_END) & 1);
  3929. if (zig) PR_INNER_VAR = (PR_INNER_END - 1) - PR_INNER_VAR;
  3930. const float xBase = xCount * xGridSpacing + left_probe_bed_position,
  3931. yBase = yCount * yGridSpacing + front_probe_bed_position;
  3932. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  3933. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  3934. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3935. indexIntoAB[xCount][yCount] = abl_probe_index;
  3936. #endif
  3937. // Keep looping till a reachable point is found
  3938. if (position_is_reachable_xy(xProbe, yProbe)) break;
  3939. ++abl_probe_index;
  3940. }
  3941. // Is there a next point to move to?
  3942. if (abl_probe_index < abl2) {
  3943. _manual_goto_xy(xProbe, yProbe); // Can be used here too!
  3944. #if HAS_SOFTWARE_ENDSTOPS
  3945. // Disable software endstops to allow manual adjustment
  3946. // If G29 is not completed, they will not be re-enabled
  3947. soft_endstops_enabled = false;
  3948. #endif
  3949. return;
  3950. }
  3951. else {
  3952. // Leveling done! Fall through to G29 finishing code below
  3953. SERIAL_PROTOCOLLNPGM("Grid probing done.");
  3954. // Re-enable software endstops, if needed
  3955. #if HAS_SOFTWARE_ENDSTOPS
  3956. soft_endstops_enabled = enable_soft_endstops;
  3957. #endif
  3958. }
  3959. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3960. // Probe at 3 arbitrary points
  3961. if (abl_probe_index < 3) {
  3962. xProbe = LOGICAL_X_POSITION(points[abl_probe_index].x);
  3963. yProbe = LOGICAL_Y_POSITION(points[abl_probe_index].y);
  3964. #if HAS_SOFTWARE_ENDSTOPS
  3965. // Disable software endstops to allow manual adjustment
  3966. // If G29 is not completed, they will not be re-enabled
  3967. soft_endstops_enabled = false;
  3968. #endif
  3969. return;
  3970. }
  3971. else {
  3972. SERIAL_PROTOCOLLNPGM("3-point probing done.");
  3973. // Re-enable software endstops, if needed
  3974. #if HAS_SOFTWARE_ENDSTOPS
  3975. soft_endstops_enabled = enable_soft_endstops;
  3976. #endif
  3977. if (!dryrun) {
  3978. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3979. if (planeNormal.z < 0) {
  3980. planeNormal.x *= -1;
  3981. planeNormal.y *= -1;
  3982. planeNormal.z *= -1;
  3983. }
  3984. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3985. // Can't re-enable (on error) until the new grid is written
  3986. abl_should_enable = false;
  3987. }
  3988. }
  3989. #endif // AUTO_BED_LEVELING_3POINT
  3990. #else // !PROBE_MANUALLY
  3991. const bool stow_probe_after_each = parser.boolval('E');
  3992. #if ABL_GRID
  3993. bool zig = PR_OUTER_END & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3994. // Outer loop is Y with PROBE_Y_FIRST disabled
  3995. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_END; PR_OUTER_VAR++) {
  3996. int8_t inStart, inStop, inInc;
  3997. if (zig) { // away from origin
  3998. inStart = 0;
  3999. inStop = PR_INNER_END;
  4000. inInc = 1;
  4001. }
  4002. else { // towards origin
  4003. inStart = PR_INNER_END - 1;
  4004. inStop = -1;
  4005. inInc = -1;
  4006. }
  4007. zig ^= true; // zag
  4008. // Inner loop is Y with PROBE_Y_FIRST enabled
  4009. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  4010. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  4011. yBase = front_probe_bed_position + yGridSpacing * yCount;
  4012. xProbe = FLOOR(xBase + (xBase < 0 ? 0 : 0.5));
  4013. yProbe = FLOOR(yBase + (yBase < 0 ? 0 : 0.5));
  4014. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4015. indexIntoAB[xCount][yCount] = ++abl_probe_index; // 0...
  4016. #endif
  4017. #if IS_KINEMATIC
  4018. // Avoid probing outside the round or hexagonal area
  4019. if (!position_is_reachable_by_probe_xy(xProbe, yProbe)) continue;
  4020. #endif
  4021. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4022. if (isnan(measured_z)) {
  4023. planner.abl_enabled = abl_should_enable;
  4024. return;
  4025. }
  4026. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  4027. mean += measured_z;
  4028. eqnBVector[abl_probe_index] = measured_z;
  4029. eqnAMatrix[abl_probe_index + 0 * abl2] = xProbe;
  4030. eqnAMatrix[abl_probe_index + 1 * abl2] = yProbe;
  4031. eqnAMatrix[abl_probe_index + 2 * abl2] = 1;
  4032. incremental_LSF(&lsf_results, xProbe, yProbe, measured_z);
  4033. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4034. z_values[xCount][yCount] = measured_z + zoffset;
  4035. #endif
  4036. abl_should_enable = false;
  4037. idle();
  4038. } // inner
  4039. } // outer
  4040. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  4041. // Probe at 3 arbitrary points
  4042. for (uint8_t i = 0; i < 3; ++i) {
  4043. // Retain the last probe position
  4044. xProbe = LOGICAL_X_POSITION(points[i].x);
  4045. yProbe = LOGICAL_Y_POSITION(points[i].y);
  4046. measured_z = faux ? 0.001 * random(-100, 101) : probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  4047. if (isnan(measured_z)) {
  4048. planner.abl_enabled = abl_should_enable;
  4049. return;
  4050. }
  4051. points[i].z = measured_z;
  4052. }
  4053. if (!dryrun) {
  4054. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  4055. if (planeNormal.z < 0) {
  4056. planeNormal.x *= -1;
  4057. planeNormal.y *= -1;
  4058. planeNormal.z *= -1;
  4059. }
  4060. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  4061. // Can't re-enable (on error) until the new grid is written
  4062. abl_should_enable = false;
  4063. }
  4064. #endif // AUTO_BED_LEVELING_3POINT
  4065. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  4066. if (STOW_PROBE()) {
  4067. planner.abl_enabled = abl_should_enable;
  4068. return;
  4069. }
  4070. #endif // !PROBE_MANUALLY
  4071. //
  4072. // G29 Finishing Code
  4073. //
  4074. // Unless this is a dry run, auto bed leveling will
  4075. // definitely be enabled after this point.
  4076. //
  4077. // If code above wants to continue leveling, it should
  4078. // return or loop before this point.
  4079. //
  4080. // Restore state after probing
  4081. if (!faux) clean_up_after_endstop_or_probe_move();
  4082. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4083. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  4084. #endif
  4085. #if ENABLED(PROBE_MANUALLY)
  4086. g29_in_progress = false;
  4087. #if ENABLED(LCD_BED_LEVELING)
  4088. lcd_wait_for_move = false;
  4089. #endif
  4090. #endif
  4091. // Calculate leveling, print reports, correct the position
  4092. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4093. if (!dryrun) extrapolate_unprobed_bed_level();
  4094. print_bilinear_leveling_grid();
  4095. refresh_bed_level();
  4096. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  4097. bed_level_virt_print();
  4098. #endif
  4099. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  4100. // For LINEAR leveling calculate matrix, print reports, correct the position
  4101. /**
  4102. * solve the plane equation ax + by + d = z
  4103. * A is the matrix with rows [x y 1] for all the probed points
  4104. * B is the vector of the Z positions
  4105. * the normal vector to the plane is formed by the coefficients of the
  4106. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  4107. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  4108. */
  4109. float plane_equation_coefficients[3];
  4110. finish_incremental_LSF(&lsf_results);
  4111. plane_equation_coefficients[0] = -lsf_results.A; // We should be able to eliminate the '-' on these three lines and down below
  4112. plane_equation_coefficients[1] = -lsf_results.B; // but that is not yet tested.
  4113. plane_equation_coefficients[2] = -lsf_results.D;
  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) // We can eliminate the '-' here and up above
  4133. );
  4134. // Show the Topography map if enabled
  4135. if (do_topography_map) {
  4136. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  4137. " +--- BACK --+\n"
  4138. " | |\n"
  4139. " L | (+) | R\n"
  4140. " E | | I\n"
  4141. " F | (-) N (+) | G\n"
  4142. " T | | H\n"
  4143. " | (-) | T\n"
  4144. " | |\n"
  4145. " O-- FRONT --+\n"
  4146. " (0,0)");
  4147. float min_diff = 999;
  4148. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4149. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4150. int ind = indexIntoAB[xx][yy];
  4151. float diff = eqnBVector[ind] - mean,
  4152. x_tmp = eqnAMatrix[ind + 0 * abl2],
  4153. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4154. z_tmp = 0;
  4155. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4156. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  4157. if (diff >= 0.0)
  4158. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  4159. else
  4160. SERIAL_PROTOCOLCHAR(' ');
  4161. SERIAL_PROTOCOL_F(diff, 5);
  4162. } // xx
  4163. SERIAL_EOL();
  4164. } // yy
  4165. SERIAL_EOL();
  4166. if (verbose_level > 3) {
  4167. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  4168. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  4169. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  4170. int ind = indexIntoAB[xx][yy];
  4171. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  4172. y_tmp = eqnAMatrix[ind + 1 * abl2],
  4173. z_tmp = 0;
  4174. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  4175. float diff = eqnBVector[ind] - z_tmp - min_diff;
  4176. if (diff >= 0.0)
  4177. SERIAL_PROTOCOLPGM(" +");
  4178. // Include + for column alignment
  4179. else
  4180. SERIAL_PROTOCOLCHAR(' ');
  4181. SERIAL_PROTOCOL_F(diff, 5);
  4182. } // xx
  4183. SERIAL_EOL();
  4184. } // yy
  4185. SERIAL_EOL();
  4186. }
  4187. } //do_topography_map
  4188. #endif // AUTO_BED_LEVELING_LINEAR
  4189. #if ABL_PLANAR
  4190. // For LINEAR and 3POINT leveling correct the current position
  4191. if (verbose_level > 0)
  4192. planner.bed_level_matrix.debug(PSTR("\n\nBed Level Correction Matrix:"));
  4193. if (!dryrun) {
  4194. //
  4195. // Correct the current XYZ position based on the tilted plane.
  4196. //
  4197. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4198. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  4199. #endif
  4200. float converted[XYZ];
  4201. COPY(converted, current_position);
  4202. planner.abl_enabled = true;
  4203. planner.unapply_leveling(converted); // use conversion machinery
  4204. planner.abl_enabled = false;
  4205. // Use the last measured distance to the bed, if possible
  4206. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  4207. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  4208. ) {
  4209. const float simple_z = current_position[Z_AXIS] - measured_z;
  4210. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4211. if (DEBUGGING(LEVELING)) {
  4212. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  4213. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  4214. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  4215. }
  4216. #endif
  4217. converted[Z_AXIS] = simple_z;
  4218. }
  4219. // The rotated XY and corrected Z are now current_position
  4220. COPY(current_position, converted);
  4221. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4222. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  4223. #endif
  4224. }
  4225. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4226. if (!dryrun) {
  4227. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4228. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  4229. #endif
  4230. // Unapply the offset because it is going to be immediately applied
  4231. // and cause compensation movement in Z
  4232. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  4233. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4234. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  4235. #endif
  4236. }
  4237. #endif // ABL_PLANAR
  4238. #ifdef Z_PROBE_END_SCRIPT
  4239. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4240. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  4241. #endif
  4242. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  4243. stepper.synchronize();
  4244. #endif
  4245. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4246. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  4247. #endif
  4248. report_current_position();
  4249. KEEPALIVE_STATE(IN_HANDLER);
  4250. // Auto Bed Leveling is complete! Enable if possible.
  4251. planner.abl_enabled = dryrun ? abl_should_enable : true;
  4252. if (planner.abl_enabled)
  4253. SYNC_PLAN_POSITION_KINEMATIC();
  4254. }
  4255. #endif // HAS_ABL && !AUTO_BED_LEVELING_UBL
  4256. #if HAS_BED_PROBE
  4257. /**
  4258. * G30: Do a single Z probe at the current XY
  4259. *
  4260. * Parameters:
  4261. *
  4262. * X Probe X position (default current X)
  4263. * Y Probe Y position (default current Y)
  4264. * S0 Leave the probe deployed
  4265. */
  4266. inline void gcode_G30() {
  4267. const float xpos = parser.linearval('X', current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER),
  4268. ypos = parser.linearval('Y', current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER);
  4269. if (!position_is_reachable_by_probe_xy(xpos, ypos)) return;
  4270. // Disable leveling so the planner won't mess with us
  4271. #if HAS_LEVELING
  4272. set_bed_leveling_enabled(false);
  4273. #endif
  4274. setup_for_endstop_or_probe_move();
  4275. const float measured_z = probe_pt(xpos, ypos, parser.boolval('S', true), 1);
  4276. if (!isnan(measured_z)) {
  4277. SERIAL_PROTOCOLPAIR("Bed X: ", FIXFLOAT(xpos));
  4278. SERIAL_PROTOCOLPAIR(" Y: ", FIXFLOAT(ypos));
  4279. SERIAL_PROTOCOLLNPAIR(" Z: ", FIXFLOAT(measured_z));
  4280. }
  4281. clean_up_after_endstop_or_probe_move();
  4282. report_current_position();
  4283. }
  4284. #if ENABLED(Z_PROBE_SLED)
  4285. /**
  4286. * G31: Deploy the Z probe
  4287. */
  4288. inline void gcode_G31() { DEPLOY_PROBE(); }
  4289. /**
  4290. * G32: Stow the Z probe
  4291. */
  4292. inline void gcode_G32() { STOW_PROBE(); }
  4293. #endif // Z_PROBE_SLED
  4294. #endif // HAS_BED_PROBE
  4295. #if PROBE_SELECTED
  4296. #if ENABLED(DELTA_AUTO_CALIBRATION)
  4297. /**
  4298. * G33 - Delta '1-4-7-point' Auto-Calibration
  4299. * Calibrate height, endstops, delta radius, and tower angles.
  4300. *
  4301. * Parameters:
  4302. *
  4303. * Pn Number of probe points:
  4304. *
  4305. * P1 Probe center and set height only.
  4306. * P2 Probe center and towers. Set height, endstops, and delta radius.
  4307. * P3 Probe all positions: center, towers and opposite towers. Set all.
  4308. * P4-P7 Probe all positions at different locations and average them.
  4309. *
  4310. * T0 Don't calibrate tower angle corrections
  4311. *
  4312. * Cn.nn Calibration precision; when omitted calibrates to maximum precision
  4313. *
  4314. * Fn Force to run at least n iterations and takes the best result
  4315. *
  4316. * Vn Verbose level:
  4317. *
  4318. * V0 Dry-run mode. Report settings and probe results. No calibration.
  4319. * V1 Report settings
  4320. * V2 Report settings and probe results
  4321. *
  4322. * E Engage the probe for each point
  4323. */
  4324. void print_signed_float(const char * const prefix, const float &f) {
  4325. SERIAL_PROTOCOLPGM(" ");
  4326. serialprintPGM(prefix);
  4327. SERIAL_PROTOCOLCHAR(':');
  4328. if (f >= 0) SERIAL_CHAR('+');
  4329. SERIAL_PROTOCOL_F(f, 2);
  4330. }
  4331. inline void print_G33_settings(const bool end_stops, const bool tower_angles){ // TODO echo these to LCD ???
  4332. SERIAL_PROTOCOLPAIR(".Height:", DELTA_HEIGHT + home_offset[Z_AXIS]);
  4333. if (end_stops) {
  4334. print_signed_float(PSTR(" Ex"), endstop_adj[A_AXIS]);
  4335. print_signed_float(PSTR("Ey"), endstop_adj[B_AXIS]);
  4336. print_signed_float(PSTR("Ez"), endstop_adj[C_AXIS]);
  4337. SERIAL_PROTOCOLPAIR(" Radius:", delta_radius);
  4338. }
  4339. SERIAL_EOL();
  4340. if (tower_angles) {
  4341. SERIAL_PROTOCOLPGM(".Tower angle : ");
  4342. print_signed_float(PSTR("Tx"), delta_tower_angle_trim[A_AXIS]);
  4343. print_signed_float(PSTR("Ty"), delta_tower_angle_trim[B_AXIS]);
  4344. SERIAL_PROTOCOLLNPGM(" Tz:+0.00");
  4345. }
  4346. }
  4347. inline void gcode_G33() {
  4348. const int8_t probe_points = parser.intval('P', DELTA_CALIBRATION_DEFAULT_POINTS);
  4349. if (!WITHIN(probe_points, 1, 7)) {
  4350. SERIAL_PROTOCOLLNPGM("?(P)oints is implausible (1-7).");
  4351. return;
  4352. }
  4353. const int8_t verbose_level = parser.byteval('V', 1);
  4354. if (!WITHIN(verbose_level, 0, 2)) {
  4355. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-2).");
  4356. return;
  4357. }
  4358. const float calibration_precision = parser.floatval('C');
  4359. if (calibration_precision < 0) {
  4360. SERIAL_PROTOCOLLNPGM("?(C)alibration precision is implausible (>0).");
  4361. return;
  4362. }
  4363. const int8_t force_iterations = parser.intval('F', 0);
  4364. if (!WITHIN(force_iterations, 0, 30)) {
  4365. SERIAL_PROTOCOLLNPGM("?(F)orce iteration is implausible (0-30).");
  4366. return;
  4367. }
  4368. const bool towers_set = parser.boolval('T', true),
  4369. stow_after_each = parser.boolval('E'),
  4370. _1p_calibration = probe_points == 1,
  4371. _4p_calibration = probe_points == 2,
  4372. _4p_towers_points = _4p_calibration && towers_set,
  4373. _4p_opposite_points = _4p_calibration && !towers_set,
  4374. _7p_calibration = probe_points >= 3,
  4375. _7p_half_circle = probe_points == 3,
  4376. _7p_double_circle = probe_points == 5,
  4377. _7p_triple_circle = probe_points == 6,
  4378. _7p_quadruple_circle = probe_points == 7,
  4379. _7p_multi_circle = _7p_double_circle || _7p_triple_circle || _7p_quadruple_circle,
  4380. _7p_intermed_points = _7p_calibration && !_7p_half_circle;
  4381. const static char save_message[] PROGMEM = "Save with M500 and/or copy to Configuration.h";
  4382. const float dx = (X_PROBE_OFFSET_FROM_EXTRUDER),
  4383. dy = (Y_PROBE_OFFSET_FROM_EXTRUDER);
  4384. int8_t iterations = 0;
  4385. float test_precision,
  4386. zero_std_dev = (verbose_level ? 999.0 : 0.0), // 0.0 in dry-run mode : forced end
  4387. zero_std_dev_old = zero_std_dev,
  4388. zero_std_dev_min = zero_std_dev,
  4389. e_old[XYZ] = {
  4390. endstop_adj[A_AXIS],
  4391. endstop_adj[B_AXIS],
  4392. endstop_adj[C_AXIS]
  4393. },
  4394. dr_old = delta_radius,
  4395. zh_old = home_offset[Z_AXIS],
  4396. alpha_old = delta_tower_angle_trim[A_AXIS],
  4397. beta_old = delta_tower_angle_trim[B_AXIS];
  4398. if (!_1p_calibration) { // test if the outer radius is reachable
  4399. const float circles = (_7p_quadruple_circle ? 1.5 :
  4400. _7p_triple_circle ? 1.0 :
  4401. _7p_double_circle ? 0.5 : 0),
  4402. r = (1 + circles * 0.1) * delta_calibration_radius;
  4403. for (uint8_t axis = 1; axis < 13; ++axis) {
  4404. const float a = RADIANS(180 + 30 * axis);
  4405. if (!position_is_reachable_xy(cos(a) * r, sin(a) * r)) {
  4406. SERIAL_PROTOCOLLNPGM("?(M665 B)ed radius is implausible.");
  4407. return;
  4408. }
  4409. }
  4410. }
  4411. SERIAL_PROTOCOLLNPGM("G33 Auto Calibrate");
  4412. stepper.synchronize();
  4413. #if HAS_LEVELING
  4414. reset_bed_level(); // After calibration bed-level data is no longer valid
  4415. #endif
  4416. #if HOTENDS > 1
  4417. const uint8_t old_tool_index = active_extruder;
  4418. tool_change(0, 0, true);
  4419. #endif
  4420. setup_for_endstop_or_probe_move();
  4421. DEPLOY_PROBE();
  4422. endstops.enable(true);
  4423. home_delta();
  4424. endstops.not_homing();
  4425. // print settings
  4426. const char *checkingac = PSTR("Checking... AC"); // TODO: Make translatable string
  4427. serialprintPGM(checkingac);
  4428. if (verbose_level == 0) SERIAL_PROTOCOLPGM(" (DRY-RUN)");
  4429. SERIAL_EOL();
  4430. lcd_setstatusPGM(checkingac);
  4431. print_G33_settings(!_1p_calibration, _7p_calibration && towers_set);
  4432. #if DISABLED(PROBE_MANUALLY)
  4433. home_offset[Z_AXIS] -= probe_pt(dx, dy, stow_after_each, 1, false); // 1st probe to set height
  4434. #endif
  4435. do {
  4436. float z_at_pt[13] = { 0.0 };
  4437. test_precision = zero_std_dev_old != 999.0 ? (zero_std_dev + zero_std_dev_old) / 2 : zero_std_dev;
  4438. iterations++;
  4439. // Probe the points
  4440. if (!_7p_half_circle && !_7p_triple_circle) { // probe the center
  4441. #if ENABLED(PROBE_MANUALLY)
  4442. z_at_pt[0] += lcd_probe_pt(0, 0);
  4443. #else
  4444. z_at_pt[0] += probe_pt(dx, dy, stow_after_each, 1, false);
  4445. #endif
  4446. }
  4447. if (_7p_calibration) { // probe extra center points
  4448. for (int8_t axis = _7p_multi_circle ? 11 : 9; axis > 0; axis -= _7p_multi_circle ? 2 : 4) {
  4449. const float a = RADIANS(180 + 30 * axis), r = delta_calibration_radius * 0.1;
  4450. #if ENABLED(PROBE_MANUALLY)
  4451. z_at_pt[0] += lcd_probe_pt(cos(a) * r, sin(a) * r);
  4452. #else
  4453. z_at_pt[0] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1, false);
  4454. #endif
  4455. }
  4456. z_at_pt[0] /= float(_7p_double_circle ? 7 : probe_points);
  4457. }
  4458. if (!_1p_calibration) { // probe the radius
  4459. bool zig_zag = true;
  4460. const uint8_t start = _4p_opposite_points ? 3 : 1,
  4461. step = _4p_calibration ? 4 : _7p_half_circle ? 2 : 1;
  4462. for (uint8_t axis = start; axis < 13; axis += step) {
  4463. const float zigadd = (zig_zag ? 0.5 : 0.0),
  4464. offset_circles = _7p_quadruple_circle ? zigadd + 1.0 :
  4465. _7p_triple_circle ? zigadd + 0.5 :
  4466. _7p_double_circle ? zigadd : 0;
  4467. for (float circles = -offset_circles ; circles <= offset_circles; circles++) {
  4468. const float a = RADIANS(180 + 30 * axis),
  4469. r = delta_calibration_radius * (1 + circles * (zig_zag ? 0.1 : -0.1));
  4470. #if ENABLED(PROBE_MANUALLY)
  4471. z_at_pt[axis] += lcd_probe_pt(cos(a) * r, sin(a) * r);
  4472. #else
  4473. z_at_pt[axis] += probe_pt(cos(a) * r + dx, sin(a) * r + dy, stow_after_each, 1, false);
  4474. #endif
  4475. }
  4476. zig_zag = !zig_zag;
  4477. z_at_pt[axis] /= (2 * offset_circles + 1);
  4478. }
  4479. }
  4480. if (_7p_intermed_points) // average intermediates to tower and opposites
  4481. for (uint8_t axis = 1; axis < 13; axis += 2)
  4482. z_at_pt[axis] = (z_at_pt[axis] + (z_at_pt[axis + 1] + z_at_pt[(axis + 10) % 12 + 1]) / 2.0) / 2.0;
  4483. float S1 = z_at_pt[0],
  4484. S2 = sq(z_at_pt[0]);
  4485. int16_t N = 1;
  4486. if (!_1p_calibration) // std dev from zero plane
  4487. for (uint8_t axis = (_4p_opposite_points ? 3 : 1); axis < 13; axis += (_4p_calibration ? 4 : 2)) {
  4488. S1 += z_at_pt[axis];
  4489. S2 += sq(z_at_pt[axis]);
  4490. N++;
  4491. }
  4492. zero_std_dev_old = zero_std_dev;
  4493. zero_std_dev = round(sqrt(S2 / N) * 1000.0) / 1000.0 + 0.00001;
  4494. // Solve matrices
  4495. if ((zero_std_dev < test_precision && zero_std_dev > calibration_precision) || iterations <= force_iterations) {
  4496. if (zero_std_dev < zero_std_dev_min) {
  4497. COPY(e_old, endstop_adj);
  4498. dr_old = delta_radius;
  4499. zh_old = home_offset[Z_AXIS];
  4500. alpha_old = delta_tower_angle_trim[A_AXIS];
  4501. beta_old = delta_tower_angle_trim[B_AXIS];
  4502. }
  4503. float e_delta[XYZ] = { 0.0 }, r_delta = 0.0, t_alpha = 0.0, t_beta = 0.0;
  4504. const float r_diff = delta_radius - delta_calibration_radius,
  4505. h_factor = 1.00 + r_diff * 0.001, //1.02 for r_diff = 20mm
  4506. r_factor = -(1.75 + 0.005 * r_diff + 0.001 * sq(r_diff)), //2.25 for r_diff = 20mm
  4507. a_factor = 100.0 / delta_calibration_radius; //1.25 for cal_rd = 80mm
  4508. #define ZP(N,I) ((N) * z_at_pt[I])
  4509. #define Z1000(I) ZP(1.00, I)
  4510. #define Z1050(I) ZP(h_factor, I)
  4511. #define Z0700(I) ZP(h_factor * 2.0 / 3.00, I)
  4512. #define Z0350(I) ZP(h_factor / 3.00, I)
  4513. #define Z0175(I) ZP(h_factor / 6.00, I)
  4514. #define Z2250(I) ZP(r_factor, I)
  4515. #define Z0750(I) ZP(r_factor / 3.00, I)
  4516. #define Z0375(I) ZP(r_factor / 6.00, I)
  4517. #define Z0444(I) ZP(a_factor * 4.0 / 9.0, I)
  4518. #define Z0888(I) ZP(a_factor * 8.0 / 9.0, I)
  4519. #if ENABLED(PROBE_MANUALLY)
  4520. test_precision = 0.00; // forced end
  4521. #endif
  4522. switch (probe_points) {
  4523. case 1:
  4524. test_precision = 0.00; // forced end
  4525. LOOP_XYZ(i) e_delta[i] = Z1000(0);
  4526. break;
  4527. case 2:
  4528. if (towers_set) {
  4529. e_delta[X_AXIS] = Z1050(0) + Z0700(1) - Z0350(5) - Z0350(9);
  4530. e_delta[Y_AXIS] = Z1050(0) - Z0350(1) + Z0700(5) - Z0350(9);
  4531. e_delta[Z_AXIS] = Z1050(0) - Z0350(1) - Z0350(5) + Z0700(9);
  4532. r_delta = Z2250(0) - Z0750(1) - Z0750(5) - Z0750(9);
  4533. }
  4534. else {
  4535. e_delta[X_AXIS] = Z1050(0) - Z0700(7) + Z0350(11) + Z0350(3);
  4536. e_delta[Y_AXIS] = Z1050(0) + Z0350(7) - Z0700(11) + Z0350(3);
  4537. e_delta[Z_AXIS] = Z1050(0) + Z0350(7) + Z0350(11) - Z0700(3);
  4538. r_delta = Z2250(0) - Z0750(7) - Z0750(11) - Z0750(3);
  4539. }
  4540. break;
  4541. default:
  4542. e_delta[X_AXIS] = Z1050(0) + Z0350(1) - Z0175(5) - Z0175(9) - Z0350(7) + Z0175(11) + Z0175(3);
  4543. e_delta[Y_AXIS] = Z1050(0) - Z0175(1) + Z0350(5) - Z0175(9) + Z0175(7) - Z0350(11) + Z0175(3);
  4544. e_delta[Z_AXIS] = Z1050(0) - Z0175(1) - Z0175(5) + Z0350(9) + Z0175(7) + Z0175(11) - Z0350(3);
  4545. r_delta = Z2250(0) - Z0375(1) - Z0375(5) - Z0375(9) - Z0375(7) - Z0375(11) - Z0375(3);
  4546. if (towers_set) {
  4547. t_alpha = Z0444(1) - Z0888(5) + Z0444(9) + Z0444(7) - Z0888(11) + Z0444(3);
  4548. t_beta = Z0888(1) - Z0444(5) - Z0444(9) + Z0888(7) - Z0444(11) - Z0444(3);
  4549. }
  4550. break;
  4551. }
  4552. LOOP_XYZ(axis) endstop_adj[axis] += e_delta[axis];
  4553. delta_radius += r_delta;
  4554. delta_tower_angle_trim[A_AXIS] += t_alpha;
  4555. delta_tower_angle_trim[B_AXIS] += t_beta;
  4556. // adjust delta_height and endstops by the max amount
  4557. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  4558. home_offset[Z_AXIS] -= z_temp;
  4559. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  4560. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4561. }
  4562. else if (zero_std_dev >= test_precision) { // step one back
  4563. COPY(endstop_adj, e_old);
  4564. delta_radius = dr_old;
  4565. home_offset[Z_AXIS] = zh_old;
  4566. delta_tower_angle_trim[A_AXIS] = alpha_old;
  4567. delta_tower_angle_trim[B_AXIS] = beta_old;
  4568. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  4569. }
  4570. NOMORE(zero_std_dev_min, zero_std_dev);
  4571. // print report
  4572. if (verbose_level != 1) {
  4573. SERIAL_PROTOCOLPGM(". ");
  4574. print_signed_float(PSTR("c"), z_at_pt[0]);
  4575. if (_4p_towers_points || _7p_calibration) {
  4576. print_signed_float(PSTR(" x"), z_at_pt[1]);
  4577. print_signed_float(PSTR(" y"), z_at_pt[5]);
  4578. print_signed_float(PSTR(" z"), z_at_pt[9]);
  4579. }
  4580. if (!_4p_opposite_points) SERIAL_EOL();
  4581. if ((_4p_opposite_points) || _7p_calibration) {
  4582. if (_7p_calibration) {
  4583. SERIAL_CHAR('.');
  4584. SERIAL_PROTOCOL_SP(13);
  4585. }
  4586. print_signed_float(PSTR(" yz"), z_at_pt[7]);
  4587. print_signed_float(PSTR("zx"), z_at_pt[11]);
  4588. print_signed_float(PSTR("xy"), z_at_pt[3]);
  4589. SERIAL_EOL();
  4590. }
  4591. }
  4592. if (verbose_level != 0) { // !dry run
  4593. if ((zero_std_dev >= test_precision || zero_std_dev <= calibration_precision) && iterations > force_iterations) { // end iterations
  4594. SERIAL_PROTOCOLPGM("Calibration OK");
  4595. SERIAL_PROTOCOL_SP(36);
  4596. #if DISABLED(PROBE_MANUALLY)
  4597. if (zero_std_dev >= test_precision && !_1p_calibration)
  4598. SERIAL_PROTOCOLPGM("rolling back.");
  4599. else
  4600. #endif
  4601. {
  4602. SERIAL_PROTOCOLPGM("std dev:");
  4603. SERIAL_PROTOCOL_F(zero_std_dev_min, 3);
  4604. }
  4605. SERIAL_EOL();
  4606. char mess[21];
  4607. sprintf_P(mess, PSTR("Calibration sd:"));
  4608. if (zero_std_dev_min < 1)
  4609. sprintf_P(&mess[15], PSTR("0.%03i"), (int)round(zero_std_dev_min * 1000.0));
  4610. else
  4611. sprintf_P(&mess[15], PSTR("%03i.x"), (int)round(zero_std_dev_min));
  4612. lcd_setstatus(mess);
  4613. print_G33_settings(!_1p_calibration, _7p_calibration && towers_set);
  4614. serialprintPGM(save_message);
  4615. SERIAL_EOL();
  4616. }
  4617. else { // !end iterations
  4618. char mess[15];
  4619. if (iterations < 31)
  4620. sprintf_P(mess, PSTR("Iteration : %02i"), (int)iterations);
  4621. else
  4622. sprintf_P(mess, PSTR("No convergence"));
  4623. SERIAL_PROTOCOL(mess);
  4624. SERIAL_PROTOCOL_SP(36);
  4625. SERIAL_PROTOCOLPGM("std dev:");
  4626. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4627. SERIAL_EOL();
  4628. lcd_setstatus(mess);
  4629. print_G33_settings(!_1p_calibration, _7p_calibration && towers_set);
  4630. }
  4631. }
  4632. else { // dry run
  4633. const char *enddryrun = PSTR("End DRY-RUN");
  4634. serialprintPGM(enddryrun);
  4635. SERIAL_PROTOCOL_SP(39);
  4636. SERIAL_PROTOCOLPGM("std dev:");
  4637. SERIAL_PROTOCOL_F(zero_std_dev, 3);
  4638. SERIAL_EOL();
  4639. char mess[21];
  4640. sprintf_P(mess, enddryrun);
  4641. sprintf_P(&mess[11], PSTR(" sd:"));
  4642. if (zero_std_dev < 1)
  4643. sprintf_P(&mess[15], PSTR("0.%03i"), (int)round(zero_std_dev * 1000.0));
  4644. else
  4645. sprintf_P(&mess[15], PSTR("%03i.x"), (int)round(zero_std_dev));
  4646. lcd_setstatus(mess);
  4647. }
  4648. endstops.enable(true);
  4649. home_delta();
  4650. endstops.not_homing();
  4651. }
  4652. while ((zero_std_dev < test_precision && zero_std_dev > calibration_precision && iterations < 31) || iterations <= force_iterations);
  4653. #if ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  4654. do_blocking_move_to_z(delta_clip_start_height);
  4655. #endif
  4656. STOW_PROBE();
  4657. clean_up_after_endstop_or_probe_move();
  4658. #if HOTENDS > 1
  4659. tool_change(old_tool_index, 0, true);
  4660. #endif
  4661. }
  4662. #endif // DELTA_AUTO_CALIBRATION
  4663. #endif // PROBE_SELECTED
  4664. #if ENABLED(G38_PROBE_TARGET)
  4665. static bool G38_run_probe() {
  4666. bool G38_pass_fail = false;
  4667. // Get direction of move and retract
  4668. float retract_mm[XYZ];
  4669. LOOP_XYZ(i) {
  4670. float dist = destination[i] - current_position[i];
  4671. retract_mm[i] = FABS(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  4672. }
  4673. stepper.synchronize(); // wait until the machine is idle
  4674. // Move until destination reached or target hit
  4675. endstops.enable(true);
  4676. G38_move = true;
  4677. G38_endstop_hit = false;
  4678. prepare_move_to_destination();
  4679. stepper.synchronize();
  4680. G38_move = false;
  4681. endstops.hit_on_purpose();
  4682. set_current_from_steppers_for_axis(ALL_AXES);
  4683. SYNC_PLAN_POSITION_KINEMATIC();
  4684. if (G38_endstop_hit) {
  4685. G38_pass_fail = true;
  4686. #if ENABLED(PROBE_DOUBLE_TOUCH)
  4687. // Move away by the retract distance
  4688. set_destination_to_current();
  4689. LOOP_XYZ(i) destination[i] += retract_mm[i];
  4690. endstops.enable(false);
  4691. prepare_move_to_destination();
  4692. stepper.synchronize();
  4693. feedrate_mm_s /= 4;
  4694. // Bump the target more slowly
  4695. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  4696. endstops.enable(true);
  4697. G38_move = true;
  4698. prepare_move_to_destination();
  4699. stepper.synchronize();
  4700. G38_move = false;
  4701. set_current_from_steppers_for_axis(ALL_AXES);
  4702. SYNC_PLAN_POSITION_KINEMATIC();
  4703. #endif
  4704. }
  4705. endstops.hit_on_purpose();
  4706. endstops.not_homing();
  4707. return G38_pass_fail;
  4708. }
  4709. /**
  4710. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  4711. * G38.3 - probe toward workpiece, stop on contact
  4712. *
  4713. * Like G28 except uses Z min probe for all axes
  4714. */
  4715. inline void gcode_G38(bool is_38_2) {
  4716. // Get X Y Z E F
  4717. gcode_get_destination();
  4718. setup_for_endstop_or_probe_move();
  4719. // If any axis has enough movement, do the move
  4720. LOOP_XYZ(i)
  4721. if (FABS(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  4722. if (!parser.seenval('F')) feedrate_mm_s = homing_feedrate(i);
  4723. // If G38.2 fails throw an error
  4724. if (!G38_run_probe() && is_38_2) {
  4725. SERIAL_ERROR_START();
  4726. SERIAL_ERRORLNPGM("Failed to reach target");
  4727. }
  4728. break;
  4729. }
  4730. clean_up_after_endstop_or_probe_move();
  4731. }
  4732. #endif // G38_PROBE_TARGET
  4733. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  4734. /**
  4735. * G42: Move X & Y axes to mesh coordinates (I & J)
  4736. */
  4737. inline void gcode_G42() {
  4738. if (IsRunning()) {
  4739. const bool hasI = parser.seenval('I');
  4740. const int8_t ix = hasI ? parser.value_int() : 0;
  4741. const bool hasJ = parser.seenval('J');
  4742. const int8_t iy = hasJ ? parser.value_int() : 0;
  4743. if ((hasI && !WITHIN(ix, 0, GRID_MAX_POINTS_X - 1)) || (hasJ && !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1))) {
  4744. SERIAL_ECHOLNPGM(MSG_ERR_MESH_XY);
  4745. return;
  4746. }
  4747. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  4748. #define _GET_MESH_X(I) bilinear_start[X_AXIS] + I * bilinear_grid_spacing[X_AXIS]
  4749. #define _GET_MESH_Y(J) bilinear_start[Y_AXIS] + J * bilinear_grid_spacing[Y_AXIS]
  4750. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  4751. #define _GET_MESH_X(I) ubl.mesh_index_to_xpos(I)
  4752. #define _GET_MESH_Y(J) ubl.mesh_index_to_ypos(J)
  4753. #elif ENABLED(MESH_BED_LEVELING)
  4754. #define _GET_MESH_X(I) mbl.index_to_xpos[I]
  4755. #define _GET_MESH_Y(J) mbl.index_to_ypos[J]
  4756. #endif
  4757. set_destination_to_current();
  4758. if (hasI) destination[X_AXIS] = LOGICAL_X_POSITION(_GET_MESH_X(ix));
  4759. if (hasJ) destination[Y_AXIS] = LOGICAL_Y_POSITION(_GET_MESH_Y(iy));
  4760. if (parser.boolval('P')) {
  4761. if (hasI) destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  4762. if (hasJ) destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  4763. }
  4764. const float fval = parser.linearval('F');
  4765. if (fval > 0.0) feedrate_mm_s = MMM_TO_MMS(fval);
  4766. // SCARA kinematic has "safe" XY raw moves
  4767. #if IS_SCARA
  4768. prepare_uninterpolated_move_to_destination();
  4769. #else
  4770. prepare_move_to_destination();
  4771. #endif
  4772. }
  4773. }
  4774. #endif // AUTO_BED_LEVELING_UBL
  4775. /**
  4776. * G92: Set current position to given X Y Z E
  4777. */
  4778. inline void gcode_G92() {
  4779. bool didXYZ = false,
  4780. didE = parser.seenval('E');
  4781. if (!didE) stepper.synchronize();
  4782. LOOP_XYZE(i) {
  4783. if (parser.seenval(axis_codes[i])) {
  4784. #if IS_SCARA
  4785. current_position[i] = parser.value_axis_units((AxisEnum)i);
  4786. if (i != E_AXIS) didXYZ = true;
  4787. #else
  4788. #if HAS_POSITION_SHIFT
  4789. const float p = current_position[i];
  4790. #endif
  4791. const float v = parser.value_axis_units((AxisEnum)i);
  4792. current_position[i] = v;
  4793. if (i != E_AXIS) {
  4794. didXYZ = true;
  4795. #if HAS_POSITION_SHIFT
  4796. position_shift[i] += v - p; // Offset the coordinate space
  4797. update_software_endstops((AxisEnum)i);
  4798. #if ENABLED(I2C_POSITION_ENCODERS)
  4799. I2CPEM.encoders[I2CPEM.idx_from_axis((AxisEnum)i)].set_axis_offset(position_shift[i]);
  4800. #endif
  4801. #endif
  4802. }
  4803. #endif
  4804. }
  4805. }
  4806. if (didXYZ)
  4807. SYNC_PLAN_POSITION_KINEMATIC();
  4808. else if (didE)
  4809. sync_plan_position_e();
  4810. report_current_position();
  4811. }
  4812. #if HAS_RESUME_CONTINUE
  4813. /**
  4814. * M0: Unconditional stop - Wait for user button press on LCD
  4815. * M1: Conditional stop - Wait for user button press on LCD
  4816. */
  4817. inline void gcode_M0_M1() {
  4818. const char * const args = parser.string_arg;
  4819. millis_t ms = 0;
  4820. bool hasP = false, hasS = false;
  4821. if (parser.seenval('P')) {
  4822. ms = parser.value_millis(); // milliseconds to wait
  4823. hasP = ms > 0;
  4824. }
  4825. if (parser.seenval('S')) {
  4826. ms = parser.value_millis_from_seconds(); // seconds to wait
  4827. hasS = ms > 0;
  4828. }
  4829. #if ENABLED(ULTIPANEL)
  4830. if (!hasP && !hasS && args && *args)
  4831. lcd_setstatus(args, true);
  4832. else {
  4833. LCD_MESSAGEPGM(MSG_USERWAIT);
  4834. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  4835. dontExpireStatus();
  4836. #endif
  4837. }
  4838. #else
  4839. if (!hasP && !hasS && args && *args) {
  4840. SERIAL_ECHO_START();
  4841. SERIAL_ECHOLN(args);
  4842. }
  4843. #endif
  4844. KEEPALIVE_STATE(PAUSED_FOR_USER);
  4845. wait_for_user = true;
  4846. stepper.synchronize();
  4847. refresh_cmd_timeout();
  4848. if (ms > 0) {
  4849. ms += previous_cmd_ms; // wait until this time for a click
  4850. while (PENDING(millis(), ms) && wait_for_user) idle();
  4851. }
  4852. else {
  4853. #if ENABLED(ULTIPANEL)
  4854. if (lcd_detected()) {
  4855. while (wait_for_user) idle();
  4856. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  4857. }
  4858. #else
  4859. while (wait_for_user) idle();
  4860. #endif
  4861. }
  4862. wait_for_user = false;
  4863. KEEPALIVE_STATE(IN_HANDLER);
  4864. }
  4865. #endif // HAS_RESUME_CONTINUE
  4866. #if ENABLED(SPINDLE_LASER_ENABLE)
  4867. /**
  4868. * M3: Spindle Clockwise
  4869. * M4: Spindle Counter-clockwise
  4870. *
  4871. * S0 turns off spindle.
  4872. *
  4873. * If no speed PWM output is defined then M3/M4 just turns it on.
  4874. *
  4875. * At least 12.8KHz (50Hz * 256) is needed for spindle PWM.
  4876. * Hardware PWM is required. ISRs are too slow.
  4877. *
  4878. * NOTE: WGM for timers 3, 4, and 5 must be either Mode 1 or Mode 5.
  4879. * No other settings give a PWM signal that goes from 0 to 5 volts.
  4880. *
  4881. * The system automatically sets WGM to Mode 1, so no special
  4882. * initialization is needed.
  4883. *
  4884. * WGM bits for timer 2 are automatically set by the system to
  4885. * Mode 1. This produces an acceptable 0 to 5 volt signal.
  4886. * No special initialization is needed.
  4887. *
  4888. * NOTE: A minimum PWM frequency of 50 Hz is needed. All prescaler
  4889. * factors for timers 2, 3, 4, and 5 are acceptable.
  4890. *
  4891. * SPINDLE_LASER_ENABLE_PIN needs an external pullup or it may power on
  4892. * the spindle/laser during power-up or when connecting to the host
  4893. * (usually goes through a reset which sets all I/O pins to tri-state)
  4894. *
  4895. * PWM duty cycle goes from 0 (off) to 255 (always on).
  4896. */
  4897. // Wait for spindle to come up to speed
  4898. inline void delay_for_power_up() {
  4899. refresh_cmd_timeout();
  4900. while (PENDING(millis(), SPINDLE_LASER_POWERUP_DELAY + previous_cmd_ms)) idle();
  4901. }
  4902. // Wait for spindle to stop turning
  4903. inline void delay_for_power_down() {
  4904. refresh_cmd_timeout();
  4905. while (PENDING(millis(), SPINDLE_LASER_POWERDOWN_DELAY + previous_cmd_ms + 1)) idle();
  4906. }
  4907. /**
  4908. * ocr_val_mode() is used for debugging and to get the points needed to compute the RPM vs ocr_val line
  4909. *
  4910. * it accepts inputs of 0-255
  4911. */
  4912. inline void ocr_val_mode() {
  4913. uint8_t spindle_laser_power = parser.value_byte();
  4914. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4915. if (SPINDLE_LASER_PWM_INVERT) spindle_laser_power = 255 - spindle_laser_power;
  4916. analogWrite(SPINDLE_LASER_PWM_PIN, spindle_laser_power);
  4917. }
  4918. inline void gcode_M3_M4(bool is_M3) {
  4919. stepper.synchronize(); // wait until previous movement commands (G0/G0/G2/G3) have completed before playing with the spindle
  4920. #if SPINDLE_DIR_CHANGE
  4921. const bool rotation_dir = (is_M3 && !SPINDLE_INVERT_DIR || !is_M3 && SPINDLE_INVERT_DIR) ? HIGH : LOW;
  4922. if (SPINDLE_STOP_ON_DIR_CHANGE \
  4923. && READ(SPINDLE_LASER_ENABLE_PIN) == SPINDLE_LASER_ENABLE_INVERT \
  4924. && READ(SPINDLE_DIR_PIN) != rotation_dir
  4925. ) {
  4926. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off
  4927. delay_for_power_down();
  4928. }
  4929. WRITE(SPINDLE_DIR_PIN, rotation_dir);
  4930. #endif
  4931. /**
  4932. * Our final value for ocr_val is an unsigned 8 bit value between 0 and 255 which usually means uint8_t.
  4933. * Went to uint16_t because some of the uint8_t calculations would sometimes give 1000 0000 rather than 1111 1111.
  4934. * Then needed to AND the uint16_t result with 0x00FF to make sure we only wrote the byte of interest.
  4935. */
  4936. #if ENABLED(SPINDLE_LASER_PWM)
  4937. if (parser.seen('O')) ocr_val_mode();
  4938. else {
  4939. const float spindle_laser_power = parser.floatval('S');
  4940. if (spindle_laser_power == 0) {
  4941. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // turn spindle off (active low)
  4942. delay_for_power_down();
  4943. }
  4944. else {
  4945. int16_t ocr_val = (spindle_laser_power - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // convert RPM to PWM duty cycle
  4946. NOMORE(ocr_val, 255); // limit to max the Atmel PWM will support
  4947. if (spindle_laser_power <= SPEED_POWER_MIN)
  4948. ocr_val = (SPEED_POWER_MIN - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // minimum setting
  4949. if (spindle_laser_power >= SPEED_POWER_MAX)
  4950. ocr_val = (SPEED_POWER_MAX - (SPEED_POWER_INTERCEPT)) * (1.0 / (SPEED_POWER_SLOPE)); // limit to max RPM
  4951. if (SPINDLE_LASER_PWM_INVERT) ocr_val = 255 - ocr_val;
  4952. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low)
  4953. analogWrite(SPINDLE_LASER_PWM_PIN, ocr_val & 0xFF); // only write low byte
  4954. delay_for_power_up();
  4955. }
  4956. }
  4957. #else
  4958. WRITE(SPINDLE_LASER_ENABLE_PIN, SPINDLE_LASER_ENABLE_INVERT); // turn spindle on (active low) if spindle speed option not enabled
  4959. delay_for_power_up();
  4960. #endif
  4961. }
  4962. /**
  4963. * M5 turn off spindle
  4964. */
  4965. inline void gcode_M5() {
  4966. stepper.synchronize();
  4967. WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT);
  4968. delay_for_power_down();
  4969. }
  4970. #endif // SPINDLE_LASER_ENABLE
  4971. /**
  4972. * M17: Enable power on all stepper motors
  4973. */
  4974. inline void gcode_M17() {
  4975. LCD_MESSAGEPGM(MSG_NO_MOVE);
  4976. enable_all_steppers();
  4977. }
  4978. #if IS_KINEMATIC
  4979. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder)
  4980. #else
  4981. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S)
  4982. #endif
  4983. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  4984. static float resume_position[XYZE];
  4985. static bool move_away_flag = false;
  4986. #if ENABLED(SDSUPPORT)
  4987. static bool sd_print_paused = false;
  4988. #endif
  4989. static void filament_change_beep(const int8_t max_beep_count, const bool init=false) {
  4990. static millis_t next_buzz = 0;
  4991. static int8_t runout_beep = 0;
  4992. if (init) next_buzz = runout_beep = 0;
  4993. const millis_t ms = millis();
  4994. if (ELAPSED(ms, next_buzz)) {
  4995. if (max_beep_count < 0 || runout_beep < max_beep_count + 5) { // Only beep as long as we're supposed to
  4996. next_buzz = ms + ((max_beep_count < 0 || runout_beep < max_beep_count) ? 2500 : 400);
  4997. BUZZ(300, 2000);
  4998. runout_beep++;
  4999. }
  5000. }
  5001. }
  5002. static void ensure_safe_temperature() {
  5003. bool heaters_heating = true;
  5004. wait_for_heatup = true; // M108 will clear this
  5005. while (wait_for_heatup && heaters_heating) {
  5006. idle();
  5007. heaters_heating = false;
  5008. HOTEND_LOOP() {
  5009. if (thermalManager.degTargetHotend(e) && abs(thermalManager.degHotend(e) - thermalManager.degTargetHotend(e)) > TEMP_HYSTERESIS) {
  5010. heaters_heating = true;
  5011. #if ENABLED(ULTIPANEL)
  5012. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  5013. #endif
  5014. break;
  5015. }
  5016. }
  5017. }
  5018. }
  5019. static bool pause_print(const float &retract, const float &z_lift, const float &x_pos, const float &y_pos,
  5020. const float &unload_length = 0 , const int8_t max_beep_count = 0, const bool show_lcd = false
  5021. ) {
  5022. if (move_away_flag) return false; // already paused
  5023. if (!DEBUGGING(DRYRUN) && (unload_length != 0 || retract != 0)) {
  5024. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5025. if (!thermalManager.allow_cold_extrude &&
  5026. thermalManager.degTargetHotend(active_extruder) < thermalManager.extrude_min_temp) {
  5027. SERIAL_ERROR_START();
  5028. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  5029. return false;
  5030. }
  5031. #endif
  5032. ensure_safe_temperature(); // wait for extruder to heat up before unloading
  5033. }
  5034. // Indicate that the printer is paused
  5035. move_away_flag = true;
  5036. // Pause the print job and timer
  5037. #if ENABLED(SDSUPPORT)
  5038. if (card.sdprinting) {
  5039. card.pauseSDPrint();
  5040. sd_print_paused = true;
  5041. }
  5042. #endif
  5043. print_job_timer.pause();
  5044. // Show initial message and wait for synchronize steppers
  5045. if (show_lcd) {
  5046. #if ENABLED(ULTIPANEL)
  5047. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INIT);
  5048. #endif
  5049. }
  5050. stepper.synchronize();
  5051. // Save current position
  5052. COPY(resume_position, current_position);
  5053. set_destination_to_current();
  5054. if (retract) {
  5055. // Initial retract before move to filament change position
  5056. destination[E_AXIS] += retract;
  5057. RUNPLAN(PAUSE_PARK_RETRACT_FEEDRATE);
  5058. }
  5059. // Lift Z axis
  5060. if (z_lift > 0) {
  5061. destination[Z_AXIS] += z_lift;
  5062. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  5063. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5064. }
  5065. // Move XY axes to filament exchange position
  5066. destination[X_AXIS] = x_pos;
  5067. destination[Y_AXIS] = y_pos;
  5068. clamp_to_software_endstops(destination);
  5069. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5070. stepper.synchronize();
  5071. if (unload_length != 0) {
  5072. if (show_lcd) {
  5073. #if ENABLED(ULTIPANEL)
  5074. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_UNLOAD);
  5075. idle();
  5076. #endif
  5077. }
  5078. // Unload filament
  5079. destination[E_AXIS] += unload_length;
  5080. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  5081. stepper.synchronize();
  5082. }
  5083. if (show_lcd) {
  5084. #if ENABLED(ULTIPANEL)
  5085. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5086. #endif
  5087. }
  5088. #if HAS_BUZZER
  5089. filament_change_beep(max_beep_count, true);
  5090. #endif
  5091. idle();
  5092. // Disable extruders steppers for manual filament changing (only on boards that have separate ENABLE_PINS)
  5093. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN
  5094. disable_e_steppers();
  5095. safe_delay(100);
  5096. #endif
  5097. // Start the heater idle timers
  5098. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5099. HOTEND_LOOP()
  5100. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5101. return true;
  5102. }
  5103. static void wait_for_filament_reload(const int8_t max_beep_count = 0) {
  5104. bool nozzle_timed_out = false;
  5105. // Wait for filament insert by user and press button
  5106. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5107. wait_for_user = true; // LCD click or M108 will clear this
  5108. while (wait_for_user) {
  5109. #if HAS_BUZZER
  5110. filament_change_beep(max_beep_count);
  5111. #endif
  5112. // If the nozzle has timed out, wait for the user to press the button to re-heat the nozzle, then
  5113. // re-heat the nozzle, re-show the insert screen, restart the idle timers, and start over
  5114. if (!nozzle_timed_out)
  5115. HOTEND_LOOP()
  5116. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5117. if (nozzle_timed_out) {
  5118. #if ENABLED(ULTIPANEL)
  5119. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  5120. #endif
  5121. // Wait for LCD click or M108
  5122. while (wait_for_user) idle(true);
  5123. // Re-enable the heaters if they timed out
  5124. HOTEND_LOOP() thermalManager.reset_heater_idle_timer(e);
  5125. // Wait for the heaters to reach the target temperatures
  5126. ensure_safe_temperature();
  5127. #if ENABLED(ULTIPANEL)
  5128. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5129. #endif
  5130. // Start the heater idle timers
  5131. const millis_t nozzle_timeout = (millis_t)(PAUSE_PARK_NOZZLE_TIMEOUT) * 1000UL;
  5132. HOTEND_LOOP()
  5133. thermalManager.start_heater_idle_timer(e, nozzle_timeout);
  5134. wait_for_user = true; /* Wait for user to load filament */
  5135. nozzle_timed_out = false;
  5136. #if HAS_BUZZER
  5137. filament_change_beep(max_beep_count, true);
  5138. #endif
  5139. }
  5140. idle(true);
  5141. }
  5142. KEEPALIVE_STATE(IN_HANDLER);
  5143. }
  5144. static void resume_print(const float &load_length = 0, const float &initial_extrude_length = 0, const int8_t max_beep_count = 0) {
  5145. bool nozzle_timed_out = false;
  5146. if (!move_away_flag) return;
  5147. // Re-enable the heaters if they timed out
  5148. HOTEND_LOOP() {
  5149. nozzle_timed_out |= thermalManager.is_heater_idle(e);
  5150. thermalManager.reset_heater_idle_timer(e);
  5151. }
  5152. if (nozzle_timed_out) ensure_safe_temperature();
  5153. #if HAS_BUZZER
  5154. filament_change_beep(max_beep_count, true);
  5155. #endif
  5156. if (load_length != 0) {
  5157. #if ENABLED(ULTIPANEL)
  5158. // Show "insert filament"
  5159. if (nozzle_timed_out)
  5160. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_INSERT);
  5161. #endif
  5162. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5163. wait_for_user = true; // LCD click or M108 will clear this
  5164. while (wait_for_user && nozzle_timed_out) {
  5165. #if HAS_BUZZER
  5166. filament_change_beep(max_beep_count);
  5167. #endif
  5168. idle(true);
  5169. }
  5170. KEEPALIVE_STATE(IN_HANDLER);
  5171. #if ENABLED(ULTIPANEL)
  5172. // Show "load" message
  5173. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_LOAD);
  5174. #endif
  5175. // Load filament
  5176. destination[E_AXIS] += load_length;
  5177. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  5178. stepper.synchronize();
  5179. }
  5180. #if ENABLED(ULTIPANEL) && ADVANCED_PAUSE_EXTRUDE_LENGTH > 0
  5181. float extrude_length = initial_extrude_length;
  5182. do {
  5183. if (extrude_length > 0) {
  5184. // "Wait for filament extrude"
  5185. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_EXTRUDE);
  5186. // Extrude filament to get into hotend
  5187. destination[E_AXIS] += extrude_length;
  5188. RUNPLAN(ADVANCED_PAUSE_EXTRUDE_FEEDRATE);
  5189. stepper.synchronize();
  5190. }
  5191. // Show "Extrude More" / "Resume" menu and wait for reply
  5192. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5193. wait_for_user = false;
  5194. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_OPTION);
  5195. while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_WAIT_FOR) idle(true);
  5196. KEEPALIVE_STATE(IN_HANDLER);
  5197. extrude_length = ADVANCED_PAUSE_EXTRUDE_LENGTH;
  5198. // Keep looping if "Extrude More" was selected
  5199. } while (advanced_pause_menu_response == ADVANCED_PAUSE_RESPONSE_EXTRUDE_MORE);
  5200. #endif
  5201. #if ENABLED(ULTIPANEL)
  5202. // "Wait for print to resume"
  5203. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_RESUME);
  5204. #endif
  5205. // Set extruder to saved position
  5206. destination[E_AXIS] = current_position[E_AXIS] = resume_position[E_AXIS];
  5207. planner.set_e_position_mm(current_position[E_AXIS]);
  5208. #if IS_KINEMATIC
  5209. // Move XYZ to starting position
  5210. planner.buffer_line_kinematic(resume_position, PAUSE_PARK_XY_FEEDRATE, active_extruder);
  5211. #else
  5212. // Move XY to starting position, then Z
  5213. destination[X_AXIS] = resume_position[X_AXIS];
  5214. destination[Y_AXIS] = resume_position[Y_AXIS];
  5215. RUNPLAN(PAUSE_PARK_XY_FEEDRATE);
  5216. destination[Z_AXIS] = resume_position[Z_AXIS];
  5217. RUNPLAN(PAUSE_PARK_Z_FEEDRATE);
  5218. #endif
  5219. stepper.synchronize();
  5220. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  5221. filament_ran_out = false;
  5222. #endif
  5223. #if ENABLED(ULTIPANEL)
  5224. // Show status screen
  5225. lcd_advanced_pause_show_message(ADVANCED_PAUSE_MESSAGE_STATUS);
  5226. #endif
  5227. #if ENABLED(SDSUPPORT)
  5228. if (sd_print_paused) {
  5229. card.startFileprint();
  5230. sd_print_paused = false;
  5231. }
  5232. #endif
  5233. move_away_flag = false;
  5234. }
  5235. #endif // ADVANCED_PAUSE_FEATURE
  5236. #if ENABLED(SDSUPPORT)
  5237. /**
  5238. * M20: List SD card to serial output
  5239. */
  5240. inline void gcode_M20() {
  5241. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  5242. card.ls();
  5243. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  5244. }
  5245. /**
  5246. * M21: Init SD Card
  5247. */
  5248. inline void gcode_M21() { card.initsd(); }
  5249. /**
  5250. * M22: Release SD Card
  5251. */
  5252. inline void gcode_M22() { card.release(); }
  5253. /**
  5254. * M23: Open a file
  5255. */
  5256. inline void gcode_M23() {
  5257. // Simplify3D includes the size, so zero out all spaces (#7227)
  5258. for (char *fn = parser.string_arg; *fn; ++fn) if (*fn == ' ') *fn = '\0';
  5259. card.openFile(parser.string_arg, true);
  5260. }
  5261. /**
  5262. * M24: Start or Resume SD Print
  5263. */
  5264. inline void gcode_M24() {
  5265. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5266. resume_print();
  5267. #endif
  5268. card.startFileprint();
  5269. print_job_timer.start();
  5270. }
  5271. /**
  5272. * M25: Pause SD Print
  5273. */
  5274. inline void gcode_M25() {
  5275. card.pauseSDPrint();
  5276. print_job_timer.pause();
  5277. #if ENABLED(PARK_HEAD_ON_PAUSE)
  5278. enqueue_and_echo_commands_P(PSTR("M125")); // Must be enqueued with pauseSDPrint set to be last in the buffer
  5279. #endif
  5280. }
  5281. /**
  5282. * M26: Set SD Card file index
  5283. */
  5284. inline void gcode_M26() {
  5285. if (card.cardOK && parser.seenval('S'))
  5286. card.setIndex(parser.value_long());
  5287. }
  5288. /**
  5289. * M27: Get SD Card status
  5290. */
  5291. inline void gcode_M27() { card.getStatus(); }
  5292. /**
  5293. * M28: Start SD Write
  5294. */
  5295. inline void gcode_M28() { card.openFile(parser.string_arg, false); }
  5296. /**
  5297. * M29: Stop SD Write
  5298. * Processed in write to file routine above
  5299. */
  5300. inline void gcode_M29() {
  5301. // card.saving = false;
  5302. }
  5303. /**
  5304. * M30 <filename>: Delete SD Card file
  5305. */
  5306. inline void gcode_M30() {
  5307. if (card.cardOK) {
  5308. card.closefile();
  5309. card.removeFile(parser.string_arg);
  5310. }
  5311. }
  5312. #endif // SDSUPPORT
  5313. /**
  5314. * M31: Get the time since the start of SD Print (or last M109)
  5315. */
  5316. inline void gcode_M31() {
  5317. char buffer[21];
  5318. duration_t elapsed = print_job_timer.duration();
  5319. elapsed.toString(buffer);
  5320. lcd_setstatus(buffer);
  5321. SERIAL_ECHO_START();
  5322. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  5323. }
  5324. #if ENABLED(SDSUPPORT)
  5325. /**
  5326. * M32: Select file and start SD Print
  5327. */
  5328. inline void gcode_M32() {
  5329. if (card.sdprinting)
  5330. stepper.synchronize();
  5331. char* namestartpos = parser.string_arg;
  5332. const bool call_procedure = parser.boolval('P');
  5333. if (card.cardOK) {
  5334. card.openFile(namestartpos, true, call_procedure);
  5335. if (parser.seenval('S'))
  5336. card.setIndex(parser.value_long());
  5337. card.startFileprint();
  5338. // Procedure calls count as normal print time.
  5339. if (!call_procedure) print_job_timer.start();
  5340. }
  5341. }
  5342. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  5343. /**
  5344. * M33: Get the long full path of a file or folder
  5345. *
  5346. * Parameters:
  5347. * <dospath> Case-insensitive DOS-style path to a file or folder
  5348. *
  5349. * Example:
  5350. * M33 miscel~1/armchair/armcha~1.gco
  5351. *
  5352. * Output:
  5353. * /Miscellaneous/Armchair/Armchair.gcode
  5354. */
  5355. inline void gcode_M33() {
  5356. card.printLongPath(parser.string_arg);
  5357. }
  5358. #endif
  5359. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  5360. /**
  5361. * M34: Set SD Card Sorting Options
  5362. */
  5363. inline void gcode_M34() {
  5364. if (parser.seen('S')) card.setSortOn(parser.value_bool());
  5365. if (parser.seenval('F')) {
  5366. const int v = parser.value_long();
  5367. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  5368. }
  5369. //if (parser.seen('R')) card.setSortReverse(parser.value_bool());
  5370. }
  5371. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  5372. /**
  5373. * M928: Start SD Write
  5374. */
  5375. inline void gcode_M928() {
  5376. card.openLogFile(parser.string_arg);
  5377. }
  5378. #endif // SDSUPPORT
  5379. /**
  5380. * Sensitive pin test for M42, M226
  5381. */
  5382. static bool pin_is_protected(const int8_t pin) {
  5383. static const int8_t sensitive_pins[] PROGMEM = SENSITIVE_PINS;
  5384. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  5385. if (pin == (int8_t)pgm_read_byte(&sensitive_pins[i])) return true;
  5386. return false;
  5387. }
  5388. /**
  5389. * M42: Change pin status via GCode
  5390. *
  5391. * P<pin> Pin number (LED if omitted)
  5392. * S<byte> Pin status from 0 - 255
  5393. */
  5394. inline void gcode_M42() {
  5395. if (!parser.seenval('S')) return;
  5396. const byte pin_status = parser.value_byte();
  5397. const int pin_number = parser.intval('P', LED_PIN);
  5398. if (pin_number < 0) return;
  5399. if (pin_is_protected(pin_number)) {
  5400. SERIAL_ERROR_START();
  5401. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  5402. return;
  5403. }
  5404. pinMode(pin_number, OUTPUT);
  5405. digitalWrite(pin_number, pin_status);
  5406. analogWrite(pin_number, pin_status);
  5407. #if FAN_COUNT > 0
  5408. switch (pin_number) {
  5409. #if HAS_FAN0
  5410. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  5411. #endif
  5412. #if HAS_FAN1
  5413. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  5414. #endif
  5415. #if HAS_FAN2
  5416. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  5417. #endif
  5418. }
  5419. #endif
  5420. }
  5421. #if ENABLED(PINS_DEBUGGING)
  5422. #include "pinsDebug.h"
  5423. inline void toggle_pins() {
  5424. const bool I_flag = parser.boolval('I');
  5425. const int repeat = parser.intval('R', 1),
  5426. start = parser.intval('S'),
  5427. end = parser.intval('E', NUM_DIGITAL_PINS - 1),
  5428. wait = parser.intval('W', 500);
  5429. for (uint8_t pin = start; pin <= end; pin++) {
  5430. //report_pin_state_extended(pin, I_flag, false);
  5431. if (!I_flag && pin_is_protected(pin)) {
  5432. report_pin_state_extended(pin, I_flag, true, "Untouched ");
  5433. SERIAL_EOL();
  5434. }
  5435. else {
  5436. report_pin_state_extended(pin, I_flag, true, "Pulsing ");
  5437. #if AVR_AT90USB1286_FAMILY // Teensy IDEs don't know about these pins so must use FASTIO
  5438. if (pin == TEENSY_E2) {
  5439. SET_OUTPUT(TEENSY_E2);
  5440. for (int16_t j = 0; j < repeat; j++) {
  5441. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  5442. WRITE(TEENSY_E2, HIGH); safe_delay(wait);
  5443. WRITE(TEENSY_E2, LOW); safe_delay(wait);
  5444. }
  5445. }
  5446. else if (pin == TEENSY_E3) {
  5447. SET_OUTPUT(TEENSY_E3);
  5448. for (int16_t j = 0; j < repeat; j++) {
  5449. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  5450. WRITE(TEENSY_E3, HIGH); safe_delay(wait);
  5451. WRITE(TEENSY_E3, LOW); safe_delay(wait);
  5452. }
  5453. }
  5454. else
  5455. #endif
  5456. {
  5457. pinMode(pin, OUTPUT);
  5458. for (int16_t j = 0; j < repeat; j++) {
  5459. digitalWrite(pin, 0); safe_delay(wait);
  5460. digitalWrite(pin, 1); safe_delay(wait);
  5461. digitalWrite(pin, 0); safe_delay(wait);
  5462. }
  5463. }
  5464. }
  5465. SERIAL_EOL();
  5466. }
  5467. SERIAL_ECHOLNPGM("Done.");
  5468. } // toggle_pins
  5469. inline void servo_probe_test() {
  5470. #if !(NUM_SERVOS > 0 && HAS_SERVO_0)
  5471. SERIAL_ERROR_START();
  5472. SERIAL_ERRORLNPGM("SERVO not setup");
  5473. #elif !HAS_Z_SERVO_ENDSTOP
  5474. SERIAL_ERROR_START();
  5475. SERIAL_ERRORLNPGM("Z_ENDSTOP_SERVO_NR not setup");
  5476. #else
  5477. const uint8_t probe_index = parser.byteval('P', Z_ENDSTOP_SERVO_NR);
  5478. SERIAL_PROTOCOLLNPGM("Servo probe test");
  5479. SERIAL_PROTOCOLLNPAIR(". using index: ", probe_index);
  5480. SERIAL_PROTOCOLLNPAIR(". deploy angle: ", z_servo_angle[0]);
  5481. SERIAL_PROTOCOLLNPAIR(". stow angle: ", z_servo_angle[1]);
  5482. bool probe_inverting;
  5483. #if ENABLED(Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN)
  5484. #define PROBE_TEST_PIN Z_MIN_PIN
  5485. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN pin: ", PROBE_TEST_PIN);
  5486. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_ENDSTOP_INVERTING (ignores Z_MIN_PROBE_ENDSTOP_INVERTING)");
  5487. SERIAL_PROTOCOLPGM(". Z_MIN_ENDSTOP_INVERTING: ");
  5488. #if Z_MIN_ENDSTOP_INVERTING
  5489. SERIAL_PROTOCOLLNPGM("true");
  5490. #else
  5491. SERIAL_PROTOCOLLNPGM("false");
  5492. #endif
  5493. probe_inverting = Z_MIN_ENDSTOP_INVERTING;
  5494. #elif ENABLED(Z_MIN_PROBE_ENDSTOP)
  5495. #define PROBE_TEST_PIN Z_MIN_PROBE_PIN
  5496. SERIAL_PROTOCOLLNPAIR(". probe uses Z_MIN_PROBE_PIN: ", PROBE_TEST_PIN);
  5497. SERIAL_PROTOCOLLNPGM(". uses Z_MIN_PROBE_ENDSTOP_INVERTING (ignores Z_MIN_ENDSTOP_INVERTING)");
  5498. SERIAL_PROTOCOLPGM(". Z_MIN_PROBE_ENDSTOP_INVERTING: ");
  5499. #if Z_MIN_PROBE_ENDSTOP_INVERTING
  5500. SERIAL_PROTOCOLLNPGM("true");
  5501. #else
  5502. SERIAL_PROTOCOLLNPGM("false");
  5503. #endif
  5504. probe_inverting = Z_MIN_PROBE_ENDSTOP_INVERTING;
  5505. #endif
  5506. SERIAL_PROTOCOLLNPGM(". deploy & stow 4 times");
  5507. SET_INPUT_PULLUP(PROBE_TEST_PIN);
  5508. bool deploy_state, stow_state;
  5509. for (uint8_t i = 0; i < 4; i++) {
  5510. servo[probe_index].move(z_servo_angle[0]); //deploy
  5511. safe_delay(500);
  5512. deploy_state = READ(PROBE_TEST_PIN);
  5513. servo[probe_index].move(z_servo_angle[1]); //stow
  5514. safe_delay(500);
  5515. stow_state = READ(PROBE_TEST_PIN);
  5516. }
  5517. if (probe_inverting != deploy_state) SERIAL_PROTOCOLLNPGM("WARNING - INVERTING setting probably backwards");
  5518. refresh_cmd_timeout();
  5519. if (deploy_state != stow_state) {
  5520. SERIAL_PROTOCOLLNPGM("BLTouch clone detected");
  5521. if (deploy_state) {
  5522. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: HIGH (logic 1)");
  5523. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: LOW (logic 0)");
  5524. }
  5525. else {
  5526. SERIAL_PROTOCOLLNPGM(". DEPLOYED state: LOW (logic 0)");
  5527. SERIAL_PROTOCOLLNPGM(". STOWED (triggered) state: HIGH (logic 1)");
  5528. }
  5529. #if ENABLED(BLTOUCH)
  5530. SERIAL_PROTOCOLLNPGM("ERROR: BLTOUCH enabled - set this device up as a Z Servo Probe with inverting as true.");
  5531. #endif
  5532. }
  5533. else { // measure active signal length
  5534. servo[probe_index].move(z_servo_angle[0]); // deploy
  5535. safe_delay(500);
  5536. SERIAL_PROTOCOLLNPGM("please trigger probe");
  5537. uint16_t probe_counter = 0;
  5538. // Allow 30 seconds max for operator to trigger probe
  5539. for (uint16_t j = 0; j < 500 * 30 && probe_counter == 0 ; j++) {
  5540. safe_delay(2);
  5541. if (0 == j % (500 * 1)) // keep cmd_timeout happy
  5542. refresh_cmd_timeout();
  5543. if (deploy_state != READ(PROBE_TEST_PIN)) { // probe triggered
  5544. for (probe_counter = 1; probe_counter < 50 && deploy_state != READ(PROBE_TEST_PIN); ++probe_counter)
  5545. safe_delay(2);
  5546. if (probe_counter == 50)
  5547. SERIAL_PROTOCOLLNPGM("Z Servo Probe detected"); // >= 100mS active time
  5548. else if (probe_counter >= 2)
  5549. SERIAL_PROTOCOLLNPAIR("BLTouch compatible probe detected - pulse width (+/- 4mS): ", probe_counter * 2); // allow 4 - 100mS pulse
  5550. else
  5551. SERIAL_PROTOCOLLNPGM("noise detected - please re-run test"); // less than 2mS pulse
  5552. servo[probe_index].move(z_servo_angle[1]); //stow
  5553. } // pulse detected
  5554. } // for loop waiting for trigger
  5555. if (probe_counter == 0) SERIAL_PROTOCOLLNPGM("trigger not detected");
  5556. } // measure active signal length
  5557. #endif
  5558. } // servo_probe_test
  5559. /**
  5560. * M43: Pin debug - report pin state, watch pins, toggle pins and servo probe test/report
  5561. *
  5562. * M43 - report name and state of pin(s)
  5563. * P<pin> Pin to read or watch. If omitted, reads all pins.
  5564. * I Flag to ignore Marlin's pin protection.
  5565. *
  5566. * M43 W - Watch pins -reporting changes- until reset, click, or M108.
  5567. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  5568. * I Flag to ignore Marlin's pin protection.
  5569. *
  5570. * M43 E<bool> - Enable / disable background endstop monitoring
  5571. * - Machine continues to operate
  5572. * - Reports changes to endstops
  5573. * - Toggles LED_PIN when an endstop changes
  5574. * - Can not reliably catch the 5mS pulse from BLTouch type probes
  5575. *
  5576. * M43 T - Toggle pin(s) and report which pin is being toggled
  5577. * S<pin> - Start Pin number. If not given, will default to 0
  5578. * L<pin> - End Pin number. If not given, will default to last pin defined for this board
  5579. * I<bool> - Flag to ignore Marlin's pin protection. Use with caution!!!!
  5580. * R - Repeat pulses on each pin this number of times before continueing to next pin
  5581. * W - Wait time (in miliseconds) between pulses. If not given will default to 500
  5582. *
  5583. * M43 S - Servo probe test
  5584. * P<index> - Probe index (optional - defaults to 0
  5585. */
  5586. inline void gcode_M43() {
  5587. if (parser.seen('T')) { // must be first or else its "S" and "E" parameters will execute endstop or servo test
  5588. toggle_pins();
  5589. return;
  5590. }
  5591. // Enable or disable endstop monitoring
  5592. if (parser.seen('E')) {
  5593. endstop_monitor_flag = parser.value_bool();
  5594. SERIAL_PROTOCOLPGM("endstop monitor ");
  5595. serialprintPGM(endstop_monitor_flag ? PSTR("en") : PSTR("dis"));
  5596. SERIAL_PROTOCOLLNPGM("abled");
  5597. return;
  5598. }
  5599. if (parser.seen('S')) {
  5600. servo_probe_test();
  5601. return;
  5602. }
  5603. // Get the range of pins to test or watch
  5604. const uint8_t first_pin = parser.byteval('P'),
  5605. last_pin = parser.seenval('P') ? first_pin : NUM_DIGITAL_PINS - 1;
  5606. if (first_pin > last_pin) return;
  5607. const bool ignore_protection = parser.boolval('I');
  5608. // Watch until click, M108, or reset
  5609. if (parser.boolval('W')) {
  5610. SERIAL_PROTOCOLLNPGM("Watching pins");
  5611. byte pin_state[last_pin - first_pin + 1];
  5612. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5613. if (pin_is_protected(pin) && !ignore_protection) continue;
  5614. pinMode(pin, INPUT_PULLUP);
  5615. delay(1);
  5616. /*
  5617. if (IS_ANALOG(pin))
  5618. pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  5619. else
  5620. //*/
  5621. pin_state[pin - first_pin] = digitalRead(pin);
  5622. }
  5623. #if HAS_RESUME_CONTINUE
  5624. wait_for_user = true;
  5625. KEEPALIVE_STATE(PAUSED_FOR_USER);
  5626. #endif
  5627. for (;;) {
  5628. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  5629. if (pin_is_protected(pin) && !ignore_protection) continue;
  5630. const byte val =
  5631. /*
  5632. IS_ANALOG(pin)
  5633. ? analogRead(pin - analogInputToDigitalPin(0)) : // int16_t val
  5634. :
  5635. //*/
  5636. digitalRead(pin);
  5637. if (val != pin_state[pin - first_pin]) {
  5638. report_pin_state_extended(pin, ignore_protection, false);
  5639. pin_state[pin - first_pin] = val;
  5640. }
  5641. }
  5642. #if HAS_RESUME_CONTINUE
  5643. if (!wait_for_user) {
  5644. KEEPALIVE_STATE(IN_HANDLER);
  5645. break;
  5646. }
  5647. #endif
  5648. safe_delay(200);
  5649. }
  5650. return;
  5651. }
  5652. // Report current state of selected pin(s)
  5653. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  5654. report_pin_state_extended(pin, ignore_protection, true);
  5655. }
  5656. #endif // PINS_DEBUGGING
  5657. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  5658. /**
  5659. * M48: Z probe repeatability measurement function.
  5660. *
  5661. * Usage:
  5662. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  5663. * P = Number of sampled points (4-50, default 10)
  5664. * X = Sample X position
  5665. * Y = Sample Y position
  5666. * V = Verbose level (0-4, default=1)
  5667. * E = Engage Z probe for each reading
  5668. * L = Number of legs of movement before probe
  5669. * S = Schizoid (Or Star if you prefer)
  5670. *
  5671. * This function assumes the bed has been homed. Specifically, that a G28 command
  5672. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  5673. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  5674. * regenerated.
  5675. */
  5676. inline void gcode_M48() {
  5677. if (axis_unhomed_error()) return;
  5678. const int8_t verbose_level = parser.byteval('V', 1);
  5679. if (!WITHIN(verbose_level, 0, 4)) {
  5680. SERIAL_PROTOCOLLNPGM("?(V)erbose level is implausible (0-4).");
  5681. return;
  5682. }
  5683. if (verbose_level > 0)
  5684. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  5685. const int8_t n_samples = parser.byteval('P', 10);
  5686. if (!WITHIN(n_samples, 4, 50)) {
  5687. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  5688. return;
  5689. }
  5690. const bool stow_probe_after_each = parser.boolval('E');
  5691. float X_current = current_position[X_AXIS],
  5692. Y_current = current_position[Y_AXIS];
  5693. const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
  5694. Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);
  5695. #if DISABLED(DELTA)
  5696. if (!WITHIN(X_probe_location, LOGICAL_X_POSITION(MIN_PROBE_X), LOGICAL_X_POSITION(MAX_PROBE_X))) {
  5697. out_of_range_error(PSTR("X"));
  5698. return;
  5699. }
  5700. if (!WITHIN(Y_probe_location, LOGICAL_Y_POSITION(MIN_PROBE_Y), LOGICAL_Y_POSITION(MAX_PROBE_Y))) {
  5701. out_of_range_error(PSTR("Y"));
  5702. return;
  5703. }
  5704. #else
  5705. if (!position_is_reachable_by_probe_xy(X_probe_location, Y_probe_location)) {
  5706. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  5707. return;
  5708. }
  5709. #endif
  5710. bool seen_L = parser.seen('L');
  5711. uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  5712. if (n_legs > 15) {
  5713. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  5714. return;
  5715. }
  5716. if (n_legs == 1) n_legs = 2;
  5717. const bool schizoid_flag = parser.boolval('S');
  5718. if (schizoid_flag && !seen_L) n_legs = 7;
  5719. /**
  5720. * Now get everything to the specified probe point So we can safely do a
  5721. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  5722. * we don't want to use that as a starting point for each probe.
  5723. */
  5724. if (verbose_level > 2)
  5725. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  5726. // Disable bed level correction in M48 because we want the raw data when we probe
  5727. #if HAS_LEVELING
  5728. const bool was_enabled = leveling_is_active();
  5729. set_bed_leveling_enabled(false);
  5730. #endif
  5731. setup_for_endstop_or_probe_move();
  5732. // Move to the first point, deploy, and probe
  5733. const float t = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  5734. if (isnan(t)) return;
  5735. randomSeed(millis());
  5736. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  5737. for (uint8_t n = 0; n < n_samples; n++) {
  5738. if (n_legs) {
  5739. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  5740. float angle = random(0.0, 360.0),
  5741. radius = random(
  5742. #if ENABLED(DELTA)
  5743. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  5744. #else
  5745. 5, X_MAX_LENGTH / 8
  5746. #endif
  5747. );
  5748. if (verbose_level > 3) {
  5749. SERIAL_ECHOPAIR("Starting radius: ", radius);
  5750. SERIAL_ECHOPAIR(" angle: ", angle);
  5751. SERIAL_ECHOPGM(" Direction: ");
  5752. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  5753. SERIAL_ECHOLNPGM("Clockwise");
  5754. }
  5755. for (uint8_t l = 0; l < n_legs - 1; l++) {
  5756. double delta_angle;
  5757. if (schizoid_flag)
  5758. // The points of a 5 point star are 72 degrees apart. We need to
  5759. // skip a point and go to the next one on the star.
  5760. delta_angle = dir * 2.0 * 72.0;
  5761. else
  5762. // If we do this line, we are just trying to move further
  5763. // around the circle.
  5764. delta_angle = dir * (float) random(25, 45);
  5765. angle += delta_angle;
  5766. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  5767. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  5768. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  5769. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  5770. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  5771. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  5772. #if DISABLED(DELTA)
  5773. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  5774. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  5775. #else
  5776. // If we have gone out too far, we can do a simple fix and scale the numbers
  5777. // back in closer to the origin.
  5778. while (!position_is_reachable_by_probe_xy(X_current, Y_current)) {
  5779. X_current *= 0.8;
  5780. Y_current *= 0.8;
  5781. if (verbose_level > 3) {
  5782. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  5783. SERIAL_ECHOLNPAIR(", ", Y_current);
  5784. }
  5785. }
  5786. #endif
  5787. if (verbose_level > 3) {
  5788. SERIAL_PROTOCOLPGM("Going to:");
  5789. SERIAL_ECHOPAIR(" X", X_current);
  5790. SERIAL_ECHOPAIR(" Y", Y_current);
  5791. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  5792. }
  5793. do_blocking_move_to_xy(X_current, Y_current);
  5794. } // n_legs loop
  5795. } // n_legs
  5796. // Probe a single point
  5797. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  5798. /**
  5799. * Get the current mean for the data points we have so far
  5800. */
  5801. double sum = 0.0;
  5802. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  5803. mean = sum / (n + 1);
  5804. NOMORE(min, sample_set[n]);
  5805. NOLESS(max, sample_set[n]);
  5806. /**
  5807. * Now, use that mean to calculate the standard deviation for the
  5808. * data points we have so far
  5809. */
  5810. sum = 0.0;
  5811. for (uint8_t j = 0; j <= n; j++)
  5812. sum += sq(sample_set[j] - mean);
  5813. sigma = SQRT(sum / (n + 1));
  5814. if (verbose_level > 0) {
  5815. if (verbose_level > 1) {
  5816. SERIAL_PROTOCOL(n + 1);
  5817. SERIAL_PROTOCOLPGM(" of ");
  5818. SERIAL_PROTOCOL((int)n_samples);
  5819. SERIAL_PROTOCOLPGM(": z: ");
  5820. SERIAL_PROTOCOL_F(sample_set[n], 3);
  5821. if (verbose_level > 2) {
  5822. SERIAL_PROTOCOLPGM(" mean: ");
  5823. SERIAL_PROTOCOL_F(mean, 4);
  5824. SERIAL_PROTOCOLPGM(" sigma: ");
  5825. SERIAL_PROTOCOL_F(sigma, 6);
  5826. SERIAL_PROTOCOLPGM(" min: ");
  5827. SERIAL_PROTOCOL_F(min, 3);
  5828. SERIAL_PROTOCOLPGM(" max: ");
  5829. SERIAL_PROTOCOL_F(max, 3);
  5830. SERIAL_PROTOCOLPGM(" range: ");
  5831. SERIAL_PROTOCOL_F(max-min, 3);
  5832. }
  5833. SERIAL_EOL();
  5834. }
  5835. }
  5836. } // End of probe loop
  5837. if (STOW_PROBE()) return;
  5838. SERIAL_PROTOCOLPGM("Finished!");
  5839. SERIAL_EOL();
  5840. if (verbose_level > 0) {
  5841. SERIAL_PROTOCOLPGM("Mean: ");
  5842. SERIAL_PROTOCOL_F(mean, 6);
  5843. SERIAL_PROTOCOLPGM(" Min: ");
  5844. SERIAL_PROTOCOL_F(min, 3);
  5845. SERIAL_PROTOCOLPGM(" Max: ");
  5846. SERIAL_PROTOCOL_F(max, 3);
  5847. SERIAL_PROTOCOLPGM(" Range: ");
  5848. SERIAL_PROTOCOL_F(max-min, 3);
  5849. SERIAL_EOL();
  5850. }
  5851. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  5852. SERIAL_PROTOCOL_F(sigma, 6);
  5853. SERIAL_EOL();
  5854. SERIAL_EOL();
  5855. clean_up_after_endstop_or_probe_move();
  5856. // Re-enable bed level correction if it had been on
  5857. #if HAS_LEVELING
  5858. set_bed_leveling_enabled(was_enabled);
  5859. #endif
  5860. report_current_position();
  5861. }
  5862. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  5863. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  5864. inline void gcode_M49() {
  5865. ubl.g26_debug_flag ^= true;
  5866. SERIAL_PROTOCOLPGM("UBL Debug Flag turned ");
  5867. serialprintPGM(ubl.g26_debug_flag ? PSTR("on.") : PSTR("off."));
  5868. }
  5869. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  5870. /**
  5871. * M75: Start print timer
  5872. */
  5873. inline void gcode_M75() { print_job_timer.start(); }
  5874. /**
  5875. * M76: Pause print timer
  5876. */
  5877. inline void gcode_M76() { print_job_timer.pause(); }
  5878. /**
  5879. * M77: Stop print timer
  5880. */
  5881. inline void gcode_M77() { print_job_timer.stop(); }
  5882. #if ENABLED(PRINTCOUNTER)
  5883. /**
  5884. * M78: Show print statistics
  5885. */
  5886. inline void gcode_M78() {
  5887. // "M78 S78" will reset the statistics
  5888. if (parser.intval('S') == 78)
  5889. print_job_timer.initStats();
  5890. else
  5891. print_job_timer.showStats();
  5892. }
  5893. #endif
  5894. /**
  5895. * M104: Set hot end temperature
  5896. */
  5897. inline void gcode_M104() {
  5898. if (get_target_extruder_from_command(104)) return;
  5899. if (DEBUGGING(DRYRUN)) return;
  5900. #if ENABLED(SINGLENOZZLE)
  5901. if (target_extruder != active_extruder) return;
  5902. #endif
  5903. if (parser.seenval('S')) {
  5904. const int16_t temp = parser.value_celsius();
  5905. thermalManager.setTargetHotend(temp, target_extruder);
  5906. #if ENABLED(DUAL_X_CARRIAGE)
  5907. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  5908. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  5909. #endif
  5910. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  5911. /**
  5912. * Stop the timer at the end of print. Start is managed by 'heat and wait' M109.
  5913. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  5914. * standby mode, for instance in a dual extruder setup, without affecting
  5915. * the running print timer.
  5916. */
  5917. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  5918. print_job_timer.stop();
  5919. LCD_MESSAGEPGM(WELCOME_MSG);
  5920. }
  5921. #endif
  5922. if (parser.value_celsius() > thermalManager.degHotend(target_extruder))
  5923. lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  5924. }
  5925. #if ENABLED(AUTOTEMP)
  5926. planner.autotemp_M104_M109();
  5927. #endif
  5928. }
  5929. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  5930. void print_heater_state(const float &c, const float &t,
  5931. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5932. const float r,
  5933. #endif
  5934. const int8_t e=-2
  5935. ) {
  5936. #if !(HAS_TEMP_BED && HAS_TEMP_HOTEND) && HOTENDS <= 1
  5937. UNUSED(e);
  5938. #endif
  5939. SERIAL_PROTOCOLCHAR(' ');
  5940. SERIAL_PROTOCOLCHAR(
  5941. #if HAS_TEMP_BED && HAS_TEMP_HOTEND
  5942. e == -1 ? 'B' : 'T'
  5943. #elif HAS_TEMP_HOTEND
  5944. 'T'
  5945. #else
  5946. 'B'
  5947. #endif
  5948. );
  5949. #if HOTENDS > 1
  5950. if (e >= 0) SERIAL_PROTOCOLCHAR('0' + e);
  5951. #endif
  5952. SERIAL_PROTOCOLCHAR(':');
  5953. SERIAL_PROTOCOL(c);
  5954. SERIAL_PROTOCOLPAIR(" /" , t);
  5955. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5956. SERIAL_PROTOCOLPAIR(" (", r / OVERSAMPLENR);
  5957. SERIAL_PROTOCOLCHAR(')');
  5958. #endif
  5959. }
  5960. void print_heaterstates() {
  5961. #if HAS_TEMP_HOTEND
  5962. print_heater_state(thermalManager.degHotend(target_extruder), thermalManager.degTargetHotend(target_extruder)
  5963. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5964. , thermalManager.rawHotendTemp(target_extruder)
  5965. #endif
  5966. );
  5967. #endif
  5968. #if HAS_TEMP_BED
  5969. print_heater_state(thermalManager.degBed(), thermalManager.degTargetBed(),
  5970. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5971. thermalManager.rawBedTemp(),
  5972. #endif
  5973. -1 // BED
  5974. );
  5975. #endif
  5976. #if HOTENDS > 1
  5977. HOTEND_LOOP() print_heater_state(thermalManager.degHotend(e), thermalManager.degTargetHotend(e),
  5978. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  5979. thermalManager.rawHotendTemp(e),
  5980. #endif
  5981. e
  5982. );
  5983. #endif
  5984. SERIAL_PROTOCOLPGM(" @:");
  5985. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  5986. #if HAS_TEMP_BED
  5987. SERIAL_PROTOCOLPGM(" B@:");
  5988. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  5989. #endif
  5990. #if HOTENDS > 1
  5991. HOTEND_LOOP() {
  5992. SERIAL_PROTOCOLPAIR(" @", e);
  5993. SERIAL_PROTOCOLCHAR(':');
  5994. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  5995. }
  5996. #endif
  5997. }
  5998. #endif
  5999. /**
  6000. * M105: Read hot end and bed temperature
  6001. */
  6002. inline void gcode_M105() {
  6003. if (get_target_extruder_from_command(105)) return;
  6004. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  6005. SERIAL_PROTOCOLPGM(MSG_OK);
  6006. print_heaterstates();
  6007. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  6008. SERIAL_ERROR_START();
  6009. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  6010. #endif
  6011. SERIAL_EOL();
  6012. }
  6013. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  6014. static uint8_t auto_report_temp_interval;
  6015. static millis_t next_temp_report_ms;
  6016. /**
  6017. * M155: Set temperature auto-report interval. M155 S<seconds>
  6018. */
  6019. inline void gcode_M155() {
  6020. if (parser.seenval('S')) {
  6021. auto_report_temp_interval = parser.value_byte();
  6022. NOMORE(auto_report_temp_interval, 60);
  6023. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6024. }
  6025. }
  6026. inline void auto_report_temperatures() {
  6027. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  6028. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  6029. print_heaterstates();
  6030. SERIAL_EOL();
  6031. }
  6032. }
  6033. #endif // AUTO_REPORT_TEMPERATURES
  6034. #if FAN_COUNT > 0
  6035. /**
  6036. * M106: Set Fan Speed
  6037. *
  6038. * S<int> Speed between 0-255
  6039. * P<index> Fan index, if more than one fan
  6040. */
  6041. inline void gcode_M106() {
  6042. uint16_t s = parser.ushortval('S', 255);
  6043. NOMORE(s, 255);
  6044. const uint8_t p = parser.byteval('P', 0);
  6045. if (p < FAN_COUNT) fanSpeeds[p] = s;
  6046. }
  6047. /**
  6048. * M107: Fan Off
  6049. */
  6050. inline void gcode_M107() {
  6051. const uint16_t p = parser.ushortval('P');
  6052. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  6053. }
  6054. #endif // FAN_COUNT > 0
  6055. #if DISABLED(EMERGENCY_PARSER)
  6056. /**
  6057. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  6058. */
  6059. inline void gcode_M108() { wait_for_heatup = false; }
  6060. /**
  6061. * M112: Emergency Stop
  6062. */
  6063. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  6064. /**
  6065. * M410: Quickstop - Abort all planned moves
  6066. *
  6067. * This will stop the carriages mid-move, so most likely they
  6068. * will be out of sync with the stepper position after this.
  6069. */
  6070. inline void gcode_M410() { quickstop_stepper(); }
  6071. #endif
  6072. /**
  6073. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  6074. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  6075. */
  6076. #ifndef MIN_COOLING_SLOPE_DEG
  6077. #define MIN_COOLING_SLOPE_DEG 1.50
  6078. #endif
  6079. #ifndef MIN_COOLING_SLOPE_TIME
  6080. #define MIN_COOLING_SLOPE_TIME 60
  6081. #endif
  6082. inline void gcode_M109() {
  6083. if (get_target_extruder_from_command(109)) return;
  6084. if (DEBUGGING(DRYRUN)) return;
  6085. #if ENABLED(SINGLENOZZLE)
  6086. if (target_extruder != active_extruder) return;
  6087. #endif
  6088. const bool no_wait_for_cooling = parser.seenval('S');
  6089. if (no_wait_for_cooling || parser.seenval('R')) {
  6090. const int16_t temp = parser.value_celsius();
  6091. thermalManager.setTargetHotend(temp, target_extruder);
  6092. #if ENABLED(DUAL_X_CARRIAGE)
  6093. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  6094. thermalManager.setTargetHotend(temp ? temp + duplicate_extruder_temp_offset : 0, 1);
  6095. #endif
  6096. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6097. /**
  6098. * Use half EXTRUDE_MINTEMP to allow nozzles to be put into hot
  6099. * standby mode, (e.g., in a dual extruder setup) without affecting
  6100. * the running print timer.
  6101. */
  6102. if (parser.value_celsius() <= (EXTRUDE_MINTEMP) / 2) {
  6103. print_job_timer.stop();
  6104. LCD_MESSAGEPGM(WELCOME_MSG);
  6105. }
  6106. else
  6107. print_job_timer.start();
  6108. #endif
  6109. if (thermalManager.isHeatingHotend(target_extruder)) lcd_status_printf_P(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  6110. }
  6111. else return;
  6112. #if ENABLED(AUTOTEMP)
  6113. planner.autotemp_M104_M109();
  6114. #endif
  6115. #if TEMP_RESIDENCY_TIME > 0
  6116. millis_t residency_start_ms = 0;
  6117. // Loop until the temperature has stabilized
  6118. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  6119. #else
  6120. // Loop until the temperature is very close target
  6121. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  6122. #endif
  6123. float target_temp = -1.0, old_temp = 9999.0;
  6124. bool wants_to_cool = false;
  6125. wait_for_heatup = true;
  6126. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6127. #if DISABLED(BUSY_WHILE_HEATING)
  6128. KEEPALIVE_STATE(NOT_BUSY);
  6129. #endif
  6130. #if ENABLED(PRINTER_EVENT_LEDS)
  6131. const float start_temp = thermalManager.degHotend(target_extruder);
  6132. uint8_t old_blue = 0;
  6133. #endif
  6134. do {
  6135. // Target temperature might be changed during the loop
  6136. if (target_temp != thermalManager.degTargetHotend(target_extruder)) {
  6137. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  6138. target_temp = thermalManager.degTargetHotend(target_extruder);
  6139. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6140. if (no_wait_for_cooling && wants_to_cool) break;
  6141. }
  6142. now = millis();
  6143. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  6144. next_temp_ms = now + 1000UL;
  6145. print_heaterstates();
  6146. #if TEMP_RESIDENCY_TIME > 0
  6147. SERIAL_PROTOCOLPGM(" W:");
  6148. if (residency_start_ms)
  6149. SERIAL_PROTOCOL(long((((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6150. else
  6151. SERIAL_PROTOCOLCHAR('?');
  6152. #endif
  6153. SERIAL_EOL();
  6154. }
  6155. idle();
  6156. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6157. const float temp = thermalManager.degHotend(target_extruder);
  6158. #if ENABLED(PRINTER_EVENT_LEDS)
  6159. // Gradually change LED strip from violet to red as nozzle heats up
  6160. if (!wants_to_cool) {
  6161. const uint8_t blue = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 255, 0);
  6162. if (blue != old_blue) set_led_color(255, 0, (old_blue = blue));
  6163. }
  6164. #endif
  6165. #if TEMP_RESIDENCY_TIME > 0
  6166. const float temp_diff = FABS(target_temp - temp);
  6167. if (!residency_start_ms) {
  6168. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  6169. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  6170. }
  6171. else if (temp_diff > TEMP_HYSTERESIS) {
  6172. // Restart the timer whenever the temperature falls outside the hysteresis.
  6173. residency_start_ms = now;
  6174. }
  6175. #endif
  6176. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  6177. if (wants_to_cool) {
  6178. // break after MIN_COOLING_SLOPE_TIME seconds
  6179. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  6180. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6181. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  6182. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  6183. old_temp = temp;
  6184. }
  6185. }
  6186. } while (wait_for_heatup && TEMP_CONDITIONS);
  6187. if (wait_for_heatup) {
  6188. LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  6189. #if ENABLED(PRINTER_EVENT_LEDS)
  6190. #if ENABLED(RGBW_LED)
  6191. set_led_color(0, 0, 0, 255); // Turn on the WHITE LED
  6192. #else
  6193. set_led_color(255, 255, 255); // Set LEDs All On
  6194. #endif
  6195. #endif
  6196. }
  6197. #if DISABLED(BUSY_WHILE_HEATING)
  6198. KEEPALIVE_STATE(IN_HANDLER);
  6199. #endif
  6200. }
  6201. #if HAS_TEMP_BED
  6202. #ifndef MIN_COOLING_SLOPE_DEG_BED
  6203. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  6204. #endif
  6205. #ifndef MIN_COOLING_SLOPE_TIME_BED
  6206. #define MIN_COOLING_SLOPE_TIME_BED 60
  6207. #endif
  6208. /**
  6209. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  6210. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  6211. */
  6212. inline void gcode_M190() {
  6213. if (DEBUGGING(DRYRUN)) return;
  6214. LCD_MESSAGEPGM(MSG_BED_HEATING);
  6215. const bool no_wait_for_cooling = parser.seenval('S');
  6216. if (no_wait_for_cooling || parser.seenval('R')) {
  6217. thermalManager.setTargetBed(parser.value_celsius());
  6218. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  6219. if (parser.value_celsius() > BED_MINTEMP)
  6220. print_job_timer.start();
  6221. #endif
  6222. }
  6223. else return;
  6224. #if TEMP_BED_RESIDENCY_TIME > 0
  6225. millis_t residency_start_ms = 0;
  6226. // Loop until the temperature has stabilized
  6227. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  6228. #else
  6229. // Loop until the temperature is very close target
  6230. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  6231. #endif
  6232. float target_temp = -1.0, old_temp = 9999.0;
  6233. bool wants_to_cool = false;
  6234. wait_for_heatup = true;
  6235. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  6236. #if DISABLED(BUSY_WHILE_HEATING)
  6237. KEEPALIVE_STATE(NOT_BUSY);
  6238. #endif
  6239. target_extruder = active_extruder; // for print_heaterstates
  6240. #if ENABLED(PRINTER_EVENT_LEDS)
  6241. const float start_temp = thermalManager.degBed();
  6242. uint8_t old_red = 255;
  6243. #endif
  6244. do {
  6245. // Target temperature might be changed during the loop
  6246. if (target_temp != thermalManager.degTargetBed()) {
  6247. wants_to_cool = thermalManager.isCoolingBed();
  6248. target_temp = thermalManager.degTargetBed();
  6249. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  6250. if (no_wait_for_cooling && wants_to_cool) break;
  6251. }
  6252. now = millis();
  6253. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  6254. next_temp_ms = now + 1000UL;
  6255. print_heaterstates();
  6256. #if TEMP_BED_RESIDENCY_TIME > 0
  6257. SERIAL_PROTOCOLPGM(" W:");
  6258. if (residency_start_ms)
  6259. SERIAL_PROTOCOL(long((((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL));
  6260. else
  6261. SERIAL_PROTOCOLCHAR('?');
  6262. #endif
  6263. SERIAL_EOL();
  6264. }
  6265. idle();
  6266. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  6267. const float temp = thermalManager.degBed();
  6268. #if ENABLED(PRINTER_EVENT_LEDS)
  6269. // Gradually change LED strip from blue to violet as bed heats up
  6270. if (!wants_to_cool) {
  6271. const uint8_t red = map(constrain(temp, start_temp, target_temp), start_temp, target_temp, 0, 255);
  6272. if (red != old_red) set_led_color((old_red = red), 0, 255);
  6273. }
  6274. #endif
  6275. #if TEMP_BED_RESIDENCY_TIME > 0
  6276. const float temp_diff = FABS(target_temp - temp);
  6277. if (!residency_start_ms) {
  6278. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  6279. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  6280. }
  6281. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  6282. // Restart the timer whenever the temperature falls outside the hysteresis.
  6283. residency_start_ms = now;
  6284. }
  6285. #endif // TEMP_BED_RESIDENCY_TIME > 0
  6286. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  6287. if (wants_to_cool) {
  6288. // Break after MIN_COOLING_SLOPE_TIME_BED seconds
  6289. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  6290. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  6291. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  6292. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  6293. old_temp = temp;
  6294. }
  6295. }
  6296. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  6297. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  6298. #if DISABLED(BUSY_WHILE_HEATING)
  6299. KEEPALIVE_STATE(IN_HANDLER);
  6300. #endif
  6301. }
  6302. #endif // HAS_TEMP_BED
  6303. /**
  6304. * M110: Set Current Line Number
  6305. */
  6306. inline void gcode_M110() {
  6307. if (parser.seenval('N')) gcode_LastN = parser.value_long();
  6308. }
  6309. /**
  6310. * M111: Set the debug level
  6311. */
  6312. inline void gcode_M111() {
  6313. marlin_debug_flags = parser.byteval('S', (uint8_t)DEBUG_NONE);
  6314. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  6315. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  6316. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  6317. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  6318. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  6319. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6320. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  6321. #endif
  6322. const static char* const debug_strings[] PROGMEM = {
  6323. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16
  6324. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6325. , str_debug_32
  6326. #endif
  6327. };
  6328. SERIAL_ECHO_START();
  6329. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  6330. if (marlin_debug_flags) {
  6331. uint8_t comma = 0;
  6332. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  6333. if (TEST(marlin_debug_flags, i)) {
  6334. if (comma++) SERIAL_CHAR(',');
  6335. serialprintPGM((char*)pgm_read_word(&debug_strings[i]));
  6336. }
  6337. }
  6338. }
  6339. else {
  6340. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  6341. }
  6342. SERIAL_EOL();
  6343. }
  6344. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  6345. /**
  6346. * M113: Get or set Host Keepalive interval (0 to disable)
  6347. *
  6348. * S<seconds> Optional. Set the keepalive interval.
  6349. */
  6350. inline void gcode_M113() {
  6351. if (parser.seenval('S')) {
  6352. host_keepalive_interval = parser.value_byte();
  6353. NOMORE(host_keepalive_interval, 60);
  6354. }
  6355. else {
  6356. SERIAL_ECHO_START();
  6357. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  6358. }
  6359. }
  6360. #endif
  6361. #if ENABLED(BARICUDA)
  6362. #if HAS_HEATER_1
  6363. /**
  6364. * M126: Heater 1 valve open
  6365. */
  6366. inline void gcode_M126() { baricuda_valve_pressure = parser.byteval('S', 255); }
  6367. /**
  6368. * M127: Heater 1 valve close
  6369. */
  6370. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  6371. #endif
  6372. #if HAS_HEATER_2
  6373. /**
  6374. * M128: Heater 2 valve open
  6375. */
  6376. inline void gcode_M128() { baricuda_e_to_p_pressure = parser.byteval('S', 255); }
  6377. /**
  6378. * M129: Heater 2 valve close
  6379. */
  6380. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  6381. #endif
  6382. #endif // BARICUDA
  6383. /**
  6384. * M140: Set bed temperature
  6385. */
  6386. inline void gcode_M140() {
  6387. if (DEBUGGING(DRYRUN)) return;
  6388. if (parser.seenval('S')) thermalManager.setTargetBed(parser.value_celsius());
  6389. }
  6390. #if ENABLED(ULTIPANEL)
  6391. /**
  6392. * M145: Set the heatup state for a material in the LCD menu
  6393. *
  6394. * S<material> (0=PLA, 1=ABS)
  6395. * H<hotend temp>
  6396. * B<bed temp>
  6397. * F<fan speed>
  6398. */
  6399. inline void gcode_M145() {
  6400. const uint8_t material = (uint8_t)parser.intval('S');
  6401. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  6402. SERIAL_ERROR_START();
  6403. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  6404. }
  6405. else {
  6406. int v;
  6407. if (parser.seenval('H')) {
  6408. v = parser.value_int();
  6409. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  6410. }
  6411. if (parser.seenval('F')) {
  6412. v = parser.value_int();
  6413. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  6414. }
  6415. #if TEMP_SENSOR_BED != 0
  6416. if (parser.seenval('B')) {
  6417. v = parser.value_int();
  6418. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  6419. }
  6420. #endif
  6421. }
  6422. }
  6423. #endif // ULTIPANEL
  6424. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  6425. /**
  6426. * M149: Set temperature units
  6427. */
  6428. inline void gcode_M149() {
  6429. if (parser.seenval('C')) parser.set_input_temp_units(TEMPUNIT_C);
  6430. else if (parser.seenval('K')) parser.set_input_temp_units(TEMPUNIT_K);
  6431. else if (parser.seenval('F')) parser.set_input_temp_units(TEMPUNIT_F);
  6432. }
  6433. #endif
  6434. #if HAS_POWER_SWITCH
  6435. /**
  6436. * M80 : Turn on the Power Supply
  6437. * M80 S : Report the current state and exit
  6438. */
  6439. inline void gcode_M80() {
  6440. // S: Report the current power supply state and exit
  6441. if (parser.seen('S')) {
  6442. serialprintPGM(powersupply_on ? PSTR("PS:1\n") : PSTR("PS:0\n"));
  6443. return;
  6444. }
  6445. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); // GND
  6446. /**
  6447. * If you have a switch on suicide pin, this is useful
  6448. * if you want to start another print with suicide feature after
  6449. * a print without suicide...
  6450. */
  6451. #if HAS_SUICIDE
  6452. OUT_WRITE(SUICIDE_PIN, HIGH);
  6453. #endif
  6454. #if ENABLED(HAVE_TMC2130)
  6455. delay(100);
  6456. tmc2130_init(); // Settings only stick when the driver has power
  6457. #endif
  6458. powersupply_on = true;
  6459. #if ENABLED(ULTIPANEL)
  6460. LCD_MESSAGEPGM(WELCOME_MSG);
  6461. #endif
  6462. }
  6463. #endif // HAS_POWER_SWITCH
  6464. /**
  6465. * M81: Turn off Power, including Power Supply, if there is one.
  6466. *
  6467. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  6468. */
  6469. inline void gcode_M81() {
  6470. thermalManager.disable_all_heaters();
  6471. stepper.finish_and_disable();
  6472. #if FAN_COUNT > 0
  6473. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  6474. #if ENABLED(PROBING_FANS_OFF)
  6475. fans_paused = false;
  6476. ZERO(paused_fanSpeeds);
  6477. #endif
  6478. #endif
  6479. safe_delay(1000); // Wait 1 second before switching off
  6480. #if HAS_SUICIDE
  6481. stepper.synchronize();
  6482. suicide();
  6483. #elif HAS_POWER_SWITCH
  6484. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  6485. powersupply_on = false;
  6486. #endif
  6487. #if ENABLED(ULTIPANEL)
  6488. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  6489. #endif
  6490. }
  6491. /**
  6492. * M82: Set E codes absolute (default)
  6493. */
  6494. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  6495. /**
  6496. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  6497. */
  6498. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  6499. /**
  6500. * M18, M84: Disable stepper motors
  6501. */
  6502. inline void gcode_M18_M84() {
  6503. if (parser.seenval('S')) {
  6504. stepper_inactive_time = parser.value_millis_from_seconds();
  6505. }
  6506. else {
  6507. bool all_axis = !((parser.seen('X')) || (parser.seen('Y')) || (parser.seen('Z')) || (parser.seen('E')));
  6508. if (all_axis) {
  6509. stepper.finish_and_disable();
  6510. }
  6511. else {
  6512. stepper.synchronize();
  6513. if (parser.seen('X')) disable_X();
  6514. if (parser.seen('Y')) disable_Y();
  6515. if (parser.seen('Z')) disable_Z();
  6516. #if E0_ENABLE_PIN != X_ENABLE_PIN && E1_ENABLE_PIN != Y_ENABLE_PIN // Only enable on boards that have separate ENABLE_PINS
  6517. if (parser.seen('E')) disable_e_steppers();
  6518. #endif
  6519. }
  6520. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  6521. ubl_lcd_map_control = defer_return_to_status = false;
  6522. #endif
  6523. }
  6524. }
  6525. /**
  6526. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  6527. */
  6528. inline void gcode_M85() {
  6529. if (parser.seen('S')) max_inactive_time = parser.value_millis_from_seconds();
  6530. }
  6531. /**
  6532. * Multi-stepper support for M92, M201, M203
  6533. */
  6534. #if ENABLED(DISTINCT_E_FACTORS)
  6535. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  6536. #define TARGET_EXTRUDER target_extruder
  6537. #else
  6538. #define GET_TARGET_EXTRUDER(CMD) NOOP
  6539. #define TARGET_EXTRUDER 0
  6540. #endif
  6541. /**
  6542. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  6543. * (Follows the same syntax as G92)
  6544. *
  6545. * With multiple extruders use T to specify which one.
  6546. */
  6547. inline void gcode_M92() {
  6548. GET_TARGET_EXTRUDER(92);
  6549. LOOP_XYZE(i) {
  6550. if (parser.seen(axis_codes[i])) {
  6551. if (i == E_AXIS) {
  6552. const float value = parser.value_per_axis_unit((AxisEnum)(E_AXIS + TARGET_EXTRUDER));
  6553. if (value < 20.0) {
  6554. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  6555. planner.max_jerk[E_AXIS] *= factor;
  6556. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  6557. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  6558. }
  6559. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  6560. }
  6561. else {
  6562. planner.axis_steps_per_mm[i] = parser.value_per_axis_unit((AxisEnum)i);
  6563. }
  6564. }
  6565. }
  6566. planner.refresh_positioning();
  6567. }
  6568. /**
  6569. * Output the current position to serial
  6570. */
  6571. void report_current_position() {
  6572. SERIAL_PROTOCOLPGM("X:");
  6573. SERIAL_PROTOCOL(current_position[X_AXIS]);
  6574. SERIAL_PROTOCOLPGM(" Y:");
  6575. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  6576. SERIAL_PROTOCOLPGM(" Z:");
  6577. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  6578. SERIAL_PROTOCOLPGM(" E:");
  6579. SERIAL_PROTOCOL(current_position[E_AXIS]);
  6580. stepper.report_positions();
  6581. #if IS_SCARA
  6582. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  6583. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  6584. SERIAL_EOL();
  6585. #endif
  6586. }
  6587. #ifdef M114_DETAIL
  6588. void report_xyze(const float pos[XYZE], const uint8_t n = 4, const uint8_t precision = 3) {
  6589. char str[12];
  6590. for (uint8_t i = 0; i < n; i++) {
  6591. SERIAL_CHAR(' ');
  6592. SERIAL_CHAR(axis_codes[i]);
  6593. SERIAL_CHAR(':');
  6594. SERIAL_PROTOCOL(dtostrf(pos[i], 8, precision, str));
  6595. }
  6596. SERIAL_EOL();
  6597. }
  6598. inline void report_xyz(const float pos[XYZ]) { report_xyze(pos, 3); }
  6599. void report_current_position_detail() {
  6600. stepper.synchronize();
  6601. SERIAL_PROTOCOLPGM("\nLogical:");
  6602. report_xyze(current_position);
  6603. SERIAL_PROTOCOLPGM("Raw: ");
  6604. 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]) };
  6605. report_xyz(raw);
  6606. SERIAL_PROTOCOLPGM("Leveled:");
  6607. float leveled[XYZ] = { current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] };
  6608. planner.apply_leveling(leveled);
  6609. report_xyz(leveled);
  6610. SERIAL_PROTOCOLPGM("UnLevel:");
  6611. float unleveled[XYZ] = { leveled[X_AXIS], leveled[Y_AXIS], leveled[Z_AXIS] };
  6612. planner.unapply_leveling(unleveled);
  6613. report_xyz(unleveled);
  6614. #if IS_KINEMATIC
  6615. #if IS_SCARA
  6616. SERIAL_PROTOCOLPGM("ScaraK: ");
  6617. #else
  6618. SERIAL_PROTOCOLPGM("DeltaK: ");
  6619. #endif
  6620. inverse_kinematics(leveled); // writes delta[]
  6621. report_xyz(delta);
  6622. #endif
  6623. SERIAL_PROTOCOLPGM("Stepper:");
  6624. const float step_count[XYZE] = { stepper.position(X_AXIS), stepper.position(Y_AXIS), stepper.position(Z_AXIS), stepper.position(E_AXIS) };
  6625. report_xyze(step_count, 4, 0);
  6626. #if IS_SCARA
  6627. const float deg[XYZ] = {
  6628. stepper.get_axis_position_degrees(A_AXIS),
  6629. stepper.get_axis_position_degrees(B_AXIS)
  6630. };
  6631. SERIAL_PROTOCOLPGM("Degrees:");
  6632. report_xyze(deg, 2);
  6633. #endif
  6634. SERIAL_PROTOCOLPGM("FromStp:");
  6635. get_cartesian_from_steppers(); // writes cartes[XYZ] (with forward kinematics)
  6636. const float from_steppers[XYZE] = { cartes[X_AXIS], cartes[Y_AXIS], cartes[Z_AXIS], stepper.get_axis_position_mm(E_AXIS) };
  6637. report_xyze(from_steppers);
  6638. const float diff[XYZE] = {
  6639. from_steppers[X_AXIS] - leveled[X_AXIS],
  6640. from_steppers[Y_AXIS] - leveled[Y_AXIS],
  6641. from_steppers[Z_AXIS] - leveled[Z_AXIS],
  6642. from_steppers[E_AXIS] - current_position[E_AXIS]
  6643. };
  6644. SERIAL_PROTOCOLPGM("Differ: ");
  6645. report_xyze(diff);
  6646. }
  6647. #endif // M114_DETAIL
  6648. /**
  6649. * M114: Report current position to host
  6650. */
  6651. inline void gcode_M114() {
  6652. #ifdef M114_DETAIL
  6653. if (parser.seen('D')) {
  6654. report_current_position_detail();
  6655. return;
  6656. }
  6657. #endif
  6658. stepper.synchronize();
  6659. report_current_position();
  6660. }
  6661. /**
  6662. * M115: Capabilities string
  6663. */
  6664. inline void gcode_M115() {
  6665. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  6666. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  6667. // EEPROM (M500, M501)
  6668. #if ENABLED(EEPROM_SETTINGS)
  6669. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  6670. #else
  6671. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  6672. #endif
  6673. // AUTOREPORT_TEMP (M155)
  6674. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  6675. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  6676. #else
  6677. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  6678. #endif
  6679. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  6680. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  6681. // Print Job timer M75, M76, M77
  6682. SERIAL_PROTOCOLLNPGM("Cap:PRINT_JOB:1");
  6683. // AUTOLEVEL (G29)
  6684. #if HAS_ABL
  6685. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  6686. #else
  6687. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  6688. #endif
  6689. // Z_PROBE (G30)
  6690. #if HAS_BED_PROBE
  6691. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  6692. #else
  6693. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  6694. #endif
  6695. // MESH_REPORT (M420 V)
  6696. #if HAS_LEVELING
  6697. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:1");
  6698. #else
  6699. SERIAL_PROTOCOLLNPGM("Cap:LEVELING_DATA:0");
  6700. #endif
  6701. // SOFTWARE_POWER (M80, M81)
  6702. #if HAS_POWER_SWITCH
  6703. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  6704. #else
  6705. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  6706. #endif
  6707. // CASE LIGHTS (M355)
  6708. #if HAS_CASE_LIGHT
  6709. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  6710. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  6711. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:1");
  6712. }
  6713. else
  6714. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6715. #else
  6716. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  6717. SERIAL_PROTOCOLLNPGM("Cap:CASE_LIGHT_BRIGHTNESS:0");
  6718. #endif
  6719. // EMERGENCY_PARSER (M108, M112, M410)
  6720. #if ENABLED(EMERGENCY_PARSER)
  6721. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  6722. #else
  6723. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  6724. #endif
  6725. #endif // EXTENDED_CAPABILITIES_REPORT
  6726. }
  6727. /**
  6728. * M117: Set LCD Status Message
  6729. */
  6730. inline void gcode_M117() { lcd_setstatus(parser.string_arg); }
  6731. /**
  6732. * M118: Display a message in the host console.
  6733. *
  6734. * A Append '// ' for an action command, as in OctoPrint
  6735. * E Have the host 'echo:' the text
  6736. */
  6737. inline void gcode_M118() {
  6738. if (parser.boolval('E')) SERIAL_ECHO_START();
  6739. if (parser.boolval('A')) SERIAL_ECHOPGM("// ");
  6740. SERIAL_ECHOLN(parser.string_arg);
  6741. }
  6742. /**
  6743. * M119: Output endstop states to serial output
  6744. */
  6745. inline void gcode_M119() { endstops.M119(); }
  6746. /**
  6747. * M120: Enable endstops and set non-homing endstop state to "enabled"
  6748. */
  6749. inline void gcode_M120() { endstops.enable_globally(true); }
  6750. /**
  6751. * M121: Disable endstops and set non-homing endstop state to "disabled"
  6752. */
  6753. inline void gcode_M121() { endstops.enable_globally(false); }
  6754. #if ENABLED(PARK_HEAD_ON_PAUSE)
  6755. /**
  6756. * M125: Store current position and move to filament change position.
  6757. * Called on pause (by M25) to prevent material leaking onto the
  6758. * object. On resume (M24) the head will be moved back and the
  6759. * print will resume.
  6760. *
  6761. * If Marlin is compiled without SD Card support, M125 can be
  6762. * used directly to pause the print and move to park position,
  6763. * resuming with a button click or M108.
  6764. *
  6765. * L = override retract length
  6766. * X = override X
  6767. * Y = override Y
  6768. * Z = override Z raise
  6769. */
  6770. inline void gcode_M125() {
  6771. // Initial retract before move to filament change position
  6772. const float retract = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  6773. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  6774. - (PAUSE_PARK_RETRACT_LENGTH)
  6775. #endif
  6776. ;
  6777. // Lift Z axis
  6778. const float z_lift = parser.linearval('Z')
  6779. #if PAUSE_PARK_Z_ADD > 0
  6780. + PAUSE_PARK_Z_ADD
  6781. #endif
  6782. ;
  6783. // Move XY axes to filament change position or given position
  6784. const float x_pos = parser.linearval('X')
  6785. #ifdef PAUSE_PARK_X_POS
  6786. + PAUSE_PARK_X_POS
  6787. #endif
  6788. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6789. + (active_extruder ? hotend_offset[X_AXIS][active_extruder] : 0)
  6790. #endif
  6791. ;
  6792. const float y_pos = parser.linearval('Y')
  6793. #ifdef PAUSE_PARK_Y_POS
  6794. + PAUSE_PARK_Y_POS
  6795. #endif
  6796. #if HOTENDS > 1 && DISABLED(DUAL_X_CARRIAGE)
  6797. + (active_extruder ? hotend_offset[Y_AXIS][active_extruder] : 0)
  6798. #endif
  6799. ;
  6800. const bool job_running = print_job_timer.isRunning();
  6801. if (pause_print(retract, z_lift, x_pos, y_pos)) {
  6802. #if DISABLED(SDSUPPORT)
  6803. // Wait for lcd click or M108
  6804. wait_for_filament_reload();
  6805. // Return to print position and continue
  6806. resume_print();
  6807. if (job_running) print_job_timer.start();
  6808. #endif
  6809. }
  6810. }
  6811. #endif // PARK_HEAD_ON_PAUSE
  6812. #if HAS_COLOR_LEDS
  6813. /**
  6814. * M150: Set Status LED Color - Use R-U-B-W for R-G-B-W
  6815. *
  6816. * Always sets all 3 or 4 components. If a component is left out, set to 0.
  6817. *
  6818. * Examples:
  6819. *
  6820. * M150 R255 ; Turn LED red
  6821. * M150 R255 U127 ; Turn LED orange (PWM only)
  6822. * M150 ; Turn LED off
  6823. * M150 R U B ; Turn LED white
  6824. * M150 W ; Turn LED white using a white LED
  6825. *
  6826. */
  6827. inline void gcode_M150() {
  6828. set_led_color(
  6829. parser.seen('R') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6830. parser.seen('U') ? (parser.has_value() ? parser.value_byte() : 255) : 0,
  6831. parser.seen('B') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6832. #if ENABLED(RGBW_LED)
  6833. , parser.seen('W') ? (parser.has_value() ? parser.value_byte() : 255) : 0
  6834. #endif
  6835. );
  6836. }
  6837. #endif // HAS_COLOR_LEDS
  6838. /**
  6839. * M200: Set filament diameter and set E axis units to cubic units
  6840. *
  6841. * T<extruder> - Optional extruder number. Current extruder if omitted.
  6842. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  6843. */
  6844. inline void gcode_M200() {
  6845. if (get_target_extruder_from_command(200)) return;
  6846. if (parser.seen('D')) {
  6847. // setting any extruder filament size disables volumetric on the assumption that
  6848. // slicers either generate in extruder values as cubic mm or as as filament feeds
  6849. // for all extruders
  6850. volumetric_enabled = (parser.value_linear_units() != 0.0);
  6851. if (volumetric_enabled) {
  6852. filament_size[target_extruder] = parser.value_linear_units();
  6853. // make sure all extruders have some sane value for the filament size
  6854. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  6855. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  6856. }
  6857. }
  6858. calculate_volumetric_multipliers();
  6859. }
  6860. /**
  6861. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  6862. *
  6863. * With multiple extruders use T to specify which one.
  6864. */
  6865. inline void gcode_M201() {
  6866. GET_TARGET_EXTRUDER(201);
  6867. LOOP_XYZE(i) {
  6868. if (parser.seen(axis_codes[i])) {
  6869. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6870. planner.max_acceleration_mm_per_s2[a] = parser.value_axis_units((AxisEnum)a);
  6871. }
  6872. }
  6873. // 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)
  6874. planner.reset_acceleration_rates();
  6875. }
  6876. #if 0 // Not used for Sprinter/grbl gen6
  6877. inline void gcode_M202() {
  6878. LOOP_XYZE(i) {
  6879. 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];
  6880. }
  6881. }
  6882. #endif
  6883. /**
  6884. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  6885. *
  6886. * With multiple extruders use T to specify which one.
  6887. */
  6888. inline void gcode_M203() {
  6889. GET_TARGET_EXTRUDER(203);
  6890. LOOP_XYZE(i)
  6891. if (parser.seen(axis_codes[i])) {
  6892. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  6893. planner.max_feedrate_mm_s[a] = parser.value_axis_units((AxisEnum)a);
  6894. }
  6895. }
  6896. /**
  6897. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  6898. *
  6899. * P = Printing moves
  6900. * R = Retract only (no X, Y, Z) moves
  6901. * T = Travel (non printing) moves
  6902. *
  6903. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  6904. */
  6905. inline void gcode_M204() {
  6906. if (parser.seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  6907. planner.travel_acceleration = planner.acceleration = parser.value_linear_units();
  6908. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  6909. }
  6910. if (parser.seen('P')) {
  6911. planner.acceleration = parser.value_linear_units();
  6912. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  6913. }
  6914. if (parser.seen('R')) {
  6915. planner.retract_acceleration = parser.value_linear_units();
  6916. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  6917. }
  6918. if (parser.seen('T')) {
  6919. planner.travel_acceleration = parser.value_linear_units();
  6920. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  6921. }
  6922. }
  6923. /**
  6924. * M205: Set Advanced Settings
  6925. *
  6926. * S = Min Feed Rate (units/s)
  6927. * T = Min Travel Feed Rate (units/s)
  6928. * B = Min Segment Time (µs)
  6929. * X = Max X Jerk (units/sec^2)
  6930. * Y = Max Y Jerk (units/sec^2)
  6931. * Z = Max Z Jerk (units/sec^2)
  6932. * E = Max E Jerk (units/sec^2)
  6933. */
  6934. inline void gcode_M205() {
  6935. if (parser.seen('S')) planner.min_feedrate_mm_s = parser.value_linear_units();
  6936. if (parser.seen('T')) planner.min_travel_feedrate_mm_s = parser.value_linear_units();
  6937. if (parser.seen('B')) planner.min_segment_time = parser.value_millis();
  6938. if (parser.seen('X')) planner.max_jerk[X_AXIS] = parser.value_linear_units();
  6939. if (parser.seen('Y')) planner.max_jerk[Y_AXIS] = parser.value_linear_units();
  6940. if (parser.seen('Z')) planner.max_jerk[Z_AXIS] = parser.value_linear_units();
  6941. if (parser.seen('E')) planner.max_jerk[E_AXIS] = parser.value_linear_units();
  6942. }
  6943. #if HAS_M206_COMMAND
  6944. /**
  6945. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  6946. *
  6947. * *** @thinkyhead: I recommend deprecating M206 for SCARA in favor of M665.
  6948. * *** M206 for SCARA will remain enabled in 1.1.x for compatibility.
  6949. * *** In the next 1.2 release, it will simply be disabled by default.
  6950. */
  6951. inline void gcode_M206() {
  6952. LOOP_XYZ(i)
  6953. if (parser.seen(axis_codes[i]))
  6954. set_home_offset((AxisEnum)i, parser.value_linear_units());
  6955. #if ENABLED(MORGAN_SCARA)
  6956. if (parser.seen('T')) set_home_offset(A_AXIS, parser.value_linear_units()); // Theta
  6957. if (parser.seen('P')) set_home_offset(B_AXIS, parser.value_linear_units()); // Psi
  6958. #endif
  6959. SYNC_PLAN_POSITION_KINEMATIC();
  6960. report_current_position();
  6961. }
  6962. #endif // HAS_M206_COMMAND
  6963. #if ENABLED(DELTA)
  6964. /**
  6965. * M665: Set delta configurations
  6966. *
  6967. * H = delta height
  6968. * L = diagonal rod
  6969. * R = delta radius
  6970. * S = segments per second
  6971. * B = delta calibration radius
  6972. * X = Alpha (Tower 1) angle trim
  6973. * Y = Beta (Tower 2) angle trim
  6974. * Z = Rotate A and B by this angle
  6975. */
  6976. inline void gcode_M665() {
  6977. if (parser.seen('H')) {
  6978. home_offset[Z_AXIS] = parser.value_linear_units() - DELTA_HEIGHT;
  6979. update_software_endstops(Z_AXIS);
  6980. }
  6981. if (parser.seen('L')) delta_diagonal_rod = parser.value_linear_units();
  6982. if (parser.seen('R')) delta_radius = parser.value_linear_units();
  6983. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  6984. if (parser.seen('B')) delta_calibration_radius = parser.value_float();
  6985. if (parser.seen('X')) delta_tower_angle_trim[A_AXIS] = parser.value_float();
  6986. if (parser.seen('Y')) delta_tower_angle_trim[B_AXIS] = parser.value_float();
  6987. if (parser.seen('Z')) { // rotate all 3 axis for Z = 0
  6988. delta_tower_angle_trim[A_AXIS] -= parser.value_float();
  6989. delta_tower_angle_trim[B_AXIS] -= parser.value_float();
  6990. }
  6991. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  6992. }
  6993. /**
  6994. * M666: Set delta endstop adjustment
  6995. */
  6996. inline void gcode_M666() {
  6997. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6998. if (DEBUGGING(LEVELING)) {
  6999. SERIAL_ECHOLNPGM(">>> gcode_M666");
  7000. }
  7001. #endif
  7002. LOOP_XYZ(i) {
  7003. if (parser.seen(axis_codes[i])) {
  7004. endstop_adj[i] = parser.value_linear_units();
  7005. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7006. if (DEBUGGING(LEVELING)) {
  7007. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  7008. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  7009. }
  7010. #endif
  7011. }
  7012. }
  7013. #if ENABLED(DEBUG_LEVELING_FEATURE)
  7014. if (DEBUGGING(LEVELING)) {
  7015. SERIAL_ECHOLNPGM("<<< gcode_M666");
  7016. }
  7017. #endif
  7018. // normalize endstops so all are <=0; set the residue to delta height
  7019. const float z_temp = MAX3(endstop_adj[A_AXIS], endstop_adj[B_AXIS], endstop_adj[C_AXIS]);
  7020. home_offset[Z_AXIS] -= z_temp;
  7021. LOOP_XYZ(i) endstop_adj[i] -= z_temp;
  7022. }
  7023. #elif IS_SCARA
  7024. /**
  7025. * M665: Set SCARA settings
  7026. *
  7027. * Parameters:
  7028. *
  7029. * S[segments-per-second] - Segments-per-second
  7030. * P[theta-psi-offset] - Theta-Psi offset, added to the shoulder (A/X) angle
  7031. * T[theta-offset] - Theta offset, added to the elbow (B/Y) angle
  7032. *
  7033. * A, P, and X are all aliases for the shoulder angle
  7034. * B, T, and Y are all aliases for the elbow angle
  7035. */
  7036. inline void gcode_M665() {
  7037. if (parser.seen('S')) delta_segments_per_second = parser.value_float();
  7038. const bool hasA = parser.seen('A'), hasP = parser.seen('P'), hasX = parser.seen('X');
  7039. const uint8_t sumAPX = hasA + hasP + hasX;
  7040. if (sumAPX == 1)
  7041. home_offset[A_AXIS] = parser.value_float();
  7042. else if (sumAPX > 1) {
  7043. SERIAL_ERROR_START();
  7044. SERIAL_ERRORLNPGM("Only one of A, P, or X is allowed.");
  7045. return;
  7046. }
  7047. const bool hasB = parser.seen('B'), hasT = parser.seen('T'), hasY = parser.seen('Y');
  7048. const uint8_t sumBTY = hasB + hasT + hasY;
  7049. if (sumBTY == 1)
  7050. home_offset[B_AXIS] = parser.value_float();
  7051. else if (sumBTY > 1) {
  7052. SERIAL_ERROR_START();
  7053. SERIAL_ERRORLNPGM("Only one of B, T, or Y is allowed.");
  7054. return;
  7055. }
  7056. }
  7057. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  7058. /**
  7059. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  7060. */
  7061. inline void gcode_M666() {
  7062. if (parser.seen('Z')) z_endstop_adj = parser.value_linear_units();
  7063. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  7064. }
  7065. #endif // !DELTA && Z_DUAL_ENDSTOPS
  7066. #if ENABLED(FWRETRACT)
  7067. /**
  7068. * M207: Set firmware retraction values
  7069. *
  7070. * S[+units] retract_length
  7071. * W[+units] retract_length_swap (multi-extruder)
  7072. * F[units/min] retract_feedrate_mm_s
  7073. * Z[units] retract_zlift
  7074. */
  7075. inline void gcode_M207() {
  7076. if (parser.seen('S')) retract_length = parser.value_axis_units(E_AXIS);
  7077. if (parser.seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7078. if (parser.seen('Z')) retract_zlift = parser.value_linear_units();
  7079. #if EXTRUDERS > 1
  7080. if (parser.seen('W')) retract_length_swap = parser.value_axis_units(E_AXIS);
  7081. #endif
  7082. }
  7083. /**
  7084. * M208: Set firmware un-retraction values
  7085. *
  7086. * S[+units] retract_recover_length (in addition to M207 S*)
  7087. * W[+units] retract_recover_length_swap (multi-extruder)
  7088. * F[units/min] retract_recover_feedrate_mm_s
  7089. */
  7090. inline void gcode_M208() {
  7091. if (parser.seen('S')) retract_recover_length = parser.value_axis_units(E_AXIS);
  7092. if (parser.seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(parser.value_axis_units(E_AXIS));
  7093. #if EXTRUDERS > 1
  7094. if (parser.seen('W')) retract_recover_length_swap = parser.value_axis_units(E_AXIS);
  7095. #endif
  7096. }
  7097. /**
  7098. * M209: Enable automatic retract (M209 S1)
  7099. * For slicers that don't support G10/11, reversed extrude-only
  7100. * moves will be classified as retraction.
  7101. */
  7102. inline void gcode_M209() {
  7103. if (parser.seen('S')) {
  7104. autoretract_enabled = parser.value_bool();
  7105. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  7106. }
  7107. }
  7108. #endif // FWRETRACT
  7109. /**
  7110. * M211: Enable, Disable, and/or Report software endstops
  7111. *
  7112. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  7113. */
  7114. inline void gcode_M211() {
  7115. SERIAL_ECHO_START();
  7116. #if HAS_SOFTWARE_ENDSTOPS
  7117. if (parser.seen('S')) soft_endstops_enabled = parser.value_bool();
  7118. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7119. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  7120. #else
  7121. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  7122. SERIAL_ECHOPGM(MSG_OFF);
  7123. #endif
  7124. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  7125. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  7126. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  7127. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  7128. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  7129. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  7130. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  7131. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  7132. }
  7133. #if HOTENDS > 1
  7134. /**
  7135. * M218 - set hotend offset (in linear units)
  7136. *
  7137. * T<tool>
  7138. * X<xoffset>
  7139. * Y<yoffset>
  7140. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_NOZZLE
  7141. */
  7142. inline void gcode_M218() {
  7143. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  7144. if (parser.seenval('X')) hotend_offset[X_AXIS][target_extruder] = parser.value_linear_units();
  7145. if (parser.seenval('Y')) hotend_offset[Y_AXIS][target_extruder] = parser.value_linear_units();
  7146. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7147. if (parser.seenval('Z')) hotend_offset[Z_AXIS][target_extruder] = parser.value_linear_units();
  7148. #endif
  7149. SERIAL_ECHO_START();
  7150. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  7151. HOTEND_LOOP() {
  7152. SERIAL_CHAR(' ');
  7153. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  7154. SERIAL_CHAR(',');
  7155. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  7156. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_NOZZLE)
  7157. SERIAL_CHAR(',');
  7158. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  7159. #endif
  7160. }
  7161. SERIAL_EOL();
  7162. }
  7163. #endif // HOTENDS > 1
  7164. /**
  7165. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  7166. */
  7167. inline void gcode_M220() {
  7168. if (parser.seenval('S')) feedrate_percentage = parser.value_int();
  7169. }
  7170. /**
  7171. * M221: Set extrusion percentage (M221 T0 S95)
  7172. */
  7173. inline void gcode_M221() {
  7174. if (get_target_extruder_from_command(221)) return;
  7175. if (parser.seenval('S'))
  7176. flow_percentage[target_extruder] = parser.value_int();
  7177. }
  7178. /**
  7179. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  7180. */
  7181. inline void gcode_M226() {
  7182. if (parser.seen('P')) {
  7183. const int pin_number = parser.value_int(),
  7184. pin_state = parser.intval('S', -1); // required pin state - default is inverted
  7185. if (WITHIN(pin_state, -1, 1) && pin_number > -1 && !pin_is_protected(pin_number)) {
  7186. int target = LOW;
  7187. stepper.synchronize();
  7188. pinMode(pin_number, INPUT);
  7189. switch (pin_state) {
  7190. case 1:
  7191. target = HIGH;
  7192. break;
  7193. case 0:
  7194. target = LOW;
  7195. break;
  7196. case -1:
  7197. target = !digitalRead(pin_number);
  7198. break;
  7199. }
  7200. while (digitalRead(pin_number) != target) idle();
  7201. } // pin_state -1 0 1 && pin_number > -1
  7202. } // parser.seen('P')
  7203. }
  7204. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7205. /**
  7206. * M260: Send data to a I2C slave device
  7207. *
  7208. * This is a PoC, the formating and arguments for the GCODE will
  7209. * change to be more compatible, the current proposal is:
  7210. *
  7211. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  7212. *
  7213. * M260 B<byte-1 value in base 10>
  7214. * M260 B<byte-2 value in base 10>
  7215. * M260 B<byte-3 value in base 10>
  7216. *
  7217. * M260 S1 ; Send the buffered data and reset the buffer
  7218. * M260 R1 ; Reset the buffer without sending data
  7219. *
  7220. */
  7221. inline void gcode_M260() {
  7222. // Set the target address
  7223. if (parser.seen('A')) i2c.address(parser.value_byte());
  7224. // Add a new byte to the buffer
  7225. if (parser.seen('B')) i2c.addbyte(parser.value_byte());
  7226. // Flush the buffer to the bus
  7227. if (parser.seen('S')) i2c.send();
  7228. // Reset and rewind the buffer
  7229. else if (parser.seen('R')) i2c.reset();
  7230. }
  7231. /**
  7232. * M261: Request X bytes from I2C slave device
  7233. *
  7234. * Usage: M261 A<slave device address base 10> B<number of bytes>
  7235. */
  7236. inline void gcode_M261() {
  7237. if (parser.seen('A')) i2c.address(parser.value_byte());
  7238. uint8_t bytes = parser.byteval('B', 1);
  7239. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  7240. i2c.relay(bytes);
  7241. }
  7242. else {
  7243. SERIAL_ERROR_START();
  7244. SERIAL_ERRORLN("Bad i2c request");
  7245. }
  7246. }
  7247. #endif // EXPERIMENTAL_I2CBUS
  7248. #if HAS_SERVOS
  7249. /**
  7250. * M280: Get or set servo position. P<index> [S<angle>]
  7251. */
  7252. inline void gcode_M280() {
  7253. if (!parser.seen('P')) return;
  7254. const int servo_index = parser.value_int();
  7255. if (WITHIN(servo_index, 0, NUM_SERVOS - 1)) {
  7256. if (parser.seen('S'))
  7257. MOVE_SERVO(servo_index, parser.value_int());
  7258. else {
  7259. SERIAL_ECHO_START();
  7260. SERIAL_ECHOPAIR(" Servo ", servo_index);
  7261. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  7262. }
  7263. }
  7264. else {
  7265. SERIAL_ERROR_START();
  7266. SERIAL_ECHOPAIR("Servo ", servo_index);
  7267. SERIAL_ECHOLNPGM(" out of range");
  7268. }
  7269. }
  7270. #endif // HAS_SERVOS
  7271. #if HAS_BUZZER
  7272. /**
  7273. * M300: Play beep sound S<frequency Hz> P<duration ms>
  7274. */
  7275. inline void gcode_M300() {
  7276. uint16_t const frequency = parser.ushortval('S', 260);
  7277. uint16_t duration = parser.ushortval('P', 1000);
  7278. // Limits the tone duration to 0-5 seconds.
  7279. NOMORE(duration, 5000);
  7280. BUZZ(duration, frequency);
  7281. }
  7282. #endif // HAS_BUZZER
  7283. #if ENABLED(PIDTEMP)
  7284. /**
  7285. * M301: Set PID parameters P I D (and optionally C, L)
  7286. *
  7287. * P[float] Kp term
  7288. * I[float] Ki term (unscaled)
  7289. * D[float] Kd term (unscaled)
  7290. *
  7291. * With PID_EXTRUSION_SCALING:
  7292. *
  7293. * C[float] Kc term
  7294. * L[float] LPQ length
  7295. */
  7296. inline void gcode_M301() {
  7297. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  7298. // default behaviour (omitting E parameter) is to update for extruder 0 only
  7299. const uint8_t e = parser.byteval('E'); // extruder being updated
  7300. if (e < HOTENDS) { // catch bad input value
  7301. if (parser.seen('P')) PID_PARAM(Kp, e) = parser.value_float();
  7302. if (parser.seen('I')) PID_PARAM(Ki, e) = scalePID_i(parser.value_float());
  7303. if (parser.seen('D')) PID_PARAM(Kd, e) = scalePID_d(parser.value_float());
  7304. #if ENABLED(PID_EXTRUSION_SCALING)
  7305. if (parser.seen('C')) PID_PARAM(Kc, e) = parser.value_float();
  7306. if (parser.seen('L')) lpq_len = parser.value_float();
  7307. NOMORE(lpq_len, LPQ_MAX_LEN);
  7308. #endif
  7309. thermalManager.updatePID();
  7310. SERIAL_ECHO_START();
  7311. #if ENABLED(PID_PARAMS_PER_HOTEND)
  7312. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  7313. #endif // PID_PARAMS_PER_HOTEND
  7314. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  7315. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  7316. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  7317. #if ENABLED(PID_EXTRUSION_SCALING)
  7318. //Kc does not have scaling applied above, or in resetting defaults
  7319. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  7320. #endif
  7321. SERIAL_EOL();
  7322. }
  7323. else {
  7324. SERIAL_ERROR_START();
  7325. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  7326. }
  7327. }
  7328. #endif // PIDTEMP
  7329. #if ENABLED(PIDTEMPBED)
  7330. inline void gcode_M304() {
  7331. if (parser.seen('P')) thermalManager.bedKp = parser.value_float();
  7332. if (parser.seen('I')) thermalManager.bedKi = scalePID_i(parser.value_float());
  7333. if (parser.seen('D')) thermalManager.bedKd = scalePID_d(parser.value_float());
  7334. thermalManager.updatePID();
  7335. SERIAL_ECHO_START();
  7336. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  7337. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  7338. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  7339. }
  7340. #endif // PIDTEMPBED
  7341. #if defined(CHDK) || HAS_PHOTOGRAPH
  7342. /**
  7343. * M240: Trigger a camera by emulating a Canon RC-1
  7344. * See http://www.doc-diy.net/photo/rc-1_hacked/
  7345. */
  7346. inline void gcode_M240() {
  7347. #ifdef CHDK
  7348. OUT_WRITE(CHDK, HIGH);
  7349. chdkHigh = millis();
  7350. chdkActive = true;
  7351. #elif HAS_PHOTOGRAPH
  7352. const uint8_t NUM_PULSES = 16;
  7353. const float PULSE_LENGTH = 0.01524;
  7354. for (int i = 0; i < NUM_PULSES; i++) {
  7355. WRITE(PHOTOGRAPH_PIN, HIGH);
  7356. _delay_ms(PULSE_LENGTH);
  7357. WRITE(PHOTOGRAPH_PIN, LOW);
  7358. _delay_ms(PULSE_LENGTH);
  7359. }
  7360. delay(7.33);
  7361. for (int i = 0; i < NUM_PULSES; i++) {
  7362. WRITE(PHOTOGRAPH_PIN, HIGH);
  7363. _delay_ms(PULSE_LENGTH);
  7364. WRITE(PHOTOGRAPH_PIN, LOW);
  7365. _delay_ms(PULSE_LENGTH);
  7366. }
  7367. #endif // !CHDK && HAS_PHOTOGRAPH
  7368. }
  7369. #endif // CHDK || PHOTOGRAPH_PIN
  7370. #if HAS_LCD_CONTRAST
  7371. /**
  7372. * M250: Read and optionally set the LCD contrast
  7373. */
  7374. inline void gcode_M250() {
  7375. if (parser.seen('C')) set_lcd_contrast(parser.value_int());
  7376. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  7377. SERIAL_PROTOCOL(lcd_contrast);
  7378. SERIAL_EOL();
  7379. }
  7380. #endif // HAS_LCD_CONTRAST
  7381. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7382. /**
  7383. * M302: Allow cold extrudes, or set the minimum extrude temperature
  7384. *
  7385. * S<temperature> sets the minimum extrude temperature
  7386. * P<bool> enables (1) or disables (0) cold extrusion
  7387. *
  7388. * Examples:
  7389. *
  7390. * M302 ; report current cold extrusion state
  7391. * M302 P0 ; enable cold extrusion checking
  7392. * M302 P1 ; disables cold extrusion checking
  7393. * M302 S0 ; always allow extrusion (disables checking)
  7394. * M302 S170 ; only allow extrusion above 170
  7395. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  7396. */
  7397. inline void gcode_M302() {
  7398. const bool seen_S = parser.seen('S');
  7399. if (seen_S) {
  7400. thermalManager.extrude_min_temp = parser.value_celsius();
  7401. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  7402. }
  7403. if (parser.seen('P'))
  7404. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || parser.value_bool();
  7405. else if (!seen_S) {
  7406. // Report current state
  7407. SERIAL_ECHO_START();
  7408. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  7409. SERIAL_ECHOPAIR("abled (min temp ", thermalManager.extrude_min_temp);
  7410. SERIAL_ECHOLNPGM("C)");
  7411. }
  7412. }
  7413. #endif // PREVENT_COLD_EXTRUSION
  7414. /**
  7415. * M303: PID relay autotune
  7416. *
  7417. * S<temperature> sets the target temperature. (default 150C)
  7418. * E<extruder> (-1 for the bed) (default 0)
  7419. * C<cycles>
  7420. * U<bool> with a non-zero value will apply the result to current settings
  7421. */
  7422. inline void gcode_M303() {
  7423. #if HAS_PID_HEATING
  7424. const int e = parser.intval('E'), c = parser.intval('C', 5);
  7425. const bool u = parser.boolval('U');
  7426. int16_t temp = parser.celsiusval('S', e < 0 ? 70 : 150);
  7427. if (WITHIN(e, 0, HOTENDS - 1))
  7428. target_extruder = e;
  7429. #if DISABLED(BUSY_WHILE_HEATING)
  7430. KEEPALIVE_STATE(NOT_BUSY);
  7431. #endif
  7432. thermalManager.PID_autotune(temp, e, c, u);
  7433. #if DISABLED(BUSY_WHILE_HEATING)
  7434. KEEPALIVE_STATE(IN_HANDLER);
  7435. #endif
  7436. #else
  7437. SERIAL_ERROR_START();
  7438. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  7439. #endif
  7440. }
  7441. #if ENABLED(MORGAN_SCARA)
  7442. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  7443. if (IsRunning()) {
  7444. forward_kinematics_SCARA(delta_a, delta_b);
  7445. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  7446. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  7447. destination[Z_AXIS] = current_position[Z_AXIS];
  7448. prepare_move_to_destination();
  7449. return true;
  7450. }
  7451. return false;
  7452. }
  7453. /**
  7454. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  7455. */
  7456. inline bool gcode_M360() {
  7457. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  7458. return SCARA_move_to_cal(0, 120);
  7459. }
  7460. /**
  7461. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  7462. */
  7463. inline bool gcode_M361() {
  7464. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  7465. return SCARA_move_to_cal(90, 130);
  7466. }
  7467. /**
  7468. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  7469. */
  7470. inline bool gcode_M362() {
  7471. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  7472. return SCARA_move_to_cal(60, 180);
  7473. }
  7474. /**
  7475. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  7476. */
  7477. inline bool gcode_M363() {
  7478. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  7479. return SCARA_move_to_cal(50, 90);
  7480. }
  7481. /**
  7482. * M364: SCARA calibration: Move to cal-position PsiC (90 deg to Theta calibration position)
  7483. */
  7484. inline bool gcode_M364() {
  7485. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  7486. return SCARA_move_to_cal(45, 135);
  7487. }
  7488. #endif // SCARA
  7489. #if ENABLED(EXT_SOLENOID)
  7490. void enable_solenoid(const uint8_t num) {
  7491. switch (num) {
  7492. case 0:
  7493. OUT_WRITE(SOL0_PIN, HIGH);
  7494. break;
  7495. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7496. case 1:
  7497. OUT_WRITE(SOL1_PIN, HIGH);
  7498. break;
  7499. #endif
  7500. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7501. case 2:
  7502. OUT_WRITE(SOL2_PIN, HIGH);
  7503. break;
  7504. #endif
  7505. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7506. case 3:
  7507. OUT_WRITE(SOL3_PIN, HIGH);
  7508. break;
  7509. #endif
  7510. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7511. case 4:
  7512. OUT_WRITE(SOL4_PIN, HIGH);
  7513. break;
  7514. #endif
  7515. default:
  7516. SERIAL_ECHO_START();
  7517. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  7518. break;
  7519. }
  7520. }
  7521. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  7522. void disable_all_solenoids() {
  7523. OUT_WRITE(SOL0_PIN, LOW);
  7524. #if HAS_SOLENOID_1 && EXTRUDERS > 1
  7525. OUT_WRITE(SOL1_PIN, LOW);
  7526. #endif
  7527. #if HAS_SOLENOID_2 && EXTRUDERS > 2
  7528. OUT_WRITE(SOL2_PIN, LOW);
  7529. #endif
  7530. #if HAS_SOLENOID_3 && EXTRUDERS > 3
  7531. OUT_WRITE(SOL3_PIN, LOW);
  7532. #endif
  7533. #if HAS_SOLENOID_4 && EXTRUDERS > 4
  7534. OUT_WRITE(SOL4_PIN, LOW);
  7535. #endif
  7536. }
  7537. /**
  7538. * M380: Enable solenoid on the active extruder
  7539. */
  7540. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  7541. /**
  7542. * M381: Disable all solenoids
  7543. */
  7544. inline void gcode_M381() { disable_all_solenoids(); }
  7545. #endif // EXT_SOLENOID
  7546. /**
  7547. * M400: Finish all moves
  7548. */
  7549. inline void gcode_M400() { stepper.synchronize(); }
  7550. #if HAS_BED_PROBE
  7551. /**
  7552. * M401: Engage Z Servo endstop if available
  7553. */
  7554. inline void gcode_M401() { DEPLOY_PROBE(); }
  7555. /**
  7556. * M402: Retract Z Servo endstop if enabled
  7557. */
  7558. inline void gcode_M402() { STOW_PROBE(); }
  7559. #endif // HAS_BED_PROBE
  7560. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7561. /**
  7562. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  7563. */
  7564. inline void gcode_M404() {
  7565. if (parser.seen('W')) {
  7566. filament_width_nominal = parser.value_linear_units();
  7567. }
  7568. else {
  7569. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  7570. SERIAL_PROTOCOLLN(filament_width_nominal);
  7571. }
  7572. }
  7573. /**
  7574. * M405: Turn on filament sensor for control
  7575. */
  7576. inline void gcode_M405() {
  7577. // This is technically a linear measurement, but since it's quantized to centimeters and is a different
  7578. // unit than everything else, it uses parser.value_byte() instead of parser.value_linear_units().
  7579. if (parser.seen('D')) {
  7580. meas_delay_cm = parser.value_byte();
  7581. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  7582. }
  7583. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  7584. const uint8_t temp_ratio = thermalManager.widthFil_to_size_ratio() - 100; // -100 to scale within a signed byte
  7585. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  7586. measurement_delay[i] = temp_ratio;
  7587. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  7588. }
  7589. filament_sensor = true;
  7590. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7591. //SERIAL_PROTOCOL(filament_width_meas);
  7592. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  7593. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  7594. }
  7595. /**
  7596. * M406: Turn off filament sensor for control
  7597. */
  7598. inline void gcode_M406() { filament_sensor = false; }
  7599. /**
  7600. * M407: Get measured filament diameter on serial output
  7601. */
  7602. inline void gcode_M407() {
  7603. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  7604. SERIAL_PROTOCOLLN(filament_width_meas);
  7605. }
  7606. #endif // FILAMENT_WIDTH_SENSOR
  7607. void quickstop_stepper() {
  7608. stepper.quick_stop();
  7609. stepper.synchronize();
  7610. set_current_from_steppers_for_axis(ALL_AXES);
  7611. SYNC_PLAN_POSITION_KINEMATIC();
  7612. }
  7613. #if HAS_LEVELING
  7614. /**
  7615. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  7616. *
  7617. * S[bool] Turns leveling on or off
  7618. * Z[height] Sets the Z fade height (0 or none to disable)
  7619. * V[bool] Verbose - Print the leveling grid
  7620. *
  7621. * With AUTO_BED_LEVELING_UBL only:
  7622. *
  7623. * L[index] Load UBL mesh from index (0 is default)
  7624. */
  7625. inline void gcode_M420() {
  7626. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7627. // L to load a mesh from the EEPROM
  7628. if (parser.seen('L')) {
  7629. #if ENABLED(EEPROM_SETTINGS)
  7630. const int8_t storage_slot = parser.has_value() ? parser.value_int() : ubl.state.storage_slot;
  7631. const int16_t a = settings.calc_num_meshes();
  7632. if (!a) {
  7633. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7634. return;
  7635. }
  7636. if (!WITHIN(storage_slot, 0, a - 1)) {
  7637. SERIAL_PROTOCOLLNPGM("?Invalid storage slot.");
  7638. SERIAL_PROTOCOLLNPAIR("?Use 0 to ", a - 1);
  7639. return;
  7640. }
  7641. settings.load_mesh(storage_slot);
  7642. ubl.state.storage_slot = storage_slot;
  7643. #else
  7644. SERIAL_PROTOCOLLNPGM("?EEPROM storage not available.");
  7645. return;
  7646. #endif
  7647. }
  7648. // L to load a mesh from the EEPROM
  7649. if (parser.seen('L') || parser.seen('V')) {
  7650. ubl.display_map(0); // Currently only supports one map type
  7651. SERIAL_ECHOLNPAIR("UBL_MESH_VALID = ", UBL_MESH_VALID);
  7652. SERIAL_ECHOLNPAIR("ubl.state.storage_slot = ", ubl.state.storage_slot);
  7653. }
  7654. #endif // AUTO_BED_LEVELING_UBL
  7655. // V to print the matrix or mesh
  7656. if (parser.seen('V')) {
  7657. #if ABL_PLANAR
  7658. planner.bed_level_matrix.debug(PSTR("Bed Level Correction Matrix:"));
  7659. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7660. if (leveling_is_valid()) {
  7661. print_bilinear_leveling_grid();
  7662. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7663. bed_level_virt_print();
  7664. #endif
  7665. }
  7666. #elif ENABLED(MESH_BED_LEVELING)
  7667. if (leveling_is_valid()) {
  7668. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  7669. mbl_mesh_report();
  7670. }
  7671. #endif
  7672. }
  7673. const bool to_enable = parser.boolval('S');
  7674. if (parser.seen('S'))
  7675. set_bed_leveling_enabled(to_enable);
  7676. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7677. if (parser.seen('Z')) set_z_fade_height(parser.value_linear_units());
  7678. #endif
  7679. const bool new_status = leveling_is_active();
  7680. if (to_enable && !new_status) {
  7681. SERIAL_ERROR_START();
  7682. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  7683. }
  7684. SERIAL_ECHO_START();
  7685. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  7686. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  7687. SERIAL_ECHO_START();
  7688. SERIAL_ECHOPGM("Fade Height ");
  7689. if (planner.z_fade_height > 0.0)
  7690. SERIAL_ECHOLN(planner.z_fade_height);
  7691. else
  7692. SERIAL_ECHOLNPGM(MSG_OFF);
  7693. #endif
  7694. }
  7695. #endif
  7696. #if ENABLED(MESH_BED_LEVELING)
  7697. /**
  7698. * M421: Set a single Mesh Bed Leveling Z coordinate
  7699. *
  7700. * Usage:
  7701. * M421 X<linear> Y<linear> Z<linear>
  7702. * M421 X<linear> Y<linear> Q<offset>
  7703. * M421 I<xindex> J<yindex> Z<linear>
  7704. * M421 I<xindex> J<yindex> Q<offset>
  7705. */
  7706. inline void gcode_M421() {
  7707. const bool hasX = parser.seen('X'), hasI = parser.seen('I');
  7708. const int8_t ix = hasI ? parser.value_int() : hasX ? mbl.probe_index_x(RAW_X_POSITION(parser.value_linear_units())) : -1;
  7709. const bool hasY = parser.seen('Y'), hasJ = parser.seen('J');
  7710. const int8_t iy = hasJ ? parser.value_int() : hasY ? mbl.probe_index_y(RAW_Y_POSITION(parser.value_linear_units())) : -1;
  7711. const bool hasZ = parser.seen('Z'), hasQ = !hasZ && parser.seen('Q');
  7712. if (int(hasI && hasJ) + int(hasX && hasY) != 1 || !(hasZ || hasQ)) {
  7713. SERIAL_ERROR_START();
  7714. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7715. }
  7716. else if (ix < 0 || iy < 0) {
  7717. SERIAL_ERROR_START();
  7718. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7719. }
  7720. else
  7721. mbl.set_z(ix, iy, parser.value_linear_units() + (hasQ ? mbl.z_values[ix][iy] : 0));
  7722. }
  7723. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7724. /**
  7725. * M421: Set a single Mesh Bed Leveling Z coordinate
  7726. *
  7727. * Usage:
  7728. * M421 I<xindex> J<yindex> Z<linear>
  7729. * M421 I<xindex> J<yindex> Q<offset>
  7730. */
  7731. inline void gcode_M421() {
  7732. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7733. const bool hasI = ix >= 0,
  7734. hasJ = iy >= 0,
  7735. hasZ = parser.seen('Z'),
  7736. hasQ = !hasZ && parser.seen('Q');
  7737. if (!hasI || !hasJ || !(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. z_values[ix][iy] = parser.value_linear_units() + (hasQ ? z_values[ix][iy] : 0);
  7747. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7748. bed_level_virt_interpolate();
  7749. #endif
  7750. }
  7751. }
  7752. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  7753. /**
  7754. * M421: Set a single Mesh Bed Leveling Z coordinate
  7755. *
  7756. * Usage:
  7757. * M421 I<xindex> J<yindex> Z<linear>
  7758. * M421 I<xindex> J<yindex> Q<offset>
  7759. * M421 C Z<linear>
  7760. * M421 C Q<offset>
  7761. */
  7762. inline void gcode_M421() {
  7763. int8_t ix = parser.intval('I', -1), iy = parser.intval('J', -1);
  7764. const bool hasI = ix >= 0,
  7765. hasJ = iy >= 0,
  7766. hasC = parser.seen('C'),
  7767. hasZ = parser.seen('Z'),
  7768. hasQ = !hasZ && parser.seen('Q');
  7769. if (hasC) {
  7770. 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);
  7771. ix = location.x_index;
  7772. iy = location.y_index;
  7773. }
  7774. if (int(hasC) + int(hasI && hasJ) != 1 || !(hasZ || hasQ)) {
  7775. SERIAL_ERROR_START();
  7776. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  7777. }
  7778. else if (!WITHIN(ix, 0, GRID_MAX_POINTS_X - 1) || !WITHIN(iy, 0, GRID_MAX_POINTS_Y - 1)) {
  7779. SERIAL_ERROR_START();
  7780. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  7781. }
  7782. else
  7783. ubl.z_values[ix][iy] = parser.value_linear_units() + (hasQ ? ubl.z_values[ix][iy] : 0);
  7784. }
  7785. #endif // AUTO_BED_LEVELING_UBL
  7786. #if HAS_M206_COMMAND
  7787. /**
  7788. * M428: Set home_offset based on the distance between the
  7789. * current_position and the nearest "reference point."
  7790. * If an axis is past center its endstop position
  7791. * is the reference-point. Otherwise it uses 0. This allows
  7792. * the Z offset to be set near the bed when using a max endstop.
  7793. *
  7794. * M428 can't be used more than 2cm away from 0 or an endstop.
  7795. *
  7796. * Use M206 to set these values directly.
  7797. */
  7798. inline void gcode_M428() {
  7799. bool err = false;
  7800. LOOP_XYZ(i) {
  7801. if (axis_homed[i]) {
  7802. const float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  7803. diff = base - RAW_POSITION(current_position[i], i);
  7804. if (WITHIN(diff, -20, 20)) {
  7805. set_home_offset((AxisEnum)i, diff);
  7806. }
  7807. else {
  7808. SERIAL_ERROR_START();
  7809. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  7810. LCD_ALERTMESSAGEPGM("Err: Too far!");
  7811. BUZZ(200, 40);
  7812. err = true;
  7813. break;
  7814. }
  7815. }
  7816. }
  7817. if (!err) {
  7818. SYNC_PLAN_POSITION_KINEMATIC();
  7819. report_current_position();
  7820. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  7821. BUZZ(100, 659);
  7822. BUZZ(100, 698);
  7823. }
  7824. }
  7825. #endif // HAS_M206_COMMAND
  7826. /**
  7827. * M500: Store settings in EEPROM
  7828. */
  7829. inline void gcode_M500() {
  7830. (void)settings.save();
  7831. }
  7832. /**
  7833. * M501: Read settings from EEPROM
  7834. */
  7835. inline void gcode_M501() {
  7836. (void)settings.load();
  7837. }
  7838. /**
  7839. * M502: Revert to default settings
  7840. */
  7841. inline void gcode_M502() {
  7842. (void)settings.reset();
  7843. }
  7844. #if DISABLED(DISABLE_M503)
  7845. /**
  7846. * M503: print settings currently in memory
  7847. */
  7848. inline void gcode_M503() {
  7849. (void)settings.report(!parser.boolval('S', true));
  7850. }
  7851. #endif
  7852. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7853. /**
  7854. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  7855. */
  7856. inline void gcode_M540() {
  7857. if (parser.seen('S')) stepper.abort_on_endstop_hit = parser.value_bool();
  7858. }
  7859. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  7860. #if HAS_BED_PROBE
  7861. void refresh_zprobe_zoffset(const bool no_babystep/*=false*/) {
  7862. static float last_zoffset = NAN;
  7863. if (!isnan(last_zoffset)) {
  7864. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(BABYSTEP_ZPROBE_OFFSET) || ENABLED(DELTA)
  7865. const float diff = zprobe_zoffset - last_zoffset;
  7866. #endif
  7867. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7868. // Correct bilinear grid for new probe offset
  7869. if (diff) {
  7870. for (uint8_t x = 0; x < GRID_MAX_POINTS_X; x++)
  7871. for (uint8_t y = 0; y < GRID_MAX_POINTS_Y; y++)
  7872. z_values[x][y] -= diff;
  7873. }
  7874. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7875. bed_level_virt_interpolate();
  7876. #endif
  7877. #endif
  7878. #if ENABLED(BABYSTEP_ZPROBE_OFFSET)
  7879. if (!no_babystep && leveling_is_active())
  7880. thermalManager.babystep_axis(Z_AXIS, -LROUND(diff * planner.axis_steps_per_mm[Z_AXIS]));
  7881. #else
  7882. UNUSED(no_babystep);
  7883. #endif
  7884. #if ENABLED(DELTA) // correct the delta_height
  7885. home_offset[Z_AXIS] -= diff;
  7886. #endif
  7887. }
  7888. last_zoffset = zprobe_zoffset;
  7889. }
  7890. inline void gcode_M851() {
  7891. SERIAL_ECHO_START();
  7892. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET " ");
  7893. if (parser.seen('Z')) {
  7894. const float value = parser.value_linear_units();
  7895. if (WITHIN(value, Z_PROBE_OFFSET_RANGE_MIN, Z_PROBE_OFFSET_RANGE_MAX)) {
  7896. zprobe_zoffset = value;
  7897. refresh_zprobe_zoffset();
  7898. SERIAL_ECHO(zprobe_zoffset);
  7899. }
  7900. else
  7901. SERIAL_ECHOPGM(MSG_Z_MIN " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MIN) " " MSG_Z_MAX " " STRINGIFY(Z_PROBE_OFFSET_RANGE_MAX));
  7902. }
  7903. else
  7904. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  7905. SERIAL_EOL();
  7906. }
  7907. #endif // HAS_BED_PROBE
  7908. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  7909. /**
  7910. * M600: Pause for filament change
  7911. *
  7912. * E[distance] - Retract the filament this far (negative value)
  7913. * Z[distance] - Move the Z axis by this distance
  7914. * X[position] - Move to this X position, with Y
  7915. * Y[position] - Move to this Y position, with X
  7916. * U[distance] - Retract distance for removal (negative value) (manual reload)
  7917. * L[distance] - Extrude distance for insertion (positive value) (manual reload)
  7918. * B[count] - Number of times to beep, -1 for indefinite (if equipped with a buzzer)
  7919. *
  7920. * Default values are used for omitted arguments.
  7921. *
  7922. */
  7923. inline void gcode_M600() {
  7924. #if ENABLED(HOME_BEFORE_FILAMENT_CHANGE)
  7925. // Don't allow filament change without homing first
  7926. if (axis_unhomed_error()) home_all_axes();
  7927. #endif
  7928. // Initial retract before move to filament change position
  7929. const float retract = parser.seen('E') ? parser.value_axis_units(E_AXIS) : 0
  7930. #if defined(PAUSE_PARK_RETRACT_LENGTH) && PAUSE_PARK_RETRACT_LENGTH > 0
  7931. - (PAUSE_PARK_RETRACT_LENGTH)
  7932. #endif
  7933. ;
  7934. // Lift Z axis
  7935. const float z_lift = parser.linearval('Z', 0
  7936. #if defined(PAUSE_PARK_Z_ADD) && PAUSE_PARK_Z_ADD > 0
  7937. + PAUSE_PARK_Z_ADD
  7938. #endif
  7939. );
  7940. // Move XY axes to filament exchange position
  7941. const float x_pos = parser.linearval('X', 0
  7942. #ifdef PAUSE_PARK_X_POS
  7943. + PAUSE_PARK_X_POS
  7944. #endif
  7945. );
  7946. const float y_pos = parser.linearval('Y', 0
  7947. #ifdef PAUSE_PARK_Y_POS
  7948. + PAUSE_PARK_Y_POS
  7949. #endif
  7950. );
  7951. // Unload filament
  7952. const float unload_length = parser.seen('U') ? parser.value_axis_units(E_AXIS) : 0
  7953. #if defined(FILAMENT_CHANGE_UNLOAD_LENGTH) && FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  7954. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  7955. #endif
  7956. ;
  7957. // Load filament
  7958. const float load_length = parser.seen('L') ? parser.value_axis_units(E_AXIS) : 0
  7959. #ifdef FILAMENT_CHANGE_LOAD_LENGTH
  7960. + FILAMENT_CHANGE_LOAD_LENGTH
  7961. #endif
  7962. ;
  7963. const int beep_count = parser.intval('B',
  7964. #ifdef FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7965. FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS
  7966. #else
  7967. -1
  7968. #endif
  7969. );
  7970. const bool job_running = print_job_timer.isRunning();
  7971. if (pause_print(retract, z_lift, x_pos, y_pos, unload_length, beep_count, true)) {
  7972. wait_for_filament_reload(beep_count);
  7973. resume_print(load_length, ADVANCED_PAUSE_EXTRUDE_LENGTH, beep_count);
  7974. }
  7975. // Resume the print job timer if it was running
  7976. if (job_running) print_job_timer.start();
  7977. }
  7978. #endif // ADVANCED_PAUSE_FEATURE
  7979. #if ENABLED(MK2_MULTIPLEXER)
  7980. inline void select_multiplexed_stepper(const uint8_t e) {
  7981. stepper.synchronize();
  7982. disable_e_steppers();
  7983. WRITE(E_MUX0_PIN, TEST(e, 0) ? HIGH : LOW);
  7984. WRITE(E_MUX1_PIN, TEST(e, 1) ? HIGH : LOW);
  7985. WRITE(E_MUX2_PIN, TEST(e, 2) ? HIGH : LOW);
  7986. safe_delay(100);
  7987. }
  7988. /**
  7989. * M702: Unload all extruders
  7990. */
  7991. inline void gcode_M702() {
  7992. for (uint8_t s = 0; s < E_STEPPERS; s++) {
  7993. select_multiplexed_stepper(e);
  7994. // TODO: standard unload filament function
  7995. // MK2 firmware behavior:
  7996. // - Make sure temperature is high enough
  7997. // - Raise Z to at least 15 to make room
  7998. // - Extrude 1cm of filament in 1 second
  7999. // - Under 230C quickly purge ~12mm, over 230C purge ~10mm
  8000. // - Change E max feedrate to 80, eject the filament from the tube. Sync.
  8001. // - Restore E max feedrate to 50
  8002. }
  8003. // Go back to the last active extruder
  8004. select_multiplexed_stepper(active_extruder);
  8005. disable_e_steppers();
  8006. }
  8007. #endif // MK2_MULTIPLEXER
  8008. #if ENABLED(DUAL_X_CARRIAGE)
  8009. /**
  8010. * M605: Set dual x-carriage movement mode
  8011. *
  8012. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  8013. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  8014. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  8015. * units x-offset and an optional differential hotend temperature of
  8016. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  8017. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  8018. *
  8019. * Note: the X axis should be homed after changing dual x-carriage mode.
  8020. */
  8021. inline void gcode_M605() {
  8022. stepper.synchronize();
  8023. if (parser.seen('S')) dual_x_carriage_mode = (DualXMode)parser.value_byte();
  8024. switch (dual_x_carriage_mode) {
  8025. case DXC_FULL_CONTROL_MODE:
  8026. case DXC_AUTO_PARK_MODE:
  8027. break;
  8028. case DXC_DUPLICATION_MODE:
  8029. if (parser.seen('X')) duplicate_extruder_x_offset = max(parser.value_linear_units(), X2_MIN_POS - x_home_pos(0));
  8030. if (parser.seen('R')) duplicate_extruder_temp_offset = parser.value_celsius_diff();
  8031. SERIAL_ECHO_START();
  8032. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  8033. SERIAL_CHAR(' ');
  8034. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  8035. SERIAL_CHAR(',');
  8036. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  8037. SERIAL_CHAR(' ');
  8038. SERIAL_ECHO(duplicate_extruder_x_offset);
  8039. SERIAL_CHAR(',');
  8040. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  8041. break;
  8042. default:
  8043. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  8044. break;
  8045. }
  8046. active_extruder_parked = false;
  8047. extruder_duplication_enabled = false;
  8048. delayed_move_time = 0;
  8049. }
  8050. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  8051. inline void gcode_M605() {
  8052. stepper.synchronize();
  8053. extruder_duplication_enabled = parser.intval('S') == (int)DXC_DUPLICATION_MODE;
  8054. SERIAL_ECHO_START();
  8055. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  8056. }
  8057. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  8058. #if ENABLED(LIN_ADVANCE)
  8059. /**
  8060. * M900: Set and/or Get advance K factor and WH/D ratio
  8061. *
  8062. * K<factor> Set advance K factor
  8063. * R<ratio> Set ratio directly (overrides WH/D)
  8064. * W<width> H<height> D<diam> Set ratio from WH/D
  8065. */
  8066. inline void gcode_M900() {
  8067. stepper.synchronize();
  8068. const float newK = parser.floatval('K', -1);
  8069. if (newK >= 0) planner.extruder_advance_k = newK;
  8070. float newR = parser.floatval('R', -1);
  8071. if (newR < 0) {
  8072. const float newD = parser.floatval('D', -1),
  8073. newW = parser.floatval('W', -1),
  8074. newH = parser.floatval('H', -1);
  8075. if (newD >= 0 && newW >= 0 && newH >= 0)
  8076. newR = newD ? (newW * newH) / (sq(newD * 0.5) * M_PI) : 0;
  8077. }
  8078. if (newR >= 0) planner.advance_ed_ratio = newR;
  8079. SERIAL_ECHO_START();
  8080. SERIAL_ECHOPAIR("Advance K=", planner.extruder_advance_k);
  8081. SERIAL_ECHOPGM(" E/D=");
  8082. const float ratio = planner.advance_ed_ratio;
  8083. if (ratio) SERIAL_ECHO(ratio); else SERIAL_ECHOPGM("Auto");
  8084. SERIAL_EOL();
  8085. }
  8086. #endif // LIN_ADVANCE
  8087. #if ENABLED(HAVE_TMC2130)
  8088. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  8089. SERIAL_CHAR(name);
  8090. SERIAL_ECHOPGM(" axis driver current: ");
  8091. SERIAL_ECHOLN(st.getCurrent());
  8092. }
  8093. static void tmc2130_set_current(TMC2130Stepper &st, const char name, const int mA) {
  8094. st.setCurrent(mA, R_SENSE, HOLD_MULTIPLIER);
  8095. tmc2130_get_current(st, name);
  8096. }
  8097. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  8098. SERIAL_CHAR(name);
  8099. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  8100. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  8101. SERIAL_EOL();
  8102. }
  8103. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  8104. st.clear_otpw();
  8105. SERIAL_CHAR(name);
  8106. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  8107. }
  8108. static void tmc2130_get_pwmthrs(TMC2130Stepper &st, const char name, const uint16_t spmm) {
  8109. SERIAL_CHAR(name);
  8110. SERIAL_ECHOPGM(" stealthChop max speed set to ");
  8111. SERIAL_ECHOLN(12650000UL * st.microsteps() / (256 * st.stealth_max_speed() * spmm));
  8112. }
  8113. static void tmc2130_set_pwmthrs(TMC2130Stepper &st, const char name, const int32_t thrs, const uint32_t spmm) {
  8114. st.stealth_max_speed(12650000UL * st.microsteps() / (256 * thrs * spmm));
  8115. tmc2130_get_pwmthrs(st, name, spmm);
  8116. }
  8117. static void tmc2130_get_sgt(TMC2130Stepper &st, const char name) {
  8118. SERIAL_CHAR(name);
  8119. SERIAL_ECHOPGM(" driver homing sensitivity set to ");
  8120. SERIAL_ECHOLN(st.sgt());
  8121. }
  8122. static void tmc2130_set_sgt(TMC2130Stepper &st, const char name, const int8_t sgt_val) {
  8123. st.sgt(sgt_val);
  8124. tmc2130_get_sgt(st, name);
  8125. }
  8126. /**
  8127. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  8128. * Report driver currents when no axis specified
  8129. *
  8130. * S1: Enable automatic current control
  8131. * S0: Disable
  8132. */
  8133. inline void gcode_M906() {
  8134. uint16_t values[XYZE];
  8135. LOOP_XYZE(i)
  8136. values[i] = parser.intval(axis_codes[i]);
  8137. #if ENABLED(X_IS_TMC2130)
  8138. if (values[X_AXIS]) tmc2130_set_current(stepperX, 'X', values[X_AXIS]);
  8139. else tmc2130_get_current(stepperX, 'X');
  8140. #endif
  8141. #if ENABLED(Y_IS_TMC2130)
  8142. if (values[Y_AXIS]) tmc2130_set_current(stepperY, 'Y', values[Y_AXIS]);
  8143. else tmc2130_get_current(stepperY, 'Y');
  8144. #endif
  8145. #if ENABLED(Z_IS_TMC2130)
  8146. if (values[Z_AXIS]) tmc2130_set_current(stepperZ, 'Z', values[Z_AXIS]);
  8147. else tmc2130_get_current(stepperZ, 'Z');
  8148. #endif
  8149. #if ENABLED(E0_IS_TMC2130)
  8150. if (values[E_AXIS]) tmc2130_set_current(stepperE0, 'E', values[E_AXIS]);
  8151. else tmc2130_get_current(stepperE0, 'E');
  8152. #endif
  8153. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8154. if (parser.seen('S')) auto_current_control = parser.value_bool();
  8155. #endif
  8156. }
  8157. /**
  8158. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  8159. * The flag is held by the library and persist until manually cleared by M912
  8160. */
  8161. inline void gcode_M911() {
  8162. const bool reportX = parser.seen('X'), reportY = parser.seen('Y'), reportZ = parser.seen('Z'), reportE = parser.seen('E'),
  8163. reportAll = (!reportX && !reportY && !reportZ && !reportE) || (reportX && reportY && reportZ && reportE);
  8164. #if ENABLED(X_IS_TMC2130)
  8165. if (reportX || reportAll) tmc2130_report_otpw(stepperX, 'X');
  8166. #endif
  8167. #if ENABLED(Y_IS_TMC2130)
  8168. if (reportY || reportAll) tmc2130_report_otpw(stepperY, 'Y');
  8169. #endif
  8170. #if ENABLED(Z_IS_TMC2130)
  8171. if (reportZ || reportAll) tmc2130_report_otpw(stepperZ, 'Z');
  8172. #endif
  8173. #if ENABLED(E0_IS_TMC2130)
  8174. if (reportE || reportAll) tmc2130_report_otpw(stepperE0, 'E');
  8175. #endif
  8176. }
  8177. /**
  8178. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  8179. */
  8180. inline void gcode_M912() {
  8181. const bool clearX = parser.seen('X'), clearY = parser.seen('Y'), clearZ = parser.seen('Z'), clearE = parser.seen('E'),
  8182. clearAll = (!clearX && !clearY && !clearZ && !clearE) || (clearX && clearY && clearZ && clearE);
  8183. #if ENABLED(X_IS_TMC2130)
  8184. if (clearX || clearAll) tmc2130_clear_otpw(stepperX, 'X');
  8185. #endif
  8186. #if ENABLED(Y_IS_TMC2130)
  8187. if (clearY || clearAll) tmc2130_clear_otpw(stepperY, 'Y');
  8188. #endif
  8189. #if ENABLED(Z_IS_TMC2130)
  8190. if (clearZ || clearAll) tmc2130_clear_otpw(stepperZ, 'Z');
  8191. #endif
  8192. #if ENABLED(E0_IS_TMC2130)
  8193. if (clearE || clearAll) tmc2130_clear_otpw(stepperE0, 'E');
  8194. #endif
  8195. }
  8196. /**
  8197. * M913: Set HYBRID_THRESHOLD speed.
  8198. */
  8199. #if ENABLED(HYBRID_THRESHOLD)
  8200. inline void gcode_M913() {
  8201. uint16_t values[XYZE];
  8202. LOOP_XYZE(i)
  8203. values[i] = parser.intval(axis_codes[i]);
  8204. #if ENABLED(X_IS_TMC2130)
  8205. if (values[X_AXIS]) tmc2130_set_pwmthrs(stepperX, 'X', values[X_AXIS], planner.axis_steps_per_mm[X_AXIS]);
  8206. else tmc2130_get_pwmthrs(stepperX, 'X', planner.axis_steps_per_mm[X_AXIS]);
  8207. #endif
  8208. #if ENABLED(Y_IS_TMC2130)
  8209. if (values[Y_AXIS]) tmc2130_set_pwmthrs(stepperY, 'Y', values[Y_AXIS], planner.axis_steps_per_mm[Y_AXIS]);
  8210. else tmc2130_get_pwmthrs(stepperY, 'Y', planner.axis_steps_per_mm[Y_AXIS]);
  8211. #endif
  8212. #if ENABLED(Z_IS_TMC2130)
  8213. if (values[Z_AXIS]) tmc2130_set_pwmthrs(stepperZ, 'Z', values[Z_AXIS], planner.axis_steps_per_mm[Z_AXIS]);
  8214. else tmc2130_get_pwmthrs(stepperZ, 'Z', planner.axis_steps_per_mm[Z_AXIS]);
  8215. #endif
  8216. #if ENABLED(E0_IS_TMC2130)
  8217. if (values[E_AXIS]) tmc2130_set_pwmthrs(stepperE0, 'E', values[E_AXIS], planner.axis_steps_per_mm[E_AXIS]);
  8218. else tmc2130_get_pwmthrs(stepperE0, 'E', planner.axis_steps_per_mm[E_AXIS]);
  8219. #endif
  8220. }
  8221. #endif // HYBRID_THRESHOLD
  8222. /**
  8223. * M914: Set SENSORLESS_HOMING sensitivity.
  8224. */
  8225. #if ENABLED(SENSORLESS_HOMING)
  8226. inline void gcode_M914() {
  8227. #if ENABLED(X_IS_TMC2130)
  8228. if (parser.seen(axis_codes[X_AXIS])) tmc2130_set_sgt(stepperX, 'X', parser.value_int());
  8229. else tmc2130_get_sgt(stepperX, 'X');
  8230. #endif
  8231. #if ENABLED(Y_IS_TMC2130)
  8232. if (parser.seen(axis_codes[Y_AXIS])) tmc2130_set_sgt(stepperY, 'Y', parser.value_int());
  8233. else tmc2130_get_sgt(stepperY, 'Y');
  8234. #endif
  8235. }
  8236. #endif // SENSORLESS_HOMING
  8237. #endif // HAVE_TMC2130
  8238. /**
  8239. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  8240. */
  8241. inline void gcode_M907() {
  8242. #if HAS_DIGIPOTSS
  8243. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.digipot_current(i, parser.value_int());
  8244. if (parser.seen('B')) stepper.digipot_current(4, parser.value_int());
  8245. if (parser.seen('S')) for (uint8_t i = 0; i <= 4; i++) stepper.digipot_current(i, parser.value_int());
  8246. #elif HAS_MOTOR_CURRENT_PWM
  8247. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  8248. if (parser.seen('X')) stepper.digipot_current(0, parser.value_int());
  8249. #endif
  8250. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  8251. if (parser.seen('Z')) stepper.digipot_current(1, parser.value_int());
  8252. #endif
  8253. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  8254. if (parser.seen('E')) stepper.digipot_current(2, parser.value_int());
  8255. #endif
  8256. #endif
  8257. #if ENABLED(DIGIPOT_I2C)
  8258. // this one uses actual amps in floating point
  8259. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) digipot_i2c_set_current(i, parser.value_float());
  8260. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  8261. 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());
  8262. #endif
  8263. #if ENABLED(DAC_STEPPER_CURRENT)
  8264. if (parser.seen('S')) {
  8265. const float dac_percent = parser.value_float();
  8266. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  8267. }
  8268. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) dac_current_percent(i, parser.value_float());
  8269. #endif
  8270. }
  8271. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  8272. /**
  8273. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  8274. */
  8275. inline void gcode_M908() {
  8276. #if HAS_DIGIPOTSS
  8277. stepper.digitalPotWrite(
  8278. parser.intval('P'),
  8279. parser.intval('S')
  8280. );
  8281. #endif
  8282. #ifdef DAC_STEPPER_CURRENT
  8283. dac_current_raw(
  8284. parser.byteval('P', -1),
  8285. parser.ushortval('S', 0)
  8286. );
  8287. #endif
  8288. }
  8289. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  8290. inline void gcode_M909() { dac_print_values(); }
  8291. inline void gcode_M910() { dac_commit_eeprom(); }
  8292. #endif
  8293. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  8294. #if HAS_MICROSTEPS
  8295. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  8296. inline void gcode_M350() {
  8297. if (parser.seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, parser.value_byte());
  8298. LOOP_XYZE(i) if (parser.seen(axis_codes[i])) stepper.microstep_mode(i, parser.value_byte());
  8299. if (parser.seen('B')) stepper.microstep_mode(4, parser.value_byte());
  8300. stepper.microstep_readings();
  8301. }
  8302. /**
  8303. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  8304. * S# determines MS1 or MS2, X# sets the pin high/low.
  8305. */
  8306. inline void gcode_M351() {
  8307. if (parser.seenval('S')) switch (parser.value_byte()) {
  8308. case 1:
  8309. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, parser.value_byte(), -1);
  8310. if (parser.seenval('B')) stepper.microstep_ms(4, parser.value_byte(), -1);
  8311. break;
  8312. case 2:
  8313. LOOP_XYZE(i) if (parser.seenval(axis_codes[i])) stepper.microstep_ms(i, -1, parser.value_byte());
  8314. if (parser.seenval('B')) stepper.microstep_ms(4, -1, parser.value_byte());
  8315. break;
  8316. }
  8317. stepper.microstep_readings();
  8318. }
  8319. #endif // HAS_MICROSTEPS
  8320. #if HAS_CASE_LIGHT
  8321. #ifndef INVERT_CASE_LIGHT
  8322. #define INVERT_CASE_LIGHT false
  8323. #endif
  8324. int case_light_brightness; // LCD routine wants INT
  8325. bool case_light_on;
  8326. void update_case_light() {
  8327. pinMode(CASE_LIGHT_PIN, OUTPUT); // digitalWrite doesn't set the port mode
  8328. uint8_t case_light_bright = (uint8_t)case_light_brightness;
  8329. if (case_light_on) {
  8330. if (USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) {
  8331. analogWrite(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? 255 - case_light_brightness : case_light_brightness );
  8332. }
  8333. else WRITE(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? LOW : HIGH);
  8334. }
  8335. else WRITE(CASE_LIGHT_PIN, INVERT_CASE_LIGHT ? HIGH : LOW);
  8336. }
  8337. #endif // HAS_CASE_LIGHT
  8338. /**
  8339. * M355: Turn case light on/off and set brightness
  8340. *
  8341. * P<byte> Set case light brightness (PWM pin required - ignored otherwise)
  8342. *
  8343. * S<bool> Set case light on/off
  8344. *
  8345. * When S turns on the light on a PWM pin then the current brightness level is used/restored
  8346. *
  8347. * M355 P200 S0 turns off the light & sets the brightness level
  8348. * M355 S1 turns on the light with a brightness of 200 (assuming a PWM pin)
  8349. */
  8350. inline void gcode_M355() {
  8351. #if HAS_CASE_LIGHT
  8352. uint8_t args = 0;
  8353. if (parser.seenval('P')) ++args, case_light_brightness = parser.value_byte();
  8354. if (parser.seenval('S')) ++args, case_light_on = parser.value_bool();
  8355. if (args) update_case_light();
  8356. // always report case light status
  8357. SERIAL_ECHO_START();
  8358. if (!case_light_on) {
  8359. SERIAL_ECHOLN("Case light: off");
  8360. }
  8361. else {
  8362. if (!USEABLE_HARDWARE_PWM(CASE_LIGHT_PIN)) SERIAL_ECHOLN("Case light: on");
  8363. else SERIAL_ECHOLNPAIR("Case light: ", case_light_brightness);
  8364. }
  8365. #else
  8366. SERIAL_ERROR_START();
  8367. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  8368. #endif // HAS_CASE_LIGHT
  8369. }
  8370. #if ENABLED(MIXING_EXTRUDER)
  8371. /**
  8372. * M163: Set a single mix factor for a mixing extruder
  8373. * This is called "weight" by some systems.
  8374. *
  8375. * S[index] The channel index to set
  8376. * P[float] The mix value
  8377. *
  8378. */
  8379. inline void gcode_M163() {
  8380. const int mix_index = parser.intval('S');
  8381. if (mix_index < MIXING_STEPPERS) {
  8382. float mix_value = parser.floatval('P');
  8383. NOLESS(mix_value, 0.0);
  8384. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  8385. }
  8386. }
  8387. #if MIXING_VIRTUAL_TOOLS > 1
  8388. /**
  8389. * M164: Store the current mix factors as a virtual tool.
  8390. *
  8391. * S[index] The virtual tool to store
  8392. *
  8393. */
  8394. inline void gcode_M164() {
  8395. const int tool_index = parser.intval('S');
  8396. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  8397. normalize_mix();
  8398. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8399. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  8400. }
  8401. }
  8402. #endif
  8403. #if ENABLED(DIRECT_MIXING_IN_G1)
  8404. /**
  8405. * M165: Set multiple mix factors for a mixing extruder.
  8406. * Factors that are left out will be set to 0.
  8407. * All factors together must add up to 1.0.
  8408. *
  8409. * A[factor] Mix factor for extruder stepper 1
  8410. * B[factor] Mix factor for extruder stepper 2
  8411. * C[factor] Mix factor for extruder stepper 3
  8412. * D[factor] Mix factor for extruder stepper 4
  8413. * H[factor] Mix factor for extruder stepper 5
  8414. * I[factor] Mix factor for extruder stepper 6
  8415. *
  8416. */
  8417. inline void gcode_M165() { gcode_get_mix(); }
  8418. #endif
  8419. #endif // MIXING_EXTRUDER
  8420. /**
  8421. * M999: Restart after being stopped
  8422. *
  8423. * Default behaviour is to flush the serial buffer and request
  8424. * a resend to the host starting on the last N line received.
  8425. *
  8426. * Sending "M999 S1" will resume printing without flushing the
  8427. * existing command buffer.
  8428. *
  8429. */
  8430. inline void gcode_M999() {
  8431. Running = true;
  8432. lcd_reset_alert_level();
  8433. if (parser.boolval('S')) return;
  8434. // gcode_LastN = Stopped_gcode_LastN;
  8435. FlushSerialRequestResend();
  8436. }
  8437. #if ENABLED(SWITCHING_EXTRUDER)
  8438. #if EXTRUDERS > 3
  8439. #define REQ_ANGLES 4
  8440. #define _SERVO_NR (e < 2 ? SWITCHING_EXTRUDER_SERVO_NR : SWITCHING_EXTRUDER_E23_SERVO_NR)
  8441. #else
  8442. #define REQ_ANGLES 2
  8443. #define _SERVO_NR SWITCHING_EXTRUDER_SERVO_NR
  8444. #endif
  8445. inline void move_extruder_servo(const uint8_t e) {
  8446. constexpr int16_t angles[] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  8447. static_assert(COUNT(angles) == REQ_ANGLES, "SWITCHING_EXTRUDER_SERVO_ANGLES needs " STRINGIFY(REQ_ANGLES) " angles.");
  8448. stepper.synchronize();
  8449. #if EXTRUDERS & 1
  8450. if (e < EXTRUDERS - 1)
  8451. #endif
  8452. {
  8453. MOVE_SERVO(_SERVO_NR, angles[e]);
  8454. safe_delay(500);
  8455. }
  8456. }
  8457. #endif // SWITCHING_EXTRUDER
  8458. #if ENABLED(SWITCHING_NOZZLE)
  8459. inline void move_nozzle_servo(const uint8_t e) {
  8460. const int16_t angles[2] = SWITCHING_NOZZLE_SERVO_ANGLES;
  8461. stepper.synchronize();
  8462. MOVE_SERVO(SWITCHING_NOZZLE_SERVO_NR, angles[e]);
  8463. safe_delay(500);
  8464. }
  8465. #endif
  8466. inline void invalid_extruder_error(const uint8_t e) {
  8467. SERIAL_ECHO_START();
  8468. SERIAL_CHAR('T');
  8469. SERIAL_ECHO_F(e, DEC);
  8470. SERIAL_CHAR(' ');
  8471. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  8472. }
  8473. /**
  8474. * Perform a tool-change, which may result in moving the
  8475. * previous tool out of the way and the new tool into place.
  8476. */
  8477. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  8478. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8479. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  8480. return invalid_extruder_error(tmp_extruder);
  8481. // T0-Tnnn: Switch virtual tool by changing the mix
  8482. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  8483. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  8484. #else // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8485. if (tmp_extruder >= EXTRUDERS)
  8486. return invalid_extruder_error(tmp_extruder);
  8487. #if HOTENDS > 1
  8488. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  8489. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  8490. if (tmp_extruder != active_extruder) {
  8491. if (!no_move && axis_unhomed_error()) {
  8492. SERIAL_ECHOLNPGM("No move on toolchange");
  8493. no_move = true;
  8494. }
  8495. // Save current position to destination, for use later
  8496. set_destination_to_current();
  8497. #if ENABLED(DUAL_X_CARRIAGE)
  8498. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8499. if (DEBUGGING(LEVELING)) {
  8500. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  8501. switch (dual_x_carriage_mode) {
  8502. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  8503. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  8504. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  8505. }
  8506. }
  8507. #endif
  8508. const float xhome = x_home_pos(active_extruder);
  8509. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  8510. && IsRunning()
  8511. && (delayed_move_time || current_position[X_AXIS] != xhome)
  8512. ) {
  8513. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  8514. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8515. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  8516. #endif
  8517. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8518. if (DEBUGGING(LEVELING)) {
  8519. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  8520. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  8521. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  8522. }
  8523. #endif
  8524. // Park old head: 1) raise 2) move to park position 3) lower
  8525. for (uint8_t i = 0; i < 3; i++)
  8526. planner.buffer_line(
  8527. i == 0 ? current_position[X_AXIS] : xhome,
  8528. current_position[Y_AXIS],
  8529. i == 2 ? current_position[Z_AXIS] : raised_z,
  8530. current_position[E_AXIS],
  8531. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  8532. active_extruder
  8533. );
  8534. stepper.synchronize();
  8535. }
  8536. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  8537. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  8538. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  8539. // Activate the new extruder
  8540. active_extruder = tmp_extruder;
  8541. // This function resets the max/min values - the current position may be overwritten below.
  8542. set_axis_is_at_home(X_AXIS);
  8543. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8544. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  8545. #endif
  8546. // Only when auto-parking are carriages safe to move
  8547. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  8548. switch (dual_x_carriage_mode) {
  8549. case DXC_FULL_CONTROL_MODE:
  8550. // New current position is the position of the activated extruder
  8551. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8552. // Save the inactive extruder's position (from the old current_position)
  8553. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8554. break;
  8555. case DXC_AUTO_PARK_MODE:
  8556. // record raised toolhead position for use by unpark
  8557. COPY(raised_parked_position, current_position);
  8558. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  8559. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  8560. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  8561. #endif
  8562. active_extruder_parked = true;
  8563. delayed_move_time = 0;
  8564. break;
  8565. case DXC_DUPLICATION_MODE:
  8566. // If the new extruder is the left one, set it "parked"
  8567. // This triggers the second extruder to move into the duplication position
  8568. active_extruder_parked = (active_extruder == 0);
  8569. if (active_extruder_parked)
  8570. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  8571. else
  8572. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  8573. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  8574. extruder_duplication_enabled = false;
  8575. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8576. if (DEBUGGING(LEVELING)) {
  8577. SERIAL_ECHOLNPAIR("Set inactive_extruder_x_pos=", inactive_extruder_x_pos);
  8578. SERIAL_ECHOLNPGM("Clear extruder_duplication_enabled");
  8579. }
  8580. #endif
  8581. break;
  8582. }
  8583. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8584. if (DEBUGGING(LEVELING)) {
  8585. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  8586. DEBUG_POS("New extruder (parked)", current_position);
  8587. }
  8588. #endif
  8589. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  8590. #else // !DUAL_X_CARRIAGE
  8591. #if ENABLED(SWITCHING_NOZZLE)
  8592. #define DONT_SWITCH (SWITCHING_EXTRUDER_SERVO_NR == SWITCHING_NOZZLE_SERVO_NR)
  8593. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  8594. const float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  8595. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  8596. // Always raise by some amount (destination copied from current_position earlier)
  8597. current_position[Z_AXIS] += z_raise;
  8598. planner.buffer_line_kinematic(current_position, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  8599. move_nozzle_servo(tmp_extruder);
  8600. #endif
  8601. /**
  8602. * Set current_position to the position of the new nozzle.
  8603. * Offsets are based on linear distance, so we need to get
  8604. * the resulting position in coordinate space.
  8605. *
  8606. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  8607. * - With mesh leveling, update Z for the new position
  8608. * - Otherwise, just use the raw linear distance
  8609. *
  8610. * Software endstops are altered here too. Consider a case where:
  8611. * E0 at X=0 ... E1 at X=10
  8612. * When we switch to E1 now X=10, but E1 can't move left.
  8613. * To express this we apply the change in XY to the software endstops.
  8614. * E1 can move farther right than E0, so the right limit is extended.
  8615. *
  8616. * Note that we don't adjust the Z software endstops. Why not?
  8617. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  8618. * because the bed is 1mm lower at the new position. As long as
  8619. * the first nozzle is out of the way, the carriage should be
  8620. * allowed to move 1mm lower. This technically "breaks" the
  8621. * Z software endstop. But this is technically correct (and
  8622. * there is no viable alternative).
  8623. */
  8624. #if ABL_PLANAR
  8625. // Offset extruder, make sure to apply the bed level rotation matrix
  8626. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  8627. hotend_offset[Y_AXIS][tmp_extruder],
  8628. 0),
  8629. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  8630. hotend_offset[Y_AXIS][active_extruder],
  8631. 0),
  8632. offset_vec = tmp_offset_vec - act_offset_vec;
  8633. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8634. if (DEBUGGING(LEVELING)) {
  8635. tmp_offset_vec.debug(PSTR("tmp_offset_vec"));
  8636. act_offset_vec.debug(PSTR("act_offset_vec"));
  8637. offset_vec.debug(PSTR("offset_vec (BEFORE)"));
  8638. }
  8639. #endif
  8640. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  8641. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8642. if (DEBUGGING(LEVELING)) offset_vec.debug(PSTR("offset_vec (AFTER)"));
  8643. #endif
  8644. // Adjustments to the current position
  8645. const float xydiff[2] = { offset_vec.x, offset_vec.y };
  8646. current_position[Z_AXIS] += offset_vec.z;
  8647. #else // !ABL_PLANAR
  8648. const float xydiff[2] = {
  8649. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  8650. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  8651. };
  8652. #if ENABLED(MESH_BED_LEVELING)
  8653. if (leveling_is_active()) {
  8654. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8655. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  8656. #endif
  8657. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  8658. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  8659. z1 = current_position[Z_AXIS], z2 = z1;
  8660. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  8661. planner.apply_leveling(x2, y2, z2);
  8662. current_position[Z_AXIS] += z2 - z1;
  8663. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8664. if (DEBUGGING(LEVELING))
  8665. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  8666. #endif
  8667. }
  8668. #endif // MESH_BED_LEVELING
  8669. #endif // !HAS_ABL
  8670. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8671. if (DEBUGGING(LEVELING)) {
  8672. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  8673. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  8674. SERIAL_ECHOLNPGM(" }");
  8675. }
  8676. #endif
  8677. // The newly-selected extruder XY is actually at...
  8678. current_position[X_AXIS] += xydiff[X_AXIS];
  8679. current_position[Y_AXIS] += xydiff[Y_AXIS];
  8680. #if HAS_WORKSPACE_OFFSET || ENABLED(DUAL_X_CARRIAGE)
  8681. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  8682. #if HAS_POSITION_SHIFT
  8683. position_shift[i] += xydiff[i];
  8684. #endif
  8685. update_software_endstops((AxisEnum)i);
  8686. }
  8687. #endif
  8688. // Set the new active extruder
  8689. active_extruder = tmp_extruder;
  8690. #endif // !DUAL_X_CARRIAGE
  8691. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8692. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  8693. #endif
  8694. // Tell the planner the new "current position"
  8695. SYNC_PLAN_POSITION_KINEMATIC();
  8696. // Move to the "old position" (move the extruder into place)
  8697. if (!no_move && IsRunning()) {
  8698. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8699. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  8700. #endif
  8701. prepare_move_to_destination();
  8702. }
  8703. #if ENABLED(SWITCHING_NOZZLE)
  8704. // Move back down, if needed. (Including when the new tool is higher.)
  8705. if (z_raise != z_diff) {
  8706. destination[Z_AXIS] += z_diff;
  8707. feedrate_mm_s = planner.max_feedrate_mm_s[Z_AXIS];
  8708. prepare_move_to_destination();
  8709. }
  8710. #endif
  8711. } // (tmp_extruder != active_extruder)
  8712. stepper.synchronize();
  8713. #if ENABLED(EXT_SOLENOID)
  8714. disable_all_solenoids();
  8715. enable_solenoid_on_active_extruder();
  8716. #endif // EXT_SOLENOID
  8717. feedrate_mm_s = old_feedrate_mm_s;
  8718. #else // HOTENDS <= 1
  8719. UNUSED(fr_mm_s);
  8720. UNUSED(no_move);
  8721. #if ENABLED(MK2_MULTIPLEXER)
  8722. if (tmp_extruder >= E_STEPPERS)
  8723. return invalid_extruder_error(tmp_extruder);
  8724. select_multiplexed_stepper(tmp_extruder);
  8725. #endif
  8726. #endif // HOTENDS <= 1
  8727. #if ENABLED(SWITCHING_EXTRUDER) && !DONT_SWITCH
  8728. stepper.synchronize();
  8729. move_extruder_servo(tmp_extruder);
  8730. #endif
  8731. active_extruder = tmp_extruder;
  8732. SERIAL_ECHO_START();
  8733. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  8734. #endif // !MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  8735. }
  8736. /**
  8737. * T0-T3: Switch tool, usually switching extruders
  8738. *
  8739. * F[units/min] Set the movement feedrate
  8740. * S1 Don't move the tool in XY after change
  8741. */
  8742. inline void gcode_T(uint8_t tmp_extruder) {
  8743. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8744. if (DEBUGGING(LEVELING)) {
  8745. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  8746. SERIAL_CHAR(')');
  8747. SERIAL_EOL();
  8748. DEBUG_POS("BEFORE", current_position);
  8749. }
  8750. #endif
  8751. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  8752. tool_change(tmp_extruder);
  8753. #elif HOTENDS > 1
  8754. tool_change(
  8755. tmp_extruder,
  8756. MMM_TO_MMS(parser.linearval('F')),
  8757. (tmp_extruder == active_extruder) || parser.boolval('S')
  8758. );
  8759. #endif
  8760. #if ENABLED(DEBUG_LEVELING_FEATURE)
  8761. if (DEBUGGING(LEVELING)) {
  8762. DEBUG_POS("AFTER", current_position);
  8763. SERIAL_ECHOLNPGM("<<< gcode_T");
  8764. }
  8765. #endif
  8766. }
  8767. /**
  8768. * Process a single command and dispatch it to its handler
  8769. * This is called from the main loop()
  8770. */
  8771. void process_next_command() {
  8772. char * const current_command = command_queue[cmd_queue_index_r];
  8773. if (DEBUGGING(ECHO)) {
  8774. SERIAL_ECHO_START();
  8775. SERIAL_ECHOLN(current_command);
  8776. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8777. SERIAL_ECHOPAIR("slot:", cmd_queue_index_r);
  8778. M100_dump_routine(" Command Queue:", (const char*)command_queue, (const char*)(command_queue + sizeof(command_queue)));
  8779. #endif
  8780. }
  8781. KEEPALIVE_STATE(IN_HANDLER);
  8782. // Parse the next command in the queue
  8783. parser.parse(current_command);
  8784. // Handle a known G, M, or T
  8785. switch (parser.command_letter) {
  8786. case 'G': switch (parser.codenum) {
  8787. // G0, G1
  8788. case 0:
  8789. case 1:
  8790. #if IS_SCARA
  8791. gcode_G0_G1(parser.codenum == 0);
  8792. #else
  8793. gcode_G0_G1();
  8794. #endif
  8795. break;
  8796. // G2, G3
  8797. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  8798. case 2: // G2: CW ARC
  8799. case 3: // G3: CCW ARC
  8800. gcode_G2_G3(parser.codenum == 2);
  8801. break;
  8802. #endif
  8803. // G4 Dwell
  8804. case 4:
  8805. gcode_G4();
  8806. break;
  8807. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8808. case 5: // G5: Cubic B_spline
  8809. gcode_G5();
  8810. break;
  8811. #endif // BEZIER_CURVE_SUPPORT
  8812. #if ENABLED(FWRETRACT)
  8813. case 10: // G10: retract
  8814. gcode_G10();
  8815. break;
  8816. case 11: // G11: retract_recover
  8817. gcode_G11();
  8818. break;
  8819. #endif // FWRETRACT
  8820. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  8821. case 12:
  8822. gcode_G12(); // G12: Nozzle Clean
  8823. break;
  8824. #endif // NOZZLE_CLEAN_FEATURE
  8825. #if ENABLED(CNC_WORKSPACE_PLANES)
  8826. case 17: // G17: Select Plane XY
  8827. gcode_G17();
  8828. break;
  8829. case 18: // G18: Select Plane ZX
  8830. gcode_G18();
  8831. break;
  8832. case 19: // G19: Select Plane YZ
  8833. gcode_G19();
  8834. break;
  8835. #endif // CNC_WORKSPACE_PLANES
  8836. #if ENABLED(INCH_MODE_SUPPORT)
  8837. case 20: //G20: Inch Mode
  8838. gcode_G20();
  8839. break;
  8840. case 21: //G21: MM Mode
  8841. gcode_G21();
  8842. break;
  8843. #endif // INCH_MODE_SUPPORT
  8844. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8845. case 26: // G26: Mesh Validation Pattern generation
  8846. gcode_G26();
  8847. break;
  8848. #endif // AUTO_BED_LEVELING_UBL
  8849. #if ENABLED(NOZZLE_PARK_FEATURE)
  8850. case 27: // G27: Nozzle Park
  8851. gcode_G27();
  8852. break;
  8853. #endif // NOZZLE_PARK_FEATURE
  8854. case 28: // G28: Home all axes, one at a time
  8855. gcode_G28(false);
  8856. break;
  8857. #if HAS_LEVELING
  8858. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  8859. // or provides access to the UBL System if enabled.
  8860. gcode_G29();
  8861. break;
  8862. #endif // HAS_LEVELING
  8863. #if HAS_BED_PROBE
  8864. case 30: // G30 Single Z probe
  8865. gcode_G30();
  8866. break;
  8867. #if ENABLED(Z_PROBE_SLED)
  8868. case 31: // G31: dock the sled
  8869. gcode_G31();
  8870. break;
  8871. case 32: // G32: undock the sled
  8872. gcode_G32();
  8873. break;
  8874. #endif // Z_PROBE_SLED
  8875. #endif // HAS_BED_PROBE
  8876. #if PROBE_SELECTED
  8877. #if ENABLED(DELTA_AUTO_CALIBRATION)
  8878. case 33: // G33: Delta Auto-Calibration
  8879. gcode_G33();
  8880. break;
  8881. #endif // DELTA_AUTO_CALIBRATION
  8882. #endif // PROBE_SELECTED
  8883. #if ENABLED(G38_PROBE_TARGET)
  8884. case 38: // G38.2 & G38.3
  8885. if (parser.subcode == 2 || parser.subcode == 3)
  8886. gcode_G38(parser.subcode == 2);
  8887. break;
  8888. #endif
  8889. case 90: // G90
  8890. relative_mode = false;
  8891. break;
  8892. case 91: // G91
  8893. relative_mode = true;
  8894. break;
  8895. case 92: // G92
  8896. gcode_G92();
  8897. break;
  8898. #if ENABLED(AUTO_BED_LEVELING_BILINEAR) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(MESH_BED_LEVELING)
  8899. case 42:
  8900. gcode_G42();
  8901. break;
  8902. #endif
  8903. #if ENABLED(DEBUG_GCODE_PARSER)
  8904. case 800:
  8905. parser.debug(); // GCode Parser Test for G
  8906. break;
  8907. #endif
  8908. }
  8909. break;
  8910. case 'M': switch (parser.codenum) {
  8911. #if HAS_RESUME_CONTINUE
  8912. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  8913. case 1: // M1: Conditional stop - Wait for user button press on LCD
  8914. gcode_M0_M1();
  8915. break;
  8916. #endif // ULTIPANEL
  8917. #if ENABLED(SPINDLE_LASER_ENABLE)
  8918. case 3:
  8919. gcode_M3_M4(true); // M3: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CW
  8920. break; // synchronizes with movement commands
  8921. case 4:
  8922. gcode_M3_M4(false); // M4: turn spindle/laser on, set laser/spindle power/speed, set rotation direction CCW
  8923. break; // synchronizes with movement commands
  8924. case 5:
  8925. gcode_M5(); // M5 - turn spindle/laser off
  8926. break; // synchronizes with movement commands
  8927. #endif
  8928. case 17: // M17: Enable all stepper motors
  8929. gcode_M17();
  8930. break;
  8931. #if ENABLED(SDSUPPORT)
  8932. case 20: // M20: list SD card
  8933. gcode_M20(); break;
  8934. case 21: // M21: init SD card
  8935. gcode_M21(); break;
  8936. case 22: // M22: release SD card
  8937. gcode_M22(); break;
  8938. case 23: // M23: Select file
  8939. gcode_M23(); break;
  8940. case 24: // M24: Start SD print
  8941. gcode_M24(); break;
  8942. case 25: // M25: Pause SD print
  8943. gcode_M25(); break;
  8944. case 26: // M26: Set SD index
  8945. gcode_M26(); break;
  8946. case 27: // M27: Get SD status
  8947. gcode_M27(); break;
  8948. case 28: // M28: Start SD write
  8949. gcode_M28(); break;
  8950. case 29: // M29: Stop SD write
  8951. gcode_M29(); break;
  8952. case 30: // M30 <filename> Delete File
  8953. gcode_M30(); break;
  8954. case 32: // M32: Select file and start SD print
  8955. gcode_M32(); break;
  8956. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  8957. case 33: // M33: Get the long full path to a file or folder
  8958. gcode_M33(); break;
  8959. #endif
  8960. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  8961. case 34: //M34 - Set SD card sorting options
  8962. gcode_M34(); break;
  8963. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  8964. case 928: // M928: Start SD write
  8965. gcode_M928(); break;
  8966. #endif // SDSUPPORT
  8967. case 31: // M31: Report time since the start of SD print or last M109
  8968. gcode_M31(); break;
  8969. case 42: // M42: Change pin state
  8970. gcode_M42(); break;
  8971. #if ENABLED(PINS_DEBUGGING)
  8972. case 43: // M43: Read pin state
  8973. gcode_M43(); break;
  8974. #endif
  8975. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  8976. case 48: // M48: Z probe repeatability test
  8977. gcode_M48();
  8978. break;
  8979. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  8980. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(UBL_G26_MESH_VALIDATION)
  8981. case 49: // M49: Turn on or off G26 debug flag for verbose output
  8982. gcode_M49();
  8983. break;
  8984. #endif // AUTO_BED_LEVELING_UBL && UBL_G26_MESH_VALIDATION
  8985. case 75: // M75: Start print timer
  8986. gcode_M75(); break;
  8987. case 76: // M76: Pause print timer
  8988. gcode_M76(); break;
  8989. case 77: // M77: Stop print timer
  8990. gcode_M77(); break;
  8991. #if ENABLED(PRINTCOUNTER)
  8992. case 78: // M78: Show print statistics
  8993. gcode_M78(); break;
  8994. #endif
  8995. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  8996. case 100: // M100: Free Memory Report
  8997. gcode_M100();
  8998. break;
  8999. #endif
  9000. case 104: // M104: Set hot end temperature
  9001. gcode_M104();
  9002. break;
  9003. case 110: // M110: Set Current Line Number
  9004. gcode_M110();
  9005. break;
  9006. case 111: // M111: Set debug level
  9007. gcode_M111();
  9008. break;
  9009. #if DISABLED(EMERGENCY_PARSER)
  9010. case 108: // M108: Cancel Waiting
  9011. gcode_M108();
  9012. break;
  9013. case 112: // M112: Emergency Stop
  9014. gcode_M112();
  9015. break;
  9016. case 410: // M410 quickstop - Abort all the planned moves.
  9017. gcode_M410();
  9018. break;
  9019. #endif
  9020. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  9021. case 113: // M113: Set Host Keepalive interval
  9022. gcode_M113();
  9023. break;
  9024. #endif
  9025. case 140: // M140: Set bed temperature
  9026. gcode_M140();
  9027. break;
  9028. case 105: // M105: Report current temperature
  9029. gcode_M105();
  9030. KEEPALIVE_STATE(NOT_BUSY);
  9031. return; // "ok" already printed
  9032. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  9033. case 155: // M155: Set temperature auto-report interval
  9034. gcode_M155();
  9035. break;
  9036. #endif
  9037. case 109: // M109: Wait for hotend temperature to reach target
  9038. gcode_M109();
  9039. break;
  9040. #if HAS_TEMP_BED
  9041. case 190: // M190: Wait for bed temperature to reach target
  9042. gcode_M190();
  9043. break;
  9044. #endif // HAS_TEMP_BED
  9045. #if FAN_COUNT > 0
  9046. case 106: // M106: Fan On
  9047. gcode_M106();
  9048. break;
  9049. case 107: // M107: Fan Off
  9050. gcode_M107();
  9051. break;
  9052. #endif // FAN_COUNT > 0
  9053. #if ENABLED(PARK_HEAD_ON_PAUSE)
  9054. case 125: // M125: Store current position and move to filament change position
  9055. gcode_M125(); break;
  9056. #endif
  9057. #if ENABLED(BARICUDA)
  9058. // PWM for HEATER_1_PIN
  9059. #if HAS_HEATER_1
  9060. case 126: // M126: valve open
  9061. gcode_M126();
  9062. break;
  9063. case 127: // M127: valve closed
  9064. gcode_M127();
  9065. break;
  9066. #endif // HAS_HEATER_1
  9067. // PWM for HEATER_2_PIN
  9068. #if HAS_HEATER_2
  9069. case 128: // M128: valve open
  9070. gcode_M128();
  9071. break;
  9072. case 129: // M129: valve closed
  9073. gcode_M129();
  9074. break;
  9075. #endif // HAS_HEATER_2
  9076. #endif // BARICUDA
  9077. #if HAS_POWER_SWITCH
  9078. case 80: // M80: Turn on Power Supply
  9079. gcode_M80();
  9080. break;
  9081. #endif // HAS_POWER_SWITCH
  9082. case 81: // M81: Turn off Power, including Power Supply, if possible
  9083. gcode_M81();
  9084. break;
  9085. case 82: // M82: Set E axis normal mode (same as other axes)
  9086. gcode_M82();
  9087. break;
  9088. case 83: // M83: Set E axis relative mode
  9089. gcode_M83();
  9090. break;
  9091. case 18: // M18 => M84
  9092. case 84: // M84: Disable all steppers or set timeout
  9093. gcode_M18_M84();
  9094. break;
  9095. case 85: // M85: Set inactivity stepper shutdown timeout
  9096. gcode_M85();
  9097. break;
  9098. case 92: // M92: Set the steps-per-unit for one or more axes
  9099. gcode_M92();
  9100. break;
  9101. case 114: // M114: Report current position
  9102. gcode_M114();
  9103. break;
  9104. case 115: // M115: Report capabilities
  9105. gcode_M115();
  9106. break;
  9107. case 117: // M117: Set LCD message text, if possible
  9108. gcode_M117();
  9109. break;
  9110. case 118: // M118: Display a message in the host console
  9111. gcode_M118();
  9112. break;
  9113. case 119: // M119: Report endstop states
  9114. gcode_M119();
  9115. break;
  9116. case 120: // M120: Enable endstops
  9117. gcode_M120();
  9118. break;
  9119. case 121: // M121: Disable endstops
  9120. gcode_M121();
  9121. break;
  9122. #if ENABLED(ULTIPANEL)
  9123. case 145: // M145: Set material heatup parameters
  9124. gcode_M145();
  9125. break;
  9126. #endif
  9127. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  9128. case 149: // M149: Set temperature units
  9129. gcode_M149();
  9130. break;
  9131. #endif
  9132. #if HAS_COLOR_LEDS
  9133. case 150: // M150: Set Status LED Color
  9134. gcode_M150();
  9135. break;
  9136. #endif // HAS_COLOR_LEDS
  9137. #if ENABLED(MIXING_EXTRUDER)
  9138. case 163: // M163: Set a component weight for mixing extruder
  9139. gcode_M163();
  9140. break;
  9141. #if MIXING_VIRTUAL_TOOLS > 1
  9142. case 164: // M164: Save current mix as a virtual extruder
  9143. gcode_M164();
  9144. break;
  9145. #endif
  9146. #if ENABLED(DIRECT_MIXING_IN_G1)
  9147. case 165: // M165: Set multiple mix weights
  9148. gcode_M165();
  9149. break;
  9150. #endif
  9151. #endif
  9152. case 200: // M200: Set filament diameter, E to cubic units
  9153. gcode_M200();
  9154. break;
  9155. case 201: // M201: Set max acceleration for print moves (units/s^2)
  9156. gcode_M201();
  9157. break;
  9158. #if 0 // Not used for Sprinter/grbl gen6
  9159. case 202: // M202
  9160. gcode_M202();
  9161. break;
  9162. #endif
  9163. case 203: // M203: Set max feedrate (units/sec)
  9164. gcode_M203();
  9165. break;
  9166. case 204: // M204: Set acceleration
  9167. gcode_M204();
  9168. break;
  9169. case 205: //M205: Set advanced settings
  9170. gcode_M205();
  9171. break;
  9172. #if HAS_M206_COMMAND
  9173. case 206: // M206: Set home offsets
  9174. gcode_M206();
  9175. break;
  9176. #endif
  9177. #if ENABLED(DELTA)
  9178. case 665: // M665: Set delta configurations
  9179. gcode_M665();
  9180. break;
  9181. #endif
  9182. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  9183. case 666: // M666: Set delta or dual endstop adjustment
  9184. gcode_M666();
  9185. break;
  9186. #endif
  9187. #if ENABLED(FWRETRACT)
  9188. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  9189. gcode_M207();
  9190. break;
  9191. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  9192. gcode_M208();
  9193. break;
  9194. case 209: // M209: Turn Automatic Retract Detection on/off
  9195. gcode_M209();
  9196. break;
  9197. #endif // FWRETRACT
  9198. case 211: // M211: Enable, Disable, and/or Report software endstops
  9199. gcode_M211();
  9200. break;
  9201. #if HOTENDS > 1
  9202. case 218: // M218: Set a tool offset
  9203. gcode_M218();
  9204. break;
  9205. #endif
  9206. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  9207. gcode_M220();
  9208. break;
  9209. case 221: // M221: Set Flow Percentage
  9210. gcode_M221();
  9211. break;
  9212. case 226: // M226: Wait until a pin reaches a state
  9213. gcode_M226();
  9214. break;
  9215. #if HAS_SERVOS
  9216. case 280: // M280: Set servo position absolute
  9217. gcode_M280();
  9218. break;
  9219. #endif // HAS_SERVOS
  9220. #if HAS_BUZZER
  9221. case 300: // M300: Play beep tone
  9222. gcode_M300();
  9223. break;
  9224. #endif // HAS_BUZZER
  9225. #if ENABLED(PIDTEMP)
  9226. case 301: // M301: Set hotend PID parameters
  9227. gcode_M301();
  9228. break;
  9229. #endif // PIDTEMP
  9230. #if ENABLED(PIDTEMPBED)
  9231. case 304: // M304: Set bed PID parameters
  9232. gcode_M304();
  9233. break;
  9234. #endif // PIDTEMPBED
  9235. #if defined(CHDK) || HAS_PHOTOGRAPH
  9236. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  9237. gcode_M240();
  9238. break;
  9239. #endif // CHDK || PHOTOGRAPH_PIN
  9240. #if HAS_LCD_CONTRAST
  9241. case 250: // M250: Set LCD contrast
  9242. gcode_M250();
  9243. break;
  9244. #endif // HAS_LCD_CONTRAST
  9245. #if ENABLED(EXPERIMENTAL_I2CBUS)
  9246. case 260: // M260: Send data to an i2c slave
  9247. gcode_M260();
  9248. break;
  9249. case 261: // M261: Request data from an i2c slave
  9250. gcode_M261();
  9251. break;
  9252. #endif // EXPERIMENTAL_I2CBUS
  9253. #if ENABLED(PREVENT_COLD_EXTRUSION)
  9254. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  9255. gcode_M302();
  9256. break;
  9257. #endif // PREVENT_COLD_EXTRUSION
  9258. case 303: // M303: PID autotune
  9259. gcode_M303();
  9260. break;
  9261. #if ENABLED(MORGAN_SCARA)
  9262. case 360: // M360: SCARA Theta pos1
  9263. if (gcode_M360()) return;
  9264. break;
  9265. case 361: // M361: SCARA Theta pos2
  9266. if (gcode_M361()) return;
  9267. break;
  9268. case 362: // M362: SCARA Psi pos1
  9269. if (gcode_M362()) return;
  9270. break;
  9271. case 363: // M363: SCARA Psi pos2
  9272. if (gcode_M363()) return;
  9273. break;
  9274. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  9275. if (gcode_M364()) return;
  9276. break;
  9277. #endif // SCARA
  9278. case 400: // M400: Finish all moves
  9279. gcode_M400();
  9280. break;
  9281. #if HAS_BED_PROBE
  9282. case 401: // M401: Deploy probe
  9283. gcode_M401();
  9284. break;
  9285. case 402: // M402: Stow probe
  9286. gcode_M402();
  9287. break;
  9288. #endif // HAS_BED_PROBE
  9289. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  9290. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  9291. gcode_M404();
  9292. break;
  9293. case 405: // M405: Turn on filament sensor for control
  9294. gcode_M405();
  9295. break;
  9296. case 406: // M406: Turn off filament sensor for control
  9297. gcode_M406();
  9298. break;
  9299. case 407: // M407: Display measured filament diameter
  9300. gcode_M407();
  9301. break;
  9302. #endif // FILAMENT_WIDTH_SENSOR
  9303. #if HAS_LEVELING
  9304. case 420: // M420: Enable/Disable Bed Leveling
  9305. gcode_M420();
  9306. break;
  9307. #endif
  9308. #if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL) || ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9309. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  9310. gcode_M421();
  9311. break;
  9312. #endif
  9313. #if HAS_M206_COMMAND
  9314. case 428: // M428: Apply current_position to home_offset
  9315. gcode_M428();
  9316. break;
  9317. #endif
  9318. case 500: // M500: Store settings in EEPROM
  9319. gcode_M500();
  9320. break;
  9321. case 501: // M501: Read settings from EEPROM
  9322. gcode_M501();
  9323. break;
  9324. case 502: // M502: Revert to default settings
  9325. gcode_M502();
  9326. break;
  9327. #if DISABLED(DISABLE_M503)
  9328. case 503: // M503: print settings currently in memory
  9329. gcode_M503();
  9330. break;
  9331. #endif
  9332. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  9333. case 540: // M540: Set abort on endstop hit for SD printing
  9334. gcode_M540();
  9335. break;
  9336. #endif
  9337. #if HAS_BED_PROBE
  9338. case 851: // M851: Set Z Probe Z Offset
  9339. gcode_M851();
  9340. break;
  9341. #endif // HAS_BED_PROBE
  9342. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  9343. case 600: // M600: Pause for filament change
  9344. gcode_M600();
  9345. break;
  9346. #endif // ADVANCED_PAUSE_FEATURE
  9347. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  9348. case 605: // M605: Set Dual X Carriage movement mode
  9349. gcode_M605();
  9350. break;
  9351. #endif // DUAL_X_CARRIAGE
  9352. #if ENABLED(MK2_MULTIPLEXER)
  9353. case 702: // M702: Unload all extruders
  9354. gcode_M702();
  9355. break;
  9356. #endif
  9357. #if ENABLED(LIN_ADVANCE)
  9358. case 900: // M900: Set advance K factor.
  9359. gcode_M900();
  9360. break;
  9361. #endif
  9362. #if ENABLED(HAVE_TMC2130)
  9363. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  9364. gcode_M906();
  9365. break;
  9366. #endif
  9367. case 907: // M907: Set digital trimpot motor current using axis codes.
  9368. gcode_M907();
  9369. break;
  9370. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  9371. case 908: // M908: Control digital trimpot directly.
  9372. gcode_M908();
  9373. break;
  9374. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  9375. case 909: // M909: Print digipot/DAC current value
  9376. gcode_M909();
  9377. break;
  9378. case 910: // M910: Commit digipot/DAC value to external EEPROM
  9379. gcode_M910();
  9380. break;
  9381. #endif
  9382. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  9383. #if ENABLED(HAVE_TMC2130)
  9384. case 911: // M911: Report TMC2130 prewarn triggered flags
  9385. gcode_M911();
  9386. break;
  9387. case 912: // M911: Clear TMC2130 prewarn triggered flags
  9388. gcode_M912();
  9389. break;
  9390. #if ENABLED(HYBRID_THRESHOLD)
  9391. case 913: // M913: Set HYBRID_THRESHOLD speed.
  9392. gcode_M913();
  9393. break;
  9394. #endif
  9395. #if ENABLED(SENSORLESS_HOMING)
  9396. case 914: // M914: Set SENSORLESS_HOMING sensitivity.
  9397. gcode_M914();
  9398. break;
  9399. #endif
  9400. #endif
  9401. #if HAS_MICROSTEPS
  9402. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  9403. gcode_M350();
  9404. break;
  9405. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  9406. gcode_M351();
  9407. break;
  9408. #endif // HAS_MICROSTEPS
  9409. case 355: // M355 set case light brightness
  9410. gcode_M355();
  9411. break;
  9412. #if ENABLED(DEBUG_GCODE_PARSER)
  9413. case 800:
  9414. parser.debug(); // GCode Parser Test for M
  9415. break;
  9416. #endif
  9417. #if ENABLED(I2C_POSITION_ENCODERS)
  9418. case 860: // M860 Report encoder module position
  9419. gcode_M860();
  9420. break;
  9421. case 861: // M861 Report encoder module status
  9422. gcode_M861();
  9423. break;
  9424. case 862: // M862 Perform axis test
  9425. gcode_M862();
  9426. break;
  9427. case 863: // M863 Calibrate steps/mm
  9428. gcode_M863();
  9429. break;
  9430. case 864: // M864 Change module address
  9431. gcode_M864();
  9432. break;
  9433. case 865: // M865 Check module firmware version
  9434. gcode_M865();
  9435. break;
  9436. case 866: // M866 Report axis error count
  9437. gcode_M866();
  9438. break;
  9439. case 867: // M867 Toggle error correction
  9440. gcode_M867();
  9441. break;
  9442. case 868: // M868 Set error correction threshold
  9443. gcode_M868();
  9444. break;
  9445. case 869: // M869 Report axis error
  9446. gcode_M869();
  9447. break;
  9448. #endif // I2C_POSITION_ENCODERS
  9449. case 999: // M999: Restart after being Stopped
  9450. gcode_M999();
  9451. break;
  9452. }
  9453. break;
  9454. case 'T':
  9455. gcode_T(parser.codenum);
  9456. break;
  9457. default: parser.unknown_command_error();
  9458. }
  9459. KEEPALIVE_STATE(NOT_BUSY);
  9460. ok_to_send();
  9461. }
  9462. /**
  9463. * Send a "Resend: nnn" message to the host to
  9464. * indicate that a command needs to be re-sent.
  9465. */
  9466. void FlushSerialRequestResend() {
  9467. //char command_queue[cmd_queue_index_r][100]="Resend:";
  9468. MYSERIAL.flush();
  9469. SERIAL_PROTOCOLPGM(MSG_RESEND);
  9470. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  9471. ok_to_send();
  9472. }
  9473. /**
  9474. * Send an "ok" message to the host, indicating
  9475. * that a command was successfully processed.
  9476. *
  9477. * If ADVANCED_OK is enabled also include:
  9478. * N<int> Line number of the command, if any
  9479. * P<int> Planner space remaining
  9480. * B<int> Block queue space remaining
  9481. */
  9482. void ok_to_send() {
  9483. refresh_cmd_timeout();
  9484. if (!send_ok[cmd_queue_index_r]) return;
  9485. SERIAL_PROTOCOLPGM(MSG_OK);
  9486. #if ENABLED(ADVANCED_OK)
  9487. char* p = command_queue[cmd_queue_index_r];
  9488. if (*p == 'N') {
  9489. SERIAL_PROTOCOL(' ');
  9490. SERIAL_ECHO(*p++);
  9491. while (NUMERIC_SIGNED(*p))
  9492. SERIAL_ECHO(*p++);
  9493. }
  9494. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  9495. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  9496. #endif
  9497. SERIAL_EOL();
  9498. }
  9499. #if HAS_SOFTWARE_ENDSTOPS
  9500. /**
  9501. * Constrain the given coordinates to the software endstops.
  9502. */
  9503. // NOTE: This makes no sense for delta beds other than Z-axis.
  9504. // For delta the X/Y would need to be clamped at
  9505. // DELTA_PRINTABLE_RADIUS from center of bed, but delta
  9506. // now enforces is_position_reachable for X/Y regardless
  9507. // of HAS_SOFTWARE_ENDSTOPS, so that enforcement would be
  9508. // redundant here. Probably should #ifdef out the X/Y
  9509. // axis clamps here for delta and just leave the Z clamp.
  9510. void clamp_to_software_endstops(float target[XYZ]) {
  9511. if (!soft_endstops_enabled) return;
  9512. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  9513. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  9514. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  9515. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  9516. #endif
  9517. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  9518. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  9519. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  9520. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  9521. #endif
  9522. }
  9523. #endif
  9524. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  9525. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  9526. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  9527. #define ABL_BG_FACTOR(A) bilinear_grid_factor_virt[A]
  9528. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  9529. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  9530. #define ABL_BG_GRID(X,Y) z_values_virt[X][Y]
  9531. #else
  9532. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  9533. #define ABL_BG_FACTOR(A) bilinear_grid_factor[A]
  9534. #define ABL_BG_POINTS_X GRID_MAX_POINTS_X
  9535. #define ABL_BG_POINTS_Y GRID_MAX_POINTS_Y
  9536. #define ABL_BG_GRID(X,Y) z_values[X][Y]
  9537. #endif
  9538. // Get the Z adjustment for non-linear bed leveling
  9539. float bilinear_z_offset(const float logical[XYZ]) {
  9540. static float z1, d2, z3, d4, L, D, ratio_x, ratio_y,
  9541. last_x = -999.999, last_y = -999.999;
  9542. // Whole units for the grid line indices. Constrained within bounds.
  9543. static int8_t gridx, gridy, nextx, nexty,
  9544. last_gridx = -99, last_gridy = -99;
  9545. // XY relative to the probed area
  9546. const float x = RAW_X_POSITION(logical[X_AXIS]) - bilinear_start[X_AXIS],
  9547. y = RAW_Y_POSITION(logical[Y_AXIS]) - bilinear_start[Y_AXIS];
  9548. #if ENABLED(EXTRAPOLATE_BEYOND_GRID)
  9549. // Keep using the last grid box
  9550. #define FAR_EDGE_OR_BOX 2
  9551. #else
  9552. // Just use the grid far edge
  9553. #define FAR_EDGE_OR_BOX 1
  9554. #endif
  9555. if (last_x != x) {
  9556. last_x = x;
  9557. ratio_x = x * ABL_BG_FACTOR(X_AXIS);
  9558. const float gx = constrain(FLOOR(ratio_x), 0, ABL_BG_POINTS_X - FAR_EDGE_OR_BOX);
  9559. ratio_x -= gx; // Subtract whole to get the ratio within the grid box
  9560. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9561. // Beyond the grid maintain height at grid edges
  9562. NOLESS(ratio_x, 0); // Never < 0.0. (> 1.0 is ok when nextx==gridx.)
  9563. #endif
  9564. gridx = gx;
  9565. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1);
  9566. }
  9567. if (last_y != y || last_gridx != gridx) {
  9568. if (last_y != y) {
  9569. last_y = y;
  9570. ratio_y = y * ABL_BG_FACTOR(Y_AXIS);
  9571. const float gy = constrain(FLOOR(ratio_y), 0, ABL_BG_POINTS_Y - FAR_EDGE_OR_BOX);
  9572. ratio_y -= gy;
  9573. #if DISABLED(EXTRAPOLATE_BEYOND_GRID)
  9574. // Beyond the grid maintain height at grid edges
  9575. NOLESS(ratio_y, 0); // Never < 0.0. (> 1.0 is ok when nexty==gridy.)
  9576. #endif
  9577. gridy = gy;
  9578. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  9579. }
  9580. if (last_gridx != gridx || last_gridy != gridy) {
  9581. last_gridx = gridx;
  9582. last_gridy = gridy;
  9583. // Z at the box corners
  9584. z1 = ABL_BG_GRID(gridx, gridy); // left-front
  9585. d2 = ABL_BG_GRID(gridx, nexty) - z1; // left-back (delta)
  9586. z3 = ABL_BG_GRID(nextx, gridy); // right-front
  9587. d4 = ABL_BG_GRID(nextx, nexty) - z3; // right-back (delta)
  9588. }
  9589. // Bilinear interpolate. Needed since y or gridx has changed.
  9590. L = z1 + d2 * ratio_y; // Linear interp. LF -> LB
  9591. const float R = z3 + d4 * ratio_y; // Linear interp. RF -> RB
  9592. D = R - L;
  9593. }
  9594. const float offset = L + ratio_x * D; // the offset almost always changes
  9595. /*
  9596. static float last_offset = 0;
  9597. if (FABS(last_offset - offset) > 0.2) {
  9598. SERIAL_ECHOPGM("Sudden Shift at ");
  9599. SERIAL_ECHOPAIR("x=", x);
  9600. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  9601. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  9602. SERIAL_ECHOPAIR(" y=", y);
  9603. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  9604. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  9605. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  9606. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  9607. SERIAL_ECHOPAIR(" z1=", z1);
  9608. SERIAL_ECHOPAIR(" z2=", z2);
  9609. SERIAL_ECHOPAIR(" z3=", z3);
  9610. SERIAL_ECHOLNPAIR(" z4=", z4);
  9611. SERIAL_ECHOPAIR(" L=", L);
  9612. SERIAL_ECHOPAIR(" R=", R);
  9613. SERIAL_ECHOLNPAIR(" offset=", offset);
  9614. }
  9615. last_offset = offset;
  9616. //*/
  9617. return offset;
  9618. }
  9619. #endif // AUTO_BED_LEVELING_BILINEAR
  9620. #if ENABLED(DELTA)
  9621. /**
  9622. * Recalculate factors used for delta kinematics whenever
  9623. * settings have been changed (e.g., by M665).
  9624. */
  9625. void recalc_delta_settings(float radius, float diagonal_rod) {
  9626. const float trt[ABC] = DELTA_RADIUS_TRIM_TOWER,
  9627. drt[ABC] = DELTA_DIAGONAL_ROD_TRIM_TOWER;
  9628. delta_tower[A_AXIS][X_AXIS] = cos(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]); // front left tower
  9629. delta_tower[A_AXIS][Y_AXIS] = sin(RADIANS(210 + delta_tower_angle_trim[A_AXIS])) * (radius + trt[A_AXIS]);
  9630. delta_tower[B_AXIS][X_AXIS] = cos(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]); // front right tower
  9631. delta_tower[B_AXIS][Y_AXIS] = sin(RADIANS(330 + delta_tower_angle_trim[B_AXIS])) * (radius + trt[B_AXIS]);
  9632. delta_tower[C_AXIS][X_AXIS] = 0.0; // back middle tower
  9633. delta_tower[C_AXIS][Y_AXIS] = (radius + trt[C_AXIS]);
  9634. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + drt[A_AXIS]);
  9635. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + drt[B_AXIS]);
  9636. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + drt[C_AXIS]);
  9637. }
  9638. #if ENABLED(DELTA_FAST_SQRT)
  9639. /**
  9640. * Fast inverse sqrt from Quake III Arena
  9641. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  9642. */
  9643. float Q_rsqrt(float number) {
  9644. long i;
  9645. float x2, y;
  9646. const float threehalfs = 1.5f;
  9647. x2 = number * 0.5f;
  9648. y = number;
  9649. i = * ( long * ) &y; // evil floating point bit level hacking
  9650. i = 0x5F3759DF - ( i >> 1 ); // what the f***?
  9651. y = * ( float * ) &i;
  9652. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  9653. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  9654. return y;
  9655. }
  9656. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  9657. #else
  9658. #define _SQRT(n) SQRT(n)
  9659. #endif
  9660. /**
  9661. * Delta Inverse Kinematics
  9662. *
  9663. * Calculate the tower positions for a given logical
  9664. * position, storing the result in the delta[] array.
  9665. *
  9666. * This is an expensive calculation, requiring 3 square
  9667. * roots per segmented linear move, and strains the limits
  9668. * of a Mega2560 with a Graphical Display.
  9669. *
  9670. * Suggested optimizations include:
  9671. *
  9672. * - Disable the home_offset (M206) and/or position_shift (G92)
  9673. * features to remove up to 12 float additions.
  9674. *
  9675. * - Use a fast-inverse-sqrt function and add the reciprocal.
  9676. * (see above)
  9677. */
  9678. // Macro to obtain the Z position of an individual tower
  9679. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  9680. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  9681. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  9682. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  9683. ) \
  9684. )
  9685. #define DELTA_RAW_IK() do { \
  9686. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  9687. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  9688. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  9689. }while(0)
  9690. #define DELTA_LOGICAL_IK() do { \
  9691. const float raw[XYZ] = { \
  9692. RAW_X_POSITION(logical[X_AXIS]), \
  9693. RAW_Y_POSITION(logical[Y_AXIS]), \
  9694. RAW_Z_POSITION(logical[Z_AXIS]) \
  9695. }; \
  9696. DELTA_RAW_IK(); \
  9697. }while(0)
  9698. #define DELTA_DEBUG() do { \
  9699. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  9700. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  9701. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  9702. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  9703. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  9704. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  9705. }while(0)
  9706. void inverse_kinematics(const float logical[XYZ]) {
  9707. DELTA_LOGICAL_IK();
  9708. // DELTA_DEBUG();
  9709. }
  9710. /**
  9711. * Calculate the highest Z position where the
  9712. * effector has the full range of XY motion.
  9713. */
  9714. float delta_safe_distance_from_top() {
  9715. float cartesian[XYZ] = {
  9716. LOGICAL_X_POSITION(0),
  9717. LOGICAL_Y_POSITION(0),
  9718. LOGICAL_Z_POSITION(0)
  9719. };
  9720. inverse_kinematics(cartesian);
  9721. float distance = delta[A_AXIS];
  9722. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  9723. inverse_kinematics(cartesian);
  9724. return FABS(distance - delta[A_AXIS]);
  9725. }
  9726. /**
  9727. * Delta Forward Kinematics
  9728. *
  9729. * See the Wikipedia article "Trilateration"
  9730. * https://en.wikipedia.org/wiki/Trilateration
  9731. *
  9732. * Establish a new coordinate system in the plane of the
  9733. * three carriage points. This system has its origin at
  9734. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  9735. * plane with a Z component of zero.
  9736. * We will define unit vectors in this coordinate system
  9737. * in our original coordinate system. Then when we calculate
  9738. * the Xnew, Ynew and Znew values, we can translate back into
  9739. * the original system by moving along those unit vectors
  9740. * by the corresponding values.
  9741. *
  9742. * Variable names matched to Marlin, c-version, and avoid the
  9743. * use of any vector library.
  9744. *
  9745. * by Andreas Hardtung 2016-06-07
  9746. * based on a Java function from "Delta Robot Kinematics V3"
  9747. * by Steve Graves
  9748. *
  9749. * The result is stored in the cartes[] array.
  9750. */
  9751. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  9752. // Create a vector in old coordinates along x axis of new coordinate
  9753. 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 };
  9754. // Get the Magnitude of vector.
  9755. float d = SQRT( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  9756. // Create unit vector by dividing by magnitude.
  9757. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  9758. // Get the vector from the origin of the new system to the third point.
  9759. 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 };
  9760. // Use the dot product to find the component of this vector on the X axis.
  9761. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  9762. // Create a vector along the x axis that represents the x component of p13.
  9763. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  9764. // Subtract the X component from the original vector leaving only Y. We use the
  9765. // variable that will be the unit vector after we scale it.
  9766. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  9767. // The magnitude of Y component
  9768. float j = SQRT( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  9769. // Convert to a unit vector
  9770. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  9771. // The cross product of the unit x and y is the unit z
  9772. // float[] ez = vectorCrossProd(ex, ey);
  9773. float ez[3] = {
  9774. ex[1] * ey[2] - ex[2] * ey[1],
  9775. ex[2] * ey[0] - ex[0] * ey[2],
  9776. ex[0] * ey[1] - ex[1] * ey[0]
  9777. };
  9778. // We now have the d, i and j values defined in Wikipedia.
  9779. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  9780. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  9781. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  9782. Znew = SQRT(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  9783. // Start from the origin of the old coordinates and add vectors in the
  9784. // old coords that represent the Xnew, Ynew and Znew to find the point
  9785. // in the old system.
  9786. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  9787. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  9788. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  9789. }
  9790. void forward_kinematics_DELTA(float point[ABC]) {
  9791. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  9792. }
  9793. #endif // DELTA
  9794. /**
  9795. * Get the stepper positions in the cartes[] array.
  9796. * Forward kinematics are applied for DELTA and SCARA.
  9797. *
  9798. * The result is in the current coordinate space with
  9799. * leveling applied. The coordinates need to be run through
  9800. * unapply_leveling to obtain the "ideal" coordinates
  9801. * suitable for current_position, etc.
  9802. */
  9803. void get_cartesian_from_steppers() {
  9804. #if ENABLED(DELTA)
  9805. forward_kinematics_DELTA(
  9806. stepper.get_axis_position_mm(A_AXIS),
  9807. stepper.get_axis_position_mm(B_AXIS),
  9808. stepper.get_axis_position_mm(C_AXIS)
  9809. );
  9810. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9811. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9812. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  9813. #elif IS_SCARA
  9814. forward_kinematics_SCARA(
  9815. stepper.get_axis_position_degrees(A_AXIS),
  9816. stepper.get_axis_position_degrees(B_AXIS)
  9817. );
  9818. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  9819. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  9820. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9821. #else
  9822. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  9823. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  9824. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  9825. #endif
  9826. }
  9827. /**
  9828. * Set the current_position for an axis based on
  9829. * the stepper positions, removing any leveling that
  9830. * may have been applied.
  9831. */
  9832. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  9833. get_cartesian_from_steppers();
  9834. #if PLANNER_LEVELING
  9835. planner.unapply_leveling(cartes);
  9836. #endif
  9837. if (axis == ALL_AXES)
  9838. COPY(current_position, cartes);
  9839. else
  9840. current_position[axis] = cartes[axis];
  9841. }
  9842. #if ENABLED(MESH_BED_LEVELING)
  9843. /**
  9844. * Prepare a mesh-leveled linear move in a Cartesian setup,
  9845. * splitting the move where it crosses mesh borders.
  9846. */
  9847. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xFF, uint8_t y_splits = 0xFF) {
  9848. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X)),
  9849. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y)),
  9850. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  9851. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  9852. NOMORE(cx1, GRID_MAX_POINTS_X - 2);
  9853. NOMORE(cy1, GRID_MAX_POINTS_Y - 2);
  9854. NOMORE(cx2, GRID_MAX_POINTS_X - 2);
  9855. NOMORE(cy2, GRID_MAX_POINTS_Y - 2);
  9856. if (cx1 == cx2 && cy1 == cy2) {
  9857. // Start and end on same mesh square
  9858. line_to_destination(fr_mm_s);
  9859. set_current_to_destination();
  9860. return;
  9861. }
  9862. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9863. float normalized_dist, end[XYZE];
  9864. // Split at the left/front border of the right/top square
  9865. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9866. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9867. COPY(end, destination);
  9868. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.index_to_xpos[gcx]);
  9869. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9870. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  9871. CBI(x_splits, gcx);
  9872. }
  9873. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9874. COPY(end, destination);
  9875. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.index_to_ypos[gcy]);
  9876. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9877. destination[X_AXIS] = MBL_SEGMENT_END(X);
  9878. CBI(y_splits, gcy);
  9879. }
  9880. else {
  9881. // Already split on a border
  9882. line_to_destination(fr_mm_s);
  9883. set_current_to_destination();
  9884. return;
  9885. }
  9886. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  9887. destination[E_AXIS] = MBL_SEGMENT_END(E);
  9888. // Do the split and look for more borders
  9889. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9890. // Restore destination from stack
  9891. COPY(destination, end);
  9892. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  9893. }
  9894. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  9895. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) * ABL_BG_FACTOR(A##_AXIS))
  9896. /**
  9897. * Prepare a bilinear-leveled linear move on Cartesian,
  9898. * splitting the move where it crosses grid borders.
  9899. */
  9900. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  9901. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  9902. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  9903. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  9904. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  9905. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  9906. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  9907. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  9908. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  9909. if (cx1 == cx2 && cy1 == cy2) {
  9910. // Start and end on same mesh square
  9911. line_to_destination(fr_mm_s);
  9912. set_current_to_destination();
  9913. return;
  9914. }
  9915. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  9916. float normalized_dist, end[XYZE];
  9917. // Split at the left/front border of the right/top square
  9918. const int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  9919. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  9920. COPY(end, destination);
  9921. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  9922. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  9923. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  9924. CBI(x_splits, gcx);
  9925. }
  9926. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  9927. COPY(end, destination);
  9928. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  9929. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  9930. destination[X_AXIS] = LINE_SEGMENT_END(X);
  9931. CBI(y_splits, gcy);
  9932. }
  9933. else {
  9934. // Already split on a border
  9935. line_to_destination(fr_mm_s);
  9936. set_current_to_destination();
  9937. return;
  9938. }
  9939. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  9940. destination[E_AXIS] = LINE_SEGMENT_END(E);
  9941. // Do the split and look for more borders
  9942. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9943. // Restore destination from stack
  9944. COPY(destination, end);
  9945. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  9946. }
  9947. #endif // AUTO_BED_LEVELING_BILINEAR
  9948. #if IS_KINEMATIC && !UBL_DELTA
  9949. /**
  9950. * Prepare a linear move in a DELTA or SCARA setup.
  9951. *
  9952. * This calls planner.buffer_line several times, adding
  9953. * small incremental moves for DELTA or SCARA.
  9954. */
  9955. inline bool prepare_kinematic_move_to(float ltarget[XYZE]) {
  9956. // Get the top feedrate of the move in the XY plane
  9957. const float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  9958. // If the move is only in Z/E don't split up the move
  9959. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  9960. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  9961. return false;
  9962. }
  9963. // Fail if attempting move outside printable radius
  9964. if (!position_is_reachable_xy(ltarget[X_AXIS], ltarget[Y_AXIS])) return true;
  9965. // Get the cartesian distances moved in XYZE
  9966. const float difference[XYZE] = {
  9967. ltarget[X_AXIS] - current_position[X_AXIS],
  9968. ltarget[Y_AXIS] - current_position[Y_AXIS],
  9969. ltarget[Z_AXIS] - current_position[Z_AXIS],
  9970. ltarget[E_AXIS] - current_position[E_AXIS]
  9971. };
  9972. // Get the linear distance in XYZ
  9973. float cartesian_mm = SQRT(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  9974. // If the move is very short, check the E move distance
  9975. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = FABS(difference[E_AXIS]);
  9976. // No E move either? Game over.
  9977. if (UNEAR_ZERO(cartesian_mm)) return true;
  9978. // Minimum number of seconds to move the given distance
  9979. const float seconds = cartesian_mm / _feedrate_mm_s;
  9980. // The number of segments-per-second times the duration
  9981. // gives the number of segments
  9982. uint16_t segments = delta_segments_per_second * seconds;
  9983. // For SCARA minimum segment size is 0.25mm
  9984. #if IS_SCARA
  9985. NOMORE(segments, cartesian_mm * 4);
  9986. #endif
  9987. // At least one segment is required
  9988. NOLESS(segments, 1);
  9989. // The approximate length of each segment
  9990. const float inv_segments = 1.0 / float(segments),
  9991. segment_distance[XYZE] = {
  9992. difference[X_AXIS] * inv_segments,
  9993. difference[Y_AXIS] * inv_segments,
  9994. difference[Z_AXIS] * inv_segments,
  9995. difference[E_AXIS] * inv_segments
  9996. };
  9997. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  9998. // SERIAL_ECHOPAIR(" seconds=", seconds);
  9999. // SERIAL_ECHOLNPAIR(" segments=", segments);
  10000. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  10001. // SCARA needs to scale the feed rate from mm/s to degrees/s
  10002. const float inv_segment_length = min(10.0, float(segments) / cartesian_mm), // 1/mm/segs
  10003. feed_factor = inv_segment_length * _feedrate_mm_s;
  10004. float oldA = stepper.get_axis_position_degrees(A_AXIS),
  10005. oldB = stepper.get_axis_position_degrees(B_AXIS);
  10006. #endif
  10007. // Get the logical current position as starting point
  10008. float logical[XYZE];
  10009. COPY(logical, current_position);
  10010. // Drop one segment so the last move is to the exact target.
  10011. // If there's only 1 segment, loops will be skipped entirely.
  10012. --segments;
  10013. // Calculate and execute the segments
  10014. for (uint16_t s = segments + 1; --s;) {
  10015. LOOP_XYZE(i) logical[i] += segment_distance[i];
  10016. #if ENABLED(DELTA)
  10017. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  10018. #else
  10019. inverse_kinematics(logical);
  10020. #endif
  10021. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  10022. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  10023. // For SCARA scale the feed rate from mm/s to degrees/s
  10024. // Use ratio between the length of the move and the larger angle change
  10025. const float adiff = abs(delta[A_AXIS] - oldA),
  10026. bdiff = abs(delta[B_AXIS] - oldB);
  10027. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  10028. oldA = delta[A_AXIS];
  10029. oldB = delta[B_AXIS];
  10030. #else
  10031. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  10032. #endif
  10033. }
  10034. // Since segment_distance is only approximate,
  10035. // the final move must be to the exact destination.
  10036. #if IS_SCARA && ENABLED(SCARA_FEEDRATE_SCALING)
  10037. // For SCARA scale the feed rate from mm/s to degrees/s
  10038. // With segments > 1 length is 1 segment, otherwise total length
  10039. inverse_kinematics(ltarget);
  10040. ADJUST_DELTA(ltarget);
  10041. const float adiff = abs(delta[A_AXIS] - oldA),
  10042. bdiff = abs(delta[B_AXIS] - oldB);
  10043. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], max(adiff, bdiff) * feed_factor, active_extruder);
  10044. #else
  10045. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  10046. #endif
  10047. return false;
  10048. }
  10049. #else // !IS_KINEMATIC || UBL_DELTA
  10050. /**
  10051. * Prepare a linear move in a Cartesian setup.
  10052. * If Mesh Bed Leveling is enabled, perform a mesh move.
  10053. *
  10054. * Returns true if the caller didn't update current_position.
  10055. */
  10056. inline bool prepare_move_to_destination_cartesian() {
  10057. #if ENABLED(AUTO_BED_LEVELING_UBL)
  10058. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10059. if (ubl.state.active) { // direct use of ubl.state.active for speed
  10060. ubl.line_to_destination_cartesian(fr_scaled, active_extruder);
  10061. return true;
  10062. }
  10063. else
  10064. line_to_destination(fr_scaled);
  10065. #else
  10066. // Do not use feedrate_percentage for E or Z only moves
  10067. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS])
  10068. line_to_destination();
  10069. else {
  10070. const float fr_scaled = MMS_SCALED(feedrate_mm_s);
  10071. #if ENABLED(MESH_BED_LEVELING)
  10072. if (mbl.active()) { // direct used of mbl.active() for speed
  10073. mesh_line_to_destination(fr_scaled);
  10074. return true;
  10075. }
  10076. else
  10077. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  10078. if (planner.abl_enabled) { // direct use of abl_enabled for speed
  10079. bilinear_line_to_destination(fr_scaled);
  10080. return true;
  10081. }
  10082. else
  10083. #endif
  10084. line_to_destination(fr_scaled);
  10085. }
  10086. #endif
  10087. return false;
  10088. }
  10089. #endif // !IS_KINEMATIC || UBL_DELTA
  10090. #if ENABLED(DUAL_X_CARRIAGE)
  10091. /**
  10092. * Prepare a linear move in a dual X axis setup
  10093. */
  10094. inline bool prepare_move_to_destination_dualx() {
  10095. if (active_extruder_parked) {
  10096. switch (dual_x_carriage_mode) {
  10097. case DXC_FULL_CONTROL_MODE:
  10098. break;
  10099. case DXC_AUTO_PARK_MODE:
  10100. if (current_position[E_AXIS] == destination[E_AXIS]) {
  10101. // This is a travel move (with no extrusion)
  10102. // Skip it, but keep track of the current position
  10103. // (so it can be used as the start of the next non-travel move)
  10104. if (delayed_move_time != 0xFFFFFFFFUL) {
  10105. set_current_to_destination();
  10106. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  10107. delayed_move_time = millis();
  10108. return true;
  10109. }
  10110. }
  10111. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  10112. for (uint8_t i = 0; i < 3; i++)
  10113. planner.buffer_line(
  10114. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  10115. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  10116. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  10117. current_position[E_AXIS],
  10118. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  10119. active_extruder
  10120. );
  10121. delayed_move_time = 0;
  10122. active_extruder_parked = false;
  10123. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10124. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Clear active_extruder_parked");
  10125. #endif
  10126. break;
  10127. case DXC_DUPLICATION_MODE:
  10128. if (active_extruder == 0) {
  10129. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10130. if (DEBUGGING(LEVELING)) {
  10131. SERIAL_ECHOPAIR("Set planner X", LOGICAL_X_POSITION(inactive_extruder_x_pos));
  10132. SERIAL_ECHOLNPAIR(" ... Line to X", current_position[X_AXIS] + duplicate_extruder_x_offset);
  10133. }
  10134. #endif
  10135. // move duplicate extruder into correct duplication position.
  10136. planner.set_position_mm(
  10137. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  10138. current_position[Y_AXIS],
  10139. current_position[Z_AXIS],
  10140. current_position[E_AXIS]
  10141. );
  10142. planner.buffer_line(
  10143. current_position[X_AXIS] + duplicate_extruder_x_offset,
  10144. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  10145. planner.max_feedrate_mm_s[X_AXIS], 1
  10146. );
  10147. SYNC_PLAN_POSITION_KINEMATIC();
  10148. stepper.synchronize();
  10149. extruder_duplication_enabled = true;
  10150. active_extruder_parked = false;
  10151. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10152. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Set extruder_duplication_enabled\nClear active_extruder_parked");
  10153. #endif
  10154. }
  10155. else {
  10156. #if ENABLED(DEBUG_LEVELING_FEATURE)
  10157. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Active extruder not 0");
  10158. #endif
  10159. }
  10160. break;
  10161. }
  10162. }
  10163. return false;
  10164. }
  10165. #endif // DUAL_X_CARRIAGE
  10166. /**
  10167. * Prepare a single move and get ready for the next one
  10168. *
  10169. * This may result in several calls to planner.buffer_line to
  10170. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  10171. */
  10172. void prepare_move_to_destination() {
  10173. clamp_to_software_endstops(destination);
  10174. refresh_cmd_timeout();
  10175. #if ENABLED(PREVENT_COLD_EXTRUSION)
  10176. if (!DEBUGGING(DRYRUN)) {
  10177. if (destination[E_AXIS] != current_position[E_AXIS]) {
  10178. if (thermalManager.tooColdToExtrude(active_extruder)) {
  10179. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10180. SERIAL_ECHO_START();
  10181. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  10182. }
  10183. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  10184. if (destination[E_AXIS] - current_position[E_AXIS] > EXTRUDE_MAXLENGTH) {
  10185. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  10186. SERIAL_ECHO_START();
  10187. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  10188. }
  10189. #endif
  10190. }
  10191. }
  10192. #endif
  10193. if (
  10194. #if UBL_DELTA // Also works for CARTESIAN (smaller segments follow mesh more closely)
  10195. ubl.prepare_segmented_line_to(destination, feedrate_mm_s)
  10196. #elif IS_KINEMATIC
  10197. prepare_kinematic_move_to(destination)
  10198. #elif ENABLED(DUAL_X_CARRIAGE)
  10199. prepare_move_to_destination_dualx()
  10200. #else
  10201. prepare_move_to_destination_cartesian()
  10202. #endif
  10203. ) return;
  10204. set_current_to_destination();
  10205. }
  10206. #if ENABLED(ARC_SUPPORT)
  10207. #if N_ARC_CORRECTION < 1
  10208. #undef N_ARC_CORRECTION
  10209. #define N_ARC_CORRECTION 1
  10210. #endif
  10211. /**
  10212. * Plan an arc in 2 dimensions
  10213. *
  10214. * The arc is approximated by generating many small linear segments.
  10215. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  10216. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  10217. * larger segments will tend to be more efficient. Your slicer should have
  10218. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  10219. */
  10220. void plan_arc(
  10221. float logical[XYZE], // Destination position
  10222. float *offset, // Center of rotation relative to current_position
  10223. uint8_t clockwise // Clockwise?
  10224. ) {
  10225. #if ENABLED(CNC_WORKSPACE_PLANES)
  10226. AxisEnum p_axis, q_axis, l_axis;
  10227. switch (workspace_plane) {
  10228. case PLANE_XY: p_axis = X_AXIS; q_axis = Y_AXIS; l_axis = Z_AXIS; break;
  10229. case PLANE_ZX: p_axis = Z_AXIS; q_axis = X_AXIS; l_axis = Y_AXIS; break;
  10230. case PLANE_YZ: p_axis = Y_AXIS; q_axis = Z_AXIS; l_axis = X_AXIS; break;
  10231. }
  10232. #else
  10233. constexpr AxisEnum p_axis = X_AXIS, q_axis = Y_AXIS, l_axis = Z_AXIS;
  10234. #endif
  10235. // Radius vector from center to current location
  10236. float r_P = -offset[0], r_Q = -offset[1];
  10237. const float radius = HYPOT(r_P, r_Q),
  10238. center_P = current_position[p_axis] - r_P,
  10239. center_Q = current_position[q_axis] - r_Q,
  10240. rt_X = logical[p_axis] - center_P,
  10241. rt_Y = logical[q_axis] - center_Q,
  10242. linear_travel = logical[l_axis] - current_position[l_axis],
  10243. extruder_travel = logical[E_AXIS] - current_position[E_AXIS];
  10244. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  10245. float angular_travel = ATAN2(r_P * rt_Y - r_Q * rt_X, r_P * rt_X + r_Q * rt_Y);
  10246. if (angular_travel < 0) angular_travel += RADIANS(360);
  10247. if (clockwise) angular_travel -= RADIANS(360);
  10248. // Make a circle if the angular rotation is 0 and the target is current position
  10249. if (angular_travel == 0 && current_position[p_axis] == logical[p_axis] && current_position[q_axis] == logical[q_axis])
  10250. angular_travel = RADIANS(360);
  10251. const float mm_of_travel = HYPOT(angular_travel * radius, FABS(linear_travel));
  10252. if (mm_of_travel < 0.001) return;
  10253. uint16_t segments = FLOOR(mm_of_travel / (MM_PER_ARC_SEGMENT));
  10254. if (segments == 0) segments = 1;
  10255. /**
  10256. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  10257. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  10258. * r_T = [cos(phi) -sin(phi);
  10259. * sin(phi) cos(phi)] * r ;
  10260. *
  10261. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  10262. * defined from the circle center to the initial position. Each line segment is formed by successive
  10263. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  10264. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  10265. * all double numbers are single precision on the Arduino. (True double precision will not have
  10266. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  10267. * tool precision in some cases. Therefore, arc path correction is implemented.
  10268. *
  10269. * Small angle approximation may be used to reduce computation overhead further. This approximation
  10270. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  10271. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  10272. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  10273. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  10274. * issue for CNC machines with the single precision Arduino calculations.
  10275. *
  10276. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  10277. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  10278. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  10279. * This is important when there are successive arc motions.
  10280. */
  10281. // Vector rotation matrix values
  10282. float arc_target[XYZE];
  10283. const float theta_per_segment = angular_travel / segments,
  10284. linear_per_segment = linear_travel / segments,
  10285. extruder_per_segment = extruder_travel / segments,
  10286. sin_T = theta_per_segment,
  10287. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  10288. // Initialize the linear axis
  10289. arc_target[l_axis] = current_position[l_axis];
  10290. // Initialize the extruder axis
  10291. arc_target[E_AXIS] = current_position[E_AXIS];
  10292. const float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  10293. millis_t next_idle_ms = millis() + 200UL;
  10294. #if N_ARC_CORRECTION > 1
  10295. int8_t count = N_ARC_CORRECTION;
  10296. #endif
  10297. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  10298. thermalManager.manage_heater();
  10299. if (ELAPSED(millis(), next_idle_ms)) {
  10300. next_idle_ms = millis() + 200UL;
  10301. idle();
  10302. }
  10303. #if N_ARC_CORRECTION > 1
  10304. if (--count) {
  10305. // Apply vector rotation matrix to previous r_P / 1
  10306. const float r_new_Y = r_P * sin_T + r_Q * cos_T;
  10307. r_P = r_P * cos_T - r_Q * sin_T;
  10308. r_Q = r_new_Y;
  10309. }
  10310. else
  10311. #endif
  10312. {
  10313. #if N_ARC_CORRECTION > 1
  10314. count = N_ARC_CORRECTION;
  10315. #endif
  10316. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  10317. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  10318. // To reduce stuttering, the sin and cos could be computed at different times.
  10319. // For now, compute both at the same time.
  10320. const float cos_Ti = cos(i * theta_per_segment), sin_Ti = sin(i * theta_per_segment);
  10321. r_P = -offset[0] * cos_Ti + offset[1] * sin_Ti;
  10322. r_Q = -offset[0] * sin_Ti - offset[1] * cos_Ti;
  10323. }
  10324. // Update arc_target location
  10325. arc_target[p_axis] = center_P + r_P;
  10326. arc_target[q_axis] = center_Q + r_Q;
  10327. arc_target[l_axis] += linear_per_segment;
  10328. arc_target[E_AXIS] += extruder_per_segment;
  10329. clamp_to_software_endstops(arc_target);
  10330. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  10331. }
  10332. // Ensure last segment arrives at target location.
  10333. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  10334. // As far as the parser is concerned, the position is now == target. In reality the
  10335. // motion control system might still be processing the action and the real tool position
  10336. // in any intermediate location.
  10337. set_current_to_destination();
  10338. }
  10339. #endif
  10340. #if ENABLED(BEZIER_CURVE_SUPPORT)
  10341. void plan_cubic_move(const float offset[4]) {
  10342. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  10343. // As far as the parser is concerned, the position is now == destination. In reality the
  10344. // motion control system might still be processing the action and the real tool position
  10345. // in any intermediate location.
  10346. set_current_to_destination();
  10347. }
  10348. #endif // BEZIER_CURVE_SUPPORT
  10349. #if ENABLED(USE_CONTROLLER_FAN)
  10350. void controllerFan() {
  10351. static millis_t lastMotorOn = 0, // Last time a motor was turned on
  10352. nextMotorCheck = 0; // Last time the state was checked
  10353. const millis_t ms = millis();
  10354. if (ELAPSED(ms, nextMotorCheck)) {
  10355. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  10356. 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
  10357. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  10358. #if E_STEPPERS > 1
  10359. || E1_ENABLE_READ == E_ENABLE_ON
  10360. #if HAS_X2_ENABLE
  10361. || X2_ENABLE_READ == X_ENABLE_ON
  10362. #endif
  10363. #if E_STEPPERS > 2
  10364. || E2_ENABLE_READ == E_ENABLE_ON
  10365. #if E_STEPPERS > 3
  10366. || E3_ENABLE_READ == E_ENABLE_ON
  10367. #if E_STEPPERS > 4
  10368. || E4_ENABLE_READ == E_ENABLE_ON
  10369. #endif // E_STEPPERS > 4
  10370. #endif // E_STEPPERS > 3
  10371. #endif // E_STEPPERS > 2
  10372. #endif // E_STEPPERS > 1
  10373. ) {
  10374. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  10375. }
  10376. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  10377. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  10378. // allows digital or PWM fan output to be used (see M42 handling)
  10379. WRITE(CONTROLLER_FAN_PIN, speed);
  10380. analogWrite(CONTROLLER_FAN_PIN, speed);
  10381. }
  10382. }
  10383. #endif // USE_CONTROLLER_FAN
  10384. #if ENABLED(MORGAN_SCARA)
  10385. /**
  10386. * Morgan SCARA Forward Kinematics. Results in cartes[].
  10387. * Maths and first version by QHARLEY.
  10388. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10389. */
  10390. void forward_kinematics_SCARA(const float &a, const float &b) {
  10391. float a_sin = sin(RADIANS(a)) * L1,
  10392. a_cos = cos(RADIANS(a)) * L1,
  10393. b_sin = sin(RADIANS(b)) * L2,
  10394. b_cos = cos(RADIANS(b)) * L2;
  10395. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  10396. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  10397. /*
  10398. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  10399. SERIAL_ECHOPAIR(" b=", b);
  10400. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  10401. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  10402. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  10403. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  10404. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  10405. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  10406. //*/
  10407. }
  10408. /**
  10409. * Morgan SCARA Inverse Kinematics. Results in delta[].
  10410. *
  10411. * See http://forums.reprap.org/read.php?185,283327
  10412. *
  10413. * Maths and first version by QHARLEY.
  10414. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  10415. */
  10416. void inverse_kinematics(const float logical[XYZ]) {
  10417. static float C2, S2, SK1, SK2, THETA, PSI;
  10418. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  10419. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  10420. if (L1 == L2)
  10421. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  10422. else
  10423. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  10424. S2 = SQRT(1 - sq(C2));
  10425. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  10426. SK1 = L1 + L2 * C2;
  10427. // Rotated Arm2 gives the distance from Arm1 to Arm2
  10428. SK2 = L2 * S2;
  10429. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  10430. THETA = ATAN2(SK1, SK2) - ATAN2(sx, sy);
  10431. // Angle of Arm2
  10432. PSI = ATAN2(S2, C2);
  10433. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  10434. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  10435. delta[C_AXIS] = logical[Z_AXIS];
  10436. /*
  10437. DEBUG_POS("SCARA IK", logical);
  10438. DEBUG_POS("SCARA IK", delta);
  10439. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  10440. SERIAL_ECHOPAIR(",", sy);
  10441. SERIAL_ECHOPAIR(" C2=", C2);
  10442. SERIAL_ECHOPAIR(" S2=", S2);
  10443. SERIAL_ECHOPAIR(" Theta=", THETA);
  10444. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  10445. //*/
  10446. }
  10447. #endif // MORGAN_SCARA
  10448. #if ENABLED(TEMP_STAT_LEDS)
  10449. static bool red_led = false;
  10450. static millis_t next_status_led_update_ms = 0;
  10451. void handle_status_leds(void) {
  10452. if (ELAPSED(millis(), next_status_led_update_ms)) {
  10453. next_status_led_update_ms += 500; // Update every 0.5s
  10454. float max_temp = 0.0;
  10455. #if HAS_TEMP_BED
  10456. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  10457. #endif
  10458. HOTEND_LOOP()
  10459. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  10460. const bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  10461. if (new_led != red_led) {
  10462. red_led = new_led;
  10463. #if PIN_EXISTS(STAT_LED_RED)
  10464. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  10465. #if PIN_EXISTS(STAT_LED_BLUE)
  10466. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  10467. #endif
  10468. #else
  10469. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  10470. #endif
  10471. }
  10472. }
  10473. }
  10474. #endif
  10475. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10476. void handle_filament_runout() {
  10477. if (!filament_ran_out) {
  10478. filament_ran_out = true;
  10479. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  10480. stepper.synchronize();
  10481. }
  10482. }
  10483. #endif // FILAMENT_RUNOUT_SENSOR
  10484. #if ENABLED(FAST_PWM_FAN)
  10485. void setPwmFrequency(uint8_t pin, int val) {
  10486. val &= 0x07;
  10487. switch (digitalPinToTimer(pin)) {
  10488. #ifdef TCCR0A
  10489. #if !AVR_AT90USB1286_FAMILY
  10490. case TIMER0A:
  10491. #endif
  10492. case TIMER0B:
  10493. //_SET_CS(0, val);
  10494. break;
  10495. #endif
  10496. #ifdef TCCR1A
  10497. case TIMER1A:
  10498. case TIMER1B:
  10499. //_SET_CS(1, val);
  10500. break;
  10501. #endif
  10502. #ifdef TCCR2
  10503. case TIMER2:
  10504. case TIMER2:
  10505. _SET_CS(2, val);
  10506. break;
  10507. #endif
  10508. #ifdef TCCR2A
  10509. case TIMER2A:
  10510. case TIMER2B:
  10511. _SET_CS(2, val);
  10512. break;
  10513. #endif
  10514. #ifdef TCCR3A
  10515. case TIMER3A:
  10516. case TIMER3B:
  10517. case TIMER3C:
  10518. _SET_CS(3, val);
  10519. break;
  10520. #endif
  10521. #ifdef TCCR4A
  10522. case TIMER4A:
  10523. case TIMER4B:
  10524. case TIMER4C:
  10525. _SET_CS(4, val);
  10526. break;
  10527. #endif
  10528. #ifdef TCCR5A
  10529. case TIMER5A:
  10530. case TIMER5B:
  10531. case TIMER5C:
  10532. _SET_CS(5, val);
  10533. break;
  10534. #endif
  10535. }
  10536. }
  10537. #endif // FAST_PWM_FAN
  10538. float calculate_volumetric_multiplier(const float diameter) {
  10539. if (!volumetric_enabled || diameter == 0) return 1.0;
  10540. return 1.0 / (M_PI * sq(diameter * 0.5));
  10541. }
  10542. void calculate_volumetric_multipliers() {
  10543. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  10544. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  10545. }
  10546. void enable_all_steppers() {
  10547. enable_X();
  10548. enable_Y();
  10549. enable_Z();
  10550. enable_E0();
  10551. enable_E1();
  10552. enable_E2();
  10553. enable_E3();
  10554. enable_E4();
  10555. }
  10556. void disable_e_steppers() {
  10557. disable_E0();
  10558. disable_E1();
  10559. disable_E2();
  10560. disable_E3();
  10561. disable_E4();
  10562. }
  10563. void disable_all_steppers() {
  10564. disable_X();
  10565. disable_Y();
  10566. disable_Z();
  10567. disable_e_steppers();
  10568. }
  10569. #if ENABLED(HAVE_TMC2130)
  10570. void automatic_current_control(TMC2130Stepper &st, String axisID) {
  10571. // Check otpw even if we don't use automatic control. Allows for flag inspection.
  10572. const bool is_otpw = st.checkOT();
  10573. // Report if a warning was triggered
  10574. static bool previous_otpw = false;
  10575. if (is_otpw && !previous_otpw) {
  10576. char timestamp[10];
  10577. duration_t elapsed = print_job_timer.duration();
  10578. const bool has_days = (elapsed.value > 60*60*24L);
  10579. (void)elapsed.toDigital(timestamp, has_days);
  10580. SERIAL_ECHO(timestamp);
  10581. SERIAL_ECHOPGM(": ");
  10582. SERIAL_ECHO(axisID);
  10583. SERIAL_ECHOLNPGM(" driver overtemperature warning!");
  10584. }
  10585. previous_otpw = is_otpw;
  10586. #if CURRENT_STEP > 0 && ENABLED(AUTOMATIC_CURRENT_CONTROL)
  10587. // Return if user has not enabled current control start with M906 S1.
  10588. if (!auto_current_control) return;
  10589. /**
  10590. * Decrease current if is_otpw is true.
  10591. * Bail out if driver is disabled.
  10592. * Increase current if OTPW has not been triggered yet.
  10593. */
  10594. uint16_t current = st.getCurrent();
  10595. if (is_otpw) {
  10596. st.setCurrent(current - CURRENT_STEP, R_SENSE, HOLD_MULTIPLIER);
  10597. #if ENABLED(REPORT_CURRENT_CHANGE)
  10598. SERIAL_ECHO(axisID);
  10599. SERIAL_ECHOPAIR(" current decreased to ", st.getCurrent());
  10600. #endif
  10601. }
  10602. else if (!st.isEnabled())
  10603. return;
  10604. else if (!is_otpw && !st.getOTPW()) {
  10605. current += CURRENT_STEP;
  10606. if (current <= AUTO_ADJUST_MAX) {
  10607. st.setCurrent(current, R_SENSE, HOLD_MULTIPLIER);
  10608. #if ENABLED(REPORT_CURRENT_CHANGE)
  10609. SERIAL_ECHO(axisID);
  10610. SERIAL_ECHOPAIR(" current increased to ", st.getCurrent());
  10611. #endif
  10612. }
  10613. }
  10614. SERIAL_EOL();
  10615. #endif
  10616. }
  10617. void checkOverTemp() {
  10618. static millis_t next_cOT = 0;
  10619. if (ELAPSED(millis(), next_cOT)) {
  10620. next_cOT = millis() + 5000;
  10621. #if ENABLED(X_IS_TMC2130)
  10622. automatic_current_control(stepperX, "X");
  10623. #endif
  10624. #if ENABLED(Y_IS_TMC2130)
  10625. automatic_current_control(stepperY, "Y");
  10626. #endif
  10627. #if ENABLED(Z_IS_TMC2130)
  10628. automatic_current_control(stepperZ, "Z");
  10629. #endif
  10630. #if ENABLED(X2_IS_TMC2130)
  10631. automatic_current_control(stepperX2, "X2");
  10632. #endif
  10633. #if ENABLED(Y2_IS_TMC2130)
  10634. automatic_current_control(stepperY2, "Y2");
  10635. #endif
  10636. #if ENABLED(Z2_IS_TMC2130)
  10637. automatic_current_control(stepperZ2, "Z2");
  10638. #endif
  10639. #if ENABLED(E0_IS_TMC2130)
  10640. automatic_current_control(stepperE0, "E0");
  10641. #endif
  10642. #if ENABLED(E1_IS_TMC2130)
  10643. automatic_current_control(stepperE1, "E1");
  10644. #endif
  10645. #if ENABLED(E2_IS_TMC2130)
  10646. automatic_current_control(stepperE2, "E2");
  10647. #endif
  10648. #if ENABLED(E3_IS_TMC2130)
  10649. automatic_current_control(stepperE3, "E3");
  10650. #endif
  10651. #if ENABLED(E4_IS_TMC2130)
  10652. automatic_current_control(stepperE4, "E4");
  10653. #endif
  10654. #if ENABLED(E4_IS_TMC2130)
  10655. automatic_current_control(stepperE4);
  10656. #endif
  10657. }
  10658. }
  10659. #endif // HAVE_TMC2130
  10660. /**
  10661. * Manage several activities:
  10662. * - Check for Filament Runout
  10663. * - Keep the command buffer full
  10664. * - Check for maximum inactive time between commands
  10665. * - Check for maximum inactive time between stepper commands
  10666. * - Check if pin CHDK needs to go LOW
  10667. * - Check for KILL button held down
  10668. * - Check for HOME button held down
  10669. * - Check if cooling fan needs to be switched on
  10670. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  10671. */
  10672. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  10673. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10674. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  10675. handle_filament_runout();
  10676. #endif
  10677. if (commands_in_queue < BUFSIZE) get_available_commands();
  10678. const millis_t ms = millis();
  10679. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  10680. SERIAL_ERROR_START();
  10681. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, parser.command_ptr);
  10682. kill(PSTR(MSG_KILLED));
  10683. }
  10684. // Prevent steppers timing-out in the middle of M600
  10685. #if ENABLED(ADVANCED_PAUSE_FEATURE) && ENABLED(PAUSE_PARK_NO_STEPPER_TIMEOUT)
  10686. #define MOVE_AWAY_TEST !move_away_flag
  10687. #else
  10688. #define MOVE_AWAY_TEST true
  10689. #endif
  10690. if (MOVE_AWAY_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  10691. && !ignore_stepper_queue && !planner.blocks_queued()) {
  10692. #if ENABLED(DISABLE_INACTIVE_X)
  10693. disable_X();
  10694. #endif
  10695. #if ENABLED(DISABLE_INACTIVE_Y)
  10696. disable_Y();
  10697. #endif
  10698. #if ENABLED(DISABLE_INACTIVE_Z)
  10699. disable_Z();
  10700. #endif
  10701. #if ENABLED(DISABLE_INACTIVE_E)
  10702. disable_e_steppers();
  10703. #endif
  10704. #if ENABLED(AUTO_BED_LEVELING_UBL) && ENABLED(ULTRA_LCD) // Only needed with an LCD
  10705. ubl_lcd_map_control = defer_return_to_status = false;
  10706. #endif
  10707. }
  10708. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  10709. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  10710. chdkActive = false;
  10711. WRITE(CHDK, LOW);
  10712. }
  10713. #endif
  10714. #if HAS_KILL
  10715. // Check if the kill button was pressed and wait just in case it was an accidental
  10716. // key kill key press
  10717. // -------------------------------------------------------------------------------
  10718. static int killCount = 0; // make the inactivity button a bit less responsive
  10719. const int KILL_DELAY = 750;
  10720. if (!READ(KILL_PIN))
  10721. killCount++;
  10722. else if (killCount > 0)
  10723. killCount--;
  10724. // Exceeded threshold and we can confirm that it was not accidental
  10725. // KILL the machine
  10726. // ----------------------------------------------------------------
  10727. if (killCount >= KILL_DELAY) {
  10728. SERIAL_ERROR_START();
  10729. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  10730. kill(PSTR(MSG_KILLED));
  10731. }
  10732. #endif
  10733. #if HAS_HOME
  10734. // Check to see if we have to home, use poor man's debouncer
  10735. // ---------------------------------------------------------
  10736. static int homeDebounceCount = 0; // poor man's debouncing count
  10737. const int HOME_DEBOUNCE_DELAY = 2500;
  10738. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  10739. if (!homeDebounceCount) {
  10740. enqueue_and_echo_commands_P(PSTR("G28"));
  10741. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  10742. }
  10743. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  10744. homeDebounceCount++;
  10745. else
  10746. homeDebounceCount = 0;
  10747. }
  10748. #endif
  10749. #if ENABLED(USE_CONTROLLER_FAN)
  10750. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  10751. #endif
  10752. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  10753. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  10754. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  10755. #if ENABLED(SWITCHING_EXTRUDER)
  10756. const bool oldstatus = E0_ENABLE_READ;
  10757. enable_E0();
  10758. #else // !SWITCHING_EXTRUDER
  10759. bool oldstatus;
  10760. switch (active_extruder) {
  10761. default: oldstatus = E0_ENABLE_READ; enable_E0(); break;
  10762. #if E_STEPPERS > 1
  10763. case 1: oldstatus = E1_ENABLE_READ; enable_E1(); break;
  10764. #if E_STEPPERS > 2
  10765. case 2: oldstatus = E2_ENABLE_READ; enable_E2(); break;
  10766. #if E_STEPPERS > 3
  10767. case 3: oldstatus = E3_ENABLE_READ; enable_E3(); break;
  10768. #if E_STEPPERS > 4
  10769. case 4: oldstatus = E4_ENABLE_READ; enable_E4(); break;
  10770. #endif // E_STEPPERS > 4
  10771. #endif // E_STEPPERS > 3
  10772. #endif // E_STEPPERS > 2
  10773. #endif // E_STEPPERS > 1
  10774. }
  10775. #endif // !SWITCHING_EXTRUDER
  10776. previous_cmd_ms = ms; // refresh_cmd_timeout()
  10777. const float olde = current_position[E_AXIS];
  10778. current_position[E_AXIS] += EXTRUDER_RUNOUT_EXTRUDE;
  10779. planner.buffer_line_kinematic(current_position, MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder);
  10780. current_position[E_AXIS] = olde;
  10781. planner.set_e_position_mm(olde);
  10782. stepper.synchronize();
  10783. #if ENABLED(SWITCHING_EXTRUDER)
  10784. E0_ENABLE_WRITE(oldstatus);
  10785. #else
  10786. switch (active_extruder) {
  10787. case 0: E0_ENABLE_WRITE(oldstatus); break;
  10788. #if E_STEPPERS > 1
  10789. case 1: E1_ENABLE_WRITE(oldstatus); break;
  10790. #if E_STEPPERS > 2
  10791. case 2: E2_ENABLE_WRITE(oldstatus); break;
  10792. #if E_STEPPERS > 3
  10793. case 3: E3_ENABLE_WRITE(oldstatus); break;
  10794. #if E_STEPPERS > 4
  10795. case 4: E4_ENABLE_WRITE(oldstatus); break;
  10796. #endif // E_STEPPERS > 4
  10797. #endif // E_STEPPERS > 3
  10798. #endif // E_STEPPERS > 2
  10799. #endif // E_STEPPERS > 1
  10800. }
  10801. #endif // !SWITCHING_EXTRUDER
  10802. }
  10803. #endif // EXTRUDER_RUNOUT_PREVENT
  10804. #if ENABLED(DUAL_X_CARRIAGE)
  10805. // handle delayed move timeout
  10806. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  10807. // travel moves have been received so enact them
  10808. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  10809. set_destination_to_current();
  10810. prepare_move_to_destination();
  10811. }
  10812. #endif
  10813. #if ENABLED(TEMP_STAT_LEDS)
  10814. handle_status_leds();
  10815. #endif
  10816. #if ENABLED(HAVE_TMC2130)
  10817. checkOverTemp();
  10818. #endif
  10819. planner.check_axes_activity();
  10820. }
  10821. /**
  10822. * Standard idle routine keeps the machine alive
  10823. */
  10824. void idle(
  10825. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10826. bool no_stepper_sleep/*=false*/
  10827. #endif
  10828. ) {
  10829. lcd_update();
  10830. host_keepalive();
  10831. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  10832. auto_report_temperatures();
  10833. #endif
  10834. manage_inactivity(
  10835. #if ENABLED(ADVANCED_PAUSE_FEATURE)
  10836. no_stepper_sleep
  10837. #endif
  10838. );
  10839. thermalManager.manage_heater();
  10840. #if ENABLED(PRINTCOUNTER)
  10841. print_job_timer.tick();
  10842. #endif
  10843. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  10844. buzzer.tick();
  10845. #endif
  10846. #if ENABLED(I2C_POSITION_ENCODERS)
  10847. if (planner.blocks_queued() &&
  10848. ( (blockBufferIndexRef != planner.block_buffer_head) ||
  10849. ((lastUpdateMillis + I2CPE_MIN_UPD_TIME_MS) < millis())) ) {
  10850. blockBufferIndexRef = planner.block_buffer_head;
  10851. I2CPEM.update();
  10852. lastUpdateMillis = millis();
  10853. }
  10854. #endif
  10855. }
  10856. /**
  10857. * Kill all activity and lock the machine.
  10858. * After this the machine will need to be reset.
  10859. */
  10860. void kill(const char* lcd_msg) {
  10861. SERIAL_ERROR_START();
  10862. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  10863. thermalManager.disable_all_heaters();
  10864. disable_all_steppers();
  10865. #if ENABLED(ULTRA_LCD)
  10866. kill_screen(lcd_msg);
  10867. #else
  10868. UNUSED(lcd_msg);
  10869. #endif
  10870. _delay_ms(600); // Wait a short time (allows messages to get out before shutting down.
  10871. cli(); // Stop interrupts
  10872. _delay_ms(250); //Wait to ensure all interrupts routines stopped
  10873. thermalManager.disable_all_heaters(); //turn off heaters again
  10874. #if defined(ACTION_ON_KILL)
  10875. SERIAL_ECHOLNPGM("//action:" ACTION_ON_KILL);
  10876. #endif
  10877. #if HAS_POWER_SWITCH
  10878. SET_INPUT(PS_ON_PIN);
  10879. #endif
  10880. suicide();
  10881. while (1) {
  10882. #if ENABLED(USE_WATCHDOG)
  10883. watchdog_reset();
  10884. #endif
  10885. } // Wait for reset
  10886. }
  10887. /**
  10888. * Turn off heaters and stop the print in progress
  10889. * After a stop the machine may be resumed with M999
  10890. */
  10891. void stop() {
  10892. thermalManager.disable_all_heaters(); // 'unpause' taken care of in here
  10893. #if ENABLED(PROBING_FANS_OFF)
  10894. if (fans_paused) fans_pause(false); // put things back the way they were
  10895. #endif
  10896. if (IsRunning()) {
  10897. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  10898. SERIAL_ERROR_START();
  10899. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  10900. LCD_MESSAGEPGM(MSG_STOPPED);
  10901. safe_delay(350); // allow enough time for messages to get out before stopping
  10902. Running = false;
  10903. }
  10904. }
  10905. /**
  10906. * Marlin entry-point: Set up before the program loop
  10907. * - Set up the kill pin, filament runout, power hold
  10908. * - Start the serial port
  10909. * - Print startup messages and diagnostics
  10910. * - Get EEPROM or default settings
  10911. * - Initialize managers for:
  10912. * • temperature
  10913. * • planner
  10914. * • watchdog
  10915. * • stepper
  10916. * • photo pin
  10917. * • servos
  10918. * • LCD controller
  10919. * • Digipot I2C
  10920. * • Z probe sled
  10921. * • status LEDs
  10922. */
  10923. void setup() {
  10924. #ifdef DISABLE_JTAG
  10925. // Disable JTAG on AT90USB chips to free up pins for IO
  10926. MCUCR = 0x80;
  10927. MCUCR = 0x80;
  10928. #endif
  10929. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  10930. setup_filrunoutpin();
  10931. #endif
  10932. setup_killpin();
  10933. setup_powerhold();
  10934. #if HAS_STEPPER_RESET
  10935. disableStepperDrivers();
  10936. #endif
  10937. MYSERIAL.begin(BAUDRATE);
  10938. SERIAL_PROTOCOLLNPGM("start");
  10939. SERIAL_ECHO_START();
  10940. // Check startup - does nothing if bootloader sets MCUSR to 0
  10941. byte mcu = MCUSR;
  10942. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  10943. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  10944. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  10945. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  10946. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  10947. MCUSR = 0;
  10948. SERIAL_ECHOPGM(MSG_MARLIN);
  10949. SERIAL_CHAR(' ');
  10950. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  10951. SERIAL_EOL();
  10952. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  10953. SERIAL_ECHO_START();
  10954. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  10955. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  10956. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  10957. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  10958. #endif
  10959. SERIAL_ECHO_START();
  10960. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  10961. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  10962. // Send "ok" after commands by default
  10963. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  10964. // Load data from EEPROM if available (or use defaults)
  10965. // This also updates variables in the planner, elsewhere
  10966. (void)settings.load();
  10967. #if HAS_M206_COMMAND
  10968. // Initialize current position based on home_offset
  10969. COPY(current_position, home_offset);
  10970. #else
  10971. ZERO(current_position);
  10972. #endif
  10973. // Vital to init stepper/planner equivalent for current_position
  10974. SYNC_PLAN_POSITION_KINEMATIC();
  10975. thermalManager.init(); // Initialize temperature loop
  10976. #if ENABLED(USE_WATCHDOG)
  10977. watchdog_init();
  10978. #endif
  10979. stepper.init(); // Initialize stepper, this enables interrupts!
  10980. servo_init();
  10981. #if HAS_PHOTOGRAPH
  10982. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  10983. #endif
  10984. #if HAS_CASE_LIGHT
  10985. case_light_on = CASE_LIGHT_DEFAULT_ON;
  10986. case_light_brightness = CASE_LIGHT_DEFAULT_BRIGHTNESS;
  10987. update_case_light();
  10988. #endif
  10989. #if ENABLED(SPINDLE_LASER_ENABLE)
  10990. OUT_WRITE(SPINDLE_LASER_ENABLE_PIN, !SPINDLE_LASER_ENABLE_INVERT); // init spindle to off
  10991. #if SPINDLE_DIR_CHANGE
  10992. OUT_WRITE(SPINDLE_DIR_PIN, SPINDLE_INVERT_DIR ? 255 : 0); // init rotation to clockwise (M3)
  10993. #endif
  10994. #if ENABLED(SPINDLE_LASER_PWM)
  10995. SET_OUTPUT(SPINDLE_LASER_PWM_PIN);
  10996. analogWrite(SPINDLE_LASER_PWM_PIN, SPINDLE_LASER_PWM_INVERT ? 255 : 0); // set to lowest speed
  10997. #endif
  10998. #endif
  10999. #if HAS_BED_PROBE
  11000. endstops.enable_z_probe(false);
  11001. #endif
  11002. #if ENABLED(USE_CONTROLLER_FAN)
  11003. SET_OUTPUT(CONTROLLER_FAN_PIN); //Set pin used for driver cooling fan
  11004. #endif
  11005. #if HAS_STEPPER_RESET
  11006. enableStepperDrivers();
  11007. #endif
  11008. #if ENABLED(DIGIPOT_I2C)
  11009. digipot_i2c_init();
  11010. #endif
  11011. #if ENABLED(DAC_STEPPER_CURRENT)
  11012. dac_init();
  11013. #endif
  11014. #if (ENABLED(Z_PROBE_SLED) || ENABLED(SOLENOID_PROBE)) && HAS_SOLENOID_1
  11015. OUT_WRITE(SOL1_PIN, LOW); // turn it off
  11016. #endif
  11017. #if HAS_HOME
  11018. SET_INPUT_PULLUP(HOME_PIN);
  11019. #endif
  11020. #if PIN_EXISTS(STAT_LED_RED)
  11021. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  11022. #endif
  11023. #if PIN_EXISTS(STAT_LED_BLUE)
  11024. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  11025. #endif
  11026. #if ENABLED(RGB_LED) || ENABLED(RGBW_LED)
  11027. SET_OUTPUT(RGB_LED_R_PIN);
  11028. SET_OUTPUT(RGB_LED_G_PIN);
  11029. SET_OUTPUT(RGB_LED_B_PIN);
  11030. #if ENABLED(RGBW_LED)
  11031. SET_OUTPUT(RGB_LED_W_PIN);
  11032. #endif
  11033. #endif
  11034. #if ENABLED(MK2_MULTIPLEXER)
  11035. SET_OUTPUT(E_MUX0_PIN);
  11036. SET_OUTPUT(E_MUX1_PIN);
  11037. SET_OUTPUT(E_MUX2_PIN);
  11038. #endif
  11039. lcd_init();
  11040. #ifndef CUSTOM_BOOTSCREEN_TIMEOUT
  11041. #define CUSTOM_BOOTSCREEN_TIMEOUT 2500
  11042. #endif
  11043. #if ENABLED(SHOW_BOOTSCREEN)
  11044. #if ENABLED(DOGLCD) // On DOGM the first bootscreen is already drawn
  11045. #if ENABLED(SHOW_CUSTOM_BOOTSCREEN)
  11046. safe_delay(CUSTOM_BOOTSCREEN_TIMEOUT); // Custom boot screen pause
  11047. lcd_bootscreen(); // Show Marlin boot screen
  11048. #endif
  11049. safe_delay(BOOTSCREEN_TIMEOUT); // Pause
  11050. #elif ENABLED(ULTRA_LCD)
  11051. lcd_bootscreen();
  11052. #if DISABLED(SDSUPPORT)
  11053. lcd_init();
  11054. #endif
  11055. #endif
  11056. #endif
  11057. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  11058. // Initialize mixing to 100% color 1
  11059. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11060. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  11061. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  11062. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  11063. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  11064. #endif
  11065. #if ENABLED(BLTOUCH)
  11066. // Make sure any BLTouch error condition is cleared
  11067. bltouch_command(BLTOUCH_RESET);
  11068. set_bltouch_deployed(true);
  11069. set_bltouch_deployed(false);
  11070. #endif
  11071. #if ENABLED(I2C_POSITION_ENCODERS)
  11072. I2CPEM.init();
  11073. #endif
  11074. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  11075. i2c.onReceive(i2c_on_receive);
  11076. i2c.onRequest(i2c_on_request);
  11077. #endif
  11078. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  11079. setup_endstop_interrupts();
  11080. #endif
  11081. #if ENABLED(SWITCHING_EXTRUDER)
  11082. move_extruder_servo(0); // Initialize extruder servo
  11083. #endif
  11084. #if ENABLED(SWITCHING_NOZZLE)
  11085. move_nozzle_servo(0); // Initialize nozzle servo
  11086. #endif
  11087. }
  11088. /**
  11089. * The main Marlin program loop
  11090. *
  11091. * - Save or log commands to SD
  11092. * - Process available commands (if not saving)
  11093. * - Call heater manager
  11094. * - Call inactivity manager
  11095. * - Call endstop manager
  11096. * - Call LCD update
  11097. */
  11098. void loop() {
  11099. if (commands_in_queue < BUFSIZE) get_available_commands();
  11100. #if ENABLED(SDSUPPORT)
  11101. card.checkautostart(false);
  11102. #endif
  11103. if (commands_in_queue) {
  11104. #if ENABLED(SDSUPPORT)
  11105. if (card.saving) {
  11106. char* command = command_queue[cmd_queue_index_r];
  11107. if (strstr_P(command, PSTR("M29"))) {
  11108. // M29 closes the file
  11109. card.closefile();
  11110. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  11111. ok_to_send();
  11112. }
  11113. else {
  11114. // Write the string from the read buffer to SD
  11115. card.write_command(command);
  11116. if (card.logging)
  11117. process_next_command(); // The card is saving because it's logging
  11118. else
  11119. ok_to_send();
  11120. }
  11121. }
  11122. else
  11123. process_next_command();
  11124. #else
  11125. process_next_command();
  11126. #endif // SDSUPPORT
  11127. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  11128. if (commands_in_queue) {
  11129. --commands_in_queue;
  11130. if (++cmd_queue_index_r >= BUFSIZE) cmd_queue_index_r = 0;
  11131. }
  11132. }
  11133. endstops.report_state();
  11134. idle();
  11135. }