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

Marlin_main.cpp 334KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709
  1. /**
  2. * Marlin 3D Printer Firmware
  3. * Copyright (C) 2016, 2017 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
  4. *
  5. * Based on Sprinter and grbl.
  6. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation, either version 3 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. /**
  23. * About Marlin
  24. *
  25. * This firmware is a mashup between Sprinter and grbl.
  26. * - https://github.com/kliment/Sprinter
  27. * - https://github.com/simen/grbl/tree
  28. */
  29. /**
  30. * -----------------
  31. * G-Codes in Marlin
  32. * -----------------
  33. *
  34. * Helpful G-code references:
  35. * - http://linuxcnc.org/handbook/gcode/g-code.html
  36. * - http://objects.reprap.org/wiki/Mendel_User_Manual:_RepRapGCodes
  37. *
  38. * Help to document Marlin's G-codes online:
  39. * - http://reprap.org/wiki/G-code
  40. * - https://github.com/MarlinFirmware/MarlinDocumentation
  41. *
  42. * -----------------
  43. *
  44. * "G" Codes
  45. *
  46. * G0 -> G1
  47. * G1 - Coordinated Movement X Y Z E
  48. * G2 - CW ARC
  49. * G3 - CCW ARC
  50. * G4 - Dwell S<seconds> or P<milliseconds>
  51. * G5 - Cubic B-spline with XYZE destination and IJPQ offsets
  52. * G10 - Retract filament according to settings of M207
  53. * G11 - Retract recover filament according to settings of M208
  54. * G12 - Clean tool
  55. * G20 - Set input units to inches
  56. * G21 - Set input units to millimeters
  57. * G28 - Home one or more axes
  58. * G29 - Detailed Z probe, probes the bed at 3 or more points. Will fail if you haven't homed yet.
  59. * G30 - Single Z probe, probes bed at X Y location (defaults to current XY location)
  60. * G31 - Dock sled (Z_PROBE_SLED only)
  61. * G32 - Undock sled (Z_PROBE_SLED only)
  62. * G38 - Probe target - similar to G28 except it uses the Z_MIN endstop for all three axes
  63. * G90 - Use Absolute Coordinates
  64. * G91 - Use Relative Coordinates
  65. * G92 - Set current position to coordinates given
  66. *
  67. * "M" Codes
  68. *
  69. * M0 - Unconditional stop - Wait for user to press a button on the LCD (Only if ULTRA_LCD is enabled)
  70. * M1 - Same as M0
  71. * M17 - Enable/Power all stepper motors
  72. * M18 - Disable all stepper motors; same as M84
  73. * M20 - List SD card. (Requires SDSUPPORT)
  74. * M21 - Init SD card. (Requires SDSUPPORT)
  75. * M22 - Release SD card. (Requires SDSUPPORT)
  76. * M23 - Select SD file: "M23 /path/file.gco". (Requires SDSUPPORT)
  77. * M24 - Start/resume SD print. (Requires SDSUPPORT)
  78. * M25 - Pause SD print. (Requires SDSUPPORT)
  79. * M26 - Set SD position in bytes: "M26 S12345". (Requires SDSUPPORT)
  80. * M27 - Report SD print status. (Requires SDSUPPORT)
  81. * M28 - Start SD write: "M28 /path/file.gco". (Requires SDSUPPORT)
  82. * M29 - Stop SD write. (Requires SDSUPPORT)
  83. * M30 - Delete file from SD: "M30 /path/file.gco"
  84. * M31 - Report time since last M109 or SD card start to serial.
  85. * M32 - Select file and start SD print: "M32 [S<bytepos>] !/path/file.gco#". (Requires SDSUPPORT)
  86. * Use P to run other files as sub-programs: "M32 P !filename#"
  87. * The '#' is necessary when calling from within sd files, as it stops buffer prereading
  88. * M33 - Get the longname version of a path. (Requires LONG_FILENAME_HOST_SUPPORT)
  89. * M34 - Set SD Card sorting options. (Requires SDCARD_SORT_ALPHA)
  90. * M42 - Change pin status via gcode: M42 P<pin> S<value>. LED pin assumed if P is omitted.
  91. * M43 - Monitor pins & report changes - report active pins
  92. * M48 - Measure Z Probe repeatability: M48 P<points> X<pos> Y<pos> V<level> E<engage> L<legs>. (Requires Z_MIN_PROBE_REPEATABILITY_TEST)
  93. * M75 - Start the print job timer.
  94. * M76 - Pause the print job timer.
  95. * M77 - Stop the print job timer.
  96. * M78 - Show statistical information about the print jobs. (Requires PRINTCOUNTER)
  97. * M80 - Turn on Power Supply. (Requires POWER_SUPPLY)
  98. * M81 - Turn off Power Supply. (Requires POWER_SUPPLY)
  99. * M82 - Set E codes absolute (default).
  100. * M83 - Set E codes relative while in Absolute (G90) mode.
  101. * M84 - Disable steppers until next move, or use S<seconds> to specify an idle
  102. * duration after which steppers should turn off. S0 disables the timeout.
  103. * M85 - Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  104. * M92 - Set planner.axis_steps_per_mm for one or more axes.
  105. * M104 - Set extruder target temp.
  106. * M105 - Report current temperatures.
  107. * M106 - Fan on.
  108. * M107 - Fan off.
  109. * M108 - Break out of heating loops (M109, M190, M303). With no controller, breaks out of M0/M1. (Requires EMERGENCY_PARSER)
  110. * M109 - Sxxx Wait for extruder current temp to reach target temp. Waits only when heating
  111. * Rxxx Wait for extruder current temp to reach target temp. Waits when heating and cooling
  112. * If AUTOTEMP is enabled, S<mintemp> B<maxtemp> F<factor>. Exit autotemp by any M109 without F
  113. * M110 - Set the current line number. (Used by host printing)
  114. * M111 - Set debug flags: "M111 S<flagbits>". See flag bits defined in enum.h.
  115. * M112 - Emergency stop.
  116. * M113 - Get or set the timeout interval for Host Keepalive "busy" messages. (Requires HOST_KEEPALIVE_FEATURE)
  117. * M114 - Report current position.
  118. * M115 - Report capabilities. (Extended capabilities requires EXTENDED_CAPABILITIES_REPORT)
  119. * M117 - Display a message on the controller screen. (Requires an LCD)
  120. * M119 - Report endstops status.
  121. * M120 - Enable endstops detection.
  122. * M121 - Disable endstops detection.
  123. * M126 - Solenoid Air Valve Open. (Requires BARICUDA)
  124. * M127 - Solenoid Air Valve Closed. (Requires BARICUDA)
  125. * M128 - EtoP Open. (Requires BARICUDA)
  126. * M129 - EtoP Closed. (Requires BARICUDA)
  127. * M140 - Set bed target temp. S<temp>
  128. * M145 - Set heatup values for materials on the LCD. H<hotend> B<bed> F<fan speed> for S<material> (0=PLA, 1=ABS)
  129. * M149 - Set temperature units. (Requires TEMPERATURE_UNITS_SUPPORT)
  130. * M150 - Set Status LED Color as R<red> U<green> B<blue>. Values 0-255. (Requires BLINKM or RGB_LED)
  131. * M155 - Auto-report temperatures with interval of S<seconds>. (Requires AUTO_REPORT_TEMPERATURES)
  132. * M163 - Set a single proportion for a mixing extruder. (Requires MIXING_EXTRUDER)
  133. * M164 - Save the mix as a virtual extruder. (Requires MIXING_EXTRUDER and MIXING_VIRTUAL_TOOLS)
  134. * M165 - Set the proportions for a mixing extruder. Use parameters ABCDHI to set the mixing factors. (Requires MIXING_EXTRUDER)
  135. * M190 - Sxxx Wait for bed current temp to reach target temp. ** Waits only when heating! **
  136. * Rxxx Wait for bed current temp to reach target temp. ** Waits for heating or cooling. **
  137. * M200 - Set filament diameter, D<diameter>, setting E axis units to cubic. (Use S0 to revert to linear units.)
  138. * M201 - Set max acceleration in units/s^2 for print moves: "M201 X<accel> Y<accel> Z<accel> E<accel>"
  139. * M202 - Set max acceleration in units/s^2 for travel moves: "M202 X<accel> Y<accel> Z<accel> E<accel>" ** UNUSED IN MARLIN! **
  140. * M203 - Set maximum feedrate: "M203 X<fr> Y<fr> Z<fr> E<fr>" in units/sec.
  141. * M204 - Set default acceleration in units/sec^2: P<printing> R<extruder_only> T<travel>
  142. * M205 - Set advanced settings. Current units apply:
  143. S<print> T<travel> minimum speeds
  144. B<minimum segment time>
  145. X<max X jerk>, Y<max Y jerk>, Z<max Z jerk>, E<max E jerk>
  146. * M206 - Set additional homing offset.
  147. * M207 - Set Retract Length: S<length>, Feedrate: F<units/min>, and Z lift: Z<distance>. (Requires FWRETRACT)
  148. * M208 - Set Recover (unretract) Additional (!) Length: S<length> and Feedrate: F<units/min>. (Requires FWRETRACT)
  149. * M209 - Turn Automatic Retract Detection on/off: S<0|1> (For slicers that don't support G10/11). (Requires FWRETRACT)
  150. Every normal extrude-only move will be classified as retract depending on the direction.
  151. * M211 - Enable, Disable, and/or Report software endstops: S<0|1>
  152. * M218 - Set a tool offset: "M218 T<index> X<offset> Y<offset>". (Requires 2 or more extruders)
  153. * M220 - Set Feedrate Percentage: "M220 S<percent>" (i.e., "FR" on the LCD)
  154. * M221 - Set Flow Percentage: "M221 S<percent>"
  155. * M226 - Wait until a pin is in a given state: "M226 P<pin> S<state>"
  156. * M240 - Trigger a camera to take a photograph. (Requires CHDK or PHOTOGRAPH_PIN)
  157. * M250 - Set LCD contrast: "M250 C<contrast>" (0-63). (Requires LCD support)
  158. * M260 - i2c Send Data (Requires EXPERIMENTAL_I2CBUS)
  159. * M261 - i2c Request Data (Requires EXPERIMENTAL_I2CBUS)
  160. * M280 - Set servo position absolute: "M280 P<index> S<angle|µs>". (Requires servos)
  161. * M300 - Play beep sound S<frequency Hz> P<duration ms>
  162. * M301 - Set PID parameters P I and D. (Requires PIDTEMP)
  163. * M302 - Allow cold extrudes, or set the minimum extrude S<temperature>. (Requires PREVENT_COLD_EXTRUSION)
  164. * M303 - PID relay autotune S<temperature> sets the target temperature. Default 150C. (Requires PIDTEMP)
  165. * M304 - Set bed PID parameters P I and D. (Requires PIDTEMPBED)
  166. * M355 - Turn the Case Light on/off and set its brightness. (Requires CASE_LIGHT_PIN)
  167. * M380 - Activate solenoid on active extruder. (Requires EXT_SOLENOID)
  168. * M381 - Disable all solenoids. (Requires EXT_SOLENOID)
  169. * M400 - Finish all moves.
  170. * M401 - Lower Z probe. (Requires a probe)
  171. * M402 - Raise Z probe. (Requires a probe)
  172. * M404 - Display or set the Nominal Filament Width: "W<diameter>". (Requires FILAMENT_WIDTH_SENSOR)
  173. * M405 - Enable Filament Sensor flow control. "M405 D<delay_cm>". (Requires FILAMENT_WIDTH_SENSOR)
  174. * M406 - Disable Filament Sensor flow control. (Requires FILAMENT_WIDTH_SENSOR)
  175. * M407 - Display measured filament diameter in millimeters. (Requires FILAMENT_WIDTH_SENSOR)
  176. * M410 - Quickstop. Abort all planned moves.
  177. * M420 - Enable/Disable Leveling (with current values) S1=enable S0=disable (Requires MESH_BED_LEVELING or ABL)
  178. * M421 - Set a single Z coordinate in the Mesh Leveling grid. X<units> Y<units> Z<units> (Requires MESH_BED_LEVELING)
  179. * M428 - Set the home_offset based on the current_position. Nearest edge applies.
  180. * M500 - Store parameters in EEPROM. (Requires EEPROM_SETTINGS)
  181. * M501 - Restore parameters from EEPROM. (Requires EEPROM_SETTINGS)
  182. * M502 - Revert to the default "factory settings". ** Does not write them to EEPROM! **
  183. * M503 - Print the current settings (in memory): "M503 S<verbose>". S0 specifies compact output.
  184. * M540 - Enable/disable SD card abort on endstop hit: "M540 S<state>". (Requires ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  185. * M600 - Pause for filament change: "M600 X<pos> Y<pos> Z<raise> E<first_retract> L<later_retract>". (Requires FILAMENT_CHANGE_FEATURE)
  186. * 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)
  187. * M666 - Set delta endstop adjustment. (Requires DELTA)
  188. * M605 - Set dual x-carriage movement mode: "M605 S<mode> [X<x_offset>] [R<temp_offset>]". (Requires DUAL_X_CARRIAGE)
  189. * M851 - Set Z probe's Z offset in current units. (Negative = below the nozzle.)
  190. * 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)
  191. * M907 - Set digital trimpot motor current using axis codes. (Requires a board with digital trimpots)
  192. * M908 - Control digital trimpot directly. (Requires DAC_STEPPER_CURRENT or DIGIPOTSS_PIN)
  193. * M909 - Print digipot/DAC current value. (Requires DAC_STEPPER_CURRENT)
  194. * M910 - Commit digipot/DAC value to external EEPROM via I2C. (Requires DAC_STEPPER_CURRENT)
  195. * M911 - Report stepper driver overtemperature pre-warn condition. (Requires HAVE_TMC2130)
  196. * M912 - Clear stepper driver overtemperature pre-warn condition flag. (Requires HAVE_TMC2130)
  197. * M350 - Set microstepping mode. (Requires digital microstepping pins.)
  198. * M351 - Toggle MS1 MS2 pins directly. (Requires digital microstepping pins.)
  199. *
  200. * ************ SCARA Specific - This can change to suit future G-code regulations
  201. * M360 - SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  202. * M361 - SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  203. * M362 - SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  204. * M363 - SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  205. * M364 - SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  206. * ************* SCARA End ***************
  207. *
  208. * ************ Custom codes - This can change to suit future G-code regulations
  209. * M100 - Watch Free Memory (For Debugging). (Requires M100_FREE_MEMORY_WATCHER)
  210. * M928 - Start SD logging: "M928 filename.gco". Stop with M29. (Requires SDSUPPORT)
  211. * M999 - Restart after being stopped by error
  212. *
  213. * "T" Codes
  214. *
  215. * T0-T3 - Select an extruder (tool) by index: "T<n> F<units/min>"
  216. *
  217. */
  218. #include "Marlin.h"
  219. #include "ultralcd.h"
  220. #include "planner.h"
  221. #include "stepper.h"
  222. #include "endstops.h"
  223. #include "temperature.h"
  224. #include "cardreader.h"
  225. #include "configuration_store.h"
  226. #include "language.h"
  227. #include "pins_arduino.h"
  228. #include "math.h"
  229. #include "nozzle.h"
  230. #include "duration_t.h"
  231. #include "types.h"
  232. #if ENABLED(AUTO_BED_LEVELING_UBL)
  233. #include "UBL.h"
  234. #endif
  235. #if HAS_ABL
  236. #include "vector_3.h"
  237. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  238. #include "qr_solve.h"
  239. #endif
  240. #elif ENABLED(MESH_BED_LEVELING)
  241. #include "mesh_bed_leveling.h"
  242. #endif
  243. #if ENABLED(BEZIER_CURVE_SUPPORT)
  244. #include "planner_bezier.h"
  245. #endif
  246. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  247. #include "buzzer.h"
  248. #endif
  249. #if ENABLED(USE_WATCHDOG)
  250. #include "watchdog.h"
  251. #endif
  252. #if ENABLED(BLINKM)
  253. #include "blinkm.h"
  254. #include "Wire.h"
  255. #endif
  256. #if HAS_SERVOS
  257. #include "servo.h"
  258. #endif
  259. #if HAS_DIGIPOTSS
  260. #include <SPI.h>
  261. #endif
  262. #if ENABLED(DAC_STEPPER_CURRENT)
  263. #include "stepper_dac.h"
  264. #endif
  265. #if ENABLED(EXPERIMENTAL_I2CBUS)
  266. #include "twibus.h"
  267. #endif
  268. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  269. #include "endstop_interrupts.h"
  270. #endif
  271. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  272. void gcode_M100();
  273. #endif
  274. #if ENABLED(SDSUPPORT)
  275. CardReader card;
  276. #endif
  277. #if ENABLED(EXPERIMENTAL_I2CBUS)
  278. TWIBus i2c;
  279. #endif
  280. #if ENABLED(G38_PROBE_TARGET)
  281. bool G38_move = false,
  282. G38_endstop_hit = false;
  283. #endif
  284. #if ENABLED(AUTO_BED_LEVELING_UBL)
  285. bed_leveling blm;
  286. #endif
  287. bool Running = true;
  288. uint8_t marlin_debug_flags = DEBUG_NONE;
  289. /**
  290. * Cartesian Current Position
  291. * Used to track the logical position as moves are queued.
  292. * Used by 'line_to_current_position' to do a move after changing it.
  293. * Used by 'SYNC_PLAN_POSITION_KINEMATIC' to update 'planner.position'.
  294. */
  295. float current_position[XYZE] = { 0.0 };
  296. /**
  297. * Cartesian Destination
  298. * A temporary position, usually applied to 'current_position'.
  299. * Set with 'gcode_get_destination' or 'set_destination_to_current'.
  300. * 'line_to_destination' sets 'current_position' to 'destination'.
  301. */
  302. float destination[XYZE] = { 0.0 };
  303. /**
  304. * axis_homed
  305. * Flags that each linear axis was homed.
  306. * XYZ on cartesian, ABC on delta, ABZ on SCARA.
  307. *
  308. * axis_known_position
  309. * Flags that the position is known in each linear axis. Set when homed.
  310. * Cleared whenever a stepper powers off, potentially losing its position.
  311. */
  312. bool axis_homed[XYZ] = { false }, axis_known_position[XYZ] = { false };
  313. /**
  314. * GCode line number handling. Hosts may opt to include line numbers when
  315. * sending commands to Marlin, and lines will be checked for sequentiality.
  316. * M110 N<int> sets the current line number.
  317. */
  318. static long gcode_N, gcode_LastN, Stopped_gcode_LastN = 0;
  319. /**
  320. * GCode Command Queue
  321. * A simple ring buffer of BUFSIZE command strings.
  322. *
  323. * Commands are copied into this buffer by the command injectors
  324. * (immediate, serial, sd card) and they are processed sequentially by
  325. * the main loop. The process_next_command function parses the next
  326. * command and hands off execution to individual handler functions.
  327. */
  328. static char command_queue[BUFSIZE][MAX_CMD_SIZE];
  329. static uint8_t cmd_queue_index_r = 0, // Ring buffer read position
  330. cmd_queue_index_w = 0, // Ring buffer write position
  331. commands_in_queue = 0; // Count of commands in the queue
  332. /**
  333. * Current GCode Command
  334. * When a GCode handler is running, these will be set
  335. */
  336. static char *current_command, // The command currently being executed
  337. *current_command_args, // The address where arguments begin
  338. *seen_pointer; // Set by code_seen(), used by the code_value functions
  339. /**
  340. * Next Injected Command pointer. NULL if no commands are being injected.
  341. * Used by Marlin internally to ensure that commands initiated from within
  342. * are enqueued ahead of any pending serial or sd card commands.
  343. */
  344. static const char *injected_commands_P = NULL;
  345. #if ENABLED(INCH_MODE_SUPPORT)
  346. float linear_unit_factor = 1.0, volumetric_unit_factor = 1.0;
  347. #endif
  348. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  349. TempUnit input_temp_units = TEMPUNIT_C;
  350. #endif
  351. /**
  352. * Feed rates are often configured with mm/m
  353. * but the planner and stepper like mm/s units.
  354. */
  355. float constexpr homing_feedrate_mm_s[] = {
  356. #if ENABLED(DELTA)
  357. MMM_TO_MMS(HOMING_FEEDRATE_Z), MMM_TO_MMS(HOMING_FEEDRATE_Z),
  358. #else
  359. MMM_TO_MMS(HOMING_FEEDRATE_XY), MMM_TO_MMS(HOMING_FEEDRATE_XY),
  360. #endif
  361. MMM_TO_MMS(HOMING_FEEDRATE_Z), 0
  362. };
  363. static float feedrate_mm_s = MMM_TO_MMS(1500.0), saved_feedrate_mm_s;
  364. int feedrate_percentage = 100, saved_feedrate_percentage,
  365. flow_percentage[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(100);
  366. bool axis_relative_modes[] = AXIS_RELATIVE_MODES,
  367. volumetric_enabled =
  368. #if ENABLED(VOLUMETRIC_DEFAULT_ON)
  369. true
  370. #else
  371. false
  372. #endif
  373. ;
  374. float filament_size[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(DEFAULT_NOMINAL_FILAMENT_DIA),
  375. volumetric_multiplier[EXTRUDERS] = ARRAY_BY_EXTRUDERS1(1.0);
  376. #if DISABLED(NO_WORKSPACE_OFFSETS)
  377. // The distance that XYZ has been offset by G92. Reset by G28.
  378. float position_shift[XYZ] = { 0 };
  379. // This offset is added to the configured home position.
  380. // Set by M206, M428, or menu item. Saved to EEPROM.
  381. float home_offset[XYZ] = { 0 };
  382. // The above two are combined to save on computes
  383. float workspace_offset[XYZ] = { 0 };
  384. #endif
  385. // Software Endstops are based on the configured limits.
  386. #if HAS_SOFTWARE_ENDSTOPS
  387. bool soft_endstops_enabled = true;
  388. #endif
  389. float soft_endstop_min[XYZ] = { X_MIN_POS, Y_MIN_POS, Z_MIN_POS },
  390. soft_endstop_max[XYZ] = { X_MAX_POS, Y_MAX_POS, Z_MAX_POS };
  391. #if FAN_COUNT > 0
  392. int fanSpeeds[FAN_COUNT] = { 0 };
  393. #endif
  394. // The active extruder (tool). Set with T<extruder> command.
  395. uint8_t active_extruder = 0;
  396. // Relative Mode. Enable with G91, disable with G90.
  397. static bool relative_mode = false;
  398. // For M109 and M190, this flag may be cleared (by M108) to exit the wait loop
  399. volatile bool wait_for_heatup = true;
  400. // For M0/M1, this flag may be cleared (by M108) to exit the wait-for-user loop
  401. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  402. volatile bool wait_for_user = false;
  403. #endif
  404. const char errormagic[] PROGMEM = "Error:";
  405. const char echomagic[] PROGMEM = "echo:";
  406. const char axis_codes[NUM_AXIS] = {'X', 'Y', 'Z', 'E'};
  407. // Number of characters read in the current line of serial input
  408. static int serial_count = 0;
  409. // Inactivity shutdown
  410. millis_t previous_cmd_ms = 0;
  411. static millis_t max_inactive_time = 0;
  412. static millis_t stepper_inactive_time = (DEFAULT_STEPPER_DEACTIVE_TIME) * 1000UL;
  413. // Print Job Timer
  414. #if ENABLED(PRINTCOUNTER)
  415. PrintCounter print_job_timer = PrintCounter();
  416. #else
  417. Stopwatch print_job_timer = Stopwatch();
  418. #endif
  419. // Buzzer - I2C on the LCD or a BEEPER_PIN
  420. #if ENABLED(LCD_USE_I2C_BUZZER)
  421. #define BUZZ(d,f) lcd_buzz(d, f)
  422. #elif PIN_EXISTS(BEEPER)
  423. Buzzer buzzer;
  424. #define BUZZ(d,f) buzzer.tone(d, f)
  425. #else
  426. #define BUZZ(d,f) NOOP
  427. #endif
  428. static uint8_t target_extruder;
  429. #if HAS_BED_PROBE
  430. float zprobe_zoffset = Z_PROBE_OFFSET_FROM_EXTRUDER;
  431. #endif
  432. #define PLANNER_XY_FEEDRATE() (min(planner.max_feedrate_mm_s[X_AXIS], planner.max_feedrate_mm_s[Y_AXIS]))
  433. #if HAS_ABL
  434. float xy_probe_feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  435. #define XY_PROBE_FEEDRATE_MM_S xy_probe_feedrate_mm_s
  436. #elif defined(XY_PROBE_SPEED)
  437. #define XY_PROBE_FEEDRATE_MM_S MMM_TO_MMS(XY_PROBE_SPEED)
  438. #else
  439. #define XY_PROBE_FEEDRATE_MM_S PLANNER_XY_FEEDRATE()
  440. #endif
  441. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  442. #if ENABLED(DELTA)
  443. #define ADJUST_DELTA(V) \
  444. if (planner.abl_enabled) { \
  445. const float zadj = bilinear_z_offset(V); \
  446. delta[A_AXIS] += zadj; \
  447. delta[B_AXIS] += zadj; \
  448. delta[C_AXIS] += zadj; \
  449. }
  450. #else
  451. #define ADJUST_DELTA(V) if (planner.abl_enabled) { delta[Z_AXIS] += bilinear_z_offset(V); }
  452. #endif
  453. #elif IS_KINEMATIC
  454. #define ADJUST_DELTA(V) NOOP
  455. #endif
  456. #if ENABLED(Z_DUAL_ENDSTOPS)
  457. float z_endstop_adj = 0;
  458. #endif
  459. // Extruder offsets
  460. #if HOTENDS > 1
  461. float hotend_offset[XYZ][HOTENDS];
  462. #endif
  463. #if HAS_Z_SERVO_ENDSTOP
  464. const int z_servo_angle[2] = Z_SERVO_ANGLES;
  465. #endif
  466. #if ENABLED(BARICUDA)
  467. int baricuda_valve_pressure = 0;
  468. int baricuda_e_to_p_pressure = 0;
  469. #endif
  470. #if ENABLED(FWRETRACT)
  471. bool autoretract_enabled = false;
  472. bool retracted[EXTRUDERS] = { false };
  473. bool retracted_swap[EXTRUDERS] = { false };
  474. float retract_length = RETRACT_LENGTH;
  475. float retract_length_swap = RETRACT_LENGTH_SWAP;
  476. float retract_feedrate_mm_s = RETRACT_FEEDRATE;
  477. float retract_zlift = RETRACT_ZLIFT;
  478. float retract_recover_length = RETRACT_RECOVER_LENGTH;
  479. float retract_recover_length_swap = RETRACT_RECOVER_LENGTH_SWAP;
  480. float retract_recover_feedrate_mm_s = RETRACT_RECOVER_FEEDRATE;
  481. #endif // FWRETRACT
  482. #if ENABLED(ULTIPANEL) && HAS_POWER_SWITCH
  483. bool powersupply =
  484. #if ENABLED(PS_DEFAULT_OFF)
  485. false
  486. #else
  487. true
  488. #endif
  489. ;
  490. #endif
  491. #if HAS_CASE_LIGHT
  492. bool case_light_on =
  493. #if ENABLED(CASE_LIGHT_DEFAULT_ON)
  494. true
  495. #else
  496. false
  497. #endif
  498. ;
  499. #endif
  500. #if ENABLED(DELTA)
  501. float delta[ABC],
  502. endstop_adj[ABC] = { 0 };
  503. // These values are loaded or reset at boot time when setup() calls
  504. // Config_RetrieveSettings(), which calls recalc_delta_settings().
  505. float delta_radius,
  506. delta_tower_angle_trim[ABC],
  507. delta_tower[ABC][2],
  508. delta_diagonal_rod,
  509. delta_diagonal_rod_trim[ABC],
  510. delta_diagonal_rod_2_tower[ABC],
  511. delta_segments_per_second,
  512. delta_clip_start_height = Z_MAX_POS;
  513. float delta_safe_distance_from_top();
  514. #endif
  515. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  516. #define UNPROBED 9999.0f
  517. int bilinear_grid_spacing[2], bilinear_start[2];
  518. float bed_level_grid[ABL_GRID_MAX_POINTS_X][ABL_GRID_MAX_POINTS_Y];
  519. #endif
  520. #if IS_SCARA
  521. // Float constants for SCARA calculations
  522. const float L1 = SCARA_LINKAGE_1, L2 = SCARA_LINKAGE_2,
  523. L1_2 = sq(float(L1)), L1_2_2 = 2.0 * L1_2,
  524. L2_2 = sq(float(L2));
  525. float delta_segments_per_second = SCARA_SEGMENTS_PER_SECOND,
  526. delta[ABC];
  527. #endif
  528. float cartes[XYZ] = { 0 };
  529. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  530. bool filament_sensor = false; //M405 turns on filament_sensor control, M406 turns it off
  531. float filament_width_nominal = DEFAULT_NOMINAL_FILAMENT_DIA, // Nominal filament width. Change with M404
  532. filament_width_meas = DEFAULT_MEASURED_FILAMENT_DIA; // Measured filament diameter
  533. int8_t measurement_delay[MAX_MEASUREMENT_DELAY + 1]; // Ring buffer to delayed measurement. Store extruder factor after subtracting 100
  534. int filwidth_delay_index[2] = { 0, -1 }; // Indexes into ring buffer
  535. int meas_delay_cm = MEASUREMENT_DELAY_CM; //distance delay setting
  536. #endif
  537. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  538. static bool filament_ran_out = false;
  539. #endif
  540. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  541. FilamentChangeMenuResponse filament_change_menu_response;
  542. #endif
  543. #if ENABLED(MIXING_EXTRUDER)
  544. float mixing_factor[MIXING_STEPPERS]; // Reciprocal of mix proportion. 0.0 = off, otherwise >= 1.0.
  545. #if MIXING_VIRTUAL_TOOLS > 1
  546. float mixing_virtual_tool_mix[MIXING_VIRTUAL_TOOLS][MIXING_STEPPERS];
  547. #endif
  548. #endif
  549. static bool send_ok[BUFSIZE];
  550. #if HAS_SERVOS
  551. Servo servo[NUM_SERVOS];
  552. #define MOVE_SERVO(I, P) servo[I].move(P)
  553. #if HAS_Z_SERVO_ENDSTOP
  554. #define DEPLOY_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[0])
  555. #define STOW_Z_SERVO() MOVE_SERVO(Z_ENDSTOP_SERVO_NR, z_servo_angle[1])
  556. #endif
  557. #endif
  558. #ifdef CHDK
  559. millis_t chdkHigh = 0;
  560. bool chdkActive = false;
  561. #endif
  562. #if ENABLED(PID_EXTRUSION_SCALING)
  563. int lpq_len = 20;
  564. #endif
  565. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  566. static MarlinBusyState busy_state = NOT_BUSY;
  567. static millis_t next_busy_signal_ms = 0;
  568. uint8_t host_keepalive_interval = DEFAULT_KEEPALIVE_INTERVAL;
  569. #define KEEPALIVE_STATE(n) do{ busy_state = n; }while(0)
  570. #else
  571. #define host_keepalive() ;
  572. #define KEEPALIVE_STATE(n) ;
  573. #endif // HOST_KEEPALIVE_FEATURE
  574. #define DEFINE_PGM_READ_ANY(type, reader) \
  575. static inline type pgm_read_any(const type *p) \
  576. { return pgm_read_##reader##_near(p); }
  577. DEFINE_PGM_READ_ANY(float, float)
  578. DEFINE_PGM_READ_ANY(signed char, byte)
  579. #define XYZ_CONSTS_FROM_CONFIG(type, array, CONFIG) \
  580. static const PROGMEM type array##_P[XYZ] = \
  581. { X_##CONFIG, Y_##CONFIG, Z_##CONFIG }; \
  582. static inline type array(int axis) \
  583. { return pgm_read_any(&array##_P[axis]); }
  584. XYZ_CONSTS_FROM_CONFIG(float, base_min_pos, MIN_POS)
  585. XYZ_CONSTS_FROM_CONFIG(float, base_max_pos, MAX_POS)
  586. XYZ_CONSTS_FROM_CONFIG(float, base_home_pos, HOME_POS)
  587. XYZ_CONSTS_FROM_CONFIG(float, max_length, MAX_LENGTH)
  588. XYZ_CONSTS_FROM_CONFIG(float, home_bump_mm, HOME_BUMP_MM)
  589. XYZ_CONSTS_FROM_CONFIG(signed char, home_dir, HOME_DIR)
  590. /**
  591. * ***************************************************************************
  592. * ******************************** FUNCTIONS ********************************
  593. * ***************************************************************************
  594. */
  595. void stop();
  596. void get_available_commands();
  597. void process_next_command();
  598. void prepare_move_to_destination();
  599. void get_cartesian_from_steppers();
  600. void set_current_from_steppers_for_axis(const AxisEnum axis);
  601. #if ENABLED(ARC_SUPPORT)
  602. void plan_arc(float target[NUM_AXIS], float* offset, uint8_t clockwise);
  603. #endif
  604. #if ENABLED(BEZIER_CURVE_SUPPORT)
  605. void plan_cubic_move(const float offset[4]);
  606. #endif
  607. void serial_echopair_P(const char* s_P, const char *v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  608. void serial_echopair_P(const char* s_P, char v) { serialprintPGM(s_P); SERIAL_CHAR(v); }
  609. void serial_echopair_P(const char* s_P, int v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  610. void serial_echopair_P(const char* s_P, long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  611. void serial_echopair_P(const char* s_P, float v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  612. void serial_echopair_P(const char* s_P, double v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  613. void serial_echopair_P(const char* s_P, unsigned long v) { serialprintPGM(s_P); SERIAL_ECHO(v); }
  614. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s=0.0, bool no_move=false);
  615. static void report_current_position();
  616. #if ENABLED(DEBUG_LEVELING_FEATURE)
  617. void print_xyz(const char* prefix, const char* suffix, const float x, const float y, const float z) {
  618. serialprintPGM(prefix);
  619. SERIAL_ECHOPAIR("(", x);
  620. SERIAL_ECHOPAIR(", ", y);
  621. SERIAL_ECHOPAIR(", ", z);
  622. SERIAL_CHAR(')');
  623. if (suffix) serialprintPGM(suffix);
  624. else SERIAL_EOL;
  625. }
  626. void print_xyz(const char* prefix, const char* suffix, const float xyz[]) {
  627. print_xyz(prefix, suffix, xyz[X_AXIS], xyz[Y_AXIS], xyz[Z_AXIS]);
  628. }
  629. #if HAS_ABL
  630. void print_xyz(const char* prefix, const char* suffix, const vector_3 &xyz) {
  631. print_xyz(prefix, suffix, xyz.x, xyz.y, xyz.z);
  632. }
  633. #endif
  634. #define DEBUG_POS(SUFFIX,VAR) do { \
  635. print_xyz(PSTR(" " STRINGIFY(VAR) "="), PSTR(" : " SUFFIX "\n"), VAR); } while(0)
  636. #endif
  637. /**
  638. * sync_plan_position
  639. *
  640. * Set the planner/stepper positions directly from current_position with
  641. * no kinematic translation. Used for homing axes and cartesian/core syncing.
  642. */
  643. inline void sync_plan_position() {
  644. #if ENABLED(DEBUG_LEVELING_FEATURE)
  645. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position", current_position);
  646. #endif
  647. planner.set_position_mm(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS]);
  648. }
  649. inline void sync_plan_position_e() { planner.set_e_position_mm(current_position[E_AXIS]); }
  650. #if IS_KINEMATIC
  651. inline void sync_plan_position_kinematic() {
  652. #if ENABLED(DEBUG_LEVELING_FEATURE)
  653. if (DEBUGGING(LEVELING)) DEBUG_POS("sync_plan_position_kinematic", current_position);
  654. #endif
  655. planner.set_position_mm_kinematic(current_position);
  656. }
  657. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position_kinematic()
  658. #else
  659. #define SYNC_PLAN_POSITION_KINEMATIC() sync_plan_position()
  660. #endif
  661. #if ENABLED(SDSUPPORT)
  662. #include "SdFatUtil.h"
  663. int freeMemory() { return SdFatUtil::FreeRam(); }
  664. #else
  665. extern "C" {
  666. extern char __bss_end;
  667. extern char __heap_start;
  668. extern void* __brkval;
  669. int freeMemory() {
  670. int free_memory;
  671. if ((int)__brkval == 0)
  672. free_memory = ((int)&free_memory) - ((int)&__bss_end);
  673. else
  674. free_memory = ((int)&free_memory) - ((int)__brkval);
  675. return free_memory;
  676. }
  677. }
  678. #endif //!SDSUPPORT
  679. #if ENABLED(DIGIPOT_I2C)
  680. extern void digipot_i2c_set_current(int channel, float current);
  681. extern void digipot_i2c_init();
  682. #endif
  683. /**
  684. * Inject the next "immediate" command, when possible.
  685. * Return true if any immediate commands remain to inject.
  686. */
  687. static bool drain_injected_commands_P() {
  688. if (injected_commands_P != NULL) {
  689. size_t i = 0;
  690. char c, cmd[30];
  691. strncpy_P(cmd, injected_commands_P, sizeof(cmd) - 1);
  692. cmd[sizeof(cmd) - 1] = '\0';
  693. while ((c = cmd[i]) && c != '\n') i++; // find the end of this gcode command
  694. cmd[i] = '\0';
  695. if (enqueue_and_echo_command(cmd)) { // success?
  696. if (c) // newline char?
  697. injected_commands_P += i + 1; // advance to the next command
  698. else
  699. injected_commands_P = NULL; // nul char? no more commands
  700. }
  701. }
  702. return (injected_commands_P != NULL); // return whether any more remain
  703. }
  704. /**
  705. * Record one or many commands to run from program memory.
  706. * Aborts the current queue, if any.
  707. * Note: drain_injected_commands_P() must be called repeatedly to drain the commands afterwards
  708. */
  709. void enqueue_and_echo_commands_P(const char* pgcode) {
  710. injected_commands_P = pgcode;
  711. drain_injected_commands_P(); // first command executed asap (when possible)
  712. }
  713. void clear_command_queue() {
  714. cmd_queue_index_r = cmd_queue_index_w;
  715. commands_in_queue = 0;
  716. }
  717. /**
  718. * Once a new command is in the ring buffer, call this to commit it
  719. */
  720. inline void _commit_command(bool say_ok) {
  721. send_ok[cmd_queue_index_w] = say_ok;
  722. cmd_queue_index_w = (cmd_queue_index_w + 1) % BUFSIZE;
  723. commands_in_queue++;
  724. }
  725. /**
  726. * Copy a command directly into the main command buffer, from RAM.
  727. * Returns true if successfully adds the command
  728. */
  729. inline bool _enqueuecommand(const char* cmd, bool say_ok=false) {
  730. if (*cmd == ';' || commands_in_queue >= BUFSIZE) return false;
  731. strcpy(command_queue[cmd_queue_index_w], cmd);
  732. _commit_command(say_ok);
  733. return true;
  734. }
  735. void enqueue_and_echo_command_now(const char* cmd) {
  736. while (!enqueue_and_echo_command(cmd)) idle();
  737. }
  738. /**
  739. * Enqueue with Serial Echo
  740. */
  741. bool enqueue_and_echo_command(const char* cmd, bool say_ok/*=false*/) {
  742. if (_enqueuecommand(cmd, say_ok)) {
  743. SERIAL_ECHO_START;
  744. SERIAL_ECHOPAIR(MSG_Enqueueing, cmd);
  745. SERIAL_CHAR('"');
  746. SERIAL_EOL;
  747. return true;
  748. }
  749. return false;
  750. }
  751. void setup_killpin() {
  752. #if HAS_KILL
  753. SET_INPUT_PULLUP(KILL_PIN);
  754. #endif
  755. }
  756. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  757. void setup_filrunoutpin() {
  758. #if ENABLED(ENDSTOPPULLUP_FIL_RUNOUT)
  759. SET_INPUT_PULLUP(FIL_RUNOUT_PIN);
  760. #else
  761. SET_INPUT(FIL_RUNOUT_PIN);
  762. #endif
  763. }
  764. #endif
  765. // Set home pin
  766. void setup_homepin(void) {
  767. #if HAS_HOME
  768. SET_INPUT_PULLUP(HOME_PIN);
  769. #endif
  770. }
  771. void setup_powerhold() {
  772. #if HAS_SUICIDE
  773. OUT_WRITE(SUICIDE_PIN, HIGH);
  774. #endif
  775. #if HAS_POWER_SWITCH
  776. #if ENABLED(PS_DEFAULT_OFF)
  777. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  778. #else
  779. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE);
  780. #endif
  781. #endif
  782. }
  783. void suicide() {
  784. #if HAS_SUICIDE
  785. OUT_WRITE(SUICIDE_PIN, LOW);
  786. #endif
  787. }
  788. void servo_init() {
  789. #if NUM_SERVOS >= 1 && HAS_SERVO_0
  790. servo[0].attach(SERVO0_PIN);
  791. servo[0].detach(); // Just set up the pin. We don't have a position yet. Don't move to a random position.
  792. #endif
  793. #if NUM_SERVOS >= 2 && HAS_SERVO_1
  794. servo[1].attach(SERVO1_PIN);
  795. servo[1].detach();
  796. #endif
  797. #if NUM_SERVOS >= 3 && HAS_SERVO_2
  798. servo[2].attach(SERVO2_PIN);
  799. servo[2].detach();
  800. #endif
  801. #if NUM_SERVOS >= 4 && HAS_SERVO_3
  802. servo[3].attach(SERVO3_PIN);
  803. servo[3].detach();
  804. #endif
  805. #if HAS_Z_SERVO_ENDSTOP
  806. /**
  807. * Set position of Z Servo Endstop
  808. *
  809. * The servo might be deployed and positioned too low to stow
  810. * when starting up the machine or rebooting the board.
  811. * There's no way to know where the nozzle is positioned until
  812. * homing has been done - no homing with z-probe without init!
  813. *
  814. */
  815. STOW_Z_SERVO();
  816. #endif
  817. }
  818. /**
  819. * Stepper Reset (RigidBoard, et.al.)
  820. */
  821. #if HAS_STEPPER_RESET
  822. void disableStepperDrivers() {
  823. OUT_WRITE(STEPPER_RESET_PIN, LOW); // drive it down to hold in reset motor driver chips
  824. }
  825. void enableStepperDrivers() { SET_INPUT(STEPPER_RESET_PIN); } // set to input, which allows it to be pulled high by pullups
  826. #endif
  827. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  828. void i2c_on_receive(int bytes) { // just echo all bytes received to serial
  829. i2c.receive(bytes);
  830. }
  831. void i2c_on_request() { // just send dummy data for now
  832. i2c.reply("Hello World!\n");
  833. }
  834. #endif
  835. void gcode_line_error(const char* err, bool doFlush = true) {
  836. SERIAL_ERROR_START;
  837. serialprintPGM(err);
  838. SERIAL_ERRORLN(gcode_LastN);
  839. //Serial.println(gcode_N);
  840. if (doFlush) FlushSerialRequestResend();
  841. serial_count = 0;
  842. }
  843. inline void get_serial_commands() {
  844. static char serial_line_buffer[MAX_CMD_SIZE];
  845. static bool serial_comment_mode = false;
  846. // If the command buffer is empty for too long,
  847. // send "wait" to indicate Marlin is still waiting.
  848. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  849. static millis_t last_command_time = 0;
  850. millis_t ms = millis();
  851. if (commands_in_queue == 0 && !MYSERIAL.available() && ELAPSED(ms, last_command_time + NO_TIMEOUTS)) {
  852. SERIAL_ECHOLNPGM(MSG_WAIT);
  853. last_command_time = ms;
  854. }
  855. #endif
  856. /**
  857. * Loop while serial characters are incoming and the queue is not full
  858. */
  859. while (commands_in_queue < BUFSIZE && MYSERIAL.available() > 0) {
  860. char serial_char = MYSERIAL.read();
  861. /**
  862. * If the character ends the line
  863. */
  864. if (serial_char == '\n' || serial_char == '\r') {
  865. serial_comment_mode = false; // end of line == end of comment
  866. if (!serial_count) continue; // skip empty lines
  867. serial_line_buffer[serial_count] = 0; // terminate string
  868. serial_count = 0; //reset buffer
  869. char* command = serial_line_buffer;
  870. while (*command == ' ') command++; // skip any leading spaces
  871. char* npos = (*command == 'N') ? command : NULL; // Require the N parameter to start the line
  872. char* apos = strchr(command, '*');
  873. if (npos) {
  874. bool M110 = strstr_P(command, PSTR("M110")) != NULL;
  875. if (M110) {
  876. char* n2pos = strchr(command + 4, 'N');
  877. if (n2pos) npos = n2pos;
  878. }
  879. gcode_N = strtol(npos + 1, NULL, 10);
  880. if (gcode_N != gcode_LastN + 1 && !M110) {
  881. gcode_line_error(PSTR(MSG_ERR_LINE_NO));
  882. return;
  883. }
  884. if (apos) {
  885. byte checksum = 0, count = 0;
  886. while (command[count] != '*') checksum ^= command[count++];
  887. if (strtol(apos + 1, NULL, 10) != checksum) {
  888. gcode_line_error(PSTR(MSG_ERR_CHECKSUM_MISMATCH));
  889. return;
  890. }
  891. // if no errors, continue parsing
  892. }
  893. else {
  894. gcode_line_error(PSTR(MSG_ERR_NO_CHECKSUM));
  895. return;
  896. }
  897. gcode_LastN = gcode_N;
  898. // if no errors, continue parsing
  899. }
  900. else if (apos) { // No '*' without 'N'
  901. gcode_line_error(PSTR(MSG_ERR_NO_LINENUMBER_WITH_CHECKSUM), false);
  902. return;
  903. }
  904. // Movement commands alert when stopped
  905. if (IsStopped()) {
  906. char* gpos = strchr(command, 'G');
  907. if (gpos) {
  908. int codenum = strtol(gpos + 1, NULL, 10);
  909. switch (codenum) {
  910. case 0:
  911. case 1:
  912. case 2:
  913. case 3:
  914. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  915. LCD_MESSAGEPGM(MSG_STOPPED);
  916. break;
  917. }
  918. }
  919. }
  920. #if DISABLED(EMERGENCY_PARSER)
  921. // If command was e-stop process now
  922. if (strcmp(command, "M108") == 0) {
  923. wait_for_heatup = false;
  924. #if ENABLED(ULTIPANEL)
  925. wait_for_user = false;
  926. #endif
  927. }
  928. if (strcmp(command, "M112") == 0) kill(PSTR(MSG_KILLED));
  929. if (strcmp(command, "M410") == 0) { quickstop_stepper(); }
  930. #endif
  931. #if defined(NO_TIMEOUTS) && NO_TIMEOUTS > 0
  932. last_command_time = ms;
  933. #endif
  934. // Add the command to the queue
  935. _enqueuecommand(serial_line_buffer, true);
  936. }
  937. else if (serial_count >= MAX_CMD_SIZE - 1) {
  938. // Keep fetching, but ignore normal characters beyond the max length
  939. // The command will be injected when EOL is reached
  940. }
  941. else if (serial_char == '\\') { // Handle escapes
  942. if (MYSERIAL.available() > 0) {
  943. // if we have one more character, copy it over
  944. serial_char = MYSERIAL.read();
  945. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  946. }
  947. // otherwise do nothing
  948. }
  949. else { // it's not a newline, carriage return or escape char
  950. if (serial_char == ';') serial_comment_mode = true;
  951. if (!serial_comment_mode) serial_line_buffer[serial_count++] = serial_char;
  952. }
  953. } // queue has space, serial has data
  954. }
  955. #if ENABLED(SDSUPPORT)
  956. inline void get_sdcard_commands() {
  957. static bool stop_buffering = false,
  958. sd_comment_mode = false;
  959. if (!card.sdprinting) return;
  960. /**
  961. * '#' stops reading from SD to the buffer prematurely, so procedural
  962. * macro calls are possible. If it occurs, stop_buffering is triggered
  963. * and the buffer is run dry; this character _can_ occur in serial com
  964. * due to checksums, however, no checksums are used in SD printing.
  965. */
  966. if (commands_in_queue == 0) stop_buffering = false;
  967. uint16_t sd_count = 0;
  968. bool card_eof = card.eof();
  969. while (commands_in_queue < BUFSIZE && !card_eof && !stop_buffering) {
  970. int16_t n = card.get();
  971. char sd_char = (char)n;
  972. card_eof = card.eof();
  973. if (card_eof || n == -1
  974. || sd_char == '\n' || sd_char == '\r'
  975. || ((sd_char == '#' || sd_char == ':') && !sd_comment_mode)
  976. ) {
  977. if (card_eof) {
  978. SERIAL_PROTOCOLLNPGM(MSG_FILE_PRINTED);
  979. card.printingHasFinished();
  980. card.checkautostart(true);
  981. }
  982. else if (n == -1) {
  983. SERIAL_ERROR_START;
  984. SERIAL_ECHOLNPGM(MSG_SD_ERR_READ);
  985. }
  986. if (sd_char == '#') stop_buffering = true;
  987. sd_comment_mode = false; //for new command
  988. if (!sd_count) continue; //skip empty lines
  989. command_queue[cmd_queue_index_w][sd_count] = '\0'; //terminate string
  990. sd_count = 0; //clear buffer
  991. _commit_command(false);
  992. }
  993. else if (sd_count >= MAX_CMD_SIZE - 1) {
  994. /**
  995. * Keep fetching, but ignore normal characters beyond the max length
  996. * The command will be injected when EOL is reached
  997. */
  998. }
  999. else {
  1000. if (sd_char == ';') sd_comment_mode = true;
  1001. if (!sd_comment_mode) command_queue[cmd_queue_index_w][sd_count++] = sd_char;
  1002. }
  1003. }
  1004. }
  1005. #endif // SDSUPPORT
  1006. /**
  1007. * Add to the circular command queue the next command from:
  1008. * - The command-injection queue (injected_commands_P)
  1009. * - The active serial input (usually USB)
  1010. * - The SD card file being actively printed
  1011. */
  1012. void get_available_commands() {
  1013. // if any immediate commands remain, don't get other commands yet
  1014. if (drain_injected_commands_P()) return;
  1015. get_serial_commands();
  1016. #if ENABLED(SDSUPPORT)
  1017. get_sdcard_commands();
  1018. #endif
  1019. }
  1020. inline bool code_has_value() {
  1021. int i = 1;
  1022. char c = seen_pointer[i];
  1023. while (c == ' ') c = seen_pointer[++i];
  1024. if (c == '-' || c == '+') c = seen_pointer[++i];
  1025. if (c == '.') c = seen_pointer[++i];
  1026. return NUMERIC(c);
  1027. }
  1028. inline float code_value_float() {
  1029. char* e = strchr(seen_pointer, 'E');
  1030. if (!e) return strtod(seen_pointer + 1, NULL);
  1031. *e = 0;
  1032. float ret = strtod(seen_pointer + 1, NULL);
  1033. *e = 'E';
  1034. return ret;
  1035. }
  1036. inline unsigned long code_value_ulong() { return strtoul(seen_pointer + 1, NULL, 10); }
  1037. inline long code_value_long() { return strtol(seen_pointer + 1, NULL, 10); }
  1038. inline int code_value_int() { return (int)strtol(seen_pointer + 1, NULL, 10); }
  1039. inline uint16_t code_value_ushort() { return (uint16_t)strtoul(seen_pointer + 1, NULL, 10); }
  1040. inline uint8_t code_value_byte() { return (uint8_t)(constrain(strtol(seen_pointer + 1, NULL, 10), 0, 255)); }
  1041. inline bool code_value_bool() { return !code_has_value() || code_value_byte() > 0; }
  1042. #if ENABLED(INCH_MODE_SUPPORT)
  1043. inline void set_input_linear_units(LinearUnit units) {
  1044. switch (units) {
  1045. case LINEARUNIT_INCH:
  1046. linear_unit_factor = 25.4;
  1047. break;
  1048. case LINEARUNIT_MM:
  1049. default:
  1050. linear_unit_factor = 1.0;
  1051. break;
  1052. }
  1053. volumetric_unit_factor = pow(linear_unit_factor, 3.0);
  1054. }
  1055. inline float axis_unit_factor(int axis) {
  1056. return (axis >= E_AXIS && volumetric_enabled ? volumetric_unit_factor : linear_unit_factor);
  1057. }
  1058. inline float code_value_linear_units() { return code_value_float() * linear_unit_factor; }
  1059. inline float code_value_axis_units(int axis) { return code_value_float() * axis_unit_factor(axis); }
  1060. inline float code_value_per_axis_unit(int axis) { return code_value_float() / axis_unit_factor(axis); }
  1061. #else
  1062. inline float code_value_linear_units() { return code_value_float(); }
  1063. inline float code_value_axis_units(int axis) { UNUSED(axis); return code_value_float(); }
  1064. inline float code_value_per_axis_unit(int axis) { UNUSED(axis); return code_value_float(); }
  1065. #endif
  1066. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  1067. inline void set_input_temp_units(TempUnit units) { input_temp_units = units; }
  1068. float code_value_temp_abs() {
  1069. switch (input_temp_units) {
  1070. case TEMPUNIT_C:
  1071. return code_value_float();
  1072. case TEMPUNIT_F:
  1073. return (code_value_float() - 32) * 0.5555555556;
  1074. case TEMPUNIT_K:
  1075. return code_value_float() - 273.15;
  1076. default:
  1077. return code_value_float();
  1078. }
  1079. }
  1080. float code_value_temp_diff() {
  1081. switch (input_temp_units) {
  1082. case TEMPUNIT_C:
  1083. case TEMPUNIT_K:
  1084. return code_value_float();
  1085. case TEMPUNIT_F:
  1086. return code_value_float() * 0.5555555556;
  1087. default:
  1088. return code_value_float();
  1089. }
  1090. }
  1091. #else
  1092. float code_value_temp_abs() { return code_value_float(); }
  1093. float code_value_temp_diff() { return code_value_float(); }
  1094. #endif
  1095. FORCE_INLINE millis_t code_value_millis() { return code_value_ulong(); }
  1096. inline millis_t code_value_millis_from_seconds() { return code_value_float() * 1000; }
  1097. bool code_seen(char code) {
  1098. seen_pointer = strchr(current_command_args, code);
  1099. return (seen_pointer != NULL); // Return TRUE if the code-letter was found
  1100. }
  1101. /**
  1102. * Set target_extruder from the T parameter or the active_extruder
  1103. *
  1104. * Returns TRUE if the target is invalid
  1105. */
  1106. bool get_target_extruder_from_command(int code) {
  1107. if (code_seen('T')) {
  1108. if (code_value_byte() >= EXTRUDERS) {
  1109. SERIAL_ECHO_START;
  1110. SERIAL_CHAR('M');
  1111. SERIAL_ECHO(code);
  1112. SERIAL_ECHOLNPAIR(" " MSG_INVALID_EXTRUDER " ", code_value_byte());
  1113. return true;
  1114. }
  1115. target_extruder = code_value_byte();
  1116. }
  1117. else
  1118. target_extruder = active_extruder;
  1119. return false;
  1120. }
  1121. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  1122. bool extruder_duplication_enabled = false; // Used in Dual X mode 2
  1123. #endif
  1124. #if ENABLED(DUAL_X_CARRIAGE)
  1125. static DualXMode dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  1126. static float x_home_pos(const int extruder) {
  1127. if (extruder == 0)
  1128. return LOGICAL_X_POSITION(base_home_pos(X_AXIS));
  1129. else
  1130. /**
  1131. * In dual carriage mode the extruder offset provides an override of the
  1132. * second X-carriage position when homed - otherwise X2_HOME_POS is used.
  1133. * This allows soft recalibration of the second extruder home position
  1134. * without firmware reflash (through the M218 command).
  1135. */
  1136. return LOGICAL_X_POSITION(hotend_offset[X_AXIS][1] > 0 ? hotend_offset[X_AXIS][1] : X2_HOME_POS);
  1137. }
  1138. static int x_home_dir(const int extruder) { return extruder ? X2_HOME_DIR : X_HOME_DIR; }
  1139. static float inactive_extruder_x_pos = X2_MAX_POS; // used in mode 0 & 1
  1140. static bool active_extruder_parked = false; // used in mode 1 & 2
  1141. static float raised_parked_position[NUM_AXIS]; // used in mode 1
  1142. static millis_t delayed_move_time = 0; // used in mode 1
  1143. static float duplicate_extruder_x_offset = DEFAULT_DUPLICATION_X_OFFSET; // used in mode 2
  1144. static float duplicate_extruder_temp_offset = 0; // used in mode 2
  1145. #endif // DUAL_X_CARRIAGE
  1146. #if DISABLED(NO_WORKSPACE_OFFSETS) || ENABLED(DUAL_X_CARRIAGE) || ENABLED(DELTA)
  1147. /**
  1148. * Software endstops can be used to monitor the open end of
  1149. * an axis that has a hardware endstop on the other end. Or
  1150. * they can prevent axes from moving past endstops and grinding.
  1151. *
  1152. * To keep doing their job as the coordinate system changes,
  1153. * the software endstop positions must be refreshed to remain
  1154. * at the same positions relative to the machine.
  1155. */
  1156. void update_software_endstops(const AxisEnum axis) {
  1157. const float offs = workspace_offset[axis] = LOGICAL_POSITION(0, axis);
  1158. #if ENABLED(DUAL_X_CARRIAGE)
  1159. if (axis == X_AXIS) {
  1160. // In Dual X mode hotend_offset[X] is T1's home position
  1161. float dual_max_x = max(hotend_offset[X_AXIS][1], X2_MAX_POS);
  1162. if (active_extruder != 0) {
  1163. // T1 can move from X2_MIN_POS to X2_MAX_POS or X2 home position (whichever is larger)
  1164. soft_endstop_min[X_AXIS] = X2_MIN_POS + offs;
  1165. soft_endstop_max[X_AXIS] = dual_max_x + offs;
  1166. }
  1167. else if (dual_x_carriage_mode == DXC_DUPLICATION_MODE) {
  1168. // In Duplication Mode, T0 can move as far left as X_MIN_POS
  1169. // but not so far to the right that T1 would move past the end
  1170. soft_endstop_min[X_AXIS] = base_min_pos(X_AXIS) + offs;
  1171. soft_endstop_max[X_AXIS] = min(base_max_pos(X_AXIS), dual_max_x - duplicate_extruder_x_offset) + offs;
  1172. }
  1173. else {
  1174. // In other modes, T0 can move from X_MIN_POS to X_MAX_POS
  1175. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1176. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1177. }
  1178. }
  1179. #else
  1180. soft_endstop_min[axis] = base_min_pos(axis) + offs;
  1181. soft_endstop_max[axis] = base_max_pos(axis) + offs;
  1182. #endif
  1183. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1184. if (DEBUGGING(LEVELING)) {
  1185. SERIAL_ECHOPAIR("For ", axis_codes[axis]);
  1186. #if DISABLED(NO_WORKSPACE_OFFSETS)
  1187. SERIAL_ECHOPAIR(" axis:\n home_offset = ", home_offset[axis]);
  1188. SERIAL_ECHOPAIR("\n position_shift = ", position_shift[axis]);
  1189. #endif
  1190. SERIAL_ECHOPAIR("\n soft_endstop_min = ", soft_endstop_min[axis]);
  1191. SERIAL_ECHOLNPAIR("\n soft_endstop_max = ", soft_endstop_max[axis]);
  1192. }
  1193. #endif
  1194. #if ENABLED(DELTA)
  1195. if (axis == Z_AXIS)
  1196. delta_clip_start_height = soft_endstop_max[axis] - delta_safe_distance_from_top();
  1197. #endif
  1198. }
  1199. #endif // NO_WORKSPACE_OFFSETS
  1200. #if DISABLED(NO_WORKSPACE_OFFSETS)
  1201. /**
  1202. * Change the home offset for an axis, update the current
  1203. * position and the software endstops to retain the same
  1204. * relative distance to the new home.
  1205. *
  1206. * Since this changes the current_position, code should
  1207. * call sync_plan_position soon after this.
  1208. */
  1209. static void set_home_offset(const AxisEnum axis, const float v) {
  1210. current_position[axis] += v - home_offset[axis];
  1211. home_offset[axis] = v;
  1212. update_software_endstops(axis);
  1213. }
  1214. #endif // NO_WORKSPACE_OFFSETS
  1215. /**
  1216. * Set an axis' current position to its home position (after homing).
  1217. *
  1218. * For Core and Cartesian robots this applies one-to-one when an
  1219. * individual axis has been homed.
  1220. *
  1221. * DELTA should wait until all homing is done before setting the XYZ
  1222. * current_position to home, because homing is a single operation.
  1223. * In the case where the axis positions are already known and previously
  1224. * homed, DELTA could home to X or Y individually by moving either one
  1225. * to the center. However, homing Z always homes XY and Z.
  1226. *
  1227. * SCARA should wait until all XY homing is done before setting the XY
  1228. * current_position to home, because neither X nor Y is at home until
  1229. * both are at home. Z can however be homed individually.
  1230. *
  1231. * Callers must sync the planner position after calling this!
  1232. */
  1233. static void set_axis_is_at_home(AxisEnum axis) {
  1234. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1235. if (DEBUGGING(LEVELING)) {
  1236. SERIAL_ECHOPAIR(">>> set_axis_is_at_home(", axis_codes[axis]);
  1237. SERIAL_CHAR(')');
  1238. SERIAL_EOL;
  1239. }
  1240. #endif
  1241. axis_known_position[axis] = axis_homed[axis] = true;
  1242. #if DISABLED(NO_WORKSPACE_OFFSETS)
  1243. position_shift[axis] = 0;
  1244. update_software_endstops(axis);
  1245. #endif
  1246. #if ENABLED(DUAL_X_CARRIAGE)
  1247. if (axis == X_AXIS && (active_extruder == 1 || dual_x_carriage_mode == DXC_DUPLICATION_MODE)) {
  1248. current_position[X_AXIS] = x_home_pos(active_extruder);
  1249. return;
  1250. }
  1251. #endif
  1252. #if ENABLED(MORGAN_SCARA)
  1253. /**
  1254. * Morgan SCARA homes XY at the same time
  1255. */
  1256. if (axis == X_AXIS || axis == Y_AXIS) {
  1257. float homeposition[XYZ];
  1258. LOOP_XYZ(i) homeposition[i] = LOGICAL_POSITION(base_home_pos((AxisEnum)i), i);
  1259. // SERIAL_ECHOPAIR("homeposition X:", homeposition[X_AXIS]);
  1260. // SERIAL_ECHOLNPAIR(" Y:", homeposition[Y_AXIS]);
  1261. /**
  1262. * Get Home position SCARA arm angles using inverse kinematics,
  1263. * and calculate homing offset using forward kinematics
  1264. */
  1265. inverse_kinematics(homeposition);
  1266. forward_kinematics_SCARA(delta[A_AXIS], delta[B_AXIS]);
  1267. // SERIAL_ECHOPAIR("Cartesian X:", cartes[X_AXIS]);
  1268. // SERIAL_ECHOLNPAIR(" Y:", cartes[Y_AXIS]);
  1269. current_position[axis] = LOGICAL_POSITION(cartes[axis], axis);
  1270. /**
  1271. * SCARA home positions are based on configuration since the actual
  1272. * limits are determined by the inverse kinematic transform.
  1273. */
  1274. soft_endstop_min[axis] = base_min_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1275. soft_endstop_max[axis] = base_max_pos(axis); // + (cartes[axis] - base_home_pos(axis));
  1276. }
  1277. else
  1278. #endif
  1279. {
  1280. current_position[axis] = LOGICAL_POSITION(base_home_pos(axis), axis);
  1281. }
  1282. /**
  1283. * Z Probe Z Homing? Account for the probe's Z offset.
  1284. */
  1285. #if HAS_BED_PROBE && Z_HOME_DIR < 0
  1286. if (axis == Z_AXIS) {
  1287. #if HOMING_Z_WITH_PROBE
  1288. current_position[Z_AXIS] -= zprobe_zoffset;
  1289. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1290. if (DEBUGGING(LEVELING)) {
  1291. SERIAL_ECHOLNPGM("*** Z HOMED WITH PROBE (Z_MIN_PROBE_USES_Z_MIN_ENDSTOP_PIN) ***");
  1292. SERIAL_ECHOLNPAIR("> zprobe_zoffset = ", zprobe_zoffset);
  1293. }
  1294. #endif
  1295. #elif ENABLED(DEBUG_LEVELING_FEATURE)
  1296. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("*** Z HOMED TO ENDSTOP (Z_MIN_PROBE_ENDSTOP) ***");
  1297. #endif
  1298. }
  1299. #endif
  1300. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1301. if (DEBUGGING(LEVELING)) {
  1302. #if DISABLED(NO_WORKSPACE_OFFSETS)
  1303. SERIAL_ECHOPAIR("> home_offset[", axis_codes[axis]);
  1304. SERIAL_ECHOLNPAIR("] = ", home_offset[axis]);
  1305. #endif
  1306. DEBUG_POS("", current_position);
  1307. SERIAL_ECHOPAIR("<<< set_axis_is_at_home(", axis_codes[axis]);
  1308. SERIAL_CHAR(')');
  1309. SERIAL_EOL;
  1310. }
  1311. #endif
  1312. }
  1313. /**
  1314. * Some planner shorthand inline functions
  1315. */
  1316. inline float get_homing_bump_feedrate(AxisEnum axis) {
  1317. int constexpr homing_bump_divisor[] = HOMING_BUMP_DIVISOR;
  1318. int hbd = homing_bump_divisor[axis];
  1319. if (hbd < 1) {
  1320. hbd = 10;
  1321. SERIAL_ECHO_START;
  1322. SERIAL_ECHOLNPGM("Warning: Homing Bump Divisor < 1");
  1323. }
  1324. return homing_feedrate_mm_s[axis] / hbd;
  1325. }
  1326. //
  1327. // line_to_current_position
  1328. // Move the planner to the current position from wherever it last moved
  1329. // (or from wherever it has been told it is located).
  1330. //
  1331. inline void line_to_current_position() {
  1332. planner.buffer_line(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS], feedrate_mm_s, active_extruder);
  1333. }
  1334. //
  1335. // line_to_destination
  1336. // Move the planner, not necessarily synced with current_position
  1337. //
  1338. inline void line_to_destination(float fr_mm_s) {
  1339. planner.buffer_line(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS], fr_mm_s, active_extruder);
  1340. }
  1341. inline void line_to_destination() { line_to_destination(feedrate_mm_s); }
  1342. inline void set_current_to_destination() { COPY(current_position, destination); }
  1343. inline void set_destination_to_current() { COPY(destination, current_position); }
  1344. #if IS_KINEMATIC
  1345. /**
  1346. * Calculate delta, start a line, and set current_position to destination
  1347. */
  1348. void prepare_uninterpolated_move_to_destination(const float fr_mm_s=0.0) {
  1349. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1350. if (DEBUGGING(LEVELING)) DEBUG_POS("prepare_uninterpolated_move_to_destination", destination);
  1351. #endif
  1352. if ( current_position[X_AXIS] == destination[X_AXIS]
  1353. && current_position[Y_AXIS] == destination[Y_AXIS]
  1354. && current_position[Z_AXIS] == destination[Z_AXIS]
  1355. && current_position[E_AXIS] == destination[E_AXIS]
  1356. ) return;
  1357. refresh_cmd_timeout();
  1358. planner.buffer_line_kinematic(destination, MMS_SCALED(fr_mm_s ? fr_mm_s : feedrate_mm_s), active_extruder);
  1359. set_current_to_destination();
  1360. }
  1361. #endif // IS_KINEMATIC
  1362. /**
  1363. * Plan a move to (X, Y, Z) and set the current_position
  1364. * The final current_position may not be the one that was requested
  1365. */
  1366. void do_blocking_move_to(const float &x, const float &y, const float &z, const float &fr_mm_s /*=0.0*/) {
  1367. const float old_feedrate_mm_s = feedrate_mm_s;
  1368. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1369. if (DEBUGGING(LEVELING)) print_xyz(PSTR(">>> do_blocking_move_to"), NULL, x, y, z);
  1370. #endif
  1371. #if ENABLED(DELTA)
  1372. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1373. set_destination_to_current(); // sync destination at the start
  1374. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1375. if (DEBUGGING(LEVELING)) DEBUG_POS("set_destination_to_current", destination);
  1376. #endif
  1377. // when in the danger zone
  1378. if (current_position[Z_AXIS] > delta_clip_start_height) {
  1379. if (z > delta_clip_start_height) { // staying in the danger zone
  1380. destination[X_AXIS] = x; // move directly (uninterpolated)
  1381. destination[Y_AXIS] = y;
  1382. destination[Z_AXIS] = z;
  1383. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1384. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1385. if (DEBUGGING(LEVELING)) DEBUG_POS("danger zone move", current_position);
  1386. #endif
  1387. return;
  1388. }
  1389. else {
  1390. destination[Z_AXIS] = delta_clip_start_height;
  1391. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1392. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1393. if (DEBUGGING(LEVELING)) DEBUG_POS("zone border move", current_position);
  1394. #endif
  1395. }
  1396. }
  1397. if (z > current_position[Z_AXIS]) { // raising?
  1398. destination[Z_AXIS] = z;
  1399. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1400. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1401. if (DEBUGGING(LEVELING)) DEBUG_POS("z raise move", current_position);
  1402. #endif
  1403. }
  1404. destination[X_AXIS] = x;
  1405. destination[Y_AXIS] = y;
  1406. prepare_move_to_destination(); // set_current_to_destination
  1407. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1408. if (DEBUGGING(LEVELING)) DEBUG_POS("xy move", current_position);
  1409. #endif
  1410. if (z < current_position[Z_AXIS]) { // lowering?
  1411. destination[Z_AXIS] = z;
  1412. prepare_uninterpolated_move_to_destination(); // set_current_to_destination
  1413. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1414. if (DEBUGGING(LEVELING)) DEBUG_POS("z lower move", current_position);
  1415. #endif
  1416. }
  1417. #elif IS_SCARA
  1418. set_destination_to_current();
  1419. // If Z needs to raise, do it before moving XY
  1420. if (destination[Z_AXIS] < z) {
  1421. destination[Z_AXIS] = z;
  1422. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1423. }
  1424. destination[X_AXIS] = x;
  1425. destination[Y_AXIS] = y;
  1426. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S);
  1427. // If Z needs to lower, do it after moving XY
  1428. if (destination[Z_AXIS] > z) {
  1429. destination[Z_AXIS] = z;
  1430. prepare_uninterpolated_move_to_destination(fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS]);
  1431. }
  1432. #else
  1433. // If Z needs to raise, do it before moving XY
  1434. if (current_position[Z_AXIS] < z) {
  1435. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1436. current_position[Z_AXIS] = z;
  1437. line_to_current_position();
  1438. }
  1439. feedrate_mm_s = fr_mm_s ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  1440. current_position[X_AXIS] = x;
  1441. current_position[Y_AXIS] = y;
  1442. line_to_current_position();
  1443. // If Z needs to lower, do it after moving XY
  1444. if (current_position[Z_AXIS] > z) {
  1445. feedrate_mm_s = fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[Z_AXIS];
  1446. current_position[Z_AXIS] = z;
  1447. line_to_current_position();
  1448. }
  1449. #endif
  1450. stepper.synchronize();
  1451. feedrate_mm_s = old_feedrate_mm_s;
  1452. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1453. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< do_blocking_move_to");
  1454. #endif
  1455. }
  1456. void do_blocking_move_to_x(const float &x, const float &fr_mm_s/*=0.0*/) {
  1457. do_blocking_move_to(x, current_position[Y_AXIS], current_position[Z_AXIS], fr_mm_s);
  1458. }
  1459. void do_blocking_move_to_z(const float &z, const float &fr_mm_s/*=0.0*/) {
  1460. do_blocking_move_to(current_position[X_AXIS], current_position[Y_AXIS], z, fr_mm_s);
  1461. }
  1462. void do_blocking_move_to_xy(const float &x, const float &y, const float &fr_mm_s/*=0.0*/) {
  1463. do_blocking_move_to(x, y, current_position[Z_AXIS], fr_mm_s);
  1464. }
  1465. //
  1466. // Prepare to do endstop or probe moves
  1467. // with custom feedrates.
  1468. //
  1469. // - Save current feedrates
  1470. // - Reset the rate multiplier
  1471. // - Reset the command timeout
  1472. // - Enable the endstops (for endstop moves)
  1473. //
  1474. static void setup_for_endstop_or_probe_move() {
  1475. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1476. if (DEBUGGING(LEVELING)) DEBUG_POS("setup_for_endstop_or_probe_move", current_position);
  1477. #endif
  1478. saved_feedrate_mm_s = feedrate_mm_s;
  1479. saved_feedrate_percentage = feedrate_percentage;
  1480. feedrate_percentage = 100;
  1481. refresh_cmd_timeout();
  1482. }
  1483. static void clean_up_after_endstop_or_probe_move() {
  1484. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1485. if (DEBUGGING(LEVELING)) DEBUG_POS("clean_up_after_endstop_or_probe_move", current_position);
  1486. #endif
  1487. feedrate_mm_s = saved_feedrate_mm_s;
  1488. feedrate_percentage = saved_feedrate_percentage;
  1489. refresh_cmd_timeout();
  1490. }
  1491. #if HAS_BED_PROBE
  1492. /**
  1493. * Raise Z to a minimum height to make room for a probe to move
  1494. */
  1495. inline void do_probe_raise(float z_raise) {
  1496. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1497. if (DEBUGGING(LEVELING)) {
  1498. SERIAL_ECHOPAIR("do_probe_raise(", z_raise);
  1499. SERIAL_CHAR(')');
  1500. SERIAL_EOL;
  1501. }
  1502. #endif
  1503. float z_dest = LOGICAL_Z_POSITION(z_raise);
  1504. if (zprobe_zoffset < 0) z_dest -= zprobe_zoffset;
  1505. if (z_dest > current_position[Z_AXIS])
  1506. do_blocking_move_to_z(z_dest);
  1507. }
  1508. #endif //HAS_BED_PROBE
  1509. #if ENABLED(Z_PROBE_ALLEN_KEY) || ENABLED(Z_PROBE_SLED) || HAS_PROBING_PROCEDURE || HOTENDS > 1 || ENABLED(NOZZLE_CLEAN_FEATURE) || ENABLED(NOZZLE_PARK_FEATURE)
  1510. bool axis_unhomed_error(const bool x, const bool y, const bool z) {
  1511. const bool xx = x && !axis_homed[X_AXIS],
  1512. yy = y && !axis_homed[Y_AXIS],
  1513. zz = z && !axis_homed[Z_AXIS];
  1514. if (xx || yy || zz) {
  1515. SERIAL_ECHO_START;
  1516. SERIAL_ECHOPGM(MSG_HOME " ");
  1517. if (xx) SERIAL_ECHOPGM(MSG_X);
  1518. if (yy) SERIAL_ECHOPGM(MSG_Y);
  1519. if (zz) SERIAL_ECHOPGM(MSG_Z);
  1520. SERIAL_ECHOLNPGM(" " MSG_FIRST);
  1521. #if ENABLED(ULTRA_LCD)
  1522. char message[3 * (LCD_WIDTH) + 1] = ""; // worst case is kana.utf with up to 3*LCD_WIDTH+1
  1523. strcat_P(message, PSTR(MSG_HOME " "));
  1524. if (xx) strcat_P(message, PSTR(MSG_X));
  1525. if (yy) strcat_P(message, PSTR(MSG_Y));
  1526. if (zz) strcat_P(message, PSTR(MSG_Z));
  1527. strcat_P(message, PSTR(" " MSG_FIRST));
  1528. lcd_setstatus(message);
  1529. #endif
  1530. return true;
  1531. }
  1532. return false;
  1533. }
  1534. #endif
  1535. #if ENABLED(Z_PROBE_SLED)
  1536. #ifndef SLED_DOCKING_OFFSET
  1537. #define SLED_DOCKING_OFFSET 0
  1538. #endif
  1539. /**
  1540. * Method to dock/undock a sled designed by Charles Bell.
  1541. *
  1542. * stow[in] If false, move to MAX_X and engage the solenoid
  1543. * If true, move to MAX_X and release the solenoid
  1544. */
  1545. static void dock_sled(bool stow) {
  1546. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1547. if (DEBUGGING(LEVELING)) {
  1548. SERIAL_ECHOPAIR("dock_sled(", stow);
  1549. SERIAL_CHAR(')');
  1550. SERIAL_EOL;
  1551. }
  1552. #endif
  1553. // Dock sled a bit closer to ensure proper capturing
  1554. do_blocking_move_to_x(X_MAX_POS + SLED_DOCKING_OFFSET - ((stow) ? 1 : 0));
  1555. #if PIN_EXISTS(SLED)
  1556. digitalWrite(SLED_PIN, !stow); // switch solenoid
  1557. #endif
  1558. }
  1559. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1560. void run_deploy_moves_script() {
  1561. #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)
  1562. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_X
  1563. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_X current_position[X_AXIS]
  1564. #endif
  1565. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Y
  1566. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Y current_position[Y_AXIS]
  1567. #endif
  1568. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_Z
  1569. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_Z current_position[Z_AXIS]
  1570. #endif
  1571. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE
  1572. #define Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE 0.0
  1573. #endif
  1574. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_1_X, Z_PROBE_ALLEN_KEY_DEPLOY_1_Y, Z_PROBE_ALLEN_KEY_DEPLOY_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_1_FEEDRATE));
  1575. #endif
  1576. #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)
  1577. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_X
  1578. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_X current_position[X_AXIS]
  1579. #endif
  1580. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Y
  1581. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Y current_position[Y_AXIS]
  1582. #endif
  1583. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_Z
  1584. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_Z current_position[Z_AXIS]
  1585. #endif
  1586. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE
  1587. #define Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE 0.0
  1588. #endif
  1589. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_2_X, Z_PROBE_ALLEN_KEY_DEPLOY_2_Y, Z_PROBE_ALLEN_KEY_DEPLOY_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_2_FEEDRATE));
  1590. #endif
  1591. #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)
  1592. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_X
  1593. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_X current_position[X_AXIS]
  1594. #endif
  1595. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Y
  1596. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Y current_position[Y_AXIS]
  1597. #endif
  1598. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_Z
  1599. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_Z current_position[Z_AXIS]
  1600. #endif
  1601. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE
  1602. #define Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE 0.0
  1603. #endif
  1604. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_3_X, Z_PROBE_ALLEN_KEY_DEPLOY_3_Y, Z_PROBE_ALLEN_KEY_DEPLOY_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_3_FEEDRATE));
  1605. #endif
  1606. #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)
  1607. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_X
  1608. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_X current_position[X_AXIS]
  1609. #endif
  1610. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Y
  1611. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Y current_position[Y_AXIS]
  1612. #endif
  1613. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_Z
  1614. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_Z current_position[Z_AXIS]
  1615. #endif
  1616. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE
  1617. #define Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE 0.0
  1618. #endif
  1619. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_4_X, Z_PROBE_ALLEN_KEY_DEPLOY_4_Y, Z_PROBE_ALLEN_KEY_DEPLOY_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_4_FEEDRATE));
  1620. #endif
  1621. #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)
  1622. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_X
  1623. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_X current_position[X_AXIS]
  1624. #endif
  1625. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Y
  1626. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Y current_position[Y_AXIS]
  1627. #endif
  1628. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_Z
  1629. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_Z current_position[Z_AXIS]
  1630. #endif
  1631. #ifndef Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE
  1632. #define Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE 0.0
  1633. #endif
  1634. do_blocking_move_to(Z_PROBE_ALLEN_KEY_DEPLOY_5_X, Z_PROBE_ALLEN_KEY_DEPLOY_5_Y, Z_PROBE_ALLEN_KEY_DEPLOY_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_DEPLOY_5_FEEDRATE));
  1635. #endif
  1636. }
  1637. void run_stow_moves_script() {
  1638. #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)
  1639. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_X
  1640. #define Z_PROBE_ALLEN_KEY_STOW_1_X current_position[X_AXIS]
  1641. #endif
  1642. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Y
  1643. #define Z_PROBE_ALLEN_KEY_STOW_1_Y current_position[Y_AXIS]
  1644. #endif
  1645. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_Z
  1646. #define Z_PROBE_ALLEN_KEY_STOW_1_Z current_position[Z_AXIS]
  1647. #endif
  1648. #ifndef Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE
  1649. #define Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE 0.0
  1650. #endif
  1651. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_1_X, Z_PROBE_ALLEN_KEY_STOW_1_Y, Z_PROBE_ALLEN_KEY_STOW_1_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_1_FEEDRATE));
  1652. #endif
  1653. #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)
  1654. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_X
  1655. #define Z_PROBE_ALLEN_KEY_STOW_2_X current_position[X_AXIS]
  1656. #endif
  1657. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Y
  1658. #define Z_PROBE_ALLEN_KEY_STOW_2_Y current_position[Y_AXIS]
  1659. #endif
  1660. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_Z
  1661. #define Z_PROBE_ALLEN_KEY_STOW_2_Z current_position[Z_AXIS]
  1662. #endif
  1663. #ifndef Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE
  1664. #define Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE 0.0
  1665. #endif
  1666. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_2_X, Z_PROBE_ALLEN_KEY_STOW_2_Y, Z_PROBE_ALLEN_KEY_STOW_2_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_2_FEEDRATE));
  1667. #endif
  1668. #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)
  1669. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_X
  1670. #define Z_PROBE_ALLEN_KEY_STOW_3_X current_position[X_AXIS]
  1671. #endif
  1672. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Y
  1673. #define Z_PROBE_ALLEN_KEY_STOW_3_Y current_position[Y_AXIS]
  1674. #endif
  1675. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_Z
  1676. #define Z_PROBE_ALLEN_KEY_STOW_3_Z current_position[Z_AXIS]
  1677. #endif
  1678. #ifndef Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE
  1679. #define Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE 0.0
  1680. #endif
  1681. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_3_X, Z_PROBE_ALLEN_KEY_STOW_3_Y, Z_PROBE_ALLEN_KEY_STOW_3_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_3_FEEDRATE));
  1682. #endif
  1683. #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)
  1684. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_X
  1685. #define Z_PROBE_ALLEN_KEY_STOW_4_X current_position[X_AXIS]
  1686. #endif
  1687. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Y
  1688. #define Z_PROBE_ALLEN_KEY_STOW_4_Y current_position[Y_AXIS]
  1689. #endif
  1690. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_Z
  1691. #define Z_PROBE_ALLEN_KEY_STOW_4_Z current_position[Z_AXIS]
  1692. #endif
  1693. #ifndef Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE
  1694. #define Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE 0.0
  1695. #endif
  1696. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_4_X, Z_PROBE_ALLEN_KEY_STOW_4_Y, Z_PROBE_ALLEN_KEY_STOW_4_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_4_FEEDRATE));
  1697. #endif
  1698. #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)
  1699. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_X
  1700. #define Z_PROBE_ALLEN_KEY_STOW_5_X current_position[X_AXIS]
  1701. #endif
  1702. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Y
  1703. #define Z_PROBE_ALLEN_KEY_STOW_5_Y current_position[Y_AXIS]
  1704. #endif
  1705. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_Z
  1706. #define Z_PROBE_ALLEN_KEY_STOW_5_Z current_position[Z_AXIS]
  1707. #endif
  1708. #ifndef Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE
  1709. #define Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE 0.0
  1710. #endif
  1711. do_blocking_move_to(Z_PROBE_ALLEN_KEY_STOW_5_X, Z_PROBE_ALLEN_KEY_STOW_5_Y, Z_PROBE_ALLEN_KEY_STOW_5_Z, MMM_TO_MMS(Z_PROBE_ALLEN_KEY_STOW_5_FEEDRATE));
  1712. #endif
  1713. }
  1714. #endif
  1715. #if HAS_BED_PROBE
  1716. // TRIGGERED_WHEN_STOWED_TEST can easily be extended to servo probes, ... if needed.
  1717. #if ENABLED(PROBE_IS_TRIGGERED_WHEN_STOWED_TEST)
  1718. #if ENABLED(Z_MIN_PROBE_ENDSTOP)
  1719. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PROBE_PIN) != Z_MIN_PROBE_ENDSTOP_INVERTING)
  1720. #else
  1721. #define _TRIGGERED_WHEN_STOWED_TEST (READ(Z_MIN_PIN) != Z_MIN_ENDSTOP_INVERTING)
  1722. #endif
  1723. #endif
  1724. #define DEPLOY_PROBE() set_probe_deployed(true)
  1725. #define STOW_PROBE() set_probe_deployed(false)
  1726. #if ENABLED(BLTOUCH)
  1727. void bltouch_command(int angle) {
  1728. servo[Z_ENDSTOP_SERVO_NR].move(angle); // Give the BL-Touch the command and wait
  1729. safe_delay(375);
  1730. }
  1731. FORCE_INLINE void set_bltouch_deployed(const bool &deploy) {
  1732. bltouch_command(deploy ? BLTOUCH_DEPLOY : BLTOUCH_STOW);
  1733. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1734. if (DEBUGGING(LEVELING)) {
  1735. SERIAL_ECHOPAIR("set_bltouch_deployed(", deploy);
  1736. SERIAL_CHAR(')');
  1737. SERIAL_EOL;
  1738. }
  1739. #endif
  1740. }
  1741. #endif
  1742. // returns false for ok and true for failure
  1743. bool set_probe_deployed(bool deploy) {
  1744. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1745. if (DEBUGGING(LEVELING)) {
  1746. DEBUG_POS("set_probe_deployed", current_position);
  1747. SERIAL_ECHOLNPAIR("deploy: ", deploy);
  1748. }
  1749. #endif
  1750. if (endstops.z_probe_enabled == deploy) return false;
  1751. // Make room for probe
  1752. do_probe_raise(_Z_CLEARANCE_DEPLOY_PROBE);
  1753. // When deploying make sure BLTOUCH is not already triggered
  1754. #if ENABLED(BLTOUCH)
  1755. if (deploy && TEST_BLTOUCH()) { // If BL-Touch says it's triggered
  1756. bltouch_command(BLTOUCH_RESET); // try to reset it.
  1757. set_bltouch_deployed(true); // Also needs to deploy and stow to
  1758. set_bltouch_deployed(false); // clear the triggered condition.
  1759. if (TEST_BLTOUCH()) { // If it still claims to be triggered...
  1760. SERIAL_ERROR_START;
  1761. SERIAL_ERRORLNPGM(MSG_STOP_BLTOUCH);
  1762. stop(); // punt!
  1763. return true;
  1764. }
  1765. }
  1766. #elif ENABLED(Z_PROBE_SLED)
  1767. if (axis_unhomed_error(true, false, false)) {
  1768. SERIAL_ERROR_START;
  1769. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1770. stop();
  1771. return true;
  1772. }
  1773. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1774. if (axis_unhomed_error(true, true, true )) {
  1775. SERIAL_ERROR_START;
  1776. SERIAL_ERRORLNPGM(MSG_STOP_UNHOMED);
  1777. stop();
  1778. return true;
  1779. }
  1780. #endif
  1781. const float oldXpos = current_position[X_AXIS],
  1782. oldYpos = current_position[Y_AXIS];
  1783. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1784. // If endstop is already false, the Z probe is deployed
  1785. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // closed after the probe specific actions.
  1786. // Would a goto be less ugly?
  1787. //while (!_TRIGGERED_WHEN_STOWED_TEST) idle(); // would offer the opportunity
  1788. // for a triggered when stowed manual probe.
  1789. if (!deploy) endstops.enable_z_probe(false); // Switch off triggered when stowed probes early
  1790. // otherwise an Allen-Key probe can't be stowed.
  1791. #endif
  1792. #if ENABLED(Z_PROBE_SLED)
  1793. dock_sled(!deploy);
  1794. #elif HAS_Z_SERVO_ENDSTOP && DISABLED(BLTOUCH)
  1795. servo[Z_ENDSTOP_SERVO_NR].move(z_servo_angle[deploy ? 0 : 1]);
  1796. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  1797. deploy ? run_deploy_moves_script() : run_stow_moves_script();
  1798. #endif
  1799. #ifdef _TRIGGERED_WHEN_STOWED_TEST
  1800. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1801. if (_TRIGGERED_WHEN_STOWED_TEST == deploy) { // State hasn't changed?
  1802. if (IsRunning()) {
  1803. SERIAL_ERROR_START;
  1804. SERIAL_ERRORLNPGM("Z-Probe failed");
  1805. LCD_ALERTMESSAGEPGM("Err: ZPROBE");
  1806. }
  1807. stop();
  1808. return true;
  1809. } // _TRIGGERED_WHEN_STOWED_TEST == deploy
  1810. #endif
  1811. do_blocking_move_to(oldXpos, oldYpos, current_position[Z_AXIS]); // return to position before deploy
  1812. endstops.enable_z_probe(deploy);
  1813. return false;
  1814. }
  1815. static void do_probe_move(float z, float fr_mm_m) {
  1816. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1817. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> do_probe_move", current_position);
  1818. #endif
  1819. // Deploy BLTouch at the start of any probe
  1820. #if ENABLED(BLTOUCH)
  1821. set_bltouch_deployed(true);
  1822. #endif
  1823. // Move down until probe triggered
  1824. do_blocking_move_to_z(LOGICAL_Z_POSITION(z), MMM_TO_MMS(fr_mm_m));
  1825. // Retract BLTouch immediately after a probe
  1826. #if ENABLED(BLTOUCH)
  1827. set_bltouch_deployed(false);
  1828. #endif
  1829. // Clear endstop flags
  1830. endstops.hit_on_purpose();
  1831. // Get Z where the steppers were interrupted
  1832. set_current_from_steppers_for_axis(Z_AXIS);
  1833. // Tell the planner where we actually are
  1834. SYNC_PLAN_POSITION_KINEMATIC();
  1835. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1836. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< do_probe_move", current_position);
  1837. #endif
  1838. }
  1839. // Do a single Z probe and return with current_position[Z_AXIS]
  1840. // at the height where the probe triggered.
  1841. static float run_z_probe() {
  1842. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1843. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> run_z_probe", current_position);
  1844. #endif
  1845. // Prevent stepper_inactive_time from running out and EXTRUDER_RUNOUT_PREVENT from extruding
  1846. refresh_cmd_timeout();
  1847. #if ENABLED(PROBE_DOUBLE_TOUCH)
  1848. // Do a first probe at the fast speed
  1849. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_FAST);
  1850. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1851. float first_probe_z = current_position[Z_AXIS];
  1852. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("1st Probe Z:", first_probe_z);
  1853. #endif
  1854. // move up by the bump distance
  1855. do_blocking_move_to_z(current_position[Z_AXIS] + home_bump_mm(Z_AXIS), MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1856. #else
  1857. // If the nozzle is above the travel height then
  1858. // move down quickly before doing the slow probe
  1859. float z = LOGICAL_Z_POSITION(Z_CLEARANCE_BETWEEN_PROBES);
  1860. if (zprobe_zoffset < 0) z -= zprobe_zoffset;
  1861. if (z < current_position[Z_AXIS])
  1862. do_blocking_move_to_z(z, MMM_TO_MMS(Z_PROBE_SPEED_FAST));
  1863. #endif
  1864. // move down slowly to find bed
  1865. do_probe_move(-(Z_MAX_LENGTH) - 10, Z_PROBE_SPEED_SLOW);
  1866. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1867. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< run_z_probe", current_position);
  1868. #endif
  1869. // Debug: compare probe heights
  1870. #if ENABLED(PROBE_DOUBLE_TOUCH) && ENABLED(DEBUG_LEVELING_FEATURE)
  1871. if (DEBUGGING(LEVELING)) {
  1872. SERIAL_ECHOPAIR("2nd Probe Z:", current_position[Z_AXIS]);
  1873. SERIAL_ECHOLNPAIR(" Discrepancy:", first_probe_z - current_position[Z_AXIS]);
  1874. }
  1875. #endif
  1876. return current_position[Z_AXIS];
  1877. }
  1878. //
  1879. // - Move to the given XY
  1880. // - Deploy the probe, if not already deployed
  1881. // - Probe the bed, get the Z position
  1882. // - Depending on the 'stow' flag
  1883. // - Stow the probe, or
  1884. // - Raise to the BETWEEN height
  1885. // - Return the probed Z position
  1886. //
  1887. //float probe_pt(const float &x, const float &y, const bool stow = true, const int verbose_level = 1) {
  1888. float probe_pt(const float x, const float y, const bool stow, const int verbose_level) {
  1889. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1890. if (DEBUGGING(LEVELING)) {
  1891. SERIAL_ECHOPAIR(">>> probe_pt(", x);
  1892. SERIAL_ECHOPAIR(", ", y);
  1893. SERIAL_ECHOPAIR(", ", stow ? "" : "no ");
  1894. SERIAL_ECHOLNPGM("stow)");
  1895. DEBUG_POS("", current_position);
  1896. }
  1897. #endif
  1898. const float old_feedrate_mm_s = feedrate_mm_s;
  1899. #if ENABLED(DELTA)
  1900. if (current_position[Z_AXIS] > delta_clip_start_height)
  1901. do_blocking_move_to_z(delta_clip_start_height);
  1902. #endif
  1903. // Ensure a minimum height before moving the probe
  1904. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1905. feedrate_mm_s = XY_PROBE_FEEDRATE_MM_S;
  1906. // Move the probe to the given XY
  1907. do_blocking_move_to_xy(x - (X_PROBE_OFFSET_FROM_EXTRUDER), y - (Y_PROBE_OFFSET_FROM_EXTRUDER));
  1908. if (DEPLOY_PROBE()) return NAN;
  1909. const float measured_z = run_z_probe();
  1910. if (!stow)
  1911. do_probe_raise(Z_CLEARANCE_BETWEEN_PROBES);
  1912. else
  1913. if (STOW_PROBE()) return NAN;
  1914. if (verbose_level > 2) {
  1915. SERIAL_PROTOCOLPGM("Bed X: ");
  1916. SERIAL_PROTOCOL_F(x, 3);
  1917. SERIAL_PROTOCOLPGM(" Y: ");
  1918. SERIAL_PROTOCOL_F(y, 3);
  1919. SERIAL_PROTOCOLPGM(" Z: ");
  1920. SERIAL_PROTOCOL_F(measured_z - -zprobe_zoffset + 0.0001, 3);
  1921. SERIAL_EOL;
  1922. }
  1923. #if ENABLED(DEBUG_LEVELING_FEATURE)
  1924. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< probe_pt");
  1925. #endif
  1926. feedrate_mm_s = old_feedrate_mm_s;
  1927. return measured_z;
  1928. }
  1929. #endif // HAS_BED_PROBE
  1930. #if PLANNER_LEVELING
  1931. /**
  1932. * Turn bed leveling on or off, fixing the current
  1933. * position as-needed.
  1934. *
  1935. * Disable: Current position = physical position
  1936. * Enable: Current position = "unleveled" physical position
  1937. */
  1938. void set_bed_leveling_enabled(bool enable/*=true*/) {
  1939. #if ENABLED(MESH_BED_LEVELING)
  1940. if (enable != mbl.active()) {
  1941. if (!enable)
  1942. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS]);
  1943. mbl.set_active(enable && mbl.has_mesh());
  1944. if (enable) planner.unapply_leveling(current_position);
  1945. }
  1946. #elif HAS_ABL
  1947. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  1948. const bool can_change = (!enable || (bilinear_grid_spacing[0] && bilinear_grid_spacing[1]));
  1949. #else
  1950. constexpr bool can_change = true;
  1951. #endif
  1952. if (can_change && enable != planner.abl_enabled) {
  1953. planner.abl_enabled = enable;
  1954. if (!enable)
  1955. set_current_from_steppers_for_axis(
  1956. #if ABL_PLANAR
  1957. ALL_AXES
  1958. #else
  1959. Z_AXIS
  1960. #endif
  1961. );
  1962. else
  1963. planner.unapply_leveling(current_position);
  1964. }
  1965. #endif
  1966. }
  1967. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  1968. void set_z_fade_height(const float zfh) {
  1969. planner.z_fade_height = zfh;
  1970. planner.inverse_z_fade_height = RECIPROCAL(zfh);
  1971. if (
  1972. #if ENABLED(MESH_BED_LEVELING)
  1973. mbl.active()
  1974. #else
  1975. planner.abl_enabled
  1976. #endif
  1977. ) {
  1978. set_current_from_steppers_for_axis(
  1979. #if ABL_PLANAR
  1980. ALL_AXES
  1981. #else
  1982. Z_AXIS
  1983. #endif
  1984. );
  1985. }
  1986. }
  1987. #endif // LEVELING_FADE_HEIGHT
  1988. /**
  1989. * Reset calibration results to zero.
  1990. */
  1991. void reset_bed_level() {
  1992. set_bed_leveling_enabled(false);
  1993. #if ENABLED(MESH_BED_LEVELING)
  1994. if (mbl.has_mesh()) {
  1995. mbl.reset();
  1996. mbl.set_has_mesh(false);
  1997. }
  1998. #else
  1999. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2000. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("reset_bed_level");
  2001. #endif
  2002. #if ABL_PLANAR
  2003. planner.bed_level_matrix.set_to_identity();
  2004. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2005. bilinear_start[X_AXIS] = bilinear_start[Y_AXIS] =
  2006. bilinear_grid_spacing[X_AXIS] = bilinear_grid_spacing[Y_AXIS] = 0;
  2007. for (uint8_t x = 0; x < ABL_GRID_MAX_POINTS_X; x++)
  2008. for (uint8_t y = 0; y < ABL_GRID_MAX_POINTS_Y; y++)
  2009. bed_level_grid[x][y] = UNPROBED;
  2010. #endif
  2011. #endif
  2012. }
  2013. #endif // PLANNER_LEVELING
  2014. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2015. /**
  2016. * Extrapolate a single point from its neighbors
  2017. */
  2018. static void extrapolate_one_point(uint8_t x, uint8_t y, int8_t xdir, int8_t ydir) {
  2019. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2020. if (DEBUGGING(LEVELING)) {
  2021. SERIAL_ECHOPGM("Extrapolate [");
  2022. if (x < 10) SERIAL_CHAR(' ');
  2023. SERIAL_ECHO((int)x);
  2024. SERIAL_CHAR(xdir ? (xdir > 0 ? '+' : '-') : ' ');
  2025. SERIAL_CHAR(' ');
  2026. if (y < 10) SERIAL_CHAR(' ');
  2027. SERIAL_ECHO((int)y);
  2028. SERIAL_CHAR(ydir ? (ydir > 0 ? '+' : '-') : ' ');
  2029. SERIAL_CHAR(']');
  2030. }
  2031. #endif
  2032. if (bed_level_grid[x][y] != UNPROBED) {
  2033. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2034. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM(" (done)");
  2035. #endif
  2036. return; // Don't overwrite good values.
  2037. }
  2038. SERIAL_EOL;
  2039. // Get X neighbors, Y neighbors, and XY neighbors
  2040. float a1 = bed_level_grid[x + xdir][y], a2 = bed_level_grid[x + xdir * 2][y],
  2041. b1 = bed_level_grid[x][y + ydir], b2 = bed_level_grid[x][y + ydir * 2],
  2042. c1 = bed_level_grid[x + xdir][y + ydir], c2 = bed_level_grid[x + xdir * 2][y + ydir * 2];
  2043. // Treat far unprobed points as zero, near as equal to far
  2044. if (a2 == UNPROBED) a2 = 0.0; if (a1 == UNPROBED) a1 = a2;
  2045. if (b2 == UNPROBED) b2 = 0.0; if (b1 == UNPROBED) b1 = b2;
  2046. if (c2 == UNPROBED) c2 = 0.0; if (c1 == UNPROBED) c1 = c2;
  2047. const float a = 2 * a1 - a2, b = 2 * b1 - b2, c = 2 * c1 - c2;
  2048. // Take the average instead of the median
  2049. bed_level_grid[x][y] = (a + b + c) / 3.0;
  2050. // Median is robust (ignores outliers).
  2051. // bed_level_grid[x][y] = (a < b) ? ((b < c) ? b : (c < a) ? a : c)
  2052. // : ((c < b) ? b : (a < c) ? a : c);
  2053. }
  2054. //Enable this if your SCARA uses 180° of total area
  2055. //#define EXTRAPOLATE_FROM_EDGE
  2056. #if ENABLED(EXTRAPOLATE_FROM_EDGE)
  2057. #if ABL_GRID_MAX_POINTS_X < ABL_GRID_MAX_POINTS_Y
  2058. #define HALF_IN_X
  2059. #elif ABL_GRID_MAX_POINTS_Y < ABL_GRID_MAX_POINTS_X
  2060. #define HALF_IN_Y
  2061. #endif
  2062. #endif
  2063. /**
  2064. * Fill in the unprobed points (corners of circular print surface)
  2065. * using linear extrapolation, away from the center.
  2066. */
  2067. static void extrapolate_unprobed_bed_level() {
  2068. #ifdef HALF_IN_X
  2069. const uint8_t ctrx2 = 0, xlen = ABL_GRID_MAX_POINTS_X - 1;
  2070. #else
  2071. const uint8_t ctrx1 = (ABL_GRID_MAX_POINTS_X - 1) / 2, // left-of-center
  2072. ctrx2 = ABL_GRID_MAX_POINTS_X / 2, // right-of-center
  2073. xlen = ctrx1;
  2074. #endif
  2075. #ifdef HALF_IN_Y
  2076. const uint8_t ctry2 = 0, ylen = ABL_GRID_MAX_POINTS_Y - 1;
  2077. #else
  2078. const uint8_t ctry1 = (ABL_GRID_MAX_POINTS_Y - 1) / 2, // top-of-center
  2079. ctry2 = ABL_GRID_MAX_POINTS_Y / 2, // bottom-of-center
  2080. ylen = ctry1;
  2081. #endif
  2082. for (uint8_t xo = 0; xo <= xlen; xo++)
  2083. for (uint8_t yo = 0; yo <= ylen; yo++) {
  2084. uint8_t x2 = ctrx2 + xo, y2 = ctry2 + yo;
  2085. #ifndef HALF_IN_X
  2086. const uint8_t x1 = ctrx1 - xo;
  2087. #endif
  2088. #ifndef HALF_IN_Y
  2089. const uint8_t y1 = ctry1 - yo;
  2090. #ifndef HALF_IN_X
  2091. extrapolate_one_point(x1, y1, +1, +1); // left-below + +
  2092. #endif
  2093. extrapolate_one_point(x2, y1, -1, +1); // right-below - +
  2094. #endif
  2095. #ifndef HALF_IN_X
  2096. extrapolate_one_point(x1, y2, +1, -1); // left-above + -
  2097. #endif
  2098. extrapolate_one_point(x2, y2, -1, -1); // right-above - -
  2099. }
  2100. }
  2101. /**
  2102. * Print calibration results for plotting or manual frame adjustment.
  2103. */
  2104. 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)) {
  2105. for (uint8_t x = 0; x < sx; x++) {
  2106. for (uint8_t i = 0; i < precision + 2 + (x < 10 ? 1 : 0); i++)
  2107. SERIAL_PROTOCOLCHAR(' ');
  2108. SERIAL_PROTOCOL((int)x);
  2109. }
  2110. SERIAL_EOL;
  2111. for (uint8_t y = 0; y < sy; y++) {
  2112. if (y < 10) SERIAL_PROTOCOLCHAR(' ');
  2113. SERIAL_PROTOCOL((int)y);
  2114. for (uint8_t x = 0; x < sx; x++) {
  2115. SERIAL_PROTOCOLCHAR(' ');
  2116. float offset = fn(x, y);
  2117. if (offset != UNPROBED) {
  2118. if (offset >= 0) SERIAL_CHAR('+');
  2119. SERIAL_PROTOCOL_F(offset, precision);
  2120. }
  2121. else
  2122. for (uint8_t i = 0; i < precision + 3; i++)
  2123. SERIAL_PROTOCOLCHAR(i ? '=' : ' ');
  2124. }
  2125. SERIAL_EOL;
  2126. }
  2127. SERIAL_EOL;
  2128. }
  2129. static void print_bilinear_leveling_grid() {
  2130. SERIAL_ECHOLNPGM("Bilinear Leveling Grid:");
  2131. print_2d_array(ABL_GRID_MAX_POINTS_X, ABL_GRID_MAX_POINTS_Y, 2,
  2132. [](const uint8_t x, const uint8_t y) { return bed_level_grid[x][y]; }
  2133. );
  2134. }
  2135. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  2136. #define ABL_GRID_POINTS_VIRT_X (ABL_GRID_MAX_POINTS_X - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2137. #define ABL_GRID_POINTS_VIRT_Y (ABL_GRID_MAX_POINTS_Y - 1) * (BILINEAR_SUBDIVISIONS) + 1
  2138. #define ABL_TEMP_POINTS_X (ABL_GRID_MAX_POINTS_X + 2)
  2139. #define ABL_TEMP_POINTS_Y (ABL_GRID_MAX_POINTS_Y + 2)
  2140. float bed_level_grid_virt[ABL_GRID_POINTS_VIRT_X][ABL_GRID_POINTS_VIRT_Y];
  2141. int bilinear_grid_spacing_virt[2] = { 0 };
  2142. static void bed_level_virt_print() {
  2143. SERIAL_ECHOLNPGM("Subdivided with CATMULL ROM Leveling Grid:");
  2144. print_2d_array(ABL_GRID_POINTS_VIRT_X, ABL_GRID_POINTS_VIRT_Y, 5,
  2145. [](const uint8_t x, const uint8_t y) { return bed_level_grid_virt[x][y]; }
  2146. );
  2147. }
  2148. #define LINEAR_EXTRAPOLATION(E, I) ((E) * 2 - (I))
  2149. float bed_level_virt_coord(const uint8_t x, const uint8_t y) {
  2150. uint8_t ep = 0, ip = 1;
  2151. if (!x || x == ABL_TEMP_POINTS_X - 1) {
  2152. if (x) {
  2153. ep = ABL_GRID_MAX_POINTS_X - 1;
  2154. ip = ABL_GRID_MAX_POINTS_X - 2;
  2155. }
  2156. if (y > 0 && y < ABL_TEMP_POINTS_Y - 1)
  2157. return LINEAR_EXTRAPOLATION(
  2158. bed_level_grid[ep][y - 1],
  2159. bed_level_grid[ip][y - 1]
  2160. );
  2161. else
  2162. return LINEAR_EXTRAPOLATION(
  2163. bed_level_virt_coord(ep + 1, y),
  2164. bed_level_virt_coord(ip + 1, y)
  2165. );
  2166. }
  2167. if (!y || y == ABL_TEMP_POINTS_Y - 1) {
  2168. if (y) {
  2169. ep = ABL_GRID_MAX_POINTS_Y - 1;
  2170. ip = ABL_GRID_MAX_POINTS_Y - 2;
  2171. }
  2172. if (x > 0 && x < ABL_TEMP_POINTS_X - 1)
  2173. return LINEAR_EXTRAPOLATION(
  2174. bed_level_grid[x - 1][ep],
  2175. bed_level_grid[x - 1][ip]
  2176. );
  2177. else
  2178. return LINEAR_EXTRAPOLATION(
  2179. bed_level_virt_coord(x, ep + 1),
  2180. bed_level_virt_coord(x, ip + 1)
  2181. );
  2182. }
  2183. return bed_level_grid[x - 1][y - 1];
  2184. }
  2185. static float bed_level_virt_cmr(const float p[4], const uint8_t i, const float t) {
  2186. return (
  2187. p[i-1] * -t * sq(1 - t)
  2188. + p[i] * (2 - 5 * sq(t) + 3 * t * sq(t))
  2189. + p[i+1] * t * (1 + 4 * t - 3 * sq(t))
  2190. - p[i+2] * sq(t) * (1 - t)
  2191. ) * 0.5;
  2192. }
  2193. static float bed_level_virt_2cmr(const uint8_t x, const uint8_t y, const float &tx, const float &ty) {
  2194. float row[4], column[4];
  2195. for (uint8_t i = 0; i < 4; i++) {
  2196. for (uint8_t j = 0; j < 4; j++) {
  2197. column[j] = bed_level_virt_coord(i + x - 1, j + y - 1);
  2198. }
  2199. row[i] = bed_level_virt_cmr(column, 1, ty);
  2200. }
  2201. return bed_level_virt_cmr(row, 1, tx);
  2202. }
  2203. void bed_level_virt_interpolate() {
  2204. for (uint8_t y = 0; y < ABL_GRID_MAX_POINTS_Y; y++)
  2205. for (uint8_t x = 0; x < ABL_GRID_MAX_POINTS_X; x++)
  2206. for (uint8_t ty = 0; ty < BILINEAR_SUBDIVISIONS; ty++)
  2207. for (uint8_t tx = 0; tx < BILINEAR_SUBDIVISIONS; tx++) {
  2208. if ((ty && y == ABL_GRID_MAX_POINTS_Y - 1) || (tx && x == ABL_GRID_MAX_POINTS_X - 1))
  2209. continue;
  2210. bed_level_grid_virt[x * (BILINEAR_SUBDIVISIONS) + tx][y * (BILINEAR_SUBDIVISIONS) + ty] =
  2211. bed_level_virt_2cmr(
  2212. x + 1,
  2213. y + 1,
  2214. (float)tx / (BILINEAR_SUBDIVISIONS),
  2215. (float)ty / (BILINEAR_SUBDIVISIONS)
  2216. );
  2217. }
  2218. }
  2219. #endif // ABL_BILINEAR_SUBDIVISION
  2220. #endif // AUTO_BED_LEVELING_BILINEAR
  2221. /**
  2222. * Home an individual linear axis
  2223. */
  2224. static void do_homing_move(const AxisEnum axis, float distance, float fr_mm_s=0.0) {
  2225. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2226. if (DEBUGGING(LEVELING)) {
  2227. SERIAL_ECHOPAIR(">>> do_homing_move(", axis_codes[axis]);
  2228. SERIAL_ECHOPAIR(", ", distance);
  2229. SERIAL_ECHOPAIR(", ", fr_mm_s);
  2230. SERIAL_CHAR(')');
  2231. SERIAL_EOL;
  2232. }
  2233. #endif
  2234. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2235. const bool deploy_bltouch = (axis == Z_AXIS && distance < 0);
  2236. if (deploy_bltouch) set_bltouch_deployed(true);
  2237. #endif
  2238. // Tell the planner we're at Z=0
  2239. current_position[axis] = 0;
  2240. #if IS_SCARA
  2241. SYNC_PLAN_POSITION_KINEMATIC();
  2242. current_position[axis] = distance;
  2243. inverse_kinematics(current_position);
  2244. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], current_position[E_AXIS], fr_mm_s ? fr_mm_s : homing_feedrate_mm_s[axis], active_extruder);
  2245. #else
  2246. sync_plan_position();
  2247. current_position[axis] = distance;
  2248. 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_mm_s[axis], active_extruder);
  2249. #endif
  2250. stepper.synchronize();
  2251. #if HOMING_Z_WITH_PROBE && ENABLED(BLTOUCH)
  2252. if (deploy_bltouch) set_bltouch_deployed(false);
  2253. #endif
  2254. endstops.hit_on_purpose();
  2255. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2256. if (DEBUGGING(LEVELING)) {
  2257. SERIAL_ECHOPAIR("<<< do_homing_move(", axis_codes[axis]);
  2258. SERIAL_CHAR(')');
  2259. SERIAL_EOL;
  2260. }
  2261. #endif
  2262. }
  2263. /**
  2264. * Home an individual "raw axis" to its endstop.
  2265. * This applies to XYZ on Cartesian and Core robots, and
  2266. * to the individual ABC steppers on DELTA and SCARA.
  2267. *
  2268. * At the end of the procedure the axis is marked as
  2269. * homed and the current position of that axis is updated.
  2270. * Kinematic robots should wait till all axes are homed
  2271. * before updating the current position.
  2272. */
  2273. #define HOMEAXIS(LETTER) homeaxis(LETTER##_AXIS)
  2274. static void homeaxis(const AxisEnum axis) {
  2275. #if IS_SCARA
  2276. // Only Z homing (with probe) is permitted
  2277. if (axis != Z_AXIS) { BUZZ(100, 880); return; }
  2278. #else
  2279. #define CAN_HOME(A) \
  2280. (axis == A##_AXIS && ((A##_MIN_PIN > -1 && A##_HOME_DIR < 0) || (A##_MAX_PIN > -1 && A##_HOME_DIR > 0)))
  2281. if (!CAN_HOME(X) && !CAN_HOME(Y) && !CAN_HOME(Z)) return;
  2282. #endif
  2283. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2284. if (DEBUGGING(LEVELING)) {
  2285. SERIAL_ECHOPAIR(">>> homeaxis(", axis_codes[axis]);
  2286. SERIAL_CHAR(')');
  2287. SERIAL_EOL;
  2288. }
  2289. #endif
  2290. const int axis_home_dir =
  2291. #if ENABLED(DUAL_X_CARRIAGE)
  2292. (axis == X_AXIS) ? x_home_dir(active_extruder) :
  2293. #endif
  2294. home_dir(axis);
  2295. // Homing Z towards the bed? Deploy the Z probe or endstop.
  2296. #if HOMING_Z_WITH_PROBE
  2297. if (axis == Z_AXIS && DEPLOY_PROBE()) return;
  2298. #endif
  2299. // Set a flag for Z motor locking
  2300. #if ENABLED(Z_DUAL_ENDSTOPS)
  2301. if (axis == Z_AXIS) stepper.set_homing_flag(true);
  2302. #endif
  2303. // Fast move towards endstop until triggered
  2304. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2305. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 1 Fast:");
  2306. #endif
  2307. do_homing_move(axis, 1.5 * max_length(axis) * axis_home_dir);
  2308. // When homing Z with probe respect probe clearance
  2309. const float bump = axis_home_dir * (
  2310. #if HOMING_Z_WITH_PROBE
  2311. (axis == Z_AXIS) ? max(Z_CLEARANCE_BETWEEN_PROBES, home_bump_mm(Z_AXIS)) :
  2312. #endif
  2313. home_bump_mm(axis)
  2314. );
  2315. // If a second homing move is configured...
  2316. if (bump) {
  2317. // Move away from the endstop by the axis HOME_BUMP_MM
  2318. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2319. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Move Away:");
  2320. #endif
  2321. do_homing_move(axis, -bump);
  2322. // Slow move towards endstop until triggered
  2323. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2324. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Home 2 Slow:");
  2325. #endif
  2326. do_homing_move(axis, 2 * bump, get_homing_bump_feedrate(axis));
  2327. }
  2328. #if ENABLED(Z_DUAL_ENDSTOPS)
  2329. if (axis == Z_AXIS) {
  2330. float adj = fabs(z_endstop_adj);
  2331. bool lockZ1;
  2332. if (axis_home_dir > 0) {
  2333. adj = -adj;
  2334. lockZ1 = (z_endstop_adj > 0);
  2335. }
  2336. else
  2337. lockZ1 = (z_endstop_adj < 0);
  2338. if (lockZ1) stepper.set_z_lock(true); else stepper.set_z2_lock(true);
  2339. // Move to the adjusted endstop height
  2340. do_homing_move(axis, adj);
  2341. if (lockZ1) stepper.set_z_lock(false); else stepper.set_z2_lock(false);
  2342. stepper.set_homing_flag(false);
  2343. } // Z_AXIS
  2344. #endif
  2345. #if IS_SCARA
  2346. set_axis_is_at_home(axis);
  2347. SYNC_PLAN_POSITION_KINEMATIC();
  2348. #elif ENABLED(DELTA)
  2349. // Delta has already moved all three towers up in G28
  2350. // so here it re-homes each tower in turn.
  2351. // Delta homing treats the axes as normal linear axes.
  2352. // retrace by the amount specified in endstop_adj
  2353. if (endstop_adj[axis] * Z_HOME_DIR < 0) {
  2354. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2355. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("endstop_adj:");
  2356. #endif
  2357. do_homing_move(axis, endstop_adj[axis]);
  2358. }
  2359. #else
  2360. // For cartesian/core machines,
  2361. // set the axis to its home position
  2362. set_axis_is_at_home(axis);
  2363. sync_plan_position();
  2364. destination[axis] = current_position[axis];
  2365. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2366. if (DEBUGGING(LEVELING)) DEBUG_POS("> AFTER set_axis_is_at_home", current_position);
  2367. #endif
  2368. #endif
  2369. // Put away the Z probe
  2370. #if HOMING_Z_WITH_PROBE
  2371. if (axis == Z_AXIS && STOW_PROBE()) return;
  2372. #endif
  2373. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2374. if (DEBUGGING(LEVELING)) {
  2375. SERIAL_ECHOPAIR("<<< homeaxis(", axis_codes[axis]);
  2376. SERIAL_CHAR(')');
  2377. SERIAL_EOL;
  2378. }
  2379. #endif
  2380. } // homeaxis()
  2381. #if ENABLED(FWRETRACT)
  2382. void retract(const bool retracting, const bool swapping = false) {
  2383. static float hop_height;
  2384. if (retracting == retracted[active_extruder]) return;
  2385. const float old_feedrate_mm_s = feedrate_mm_s;
  2386. set_destination_to_current();
  2387. if (retracting) {
  2388. feedrate_mm_s = retract_feedrate_mm_s;
  2389. current_position[E_AXIS] += (swapping ? retract_length_swap : retract_length) / volumetric_multiplier[active_extruder];
  2390. sync_plan_position_e();
  2391. prepare_move_to_destination();
  2392. if (retract_zlift > 0.01) {
  2393. hop_height = current_position[Z_AXIS];
  2394. // Pretend current position is lower
  2395. current_position[Z_AXIS] -= retract_zlift;
  2396. SYNC_PLAN_POSITION_KINEMATIC();
  2397. // Raise up to the old current_position
  2398. prepare_move_to_destination();
  2399. }
  2400. }
  2401. else {
  2402. // If the height hasn't been altered, undo the Z hop
  2403. if (retract_zlift > 0.01 && hop_height == current_position[Z_AXIS]) {
  2404. // Pretend current position is higher. Z will lower on the next move
  2405. current_position[Z_AXIS] += retract_zlift;
  2406. SYNC_PLAN_POSITION_KINEMATIC();
  2407. }
  2408. feedrate_mm_s = retract_recover_feedrate_mm_s;
  2409. const float move_e = swapping ? retract_length_swap + retract_recover_length_swap : retract_length + retract_recover_length;
  2410. current_position[E_AXIS] -= move_e / volumetric_multiplier[active_extruder];
  2411. sync_plan_position_e();
  2412. // Lower Z and recover E
  2413. prepare_move_to_destination();
  2414. }
  2415. feedrate_mm_s = old_feedrate_mm_s;
  2416. retracted[active_extruder] = retracting;
  2417. } // retract()
  2418. #endif // FWRETRACT
  2419. #if ENABLED(MIXING_EXTRUDER)
  2420. void normalize_mix() {
  2421. float mix_total = 0.0;
  2422. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mix_total += RECIPROCAL(mixing_factor[i]);
  2423. // Scale all values if they don't add up to ~1.0
  2424. if (!NEAR(mix_total, 1.0)) {
  2425. SERIAL_PROTOCOLLNPGM("Warning: Mix factors must add up to 1.0. Scaling.");
  2426. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) mixing_factor[i] *= mix_total;
  2427. }
  2428. }
  2429. #if ENABLED(DIRECT_MIXING_IN_G1)
  2430. // Get mixing parameters from the GCode
  2431. // The total "must" be 1.0 (but it will be normalized)
  2432. // If no mix factors are given, the old mix is preserved
  2433. void gcode_get_mix() {
  2434. const char* mixing_codes = "ABCDHI";
  2435. byte mix_bits = 0;
  2436. for (uint8_t i = 0; i < MIXING_STEPPERS; i++) {
  2437. if (code_seen(mixing_codes[i])) {
  2438. SBI(mix_bits, i);
  2439. float v = code_value_float();
  2440. NOLESS(v, 0.0);
  2441. mixing_factor[i] = RECIPROCAL(v);
  2442. }
  2443. }
  2444. // If any mixing factors were included, clear the rest
  2445. // If none were included, preserve the last mix
  2446. if (mix_bits) {
  2447. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  2448. if (!TEST(mix_bits, i)) mixing_factor[i] = 0.0;
  2449. normalize_mix();
  2450. }
  2451. }
  2452. #endif
  2453. #endif
  2454. /**
  2455. * ***************************************************************************
  2456. * ***************************** G-CODE HANDLING *****************************
  2457. * ***************************************************************************
  2458. */
  2459. /**
  2460. * Set XYZE destination and feedrate from the current GCode command
  2461. *
  2462. * - Set destination from included axis codes
  2463. * - Set to current for missing axis codes
  2464. * - Set the feedrate, if included
  2465. */
  2466. void gcode_get_destination() {
  2467. LOOP_XYZE(i) {
  2468. if (code_seen(axis_codes[i]))
  2469. destination[i] = code_value_axis_units(i) + (axis_relative_modes[i] || relative_mode ? current_position[i] : 0);
  2470. else
  2471. destination[i] = current_position[i];
  2472. }
  2473. if (code_seen('F') && code_value_linear_units() > 0.0)
  2474. feedrate_mm_s = MMM_TO_MMS(code_value_linear_units());
  2475. #if ENABLED(PRINTCOUNTER)
  2476. if (!DEBUGGING(DRYRUN))
  2477. print_job_timer.incFilamentUsed(destination[E_AXIS] - current_position[E_AXIS]);
  2478. #endif
  2479. // Get ABCDHI mixing factors
  2480. #if ENABLED(MIXING_EXTRUDER) && ENABLED(DIRECT_MIXING_IN_G1)
  2481. gcode_get_mix();
  2482. #endif
  2483. }
  2484. void unknown_command_error() {
  2485. SERIAL_ECHO_START;
  2486. SERIAL_ECHOPAIR(MSG_UNKNOWN_COMMAND, current_command);
  2487. SERIAL_CHAR('"');
  2488. SERIAL_EOL;
  2489. }
  2490. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  2491. /**
  2492. * Output a "busy" message at regular intervals
  2493. * while the machine is not accepting commands.
  2494. */
  2495. void host_keepalive() {
  2496. const millis_t ms = millis();
  2497. if (host_keepalive_interval && busy_state != NOT_BUSY) {
  2498. if (PENDING(ms, next_busy_signal_ms)) return;
  2499. switch (busy_state) {
  2500. case IN_HANDLER:
  2501. case IN_PROCESS:
  2502. SERIAL_ECHO_START;
  2503. SERIAL_ECHOLNPGM(MSG_BUSY_PROCESSING);
  2504. break;
  2505. case PAUSED_FOR_USER:
  2506. SERIAL_ECHO_START;
  2507. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_USER);
  2508. break;
  2509. case PAUSED_FOR_INPUT:
  2510. SERIAL_ECHO_START;
  2511. SERIAL_ECHOLNPGM(MSG_BUSY_PAUSED_FOR_INPUT);
  2512. break;
  2513. default:
  2514. break;
  2515. }
  2516. }
  2517. next_busy_signal_ms = ms + host_keepalive_interval * 1000UL;
  2518. }
  2519. #endif //HOST_KEEPALIVE_FEATURE
  2520. bool position_is_reachable(float target[XYZ]
  2521. #if HAS_BED_PROBE
  2522. , bool by_probe=false
  2523. #endif
  2524. ) {
  2525. float dx = RAW_X_POSITION(target[X_AXIS]),
  2526. dy = RAW_Y_POSITION(target[Y_AXIS]);
  2527. #if HAS_BED_PROBE
  2528. if (by_probe) {
  2529. dx -= X_PROBE_OFFSET_FROM_EXTRUDER;
  2530. dy -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  2531. }
  2532. #endif
  2533. #if IS_SCARA
  2534. #if MIDDLE_DEAD_ZONE_R > 0
  2535. const float R2 = HYPOT2(dx - SCARA_OFFSET_X, dy - SCARA_OFFSET_Y);
  2536. return R2 >= sq(float(MIDDLE_DEAD_ZONE_R)) && R2 <= sq(L1 + L2);
  2537. #else
  2538. return HYPOT2(dx - SCARA_OFFSET_X, dy - SCARA_OFFSET_Y) <= sq(L1 + L2);
  2539. #endif
  2540. #elif ENABLED(DELTA)
  2541. return HYPOT2(dx, dy) <= sq((float)(DELTA_PRINTABLE_RADIUS));
  2542. #else
  2543. const float dz = RAW_Z_POSITION(target[Z_AXIS]);
  2544. return dx >= X_MIN_POS - 0.0001 && dx <= X_MAX_POS + 0.0001
  2545. && dy >= Y_MIN_POS - 0.0001 && dy <= Y_MAX_POS + 0.0001
  2546. && dz >= Z_MIN_POS - 0.0001 && dz <= Z_MAX_POS + 0.0001;
  2547. #endif
  2548. }
  2549. /**************************************************
  2550. ***************** GCode Handlers *****************
  2551. **************************************************/
  2552. /**
  2553. * G0, G1: Coordinated movement of X Y Z E axes
  2554. */
  2555. inline void gcode_G0_G1(
  2556. #if IS_SCARA
  2557. bool fast_move=false
  2558. #endif
  2559. ) {
  2560. if (IsRunning()) {
  2561. gcode_get_destination(); // For X Y Z E F
  2562. #if ENABLED(FWRETRACT)
  2563. if (autoretract_enabled && !(code_seen('X') || code_seen('Y') || code_seen('Z')) && code_seen('E')) {
  2564. const float echange = destination[E_AXIS] - current_position[E_AXIS];
  2565. // Is this move an attempt to retract or recover?
  2566. if ((echange < -MIN_RETRACT && !retracted[active_extruder]) || (echange > MIN_RETRACT && retracted[active_extruder])) {
  2567. current_position[E_AXIS] = destination[E_AXIS]; // hide the slicer-generated retract/recover from calculations
  2568. sync_plan_position_e(); // AND from the planner
  2569. retract(!retracted[active_extruder]);
  2570. return;
  2571. }
  2572. }
  2573. #endif //FWRETRACT
  2574. #if IS_SCARA
  2575. fast_move ? prepare_uninterpolated_move_to_destination() : prepare_move_to_destination();
  2576. #else
  2577. prepare_move_to_destination();
  2578. #endif
  2579. }
  2580. }
  2581. /**
  2582. * G2: Clockwise Arc
  2583. * G3: Counterclockwise Arc
  2584. *
  2585. * This command has two forms: IJ-form and R-form.
  2586. *
  2587. * - I specifies an X offset. J specifies a Y offset.
  2588. * At least one of the IJ parameters is required.
  2589. * X and Y can be omitted to do a complete circle.
  2590. * The given XY is not error-checked. The arc ends
  2591. * based on the angle of the destination.
  2592. * Mixing I or J with R will throw an error.
  2593. *
  2594. * - R specifies the radius. X or Y is required.
  2595. * Omitting both X and Y will throw an error.
  2596. * X or Y must differ from the current XY.
  2597. * Mixing R with I or J will throw an error.
  2598. *
  2599. * Examples:
  2600. *
  2601. * G2 I10 ; CW circle centered at X+10
  2602. * G3 X20 Y12 R14 ; CCW circle with r=14 ending at X20 Y12
  2603. */
  2604. #if ENABLED(ARC_SUPPORT)
  2605. inline void gcode_G2_G3(bool clockwise) {
  2606. if (IsRunning()) {
  2607. #if ENABLED(SF_ARC_FIX)
  2608. const bool relative_mode_backup = relative_mode;
  2609. relative_mode = true;
  2610. #endif
  2611. gcode_get_destination();
  2612. #if ENABLED(SF_ARC_FIX)
  2613. relative_mode = relative_mode_backup;
  2614. #endif
  2615. float arc_offset[2] = { 0.0, 0.0 };
  2616. if (code_seen('R')) {
  2617. const float r = code_value_axis_units(X_AXIS),
  2618. x1 = current_position[X_AXIS], y1 = current_position[Y_AXIS],
  2619. x2 = destination[X_AXIS], y2 = destination[Y_AXIS];
  2620. if (r && (x2 != x1 || y2 != y1)) {
  2621. const float e = clockwise ^ (r < 0) ? -1 : 1, // clockwise -1/1, counterclockwise 1/-1
  2622. dx = x2 - x1, dy = y2 - y1, // X and Y differences
  2623. d = HYPOT(dx, dy), // Linear distance between the points
  2624. h = sqrt(sq(r) - sq(d * 0.5)), // Distance to the arc pivot-point
  2625. mx = (x1 + x2) * 0.5, my = (y1 + y2) * 0.5, // Point between the two points
  2626. sx = -dy / d, sy = dx / d, // Slope of the perpendicular bisector
  2627. cx = mx + e * h * sx, cy = my + e * h * sy; // Pivot-point of the arc
  2628. arc_offset[X_AXIS] = cx - x1;
  2629. arc_offset[Y_AXIS] = cy - y1;
  2630. }
  2631. }
  2632. else {
  2633. if (code_seen('I')) arc_offset[X_AXIS] = code_value_axis_units(X_AXIS);
  2634. if (code_seen('J')) arc_offset[Y_AXIS] = code_value_axis_units(Y_AXIS);
  2635. }
  2636. if (arc_offset[0] || arc_offset[1]) {
  2637. // Send an arc to the planner
  2638. plan_arc(destination, arc_offset, clockwise);
  2639. refresh_cmd_timeout();
  2640. }
  2641. else {
  2642. // Bad arguments
  2643. SERIAL_ERROR_START;
  2644. SERIAL_ERRORLNPGM(MSG_ERR_ARC_ARGS);
  2645. }
  2646. }
  2647. }
  2648. #endif
  2649. /**
  2650. * G4: Dwell S<seconds> or P<milliseconds>
  2651. */
  2652. inline void gcode_G4() {
  2653. millis_t dwell_ms = 0;
  2654. if (code_seen('P')) dwell_ms = code_value_millis(); // milliseconds to wait
  2655. if (code_seen('S')) dwell_ms = code_value_millis_from_seconds(); // seconds to wait
  2656. stepper.synchronize();
  2657. refresh_cmd_timeout();
  2658. dwell_ms += previous_cmd_ms; // keep track of when we started waiting
  2659. if (!lcd_hasstatus()) LCD_MESSAGEPGM(MSG_DWELL);
  2660. while (PENDING(millis(), dwell_ms)) idle();
  2661. }
  2662. #if ENABLED(BEZIER_CURVE_SUPPORT)
  2663. /**
  2664. * Parameters interpreted according to:
  2665. * http://linuxcnc.org/docs/2.6/html/gcode/gcode.html#sec:G5-Cubic-Spline
  2666. * However I, J omission is not supported at this point; all
  2667. * parameters can be omitted and default to zero.
  2668. */
  2669. /**
  2670. * G5: Cubic B-spline
  2671. */
  2672. inline void gcode_G5() {
  2673. if (IsRunning()) {
  2674. gcode_get_destination();
  2675. const float offset[] = {
  2676. code_seen('I') ? code_value_axis_units(X_AXIS) : 0.0,
  2677. code_seen('J') ? code_value_axis_units(Y_AXIS) : 0.0,
  2678. code_seen('P') ? code_value_axis_units(X_AXIS) : 0.0,
  2679. code_seen('Q') ? code_value_axis_units(Y_AXIS) : 0.0
  2680. };
  2681. plan_cubic_move(offset);
  2682. }
  2683. }
  2684. #endif // BEZIER_CURVE_SUPPORT
  2685. #if ENABLED(FWRETRACT)
  2686. /**
  2687. * G10 - Retract filament according to settings of M207
  2688. * G11 - Recover filament according to settings of M208
  2689. */
  2690. inline void gcode_G10_G11(bool doRetract=false) {
  2691. #if EXTRUDERS > 1
  2692. if (doRetract) {
  2693. retracted_swap[active_extruder] = (code_seen('S') && code_value_bool()); // checks for swap retract argument
  2694. }
  2695. #endif
  2696. retract(doRetract
  2697. #if EXTRUDERS > 1
  2698. , retracted_swap[active_extruder]
  2699. #endif
  2700. );
  2701. }
  2702. #endif //FWRETRACT
  2703. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  2704. /**
  2705. * G12: Clean the nozzle
  2706. */
  2707. inline void gcode_G12() {
  2708. // Don't allow nozzle cleaning without homing first
  2709. if (axis_unhomed_error(true, true, true)) { return; }
  2710. const uint8_t pattern = code_seen('P') ? code_value_ushort() : 0,
  2711. strokes = code_seen('S') ? code_value_ushort() : NOZZLE_CLEAN_STROKES,
  2712. objects = code_seen('T') ? code_value_ushort() : NOZZLE_CLEAN_TRIANGLES;
  2713. const float radius = code_seen('R') ? code_value_float() : NOZZLE_CLEAN_CIRCLE_RADIUS;
  2714. Nozzle::clean(pattern, strokes, radius, objects);
  2715. }
  2716. #endif
  2717. #if ENABLED(INCH_MODE_SUPPORT)
  2718. /**
  2719. * G20: Set input mode to inches
  2720. */
  2721. inline void gcode_G20() { set_input_linear_units(LINEARUNIT_INCH); }
  2722. /**
  2723. * G21: Set input mode to millimeters
  2724. */
  2725. inline void gcode_G21() { set_input_linear_units(LINEARUNIT_MM); }
  2726. #endif
  2727. #if ENABLED(NOZZLE_PARK_FEATURE)
  2728. /**
  2729. * G27: Park the nozzle
  2730. */
  2731. inline void gcode_G27() {
  2732. // Don't allow nozzle parking without homing first
  2733. if (axis_unhomed_error(true, true, true)) return;
  2734. Nozzle::park(code_seen('P') ? code_value_ushort() : 0);
  2735. }
  2736. #endif // NOZZLE_PARK_FEATURE
  2737. #if ENABLED(QUICK_HOME)
  2738. static void quick_home_xy() {
  2739. // Pretend the current position is 0,0
  2740. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2741. sync_plan_position();
  2742. const int x_axis_home_dir =
  2743. #if ENABLED(DUAL_X_CARRIAGE)
  2744. x_home_dir(active_extruder)
  2745. #else
  2746. home_dir(X_AXIS)
  2747. #endif
  2748. ;
  2749. const float mlx = max_length(X_AXIS),
  2750. mly = max_length(Y_AXIS),
  2751. mlratio = mlx > mly ? mly / mlx : mlx / mly,
  2752. fr_mm_s = min(homing_feedrate_mm_s[X_AXIS], homing_feedrate_mm_s[Y_AXIS]) * sqrt(sq(mlratio) + 1.0);
  2753. do_blocking_move_to_xy(1.5 * mlx * x_axis_home_dir, 1.5 * mly * home_dir(Y_AXIS), fr_mm_s);
  2754. endstops.hit_on_purpose(); // clear endstop hit flags
  2755. current_position[X_AXIS] = current_position[Y_AXIS] = 0.0;
  2756. }
  2757. #endif // QUICK_HOME
  2758. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2759. void log_machine_info() {
  2760. SERIAL_ECHOPGM("Machine Type: ");
  2761. #if ENABLED(DELTA)
  2762. SERIAL_ECHOLNPGM("Delta");
  2763. #elif IS_SCARA
  2764. SERIAL_ECHOLNPGM("SCARA");
  2765. #elif IS_CORE
  2766. SERIAL_ECHOLNPGM("Core");
  2767. #else
  2768. SERIAL_ECHOLNPGM("Cartesian");
  2769. #endif
  2770. SERIAL_ECHOPGM("Probe: ");
  2771. #if ENABLED(FIX_MOUNTED_PROBE)
  2772. SERIAL_ECHOLNPGM("FIX_MOUNTED_PROBE");
  2773. #elif ENABLED(BLTOUCH)
  2774. SERIAL_ECHOLNPGM("BLTOUCH");
  2775. #elif HAS_Z_SERVO_ENDSTOP
  2776. SERIAL_ECHOLNPGM("SERVO PROBE");
  2777. #elif ENABLED(Z_PROBE_SLED)
  2778. SERIAL_ECHOLNPGM("Z_PROBE_SLED");
  2779. #elif ENABLED(Z_PROBE_ALLEN_KEY)
  2780. SERIAL_ECHOLNPGM("Z_PROBE_ALLEN_KEY");
  2781. #else
  2782. SERIAL_ECHOLNPGM("NONE");
  2783. #endif
  2784. #if HAS_BED_PROBE
  2785. SERIAL_ECHOPAIR("Probe Offset X:", X_PROBE_OFFSET_FROM_EXTRUDER);
  2786. SERIAL_ECHOPAIR(" Y:", Y_PROBE_OFFSET_FROM_EXTRUDER);
  2787. SERIAL_ECHOPAIR(" Z:", zprobe_zoffset);
  2788. #if (X_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2789. SERIAL_ECHOPGM(" (Right");
  2790. #elif (X_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2791. SERIAL_ECHOPGM(" (Left");
  2792. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2793. SERIAL_ECHOPGM(" (Middle");
  2794. #else
  2795. SERIAL_ECHOPGM(" (Aligned With");
  2796. #endif
  2797. #if (Y_PROBE_OFFSET_FROM_EXTRUDER > 0)
  2798. SERIAL_ECHOPGM("-Back");
  2799. #elif (Y_PROBE_OFFSET_FROM_EXTRUDER < 0)
  2800. SERIAL_ECHOPGM("-Front");
  2801. #elif (X_PROBE_OFFSET_FROM_EXTRUDER != 0)
  2802. SERIAL_ECHOPGM("-Center");
  2803. #endif
  2804. if (zprobe_zoffset < 0)
  2805. SERIAL_ECHOPGM(" & Below");
  2806. else if (zprobe_zoffset > 0)
  2807. SERIAL_ECHOPGM(" & Above");
  2808. else
  2809. SERIAL_ECHOPGM(" & Same Z as");
  2810. SERIAL_ECHOLNPGM(" Nozzle)");
  2811. #endif
  2812. #if HAS_ABL
  2813. SERIAL_ECHOPGM("Auto Bed Leveling: ");
  2814. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  2815. SERIAL_ECHOPGM("LINEAR");
  2816. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2817. SERIAL_ECHOPGM("BILINEAR");
  2818. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  2819. SERIAL_ECHOPGM("3POINT");
  2820. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  2821. SERIAL_ECHOPGM("UBL");
  2822. #endif
  2823. if (planner.abl_enabled) {
  2824. SERIAL_ECHOLNPGM(" (enabled)");
  2825. #if ENABLED(AUTO_BED_LEVELING_LINEAR) || ENABLED(AUTO_BED_LEVELING_3POINT) || ENABLED(AUTO_BED_LEVELING_UBL)
  2826. float diff[XYZ] = {
  2827. stepper.get_axis_position_mm(X_AXIS) - current_position[X_AXIS],
  2828. stepper.get_axis_position_mm(Y_AXIS) - current_position[Y_AXIS],
  2829. stepper.get_axis_position_mm(Z_AXIS) - current_position[Z_AXIS]
  2830. };
  2831. SERIAL_ECHOPGM("ABL Adjustment X");
  2832. if (diff[X_AXIS] > 0) SERIAL_CHAR('+');
  2833. SERIAL_ECHO(diff[X_AXIS]);
  2834. SERIAL_ECHOPGM(" Y");
  2835. if (diff[Y_AXIS] > 0) SERIAL_CHAR('+');
  2836. SERIAL_ECHO(diff[Y_AXIS]);
  2837. SERIAL_ECHOPGM(" Z");
  2838. if (diff[Z_AXIS] > 0) SERIAL_CHAR('+');
  2839. SERIAL_ECHO(diff[Z_AXIS]);
  2840. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  2841. SERIAL_ECHOPAIR("ABL Adjustment Z", bilinear_z_offset(current_position));
  2842. #endif
  2843. }
  2844. SERIAL_EOL;
  2845. #elif ENABLED(MESH_BED_LEVELING)
  2846. SERIAL_ECHOPGM("Mesh Bed Leveling");
  2847. if (mbl.active()) {
  2848. float lz = current_position[Z_AXIS];
  2849. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], lz);
  2850. SERIAL_ECHOLNPGM(" (enabled)");
  2851. SERIAL_ECHOPAIR("MBL Adjustment Z", lz);
  2852. }
  2853. SERIAL_EOL;
  2854. #endif
  2855. }
  2856. #endif // DEBUG_LEVELING_FEATURE
  2857. #if ENABLED(DELTA)
  2858. /**
  2859. * A delta can only safely home all axes at the same time
  2860. * This is like quick_home_xy() but for 3 towers.
  2861. */
  2862. inline void home_delta() {
  2863. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2864. if (DEBUGGING(LEVELING)) DEBUG_POS(">>> home_delta", current_position);
  2865. #endif
  2866. // Init the current position of all carriages to 0,0,0
  2867. ZERO(current_position);
  2868. sync_plan_position();
  2869. // Move all carriages together linearly until an endstop is hit.
  2870. current_position[X_AXIS] = current_position[Y_AXIS] = current_position[Z_AXIS] = (Z_MAX_LENGTH + 10);
  2871. feedrate_mm_s = homing_feedrate_mm_s[X_AXIS];
  2872. line_to_current_position();
  2873. stepper.synchronize();
  2874. endstops.hit_on_purpose(); // clear endstop hit flags
  2875. // At least one carriage has reached the top.
  2876. // Now re-home each carriage separately.
  2877. HOMEAXIS(A);
  2878. HOMEAXIS(B);
  2879. HOMEAXIS(C);
  2880. // Set all carriages to their home positions
  2881. // Do this here all at once for Delta, because
  2882. // XYZ isn't ABC. Applying this per-tower would
  2883. // give the impression that they are the same.
  2884. LOOP_XYZ(i) set_axis_is_at_home((AxisEnum)i);
  2885. SYNC_PLAN_POSITION_KINEMATIC();
  2886. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2887. if (DEBUGGING(LEVELING)) DEBUG_POS("<<< home_delta", current_position);
  2888. #endif
  2889. }
  2890. #endif // DELTA
  2891. #if ENABLED(Z_SAFE_HOMING)
  2892. inline void home_z_safely() {
  2893. // Disallow Z homing if X or Y are unknown
  2894. if (!axis_known_position[X_AXIS] || !axis_known_position[Y_AXIS]) {
  2895. LCD_MESSAGEPGM(MSG_ERR_Z_HOMING);
  2896. SERIAL_ECHO_START;
  2897. SERIAL_ECHOLNPGM(MSG_ERR_Z_HOMING);
  2898. return;
  2899. }
  2900. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2901. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("Z_SAFE_HOMING >>>");
  2902. #endif
  2903. SYNC_PLAN_POSITION_KINEMATIC();
  2904. /**
  2905. * Move the Z probe (or just the nozzle) to the safe homing point
  2906. */
  2907. destination[X_AXIS] = LOGICAL_X_POSITION(Z_SAFE_HOMING_X_POINT);
  2908. destination[Y_AXIS] = LOGICAL_Y_POSITION(Z_SAFE_HOMING_Y_POINT);
  2909. destination[Z_AXIS] = current_position[Z_AXIS]; // Z is already at the right height
  2910. if (position_is_reachable(
  2911. destination
  2912. #if HOMING_Z_WITH_PROBE
  2913. , true
  2914. #endif
  2915. )
  2916. ) {
  2917. #if HOMING_Z_WITH_PROBE
  2918. destination[X_AXIS] -= X_PROBE_OFFSET_FROM_EXTRUDER;
  2919. destination[Y_AXIS] -= Y_PROBE_OFFSET_FROM_EXTRUDER;
  2920. #endif
  2921. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2922. if (DEBUGGING(LEVELING)) DEBUG_POS("Z_SAFE_HOMING", destination);
  2923. #endif
  2924. // This causes the carriage on Dual X to unpark
  2925. #if ENABLED(DUAL_X_CARRIAGE)
  2926. active_extruder_parked = false;
  2927. #endif
  2928. do_blocking_move_to_xy(destination[X_AXIS], destination[Y_AXIS]);
  2929. HOMEAXIS(Z);
  2930. }
  2931. else {
  2932. LCD_MESSAGEPGM(MSG_ZPROBE_OUT);
  2933. SERIAL_ECHO_START;
  2934. SERIAL_ECHOLNPGM(MSG_ZPROBE_OUT);
  2935. }
  2936. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2937. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< Z_SAFE_HOMING");
  2938. #endif
  2939. }
  2940. #endif // Z_SAFE_HOMING
  2941. /**
  2942. * G28: Home all axes according to settings
  2943. *
  2944. * Parameters
  2945. *
  2946. * None Home to all axes with no parameters.
  2947. * With QUICK_HOME enabled XY will home together, then Z.
  2948. *
  2949. * Cartesian parameters
  2950. *
  2951. * X Home to the X endstop
  2952. * Y Home to the Y endstop
  2953. * Z Home to the Z endstop
  2954. *
  2955. */
  2956. inline void gcode_G28() {
  2957. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2958. if (DEBUGGING(LEVELING)) {
  2959. SERIAL_ECHOLNPGM(">>> gcode_G28");
  2960. log_machine_info();
  2961. }
  2962. #endif
  2963. // Wait for planner moves to finish!
  2964. stepper.synchronize();
  2965. // Disable the leveling matrix before homing
  2966. #if PLANNER_LEVELING || ENABLED(MESH_BED_LEVELING)
  2967. set_bed_leveling_enabled(false);
  2968. #endif
  2969. // Always home with tool 0 active
  2970. #if HOTENDS > 1
  2971. const uint8_t old_tool_index = active_extruder;
  2972. tool_change(0, 0, true);
  2973. #endif
  2974. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  2975. extruder_duplication_enabled = false;
  2976. #endif
  2977. setup_for_endstop_or_probe_move();
  2978. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2979. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> endstops.enable(true)");
  2980. #endif
  2981. endstops.enable(true); // Enable endstops for next homing move
  2982. #if ENABLED(DELTA)
  2983. home_delta();
  2984. #else // NOT DELTA
  2985. const bool homeX = code_seen('X'), homeY = code_seen('Y'), homeZ = code_seen('Z'),
  2986. home_all_axis = (!homeX && !homeY && !homeZ) || (homeX && homeY && homeZ);
  2987. set_destination_to_current();
  2988. #if Z_HOME_DIR > 0 // If homing away from BED do Z first
  2989. if (home_all_axis || homeZ) {
  2990. HOMEAXIS(Z);
  2991. #if ENABLED(DEBUG_LEVELING_FEATURE)
  2992. if (DEBUGGING(LEVELING)) DEBUG_POS("> HOMEAXIS(Z)", current_position);
  2993. #endif
  2994. }
  2995. #else
  2996. if (home_all_axis || homeX || homeY) {
  2997. // Raise Z before homing any other axes and z is not already high enough (never lower z)
  2998. destination[Z_AXIS] = LOGICAL_Z_POSITION(Z_HOMING_HEIGHT);
  2999. if (destination[Z_AXIS] > current_position[Z_AXIS]) {
  3000. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3001. if (DEBUGGING(LEVELING))
  3002. SERIAL_ECHOLNPAIR("Raise Z (before homing) to ", destination[Z_AXIS]);
  3003. #endif
  3004. do_blocking_move_to_z(destination[Z_AXIS]);
  3005. }
  3006. }
  3007. #endif
  3008. #if ENABLED(QUICK_HOME)
  3009. if (home_all_axis || (homeX && homeY)) quick_home_xy();
  3010. #endif
  3011. #if ENABLED(HOME_Y_BEFORE_X)
  3012. // Home Y
  3013. if (home_all_axis || homeY) {
  3014. HOMEAXIS(Y);
  3015. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3016. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3017. #endif
  3018. }
  3019. #endif
  3020. // Home X
  3021. if (home_all_axis || homeX) {
  3022. #if ENABLED(DUAL_X_CARRIAGE)
  3023. // Always home the 2nd (right) extruder first
  3024. active_extruder = 1;
  3025. HOMEAXIS(X);
  3026. // Remember this extruder's position for later tool change
  3027. inactive_extruder_x_pos = RAW_X_POSITION(current_position[X_AXIS]);
  3028. // Home the 1st (left) extruder
  3029. active_extruder = 0;
  3030. HOMEAXIS(X);
  3031. // Consider the active extruder to be parked
  3032. COPY(raised_parked_position, current_position);
  3033. delayed_move_time = 0;
  3034. active_extruder_parked = true;
  3035. #else
  3036. HOMEAXIS(X);
  3037. #endif
  3038. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3039. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeX", current_position);
  3040. #endif
  3041. }
  3042. #if DISABLED(HOME_Y_BEFORE_X)
  3043. // Home Y
  3044. if (home_all_axis || homeY) {
  3045. HOMEAXIS(Y);
  3046. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3047. if (DEBUGGING(LEVELING)) DEBUG_POS("> homeY", current_position);
  3048. #endif
  3049. }
  3050. #endif
  3051. // Home Z last if homing towards the bed
  3052. #if Z_HOME_DIR < 0
  3053. if (home_all_axis || homeZ) {
  3054. #if ENABLED(Z_SAFE_HOMING)
  3055. home_z_safely();
  3056. #else
  3057. HOMEAXIS(Z);
  3058. #endif
  3059. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3060. if (DEBUGGING(LEVELING)) DEBUG_POS("> (home_all_axis || homeZ) > final", current_position);
  3061. #endif
  3062. } // home_all_axis || homeZ
  3063. #endif // Z_HOME_DIR < 0
  3064. SYNC_PLAN_POSITION_KINEMATIC();
  3065. #endif // !DELTA (gcode_G28)
  3066. endstops.not_homing();
  3067. #if ENABLED(DELTA) && ENABLED(DELTA_HOME_TO_SAFE_ZONE)
  3068. // move to a height where we can use the full xy-area
  3069. do_blocking_move_to_z(delta_clip_start_height);
  3070. #endif
  3071. // Enable mesh leveling again
  3072. #if ENABLED(MESH_BED_LEVELING)
  3073. if (mbl.reactivate()) {
  3074. set_bed_leveling_enabled(true);
  3075. if (home_all_axis || (axis_homed[X_AXIS] && axis_homed[Y_AXIS] && homeZ)) {
  3076. #if ENABLED(MESH_G28_REST_ORIGIN)
  3077. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS);
  3078. set_destination_to_current();
  3079. line_to_destination(homing_feedrate_mm_s[Z_AXIS]);
  3080. stepper.synchronize();
  3081. #endif
  3082. }
  3083. }
  3084. #endif
  3085. clean_up_after_endstop_or_probe_move();
  3086. // Restore the active tool after homing
  3087. #if HOTENDS > 1
  3088. tool_change(old_tool_index, 0, true);
  3089. #endif
  3090. report_current_position();
  3091. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3092. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G28");
  3093. #endif
  3094. }
  3095. #if HAS_PROBING_PROCEDURE
  3096. void out_of_range_error(const char* p_edge) {
  3097. SERIAL_PROTOCOLPGM("?Probe ");
  3098. serialprintPGM(p_edge);
  3099. SERIAL_PROTOCOLLNPGM(" position out of range.");
  3100. }
  3101. #endif
  3102. #if ENABLED(MESH_BED_LEVELING)
  3103. inline void _mbl_goto_xy(const float &x, const float &y) {
  3104. const float old_feedrate_mm_s = feedrate_mm_s;
  3105. #if MANUAL_PROBE_HEIGHT > 0
  3106. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3107. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3108. line_to_current_position();
  3109. #endif
  3110. feedrate_mm_s = MMM_TO_MMS(XY_PROBE_SPEED);
  3111. current_position[X_AXIS] = LOGICAL_X_POSITION(x);
  3112. current_position[Y_AXIS] = LOGICAL_Y_POSITION(y);
  3113. line_to_current_position();
  3114. #if MANUAL_PROBE_HEIGHT > 0
  3115. feedrate_mm_s = homing_feedrate_mm_s[Z_AXIS];
  3116. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + 0.2; // just slightly over the bed
  3117. line_to_current_position();
  3118. #endif
  3119. feedrate_mm_s = old_feedrate_mm_s;
  3120. stepper.synchronize();
  3121. }
  3122. // Save 130 bytes with non-duplication of PSTR
  3123. void say_not_entered() { SERIAL_PROTOCOLLNPGM(" not entered."); }
  3124. void mbl_mesh_report() {
  3125. SERIAL_PROTOCOLLNPGM("Num X,Y: " STRINGIFY(MESH_NUM_X_POINTS) "," STRINGIFY(MESH_NUM_Y_POINTS));
  3126. SERIAL_PROTOCOLPGM("Z offset: "); SERIAL_PROTOCOL_F(mbl.z_offset, 5);
  3127. SERIAL_PROTOCOLLNPGM("\nMeasured points:");
  3128. for (uint8_t py = 0; py < MESH_NUM_Y_POINTS; py++) {
  3129. for (uint8_t px = 0; px < MESH_NUM_X_POINTS; px++) {
  3130. SERIAL_PROTOCOLPGM(" ");
  3131. SERIAL_PROTOCOL_F(mbl.z_values[py][px], 5);
  3132. }
  3133. SERIAL_EOL;
  3134. }
  3135. }
  3136. /**
  3137. * G29: Mesh-based Z probe, probes a grid and produces a
  3138. * mesh to compensate for variable bed height
  3139. *
  3140. * Parameters With MESH_BED_LEVELING:
  3141. *
  3142. * S0 Produce a mesh report
  3143. * S1 Start probing mesh points
  3144. * S2 Probe the next mesh point
  3145. * S3 Xn Yn Zn.nn Manually modify a single point
  3146. * S4 Zn.nn Set z offset. Positive away from bed, negative closer to bed.
  3147. * S5 Reset and disable mesh
  3148. *
  3149. * The S0 report the points as below
  3150. *
  3151. * +----> X-axis 1-n
  3152. * |
  3153. * |
  3154. * v Y-axis 1-n
  3155. *
  3156. */
  3157. inline void gcode_G29() {
  3158. static int probe_index = -1;
  3159. #if HAS_SOFTWARE_ENDSTOPS
  3160. static bool enable_soft_endstops;
  3161. #endif
  3162. const MeshLevelingState state = code_seen('S') ? (MeshLevelingState)code_value_byte() : MeshReport;
  3163. if (state < 0 || state > 5) {
  3164. SERIAL_PROTOCOLLNPGM("S out of range (0-5).");
  3165. return;
  3166. }
  3167. int8_t px, py;
  3168. switch (state) {
  3169. case MeshReport:
  3170. if (mbl.has_mesh()) {
  3171. SERIAL_PROTOCOLLNPAIR("State: ", mbl.active() ? MSG_ON : MSG_OFF);
  3172. mbl_mesh_report();
  3173. }
  3174. else
  3175. SERIAL_PROTOCOLLNPGM("Mesh bed leveling has no data.");
  3176. break;
  3177. case MeshStart:
  3178. mbl.reset();
  3179. probe_index = 0;
  3180. enqueue_and_echo_commands_P(PSTR("G28\nG29 S2"));
  3181. break;
  3182. case MeshNext:
  3183. if (probe_index < 0) {
  3184. SERIAL_PROTOCOLLNPGM("Start mesh probing with \"G29 S1\" first.");
  3185. return;
  3186. }
  3187. // For each G29 S2...
  3188. if (probe_index == 0) {
  3189. #if HAS_SOFTWARE_ENDSTOPS
  3190. // For the initial G29 S2 save software endstop state
  3191. enable_soft_endstops = soft_endstops_enabled;
  3192. #endif
  3193. }
  3194. else {
  3195. // For G29 S2 after adjusting Z.
  3196. mbl.set_zigzag_z(probe_index - 1, current_position[Z_AXIS]);
  3197. #if HAS_SOFTWARE_ENDSTOPS
  3198. soft_endstops_enabled = enable_soft_endstops;
  3199. #endif
  3200. }
  3201. // If there's another point to sample, move there with optional lift.
  3202. if (probe_index < (MESH_NUM_X_POINTS) * (MESH_NUM_Y_POINTS)) {
  3203. mbl.zigzag(probe_index, px, py);
  3204. _mbl_goto_xy(mbl.get_probe_x(px), mbl.get_probe_y(py));
  3205. #if HAS_SOFTWARE_ENDSTOPS
  3206. // Disable software endstops to allow manual adjustment
  3207. // If G29 is not completed, they will not be re-enabled
  3208. soft_endstops_enabled = false;
  3209. #endif
  3210. probe_index++;
  3211. }
  3212. else {
  3213. // One last "return to the bed" (as originally coded) at completion
  3214. current_position[Z_AXIS] = LOGICAL_Z_POSITION(Z_MIN_POS) + MANUAL_PROBE_HEIGHT;
  3215. line_to_current_position();
  3216. stepper.synchronize();
  3217. // After recording the last point, activate the mbl and home
  3218. SERIAL_PROTOCOLLNPGM("Mesh probing done.");
  3219. probe_index = -1;
  3220. mbl.set_has_mesh(true);
  3221. mbl.set_reactivate(true);
  3222. enqueue_and_echo_commands_P(PSTR("G28"));
  3223. #if HAS_BUZZER
  3224. lcd_buzz(200, 659);
  3225. lcd_buzz(200, 698);
  3226. #endif
  3227. }
  3228. break;
  3229. case MeshSet:
  3230. if (code_seen('X')) {
  3231. px = code_value_int() - 1;
  3232. if (px < 0 || px >= MESH_NUM_X_POINTS) {
  3233. SERIAL_PROTOCOLLNPGM("X out of range (1-" STRINGIFY(MESH_NUM_X_POINTS) ").");
  3234. return;
  3235. }
  3236. }
  3237. else {
  3238. SERIAL_CHAR('X'); say_not_entered();
  3239. return;
  3240. }
  3241. if (code_seen('Y')) {
  3242. py = code_value_int() - 1;
  3243. if (py < 0 || py >= MESH_NUM_Y_POINTS) {
  3244. SERIAL_PROTOCOLLNPGM("Y out of range (1-" STRINGIFY(MESH_NUM_Y_POINTS) ").");
  3245. return;
  3246. }
  3247. }
  3248. else {
  3249. SERIAL_CHAR('Y'); say_not_entered();
  3250. return;
  3251. }
  3252. if (code_seen('Z')) {
  3253. mbl.z_values[py][px] = code_value_axis_units(Z_AXIS);
  3254. }
  3255. else {
  3256. SERIAL_CHAR('Z'); say_not_entered();
  3257. return;
  3258. }
  3259. break;
  3260. case MeshSetZOffset:
  3261. if (code_seen('Z')) {
  3262. mbl.z_offset = code_value_axis_units(Z_AXIS);
  3263. }
  3264. else {
  3265. SERIAL_CHAR('Z'); say_not_entered();
  3266. return;
  3267. }
  3268. break;
  3269. case MeshReset:
  3270. reset_bed_level();
  3271. break;
  3272. } // switch(state)
  3273. report_current_position();
  3274. }
  3275. #elif HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3276. /**
  3277. * G29: Detailed Z probe, probes the bed at 3 or more points.
  3278. * Will fail if the printer has not been homed with G28.
  3279. *
  3280. * Enhanced G29 Auto Bed Leveling Probe Routine
  3281. *
  3282. * Parameters With LINEAR and BILINEAR:
  3283. *
  3284. * P Set the size of the grid that will be probed (P x P points).
  3285. * Not supported by non-linear delta printer bed leveling.
  3286. * Example: "G29 P4"
  3287. *
  3288. * S Set the XY travel speed between probe points (in units/min)
  3289. *
  3290. * D Dry-Run mode. Just evaluate the bed Topology - Don't apply
  3291. * or clean the rotation Matrix. Useful to check the topology
  3292. * after a first run of G29.
  3293. *
  3294. * V Set the verbose level (0-4). Example: "G29 V3"
  3295. *
  3296. * T Generate a Bed Topology Report. Example: "G29 P5 T" for a detailed report.
  3297. * This is useful for manual bed leveling and finding flaws in the bed (to
  3298. * assist with part placement).
  3299. * Not supported by non-linear delta printer bed leveling.
  3300. *
  3301. * F Set the Front limit of the probing grid
  3302. * B Set the Back limit of the probing grid
  3303. * L Set the Left limit of the probing grid
  3304. * R Set the Right limit of the probing grid
  3305. *
  3306. * Parameters with BILINEAR only:
  3307. *
  3308. * Z Supply an additional Z probe offset
  3309. *
  3310. * Global Parameters:
  3311. *
  3312. * E/e By default G29 will engage the Z probe, test the bed, then disengage.
  3313. * Include "E" to engage/disengage the Z probe for each sample.
  3314. * There's no extra effect if you have a fixed Z probe.
  3315. * Usage: "G29 E" or "G29 e"
  3316. *
  3317. */
  3318. inline void gcode_G29() {
  3319. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3320. const bool query = code_seen('Q');
  3321. const uint8_t old_debug_flags = marlin_debug_flags;
  3322. if (query) marlin_debug_flags |= DEBUG_LEVELING;
  3323. if (DEBUGGING(LEVELING)) {
  3324. DEBUG_POS(">>> gcode_G29", current_position);
  3325. log_machine_info();
  3326. }
  3327. marlin_debug_flags = old_debug_flags;
  3328. if (query) return;
  3329. #endif
  3330. // Don't allow auto-leveling without homing first
  3331. if (axis_unhomed_error(true, true, true)) return;
  3332. const int verbose_level = code_seen('V') ? code_value_int() : 1;
  3333. if (verbose_level < 0 || verbose_level > 4) {
  3334. SERIAL_PROTOCOLLNPGM("?(V)erbose Level is implausible (0-4).");
  3335. return;
  3336. }
  3337. bool dryrun = code_seen('D'),
  3338. stow_probe_after_each = code_seen('E');
  3339. #if ABL_GRID
  3340. if (verbose_level > 0) {
  3341. SERIAL_PROTOCOLLNPGM("G29 Auto Bed Leveling");
  3342. if (dryrun) SERIAL_PROTOCOLLNPGM("Running in DRY-RUN mode");
  3343. }
  3344. #if ABL_PLANAR
  3345. bool do_topography_map = verbose_level > 2 || code_seen('T');
  3346. // X and Y specify points in each direction, overriding the default
  3347. // These values may be saved with the completed mesh
  3348. int abl_grid_points_x = code_seen('X') ? code_value_int() : ABL_GRID_MAX_POINTS_X,
  3349. abl_grid_points_y = code_seen('Y') ? code_value_int() : ABL_GRID_MAX_POINTS_Y;
  3350. if (code_seen('P')) abl_grid_points_x = abl_grid_points_y = code_value_int();
  3351. if (abl_grid_points_x < 2 || abl_grid_points_y < 2) {
  3352. SERIAL_PROTOCOLLNPGM("?Number of probe points is implausible (2 minimum).");
  3353. return;
  3354. }
  3355. #else
  3356. const uint8_t abl_grid_points_x = ABL_GRID_MAX_POINTS_X, abl_grid_points_y = ABL_GRID_MAX_POINTS_Y;
  3357. #endif
  3358. xy_probe_feedrate_mm_s = MMM_TO_MMS(code_seen('S') ? code_value_linear_units() : XY_PROBE_SPEED);
  3359. int left_probe_bed_position = code_seen('L') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(LEFT_PROBE_BED_POSITION),
  3360. right_probe_bed_position = code_seen('R') ? (int)code_value_axis_units(X_AXIS) : LOGICAL_X_POSITION(RIGHT_PROBE_BED_POSITION),
  3361. front_probe_bed_position = code_seen('F') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(FRONT_PROBE_BED_POSITION),
  3362. back_probe_bed_position = code_seen('B') ? (int)code_value_axis_units(Y_AXIS) : LOGICAL_Y_POSITION(BACK_PROBE_BED_POSITION);
  3363. const bool left_out_l = left_probe_bed_position < LOGICAL_X_POSITION(MIN_PROBE_X),
  3364. left_out = left_out_l || left_probe_bed_position > right_probe_bed_position - (MIN_PROBE_EDGE),
  3365. right_out_r = right_probe_bed_position > LOGICAL_X_POSITION(MAX_PROBE_X),
  3366. right_out = right_out_r || right_probe_bed_position < left_probe_bed_position + MIN_PROBE_EDGE,
  3367. front_out_f = front_probe_bed_position < LOGICAL_Y_POSITION(MIN_PROBE_Y),
  3368. front_out = front_out_f || front_probe_bed_position > back_probe_bed_position - (MIN_PROBE_EDGE),
  3369. back_out_b = back_probe_bed_position > LOGICAL_Y_POSITION(MAX_PROBE_Y),
  3370. back_out = back_out_b || back_probe_bed_position < front_probe_bed_position + MIN_PROBE_EDGE;
  3371. if (left_out || right_out || front_out || back_out) {
  3372. if (left_out) {
  3373. out_of_range_error(PSTR("(L)eft"));
  3374. left_probe_bed_position = left_out_l ? LOGICAL_X_POSITION(MIN_PROBE_X) : right_probe_bed_position - (MIN_PROBE_EDGE);
  3375. }
  3376. if (right_out) {
  3377. out_of_range_error(PSTR("(R)ight"));
  3378. right_probe_bed_position = right_out_r ? LOGICAL_Y_POSITION(MAX_PROBE_X) : left_probe_bed_position + MIN_PROBE_EDGE;
  3379. }
  3380. if (front_out) {
  3381. out_of_range_error(PSTR("(F)ront"));
  3382. front_probe_bed_position = front_out_f ? LOGICAL_Y_POSITION(MIN_PROBE_Y) : back_probe_bed_position - (MIN_PROBE_EDGE);
  3383. }
  3384. if (back_out) {
  3385. out_of_range_error(PSTR("(B)ack"));
  3386. back_probe_bed_position = back_out_b ? LOGICAL_Y_POSITION(MAX_PROBE_Y) : front_probe_bed_position + MIN_PROBE_EDGE;
  3387. }
  3388. return;
  3389. }
  3390. #endif // ABL_GRID
  3391. stepper.synchronize();
  3392. // Disable auto bed leveling during G29
  3393. bool abl_should_enable = planner.abl_enabled;
  3394. planner.abl_enabled = false;
  3395. if (!dryrun) {
  3396. // Re-orient the current position without leveling
  3397. // based on where the steppers are positioned.
  3398. set_current_from_steppers_for_axis(ALL_AXES);
  3399. // Sync the planner to where the steppers stopped
  3400. SYNC_PLAN_POSITION_KINEMATIC();
  3401. }
  3402. setup_for_endstop_or_probe_move();
  3403. // Deploy the probe. Probe will raise if needed.
  3404. if (DEPLOY_PROBE()) {
  3405. planner.abl_enabled = abl_should_enable;
  3406. return;
  3407. }
  3408. float xProbe = 0, yProbe = 0, measured_z = 0;
  3409. #if ABL_GRID
  3410. // probe at the points of a lattice grid
  3411. const float xGridSpacing = (right_probe_bed_position - left_probe_bed_position) / (abl_grid_points_x - 1),
  3412. yGridSpacing = (back_probe_bed_position - front_probe_bed_position) / (abl_grid_points_y - 1);
  3413. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3414. float zoffset = zprobe_zoffset;
  3415. if (code_seen('Z')) zoffset += code_value_axis_units(Z_AXIS);
  3416. if ( xGridSpacing != bilinear_grid_spacing[X_AXIS]
  3417. || yGridSpacing != bilinear_grid_spacing[Y_AXIS]
  3418. || left_probe_bed_position != bilinear_start[X_AXIS]
  3419. || front_probe_bed_position != bilinear_start[Y_AXIS]
  3420. ) {
  3421. if (dryrun) {
  3422. // Before reset bed level, re-enable to correct the position
  3423. planner.abl_enabled = abl_should_enable;
  3424. }
  3425. // Reset grid to 0.0 or "not probed". (Also disables ABL)
  3426. reset_bed_level();
  3427. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3428. bilinear_grid_spacing_virt[X_AXIS] = xGridSpacing / (BILINEAR_SUBDIVISIONS);
  3429. bilinear_grid_spacing_virt[Y_AXIS] = yGridSpacing / (BILINEAR_SUBDIVISIONS);
  3430. #endif
  3431. bilinear_grid_spacing[X_AXIS] = xGridSpacing;
  3432. bilinear_grid_spacing[Y_AXIS] = yGridSpacing;
  3433. bilinear_start[X_AXIS] = RAW_X_POSITION(left_probe_bed_position);
  3434. bilinear_start[Y_AXIS] = RAW_Y_POSITION(front_probe_bed_position);
  3435. // Can't re-enable (on error) until the new grid is written
  3436. abl_should_enable = false;
  3437. }
  3438. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3439. /**
  3440. * solve the plane equation ax + by + d = z
  3441. * A is the matrix with rows [x y 1] for all the probed points
  3442. * B is the vector of the Z positions
  3443. * the normal vector to the plane is formed by the coefficients of the
  3444. * plane equation in the standard form, which is Vx*x+Vy*y+Vz*z+d = 0
  3445. * so Vx = -a Vy = -b Vz = 1 (we want the vector facing towards positive Z
  3446. */
  3447. const int abl2 = abl_grid_points_x * abl_grid_points_y;
  3448. int indexIntoAB[abl_grid_points_x][abl_grid_points_y],
  3449. probe_index = -1;
  3450. float eqnAMatrix[abl2 * 3], // "A" matrix of the linear system of equations
  3451. eqnBVector[abl2], // "B" vector of Z points
  3452. mean = 0.0;
  3453. #endif // AUTO_BED_LEVELING_LINEAR
  3454. #if ENABLED(PROBE_Y_FIRST)
  3455. #define PR_OUTER_VAR xCount
  3456. #define PR_OUTER_NUM abl_grid_points_x
  3457. #define PR_INNER_VAR yCount
  3458. #define PR_INNER_NUM abl_grid_points_y
  3459. #else
  3460. #define PR_OUTER_VAR yCount
  3461. #define PR_OUTER_NUM abl_grid_points_y
  3462. #define PR_INNER_VAR xCount
  3463. #define PR_INNER_NUM abl_grid_points_x
  3464. #endif
  3465. bool zig = PR_OUTER_NUM & 1; // Always end at RIGHT and BACK_PROBE_BED_POSITION
  3466. // Outer loop is Y with PROBE_Y_FIRST disabled
  3467. for (uint8_t PR_OUTER_VAR = 0; PR_OUTER_VAR < PR_OUTER_NUM; PR_OUTER_VAR++) {
  3468. int8_t inStart, inStop, inInc;
  3469. if (zig) { // away from origin
  3470. inStart = 0;
  3471. inStop = PR_INNER_NUM;
  3472. inInc = 1;
  3473. }
  3474. else { // towards origin
  3475. inStart = PR_INNER_NUM - 1;
  3476. inStop = -1;
  3477. inInc = -1;
  3478. }
  3479. zig = !zig; // zag
  3480. // Inner loop is Y with PROBE_Y_FIRST enabled
  3481. for (int8_t PR_INNER_VAR = inStart; PR_INNER_VAR != inStop; PR_INNER_VAR += inInc) {
  3482. float xBase = left_probe_bed_position + xGridSpacing * xCount,
  3483. yBase = front_probe_bed_position + yGridSpacing * yCount;
  3484. xProbe = floor(xBase + (xBase < 0 ? 0 : 0.5));
  3485. yProbe = floor(yBase + (yBase < 0 ? 0 : 0.5));
  3486. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3487. indexIntoAB[xCount][yCount] = ++probe_index;
  3488. #endif
  3489. #if IS_KINEMATIC
  3490. // Avoid probing outside the round or hexagonal area
  3491. float pos[XYZ] = { xProbe, yProbe, 0 };
  3492. if (!position_is_reachable(pos, true)) continue;
  3493. #endif
  3494. measured_z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3495. if (measured_z == NAN) {
  3496. planner.abl_enabled = abl_should_enable;
  3497. return;
  3498. }
  3499. #if ENABLED(AUTO_BED_LEVELING_LINEAR)
  3500. mean += measured_z;
  3501. eqnBVector[probe_index] = measured_z;
  3502. eqnAMatrix[probe_index + 0 * abl2] = xProbe;
  3503. eqnAMatrix[probe_index + 1 * abl2] = yProbe;
  3504. eqnAMatrix[probe_index + 2 * abl2] = 1;
  3505. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3506. bed_level_grid[xCount][yCount] = measured_z + zoffset;
  3507. #endif
  3508. idle();
  3509. } // inner
  3510. } // outer
  3511. #elif ENABLED(AUTO_BED_LEVELING_3POINT)
  3512. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3513. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("> 3-point Leveling");
  3514. #endif
  3515. // Probe at 3 arbitrary points
  3516. vector_3 points[3] = {
  3517. vector_3(ABL_PROBE_PT_1_X, ABL_PROBE_PT_1_Y, 0),
  3518. vector_3(ABL_PROBE_PT_2_X, ABL_PROBE_PT_2_Y, 0),
  3519. vector_3(ABL_PROBE_PT_3_X, ABL_PROBE_PT_3_Y, 0)
  3520. };
  3521. for (uint8_t i = 0; i < 3; ++i) {
  3522. // Retain the last probe position
  3523. xProbe = LOGICAL_X_POSITION(points[i].x);
  3524. yProbe = LOGICAL_Y_POSITION(points[i].y);
  3525. measured_z = points[i].z = probe_pt(xProbe, yProbe, stow_probe_after_each, verbose_level);
  3526. }
  3527. if (measured_z == NAN) {
  3528. planner.abl_enabled = abl_should_enable;
  3529. return;
  3530. }
  3531. if (!dryrun) {
  3532. vector_3 planeNormal = vector_3::cross(points[0] - points[1], points[2] - points[1]).get_normal();
  3533. if (planeNormal.z < 0) {
  3534. planeNormal.x *= -1;
  3535. planeNormal.y *= -1;
  3536. planeNormal.z *= -1;
  3537. }
  3538. planner.bed_level_matrix = matrix_3x3::create_look_at(planeNormal);
  3539. // Can't re-enable (on error) until the new grid is written
  3540. abl_should_enable = false;
  3541. }
  3542. #endif // AUTO_BED_LEVELING_3POINT
  3543. // Raise to _Z_CLEARANCE_DEPLOY_PROBE. Stow the probe.
  3544. if (STOW_PROBE()) {
  3545. planner.abl_enabled = abl_should_enable;
  3546. return;
  3547. }
  3548. //
  3549. // Unless this is a dry run, auto bed leveling will
  3550. // definitely be enabled after this point
  3551. //
  3552. // Restore state after probing
  3553. clean_up_after_endstop_or_probe_move();
  3554. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3555. if (DEBUGGING(LEVELING)) DEBUG_POS("> probing complete", current_position);
  3556. #endif
  3557. // Calculate leveling, print reports, correct the position
  3558. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3559. if (!dryrun) extrapolate_unprobed_bed_level();
  3560. print_bilinear_leveling_grid();
  3561. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  3562. bed_level_virt_interpolate();
  3563. bed_level_virt_print();
  3564. #endif
  3565. #elif ENABLED(AUTO_BED_LEVELING_LINEAR)
  3566. // For LINEAR leveling calculate matrix, print reports, correct the position
  3567. // solve lsq problem
  3568. float plane_equation_coefficients[3];
  3569. qr_solve(plane_equation_coefficients, abl2, 3, eqnAMatrix, eqnBVector);
  3570. mean /= abl2;
  3571. if (verbose_level) {
  3572. SERIAL_PROTOCOLPGM("Eqn coefficients: a: ");
  3573. SERIAL_PROTOCOL_F(plane_equation_coefficients[0], 8);
  3574. SERIAL_PROTOCOLPGM(" b: ");
  3575. SERIAL_PROTOCOL_F(plane_equation_coefficients[1], 8);
  3576. SERIAL_PROTOCOLPGM(" d: ");
  3577. SERIAL_PROTOCOL_F(plane_equation_coefficients[2], 8);
  3578. SERIAL_EOL;
  3579. if (verbose_level > 2) {
  3580. SERIAL_PROTOCOLPGM("Mean of sampled points: ");
  3581. SERIAL_PROTOCOL_F(mean, 8);
  3582. SERIAL_EOL;
  3583. }
  3584. }
  3585. // Create the matrix but don't correct the position yet
  3586. if (!dryrun) {
  3587. planner.bed_level_matrix = matrix_3x3::create_look_at(
  3588. vector_3(-plane_equation_coefficients[0], -plane_equation_coefficients[1], 1)
  3589. );
  3590. }
  3591. // Show the Topography map if enabled
  3592. if (do_topography_map) {
  3593. SERIAL_PROTOCOLLNPGM("\nBed Height Topography:\n"
  3594. " +--- BACK --+\n"
  3595. " | |\n"
  3596. " L | (+) | R\n"
  3597. " E | | I\n"
  3598. " F | (-) N (+) | G\n"
  3599. " T | | H\n"
  3600. " | (-) | T\n"
  3601. " | |\n"
  3602. " O-- FRONT --+\n"
  3603. " (0,0)");
  3604. float min_diff = 999;
  3605. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  3606. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  3607. int ind = indexIntoAB[xx][yy];
  3608. float diff = eqnBVector[ind] - mean,
  3609. x_tmp = eqnAMatrix[ind + 0 * abl2],
  3610. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3611. z_tmp = 0;
  3612. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3613. NOMORE(min_diff, eqnBVector[ind] - z_tmp);
  3614. if (diff >= 0.0)
  3615. SERIAL_PROTOCOLPGM(" +"); // Include + for column alignment
  3616. else
  3617. SERIAL_PROTOCOLCHAR(' ');
  3618. SERIAL_PROTOCOL_F(diff, 5);
  3619. } // xx
  3620. SERIAL_EOL;
  3621. } // yy
  3622. SERIAL_EOL;
  3623. if (verbose_level > 3) {
  3624. SERIAL_PROTOCOLLNPGM("\nCorrected Bed Height vs. Bed Topology:");
  3625. for (int8_t yy = abl_grid_points_y - 1; yy >= 0; yy--) {
  3626. for (uint8_t xx = 0; xx < abl_grid_points_x; xx++) {
  3627. int ind = indexIntoAB[xx][yy];
  3628. float x_tmp = eqnAMatrix[ind + 0 * abl2],
  3629. y_tmp = eqnAMatrix[ind + 1 * abl2],
  3630. z_tmp = 0;
  3631. apply_rotation_xyz(planner.bed_level_matrix, x_tmp, y_tmp, z_tmp);
  3632. float diff = eqnBVector[ind] - z_tmp - min_diff;
  3633. if (diff >= 0.0)
  3634. SERIAL_PROTOCOLPGM(" +");
  3635. // Include + for column alignment
  3636. else
  3637. SERIAL_PROTOCOLCHAR(' ');
  3638. SERIAL_PROTOCOL_F(diff, 5);
  3639. } // xx
  3640. SERIAL_EOL;
  3641. } // yy
  3642. SERIAL_EOL;
  3643. }
  3644. } //do_topography_map
  3645. #endif // AUTO_BED_LEVELING_LINEAR
  3646. #if ABL_PLANAR
  3647. // For LINEAR and 3POINT leveling correct the current position
  3648. if (verbose_level > 0)
  3649. planner.bed_level_matrix.debug("\n\nBed Level Correction Matrix:");
  3650. if (!dryrun) {
  3651. //
  3652. // Correct the current XYZ position based on the tilted plane.
  3653. //
  3654. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3655. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 uncorrected XYZ", current_position);
  3656. #endif
  3657. float converted[XYZ];
  3658. COPY(converted, current_position);
  3659. planner.abl_enabled = true;
  3660. planner.unapply_leveling(converted); // use conversion machinery
  3661. planner.abl_enabled = false;
  3662. // Use the last measured distance to the bed, if possible
  3663. if ( NEAR(current_position[X_AXIS], xProbe - (X_PROBE_OFFSET_FROM_EXTRUDER))
  3664. && NEAR(current_position[Y_AXIS], yProbe - (Y_PROBE_OFFSET_FROM_EXTRUDER))
  3665. ) {
  3666. float simple_z = current_position[Z_AXIS] - (measured_z - (-zprobe_zoffset));
  3667. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3668. if (DEBUGGING(LEVELING)) {
  3669. SERIAL_ECHOPAIR("Z from Probe:", simple_z);
  3670. SERIAL_ECHOPAIR(" Matrix:", converted[Z_AXIS]);
  3671. SERIAL_ECHOLNPAIR(" Discrepancy:", simple_z - converted[Z_AXIS]);
  3672. }
  3673. #endif
  3674. converted[Z_AXIS] = simple_z;
  3675. }
  3676. // The rotated XY and corrected Z are now current_position
  3677. COPY(current_position, converted);
  3678. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3679. if (DEBUGGING(LEVELING)) DEBUG_POS("G29 corrected XYZ", current_position);
  3680. #endif
  3681. }
  3682. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  3683. if (!dryrun) {
  3684. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3685. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("G29 uncorrected Z:", current_position[Z_AXIS]);
  3686. #endif
  3687. // Unapply the offset because it is going to be immediately applied
  3688. // and cause compensation movement in Z
  3689. current_position[Z_AXIS] -= bilinear_z_offset(current_position);
  3690. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3691. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR(" corrected Z:", current_position[Z_AXIS]);
  3692. #endif
  3693. }
  3694. #endif // ABL_PLANAR
  3695. #ifdef Z_PROBE_END_SCRIPT
  3696. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3697. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPAIR("Z Probe End Script: ", Z_PROBE_END_SCRIPT);
  3698. #endif
  3699. enqueue_and_echo_commands_P(PSTR(Z_PROBE_END_SCRIPT));
  3700. stepper.synchronize();
  3701. #endif
  3702. #if ENABLED(DEBUG_LEVELING_FEATURE)
  3703. if (DEBUGGING(LEVELING)) SERIAL_ECHOLNPGM("<<< gcode_G29");
  3704. #endif
  3705. report_current_position();
  3706. KEEPALIVE_STATE(IN_HANDLER);
  3707. // Auto Bed Leveling is complete! Enable if possible.
  3708. planner.abl_enabled = dryrun ? abl_should_enable : true;
  3709. if (planner.abl_enabled)
  3710. SYNC_PLAN_POSITION_KINEMATIC();
  3711. }
  3712. #endif // HAS_ABL && DISABLED(AUTO_BED_LEVELING_UBL)
  3713. #if HAS_BED_PROBE
  3714. /**
  3715. * G30: Do a single Z probe at the current XY
  3716. * Usage:
  3717. * G30 <X#> <Y#> <S#>
  3718. * X = Probe X position (default=current probe position)
  3719. * Y = Probe Y position (default=current probe position)
  3720. * S = Stows the probe if 1 (default=1)
  3721. */
  3722. inline void gcode_G30() {
  3723. float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : current_position[X_AXIS] + X_PROBE_OFFSET_FROM_EXTRUDER,
  3724. Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : current_position[Y_AXIS] + Y_PROBE_OFFSET_FROM_EXTRUDER;
  3725. float pos[XYZ] = { X_probe_location, Y_probe_location, LOGICAL_Z_POSITION(0) };
  3726. if (!position_is_reachable(pos, true)) return;
  3727. bool stow = code_seen('S') ? code_value_bool() : true;
  3728. // Disable leveling so the planner won't mess with us
  3729. #if PLANNER_LEVELING
  3730. set_bed_leveling_enabled(false);
  3731. #endif
  3732. setup_for_endstop_or_probe_move();
  3733. float measured_z = probe_pt(X_probe_location, Y_probe_location, stow, 1);
  3734. SERIAL_PROTOCOLPGM("Bed X: ");
  3735. SERIAL_PROTOCOL(X_probe_location + 0.0001);
  3736. SERIAL_PROTOCOLPGM(" Y: ");
  3737. SERIAL_PROTOCOL(Y_probe_location + 0.0001);
  3738. SERIAL_PROTOCOLPGM(" Z: ");
  3739. SERIAL_PROTOCOLLN(measured_z - -zprobe_zoffset + 0.0001);
  3740. clean_up_after_endstop_or_probe_move();
  3741. report_current_position();
  3742. }
  3743. #if ENABLED(Z_PROBE_SLED)
  3744. /**
  3745. * G31: Deploy the Z probe
  3746. */
  3747. inline void gcode_G31() { DEPLOY_PROBE(); }
  3748. /**
  3749. * G32: Stow the Z probe
  3750. */
  3751. inline void gcode_G32() { STOW_PROBE(); }
  3752. #endif // Z_PROBE_SLED
  3753. #endif // HAS_BED_PROBE
  3754. #if ENABLED(G38_PROBE_TARGET)
  3755. static bool G38_run_probe() {
  3756. bool G38_pass_fail = false;
  3757. // Get direction of move and retract
  3758. float retract_mm[XYZ];
  3759. LOOP_XYZ(i) {
  3760. float dist = destination[i] - current_position[i];
  3761. retract_mm[i] = fabs(dist) < G38_MINIMUM_MOVE ? 0 : home_bump_mm((AxisEnum)i) * (dist > 0 ? -1 : 1);
  3762. }
  3763. stepper.synchronize(); // wait until the machine is idle
  3764. // Move until destination reached or target hit
  3765. endstops.enable(true);
  3766. G38_move = true;
  3767. G38_endstop_hit = false;
  3768. prepare_move_to_destination();
  3769. stepper.synchronize();
  3770. G38_move = false;
  3771. endstops.hit_on_purpose();
  3772. set_current_from_steppers_for_axis(ALL_AXES);
  3773. SYNC_PLAN_POSITION_KINEMATIC();
  3774. // Only do remaining moves if target was hit
  3775. if (G38_endstop_hit) {
  3776. G38_pass_fail = true;
  3777. // Move away by the retract distance
  3778. set_destination_to_current();
  3779. LOOP_XYZ(i) destination[i] += retract_mm[i];
  3780. endstops.enable(false);
  3781. prepare_move_to_destination();
  3782. stepper.synchronize();
  3783. feedrate_mm_s /= 4;
  3784. // Bump the target more slowly
  3785. LOOP_XYZ(i) destination[i] -= retract_mm[i] * 2;
  3786. endstops.enable(true);
  3787. G38_move = true;
  3788. prepare_move_to_destination();
  3789. stepper.synchronize();
  3790. G38_move = false;
  3791. set_current_from_steppers_for_axis(ALL_AXES);
  3792. SYNC_PLAN_POSITION_KINEMATIC();
  3793. }
  3794. endstops.hit_on_purpose();
  3795. endstops.not_homing();
  3796. return G38_pass_fail;
  3797. }
  3798. /**
  3799. * G38.2 - probe toward workpiece, stop on contact, signal error if failure
  3800. * G38.3 - probe toward workpiece, stop on contact
  3801. *
  3802. * Like G28 except uses Z min endstop for all axes
  3803. */
  3804. inline void gcode_G38(bool is_38_2) {
  3805. // Get X Y Z E F
  3806. gcode_get_destination();
  3807. setup_for_endstop_or_probe_move();
  3808. // If any axis has enough movement, do the move
  3809. LOOP_XYZ(i)
  3810. if (fabs(destination[i] - current_position[i]) >= G38_MINIMUM_MOVE) {
  3811. if (!code_seen('F')) feedrate_mm_s = homing_feedrate_mm_s[i];
  3812. // If G38.2 fails throw an error
  3813. if (!G38_run_probe() && is_38_2) {
  3814. SERIAL_ERROR_START;
  3815. SERIAL_ERRORLNPGM("Failed to reach target");
  3816. }
  3817. break;
  3818. }
  3819. clean_up_after_endstop_or_probe_move();
  3820. }
  3821. #endif // G38_PROBE_TARGET
  3822. /**
  3823. * G92: Set current position to given X Y Z E
  3824. */
  3825. inline void gcode_G92() {
  3826. bool didXYZ = false,
  3827. didE = code_seen('E');
  3828. if (!didE) stepper.synchronize();
  3829. LOOP_XYZE(i) {
  3830. if (code_seen(axis_codes[i])) {
  3831. #if IS_SCARA
  3832. current_position[i] = code_value_axis_units(i);
  3833. if (i != E_AXIS) didXYZ = true;
  3834. #else
  3835. #if DISABLED(NO_WORKSPACE_OFFSETS)
  3836. float p = current_position[i];
  3837. #endif
  3838. float v = code_value_axis_units(i);
  3839. current_position[i] = v;
  3840. if (i != E_AXIS) {
  3841. didXYZ = true;
  3842. #if DISABLED(NO_WORKSPACE_OFFSETS)
  3843. position_shift[i] += v - p; // Offset the coordinate space
  3844. update_software_endstops((AxisEnum)i);
  3845. #endif
  3846. }
  3847. #endif
  3848. }
  3849. }
  3850. if (didXYZ)
  3851. SYNC_PLAN_POSITION_KINEMATIC();
  3852. else if (didE)
  3853. sync_plan_position_e();
  3854. report_current_position();
  3855. }
  3856. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  3857. /**
  3858. * M0: Unconditional stop - Wait for user button press on LCD
  3859. * M1: Conditional stop - Wait for user button press on LCD
  3860. */
  3861. inline void gcode_M0_M1() {
  3862. char* args = current_command_args;
  3863. millis_t codenum = 0;
  3864. bool hasP = false, hasS = false;
  3865. if (code_seen('P')) {
  3866. codenum = code_value_millis(); // milliseconds to wait
  3867. hasP = codenum > 0;
  3868. }
  3869. if (code_seen('S')) {
  3870. codenum = code_value_millis_from_seconds(); // seconds to wait
  3871. hasS = codenum > 0;
  3872. }
  3873. #if ENABLED(ULTIPANEL)
  3874. if (!hasP && !hasS && *args != '\0')
  3875. lcd_setstatus(args, true);
  3876. else {
  3877. LCD_MESSAGEPGM(MSG_USERWAIT);
  3878. #if ENABLED(LCD_PROGRESS_BAR) && PROGRESS_MSG_EXPIRE > 0
  3879. dontExpireStatus();
  3880. #endif
  3881. }
  3882. #else
  3883. if (!hasP && !hasS && *args != '\0') {
  3884. SERIAL_ECHO_START;
  3885. SERIAL_ECHOLN(args);
  3886. }
  3887. #endif
  3888. wait_for_user = true;
  3889. KEEPALIVE_STATE(PAUSED_FOR_USER);
  3890. stepper.synchronize();
  3891. refresh_cmd_timeout();
  3892. if (codenum > 0) {
  3893. codenum += previous_cmd_ms; // wait until this time for a click
  3894. while (PENDING(millis(), codenum) && wait_for_user) idle();
  3895. }
  3896. else {
  3897. #if ENABLED(ULTIPANEL)
  3898. if (lcd_detected()) {
  3899. while (wait_for_user) idle();
  3900. IS_SD_PRINTING ? LCD_MESSAGEPGM(MSG_RESUMING) : LCD_MESSAGEPGM(WELCOME_MSG);
  3901. }
  3902. #else
  3903. while (wait_for_user) idle();
  3904. #endif
  3905. }
  3906. wait_for_user = false;
  3907. KEEPALIVE_STATE(IN_HANDLER);
  3908. }
  3909. #endif // EMERGENCY_PARSER || ULTIPANEL
  3910. /**
  3911. * M17: Enable power on all stepper motors
  3912. */
  3913. inline void gcode_M17() {
  3914. LCD_MESSAGEPGM(MSG_NO_MOVE);
  3915. enable_all_steppers();
  3916. }
  3917. #if ENABLED(SDSUPPORT)
  3918. /**
  3919. * M20: List SD card to serial output
  3920. */
  3921. inline void gcode_M20() {
  3922. SERIAL_PROTOCOLLNPGM(MSG_BEGIN_FILE_LIST);
  3923. card.ls();
  3924. SERIAL_PROTOCOLLNPGM(MSG_END_FILE_LIST);
  3925. }
  3926. /**
  3927. * M21: Init SD Card
  3928. */
  3929. inline void gcode_M21() { card.initsd(); }
  3930. /**
  3931. * M22: Release SD Card
  3932. */
  3933. inline void gcode_M22() { card.release(); }
  3934. /**
  3935. * M23: Open a file
  3936. */
  3937. inline void gcode_M23() { card.openFile(current_command_args, true); }
  3938. /**
  3939. * M24: Start SD Print
  3940. */
  3941. inline void gcode_M24() {
  3942. card.startFileprint();
  3943. print_job_timer.start();
  3944. }
  3945. /**
  3946. * M25: Pause SD Print
  3947. */
  3948. inline void gcode_M25() { card.pauseSDPrint(); }
  3949. /**
  3950. * M26: Set SD Card file index
  3951. */
  3952. inline void gcode_M26() {
  3953. if (card.cardOK && code_seen('S'))
  3954. card.setIndex(code_value_long());
  3955. }
  3956. /**
  3957. * M27: Get SD Card status
  3958. */
  3959. inline void gcode_M27() { card.getStatus(); }
  3960. /**
  3961. * M28: Start SD Write
  3962. */
  3963. inline void gcode_M28() { card.openFile(current_command_args, false); }
  3964. /**
  3965. * M29: Stop SD Write
  3966. * Processed in write to file routine above
  3967. */
  3968. inline void gcode_M29() {
  3969. // card.saving = false;
  3970. }
  3971. /**
  3972. * M30 <filename>: Delete SD Card file
  3973. */
  3974. inline void gcode_M30() {
  3975. if (card.cardOK) {
  3976. card.closefile();
  3977. card.removeFile(current_command_args);
  3978. }
  3979. }
  3980. #endif // SDSUPPORT
  3981. /**
  3982. * M31: Get the time since the start of SD Print (or last M109)
  3983. */
  3984. inline void gcode_M31() {
  3985. char buffer[21];
  3986. duration_t elapsed = print_job_timer.duration();
  3987. elapsed.toString(buffer);
  3988. lcd_setstatus(buffer);
  3989. SERIAL_ECHO_START;
  3990. SERIAL_ECHOLNPAIR("Print time: ", buffer);
  3991. #if ENABLED(AUTOTEMP)
  3992. thermalManager.autotempShutdown();
  3993. #endif
  3994. }
  3995. #if ENABLED(SDSUPPORT)
  3996. /**
  3997. * M32: Select file and start SD Print
  3998. */
  3999. inline void gcode_M32() {
  4000. if (card.sdprinting)
  4001. stepper.synchronize();
  4002. char* namestartpos = strchr(current_command_args, '!'); // Find ! to indicate filename string start.
  4003. if (!namestartpos)
  4004. namestartpos = current_command_args; // Default name position, 4 letters after the M
  4005. else
  4006. namestartpos++; //to skip the '!'
  4007. bool call_procedure = code_seen('P') && (seen_pointer < namestartpos);
  4008. if (card.cardOK) {
  4009. card.openFile(namestartpos, true, call_procedure);
  4010. if (code_seen('S') && seen_pointer < namestartpos) // "S" (must occur _before_ the filename!)
  4011. card.setIndex(code_value_long());
  4012. card.startFileprint();
  4013. // Procedure calls count as normal print time.
  4014. if (!call_procedure) print_job_timer.start();
  4015. }
  4016. }
  4017. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  4018. /**
  4019. * M33: Get the long full path of a file or folder
  4020. *
  4021. * Parameters:
  4022. * <dospath> Case-insensitive DOS-style path to a file or folder
  4023. *
  4024. * Example:
  4025. * M33 miscel~1/armchair/armcha~1.gco
  4026. *
  4027. * Output:
  4028. * /Miscellaneous/Armchair/Armchair.gcode
  4029. */
  4030. inline void gcode_M33() {
  4031. card.printLongPath(current_command_args);
  4032. }
  4033. #endif
  4034. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  4035. /**
  4036. * M34: Set SD Card Sorting Options
  4037. */
  4038. inline void gcode_M34() {
  4039. if (code_seen('S')) card.setSortOn(code_value_bool());
  4040. if (code_seen('F')) {
  4041. int v = code_value_long();
  4042. card.setSortFolders(v < 0 ? -1 : v > 0 ? 1 : 0);
  4043. }
  4044. //if (code_seen('R')) card.setSortReverse(code_value_bool());
  4045. }
  4046. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  4047. /**
  4048. * M928: Start SD Write
  4049. */
  4050. inline void gcode_M928() {
  4051. card.openLogFile(current_command_args);
  4052. }
  4053. #endif // SDSUPPORT
  4054. /**
  4055. * Sensitive pin test for M42, M226
  4056. */
  4057. static bool pin_is_protected(uint8_t pin) {
  4058. static const int sensitive_pins[] = SENSITIVE_PINS;
  4059. for (uint8_t i = 0; i < COUNT(sensitive_pins); i++)
  4060. if (sensitive_pins[i] == pin) return true;
  4061. return false;
  4062. }
  4063. /**
  4064. * M42: Change pin status via GCode
  4065. *
  4066. * P<pin> Pin number (LED if omitted)
  4067. * S<byte> Pin status from 0 - 255
  4068. */
  4069. inline void gcode_M42() {
  4070. if (!code_seen('S')) return;
  4071. int pin_status = code_value_int();
  4072. if (pin_status < 0 || pin_status > 255) return;
  4073. int pin_number = code_seen('P') ? code_value_int() : LED_PIN;
  4074. if (pin_number < 0) return;
  4075. if (pin_is_protected(pin_number)) {
  4076. SERIAL_ERROR_START;
  4077. SERIAL_ERRORLNPGM(MSG_ERR_PROTECTED_PIN);
  4078. return;
  4079. }
  4080. pinMode(pin_number, OUTPUT);
  4081. digitalWrite(pin_number, pin_status);
  4082. analogWrite(pin_number, pin_status);
  4083. #if FAN_COUNT > 0
  4084. switch (pin_number) {
  4085. #if HAS_FAN0
  4086. case FAN_PIN: fanSpeeds[0] = pin_status; break;
  4087. #endif
  4088. #if HAS_FAN1
  4089. case FAN1_PIN: fanSpeeds[1] = pin_status; break;
  4090. #endif
  4091. #if HAS_FAN2
  4092. case FAN2_PIN: fanSpeeds[2] = pin_status; break;
  4093. #endif
  4094. }
  4095. #endif
  4096. }
  4097. #if ENABLED(PINS_DEBUGGING)
  4098. #include "pinsDebug.h"
  4099. /**
  4100. * M43: Pin report and debug
  4101. *
  4102. * E<bool> Enable / disable background endstop monitoring
  4103. * - Machine continues to operate
  4104. * - Reports changes to endstops
  4105. * - Toggles LED when an endstop changes
  4106. *
  4107. * or
  4108. *
  4109. * P<pin> Pin to read or watch. If omitted, read/watch all pins.
  4110. * W<bool> Watch pins -reporting changes- until reset, click, or M108.
  4111. * I<bool> Flag to ignore Marlin's pin protection.
  4112. *
  4113. */
  4114. inline void gcode_M43() {
  4115. // Enable or disable endstop monitoring
  4116. if (code_seen('E')) {
  4117. endstop_monitor_flag = code_value_bool();
  4118. SERIAL_PROTOCOLPGM("endstop monitor ");
  4119. SERIAL_PROTOCOL(endstop_monitor_flag ? "en" : "dis");
  4120. SERIAL_PROTOCOLLNPGM("abled");
  4121. return;
  4122. }
  4123. // Get the range of pins to test or watch
  4124. int first_pin = 0, last_pin = NUM_DIGITAL_PINS - 1;
  4125. if (code_seen('P')) {
  4126. first_pin = last_pin = code_value_byte();
  4127. if (first_pin > NUM_DIGITAL_PINS - 1) return;
  4128. }
  4129. bool ignore_protection = code_seen('I') ? code_value_bool() : false;
  4130. // Watch until click, M108, or reset
  4131. if (code_seen('W') && code_value_bool()) { // watch digital pins
  4132. byte pin_state[last_pin - first_pin + 1];
  4133. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  4134. if (pin_is_protected(pin) && !ignore_protection) continue;
  4135. pinMode(pin, INPUT_PULLUP);
  4136. // if (IS_ANALOG(pin))
  4137. // pin_state[pin - first_pin] = analogRead(pin - analogInputToDigitalPin(0)); // int16_t pin_state[...]
  4138. // else
  4139. pin_state[pin - first_pin] = digitalRead(pin);
  4140. }
  4141. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  4142. wait_for_user = true;
  4143. #endif
  4144. for(;;) {
  4145. for (int8_t pin = first_pin; pin <= last_pin; pin++) {
  4146. if (pin_is_protected(pin)) continue;
  4147. byte val;
  4148. // if (IS_ANALOG(pin))
  4149. // val = analogRead(pin - analogInputToDigitalPin(0)); // int16_t val
  4150. // else
  4151. val = digitalRead(pin);
  4152. if (val != pin_state[pin - first_pin]) {
  4153. report_pin_state(pin);
  4154. pin_state[pin - first_pin] = val;
  4155. }
  4156. }
  4157. #if ENABLED(EMERGENCY_PARSER) || ENABLED(ULTIPANEL)
  4158. if (!wait_for_user) break;
  4159. #endif
  4160. safe_delay(500);
  4161. }
  4162. return;
  4163. }
  4164. // Report current state of selected pin(s)
  4165. for (uint8_t pin = first_pin; pin <= last_pin; pin++)
  4166. report_pin_state_extended(pin, ignore_protection);
  4167. }
  4168. #endif // PINS_DEBUGGING
  4169. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  4170. /**
  4171. * M48: Z probe repeatability measurement function.
  4172. *
  4173. * Usage:
  4174. * M48 <P#> <X#> <Y#> <V#> <E> <L#>
  4175. * P = Number of sampled points (4-50, default 10)
  4176. * X = Sample X position
  4177. * Y = Sample Y position
  4178. * V = Verbose level (0-4, default=1)
  4179. * E = Engage Z probe for each reading
  4180. * L = Number of legs of movement before probe
  4181. * S = Schizoid (Or Star if you prefer)
  4182. *
  4183. * This function assumes the bed has been homed. Specifically, that a G28 command
  4184. * as been issued prior to invoking the M48 Z probe repeatability measurement function.
  4185. * Any information generated by a prior G29 Bed leveling command will be lost and need to be
  4186. * regenerated.
  4187. */
  4188. inline void gcode_M48() {
  4189. if (axis_unhomed_error(true, true, true)) return;
  4190. int8_t verbose_level = code_seen('V') ? code_value_byte() : 1;
  4191. if (verbose_level < 0 || verbose_level > 4) {
  4192. SERIAL_PROTOCOLLNPGM("?Verbose Level not plausible (0-4).");
  4193. return;
  4194. }
  4195. if (verbose_level > 0)
  4196. SERIAL_PROTOCOLLNPGM("M48 Z-Probe Repeatability Test");
  4197. int8_t n_samples = code_seen('P') ? code_value_byte() : 10;
  4198. if (n_samples < 4 || n_samples > 50) {
  4199. SERIAL_PROTOCOLLNPGM("?Sample size not plausible (4-50).");
  4200. return;
  4201. }
  4202. float X_current = current_position[X_AXIS],
  4203. Y_current = current_position[Y_AXIS];
  4204. bool stow_probe_after_each = code_seen('E');
  4205. float X_probe_location = code_seen('X') ? code_value_axis_units(X_AXIS) : X_current + X_PROBE_OFFSET_FROM_EXTRUDER;
  4206. #if DISABLED(DELTA)
  4207. if (X_probe_location < LOGICAL_X_POSITION(MIN_PROBE_X) || X_probe_location > LOGICAL_X_POSITION(MAX_PROBE_X)) {
  4208. out_of_range_error(PSTR("X"));
  4209. return;
  4210. }
  4211. #endif
  4212. float Y_probe_location = code_seen('Y') ? code_value_axis_units(Y_AXIS) : Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER;
  4213. #if DISABLED(DELTA)
  4214. if (Y_probe_location < LOGICAL_Y_POSITION(MIN_PROBE_Y) || Y_probe_location > LOGICAL_Y_POSITION(MAX_PROBE_Y)) {
  4215. out_of_range_error(PSTR("Y"));
  4216. return;
  4217. }
  4218. #else
  4219. float pos[XYZ] = { X_probe_location, Y_probe_location, 0 };
  4220. if (!position_is_reachable(pos, true)) {
  4221. SERIAL_PROTOCOLLNPGM("? (X,Y) location outside of probeable radius.");
  4222. return;
  4223. }
  4224. #endif
  4225. bool seen_L = code_seen('L');
  4226. uint8_t n_legs = seen_L ? code_value_byte() : 0;
  4227. if (n_legs > 15) {
  4228. SERIAL_PROTOCOLLNPGM("?Number of legs in movement not plausible (0-15).");
  4229. return;
  4230. }
  4231. if (n_legs == 1) n_legs = 2;
  4232. bool schizoid_flag = code_seen('S');
  4233. if (schizoid_flag && !seen_L) n_legs = 7;
  4234. /**
  4235. * Now get everything to the specified probe point So we can safely do a
  4236. * probe to get us close to the bed. If the Z-Axis is far from the bed,
  4237. * we don't want to use that as a starting point for each probe.
  4238. */
  4239. if (verbose_level > 2)
  4240. SERIAL_PROTOCOLLNPGM("Positioning the probe...");
  4241. // Disable bed level correction in M48 because we want the raw data when we probe
  4242. #if HAS_ABL
  4243. const bool abl_was_enabled = planner.abl_enabled;
  4244. set_bed_leveling_enabled(false);
  4245. #endif
  4246. setup_for_endstop_or_probe_move();
  4247. // Move to the first point, deploy, and probe
  4248. probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, verbose_level);
  4249. randomSeed(millis());
  4250. double mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];
  4251. for (uint8_t n = 0; n < n_samples; n++) {
  4252. if (n_legs) {
  4253. int dir = (random(0, 10) > 5.0) ? -1 : 1; // clockwise or counter clockwise
  4254. float angle = random(0.0, 360.0),
  4255. radius = random(
  4256. #if ENABLED(DELTA)
  4257. DELTA_PROBEABLE_RADIUS / 8, DELTA_PROBEABLE_RADIUS / 3
  4258. #else
  4259. 5, X_MAX_LENGTH / 8
  4260. #endif
  4261. );
  4262. if (verbose_level > 3) {
  4263. SERIAL_ECHOPAIR("Starting radius: ", radius);
  4264. SERIAL_ECHOPAIR(" angle: ", angle);
  4265. SERIAL_ECHOPGM(" Direction: ");
  4266. if (dir > 0) SERIAL_ECHOPGM("Counter-");
  4267. SERIAL_ECHOLNPGM("Clockwise");
  4268. }
  4269. for (uint8_t l = 0; l < n_legs - 1; l++) {
  4270. double delta_angle;
  4271. if (schizoid_flag)
  4272. // The points of a 5 point star are 72 degrees apart. We need to
  4273. // skip a point and go to the next one on the star.
  4274. delta_angle = dir * 2.0 * 72.0;
  4275. else
  4276. // If we do this line, we are just trying to move further
  4277. // around the circle.
  4278. delta_angle = dir * (float) random(25, 45);
  4279. angle += delta_angle;
  4280. while (angle > 360.0) // We probably do not need to keep the angle between 0 and 2*PI, but the
  4281. angle -= 360.0; // Arduino documentation says the trig functions should not be given values
  4282. while (angle < 0.0) // outside of this range. It looks like they behave correctly with
  4283. angle += 360.0; // numbers outside of the range, but just to be safe we clamp them.
  4284. X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
  4285. Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;
  4286. #if DISABLED(DELTA)
  4287. X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
  4288. Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
  4289. #else
  4290. // If we have gone out too far, we can do a simple fix and scale the numbers
  4291. // back in closer to the origin.
  4292. while (HYPOT(X_current, Y_current) > DELTA_PROBEABLE_RADIUS) {
  4293. X_current /= 1.25;
  4294. Y_current /= 1.25;
  4295. if (verbose_level > 3) {
  4296. SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
  4297. SERIAL_ECHOLNPAIR(", ", Y_current);
  4298. }
  4299. }
  4300. #endif
  4301. if (verbose_level > 3) {
  4302. SERIAL_PROTOCOLPGM("Going to:");
  4303. SERIAL_ECHOPAIR(" X", X_current);
  4304. SERIAL_ECHOPAIR(" Y", Y_current);
  4305. SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
  4306. }
  4307. do_blocking_move_to_xy(X_current, Y_current);
  4308. } // n_legs loop
  4309. } // n_legs
  4310. // Probe a single point
  4311. sample_set[n] = probe_pt(X_probe_location, Y_probe_location, stow_probe_after_each, 0);
  4312. /**
  4313. * Get the current mean for the data points we have so far
  4314. */
  4315. double sum = 0.0;
  4316. for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
  4317. mean = sum / (n + 1);
  4318. NOMORE(min, sample_set[n]);
  4319. NOLESS(max, sample_set[n]);
  4320. /**
  4321. * Now, use that mean to calculate the standard deviation for the
  4322. * data points we have so far
  4323. */
  4324. sum = 0.0;
  4325. for (uint8_t j = 0; j <= n; j++)
  4326. sum += sq(sample_set[j] - mean);
  4327. sigma = sqrt(sum / (n + 1));
  4328. if (verbose_level > 0) {
  4329. if (verbose_level > 1) {
  4330. SERIAL_PROTOCOL(n + 1);
  4331. SERIAL_PROTOCOLPGM(" of ");
  4332. SERIAL_PROTOCOL((int)n_samples);
  4333. SERIAL_PROTOCOLPGM(": z: ");
  4334. SERIAL_PROTOCOL_F(sample_set[n], 3);
  4335. if (verbose_level > 2) {
  4336. SERIAL_PROTOCOLPGM(" mean: ");
  4337. SERIAL_PROTOCOL_F(mean, 4);
  4338. SERIAL_PROTOCOLPGM(" sigma: ");
  4339. SERIAL_PROTOCOL_F(sigma, 6);
  4340. SERIAL_PROTOCOLPGM(" min: ");
  4341. SERIAL_PROTOCOL_F(min, 3);
  4342. SERIAL_PROTOCOLPGM(" max: ");
  4343. SERIAL_PROTOCOL_F(max, 3);
  4344. SERIAL_PROTOCOLPGM(" range: ");
  4345. SERIAL_PROTOCOL_F(max-min, 3);
  4346. }
  4347. SERIAL_EOL;
  4348. }
  4349. }
  4350. } // End of probe loop
  4351. if (STOW_PROBE()) return;
  4352. SERIAL_PROTOCOLPGM("Finished!");
  4353. SERIAL_EOL;
  4354. if (verbose_level > 0) {
  4355. SERIAL_PROTOCOLPGM("Mean: ");
  4356. SERIAL_PROTOCOL_F(mean, 6);
  4357. SERIAL_PROTOCOLPGM(" Min: ");
  4358. SERIAL_PROTOCOL_F(min, 3);
  4359. SERIAL_PROTOCOLPGM(" Max: ");
  4360. SERIAL_PROTOCOL_F(max, 3);
  4361. SERIAL_PROTOCOLPGM(" Range: ");
  4362. SERIAL_PROTOCOL_F(max-min, 3);
  4363. SERIAL_EOL;
  4364. }
  4365. SERIAL_PROTOCOLPGM("Standard Deviation: ");
  4366. SERIAL_PROTOCOL_F(sigma, 6);
  4367. SERIAL_EOL;
  4368. SERIAL_EOL;
  4369. clean_up_after_endstop_or_probe_move();
  4370. // Re-enable bed level correction if it has been on
  4371. #if HAS_ABL
  4372. set_bed_leveling_enabled(abl_was_enabled);
  4373. #endif
  4374. report_current_position();
  4375. }
  4376. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  4377. /**
  4378. * M75: Start print timer
  4379. */
  4380. inline void gcode_M75() { print_job_timer.start(); }
  4381. /**
  4382. * M76: Pause print timer
  4383. */
  4384. inline void gcode_M76() { print_job_timer.pause(); }
  4385. /**
  4386. * M77: Stop print timer
  4387. */
  4388. inline void gcode_M77() { print_job_timer.stop(); }
  4389. #if ENABLED(PRINTCOUNTER)
  4390. /**
  4391. * M78: Show print statistics
  4392. */
  4393. inline void gcode_M78() {
  4394. // "M78 S78" will reset the statistics
  4395. if (code_seen('S') && code_value_int() == 78)
  4396. print_job_timer.initStats();
  4397. else
  4398. print_job_timer.showStats();
  4399. }
  4400. #endif
  4401. /**
  4402. * M104: Set hot end temperature
  4403. */
  4404. inline void gcode_M104() {
  4405. if (get_target_extruder_from_command(104)) return;
  4406. if (DEBUGGING(DRYRUN)) return;
  4407. #if ENABLED(SINGLENOZZLE)
  4408. if (target_extruder != active_extruder) return;
  4409. #endif
  4410. if (code_seen('S')) {
  4411. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  4412. #if ENABLED(DUAL_X_CARRIAGE)
  4413. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  4414. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  4415. #endif
  4416. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4417. /**
  4418. * Stop the timer at the end of print, starting is managed by
  4419. * 'heat and wait' M109.
  4420. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  4421. * stand by mode, for instance in a dual extruder setup, without affecting
  4422. * the running print timer.
  4423. */
  4424. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  4425. print_job_timer.stop();
  4426. LCD_MESSAGEPGM(WELCOME_MSG);
  4427. }
  4428. #endif
  4429. if (code_value_temp_abs() > thermalManager.degHotend(target_extruder)) status_printf(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  4430. }
  4431. #if ENABLED(AUTOTEMP)
  4432. planner.autotemp_M104_M109();
  4433. #endif
  4434. }
  4435. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  4436. void print_heaterstates() {
  4437. #if HAS_TEMP_HOTEND
  4438. SERIAL_PROTOCOLPGM(" T:");
  4439. SERIAL_PROTOCOL_F(thermalManager.degHotend(target_extruder), 1);
  4440. SERIAL_PROTOCOLPGM(" /");
  4441. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(target_extruder), 1);
  4442. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4443. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[target_extruder] / OVERSAMPLENR);
  4444. SERIAL_CHAR(')');
  4445. #endif
  4446. #endif
  4447. #if HAS_TEMP_BED
  4448. SERIAL_PROTOCOLPGM(" B:");
  4449. SERIAL_PROTOCOL_F(thermalManager.degBed(), 1);
  4450. SERIAL_PROTOCOLPGM(" /");
  4451. SERIAL_PROTOCOL_F(thermalManager.degTargetBed(), 1);
  4452. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4453. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_bed_raw / OVERSAMPLENR);
  4454. SERIAL_CHAR(')');
  4455. #endif
  4456. #endif
  4457. #if HOTENDS > 1
  4458. HOTEND_LOOP() {
  4459. SERIAL_PROTOCOLPAIR(" T", e);
  4460. SERIAL_PROTOCOLCHAR(':');
  4461. SERIAL_PROTOCOL_F(thermalManager.degHotend(e), 1);
  4462. SERIAL_PROTOCOLPGM(" /");
  4463. SERIAL_PROTOCOL_F(thermalManager.degTargetHotend(e), 1);
  4464. #if ENABLED(SHOW_TEMP_ADC_VALUES)
  4465. SERIAL_PROTOCOLPAIR(" (", thermalManager.current_temperature_raw[e] / OVERSAMPLENR);
  4466. SERIAL_CHAR(')');
  4467. #endif
  4468. }
  4469. #endif
  4470. SERIAL_PROTOCOLPGM(" @:");
  4471. SERIAL_PROTOCOL(thermalManager.getHeaterPower(target_extruder));
  4472. #if HAS_TEMP_BED
  4473. SERIAL_PROTOCOLPGM(" B@:");
  4474. SERIAL_PROTOCOL(thermalManager.getHeaterPower(-1));
  4475. #endif
  4476. #if HOTENDS > 1
  4477. HOTEND_LOOP() {
  4478. SERIAL_PROTOCOLPAIR(" @", e);
  4479. SERIAL_PROTOCOLCHAR(':');
  4480. SERIAL_PROTOCOL(thermalManager.getHeaterPower(e));
  4481. }
  4482. #endif
  4483. }
  4484. #endif
  4485. /**
  4486. * M105: Read hot end and bed temperature
  4487. */
  4488. inline void gcode_M105() {
  4489. if (get_target_extruder_from_command(105)) return;
  4490. #if HAS_TEMP_HOTEND || HAS_TEMP_BED
  4491. SERIAL_PROTOCOLPGM(MSG_OK);
  4492. print_heaterstates();
  4493. #else // !HAS_TEMP_HOTEND && !HAS_TEMP_BED
  4494. SERIAL_ERROR_START;
  4495. SERIAL_ERRORLNPGM(MSG_ERR_NO_THERMISTORS);
  4496. #endif
  4497. SERIAL_EOL;
  4498. }
  4499. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  4500. static uint8_t auto_report_temp_interval;
  4501. static millis_t next_temp_report_ms;
  4502. /**
  4503. * M155: Set temperature auto-report interval. M155 S<seconds>
  4504. */
  4505. inline void gcode_M155() {
  4506. if (code_seen('S')) {
  4507. auto_report_temp_interval = code_value_byte();
  4508. NOMORE(auto_report_temp_interval, 60);
  4509. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  4510. }
  4511. }
  4512. inline void auto_report_temperatures() {
  4513. if (auto_report_temp_interval && ELAPSED(millis(), next_temp_report_ms)) {
  4514. next_temp_report_ms = millis() + 1000UL * auto_report_temp_interval;
  4515. print_heaterstates();
  4516. SERIAL_EOL;
  4517. }
  4518. }
  4519. #endif // AUTO_REPORT_TEMPERATURES
  4520. #if FAN_COUNT > 0
  4521. /**
  4522. * M106: Set Fan Speed
  4523. *
  4524. * S<int> Speed between 0-255
  4525. * P<index> Fan index, if more than one fan
  4526. */
  4527. inline void gcode_M106() {
  4528. uint16_t s = code_seen('S') ? code_value_ushort() : 255,
  4529. p = code_seen('P') ? code_value_ushort() : 0;
  4530. NOMORE(s, 255);
  4531. if (p < FAN_COUNT) fanSpeeds[p] = s;
  4532. }
  4533. /**
  4534. * M107: Fan Off
  4535. */
  4536. inline void gcode_M107() {
  4537. uint16_t p = code_seen('P') ? code_value_ushort() : 0;
  4538. if (p < FAN_COUNT) fanSpeeds[p] = 0;
  4539. }
  4540. #endif // FAN_COUNT > 0
  4541. #if DISABLED(EMERGENCY_PARSER)
  4542. /**
  4543. * M108: Stop the waiting for heaters in M109, M190, M303. Does not affect the target temperature.
  4544. */
  4545. inline void gcode_M108() { wait_for_heatup = false; }
  4546. /**
  4547. * M112: Emergency Stop
  4548. */
  4549. inline void gcode_M112() { kill(PSTR(MSG_KILLED)); }
  4550. /**
  4551. * M410: Quickstop - Abort all planned moves
  4552. *
  4553. * This will stop the carriages mid-move, so most likely they
  4554. * will be out of sync with the stepper position after this.
  4555. */
  4556. inline void gcode_M410() { quickstop_stepper(); }
  4557. #endif
  4558. #ifndef MIN_COOLING_SLOPE_DEG
  4559. #define MIN_COOLING_SLOPE_DEG 1.50
  4560. #endif
  4561. #ifndef MIN_COOLING_SLOPE_TIME
  4562. #define MIN_COOLING_SLOPE_TIME 60
  4563. #endif
  4564. /**
  4565. * M109: Sxxx Wait for extruder(s) to reach temperature. Waits only when heating.
  4566. * Rxxx Wait for extruder(s) to reach temperature. Waits when heating and cooling.
  4567. */
  4568. inline void gcode_M109() {
  4569. if (get_target_extruder_from_command(109)) return;
  4570. if (DEBUGGING(DRYRUN)) return;
  4571. #if ENABLED(SINGLENOZZLE)
  4572. if (target_extruder != active_extruder) return;
  4573. #endif
  4574. bool no_wait_for_cooling = code_seen('S');
  4575. if (no_wait_for_cooling || code_seen('R')) {
  4576. thermalManager.setTargetHotend(code_value_temp_abs(), target_extruder);
  4577. #if ENABLED(DUAL_X_CARRIAGE)
  4578. if (dual_x_carriage_mode == DXC_DUPLICATION_MODE && target_extruder == 0)
  4579. thermalManager.setTargetHotend(code_value_temp_abs() == 0.0 ? 0.0 : code_value_temp_abs() + duplicate_extruder_temp_offset, 1);
  4580. #endif
  4581. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4582. /**
  4583. * We use half EXTRUDE_MINTEMP here to allow nozzles to be put into hot
  4584. * stand by mode, for instance in a dual extruder setup, without affecting
  4585. * the running print timer.
  4586. */
  4587. if (code_value_temp_abs() <= (EXTRUDE_MINTEMP)/2) {
  4588. print_job_timer.stop();
  4589. LCD_MESSAGEPGM(WELCOME_MSG);
  4590. }
  4591. /**
  4592. * We do not check if the timer is already running because this check will
  4593. * be done for us inside the Stopwatch::start() method thus a running timer
  4594. * will not restart.
  4595. */
  4596. else print_job_timer.start();
  4597. #endif
  4598. if (thermalManager.isHeatingHotend(target_extruder)) status_printf(0, PSTR("E%i %s"), target_extruder + 1, MSG_HEATING);
  4599. }
  4600. #if ENABLED(AUTOTEMP)
  4601. planner.autotemp_M104_M109();
  4602. #endif
  4603. #if TEMP_RESIDENCY_TIME > 0
  4604. millis_t residency_start_ms = 0;
  4605. // Loop until the temperature has stabilized
  4606. #define TEMP_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_RESIDENCY_TIME) * 1000UL))
  4607. #else
  4608. // Loop until the temperature is very close target
  4609. #define TEMP_CONDITIONS (wants_to_cool ? thermalManager.isCoolingHotend(target_extruder) : thermalManager.isHeatingHotend(target_extruder))
  4610. #endif //TEMP_RESIDENCY_TIME > 0
  4611. float theTarget = -1.0, old_temp = 9999.0;
  4612. bool wants_to_cool = false;
  4613. wait_for_heatup = true;
  4614. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  4615. KEEPALIVE_STATE(NOT_BUSY);
  4616. do {
  4617. // Target temperature might be changed during the loop
  4618. if (theTarget != thermalManager.degTargetHotend(target_extruder)) {
  4619. wants_to_cool = thermalManager.isCoolingHotend(target_extruder);
  4620. theTarget = thermalManager.degTargetHotend(target_extruder);
  4621. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  4622. if (no_wait_for_cooling && wants_to_cool) break;
  4623. }
  4624. now = millis();
  4625. if (ELAPSED(now, next_temp_ms)) { //Print temp & remaining time every 1s while waiting
  4626. next_temp_ms = now + 1000UL;
  4627. print_heaterstates();
  4628. #if TEMP_RESIDENCY_TIME > 0
  4629. SERIAL_PROTOCOLPGM(" W:");
  4630. if (residency_start_ms) {
  4631. long rem = (((TEMP_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  4632. SERIAL_PROTOCOLLN(rem);
  4633. }
  4634. else {
  4635. SERIAL_PROTOCOLLNPGM("?");
  4636. }
  4637. #else
  4638. SERIAL_EOL;
  4639. #endif
  4640. }
  4641. idle();
  4642. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  4643. float temp = thermalManager.degHotend(target_extruder);
  4644. #if TEMP_RESIDENCY_TIME > 0
  4645. float temp_diff = fabs(theTarget - temp);
  4646. if (!residency_start_ms) {
  4647. // Start the TEMP_RESIDENCY_TIME timer when we reach target temp for the first time.
  4648. if (temp_diff < TEMP_WINDOW) residency_start_ms = now;
  4649. }
  4650. else if (temp_diff > TEMP_HYSTERESIS) {
  4651. // Restart the timer whenever the temperature falls outside the hysteresis.
  4652. residency_start_ms = now;
  4653. }
  4654. #endif //TEMP_RESIDENCY_TIME > 0
  4655. // Prevent a wait-forever situation if R is misused i.e. M109 R0
  4656. if (wants_to_cool) {
  4657. // break after MIN_COOLING_SLOPE_TIME seconds
  4658. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG
  4659. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  4660. if (old_temp - temp < MIN_COOLING_SLOPE_DEG) break;
  4661. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME;
  4662. old_temp = temp;
  4663. }
  4664. }
  4665. } while (wait_for_heatup && TEMP_CONDITIONS);
  4666. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_HEATING_COMPLETE);
  4667. KEEPALIVE_STATE(IN_HANDLER);
  4668. }
  4669. #if HAS_TEMP_BED
  4670. #ifndef MIN_COOLING_SLOPE_DEG_BED
  4671. #define MIN_COOLING_SLOPE_DEG_BED 1.50
  4672. #endif
  4673. #ifndef MIN_COOLING_SLOPE_TIME_BED
  4674. #define MIN_COOLING_SLOPE_TIME_BED 60
  4675. #endif
  4676. /**
  4677. * M190: Sxxx Wait for bed current temp to reach target temp. Waits only when heating
  4678. * Rxxx Wait for bed current temp to reach target temp. Waits when heating and cooling
  4679. */
  4680. inline void gcode_M190() {
  4681. if (DEBUGGING(DRYRUN)) return;
  4682. LCD_MESSAGEPGM(MSG_BED_HEATING);
  4683. bool no_wait_for_cooling = code_seen('S');
  4684. if (no_wait_for_cooling || code_seen('R')) {
  4685. thermalManager.setTargetBed(code_value_temp_abs());
  4686. #if ENABLED(PRINTJOB_TIMER_AUTOSTART)
  4687. if (code_value_temp_abs() > BED_MINTEMP) {
  4688. /**
  4689. * We start the timer when 'heating and waiting' command arrives, LCD
  4690. * functions never wait. Cooling down managed by extruders.
  4691. *
  4692. * We do not check if the timer is already running because this check will
  4693. * be done for us inside the Stopwatch::start() method thus a running timer
  4694. * will not restart.
  4695. */
  4696. print_job_timer.start();
  4697. }
  4698. #endif
  4699. }
  4700. #if TEMP_BED_RESIDENCY_TIME > 0
  4701. millis_t residency_start_ms = 0;
  4702. // Loop until the temperature has stabilized
  4703. #define TEMP_BED_CONDITIONS (!residency_start_ms || PENDING(now, residency_start_ms + (TEMP_BED_RESIDENCY_TIME) * 1000UL))
  4704. #else
  4705. // Loop until the temperature is very close target
  4706. #define TEMP_BED_CONDITIONS (wants_to_cool ? thermalManager.isCoolingBed() : thermalManager.isHeatingBed())
  4707. #endif //TEMP_BED_RESIDENCY_TIME > 0
  4708. float theTarget = -1.0, old_temp = 9999.0;
  4709. bool wants_to_cool = false;
  4710. wait_for_heatup = true;
  4711. millis_t now, next_temp_ms = 0, next_cool_check_ms = 0;
  4712. KEEPALIVE_STATE(NOT_BUSY);
  4713. target_extruder = active_extruder; // for print_heaterstates
  4714. do {
  4715. // Target temperature might be changed during the loop
  4716. if (theTarget != thermalManager.degTargetBed()) {
  4717. wants_to_cool = thermalManager.isCoolingBed();
  4718. theTarget = thermalManager.degTargetBed();
  4719. // Exit if S<lower>, continue if S<higher>, R<lower>, or R<higher>
  4720. if (no_wait_for_cooling && wants_to_cool) break;
  4721. }
  4722. now = millis();
  4723. if (ELAPSED(now, next_temp_ms)) { //Print Temp Reading every 1 second while heating up.
  4724. next_temp_ms = now + 1000UL;
  4725. print_heaterstates();
  4726. #if TEMP_BED_RESIDENCY_TIME > 0
  4727. SERIAL_PROTOCOLPGM(" W:");
  4728. if (residency_start_ms) {
  4729. long rem = (((TEMP_BED_RESIDENCY_TIME) * 1000UL) - (now - residency_start_ms)) / 1000UL;
  4730. SERIAL_PROTOCOLLN(rem);
  4731. }
  4732. else {
  4733. SERIAL_PROTOCOLLNPGM("?");
  4734. }
  4735. #else
  4736. SERIAL_EOL;
  4737. #endif
  4738. }
  4739. idle();
  4740. refresh_cmd_timeout(); // to prevent stepper_inactive_time from running out
  4741. float temp = thermalManager.degBed();
  4742. #if TEMP_BED_RESIDENCY_TIME > 0
  4743. float temp_diff = fabs(theTarget - temp);
  4744. if (!residency_start_ms) {
  4745. // Start the TEMP_BED_RESIDENCY_TIME timer when we reach target temp for the first time.
  4746. if (temp_diff < TEMP_BED_WINDOW) residency_start_ms = now;
  4747. }
  4748. else if (temp_diff > TEMP_BED_HYSTERESIS) {
  4749. // Restart the timer whenever the temperature falls outside the hysteresis.
  4750. residency_start_ms = now;
  4751. }
  4752. #endif //TEMP_BED_RESIDENCY_TIME > 0
  4753. // Prevent a wait-forever situation if R is misused i.e. M190 R0
  4754. if (wants_to_cool) {
  4755. // break after MIN_COOLING_SLOPE_TIME_BED seconds
  4756. // if the temperature did not drop at least MIN_COOLING_SLOPE_DEG_BED
  4757. if (!next_cool_check_ms || ELAPSED(now, next_cool_check_ms)) {
  4758. if (old_temp - temp < MIN_COOLING_SLOPE_DEG_BED) break;
  4759. next_cool_check_ms = now + 1000UL * MIN_COOLING_SLOPE_TIME_BED;
  4760. old_temp = temp;
  4761. }
  4762. }
  4763. } while (wait_for_heatup && TEMP_BED_CONDITIONS);
  4764. if (wait_for_heatup) LCD_MESSAGEPGM(MSG_BED_DONE);
  4765. KEEPALIVE_STATE(IN_HANDLER);
  4766. }
  4767. #endif // HAS_TEMP_BED
  4768. /**
  4769. * M110: Set Current Line Number
  4770. */
  4771. inline void gcode_M110() {
  4772. if (code_seen('N')) gcode_LastN = code_value_long();
  4773. }
  4774. /**
  4775. * M111: Set the debug level
  4776. */
  4777. inline void gcode_M111() {
  4778. marlin_debug_flags = code_seen('S') ? code_value_byte() : (uint8_t) DEBUG_NONE;
  4779. const static char str_debug_1[] PROGMEM = MSG_DEBUG_ECHO;
  4780. const static char str_debug_2[] PROGMEM = MSG_DEBUG_INFO;
  4781. const static char str_debug_4[] PROGMEM = MSG_DEBUG_ERRORS;
  4782. const static char str_debug_8[] PROGMEM = MSG_DEBUG_DRYRUN;
  4783. const static char str_debug_16[] PROGMEM = MSG_DEBUG_COMMUNICATION;
  4784. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4785. const static char str_debug_32[] PROGMEM = MSG_DEBUG_LEVELING;
  4786. #endif
  4787. const static char* const debug_strings[] PROGMEM = {
  4788. str_debug_1, str_debug_2, str_debug_4, str_debug_8, str_debug_16,
  4789. #if ENABLED(DEBUG_LEVELING_FEATURE)
  4790. str_debug_32
  4791. #endif
  4792. };
  4793. SERIAL_ECHO_START;
  4794. SERIAL_ECHOPGM(MSG_DEBUG_PREFIX);
  4795. if (marlin_debug_flags) {
  4796. uint8_t comma = 0;
  4797. for (uint8_t i = 0; i < COUNT(debug_strings); i++) {
  4798. if (TEST(marlin_debug_flags, i)) {
  4799. if (comma++) SERIAL_CHAR(',');
  4800. serialprintPGM((char*)pgm_read_word(&(debug_strings[i])));
  4801. }
  4802. }
  4803. }
  4804. else {
  4805. SERIAL_ECHOPGM(MSG_DEBUG_OFF);
  4806. }
  4807. SERIAL_EOL;
  4808. }
  4809. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  4810. /**
  4811. * M113: Get or set Host Keepalive interval (0 to disable)
  4812. *
  4813. * S<seconds> Optional. Set the keepalive interval.
  4814. */
  4815. inline void gcode_M113() {
  4816. if (code_seen('S')) {
  4817. host_keepalive_interval = code_value_byte();
  4818. NOMORE(host_keepalive_interval, 60);
  4819. }
  4820. else {
  4821. SERIAL_ECHO_START;
  4822. SERIAL_ECHOLNPAIR("M113 S", (unsigned long)host_keepalive_interval);
  4823. }
  4824. }
  4825. #endif
  4826. #if ENABLED(BARICUDA)
  4827. #if HAS_HEATER_1
  4828. /**
  4829. * M126: Heater 1 valve open
  4830. */
  4831. inline void gcode_M126() { baricuda_valve_pressure = code_seen('S') ? code_value_byte() : 255; }
  4832. /**
  4833. * M127: Heater 1 valve close
  4834. */
  4835. inline void gcode_M127() { baricuda_valve_pressure = 0; }
  4836. #endif
  4837. #if HAS_HEATER_2
  4838. /**
  4839. * M128: Heater 2 valve open
  4840. */
  4841. inline void gcode_M128() { baricuda_e_to_p_pressure = code_seen('S') ? code_value_byte() : 255; }
  4842. /**
  4843. * M129: Heater 2 valve close
  4844. */
  4845. inline void gcode_M129() { baricuda_e_to_p_pressure = 0; }
  4846. #endif
  4847. #endif //BARICUDA
  4848. /**
  4849. * M140: Set bed temperature
  4850. */
  4851. inline void gcode_M140() {
  4852. if (DEBUGGING(DRYRUN)) return;
  4853. if (code_seen('S')) thermalManager.setTargetBed(code_value_temp_abs());
  4854. }
  4855. #if ENABLED(ULTIPANEL)
  4856. /**
  4857. * M145: Set the heatup state for a material in the LCD menu
  4858. * S<material> (0=PLA, 1=ABS)
  4859. * H<hotend temp>
  4860. * B<bed temp>
  4861. * F<fan speed>
  4862. */
  4863. inline void gcode_M145() {
  4864. uint8_t material = code_seen('S') ? (uint8_t)code_value_int() : 0;
  4865. if (material >= COUNT(lcd_preheat_hotend_temp)) {
  4866. SERIAL_ERROR_START;
  4867. SERIAL_ERRORLNPGM(MSG_ERR_MATERIAL_INDEX);
  4868. }
  4869. else {
  4870. int v;
  4871. if (code_seen('H')) {
  4872. v = code_value_int();
  4873. lcd_preheat_hotend_temp[material] = constrain(v, EXTRUDE_MINTEMP, HEATER_0_MAXTEMP - 15);
  4874. }
  4875. if (code_seen('F')) {
  4876. v = code_value_int();
  4877. lcd_preheat_fan_speed[material] = constrain(v, 0, 255);
  4878. }
  4879. #if TEMP_SENSOR_BED != 0
  4880. if (code_seen('B')) {
  4881. v = code_value_int();
  4882. lcd_preheat_bed_temp[material] = constrain(v, BED_MINTEMP, BED_MAXTEMP - 15);
  4883. }
  4884. #endif
  4885. }
  4886. }
  4887. #endif // ULTIPANEL
  4888. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  4889. /**
  4890. * M149: Set temperature units
  4891. */
  4892. inline void gcode_M149() {
  4893. if (code_seen('C')) set_input_temp_units(TEMPUNIT_C);
  4894. else if (code_seen('K')) set_input_temp_units(TEMPUNIT_K);
  4895. else if (code_seen('F')) set_input_temp_units(TEMPUNIT_F);
  4896. }
  4897. #endif
  4898. #if HAS_POWER_SWITCH
  4899. /**
  4900. * M80: Turn on Power Supply
  4901. */
  4902. inline void gcode_M80() {
  4903. OUT_WRITE(PS_ON_PIN, PS_ON_AWAKE); //GND
  4904. /**
  4905. * If you have a switch on suicide pin, this is useful
  4906. * if you want to start another print with suicide feature after
  4907. * a print without suicide...
  4908. */
  4909. #if HAS_SUICIDE
  4910. OUT_WRITE(SUICIDE_PIN, HIGH);
  4911. #endif
  4912. #if ENABLED(ULTIPANEL)
  4913. powersupply = true;
  4914. LCD_MESSAGEPGM(WELCOME_MSG);
  4915. lcd_update();
  4916. #endif
  4917. }
  4918. #endif // HAS_POWER_SWITCH
  4919. /**
  4920. * M81: Turn off Power, including Power Supply, if there is one.
  4921. *
  4922. * This code should ALWAYS be available for EMERGENCY SHUTDOWN!
  4923. */
  4924. inline void gcode_M81() {
  4925. thermalManager.disable_all_heaters();
  4926. stepper.finish_and_disable();
  4927. #if FAN_COUNT > 0
  4928. #if FAN_COUNT > 1
  4929. for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
  4930. #else
  4931. fanSpeeds[0] = 0;
  4932. #endif
  4933. #endif
  4934. delay(1000); // Wait 1 second before switching off
  4935. #if HAS_SUICIDE
  4936. stepper.synchronize();
  4937. suicide();
  4938. #elif HAS_POWER_SWITCH
  4939. OUT_WRITE(PS_ON_PIN, PS_ON_ASLEEP);
  4940. #endif
  4941. #if ENABLED(ULTIPANEL)
  4942. #if HAS_POWER_SWITCH
  4943. powersupply = false;
  4944. #endif
  4945. LCD_MESSAGEPGM(MACHINE_NAME " " MSG_OFF ".");
  4946. lcd_update();
  4947. #endif
  4948. }
  4949. /**
  4950. * M82: Set E codes absolute (default)
  4951. */
  4952. inline void gcode_M82() { axis_relative_modes[E_AXIS] = false; }
  4953. /**
  4954. * M83: Set E codes relative while in Absolute Coordinates (G90) mode
  4955. */
  4956. inline void gcode_M83() { axis_relative_modes[E_AXIS] = true; }
  4957. /**
  4958. * M18, M84: Disable all stepper motors
  4959. */
  4960. inline void gcode_M18_M84() {
  4961. if (code_seen('S')) {
  4962. stepper_inactive_time = code_value_millis_from_seconds();
  4963. }
  4964. else {
  4965. bool all_axis = !((code_seen('X')) || (code_seen('Y')) || (code_seen('Z')) || (code_seen('E')));
  4966. if (all_axis) {
  4967. stepper.finish_and_disable();
  4968. }
  4969. else {
  4970. stepper.synchronize();
  4971. if (code_seen('X')) disable_x();
  4972. if (code_seen('Y')) disable_y();
  4973. if (code_seen('Z')) disable_z();
  4974. #if ((E0_ENABLE_PIN != X_ENABLE_PIN) && (E1_ENABLE_PIN != Y_ENABLE_PIN)) // Only enable on boards that have seperate ENABLE_PINS
  4975. if (code_seen('E')) {
  4976. disable_e0();
  4977. disable_e1();
  4978. disable_e2();
  4979. disable_e3();
  4980. }
  4981. #endif
  4982. }
  4983. }
  4984. }
  4985. /**
  4986. * M85: Set inactivity shutdown timer with parameter S<seconds>. To disable set zero (default)
  4987. */
  4988. inline void gcode_M85() {
  4989. if (code_seen('S')) max_inactive_time = code_value_millis_from_seconds();
  4990. }
  4991. /**
  4992. * Multi-stepper support for M92, M201, M203
  4993. */
  4994. #if ENABLED(DISTINCT_E_FACTORS)
  4995. #define GET_TARGET_EXTRUDER(CMD) if (get_target_extruder_from_command(CMD)) return
  4996. #define TARGET_EXTRUDER target_extruder
  4997. #else
  4998. #define GET_TARGET_EXTRUDER(CMD) NOOP
  4999. #define TARGET_EXTRUDER 0
  5000. #endif
  5001. /**
  5002. * M92: Set axis steps-per-unit for one or more axes, X, Y, Z, and E.
  5003. * (Follows the same syntax as G92)
  5004. *
  5005. * With multiple extruders use T to specify which one.
  5006. */
  5007. inline void gcode_M92() {
  5008. GET_TARGET_EXTRUDER(92);
  5009. LOOP_XYZE(i) {
  5010. if (code_seen(axis_codes[i])) {
  5011. if (i == E_AXIS) {
  5012. float value = code_value_per_axis_unit(E_AXIS + TARGET_EXTRUDER);
  5013. if (value < 20.0) {
  5014. float factor = planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] / value; // increase e constants if M92 E14 is given for netfab.
  5015. planner.max_jerk[E_AXIS] *= factor;
  5016. planner.max_feedrate_mm_s[E_AXIS + TARGET_EXTRUDER] *= factor;
  5017. planner.max_acceleration_steps_per_s2[E_AXIS + TARGET_EXTRUDER] *= factor;
  5018. }
  5019. planner.axis_steps_per_mm[E_AXIS + TARGET_EXTRUDER] = value;
  5020. }
  5021. else {
  5022. planner.axis_steps_per_mm[i] = code_value_per_axis_unit(i);
  5023. }
  5024. }
  5025. }
  5026. planner.refresh_positioning();
  5027. }
  5028. /**
  5029. * Output the current position to serial
  5030. */
  5031. static void report_current_position() {
  5032. SERIAL_PROTOCOLPGM("X:");
  5033. SERIAL_PROTOCOL(current_position[X_AXIS]);
  5034. SERIAL_PROTOCOLPGM(" Y:");
  5035. SERIAL_PROTOCOL(current_position[Y_AXIS]);
  5036. SERIAL_PROTOCOLPGM(" Z:");
  5037. SERIAL_PROTOCOL(current_position[Z_AXIS]);
  5038. SERIAL_PROTOCOLPGM(" E:");
  5039. SERIAL_PROTOCOL(current_position[E_AXIS]);
  5040. stepper.report_positions();
  5041. #if IS_SCARA
  5042. SERIAL_PROTOCOLPAIR("SCARA Theta:", stepper.get_axis_position_degrees(A_AXIS));
  5043. SERIAL_PROTOCOLLNPAIR(" Psi+Theta:", stepper.get_axis_position_degrees(B_AXIS));
  5044. SERIAL_EOL;
  5045. #endif
  5046. }
  5047. /**
  5048. * M114: Output current position to serial port
  5049. */
  5050. inline void gcode_M114() { stepper.synchronize(); report_current_position(); }
  5051. /**
  5052. * M115: Capabilities string
  5053. */
  5054. inline void gcode_M115() {
  5055. SERIAL_PROTOCOLLNPGM(MSG_M115_REPORT);
  5056. #if ENABLED(EXTENDED_CAPABILITIES_REPORT)
  5057. // EEPROM (M500, M501)
  5058. #if ENABLED(EEPROM_SETTINGS)
  5059. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:1");
  5060. #else
  5061. SERIAL_PROTOCOLLNPGM("Cap:EEPROM:0");
  5062. #endif
  5063. // AUTOREPORT_TEMP (M155)
  5064. #if ENABLED(AUTO_REPORT_TEMPERATURES)
  5065. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:1");
  5066. #else
  5067. SERIAL_PROTOCOLLNPGM("Cap:AUTOREPORT_TEMP:0");
  5068. #endif
  5069. // PROGRESS (M530 S L, M531 <file>, M532 X L)
  5070. SERIAL_PROTOCOLLNPGM("Cap:PROGRESS:0");
  5071. // AUTOLEVEL (G29)
  5072. #if HAS_ABL
  5073. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:1");
  5074. #else
  5075. SERIAL_PROTOCOLLNPGM("Cap:AUTOLEVEL:0");
  5076. #endif
  5077. // Z_PROBE (G30)
  5078. #if HAS_BED_PROBE
  5079. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:1");
  5080. #else
  5081. SERIAL_PROTOCOLLNPGM("Cap:Z_PROBE:0");
  5082. #endif
  5083. // SOFTWARE_POWER (G30)
  5084. #if HAS_POWER_SWITCH
  5085. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:1");
  5086. #else
  5087. SERIAL_PROTOCOLLNPGM("Cap:SOFTWARE_POWER:0");
  5088. #endif
  5089. // TOGGLE_LIGHTS (M355)
  5090. #if HAS_CASE_LIGHT
  5091. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:1");
  5092. #else
  5093. SERIAL_PROTOCOLLNPGM("Cap:TOGGLE_LIGHTS:0");
  5094. #endif
  5095. // EMERGENCY_PARSER (M108, M112, M410)
  5096. #if ENABLED(EMERGENCY_PARSER)
  5097. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:1");
  5098. #else
  5099. SERIAL_PROTOCOLLNPGM("Cap:EMERGENCY_PARSER:0");
  5100. #endif
  5101. #endif // EXTENDED_CAPABILITIES_REPORT
  5102. }
  5103. /**
  5104. * M117: Set LCD Status Message
  5105. */
  5106. inline void gcode_M117() {
  5107. lcd_setstatus(current_command_args);
  5108. }
  5109. /**
  5110. * M119: Output endstop states to serial output
  5111. */
  5112. inline void gcode_M119() { endstops.M119(); }
  5113. /**
  5114. * M120: Enable endstops and set non-homing endstop state to "enabled"
  5115. */
  5116. inline void gcode_M120() { endstops.enable_globally(true); }
  5117. /**
  5118. * M121: Disable endstops and set non-homing endstop state to "disabled"
  5119. */
  5120. inline void gcode_M121() { endstops.enable_globally(false); }
  5121. #if ENABLED(BLINKM) || ENABLED(RGB_LED)
  5122. void set_led_color(const uint8_t r, const uint8_t g, const uint8_t b) {
  5123. #if ENABLED(BLINKM)
  5124. // This variant uses i2c to send the RGB components to the device.
  5125. SendColors(r, g, b);
  5126. #else
  5127. // This variant uses 3 separate pins for the RGB components.
  5128. // If the pins can do PWM then their intensity will be set.
  5129. digitalWrite(RGB_LED_R_PIN, r ? HIGH : LOW);
  5130. digitalWrite(RGB_LED_G_PIN, g ? HIGH : LOW);
  5131. digitalWrite(RGB_LED_B_PIN, b ? HIGH : LOW);
  5132. analogWrite(RGB_LED_R_PIN, r);
  5133. analogWrite(RGB_LED_G_PIN, g);
  5134. analogWrite(RGB_LED_B_PIN, b);
  5135. #endif
  5136. }
  5137. /**
  5138. * M150: Set Status LED Color - Use R-U-B for R-G-B
  5139. *
  5140. * Always sets all 3 components. If a component is left out, set to 0.
  5141. *
  5142. * Examples:
  5143. *
  5144. * M150 R255 ; Turn LED red
  5145. * M150 R255 U127 ; Turn LED orange (PWM only)
  5146. * M150 ; Turn LED off
  5147. * M150 R U B ; Turn LED white
  5148. *
  5149. */
  5150. inline void gcode_M150() {
  5151. set_led_color(
  5152. code_seen('R') ? (code_has_value() ? code_value_byte() : 255) : 0,
  5153. code_seen('U') ? (code_has_value() ? code_value_byte() : 255) : 0,
  5154. code_seen('B') ? (code_has_value() ? code_value_byte() : 255) : 0
  5155. );
  5156. }
  5157. #endif // BLINKM || RGB_LED
  5158. /**
  5159. * M200: Set filament diameter and set E axis units to cubic units
  5160. *
  5161. * T<extruder> - Optional extruder number. Current extruder if omitted.
  5162. * D<linear> - Diameter of the filament. Use "D0" to switch back to linear units on the E axis.
  5163. */
  5164. inline void gcode_M200() {
  5165. if (get_target_extruder_from_command(200)) return;
  5166. if (code_seen('D')) {
  5167. // setting any extruder filament size disables volumetric on the assumption that
  5168. // slicers either generate in extruder values as cubic mm or as as filament feeds
  5169. // for all extruders
  5170. volumetric_enabled = (code_value_linear_units() != 0.0);
  5171. if (volumetric_enabled) {
  5172. filament_size[target_extruder] = code_value_linear_units();
  5173. // make sure all extruders have some sane value for the filament size
  5174. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  5175. if (! filament_size[i]) filament_size[i] = DEFAULT_NOMINAL_FILAMENT_DIA;
  5176. }
  5177. }
  5178. else {
  5179. //reserved for setting filament diameter via UFID or filament measuring device
  5180. return;
  5181. }
  5182. calculate_volumetric_multipliers();
  5183. }
  5184. /**
  5185. * M201: Set max acceleration in units/s^2 for print moves (M201 X1000 Y1000)
  5186. *
  5187. * With multiple extruders use T to specify which one.
  5188. */
  5189. inline void gcode_M201() {
  5190. GET_TARGET_EXTRUDER(201);
  5191. LOOP_XYZE(i) {
  5192. if (code_seen(axis_codes[i])) {
  5193. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  5194. planner.max_acceleration_mm_per_s2[a] = code_value_axis_units(a);
  5195. }
  5196. }
  5197. // 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)
  5198. planner.reset_acceleration_rates();
  5199. }
  5200. #if 0 // Not used for Sprinter/grbl gen6
  5201. inline void gcode_M202() {
  5202. LOOP_XYZE(i) {
  5203. if (code_seen(axis_codes[i])) axis_travel_steps_per_sqr_second[i] = code_value_axis_units(i) * planner.axis_steps_per_mm[i];
  5204. }
  5205. }
  5206. #endif
  5207. /**
  5208. * M203: Set maximum feedrate that your machine can sustain (M203 X200 Y200 Z300 E10000) in units/sec
  5209. *
  5210. * With multiple extruders use T to specify which one.
  5211. */
  5212. inline void gcode_M203() {
  5213. GET_TARGET_EXTRUDER(203);
  5214. LOOP_XYZE(i)
  5215. if (code_seen(axis_codes[i])) {
  5216. const uint8_t a = i + (i == E_AXIS ? TARGET_EXTRUDER : 0);
  5217. planner.max_feedrate_mm_s[a] = code_value_axis_units(a);
  5218. }
  5219. }
  5220. /**
  5221. * M204: Set Accelerations in units/sec^2 (M204 P1200 R3000 T3000)
  5222. *
  5223. * P = Printing moves
  5224. * R = Retract only (no X, Y, Z) moves
  5225. * T = Travel (non printing) moves
  5226. *
  5227. * Also sets minimum segment time in ms (B20000) to prevent buffer under-runs and M20 minimum feedrate
  5228. */
  5229. inline void gcode_M204() {
  5230. if (code_seen('S')) { // Kept for legacy compatibility. Should NOT BE USED for new developments.
  5231. planner.travel_acceleration = planner.acceleration = code_value_linear_units();
  5232. SERIAL_ECHOLNPAIR("Setting Print and Travel Acceleration: ", planner.acceleration);
  5233. }
  5234. if (code_seen('P')) {
  5235. planner.acceleration = code_value_linear_units();
  5236. SERIAL_ECHOLNPAIR("Setting Print Acceleration: ", planner.acceleration);
  5237. }
  5238. if (code_seen('R')) {
  5239. planner.retract_acceleration = code_value_linear_units();
  5240. SERIAL_ECHOLNPAIR("Setting Retract Acceleration: ", planner.retract_acceleration);
  5241. }
  5242. if (code_seen('T')) {
  5243. planner.travel_acceleration = code_value_linear_units();
  5244. SERIAL_ECHOLNPAIR("Setting Travel Acceleration: ", planner.travel_acceleration);
  5245. }
  5246. }
  5247. /**
  5248. * M205: Set Advanced Settings
  5249. *
  5250. * S = Min Feed Rate (units/s)
  5251. * T = Min Travel Feed Rate (units/s)
  5252. * B = Min Segment Time (µs)
  5253. * X = Max X Jerk (units/sec^2)
  5254. * Y = Max Y Jerk (units/sec^2)
  5255. * Z = Max Z Jerk (units/sec^2)
  5256. * E = Max E Jerk (units/sec^2)
  5257. */
  5258. inline void gcode_M205() {
  5259. if (code_seen('S')) planner.min_feedrate_mm_s = code_value_linear_units();
  5260. if (code_seen('T')) planner.min_travel_feedrate_mm_s = code_value_linear_units();
  5261. if (code_seen('B')) planner.min_segment_time = code_value_millis();
  5262. if (code_seen('X')) planner.max_jerk[X_AXIS] = code_value_axis_units(X_AXIS);
  5263. if (code_seen('Y')) planner.max_jerk[Y_AXIS] = code_value_axis_units(Y_AXIS);
  5264. if (code_seen('Z')) planner.max_jerk[Z_AXIS] = code_value_axis_units(Z_AXIS);
  5265. if (code_seen('E')) planner.max_jerk[E_AXIS] = code_value_axis_units(E_AXIS);
  5266. }
  5267. #if DISABLED(NO_WORKSPACE_OFFSETS)
  5268. /**
  5269. * M206: Set Additional Homing Offset (X Y Z). SCARA aliases T=X, P=Y
  5270. */
  5271. inline void gcode_M206() {
  5272. LOOP_XYZ(i)
  5273. if (code_seen(axis_codes[i]))
  5274. set_home_offset((AxisEnum)i, code_value_axis_units(i));
  5275. #if ENABLED(MORGAN_SCARA)
  5276. if (code_seen('T')) set_home_offset(A_AXIS, code_value_axis_units(A_AXIS)); // Theta
  5277. if (code_seen('P')) set_home_offset(B_AXIS, code_value_axis_units(B_AXIS)); // Psi
  5278. #endif
  5279. SYNC_PLAN_POSITION_KINEMATIC();
  5280. report_current_position();
  5281. }
  5282. #endif // NO_WORKSPACE_OFFSETS
  5283. #if ENABLED(DELTA)
  5284. /**
  5285. * M665: Set delta configurations
  5286. *
  5287. * L = diagonal rod
  5288. * R = delta radius
  5289. * S = segments per second
  5290. * A = Alpha (Tower 1) diagonal rod trim
  5291. * B = Beta (Tower 2) diagonal rod trim
  5292. * C = Gamma (Tower 3) diagonal rod trim
  5293. */
  5294. inline void gcode_M665() {
  5295. if (code_seen('L')) delta_diagonal_rod = code_value_linear_units();
  5296. if (code_seen('R')) delta_radius = code_value_linear_units();
  5297. if (code_seen('S')) delta_segments_per_second = code_value_float();
  5298. if (code_seen('A')) delta_diagonal_rod_trim[A_AXIS] = code_value_linear_units();
  5299. if (code_seen('B')) delta_diagonal_rod_trim[B_AXIS] = code_value_linear_units();
  5300. if (code_seen('C')) delta_diagonal_rod_trim[C_AXIS] = code_value_linear_units();
  5301. if (code_seen('I')) delta_tower_angle_trim[A_AXIS] = code_value_linear_units();
  5302. if (code_seen('J')) delta_tower_angle_trim[B_AXIS] = code_value_linear_units();
  5303. if (code_seen('K')) delta_tower_angle_trim[C_AXIS] = code_value_linear_units();
  5304. recalc_delta_settings(delta_radius, delta_diagonal_rod);
  5305. }
  5306. /**
  5307. * M666: Set delta endstop adjustment
  5308. */
  5309. inline void gcode_M666() {
  5310. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5311. if (DEBUGGING(LEVELING)) {
  5312. SERIAL_ECHOLNPGM(">>> gcode_M666");
  5313. }
  5314. #endif
  5315. LOOP_XYZ(i) {
  5316. if (code_seen(axis_codes[i])) {
  5317. endstop_adj[i] = code_value_axis_units(i);
  5318. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5319. if (DEBUGGING(LEVELING)) {
  5320. SERIAL_ECHOPAIR("endstop_adj[", axis_codes[i]);
  5321. SERIAL_ECHOLNPAIR("] = ", endstop_adj[i]);
  5322. }
  5323. #endif
  5324. }
  5325. }
  5326. #if ENABLED(DEBUG_LEVELING_FEATURE)
  5327. if (DEBUGGING(LEVELING)) {
  5328. SERIAL_ECHOLNPGM("<<< gcode_M666");
  5329. }
  5330. #endif
  5331. }
  5332. #elif ENABLED(Z_DUAL_ENDSTOPS) // !DELTA && ENABLED(Z_DUAL_ENDSTOPS)
  5333. /**
  5334. * M666: For Z Dual Endstop setup, set z axis offset to the z2 axis.
  5335. */
  5336. inline void gcode_M666() {
  5337. if (code_seen('Z')) z_endstop_adj = code_value_axis_units(Z_AXIS);
  5338. SERIAL_ECHOLNPAIR("Z Endstop Adjustment set to (mm):", z_endstop_adj);
  5339. }
  5340. #endif // !DELTA && Z_DUAL_ENDSTOPS
  5341. #if ENABLED(FWRETRACT)
  5342. /**
  5343. * M207: Set firmware retraction values
  5344. *
  5345. * S[+units] retract_length
  5346. * W[+units] retract_length_swap (multi-extruder)
  5347. * F[units/min] retract_feedrate_mm_s
  5348. * Z[units] retract_zlift
  5349. */
  5350. inline void gcode_M207() {
  5351. if (code_seen('S')) retract_length = code_value_axis_units(E_AXIS);
  5352. if (code_seen('F')) retract_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS));
  5353. if (code_seen('Z')) retract_zlift = code_value_axis_units(Z_AXIS);
  5354. #if EXTRUDERS > 1
  5355. if (code_seen('W')) retract_length_swap = code_value_axis_units(E_AXIS);
  5356. #endif
  5357. }
  5358. /**
  5359. * M208: Set firmware un-retraction values
  5360. *
  5361. * S[+units] retract_recover_length (in addition to M207 S*)
  5362. * W[+units] retract_recover_length_swap (multi-extruder)
  5363. * F[units/min] retract_recover_feedrate_mm_s
  5364. */
  5365. inline void gcode_M208() {
  5366. if (code_seen('S')) retract_recover_length = code_value_axis_units(E_AXIS);
  5367. if (code_seen('F')) retract_recover_feedrate_mm_s = MMM_TO_MMS(code_value_axis_units(E_AXIS));
  5368. #if EXTRUDERS > 1
  5369. if (code_seen('W')) retract_recover_length_swap = code_value_axis_units(E_AXIS);
  5370. #endif
  5371. }
  5372. /**
  5373. * M209: Enable automatic retract (M209 S1)
  5374. * For slicers that don't support G10/11, reversed extrude-only
  5375. * moves will be classified as retraction.
  5376. */
  5377. inline void gcode_M209() {
  5378. if (code_seen('S')) {
  5379. autoretract_enabled = code_value_bool();
  5380. for (int i = 0; i < EXTRUDERS; i++) retracted[i] = false;
  5381. }
  5382. }
  5383. #endif // FWRETRACT
  5384. /**
  5385. * M211: Enable, Disable, and/or Report software endstops
  5386. *
  5387. * Usage: M211 S1 to enable, M211 S0 to disable, M211 alone for report
  5388. */
  5389. inline void gcode_M211() {
  5390. SERIAL_ECHO_START;
  5391. #if HAS_SOFTWARE_ENDSTOPS
  5392. if (code_seen('S')) soft_endstops_enabled = code_value_bool();
  5393. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  5394. serialprintPGM(soft_endstops_enabled ? PSTR(MSG_ON) : PSTR(MSG_OFF));
  5395. #else
  5396. SERIAL_ECHOPGM(MSG_SOFT_ENDSTOPS);
  5397. SERIAL_ECHOPGM(MSG_OFF);
  5398. #endif
  5399. SERIAL_ECHOPGM(MSG_SOFT_MIN);
  5400. SERIAL_ECHOPAIR( MSG_X, soft_endstop_min[X_AXIS]);
  5401. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_min[Y_AXIS]);
  5402. SERIAL_ECHOPAIR(" " MSG_Z, soft_endstop_min[Z_AXIS]);
  5403. SERIAL_ECHOPGM(MSG_SOFT_MAX);
  5404. SERIAL_ECHOPAIR( MSG_X, soft_endstop_max[X_AXIS]);
  5405. SERIAL_ECHOPAIR(" " MSG_Y, soft_endstop_max[Y_AXIS]);
  5406. SERIAL_ECHOLNPAIR(" " MSG_Z, soft_endstop_max[Z_AXIS]);
  5407. }
  5408. #if HOTENDS > 1
  5409. /**
  5410. * M218 - set hotend offset (in linear units)
  5411. *
  5412. * T<tool>
  5413. * X<xoffset>
  5414. * Y<yoffset>
  5415. * Z<zoffset> - Available with DUAL_X_CARRIAGE and SWITCHING_EXTRUDER
  5416. */
  5417. inline void gcode_M218() {
  5418. if (get_target_extruder_from_command(218) || target_extruder == 0) return;
  5419. if (code_seen('X')) hotend_offset[X_AXIS][target_extruder] = code_value_axis_units(X_AXIS);
  5420. if (code_seen('Y')) hotend_offset[Y_AXIS][target_extruder] = code_value_axis_units(Y_AXIS);
  5421. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER)
  5422. if (code_seen('Z')) hotend_offset[Z_AXIS][target_extruder] = code_value_axis_units(Z_AXIS);
  5423. #endif
  5424. SERIAL_ECHO_START;
  5425. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  5426. HOTEND_LOOP() {
  5427. SERIAL_CHAR(' ');
  5428. SERIAL_ECHO(hotend_offset[X_AXIS][e]);
  5429. SERIAL_CHAR(',');
  5430. SERIAL_ECHO(hotend_offset[Y_AXIS][e]);
  5431. #if ENABLED(DUAL_X_CARRIAGE) || ENABLED(SWITCHING_EXTRUDER)
  5432. SERIAL_CHAR(',');
  5433. SERIAL_ECHO(hotend_offset[Z_AXIS][e]);
  5434. #endif
  5435. }
  5436. SERIAL_EOL;
  5437. }
  5438. #endif // HOTENDS > 1
  5439. /**
  5440. * M220: Set speed percentage factor, aka "Feed Rate" (M220 S95)
  5441. */
  5442. inline void gcode_M220() {
  5443. if (code_seen('S')) feedrate_percentage = code_value_int();
  5444. }
  5445. /**
  5446. * M221: Set extrusion percentage (M221 T0 S95)
  5447. */
  5448. inline void gcode_M221() {
  5449. if (get_target_extruder_from_command(221)) return;
  5450. if (code_seen('S'))
  5451. flow_percentage[target_extruder] = code_value_int();
  5452. }
  5453. /**
  5454. * M226: Wait until the specified pin reaches the state required (M226 P<pin> S<state>)
  5455. */
  5456. inline void gcode_M226() {
  5457. if (code_seen('P')) {
  5458. int pin_number = code_value_int(),
  5459. pin_state = code_seen('S') ? code_value_int() : -1; // required pin state - default is inverted
  5460. if (pin_state >= -1 && pin_state <= 1 && pin_number > -1 && !pin_is_protected(pin_number)) {
  5461. int target = LOW;
  5462. stepper.synchronize();
  5463. pinMode(pin_number, INPUT);
  5464. switch (pin_state) {
  5465. case 1:
  5466. target = HIGH;
  5467. break;
  5468. case 0:
  5469. target = LOW;
  5470. break;
  5471. case -1:
  5472. target = !digitalRead(pin_number);
  5473. break;
  5474. }
  5475. while (digitalRead(pin_number) != target) idle();
  5476. } // pin_state -1 0 1 && pin_number > -1
  5477. } // code_seen('P')
  5478. }
  5479. #if ENABLED(EXPERIMENTAL_I2CBUS)
  5480. /**
  5481. * M260: Send data to a I2C slave device
  5482. *
  5483. * This is a PoC, the formating and arguments for the GCODE will
  5484. * change to be more compatible, the current proposal is:
  5485. *
  5486. * M260 A<slave device address base 10> ; Sets the I2C slave address the data will be sent to
  5487. *
  5488. * M260 B<byte-1 value in base 10>
  5489. * M260 B<byte-2 value in base 10>
  5490. * M260 B<byte-3 value in base 10>
  5491. *
  5492. * M260 S1 ; Send the buffered data and reset the buffer
  5493. * M260 R1 ; Reset the buffer without sending data
  5494. *
  5495. */
  5496. inline void gcode_M260() {
  5497. // Set the target address
  5498. if (code_seen('A')) i2c.address(code_value_byte());
  5499. // Add a new byte to the buffer
  5500. if (code_seen('B')) i2c.addbyte(code_value_byte());
  5501. // Flush the buffer to the bus
  5502. if (code_seen('S')) i2c.send();
  5503. // Reset and rewind the buffer
  5504. else if (code_seen('R')) i2c.reset();
  5505. }
  5506. /**
  5507. * M261: Request X bytes from I2C slave device
  5508. *
  5509. * Usage: M261 A<slave device address base 10> B<number of bytes>
  5510. */
  5511. inline void gcode_M261() {
  5512. if (code_seen('A')) i2c.address(code_value_byte());
  5513. uint8_t bytes = code_seen('B') ? code_value_byte() : 1;
  5514. if (i2c.addr && bytes && bytes <= TWIBUS_BUFFER_SIZE) {
  5515. i2c.relay(bytes);
  5516. }
  5517. else {
  5518. SERIAL_ERROR_START;
  5519. SERIAL_ERRORLN("Bad i2c request");
  5520. }
  5521. }
  5522. #endif // EXPERIMENTAL_I2CBUS
  5523. #if HAS_SERVOS
  5524. /**
  5525. * M280: Get or set servo position. P<index> [S<angle>]
  5526. */
  5527. inline void gcode_M280() {
  5528. if (!code_seen('P')) return;
  5529. int servo_index = code_value_int();
  5530. if (servo_index >= 0 && servo_index < NUM_SERVOS) {
  5531. if (code_seen('S'))
  5532. MOVE_SERVO(servo_index, code_value_int());
  5533. else {
  5534. SERIAL_ECHO_START;
  5535. SERIAL_ECHOPAIR(" Servo ", servo_index);
  5536. SERIAL_ECHOLNPAIR(": ", servo[servo_index].read());
  5537. }
  5538. }
  5539. else {
  5540. SERIAL_ERROR_START;
  5541. SERIAL_ECHOPAIR("Servo ", servo_index);
  5542. SERIAL_ECHOLNPGM(" out of range");
  5543. }
  5544. }
  5545. #endif // HAS_SERVOS
  5546. #if HAS_BUZZER
  5547. /**
  5548. * M300: Play beep sound S<frequency Hz> P<duration ms>
  5549. */
  5550. inline void gcode_M300() {
  5551. uint16_t const frequency = code_seen('S') ? code_value_ushort() : 260;
  5552. uint16_t duration = code_seen('P') ? code_value_ushort() : 1000;
  5553. // Limits the tone duration to 0-5 seconds.
  5554. NOMORE(duration, 5000);
  5555. BUZZ(duration, frequency);
  5556. }
  5557. #endif // HAS_BUZZER
  5558. #if ENABLED(PIDTEMP)
  5559. /**
  5560. * M301: Set PID parameters P I D (and optionally C, L)
  5561. *
  5562. * P[float] Kp term
  5563. * I[float] Ki term (unscaled)
  5564. * D[float] Kd term (unscaled)
  5565. *
  5566. * With PID_EXTRUSION_SCALING:
  5567. *
  5568. * C[float] Kc term
  5569. * L[float] LPQ length
  5570. */
  5571. inline void gcode_M301() {
  5572. // multi-extruder PID patch: M301 updates or prints a single extruder's PID values
  5573. // default behaviour (omitting E parameter) is to update for extruder 0 only
  5574. int e = code_seen('E') ? code_value_int() : 0; // extruder being updated
  5575. if (e < HOTENDS) { // catch bad input value
  5576. if (code_seen('P')) PID_PARAM(Kp, e) = code_value_float();
  5577. if (code_seen('I')) PID_PARAM(Ki, e) = scalePID_i(code_value_float());
  5578. if (code_seen('D')) PID_PARAM(Kd, e) = scalePID_d(code_value_float());
  5579. #if ENABLED(PID_EXTRUSION_SCALING)
  5580. if (code_seen('C')) PID_PARAM(Kc, e) = code_value_float();
  5581. if (code_seen('L')) lpq_len = code_value_float();
  5582. NOMORE(lpq_len, LPQ_MAX_LEN);
  5583. #endif
  5584. thermalManager.updatePID();
  5585. SERIAL_ECHO_START;
  5586. #if ENABLED(PID_PARAMS_PER_HOTEND)
  5587. SERIAL_ECHOPAIR(" e:", e); // specify extruder in serial output
  5588. #endif // PID_PARAMS_PER_HOTEND
  5589. SERIAL_ECHOPAIR(" p:", PID_PARAM(Kp, e));
  5590. SERIAL_ECHOPAIR(" i:", unscalePID_i(PID_PARAM(Ki, e)));
  5591. SERIAL_ECHOPAIR(" d:", unscalePID_d(PID_PARAM(Kd, e)));
  5592. #if ENABLED(PID_EXTRUSION_SCALING)
  5593. //Kc does not have scaling applied above, or in resetting defaults
  5594. SERIAL_ECHOPAIR(" c:", PID_PARAM(Kc, e));
  5595. #endif
  5596. SERIAL_EOL;
  5597. }
  5598. else {
  5599. SERIAL_ERROR_START;
  5600. SERIAL_ERRORLN(MSG_INVALID_EXTRUDER);
  5601. }
  5602. }
  5603. #endif // PIDTEMP
  5604. #if ENABLED(PIDTEMPBED)
  5605. inline void gcode_M304() {
  5606. if (code_seen('P')) thermalManager.bedKp = code_value_float();
  5607. if (code_seen('I')) thermalManager.bedKi = scalePID_i(code_value_float());
  5608. if (code_seen('D')) thermalManager.bedKd = scalePID_d(code_value_float());
  5609. thermalManager.updatePID();
  5610. SERIAL_ECHO_START;
  5611. SERIAL_ECHOPAIR(" p:", thermalManager.bedKp);
  5612. SERIAL_ECHOPAIR(" i:", unscalePID_i(thermalManager.bedKi));
  5613. SERIAL_ECHOLNPAIR(" d:", unscalePID_d(thermalManager.bedKd));
  5614. }
  5615. #endif // PIDTEMPBED
  5616. #if defined(CHDK) || HAS_PHOTOGRAPH
  5617. /**
  5618. * M240: Trigger a camera by emulating a Canon RC-1
  5619. * See http://www.doc-diy.net/photo/rc-1_hacked/
  5620. */
  5621. inline void gcode_M240() {
  5622. #ifdef CHDK
  5623. OUT_WRITE(CHDK, HIGH);
  5624. chdkHigh = millis();
  5625. chdkActive = true;
  5626. #elif HAS_PHOTOGRAPH
  5627. const uint8_t NUM_PULSES = 16;
  5628. const float PULSE_LENGTH = 0.01524;
  5629. for (int i = 0; i < NUM_PULSES; i++) {
  5630. WRITE(PHOTOGRAPH_PIN, HIGH);
  5631. _delay_ms(PULSE_LENGTH);
  5632. WRITE(PHOTOGRAPH_PIN, LOW);
  5633. _delay_ms(PULSE_LENGTH);
  5634. }
  5635. delay(7.33);
  5636. for (int i = 0; i < NUM_PULSES; i++) {
  5637. WRITE(PHOTOGRAPH_PIN, HIGH);
  5638. _delay_ms(PULSE_LENGTH);
  5639. WRITE(PHOTOGRAPH_PIN, LOW);
  5640. _delay_ms(PULSE_LENGTH);
  5641. }
  5642. #endif // !CHDK && HAS_PHOTOGRAPH
  5643. }
  5644. #endif // CHDK || PHOTOGRAPH_PIN
  5645. #if HAS_LCD_CONTRAST
  5646. /**
  5647. * M250: Read and optionally set the LCD contrast
  5648. */
  5649. inline void gcode_M250() {
  5650. if (code_seen('C')) set_lcd_contrast(code_value_int());
  5651. SERIAL_PROTOCOLPGM("lcd contrast value: ");
  5652. SERIAL_PROTOCOL(lcd_contrast);
  5653. SERIAL_EOL;
  5654. }
  5655. #endif // HAS_LCD_CONTRAST
  5656. #if ENABLED(PREVENT_COLD_EXTRUSION)
  5657. /**
  5658. * M302: Allow cold extrudes, or set the minimum extrude temperature
  5659. *
  5660. * S<temperature> sets the minimum extrude temperature
  5661. * P<bool> enables (1) or disables (0) cold extrusion
  5662. *
  5663. * Examples:
  5664. *
  5665. * M302 ; report current cold extrusion state
  5666. * M302 P0 ; enable cold extrusion checking
  5667. * M302 P1 ; disables cold extrusion checking
  5668. * M302 S0 ; always allow extrusion (disables checking)
  5669. * M302 S170 ; only allow extrusion above 170
  5670. * M302 S170 P1 ; set min extrude temp to 170 but leave disabled
  5671. */
  5672. inline void gcode_M302() {
  5673. bool seen_S = code_seen('S');
  5674. if (seen_S) {
  5675. thermalManager.extrude_min_temp = code_value_temp_abs();
  5676. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0);
  5677. }
  5678. if (code_seen('P'))
  5679. thermalManager.allow_cold_extrude = (thermalManager.extrude_min_temp == 0) || code_value_bool();
  5680. else if (!seen_S) {
  5681. // Report current state
  5682. SERIAL_ECHO_START;
  5683. SERIAL_ECHOPAIR("Cold extrudes are ", (thermalManager.allow_cold_extrude ? "en" : "dis"));
  5684. SERIAL_ECHOPAIR("abled (min temp ", int(thermalManager.extrude_min_temp + 0.5));
  5685. SERIAL_ECHOLNPGM("C)");
  5686. }
  5687. }
  5688. #endif // PREVENT_COLD_EXTRUSION
  5689. /**
  5690. * M303: PID relay autotune
  5691. *
  5692. * S<temperature> sets the target temperature. (default 150C)
  5693. * E<extruder> (-1 for the bed) (default 0)
  5694. * C<cycles>
  5695. * U<bool> with a non-zero value will apply the result to current settings
  5696. */
  5697. inline void gcode_M303() {
  5698. #if HAS_PID_HEATING
  5699. int e = code_seen('E') ? code_value_int() : 0;
  5700. int c = code_seen('C') ? code_value_int() : 5;
  5701. bool u = code_seen('U') && code_value_bool();
  5702. float temp = code_seen('S') ? code_value_temp_abs() : (e < 0 ? 70.0 : 150.0);
  5703. if (e >= 0 && e < HOTENDS)
  5704. target_extruder = e;
  5705. KEEPALIVE_STATE(NOT_BUSY); // don't send "busy: processing" messages during autotune output
  5706. thermalManager.PID_autotune(temp, e, c, u);
  5707. KEEPALIVE_STATE(IN_HANDLER);
  5708. #else
  5709. SERIAL_ERROR_START;
  5710. SERIAL_ERRORLNPGM(MSG_ERR_M303_DISABLED);
  5711. #endif
  5712. }
  5713. #if ENABLED(MORGAN_SCARA)
  5714. bool SCARA_move_to_cal(uint8_t delta_a, uint8_t delta_b) {
  5715. if (IsRunning()) {
  5716. forward_kinematics_SCARA(delta_a, delta_b);
  5717. destination[X_AXIS] = LOGICAL_X_POSITION(cartes[X_AXIS]);
  5718. destination[Y_AXIS] = LOGICAL_Y_POSITION(cartes[Y_AXIS]);
  5719. destination[Z_AXIS] = current_position[Z_AXIS];
  5720. prepare_move_to_destination();
  5721. return true;
  5722. }
  5723. return false;
  5724. }
  5725. /**
  5726. * M360: SCARA calibration: Move to cal-position ThetaA (0 deg calibration)
  5727. */
  5728. inline bool gcode_M360() {
  5729. SERIAL_ECHOLNPGM(" Cal: Theta 0");
  5730. return SCARA_move_to_cal(0, 120);
  5731. }
  5732. /**
  5733. * M361: SCARA calibration: Move to cal-position ThetaB (90 deg calibration - steps per degree)
  5734. */
  5735. inline bool gcode_M361() {
  5736. SERIAL_ECHOLNPGM(" Cal: Theta 90");
  5737. return SCARA_move_to_cal(90, 130);
  5738. }
  5739. /**
  5740. * M362: SCARA calibration: Move to cal-position PsiA (0 deg calibration)
  5741. */
  5742. inline bool gcode_M362() {
  5743. SERIAL_ECHOLNPGM(" Cal: Psi 0");
  5744. return SCARA_move_to_cal(60, 180);
  5745. }
  5746. /**
  5747. * M363: SCARA calibration: Move to cal-position PsiB (90 deg calibration - steps per degree)
  5748. */
  5749. inline bool gcode_M363() {
  5750. SERIAL_ECHOLNPGM(" Cal: Psi 90");
  5751. return SCARA_move_to_cal(50, 90);
  5752. }
  5753. /**
  5754. * M364: SCARA calibration: Move to cal-position PSIC (90 deg to Theta calibration position)
  5755. */
  5756. inline bool gcode_M364() {
  5757. SERIAL_ECHOLNPGM(" Cal: Theta-Psi 90");
  5758. return SCARA_move_to_cal(45, 135);
  5759. }
  5760. #endif // SCARA
  5761. #if ENABLED(EXT_SOLENOID)
  5762. void enable_solenoid(uint8_t num) {
  5763. switch (num) {
  5764. case 0:
  5765. OUT_WRITE(SOL0_PIN, HIGH);
  5766. break;
  5767. #if HAS_SOLENOID_1
  5768. case 1:
  5769. OUT_WRITE(SOL1_PIN, HIGH);
  5770. break;
  5771. #endif
  5772. #if HAS_SOLENOID_2
  5773. case 2:
  5774. OUT_WRITE(SOL2_PIN, HIGH);
  5775. break;
  5776. #endif
  5777. #if HAS_SOLENOID_3
  5778. case 3:
  5779. OUT_WRITE(SOL3_PIN, HIGH);
  5780. break;
  5781. #endif
  5782. default:
  5783. SERIAL_ECHO_START;
  5784. SERIAL_ECHOLNPGM(MSG_INVALID_SOLENOID);
  5785. break;
  5786. }
  5787. }
  5788. void enable_solenoid_on_active_extruder() { enable_solenoid(active_extruder); }
  5789. void disable_all_solenoids() {
  5790. OUT_WRITE(SOL0_PIN, LOW);
  5791. OUT_WRITE(SOL1_PIN, LOW);
  5792. OUT_WRITE(SOL2_PIN, LOW);
  5793. OUT_WRITE(SOL3_PIN, LOW);
  5794. }
  5795. /**
  5796. * M380: Enable solenoid on the active extruder
  5797. */
  5798. inline void gcode_M380() { enable_solenoid_on_active_extruder(); }
  5799. /**
  5800. * M381: Disable all solenoids
  5801. */
  5802. inline void gcode_M381() { disable_all_solenoids(); }
  5803. #endif // EXT_SOLENOID
  5804. /**
  5805. * M400: Finish all moves
  5806. */
  5807. inline void gcode_M400() { stepper.synchronize(); }
  5808. #if HAS_BED_PROBE
  5809. /**
  5810. * M401: Engage Z Servo endstop if available
  5811. */
  5812. inline void gcode_M401() { DEPLOY_PROBE(); }
  5813. /**
  5814. * M402: Retract Z Servo endstop if enabled
  5815. */
  5816. inline void gcode_M402() { STOW_PROBE(); }
  5817. #endif // HAS_BED_PROBE
  5818. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  5819. /**
  5820. * M404: Display or set (in current units) the nominal filament width (3mm, 1.75mm ) W<3.0>
  5821. */
  5822. inline void gcode_M404() {
  5823. if (code_seen('W')) {
  5824. filament_width_nominal = code_value_linear_units();
  5825. }
  5826. else {
  5827. SERIAL_PROTOCOLPGM("Filament dia (nominal mm):");
  5828. SERIAL_PROTOCOLLN(filament_width_nominal);
  5829. }
  5830. }
  5831. /**
  5832. * M405: Turn on filament sensor for control
  5833. */
  5834. inline void gcode_M405() {
  5835. // This is technically a linear measurement, but since it's quantized to centimeters and is a different unit than
  5836. // everything else, it uses code_value_int() instead of code_value_linear_units().
  5837. if (code_seen('D')) meas_delay_cm = code_value_int();
  5838. NOMORE(meas_delay_cm, MAX_MEASUREMENT_DELAY);
  5839. if (filwidth_delay_index[1] == -1) { // Initialize the ring buffer if not done since startup
  5840. int temp_ratio = thermalManager.widthFil_to_size_ratio();
  5841. for (uint8_t i = 0; i < COUNT(measurement_delay); ++i)
  5842. measurement_delay[i] = temp_ratio - 100; // Subtract 100 to scale within a signed byte
  5843. filwidth_delay_index[0] = filwidth_delay_index[1] = 0;
  5844. }
  5845. filament_sensor = true;
  5846. //SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5847. //SERIAL_PROTOCOL(filament_width_meas);
  5848. //SERIAL_PROTOCOLPGM("Extrusion ratio(%):");
  5849. //SERIAL_PROTOCOL(flow_percentage[active_extruder]);
  5850. }
  5851. /**
  5852. * M406: Turn off filament sensor for control
  5853. */
  5854. inline void gcode_M406() { filament_sensor = false; }
  5855. /**
  5856. * M407: Get measured filament diameter on serial output
  5857. */
  5858. inline void gcode_M407() {
  5859. SERIAL_PROTOCOLPGM("Filament dia (measured mm):");
  5860. SERIAL_PROTOCOLLN(filament_width_meas);
  5861. }
  5862. #endif // FILAMENT_WIDTH_SENSOR
  5863. void quickstop_stepper() {
  5864. stepper.quick_stop();
  5865. stepper.synchronize();
  5866. set_current_from_steppers_for_axis(ALL_AXES);
  5867. SYNC_PLAN_POSITION_KINEMATIC();
  5868. }
  5869. #if PLANNER_LEVELING
  5870. /**
  5871. * M420: Enable/Disable Bed Leveling and/or set the Z fade height.
  5872. *
  5873. * S[bool] Turns leveling on or off
  5874. * Z[height] Sets the Z fade height (0 or none to disable)
  5875. * V[bool] Verbose - Print the levelng grid
  5876. */
  5877. inline void gcode_M420() {
  5878. bool to_enable = false;
  5879. if (code_seen('S')) {
  5880. to_enable = code_value_bool();
  5881. set_bed_leveling_enabled(to_enable);
  5882. }
  5883. #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT)
  5884. if (code_seen('Z')) set_z_fade_height(code_value_linear_units());
  5885. #endif
  5886. const bool new_status =
  5887. #if ENABLED(MESH_BED_LEVELING)
  5888. mbl.active()
  5889. #else
  5890. planner.abl_enabled
  5891. #endif
  5892. ;
  5893. if (to_enable && !new_status) {
  5894. SERIAL_ERROR_START;
  5895. SERIAL_ERRORLNPGM(MSG_ERR_M420_FAILED);
  5896. }
  5897. SERIAL_ECHO_START;
  5898. SERIAL_ECHOLNPAIR("Bed Leveling ", new_status ? MSG_ON : MSG_OFF);
  5899. // V to print the matrix or mesh
  5900. if (code_seen('V')) {
  5901. #if ABL_PLANAR
  5902. planner.bed_level_matrix.debug("Bed Level Correction Matrix:");
  5903. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  5904. if (bilinear_grid_spacing[X_AXIS]) {
  5905. print_bilinear_leveling_grid();
  5906. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  5907. bed_level_virt_print();
  5908. #endif
  5909. }
  5910. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  5911. blm.display_map(0); // Right now, we only support one type of map
  5912. #elif ENABLED(MESH_BED_LEVELING)
  5913. if (mbl.has_mesh()) {
  5914. SERIAL_ECHOLNPGM("Mesh Bed Level data:");
  5915. mbl_mesh_report();
  5916. }
  5917. #endif
  5918. }
  5919. }
  5920. #endif
  5921. #if ENABLED(MESH_BED_LEVELING)
  5922. /**
  5923. * M421: Set a single Mesh Bed Leveling Z coordinate
  5924. * Use either 'M421 X<linear> Y<linear> Z<linear>' or 'M421 I<xindex> J<yindex> Z<linear>'
  5925. */
  5926. inline void gcode_M421() {
  5927. int8_t px = 0, py = 0;
  5928. float z = 0;
  5929. bool hasX, hasY, hasZ, hasI, hasJ;
  5930. if ((hasX = code_seen('X'))) px = mbl.probe_index_x(code_value_axis_units(X_AXIS));
  5931. if ((hasY = code_seen('Y'))) py = mbl.probe_index_y(code_value_axis_units(Y_AXIS));
  5932. if ((hasI = code_seen('I'))) px = code_value_axis_units(X_AXIS);
  5933. if ((hasJ = code_seen('J'))) py = code_value_axis_units(Y_AXIS);
  5934. if ((hasZ = code_seen('Z'))) z = code_value_axis_units(Z_AXIS);
  5935. if (hasX && hasY && hasZ) {
  5936. if (px >= 0 && py >= 0)
  5937. mbl.set_z(px, py, z);
  5938. else {
  5939. SERIAL_ERROR_START;
  5940. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5941. }
  5942. }
  5943. else if (hasI && hasJ && hasZ) {
  5944. if (px >= 0 && px < MESH_NUM_X_POINTS && py >= 0 && py < MESH_NUM_Y_POINTS)
  5945. mbl.set_z(px, py, z);
  5946. else {
  5947. SERIAL_ERROR_START;
  5948. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5949. }
  5950. }
  5951. else {
  5952. SERIAL_ERROR_START;
  5953. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  5954. }
  5955. }
  5956. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  5957. /**
  5958. * M421: Set a single Mesh Bed Leveling Z coordinate
  5959. *
  5960. * M421 I<xindex> J<yindex> Z<linear>
  5961. */
  5962. inline void gcode_M421() {
  5963. int8_t px = 0, py = 0;
  5964. float z = 0;
  5965. bool hasI, hasJ, hasZ;
  5966. if ((hasI = code_seen('I'))) px = code_value_axis_units(X_AXIS);
  5967. if ((hasJ = code_seen('J'))) py = code_value_axis_units(Y_AXIS);
  5968. if ((hasZ = code_seen('Z'))) z = code_value_axis_units(Z_AXIS);
  5969. if (hasI && hasJ && hasZ) {
  5970. if (px >= 0 && px < ABL_GRID_MAX_POINTS_X && py >= 0 && py < ABL_GRID_MAX_POINTS_X) {
  5971. bed_level_grid[px][py] = z;
  5972. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  5973. bed_level_virt_interpolate();
  5974. #endif
  5975. }
  5976. else {
  5977. SERIAL_ERROR_START;
  5978. SERIAL_ERRORLNPGM(MSG_ERR_MESH_XY);
  5979. }
  5980. }
  5981. else {
  5982. SERIAL_ERROR_START;
  5983. SERIAL_ERRORLNPGM(MSG_ERR_M421_PARAMETERS);
  5984. }
  5985. }
  5986. #endif
  5987. #if DISABLED(NO_WORKSPACE_OFFSETS)
  5988. /**
  5989. * M428: Set home_offset based on the distance between the
  5990. * current_position and the nearest "reference point."
  5991. * If an axis is past center its endstop position
  5992. * is the reference-point. Otherwise it uses 0. This allows
  5993. * the Z offset to be set near the bed when using a max endstop.
  5994. *
  5995. * M428 can't be used more than 2cm away from 0 or an endstop.
  5996. *
  5997. * Use M206 to set these values directly.
  5998. */
  5999. inline void gcode_M428() {
  6000. bool err = false;
  6001. LOOP_XYZ(i) {
  6002. if (axis_homed[i]) {
  6003. float base = (current_position[i] > (soft_endstop_min[i] + soft_endstop_max[i]) * 0.5) ? base_home_pos((AxisEnum)i) : 0,
  6004. diff = current_position[i] - LOGICAL_POSITION(base, i);
  6005. if (diff > -20 && diff < 20) {
  6006. set_home_offset((AxisEnum)i, home_offset[i] - diff);
  6007. }
  6008. else {
  6009. SERIAL_ERROR_START;
  6010. SERIAL_ERRORLNPGM(MSG_ERR_M428_TOO_FAR);
  6011. LCD_ALERTMESSAGEPGM("Err: Too far!");
  6012. BUZZ(200, 40);
  6013. err = true;
  6014. break;
  6015. }
  6016. }
  6017. }
  6018. if (!err) {
  6019. SYNC_PLAN_POSITION_KINEMATIC();
  6020. report_current_position();
  6021. LCD_MESSAGEPGM(MSG_HOME_OFFSETS_APPLIED);
  6022. BUZZ(200, 659);
  6023. BUZZ(200, 698);
  6024. }
  6025. }
  6026. #endif // NO_WORKSPACE_OFFSETS
  6027. /**
  6028. * M500: Store settings in EEPROM
  6029. */
  6030. inline void gcode_M500() {
  6031. Config_StoreSettings();
  6032. }
  6033. /**
  6034. * M501: Read settings from EEPROM
  6035. */
  6036. inline void gcode_M501() {
  6037. Config_RetrieveSettings();
  6038. }
  6039. /**
  6040. * M502: Revert to default settings
  6041. */
  6042. inline void gcode_M502() {
  6043. Config_ResetDefault();
  6044. }
  6045. /**
  6046. * M503: print settings currently in memory
  6047. */
  6048. inline void gcode_M503() {
  6049. Config_PrintSettings(code_seen('S') && !code_value_bool());
  6050. }
  6051. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  6052. /**
  6053. * M540: Set whether SD card print should abort on endstop hit (M540 S<0|1>)
  6054. */
  6055. inline void gcode_M540() {
  6056. if (code_seen('S')) stepper.abort_on_endstop_hit = code_value_bool();
  6057. }
  6058. #endif // ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
  6059. #if HAS_BED_PROBE
  6060. inline void gcode_M851() {
  6061. SERIAL_ECHO_START;
  6062. SERIAL_ECHOPGM(MSG_ZPROBE_ZOFFSET);
  6063. SERIAL_CHAR(' ');
  6064. if (code_seen('Z')) {
  6065. float value = code_value_axis_units(Z_AXIS);
  6066. if (Z_PROBE_OFFSET_RANGE_MIN <= value && value <= Z_PROBE_OFFSET_RANGE_MAX) {
  6067. zprobe_zoffset = value;
  6068. SERIAL_ECHO(zprobe_zoffset);
  6069. }
  6070. else {
  6071. SERIAL_ECHOPAIR(MSG_Z_MIN, Z_PROBE_OFFSET_RANGE_MIN);
  6072. SERIAL_CHAR(' ');
  6073. SERIAL_ECHOPAIR(MSG_Z_MAX, Z_PROBE_OFFSET_RANGE_MAX);
  6074. }
  6075. }
  6076. else {
  6077. SERIAL_ECHOPAIR(": ", zprobe_zoffset);
  6078. }
  6079. SERIAL_EOL;
  6080. }
  6081. #endif // HAS_BED_PROBE
  6082. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  6083. millis_t next_buzz = 0;
  6084. unsigned long int runout_beep = 0;
  6085. void filament_change_beep() {
  6086. const millis_t ms = millis();
  6087. if (ELAPSED(ms, next_buzz)) {
  6088. if (runout_beep <= FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS + 5) { // Only beep as long as we're supposed to
  6089. next_buzz = ms + (runout_beep <= FILAMENT_CHANGE_NUMBER_OF_ALERT_BEEPS ? 2500 : 400);
  6090. BUZZ(300, 2000);
  6091. runout_beep++;
  6092. }
  6093. }
  6094. }
  6095. static bool busy_doing_M600 = false;
  6096. /**
  6097. * M600: Pause for filament change
  6098. *
  6099. * E[distance] - Retract the filament this far (negative value)
  6100. * Z[distance] - Move the Z axis by this distance
  6101. * X[position] - Move to this X position, with Y
  6102. * Y[position] - Move to this Y position, with X
  6103. * L[distance] - Retract distance for removal (manual reload)
  6104. *
  6105. * Default values are used for omitted arguments.
  6106. *
  6107. */
  6108. inline void gcode_M600() {
  6109. if (!DEBUGGING(DRYRUN) && thermalManager.tooColdToExtrude(active_extruder)) {
  6110. SERIAL_ERROR_START;
  6111. SERIAL_ERRORLNPGM(MSG_TOO_COLD_FOR_M600);
  6112. return;
  6113. }
  6114. busy_doing_M600 = true; // Stepper Motors can't timeout when this is set
  6115. // Pause the print job timer
  6116. bool job_running = print_job_timer.isRunning();
  6117. print_job_timer.pause();
  6118. // Show initial message and wait for synchronize steppers
  6119. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INIT);
  6120. stepper.synchronize();
  6121. float lastpos[NUM_AXIS];
  6122. // Save current position of all axes
  6123. LOOP_XYZE(i)
  6124. lastpos[i] = destination[i] = current_position[i];
  6125. // Define runplan for move axes
  6126. #if IS_KINEMATIC
  6127. #define RUNPLAN(RATE_MM_S) planner.buffer_line_kinematic(destination, RATE_MM_S, active_extruder);
  6128. #else
  6129. #define RUNPLAN(RATE_MM_S) line_to_destination(RATE_MM_S);
  6130. #endif
  6131. // Initial retract before move to filament change position
  6132. destination[E_AXIS] += code_seen('E') ? code_value_axis_units(E_AXIS) : 0
  6133. #if defined(FILAMENT_CHANGE_RETRACT_LENGTH) && FILAMENT_CHANGE_RETRACT_LENGTH > 0
  6134. - (FILAMENT_CHANGE_RETRACT_LENGTH)
  6135. #endif
  6136. ;
  6137. RUNPLAN(FILAMENT_CHANGE_RETRACT_FEEDRATE);
  6138. // Lift Z axis
  6139. float z_lift = code_seen('Z') ? code_value_axis_units(Z_AXIS) :
  6140. #if defined(FILAMENT_CHANGE_Z_ADD) && FILAMENT_CHANGE_Z_ADD > 0
  6141. FILAMENT_CHANGE_Z_ADD
  6142. #else
  6143. 0
  6144. #endif
  6145. ;
  6146. if (z_lift > 0) {
  6147. destination[Z_AXIS] += z_lift;
  6148. NOMORE(destination[Z_AXIS], Z_MAX_POS);
  6149. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  6150. }
  6151. // Move XY axes to filament exchange position
  6152. if (code_seen('X')) destination[X_AXIS] = code_value_axis_units(X_AXIS);
  6153. #ifdef FILAMENT_CHANGE_X_POS
  6154. else destination[X_AXIS] = FILAMENT_CHANGE_X_POS;
  6155. #endif
  6156. if (code_seen('Y')) destination[Y_AXIS] = code_value_axis_units(Y_AXIS);
  6157. #ifdef FILAMENT_CHANGE_Y_POS
  6158. else destination[Y_AXIS] = FILAMENT_CHANGE_Y_POS;
  6159. #endif
  6160. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  6161. stepper.synchronize();
  6162. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_UNLOAD);
  6163. idle();
  6164. // Unload filament
  6165. destination[E_AXIS] += code_seen('L') ? code_value_axis_units(E_AXIS) : 0
  6166. #if FILAMENT_CHANGE_UNLOAD_LENGTH > 0
  6167. - (FILAMENT_CHANGE_UNLOAD_LENGTH)
  6168. #endif
  6169. ;
  6170. RUNPLAN(FILAMENT_CHANGE_UNLOAD_FEEDRATE);
  6171. // Synchronize steppers and then disable extruders steppers for manual filament changing
  6172. stepper.synchronize();
  6173. disable_e0();
  6174. disable_e1();
  6175. disable_e2();
  6176. disable_e3();
  6177. delay(100);
  6178. millis_t nozzle_timeout = millis() + FILAMENT_CHANGE_NOZZLE_TIMEOUT * 1000L;
  6179. bool nozzle_timed_out = false;
  6180. float temps[4];
  6181. // Wait for filament insert by user and press button
  6182. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INSERT);
  6183. idle();
  6184. wait_for_user = true; // LCD click or M108 will clear this
  6185. next_buzz = 0;
  6186. runout_beep = 0;
  6187. HOTEND_LOOP() temps[e] = thermalManager.target_temperature[e]; // Save nozzle temps
  6188. while (wait_for_user) {
  6189. millis_t current_ms = millis();
  6190. if (nozzle_timed_out)
  6191. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  6192. #if HAS_BUZZER
  6193. filament_change_beep();
  6194. #endif
  6195. if (current_ms >= nozzle_timeout) {
  6196. if (!nozzle_timed_out) {
  6197. nozzle_timed_out = true; // on nozzle timeout remember the nozzles need to be reheated
  6198. HOTEND_LOOP() thermalManager.setTargetHotend(0, e); // Turn off all the nozzles
  6199. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_CLICK_TO_HEAT_NOZZLE);
  6200. }
  6201. }
  6202. idle(true);
  6203. }
  6204. if (nozzle_timed_out) // Turn nozzles back on if they were turned off
  6205. HOTEND_LOOP() thermalManager.setTargetHotend(temps[e], e);
  6206. // Show "wait for heating"
  6207. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_WAIT_FOR_NOZZLES_TO_HEAT);
  6208. wait_for_heatup = true;
  6209. while (wait_for_heatup) {
  6210. idle();
  6211. wait_for_heatup = false;
  6212. HOTEND_LOOP() {
  6213. if (abs(thermalManager.degHotend(e) - temps[e]) > 3) {
  6214. wait_for_heatup = true;
  6215. break;
  6216. }
  6217. }
  6218. }
  6219. // Show "insert filament"
  6220. if (nozzle_timed_out)
  6221. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_INSERT);
  6222. wait_for_user = true; // LCD click or M108 will clear this
  6223. next_buzz = 0;
  6224. runout_beep = 0;
  6225. while (wait_for_user && nozzle_timed_out) {
  6226. #if HAS_BUZZER
  6227. filament_change_beep();
  6228. #endif
  6229. idle(true);
  6230. }
  6231. // Show "load" message
  6232. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_LOAD);
  6233. // Load filament
  6234. destination[E_AXIS] += code_seen('L') ? -code_value_axis_units(E_AXIS) : 0
  6235. #if FILAMENT_CHANGE_LOAD_LENGTH > 0
  6236. + FILAMENT_CHANGE_LOAD_LENGTH
  6237. #endif
  6238. ;
  6239. RUNPLAN(FILAMENT_CHANGE_LOAD_FEEDRATE);
  6240. stepper.synchronize();
  6241. #if defined(FILAMENT_CHANGE_EXTRUDE_LENGTH) && FILAMENT_CHANGE_EXTRUDE_LENGTH > 0
  6242. do {
  6243. // "Wait for filament extrude"
  6244. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_EXTRUDE);
  6245. // Extrude filament to get into hotend
  6246. destination[E_AXIS] += FILAMENT_CHANGE_EXTRUDE_LENGTH;
  6247. RUNPLAN(FILAMENT_CHANGE_EXTRUDE_FEEDRATE);
  6248. stepper.synchronize();
  6249. // Show "Extrude More" / "Resume" menu and wait for reply
  6250. KEEPALIVE_STATE(PAUSED_FOR_USER);
  6251. wait_for_user = false;
  6252. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_OPTION);
  6253. while (filament_change_menu_response == FILAMENT_CHANGE_RESPONSE_WAIT_FOR) idle(true);
  6254. KEEPALIVE_STATE(IN_HANDLER);
  6255. // Keep looping if "Extrude More" was selected
  6256. } while (filament_change_menu_response == FILAMENT_CHANGE_RESPONSE_EXTRUDE_MORE);
  6257. #endif
  6258. // "Wait for print to resume"
  6259. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_RESUME);
  6260. // Set extruder to saved position
  6261. destination[E_AXIS] = current_position[E_AXIS] = lastpos[E_AXIS];
  6262. planner.set_e_position_mm(current_position[E_AXIS]);
  6263. #if IS_KINEMATIC
  6264. // Move XYZ to starting position
  6265. planner.buffer_line_kinematic(lastpos, FILAMENT_CHANGE_XY_FEEDRATE, active_extruder);
  6266. #else
  6267. // Move XY to starting position, then Z
  6268. destination[X_AXIS] = lastpos[X_AXIS];
  6269. destination[Y_AXIS] = lastpos[Y_AXIS];
  6270. RUNPLAN(FILAMENT_CHANGE_XY_FEEDRATE);
  6271. destination[Z_AXIS] = lastpos[Z_AXIS];
  6272. RUNPLAN(FILAMENT_CHANGE_Z_FEEDRATE);
  6273. #endif
  6274. stepper.synchronize();
  6275. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  6276. filament_ran_out = false;
  6277. #endif
  6278. // Show status screen
  6279. lcd_filament_change_show_message(FILAMENT_CHANGE_MESSAGE_STATUS);
  6280. // Resume the print job timer if it was running
  6281. if (job_running) print_job_timer.start();
  6282. busy_doing_M600 = false; // Allow Stepper Motors to be turned off during inactivity
  6283. }
  6284. #endif // FILAMENT_CHANGE_FEATURE
  6285. #if ENABLED(DUAL_X_CARRIAGE)
  6286. /**
  6287. * M605: Set dual x-carriage movement mode
  6288. *
  6289. * M605 S0: Full control mode. The slicer has full control over x-carriage movement
  6290. * M605 S1: Auto-park mode. The inactive head will auto park/unpark without slicer involvement
  6291. * M605 S2 [Xnnn] [Rmmm]: Duplication mode. The second extruder will duplicate the first with nnn
  6292. * units x-offset and an optional differential hotend temperature of
  6293. * mmm degrees. E.g., with "M605 S2 X100 R2" the second extruder will duplicate
  6294. * the first with a spacing of 100mm in the x direction and 2 degrees hotter.
  6295. *
  6296. * Note: the X axis should be homed after changing dual x-carriage mode.
  6297. */
  6298. inline void gcode_M605() {
  6299. stepper.synchronize();
  6300. if (code_seen('S')) dual_x_carriage_mode = (DualXMode)code_value_byte();
  6301. switch (dual_x_carriage_mode) {
  6302. case DXC_FULL_CONTROL_MODE:
  6303. case DXC_AUTO_PARK_MODE:
  6304. break;
  6305. case DXC_DUPLICATION_MODE:
  6306. if (code_seen('X')) duplicate_extruder_x_offset = max(code_value_axis_units(X_AXIS), X2_MIN_POS - x_home_pos(0));
  6307. if (code_seen('R')) duplicate_extruder_temp_offset = code_value_temp_diff();
  6308. SERIAL_ECHO_START;
  6309. SERIAL_ECHOPGM(MSG_HOTEND_OFFSET);
  6310. SERIAL_CHAR(' ');
  6311. SERIAL_ECHO(hotend_offset[X_AXIS][0]);
  6312. SERIAL_CHAR(',');
  6313. SERIAL_ECHO(hotend_offset[Y_AXIS][0]);
  6314. SERIAL_CHAR(' ');
  6315. SERIAL_ECHO(duplicate_extruder_x_offset);
  6316. SERIAL_CHAR(',');
  6317. SERIAL_ECHOLN(hotend_offset[Y_AXIS][1]);
  6318. break;
  6319. default:
  6320. dual_x_carriage_mode = DEFAULT_DUAL_X_CARRIAGE_MODE;
  6321. break;
  6322. }
  6323. active_extruder_parked = false;
  6324. extruder_duplication_enabled = false;
  6325. delayed_move_time = 0;
  6326. }
  6327. #elif ENABLED(DUAL_NOZZLE_DUPLICATION_MODE)
  6328. inline void gcode_M605() {
  6329. stepper.synchronize();
  6330. extruder_duplication_enabled = code_seen('S') && code_value_int() == 2;
  6331. SERIAL_ECHO_START;
  6332. SERIAL_ECHOLNPAIR(MSG_DUPLICATION_MODE, extruder_duplication_enabled ? MSG_ON : MSG_OFF);
  6333. }
  6334. #endif // DUAL_NOZZLE_DUPLICATION_MODE
  6335. #if ENABLED(LIN_ADVANCE)
  6336. /**
  6337. * M905: Set advance factor
  6338. */
  6339. inline void gcode_M905() {
  6340. stepper.synchronize();
  6341. const float newK = code_seen('K') ? code_value_float() : -1,
  6342. newD = code_seen('D') ? code_value_float() : -1,
  6343. newW = code_seen('W') ? code_value_float() : -1,
  6344. newH = code_seen('H') ? code_value_float() : -1;
  6345. if (newK >= 0.0) planner.set_extruder_advance_k(newK);
  6346. SERIAL_ECHO_START;
  6347. SERIAL_ECHOLNPAIR("Advance factor: ", planner.get_extruder_advance_k());
  6348. if (newD >= 0 || newW >= 0 || newH >= 0) {
  6349. const float ratio = (!newD || !newW || !newH) ? 0 : (newW * newH) / (sq(newD * 0.5) * M_PI);
  6350. planner.set_advance_ed_ratio(ratio);
  6351. SERIAL_ECHO_START;
  6352. SERIAL_ECHOPGM("E/D ratio: ");
  6353. if (ratio) SERIAL_ECHOLN(ratio); else SERIAL_ECHOLNPGM("Automatic");
  6354. }
  6355. }
  6356. #endif // LIN_ADVANCE
  6357. #if ENABLED(HAVE_TMC2130)
  6358. static void tmc2130_print_current(const int mA, const char name) {
  6359. SERIAL_CHAR(name);
  6360. SERIAL_ECHOPGM(" axis driver current: ");
  6361. SERIAL_ECHOLN(mA);
  6362. }
  6363. static void tmc2130_set_current(const int mA, TMC2130Stepper &st, const char name) {
  6364. tmc2130_print_current(mA, name);
  6365. st.setCurrent(mA, 0.11, 0.5);
  6366. }
  6367. static void tmc2130_get_current(TMC2130Stepper &st, const char name) {
  6368. tmc2130_print_current(st.getCurrent(), name);
  6369. }
  6370. static void tmc2130_report_otpw(TMC2130Stepper &st, const char name) {
  6371. SERIAL_CHAR(name);
  6372. SERIAL_ECHOPGM(" axis temperature prewarn triggered: ");
  6373. serialprintPGM(st.getOTPW() ? PSTR("true") : PSTR("false"));
  6374. }
  6375. static void tmc2130_clear_otpw(TMC2130Stepper &st, const char name) {
  6376. st.clear_otpw();
  6377. SERIAL_CHAR(name);
  6378. SERIAL_ECHOLNPGM(" prewarn flag cleared");
  6379. }
  6380. /**
  6381. * M906: Set motor current in milliamps using axis codes X, Y, Z, E
  6382. *
  6383. * Report driver currents when no axis specified
  6384. */
  6385. inline void gcode_M906() {
  6386. uint16_t values[NUM_AXIS];
  6387. LOOP_XYZE(i)
  6388. values[i] = code_seen(axis_codes[i]) ? code_value_int() : 0;
  6389. #if ENABLED(X_IS_TMC2130)
  6390. if (values[X_AXIS]) tmc2130_set_current(values[X_AXIS], stepperX, 'X');
  6391. else tmc2130_get_current(stepperX, 'X');
  6392. #endif
  6393. #if ENABLED(Y_IS_TMC2130)
  6394. if (values[Y_AXIS]) tmc2130_set_current(values[Y_AXIS], stepperY, 'Y');
  6395. else tmc2130_get_current(stepperY, 'Y');
  6396. #endif
  6397. #if ENABLED(Z_IS_TMC2130)
  6398. if (values[Z_AXIS]) tmc2130_set_current(values[Z_AXIS], stepperZ, 'Z');
  6399. else tmc2130_get_current(stepperZ, 'Z');
  6400. #endif
  6401. #if ENABLED(E0_IS_TMC2130)
  6402. if (values[E_AXIS]) tmc2130_set_current(values[E_AXIS], stepperE0, 'E');
  6403. else tmc2130_get_current(stepperE0, 'E');
  6404. #endif
  6405. }
  6406. /**
  6407. * M911: Report TMC2130 stepper driver overtemperature pre-warn flag
  6408. * The flag is held by the library and persist until manually cleared by M912
  6409. */
  6410. inline void gcode_M911() {
  6411. #if ENABLED(X_IS_TMC2130)
  6412. tmc2130_report_otpw(stepperX, 'X');
  6413. #endif
  6414. #if ENABLED(Y_IS_TMC2130)
  6415. tmc2130_report_otpw(stepperY, 'Y');
  6416. #endif
  6417. #if ENABLED(Z_IS_TMC2130)
  6418. tmc2130_report_otpw(stepperZ, 'Z');
  6419. #endif
  6420. #if ENABLED(E0_IS_TMC2130)
  6421. tmc2130_report_otpw(stepperE0, 'E');
  6422. #endif
  6423. }
  6424. /**
  6425. * M912: Clear TMC2130 stepper driver overtemperature pre-warn flag held by the library
  6426. */
  6427. inline void gcode_M912() {
  6428. #if ENABLED(X_IS_TMC2130)
  6429. if (code_seen('X')) tmc2130_clear_otpw(stepperX, 'X');
  6430. #endif
  6431. #if ENABLED(Y_IS_TMC2130)
  6432. if (code_seen('Y')) tmc2130_clear_otpw(stepperY, 'Y');
  6433. #endif
  6434. #if ENABLED(Z_IS_TMC2130)
  6435. if (code_seen('Z')) tmc2130_clear_otpw(stepperZ, 'Z');
  6436. #endif
  6437. #if ENABLED(E0_IS_TMC2130)
  6438. if (code_seen('E')) tmc2130_clear_otpw(stepperE0, 'E');
  6439. #endif
  6440. }
  6441. #endif // HAVE_TMC2130
  6442. /**
  6443. * M907: Set digital trimpot motor current using axis codes X, Y, Z, E, B, S
  6444. */
  6445. inline void gcode_M907() {
  6446. #if HAS_DIGIPOTSS
  6447. LOOP_XYZE(i)
  6448. if (code_seen(axis_codes[i])) stepper.digipot_current(i, code_value_int());
  6449. if (code_seen('B')) stepper.digipot_current(4, code_value_int());
  6450. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.digipot_current(i, code_value_int());
  6451. #elif HAS_MOTOR_CURRENT_PWM
  6452. #if PIN_EXISTS(MOTOR_CURRENT_PWM_XY)
  6453. if (code_seen('X')) stepper.digipot_current(0, code_value_int());
  6454. #endif
  6455. #if PIN_EXISTS(MOTOR_CURRENT_PWM_Z)
  6456. if (code_seen('Z')) stepper.digipot_current(1, code_value_int());
  6457. #endif
  6458. #if PIN_EXISTS(MOTOR_CURRENT_PWM_E)
  6459. if (code_seen('E')) stepper.digipot_current(2, code_value_int());
  6460. #endif
  6461. #endif
  6462. #if ENABLED(DIGIPOT_I2C)
  6463. // this one uses actual amps in floating point
  6464. LOOP_XYZE(i) if (code_seen(axis_codes[i])) digipot_i2c_set_current(i, code_value_float());
  6465. // for each additional extruder (named B,C,D,E..., channels 4,5,6,7...)
  6466. for (int i = NUM_AXIS; i < DIGIPOT_I2C_NUM_CHANNELS; i++) if (code_seen('B' + i - (NUM_AXIS))) digipot_i2c_set_current(i, code_value_float());
  6467. #endif
  6468. #if ENABLED(DAC_STEPPER_CURRENT)
  6469. if (code_seen('S')) {
  6470. float dac_percent = code_value_float();
  6471. for (uint8_t i = 0; i <= 4; i++) dac_current_percent(i, dac_percent);
  6472. }
  6473. LOOP_XYZE(i) if (code_seen(axis_codes[i])) dac_current_percent(i, code_value_float());
  6474. #endif
  6475. }
  6476. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  6477. /**
  6478. * M908: Control digital trimpot directly (M908 P<pin> S<current>)
  6479. */
  6480. inline void gcode_M908() {
  6481. #if HAS_DIGIPOTSS
  6482. stepper.digitalPotWrite(
  6483. code_seen('P') ? code_value_int() : 0,
  6484. code_seen('S') ? code_value_int() : 0
  6485. );
  6486. #endif
  6487. #ifdef DAC_STEPPER_CURRENT
  6488. dac_current_raw(
  6489. code_seen('P') ? code_value_byte() : -1,
  6490. code_seen('S') ? code_value_ushort() : 0
  6491. );
  6492. #endif
  6493. }
  6494. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  6495. inline void gcode_M909() { dac_print_values(); }
  6496. inline void gcode_M910() { dac_commit_eeprom(); }
  6497. #endif
  6498. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  6499. #if HAS_MICROSTEPS
  6500. // M350 Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  6501. inline void gcode_M350() {
  6502. if (code_seen('S')) for (int i = 0; i <= 4; i++) stepper.microstep_mode(i, code_value_byte());
  6503. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_mode(i, code_value_byte());
  6504. if (code_seen('B')) stepper.microstep_mode(4, code_value_byte());
  6505. stepper.microstep_readings();
  6506. }
  6507. /**
  6508. * M351: Toggle MS1 MS2 pins directly with axis codes X Y Z E B
  6509. * S# determines MS1 or MS2, X# sets the pin high/low.
  6510. */
  6511. inline void gcode_M351() {
  6512. if (code_seen('S')) switch (code_value_byte()) {
  6513. case 1:
  6514. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, code_value_byte(), -1);
  6515. if (code_seen('B')) stepper.microstep_ms(4, code_value_byte(), -1);
  6516. break;
  6517. case 2:
  6518. LOOP_XYZE(i) if (code_seen(axis_codes[i])) stepper.microstep_ms(i, -1, code_value_byte());
  6519. if (code_seen('B')) stepper.microstep_ms(4, -1, code_value_byte());
  6520. break;
  6521. }
  6522. stepper.microstep_readings();
  6523. }
  6524. #endif // HAS_MICROSTEPS
  6525. #if HAS_CASE_LIGHT
  6526. uint8_t case_light_brightness = 255;
  6527. void update_case_light() {
  6528. digitalWrite(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? HIGH : LOW);
  6529. analogWrite(CASE_LIGHT_PIN, case_light_on != INVERT_CASE_LIGHT ? case_light_brightness : 0);
  6530. }
  6531. #endif // HAS_CASE_LIGHT
  6532. /**
  6533. * M355: Turn case lights on/off and set brightness
  6534. *
  6535. * S<bool> Turn case light on or off
  6536. * P<byte> Set case light brightness (PWM pin required)
  6537. */
  6538. inline void gcode_M355() {
  6539. #if HAS_CASE_LIGHT
  6540. if (code_seen('P')) case_light_brightness = code_value_byte();
  6541. if (code_seen('S')) case_light_on = code_value_bool();
  6542. update_case_light();
  6543. SERIAL_ECHO_START;
  6544. SERIAL_ECHOPGM("Case lights ");
  6545. case_light_on ? SERIAL_ECHOLNPGM("on") : SERIAL_ECHOLNPGM("off");
  6546. #else
  6547. SERIAL_ERROR_START;
  6548. SERIAL_ERRORLNPGM(MSG_ERR_M355_NONE);
  6549. #endif // HAS_CASE_LIGHT
  6550. }
  6551. #if ENABLED(MIXING_EXTRUDER)
  6552. /**
  6553. * M163: Set a single mix factor for a mixing extruder
  6554. * This is called "weight" by some systems.
  6555. *
  6556. * S[index] The channel index to set
  6557. * P[float] The mix value
  6558. *
  6559. */
  6560. inline void gcode_M163() {
  6561. int mix_index = code_seen('S') ? code_value_int() : 0;
  6562. if (mix_index < MIXING_STEPPERS) {
  6563. float mix_value = code_seen('P') ? code_value_float() : 0.0;
  6564. NOLESS(mix_value, 0.0);
  6565. mixing_factor[mix_index] = RECIPROCAL(mix_value);
  6566. }
  6567. }
  6568. #if MIXING_VIRTUAL_TOOLS > 1
  6569. /**
  6570. * M164: Store the current mix factors as a virtual tool.
  6571. *
  6572. * S[index] The virtual tool to store
  6573. *
  6574. */
  6575. inline void gcode_M164() {
  6576. int tool_index = code_seen('S') ? code_value_int() : 0;
  6577. if (tool_index < MIXING_VIRTUAL_TOOLS) {
  6578. normalize_mix();
  6579. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  6580. mixing_virtual_tool_mix[tool_index][i] = mixing_factor[i];
  6581. }
  6582. }
  6583. #endif
  6584. #if ENABLED(DIRECT_MIXING_IN_G1)
  6585. /**
  6586. * M165: Set multiple mix factors for a mixing extruder.
  6587. * Factors that are left out will be set to 0.
  6588. * All factors together must add up to 1.0.
  6589. *
  6590. * A[factor] Mix factor for extruder stepper 1
  6591. * B[factor] Mix factor for extruder stepper 2
  6592. * C[factor] Mix factor for extruder stepper 3
  6593. * D[factor] Mix factor for extruder stepper 4
  6594. * H[factor] Mix factor for extruder stepper 5
  6595. * I[factor] Mix factor for extruder stepper 6
  6596. *
  6597. */
  6598. inline void gcode_M165() { gcode_get_mix(); }
  6599. #endif
  6600. #endif // MIXING_EXTRUDER
  6601. /**
  6602. * M999: Restart after being stopped
  6603. *
  6604. * Default behaviour is to flush the serial buffer and request
  6605. * a resend to the host starting on the last N line received.
  6606. *
  6607. * Sending "M999 S1" will resume printing without flushing the
  6608. * existing command buffer.
  6609. *
  6610. */
  6611. inline void gcode_M999() {
  6612. Running = true;
  6613. lcd_reset_alert_level();
  6614. if (code_seen('S') && code_value_bool()) return;
  6615. // gcode_LastN = Stopped_gcode_LastN;
  6616. FlushSerialRequestResend();
  6617. }
  6618. #if ENABLED(SWITCHING_EXTRUDER)
  6619. inline void move_extruder_servo(uint8_t e) {
  6620. const int angles[2] = SWITCHING_EXTRUDER_SERVO_ANGLES;
  6621. MOVE_SERVO(SWITCHING_EXTRUDER_SERVO_NR, angles[e]);
  6622. }
  6623. #endif
  6624. inline void invalid_extruder_error(const uint8_t &e) {
  6625. SERIAL_ECHO_START;
  6626. SERIAL_CHAR('T');
  6627. SERIAL_PROTOCOL_F(e, DEC);
  6628. SERIAL_ECHOLN(MSG_INVALID_EXTRUDER);
  6629. }
  6630. /**
  6631. * Perform a tool-change, which may result in moving the
  6632. * previous tool out of the way and the new tool into place.
  6633. */
  6634. void tool_change(const uint8_t tmp_extruder, const float fr_mm_s/*=0.0*/, bool no_move/*=false*/) {
  6635. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  6636. if (tmp_extruder >= MIXING_VIRTUAL_TOOLS)
  6637. return invalid_extruder_error(tmp_extruder);
  6638. // T0-Tnnn: Switch virtual tool by changing the mix
  6639. for (uint8_t j = 0; j < MIXING_STEPPERS; j++)
  6640. mixing_factor[j] = mixing_virtual_tool_mix[tmp_extruder][j];
  6641. #else //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  6642. #if HOTENDS > 1
  6643. if (tmp_extruder >= EXTRUDERS)
  6644. return invalid_extruder_error(tmp_extruder);
  6645. const float old_feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : feedrate_mm_s;
  6646. feedrate_mm_s = fr_mm_s > 0.0 ? fr_mm_s : XY_PROBE_FEEDRATE_MM_S;
  6647. if (tmp_extruder != active_extruder) {
  6648. if (!no_move && axis_unhomed_error(true, true, true)) {
  6649. SERIAL_ECHOLNPGM("No move on toolchange");
  6650. no_move = true;
  6651. }
  6652. // Save current position to destination, for use later
  6653. set_destination_to_current();
  6654. #if ENABLED(DUAL_X_CARRIAGE)
  6655. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6656. if (DEBUGGING(LEVELING)) {
  6657. SERIAL_ECHOPGM("Dual X Carriage Mode ");
  6658. switch (dual_x_carriage_mode) {
  6659. case DXC_FULL_CONTROL_MODE: SERIAL_ECHOLNPGM("DXC_FULL_CONTROL_MODE"); break;
  6660. case DXC_AUTO_PARK_MODE: SERIAL_ECHOLNPGM("DXC_AUTO_PARK_MODE"); break;
  6661. case DXC_DUPLICATION_MODE: SERIAL_ECHOLNPGM("DXC_DUPLICATION_MODE"); break;
  6662. }
  6663. }
  6664. #endif
  6665. const float xhome = x_home_pos(active_extruder);
  6666. if (dual_x_carriage_mode == DXC_AUTO_PARK_MODE
  6667. && IsRunning()
  6668. && (delayed_move_time || current_position[X_AXIS] != xhome)
  6669. ) {
  6670. float raised_z = current_position[Z_AXIS] + TOOLCHANGE_PARK_ZLIFT;
  6671. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  6672. NOMORE(raised_z, soft_endstop_max[Z_AXIS]);
  6673. #endif
  6674. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6675. if (DEBUGGING(LEVELING)) {
  6676. SERIAL_ECHOLNPAIR("Raise to ", raised_z);
  6677. SERIAL_ECHOLNPAIR("MoveX to ", xhome);
  6678. SERIAL_ECHOLNPAIR("Lower to ", current_position[Z_AXIS]);
  6679. }
  6680. #endif
  6681. // Park old head: 1) raise 2) move to park position 3) lower
  6682. for (uint8_t i = 0; i < 3; i++)
  6683. planner.buffer_line(
  6684. i == 0 ? current_position[X_AXIS] : xhome,
  6685. current_position[Y_AXIS],
  6686. i == 2 ? current_position[Z_AXIS] : raised_z,
  6687. current_position[E_AXIS],
  6688. planner.max_feedrate_mm_s[i == 1 ? X_AXIS : Z_AXIS],
  6689. active_extruder
  6690. );
  6691. stepper.synchronize();
  6692. }
  6693. // Apply Y & Z extruder offset (X offset is used as home pos with Dual X)
  6694. current_position[Y_AXIS] -= hotend_offset[Y_AXIS][active_extruder] - hotend_offset[Y_AXIS][tmp_extruder];
  6695. current_position[Z_AXIS] -= hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder];
  6696. // Activate the new extruder
  6697. active_extruder = tmp_extruder;
  6698. // This function resets the max/min values - the current position may be overwritten below.
  6699. set_axis_is_at_home(X_AXIS);
  6700. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6701. if (DEBUGGING(LEVELING)) DEBUG_POS("New Extruder", current_position);
  6702. #endif
  6703. // Only when auto-parking are carriages safe to move
  6704. if (dual_x_carriage_mode != DXC_AUTO_PARK_MODE) no_move = true;
  6705. switch (dual_x_carriage_mode) {
  6706. case DXC_FULL_CONTROL_MODE:
  6707. // New current position is the position of the activated extruder
  6708. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  6709. // Save the inactive extruder's position (from the old current_position)
  6710. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  6711. break;
  6712. case DXC_AUTO_PARK_MODE:
  6713. // record raised toolhead position for use by unpark
  6714. COPY(raised_parked_position, current_position);
  6715. raised_parked_position[Z_AXIS] += TOOLCHANGE_UNPARK_ZLIFT;
  6716. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  6717. NOMORE(raised_parked_position[Z_AXIS], soft_endstop_max[Z_AXIS]);
  6718. #endif
  6719. active_extruder_parked = true;
  6720. delayed_move_time = 0;
  6721. break;
  6722. case DXC_DUPLICATION_MODE:
  6723. // If the new extruder is the left one, set it "parked"
  6724. // This triggers the second extruder to move into the duplication position
  6725. active_extruder_parked = (active_extruder == 0);
  6726. if (active_extruder_parked)
  6727. current_position[X_AXIS] = LOGICAL_X_POSITION(inactive_extruder_x_pos);
  6728. else
  6729. current_position[X_AXIS] = destination[X_AXIS] + duplicate_extruder_x_offset;
  6730. inactive_extruder_x_pos = RAW_X_POSITION(destination[X_AXIS]);
  6731. extruder_duplication_enabled = false;
  6732. break;
  6733. }
  6734. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6735. if (DEBUGGING(LEVELING)) {
  6736. SERIAL_ECHOLNPAIR("Active extruder parked: ", active_extruder_parked ? "yes" : "no");
  6737. DEBUG_POS("New extruder (parked)", current_position);
  6738. }
  6739. #endif
  6740. // No extra case for HAS_ABL in DUAL_X_CARRIAGE. Does that mean they don't work together?
  6741. #else // !DUAL_X_CARRIAGE
  6742. #if ENABLED(SWITCHING_EXTRUDER)
  6743. // <0 if the new nozzle is higher, >0 if lower. A bigger raise when lower.
  6744. float z_diff = hotend_offset[Z_AXIS][active_extruder] - hotend_offset[Z_AXIS][tmp_extruder],
  6745. z_raise = 0.3 + (z_diff > 0.0 ? z_diff : 0.0);
  6746. // Always raise by some amount (destination copied from current_position earlier)
  6747. float save_Z = destination[Z_AXIS]; // save Z for later on
  6748. destination[Z_AXIS] += z_raise;
  6749. planner.buffer_line_kinematic(destination, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  6750. stepper.synchronize();
  6751. move_extruder_servo(active_extruder);
  6752. delay(500);
  6753. // Move back down, if needed
  6754. if (z_raise != z_diff) {
  6755. destination[Z_AXIS] = current_position[Z_AXIS] + z_diff;
  6756. planner.buffer_line_kinematic(destination, planner.max_feedrate_mm_s[Z_AXIS], active_extruder);
  6757. stepper.synchronize();
  6758. }
  6759. destination[Z_AXIS] = save_Z; // restore original Z position so the 'Move to the "old position"' is correct
  6760. #endif
  6761. /**
  6762. * Set current_position to the position of the new nozzle.
  6763. * Offsets are based on linear distance, so we need to get
  6764. * the resulting position in coordinate space.
  6765. *
  6766. * - With grid or 3-point leveling, offset XYZ by a tilted vector
  6767. * - With mesh leveling, update Z for the new position
  6768. * - Otherwise, just use the raw linear distance
  6769. *
  6770. * Software endstops are altered here too. Consider a case where:
  6771. * E0 at X=0 ... E1 at X=10
  6772. * When we switch to E1 now X=10, but E1 can't move left.
  6773. * To express this we apply the change in XY to the software endstops.
  6774. * E1 can move farther right than E0, so the right limit is extended.
  6775. *
  6776. * Note that we don't adjust the Z software endstops. Why not?
  6777. * Consider a case where Z=0 (here) and switching to E1 makes Z=1
  6778. * because the bed is 1mm lower at the new position. As long as
  6779. * the first nozzle is out of the way, the carriage should be
  6780. * allowed to move 1mm lower. This technically "breaks" the
  6781. * Z software endstop. But this is technically correct (and
  6782. * there is no viable alternative).
  6783. */
  6784. #if ABL_PLANAR
  6785. // Offset extruder, make sure to apply the bed level rotation matrix
  6786. vector_3 tmp_offset_vec = vector_3(hotend_offset[X_AXIS][tmp_extruder],
  6787. hotend_offset[Y_AXIS][tmp_extruder],
  6788. 0),
  6789. act_offset_vec = vector_3(hotend_offset[X_AXIS][active_extruder],
  6790. hotend_offset[Y_AXIS][active_extruder],
  6791. 0),
  6792. offset_vec = tmp_offset_vec - act_offset_vec;
  6793. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6794. if (DEBUGGING(LEVELING)) {
  6795. tmp_offset_vec.debug("tmp_offset_vec");
  6796. act_offset_vec.debug("act_offset_vec");
  6797. offset_vec.debug("offset_vec (BEFORE)");
  6798. }
  6799. #endif
  6800. offset_vec.apply_rotation(planner.bed_level_matrix.transpose(planner.bed_level_matrix));
  6801. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6802. if (DEBUGGING(LEVELING)) offset_vec.debug("offset_vec (AFTER)");
  6803. #endif
  6804. // Adjustments to the current position
  6805. float xydiff[2] = { offset_vec.x, offset_vec.y };
  6806. current_position[Z_AXIS] += offset_vec.z;
  6807. #else // !ABL_PLANAR
  6808. float xydiff[2] = {
  6809. hotend_offset[X_AXIS][tmp_extruder] - hotend_offset[X_AXIS][active_extruder],
  6810. hotend_offset[Y_AXIS][tmp_extruder] - hotend_offset[Y_AXIS][active_extruder]
  6811. };
  6812. #if ENABLED(MESH_BED_LEVELING)
  6813. if (mbl.active()) {
  6814. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6815. if (DEBUGGING(LEVELING)) SERIAL_ECHOPAIR("Z before MBL: ", current_position[Z_AXIS]);
  6816. #endif
  6817. float x2 = current_position[X_AXIS] + xydiff[X_AXIS],
  6818. y2 = current_position[Y_AXIS] + xydiff[Y_AXIS],
  6819. z1 = current_position[Z_AXIS], z2 = z1;
  6820. planner.apply_leveling(current_position[X_AXIS], current_position[Y_AXIS], z1);
  6821. planner.apply_leveling(x2, y2, z2);
  6822. current_position[Z_AXIS] += z2 - z1;
  6823. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6824. if (DEBUGGING(LEVELING))
  6825. SERIAL_ECHOLNPAIR(" after: ", current_position[Z_AXIS]);
  6826. #endif
  6827. }
  6828. #endif // MESH_BED_LEVELING
  6829. #endif // !HAS_ABL
  6830. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6831. if (DEBUGGING(LEVELING)) {
  6832. SERIAL_ECHOPAIR("Offset Tool XY by { ", xydiff[X_AXIS]);
  6833. SERIAL_ECHOPAIR(", ", xydiff[Y_AXIS]);
  6834. SERIAL_ECHOLNPGM(" }");
  6835. }
  6836. #endif
  6837. // The newly-selected extruder XY is actually at...
  6838. current_position[X_AXIS] += xydiff[X_AXIS];
  6839. current_position[Y_AXIS] += xydiff[Y_AXIS];
  6840. #if DISABLED(NO_WORKSPACE_OFFSETS) || ENABLED(DUAL_X_CARRIAGE)
  6841. for (uint8_t i = X_AXIS; i <= Y_AXIS; i++) {
  6842. #if DISABLED(NO_WORKSPACE_OFFSETS)
  6843. position_shift[i] += xydiff[i];
  6844. #endif
  6845. update_software_endstops((AxisEnum)i);
  6846. }
  6847. #endif
  6848. // Set the new active extruder
  6849. active_extruder = tmp_extruder;
  6850. #endif // !DUAL_X_CARRIAGE
  6851. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6852. if (DEBUGGING(LEVELING)) DEBUG_POS("Sync After Toolchange", current_position);
  6853. #endif
  6854. // Tell the planner the new "current position"
  6855. SYNC_PLAN_POSITION_KINEMATIC();
  6856. // Move to the "old position" (move the extruder into place)
  6857. if (!no_move && IsRunning()) {
  6858. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6859. if (DEBUGGING(LEVELING)) DEBUG_POS("Move back", destination);
  6860. #endif
  6861. prepare_move_to_destination();
  6862. }
  6863. } // (tmp_extruder != active_extruder)
  6864. stepper.synchronize();
  6865. #if ENABLED(EXT_SOLENOID)
  6866. disable_all_solenoids();
  6867. enable_solenoid_on_active_extruder();
  6868. #endif // EXT_SOLENOID
  6869. feedrate_mm_s = old_feedrate_mm_s;
  6870. #else // HOTENDS <= 1
  6871. // Set the new active extruder
  6872. active_extruder = tmp_extruder;
  6873. UNUSED(fr_mm_s);
  6874. UNUSED(no_move);
  6875. #endif // HOTENDS <= 1
  6876. SERIAL_ECHO_START;
  6877. SERIAL_ECHOLNPAIR(MSG_ACTIVE_EXTRUDER, (int)active_extruder);
  6878. #endif //!MIXING_EXTRUDER || MIXING_VIRTUAL_TOOLS <= 1
  6879. }
  6880. /**
  6881. * T0-T3: Switch tool, usually switching extruders
  6882. *
  6883. * F[units/min] Set the movement feedrate
  6884. * S1 Don't move the tool in XY after change
  6885. */
  6886. inline void gcode_T(uint8_t tmp_extruder) {
  6887. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6888. if (DEBUGGING(LEVELING)) {
  6889. SERIAL_ECHOPAIR(">>> gcode_T(", tmp_extruder);
  6890. SERIAL_CHAR(')');
  6891. SERIAL_EOL;
  6892. DEBUG_POS("BEFORE", current_position);
  6893. }
  6894. #endif
  6895. #if HOTENDS == 1 || (ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1)
  6896. tool_change(tmp_extruder);
  6897. #elif HOTENDS > 1
  6898. tool_change(
  6899. tmp_extruder,
  6900. code_seen('F') ? MMM_TO_MMS(code_value_axis_units(X_AXIS)) : 0.0,
  6901. (tmp_extruder == active_extruder) || (code_seen('S') && code_value_bool())
  6902. );
  6903. #endif
  6904. #if ENABLED(DEBUG_LEVELING_FEATURE)
  6905. if (DEBUGGING(LEVELING)) {
  6906. DEBUG_POS("AFTER", current_position);
  6907. SERIAL_ECHOLNPGM("<<< gcode_T");
  6908. }
  6909. #endif
  6910. }
  6911. /**
  6912. * Process a single command and dispatch it to its handler
  6913. * This is called from the main loop()
  6914. */
  6915. void process_next_command() {
  6916. current_command = command_queue[cmd_queue_index_r];
  6917. if (DEBUGGING(ECHO)) {
  6918. SERIAL_ECHO_START;
  6919. SERIAL_ECHOLN(current_command);
  6920. }
  6921. // Sanitize the current command:
  6922. // - Skip leading spaces
  6923. // - Bypass N[-0-9][0-9]*[ ]*
  6924. // - Overwrite * with nul to mark the end
  6925. while (*current_command == ' ') ++current_command;
  6926. if (*current_command == 'N' && NUMERIC_SIGNED(current_command[1])) {
  6927. current_command += 2; // skip N[-0-9]
  6928. while (NUMERIC(*current_command)) ++current_command; // skip [0-9]*
  6929. while (*current_command == ' ') ++current_command; // skip [ ]*
  6930. }
  6931. char* starpos = strchr(current_command, '*'); // * should always be the last parameter
  6932. if (starpos) while (*starpos == ' ' || *starpos == '*') *starpos-- = '\0'; // nullify '*' and ' '
  6933. char *cmd_ptr = current_command;
  6934. // Get the command code, which must be G, M, or T
  6935. char command_code = *cmd_ptr++;
  6936. // Skip spaces to get the numeric part
  6937. while (*cmd_ptr == ' ') cmd_ptr++;
  6938. // Allow for decimal point in command
  6939. #if ENABLED(G38_PROBE_TARGET)
  6940. uint8_t subcode = 0;
  6941. #endif
  6942. uint16_t codenum = 0; // define ahead of goto
  6943. // Bail early if there's no code
  6944. bool code_is_good = NUMERIC(*cmd_ptr);
  6945. if (!code_is_good) goto ExitUnknownCommand;
  6946. // Get and skip the code number
  6947. do {
  6948. codenum = (codenum * 10) + (*cmd_ptr - '0');
  6949. cmd_ptr++;
  6950. } while (NUMERIC(*cmd_ptr));
  6951. // Allow for decimal point in command
  6952. #if ENABLED(G38_PROBE_TARGET)
  6953. if (*cmd_ptr == '.') {
  6954. cmd_ptr++;
  6955. while (NUMERIC(*cmd_ptr))
  6956. subcode = (subcode * 10) + (*cmd_ptr++ - '0');
  6957. }
  6958. #endif
  6959. // Skip all spaces to get to the first argument, or nul
  6960. while (*cmd_ptr == ' ') cmd_ptr++;
  6961. // The command's arguments (if any) start here, for sure!
  6962. current_command_args = cmd_ptr;
  6963. KEEPALIVE_STATE(IN_HANDLER);
  6964. // Handle a known G, M, or T
  6965. switch (command_code) {
  6966. case 'G': switch (codenum) {
  6967. // G0, G1
  6968. case 0:
  6969. case 1:
  6970. #if IS_SCARA
  6971. gcode_G0_G1(codenum == 0);
  6972. #else
  6973. gcode_G0_G1();
  6974. #endif
  6975. break;
  6976. // G2, G3
  6977. #if ENABLED(ARC_SUPPORT) && DISABLED(SCARA)
  6978. case 2: // G2 - CW ARC
  6979. case 3: // G3 - CCW ARC
  6980. gcode_G2_G3(codenum == 2);
  6981. break;
  6982. #endif
  6983. // G4 Dwell
  6984. case 4:
  6985. gcode_G4();
  6986. break;
  6987. #if ENABLED(BEZIER_CURVE_SUPPORT)
  6988. // G5
  6989. case 5: // G5 - Cubic B_spline
  6990. gcode_G5();
  6991. break;
  6992. #endif // BEZIER_CURVE_SUPPORT
  6993. #if ENABLED(FWRETRACT)
  6994. case 10: // G10: retract
  6995. case 11: // G11: retract_recover
  6996. gcode_G10_G11(codenum == 10);
  6997. break;
  6998. #endif // FWRETRACT
  6999. #if ENABLED(NOZZLE_CLEAN_FEATURE)
  7000. case 12:
  7001. gcode_G12(); // G12: Nozzle Clean
  7002. break;
  7003. #endif // NOZZLE_CLEAN_FEATURE
  7004. #if ENABLED(INCH_MODE_SUPPORT)
  7005. case 20: //G20: Inch Mode
  7006. gcode_G20();
  7007. break;
  7008. case 21: //G21: MM Mode
  7009. gcode_G21();
  7010. break;
  7011. #endif // INCH_MODE_SUPPORT
  7012. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7013. case 26: // G26: Mesh Validation Pattern generation
  7014. gcode_G26();
  7015. break;
  7016. #endif // AUTO_BED_LEVELING_UBL
  7017. #if ENABLED(NOZZLE_PARK_FEATURE)
  7018. case 27: // G27: Nozzle Park
  7019. gcode_G27();
  7020. break;
  7021. #endif // NOZZLE_PARK_FEATURE
  7022. case 28: // G28: Home all axes, one at a time
  7023. gcode_G28();
  7024. break;
  7025. #if PLANNER_LEVELING
  7026. case 29: // G29 Detailed Z probe, probes the bed at 3 or more points,
  7027. // or provides access to the UBL System if enabled.
  7028. gcode_G29();
  7029. break;
  7030. #endif // PLANNER_LEVELING
  7031. #if HAS_BED_PROBE
  7032. case 30: // G30 Single Z probe
  7033. gcode_G30();
  7034. break;
  7035. #if ENABLED(Z_PROBE_SLED)
  7036. case 31: // G31: dock the sled
  7037. gcode_G31();
  7038. break;
  7039. case 32: // G32: undock the sled
  7040. gcode_G32();
  7041. break;
  7042. #endif // Z_PROBE_SLED
  7043. #endif // HAS_BED_PROBE
  7044. #if ENABLED(G38_PROBE_TARGET)
  7045. case 38: // G38.2 & G38.3
  7046. if (subcode == 2 || subcode == 3)
  7047. gcode_G38(subcode == 2);
  7048. break;
  7049. #endif
  7050. case 90: // G90
  7051. relative_mode = false;
  7052. break;
  7053. case 91: // G91
  7054. relative_mode = true;
  7055. break;
  7056. case 92: // G92
  7057. gcode_G92();
  7058. break;
  7059. }
  7060. break;
  7061. case 'M': switch (codenum) {
  7062. #if ENABLED(ULTIPANEL) || ENABLED(EMERGENCY_PARSER)
  7063. case 0: // M0: Unconditional stop - Wait for user button press on LCD
  7064. case 1: // M1: Conditional stop - Wait for user button press on LCD
  7065. gcode_M0_M1();
  7066. break;
  7067. #endif // ULTIPANEL
  7068. case 17: // M17: Enable all stepper motors
  7069. gcode_M17();
  7070. break;
  7071. #if ENABLED(SDSUPPORT)
  7072. case 20: // M20: list SD card
  7073. gcode_M20(); break;
  7074. case 21: // M21: init SD card
  7075. gcode_M21(); break;
  7076. case 22: // M22: release SD card
  7077. gcode_M22(); break;
  7078. case 23: // M23: Select file
  7079. gcode_M23(); break;
  7080. case 24: // M24: Start SD print
  7081. gcode_M24(); break;
  7082. case 25: // M25: Pause SD print
  7083. gcode_M25(); break;
  7084. case 26: // M26: Set SD index
  7085. gcode_M26(); break;
  7086. case 27: // M27: Get SD status
  7087. gcode_M27(); break;
  7088. case 28: // M28: Start SD write
  7089. gcode_M28(); break;
  7090. case 29: // M29: Stop SD write
  7091. gcode_M29(); break;
  7092. case 30: // M30 <filename> Delete File
  7093. gcode_M30(); break;
  7094. case 32: // M32: Select file and start SD print
  7095. gcode_M32(); break;
  7096. #if ENABLED(LONG_FILENAME_HOST_SUPPORT)
  7097. case 33: // M33: Get the long full path to a file or folder
  7098. gcode_M33(); break;
  7099. #endif
  7100. #if ENABLED(SDCARD_SORT_ALPHA) && ENABLED(SDSORT_GCODE)
  7101. case 34: //M34 - Set SD card sorting options
  7102. gcode_M34(); break;
  7103. #endif // SDCARD_SORT_ALPHA && SDSORT_GCODE
  7104. case 928: // M928: Start SD write
  7105. gcode_M928(); break;
  7106. #endif //SDSUPPORT
  7107. case 31: // M31: Report time since the start of SD print or last M109
  7108. gcode_M31(); break;
  7109. case 42: // M42: Change pin state
  7110. gcode_M42(); break;
  7111. #if ENABLED(PINS_DEBUGGING)
  7112. case 43: // M43: Read pin state
  7113. gcode_M43(); break;
  7114. #endif
  7115. #if ENABLED(Z_MIN_PROBE_REPEATABILITY_TEST)
  7116. case 48: // M48: Z probe repeatability test
  7117. gcode_M48();
  7118. break;
  7119. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  7120. #if ENABLED(AUTO_BED_LEVELING_UBL)
  7121. case 49: // M49: Turn on or off G26_Debug_flag for verbose output
  7122. if (G26_Debug_flag) {
  7123. SERIAL_PROTOCOLPGM("UBL Debug Flag turned off.\n");
  7124. G26_Debug_flag = 0; }
  7125. else {
  7126. SERIAL_PROTOCOLPGM("UBL Debug Flag turned on.\n");
  7127. G26_Debug_flag++; }
  7128. break;
  7129. #endif // Z_MIN_PROBE_REPEATABILITY_TEST
  7130. case 75: // M75: Start print timer
  7131. gcode_M75(); break;
  7132. case 76: // M76: Pause print timer
  7133. gcode_M76(); break;
  7134. case 77: // M77: Stop print timer
  7135. gcode_M77(); break;
  7136. #if ENABLED(PRINTCOUNTER)
  7137. case 78: // M78: Show print statistics
  7138. gcode_M78(); break;
  7139. #endif
  7140. #if ENABLED(M100_FREE_MEMORY_WATCHER)
  7141. case 100: // M100: Free Memory Report
  7142. gcode_M100();
  7143. break;
  7144. #endif
  7145. case 104: // M104: Set hot end temperature
  7146. gcode_M104();
  7147. break;
  7148. case 110: // M110: Set Current Line Number
  7149. gcode_M110();
  7150. break;
  7151. case 111: // M111: Set debug level
  7152. gcode_M111();
  7153. break;
  7154. #if DISABLED(EMERGENCY_PARSER)
  7155. case 108: // M108: Cancel Waiting
  7156. gcode_M108();
  7157. break;
  7158. case 112: // M112: Emergency Stop
  7159. gcode_M112();
  7160. break;
  7161. case 410: // M410 quickstop - Abort all the planned moves.
  7162. gcode_M410();
  7163. break;
  7164. #endif
  7165. #if ENABLED(HOST_KEEPALIVE_FEATURE)
  7166. case 113: // M113: Set Host Keepalive interval
  7167. gcode_M113();
  7168. break;
  7169. #endif
  7170. case 140: // M140: Set bed temperature
  7171. gcode_M140();
  7172. break;
  7173. case 105: // M105: Report current temperature
  7174. gcode_M105();
  7175. KEEPALIVE_STATE(NOT_BUSY);
  7176. return; // "ok" already printed
  7177. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  7178. case 155: // M155: Set temperature auto-report interval
  7179. gcode_M155();
  7180. break;
  7181. #endif
  7182. case 109: // M109: Wait for hotend temperature to reach target
  7183. gcode_M109();
  7184. break;
  7185. #if HAS_TEMP_BED
  7186. case 190: // M190: Wait for bed temperature to reach target
  7187. gcode_M190();
  7188. break;
  7189. #endif // HAS_TEMP_BED
  7190. #if FAN_COUNT > 0
  7191. case 106: // M106: Fan On
  7192. gcode_M106();
  7193. break;
  7194. case 107: // M107: Fan Off
  7195. gcode_M107();
  7196. break;
  7197. #endif // FAN_COUNT > 0
  7198. #if ENABLED(BARICUDA)
  7199. // PWM for HEATER_1_PIN
  7200. #if HAS_HEATER_1
  7201. case 126: // M126: valve open
  7202. gcode_M126();
  7203. break;
  7204. case 127: // M127: valve closed
  7205. gcode_M127();
  7206. break;
  7207. #endif // HAS_HEATER_1
  7208. // PWM for HEATER_2_PIN
  7209. #if HAS_HEATER_2
  7210. case 128: // M128: valve open
  7211. gcode_M128();
  7212. break;
  7213. case 129: // M129: valve closed
  7214. gcode_M129();
  7215. break;
  7216. #endif // HAS_HEATER_2
  7217. #endif // BARICUDA
  7218. #if HAS_POWER_SWITCH
  7219. case 80: // M80: Turn on Power Supply
  7220. gcode_M80();
  7221. break;
  7222. #endif // HAS_POWER_SWITCH
  7223. case 81: // M81: Turn off Power, including Power Supply, if possible
  7224. gcode_M81();
  7225. break;
  7226. case 82: // M83: Set E axis normal mode (same as other axes)
  7227. gcode_M82();
  7228. break;
  7229. case 83: // M83: Set E axis relative mode
  7230. gcode_M83();
  7231. break;
  7232. case 18: // M18 => M84
  7233. case 84: // M84: Disable all steppers or set timeout
  7234. gcode_M18_M84();
  7235. break;
  7236. case 85: // M85: Set inactivity stepper shutdown timeout
  7237. gcode_M85();
  7238. break;
  7239. case 92: // M92: Set the steps-per-unit for one or more axes
  7240. gcode_M92();
  7241. break;
  7242. case 114: // M114: Report current position
  7243. gcode_M114();
  7244. break;
  7245. case 115: // M115: Report capabilities
  7246. gcode_M115();
  7247. break;
  7248. case 117: // M117: Set LCD message text, if possible
  7249. gcode_M117();
  7250. break;
  7251. case 119: // M119: Report endstop states
  7252. gcode_M119();
  7253. break;
  7254. case 120: // M120: Enable endstops
  7255. gcode_M120();
  7256. break;
  7257. case 121: // M121: Disable endstops
  7258. gcode_M121();
  7259. break;
  7260. #if ENABLED(ULTIPANEL)
  7261. case 145: // M145: Set material heatup parameters
  7262. gcode_M145();
  7263. break;
  7264. #endif
  7265. #if ENABLED(TEMPERATURE_UNITS_SUPPORT)
  7266. case 149: // M149: Set temperature units
  7267. gcode_M149();
  7268. break;
  7269. #endif
  7270. #if ENABLED(BLINKM) || ENABLED(RGB_LED)
  7271. case 150: // M150: Set Status LED Color
  7272. gcode_M150();
  7273. break;
  7274. #endif // BLINKM
  7275. #if ENABLED(MIXING_EXTRUDER)
  7276. case 163: // M163: Set a component weight for mixing extruder
  7277. gcode_M163();
  7278. break;
  7279. #if MIXING_VIRTUAL_TOOLS > 1
  7280. case 164: // M164: Save current mix as a virtual extruder
  7281. gcode_M164();
  7282. break;
  7283. #endif
  7284. #if ENABLED(DIRECT_MIXING_IN_G1)
  7285. case 165: // M165: Set multiple mix weights
  7286. gcode_M165();
  7287. break;
  7288. #endif
  7289. #endif
  7290. case 200: // M200: Set filament diameter, E to cubic units
  7291. gcode_M200();
  7292. break;
  7293. case 201: // M201: Set max acceleration for print moves (units/s^2)
  7294. gcode_M201();
  7295. break;
  7296. #if 0 // Not used for Sprinter/grbl gen6
  7297. case 202: // M202
  7298. gcode_M202();
  7299. break;
  7300. #endif
  7301. case 203: // M203: Set max feedrate (units/sec)
  7302. gcode_M203();
  7303. break;
  7304. case 204: // M204: Set acceleration
  7305. gcode_M204();
  7306. break;
  7307. case 205: //M205: Set advanced settings
  7308. gcode_M205();
  7309. break;
  7310. #if DISABLED(NO_WORKSPACE_OFFSETS)
  7311. case 206: // M206: Set home offsets
  7312. gcode_M206();
  7313. break;
  7314. #endif
  7315. #if ENABLED(DELTA)
  7316. case 665: // M665: Set delta configurations
  7317. gcode_M665();
  7318. break;
  7319. #endif
  7320. #if ENABLED(DELTA) || ENABLED(Z_DUAL_ENDSTOPS)
  7321. case 666: // M666: Set delta or dual endstop adjustment
  7322. gcode_M666();
  7323. break;
  7324. #endif
  7325. #if ENABLED(FWRETRACT)
  7326. case 207: // M207: Set Retract Length, Feedrate, and Z lift
  7327. gcode_M207();
  7328. break;
  7329. case 208: // M208: Set Recover (unretract) Additional Length and Feedrate
  7330. gcode_M208();
  7331. break;
  7332. case 209: // M209: Turn Automatic Retract Detection on/off
  7333. gcode_M209();
  7334. break;
  7335. #endif // FWRETRACT
  7336. case 211: // M211: Enable, Disable, and/or Report software endstops
  7337. gcode_M211();
  7338. break;
  7339. #if HOTENDS > 1
  7340. case 218: // M218: Set a tool offset
  7341. gcode_M218();
  7342. break;
  7343. #endif
  7344. case 220: // M220: Set Feedrate Percentage: S<percent> ("FR" on your LCD)
  7345. gcode_M220();
  7346. break;
  7347. case 221: // M221: Set Flow Percentage
  7348. gcode_M221();
  7349. break;
  7350. case 226: // M226: Wait until a pin reaches a state
  7351. gcode_M226();
  7352. break;
  7353. #if HAS_SERVOS
  7354. case 280: // M280: Set servo position absolute
  7355. gcode_M280();
  7356. break;
  7357. #endif // HAS_SERVOS
  7358. #if HAS_BUZZER
  7359. case 300: // M300: Play beep tone
  7360. gcode_M300();
  7361. break;
  7362. #endif // HAS_BUZZER
  7363. #if ENABLED(PIDTEMP)
  7364. case 301: // M301: Set hotend PID parameters
  7365. gcode_M301();
  7366. break;
  7367. #endif // PIDTEMP
  7368. #if ENABLED(PIDTEMPBED)
  7369. case 304: // M304: Set bed PID parameters
  7370. gcode_M304();
  7371. break;
  7372. #endif // PIDTEMPBED
  7373. #if defined(CHDK) || HAS_PHOTOGRAPH
  7374. case 240: // M240: Trigger a camera by emulating a Canon RC-1 : http://www.doc-diy.net/photo/rc-1_hacked/
  7375. gcode_M240();
  7376. break;
  7377. #endif // CHDK || PHOTOGRAPH_PIN
  7378. #if HAS_LCD_CONTRAST
  7379. case 250: // M250: Set LCD contrast
  7380. gcode_M250();
  7381. break;
  7382. #endif // HAS_LCD_CONTRAST
  7383. #if ENABLED(EXPERIMENTAL_I2CBUS)
  7384. case 260: // M260: Send data to an i2c slave
  7385. gcode_M260();
  7386. break;
  7387. case 261: // M261: Request data from an i2c slave
  7388. gcode_M261();
  7389. break;
  7390. #endif // EXPERIMENTAL_I2CBUS
  7391. #if ENABLED(PREVENT_COLD_EXTRUSION)
  7392. case 302: // M302: Allow cold extrudes (set the minimum extrude temperature)
  7393. gcode_M302();
  7394. break;
  7395. #endif // PREVENT_COLD_EXTRUSION
  7396. case 303: // M303: PID autotune
  7397. gcode_M303();
  7398. break;
  7399. #if ENABLED(MORGAN_SCARA)
  7400. case 360: // M360: SCARA Theta pos1
  7401. if (gcode_M360()) return;
  7402. break;
  7403. case 361: // M361: SCARA Theta pos2
  7404. if (gcode_M361()) return;
  7405. break;
  7406. case 362: // M362: SCARA Psi pos1
  7407. if (gcode_M362()) return;
  7408. break;
  7409. case 363: // M363: SCARA Psi pos2
  7410. if (gcode_M363()) return;
  7411. break;
  7412. case 364: // M364: SCARA Psi pos3 (90 deg to Theta)
  7413. if (gcode_M364()) return;
  7414. break;
  7415. #endif // SCARA
  7416. case 400: // M400: Finish all moves
  7417. gcode_M400();
  7418. break;
  7419. #if HAS_BED_PROBE
  7420. case 401: // M401: Deploy probe
  7421. gcode_M401();
  7422. break;
  7423. case 402: // M402: Stow probe
  7424. gcode_M402();
  7425. break;
  7426. #endif // HAS_BED_PROBE
  7427. #if ENABLED(FILAMENT_WIDTH_SENSOR)
  7428. case 404: // M404: Enter the nominal filament width (3mm, 1.75mm ) N<3.0> or display nominal filament width
  7429. gcode_M404();
  7430. break;
  7431. case 405: // M405: Turn on filament sensor for control
  7432. gcode_M405();
  7433. break;
  7434. case 406: // M406: Turn off filament sensor for control
  7435. gcode_M406();
  7436. break;
  7437. case 407: // M407: Display measured filament diameter
  7438. gcode_M407();
  7439. break;
  7440. #endif // ENABLED(FILAMENT_WIDTH_SENSOR)
  7441. #if PLANNER_LEVELING
  7442. case 420: // M420: Enable/Disable Bed Leveling
  7443. gcode_M420();
  7444. break;
  7445. #endif
  7446. #if ENABLED(MESH_BED_LEVELING)
  7447. case 421: // M421: Set a Mesh Bed Leveling Z coordinate
  7448. gcode_M421();
  7449. break;
  7450. #endif
  7451. #if DISABLED(NO_WORKSPACE_OFFSETS)
  7452. case 428: // M428: Apply current_position to home_offset
  7453. gcode_M428();
  7454. break;
  7455. #endif
  7456. case 500: // M500: Store settings in EEPROM
  7457. gcode_M500();
  7458. break;
  7459. case 501: // M501: Read settings from EEPROM
  7460. gcode_M501();
  7461. break;
  7462. case 502: // M502: Revert to default settings
  7463. gcode_M502();
  7464. break;
  7465. case 503: // M503: print settings currently in memory
  7466. gcode_M503();
  7467. break;
  7468. #if ENABLED(ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED)
  7469. case 540: // M540: Set abort on endstop hit for SD printing
  7470. gcode_M540();
  7471. break;
  7472. #endif
  7473. #if HAS_BED_PROBE
  7474. case 851: // M851: Set Z Probe Z Offset
  7475. gcode_M851();
  7476. break;
  7477. #endif // HAS_BED_PROBE
  7478. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  7479. case 600: // M600: Pause for filament change
  7480. gcode_M600();
  7481. break;
  7482. #endif // FILAMENT_CHANGE_FEATURE
  7483. #if ENABLED(DUAL_X_CARRIAGE)
  7484. case 605: // M605: Set Dual X Carriage movement mode
  7485. gcode_M605();
  7486. break;
  7487. #endif // DUAL_X_CARRIAGE
  7488. #if ENABLED(LIN_ADVANCE)
  7489. case 905: // M905: Set advance K factor.
  7490. gcode_M905();
  7491. break;
  7492. #endif
  7493. #if ENABLED(HAVE_TMC2130)
  7494. case 906: // M906: Set motor current in milliamps using axis codes X, Y, Z, E
  7495. gcode_M906();
  7496. break;
  7497. #endif
  7498. case 907: // M907: Set digital trimpot motor current using axis codes.
  7499. gcode_M907();
  7500. break;
  7501. #if HAS_DIGIPOTSS || ENABLED(DAC_STEPPER_CURRENT)
  7502. case 908: // M908: Control digital trimpot directly.
  7503. gcode_M908();
  7504. break;
  7505. #if ENABLED(DAC_STEPPER_CURRENT) // As with Printrbot RevF
  7506. case 909: // M909: Print digipot/DAC current value
  7507. gcode_M909();
  7508. break;
  7509. case 910: // M910: Commit digipot/DAC value to external EEPROM
  7510. gcode_M910();
  7511. break;
  7512. #endif
  7513. #endif // HAS_DIGIPOTSS || DAC_STEPPER_CURRENT
  7514. #if ENABLED(HAVE_TMC2130)
  7515. case 911: // M911: Report TMC2130 prewarn triggered flags
  7516. gcode_M911();
  7517. break;
  7518. case 912: // M911: Clear TMC2130 prewarn triggered flags
  7519. gcode_M912();
  7520. break;
  7521. #endif
  7522. #if HAS_MICROSTEPS
  7523. case 350: // M350: Set microstepping mode. Warning: Steps per unit remains unchanged. S code sets stepping mode for all drivers.
  7524. gcode_M350();
  7525. break;
  7526. case 351: // M351: Toggle MS1 MS2 pins directly, S# determines MS1 or MS2, X# sets the pin high/low.
  7527. gcode_M351();
  7528. break;
  7529. #endif // HAS_MICROSTEPS
  7530. case 355: // M355 Turn case lights on/off
  7531. gcode_M355();
  7532. break;
  7533. case 999: // M999: Restart after being Stopped
  7534. gcode_M999();
  7535. break;
  7536. }
  7537. break;
  7538. case 'T':
  7539. gcode_T(codenum);
  7540. break;
  7541. default: code_is_good = false;
  7542. }
  7543. KEEPALIVE_STATE(NOT_BUSY);
  7544. ExitUnknownCommand:
  7545. // Still unknown command? Throw an error
  7546. if (!code_is_good) unknown_command_error();
  7547. ok_to_send();
  7548. }
  7549. /**
  7550. * Send a "Resend: nnn" message to the host to
  7551. * indicate that a command needs to be re-sent.
  7552. */
  7553. void FlushSerialRequestResend() {
  7554. //char command_queue[cmd_queue_index_r][100]="Resend:";
  7555. MYSERIAL.flush();
  7556. SERIAL_PROTOCOLPGM(MSG_RESEND);
  7557. SERIAL_PROTOCOLLN(gcode_LastN + 1);
  7558. ok_to_send();
  7559. }
  7560. /**
  7561. * Send an "ok" message to the host, indicating
  7562. * that a command was successfully processed.
  7563. *
  7564. * If ADVANCED_OK is enabled also include:
  7565. * N<int> Line number of the command, if any
  7566. * P<int> Planner space remaining
  7567. * B<int> Block queue space remaining
  7568. */
  7569. void ok_to_send() {
  7570. refresh_cmd_timeout();
  7571. if (!send_ok[cmd_queue_index_r]) return;
  7572. SERIAL_PROTOCOLPGM(MSG_OK);
  7573. #if ENABLED(ADVANCED_OK)
  7574. char* p = command_queue[cmd_queue_index_r];
  7575. if (*p == 'N') {
  7576. SERIAL_PROTOCOL(' ');
  7577. SERIAL_ECHO(*p++);
  7578. while (NUMERIC_SIGNED(*p))
  7579. SERIAL_ECHO(*p++);
  7580. }
  7581. SERIAL_PROTOCOLPGM(" P"); SERIAL_PROTOCOL(int(BLOCK_BUFFER_SIZE - planner.movesplanned() - 1));
  7582. SERIAL_PROTOCOLPGM(" B"); SERIAL_PROTOCOL(BUFSIZE - commands_in_queue);
  7583. #endif
  7584. SERIAL_EOL;
  7585. }
  7586. #if HAS_SOFTWARE_ENDSTOPS
  7587. /**
  7588. * Constrain the given coordinates to the software endstops.
  7589. */
  7590. void clamp_to_software_endstops(float target[XYZ]) {
  7591. if (!soft_endstops_enabled) return;
  7592. #if ENABLED(MIN_SOFTWARE_ENDSTOPS)
  7593. NOLESS(target[X_AXIS], soft_endstop_min[X_AXIS]);
  7594. NOLESS(target[Y_AXIS], soft_endstop_min[Y_AXIS]);
  7595. NOLESS(target[Z_AXIS], soft_endstop_min[Z_AXIS]);
  7596. #endif
  7597. #if ENABLED(MAX_SOFTWARE_ENDSTOPS)
  7598. NOMORE(target[X_AXIS], soft_endstop_max[X_AXIS]);
  7599. NOMORE(target[Y_AXIS], soft_endstop_max[Y_AXIS]);
  7600. NOMORE(target[Z_AXIS], soft_endstop_max[Z_AXIS]);
  7601. #endif
  7602. }
  7603. #endif
  7604. #if ENABLED(AUTO_BED_LEVELING_BILINEAR)
  7605. #if ENABLED(ABL_BILINEAR_SUBDIVISION)
  7606. #define ABL_BG_SPACING(A) bilinear_grid_spacing_virt[A]
  7607. #define ABL_BG_POINTS_X ABL_GRID_POINTS_VIRT_X
  7608. #define ABL_BG_POINTS_Y ABL_GRID_POINTS_VIRT_Y
  7609. #define ABL_BG_GRID(X,Y) bed_level_grid_virt[X][Y]
  7610. #else
  7611. #define ABL_BG_SPACING(A) bilinear_grid_spacing[A]
  7612. #define ABL_BG_POINTS_X ABL_GRID_MAX_POINTS_X
  7613. #define ABL_BG_POINTS_Y ABL_GRID_MAX_POINTS_Y
  7614. #define ABL_BG_GRID(X,Y) bed_level_grid[X][Y]
  7615. #endif
  7616. // Get the Z adjustment for non-linear bed leveling
  7617. float bilinear_z_offset(float cartesian[XYZ]) {
  7618. // XY relative to the probed area
  7619. const float x = RAW_X_POSITION(cartesian[X_AXIS]) - bilinear_start[X_AXIS],
  7620. y = RAW_Y_POSITION(cartesian[Y_AXIS]) - bilinear_start[Y_AXIS];
  7621. // Convert to grid box units
  7622. float ratio_x = x / ABL_BG_SPACING(X_AXIS),
  7623. ratio_y = y / ABL_BG_SPACING(Y_AXIS);
  7624. // Whole units for the grid line indices. Constrained within bounds.
  7625. const int gridx = constrain(floor(ratio_x), 0, ABL_BG_POINTS_X - 1),
  7626. gridy = constrain(floor(ratio_y), 0, ABL_BG_POINTS_Y - 1),
  7627. nextx = min(gridx + 1, ABL_BG_POINTS_X - 1),
  7628. nexty = min(gridy + 1, ABL_BG_POINTS_Y - 1);
  7629. // Subtract whole to get the ratio within the grid box
  7630. ratio_x -= gridx; ratio_y -= gridy;
  7631. // Never less than 0.0. (Over 1.0 is fine due to previous contraints.)
  7632. NOLESS(ratio_x, 0); NOLESS(ratio_y, 0);
  7633. // Z at the box corners
  7634. const float z1 = ABL_BG_GRID(gridx, gridy), // left-front
  7635. z2 = ABL_BG_GRID(gridx, nexty), // left-back
  7636. z3 = ABL_BG_GRID(nextx, gridy), // right-front
  7637. z4 = ABL_BG_GRID(nextx, nexty), // right-back
  7638. // Bilinear interpolate
  7639. L = z1 + (z2 - z1) * ratio_y, // Linear interp. LF -> LB
  7640. R = z3 + (z4 - z3) * ratio_y, // Linear interp. RF -> RB
  7641. offset = L + ratio_x * (R - L);
  7642. /*
  7643. static float last_offset = 0;
  7644. if (fabs(last_offset - offset) > 0.2) {
  7645. SERIAL_ECHOPGM("Sudden Shift at ");
  7646. SERIAL_ECHOPAIR("x=", x);
  7647. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[X_AXIS]);
  7648. SERIAL_ECHOLNPAIR(" -> gridx=", gridx);
  7649. SERIAL_ECHOPAIR(" y=", y);
  7650. SERIAL_ECHOPAIR(" / ", bilinear_grid_spacing[Y_AXIS]);
  7651. SERIAL_ECHOLNPAIR(" -> gridy=", gridy);
  7652. SERIAL_ECHOPAIR(" ratio_x=", ratio_x);
  7653. SERIAL_ECHOLNPAIR(" ratio_y=", ratio_y);
  7654. SERIAL_ECHOPAIR(" z1=", z1);
  7655. SERIAL_ECHOPAIR(" z2=", z2);
  7656. SERIAL_ECHOPAIR(" z3=", z3);
  7657. SERIAL_ECHOLNPAIR(" z4=", z4);
  7658. SERIAL_ECHOPAIR(" L=", L);
  7659. SERIAL_ECHOPAIR(" R=", R);
  7660. SERIAL_ECHOLNPAIR(" offset=", offset);
  7661. }
  7662. last_offset = offset;
  7663. */
  7664. return offset;
  7665. }
  7666. #endif // AUTO_BED_LEVELING_BILINEAR
  7667. #if ENABLED(DELTA)
  7668. /**
  7669. * Recalculate factors used for delta kinematics whenever
  7670. * settings have been changed (e.g., by M665).
  7671. */
  7672. void recalc_delta_settings(float radius, float diagonal_rod) {
  7673. delta_tower[A_AXIS][X_AXIS] = -sin(RADIANS(60 - delta_tower_angle_trim[A_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1), // front left tower
  7674. delta_tower[A_AXIS][Y_AXIS] = -cos(RADIANS(60 - delta_tower_angle_trim[A_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_1),
  7675. delta_tower[B_AXIS][X_AXIS] = sin(RADIANS(60 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2), // front right tower
  7676. delta_tower[B_AXIS][Y_AXIS] = -cos(RADIANS(60 + delta_tower_angle_trim[B_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_2),
  7677. delta_tower[C_AXIS][X_AXIS] = -sin(RADIANS( delta_tower_angle_trim[C_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_3), // back middle tower
  7678. delta_tower[C_AXIS][Y_AXIS] = cos(RADIANS( delta_tower_angle_trim[C_AXIS])) * (delta_radius + DELTA_RADIUS_TRIM_TOWER_3),
  7679. delta_diagonal_rod_2_tower[A_AXIS] = sq(diagonal_rod + delta_diagonal_rod_trim[A_AXIS]);
  7680. delta_diagonal_rod_2_tower[B_AXIS] = sq(diagonal_rod + delta_diagonal_rod_trim[B_AXIS]);
  7681. delta_diagonal_rod_2_tower[C_AXIS] = sq(diagonal_rod + delta_diagonal_rod_trim[C_AXIS]);
  7682. }
  7683. #if ENABLED(DELTA_FAST_SQRT)
  7684. /**
  7685. * Fast inverse sqrt from Quake III Arena
  7686. * See: https://en.wikipedia.org/wiki/Fast_inverse_square_root
  7687. */
  7688. float Q_rsqrt(float number) {
  7689. long i;
  7690. float x2, y;
  7691. const float threehalfs = 1.5f;
  7692. x2 = number * 0.5f;
  7693. y = number;
  7694. i = * ( long * ) &y; // evil floating point bit level hacking
  7695. i = 0x5f3759df - ( i >> 1 ); // what the f***?
  7696. y = * ( float * ) &i;
  7697. y = y * ( threehalfs - ( x2 * y * y ) ); // 1st iteration
  7698. // y = y * ( threehalfs - ( x2 * y * y ) ); // 2nd iteration, this can be removed
  7699. return y;
  7700. }
  7701. #define _SQRT(n) (1.0f / Q_rsqrt(n))
  7702. #else
  7703. #define _SQRT(n) sqrt(n)
  7704. #endif
  7705. /**
  7706. * Delta Inverse Kinematics
  7707. *
  7708. * Calculate the tower positions for a given logical
  7709. * position, storing the result in the delta[] array.
  7710. *
  7711. * This is an expensive calculation, requiring 3 square
  7712. * roots per segmented linear move, and strains the limits
  7713. * of a Mega2560 with a Graphical Display.
  7714. *
  7715. * Suggested optimizations include:
  7716. *
  7717. * - Disable the home_offset (M206) and/or position_shift (G92)
  7718. * features to remove up to 12 float additions.
  7719. *
  7720. * - Use a fast-inverse-sqrt function and add the reciprocal.
  7721. * (see above)
  7722. */
  7723. // Macro to obtain the Z position of an individual tower
  7724. #define DELTA_Z(T) raw[Z_AXIS] + _SQRT( \
  7725. delta_diagonal_rod_2_tower[T] - HYPOT2( \
  7726. delta_tower[T][X_AXIS] - raw[X_AXIS], \
  7727. delta_tower[T][Y_AXIS] - raw[Y_AXIS] \
  7728. ) \
  7729. )
  7730. #define DELTA_RAW_IK() do { \
  7731. delta[A_AXIS] = DELTA_Z(A_AXIS); \
  7732. delta[B_AXIS] = DELTA_Z(B_AXIS); \
  7733. delta[C_AXIS] = DELTA_Z(C_AXIS); \
  7734. } while(0)
  7735. #define DELTA_LOGICAL_IK() do { \
  7736. const float raw[XYZ] = { \
  7737. RAW_X_POSITION(logical[X_AXIS]), \
  7738. RAW_Y_POSITION(logical[Y_AXIS]), \
  7739. RAW_Z_POSITION(logical[Z_AXIS]) \
  7740. }; \
  7741. DELTA_RAW_IK(); \
  7742. } while(0)
  7743. #define DELTA_DEBUG() do { \
  7744. SERIAL_ECHOPAIR("cartesian X:", raw[X_AXIS]); \
  7745. SERIAL_ECHOPAIR(" Y:", raw[Y_AXIS]); \
  7746. SERIAL_ECHOLNPAIR(" Z:", raw[Z_AXIS]); \
  7747. SERIAL_ECHOPAIR("delta A:", delta[A_AXIS]); \
  7748. SERIAL_ECHOPAIR(" B:", delta[B_AXIS]); \
  7749. SERIAL_ECHOLNPAIR(" C:", delta[C_AXIS]); \
  7750. } while(0)
  7751. void inverse_kinematics(const float logical[XYZ]) {
  7752. DELTA_LOGICAL_IK();
  7753. // DELTA_DEBUG();
  7754. }
  7755. /**
  7756. * Calculate the highest Z position where the
  7757. * effector has the full range of XY motion.
  7758. */
  7759. float delta_safe_distance_from_top() {
  7760. float cartesian[XYZ] = {
  7761. LOGICAL_X_POSITION(0),
  7762. LOGICAL_Y_POSITION(0),
  7763. LOGICAL_Z_POSITION(0)
  7764. };
  7765. inverse_kinematics(cartesian);
  7766. float distance = delta[A_AXIS];
  7767. cartesian[Y_AXIS] = LOGICAL_Y_POSITION(DELTA_PRINTABLE_RADIUS);
  7768. inverse_kinematics(cartesian);
  7769. return abs(distance - delta[A_AXIS]);
  7770. }
  7771. /**
  7772. * Delta Forward Kinematics
  7773. *
  7774. * See the Wikipedia article "Trilateration"
  7775. * https://en.wikipedia.org/wiki/Trilateration
  7776. *
  7777. * Establish a new coordinate system in the plane of the
  7778. * three carriage points. This system has its origin at
  7779. * tower1, with tower2 on the X axis. Tower3 is in the X-Y
  7780. * plane with a Z component of zero.
  7781. * We will define unit vectors in this coordinate system
  7782. * in our original coordinate system. Then when we calculate
  7783. * the Xnew, Ynew and Znew values, we can translate back into
  7784. * the original system by moving along those unit vectors
  7785. * by the corresponding values.
  7786. *
  7787. * Variable names matched to Marlin, c-version, and avoid the
  7788. * use of any vector library.
  7789. *
  7790. * by Andreas Hardtung 2016-06-07
  7791. * based on a Java function from "Delta Robot Kinematics V3"
  7792. * by Steve Graves
  7793. *
  7794. * The result is stored in the cartes[] array.
  7795. */
  7796. void forward_kinematics_DELTA(float z1, float z2, float z3) {
  7797. // Create a vector in old coordinates along x axis of new coordinate
  7798. 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 };
  7799. // Get the Magnitude of vector.
  7800. float d = sqrt( sq(p12[0]) + sq(p12[1]) + sq(p12[2]) );
  7801. // Create unit vector by dividing by magnitude.
  7802. float ex[3] = { p12[0] / d, p12[1] / d, p12[2] / d };
  7803. // Get the vector from the origin of the new system to the third point.
  7804. 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 };
  7805. // Use the dot product to find the component of this vector on the X axis.
  7806. float i = ex[0] * p13[0] + ex[1] * p13[1] + ex[2] * p13[2];
  7807. // Create a vector along the x axis that represents the x component of p13.
  7808. float iex[3] = { ex[0] * i, ex[1] * i, ex[2] * i };
  7809. // Subtract the X component from the original vector leaving only Y. We use the
  7810. // variable that will be the unit vector after we scale it.
  7811. float ey[3] = { p13[0] - iex[0], p13[1] - iex[1], p13[2] - iex[2] };
  7812. // The magnitude of Y component
  7813. float j = sqrt( sq(ey[0]) + sq(ey[1]) + sq(ey[2]) );
  7814. // Convert to a unit vector
  7815. ey[0] /= j; ey[1] /= j; ey[2] /= j;
  7816. // The cross product of the unit x and y is the unit z
  7817. // float[] ez = vectorCrossProd(ex, ey);
  7818. float ez[3] = {
  7819. ex[1] * ey[2] - ex[2] * ey[1],
  7820. ex[2] * ey[0] - ex[0] * ey[2],
  7821. ex[0] * ey[1] - ex[1] * ey[0]
  7822. };
  7823. // We now have the d, i and j values defined in Wikipedia.
  7824. // Plug them into the equations defined in Wikipedia for Xnew, Ynew and Znew
  7825. float Xnew = (delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[B_AXIS] + sq(d)) / (d * 2),
  7826. Ynew = ((delta_diagonal_rod_2_tower[A_AXIS] - delta_diagonal_rod_2_tower[C_AXIS] + HYPOT2(i, j)) / 2 - i * Xnew) / j,
  7827. Znew = sqrt(delta_diagonal_rod_2_tower[A_AXIS] - HYPOT2(Xnew, Ynew));
  7828. // Start from the origin of the old coordinates and add vectors in the
  7829. // old coords that represent the Xnew, Ynew and Znew to find the point
  7830. // in the old system.
  7831. cartes[X_AXIS] = delta_tower[A_AXIS][X_AXIS] + ex[0] * Xnew + ey[0] * Ynew - ez[0] * Znew;
  7832. cartes[Y_AXIS] = delta_tower[A_AXIS][Y_AXIS] + ex[1] * Xnew + ey[1] * Ynew - ez[1] * Znew;
  7833. cartes[Z_AXIS] = z1 + ex[2] * Xnew + ey[2] * Ynew - ez[2] * Znew;
  7834. }
  7835. void forward_kinematics_DELTA(float point[ABC]) {
  7836. forward_kinematics_DELTA(point[A_AXIS], point[B_AXIS], point[C_AXIS]);
  7837. }
  7838. #endif // DELTA
  7839. /**
  7840. * Get the stepper positions in the cartes[] array.
  7841. * Forward kinematics are applied for DELTA and SCARA.
  7842. *
  7843. * The result is in the current coordinate space with
  7844. * leveling applied. The coordinates need to be run through
  7845. * unapply_leveling to obtain the "ideal" coordinates
  7846. * suitable for current_position, etc.
  7847. */
  7848. void get_cartesian_from_steppers() {
  7849. #if ENABLED(DELTA)
  7850. forward_kinematics_DELTA(
  7851. stepper.get_axis_position_mm(A_AXIS),
  7852. stepper.get_axis_position_mm(B_AXIS),
  7853. stepper.get_axis_position_mm(C_AXIS)
  7854. );
  7855. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  7856. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  7857. cartes[Z_AXIS] += LOGICAL_Z_POSITION(0);
  7858. #elif IS_SCARA
  7859. forward_kinematics_SCARA(
  7860. stepper.get_axis_position_degrees(A_AXIS),
  7861. stepper.get_axis_position_degrees(B_AXIS)
  7862. );
  7863. cartes[X_AXIS] += LOGICAL_X_POSITION(0);
  7864. cartes[Y_AXIS] += LOGICAL_Y_POSITION(0);
  7865. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  7866. #else
  7867. cartes[X_AXIS] = stepper.get_axis_position_mm(X_AXIS);
  7868. cartes[Y_AXIS] = stepper.get_axis_position_mm(Y_AXIS);
  7869. cartes[Z_AXIS] = stepper.get_axis_position_mm(Z_AXIS);
  7870. #endif
  7871. }
  7872. /**
  7873. * Set the current_position for an axis based on
  7874. * the stepper positions, removing any leveling that
  7875. * may have been applied.
  7876. */
  7877. void set_current_from_steppers_for_axis(const AxisEnum axis) {
  7878. get_cartesian_from_steppers();
  7879. #if PLANNER_LEVELING
  7880. planner.unapply_leveling(cartes);
  7881. #endif
  7882. if (axis == ALL_AXES)
  7883. COPY(current_position, cartes);
  7884. else
  7885. current_position[axis] = cartes[axis];
  7886. }
  7887. #if ENABLED(MESH_BED_LEVELING)
  7888. /**
  7889. * Prepare a mesh-leveled linear move in a Cartesian setup,
  7890. * splitting the move where it crosses mesh borders.
  7891. */
  7892. void mesh_line_to_destination(float fr_mm_s, uint8_t x_splits = 0xff, uint8_t y_splits = 0xff) {
  7893. int cx1 = mbl.cell_index_x(RAW_CURRENT_POSITION(X_AXIS)),
  7894. cy1 = mbl.cell_index_y(RAW_CURRENT_POSITION(Y_AXIS)),
  7895. cx2 = mbl.cell_index_x(RAW_X_POSITION(destination[X_AXIS])),
  7896. cy2 = mbl.cell_index_y(RAW_Y_POSITION(destination[Y_AXIS]));
  7897. NOMORE(cx1, MESH_NUM_X_POINTS - 2);
  7898. NOMORE(cy1, MESH_NUM_Y_POINTS - 2);
  7899. NOMORE(cx2, MESH_NUM_X_POINTS - 2);
  7900. NOMORE(cy2, MESH_NUM_Y_POINTS - 2);
  7901. if (cx1 == cx2 && cy1 == cy2) {
  7902. // Start and end on same mesh square
  7903. line_to_destination(fr_mm_s);
  7904. set_current_to_destination();
  7905. return;
  7906. }
  7907. #define MBL_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  7908. float normalized_dist, end[XYZE];
  7909. // Split at the left/front border of the right/top square
  7910. int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  7911. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  7912. COPY(end, destination);
  7913. destination[X_AXIS] = LOGICAL_X_POSITION(mbl.get_probe_x(gcx));
  7914. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  7915. destination[Y_AXIS] = MBL_SEGMENT_END(Y);
  7916. CBI(x_splits, gcx);
  7917. }
  7918. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  7919. COPY(end, destination);
  7920. destination[Y_AXIS] = LOGICAL_Y_POSITION(mbl.get_probe_y(gcy));
  7921. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  7922. destination[X_AXIS] = MBL_SEGMENT_END(X);
  7923. CBI(y_splits, gcy);
  7924. }
  7925. else {
  7926. // Already split on a border
  7927. line_to_destination(fr_mm_s);
  7928. set_current_to_destination();
  7929. return;
  7930. }
  7931. destination[Z_AXIS] = MBL_SEGMENT_END(Z);
  7932. destination[E_AXIS] = MBL_SEGMENT_END(E);
  7933. // Do the split and look for more borders
  7934. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  7935. // Restore destination from stack
  7936. COPY(destination, end);
  7937. mesh_line_to_destination(fr_mm_s, x_splits, y_splits);
  7938. }
  7939. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) && !IS_KINEMATIC
  7940. #define CELL_INDEX(A,V) ((RAW_##A##_POSITION(V) - bilinear_start[A##_AXIS]) / ABL_BG_SPACING(A##_AXIS))
  7941. /**
  7942. * Prepare a bilinear-leveled linear move on Cartesian,
  7943. * splitting the move where it crosses grid borders.
  7944. */
  7945. void bilinear_line_to_destination(float fr_mm_s, uint16_t x_splits = 0xFFFF, uint16_t y_splits = 0xFFFF) {
  7946. int cx1 = CELL_INDEX(X, current_position[X_AXIS]),
  7947. cy1 = CELL_INDEX(Y, current_position[Y_AXIS]),
  7948. cx2 = CELL_INDEX(X, destination[X_AXIS]),
  7949. cy2 = CELL_INDEX(Y, destination[Y_AXIS]);
  7950. cx1 = constrain(cx1, 0, ABL_BG_POINTS_X - 2);
  7951. cy1 = constrain(cy1, 0, ABL_BG_POINTS_Y - 2);
  7952. cx2 = constrain(cx2, 0, ABL_BG_POINTS_X - 2);
  7953. cy2 = constrain(cy2, 0, ABL_BG_POINTS_Y - 2);
  7954. if (cx1 == cx2 && cy1 == cy2) {
  7955. // Start and end on same mesh square
  7956. line_to_destination(fr_mm_s);
  7957. set_current_to_destination();
  7958. return;
  7959. }
  7960. #define LINE_SEGMENT_END(A) (current_position[A ##_AXIS] + (destination[A ##_AXIS] - current_position[A ##_AXIS]) * normalized_dist)
  7961. float normalized_dist, end[XYZE];
  7962. // Split at the left/front border of the right/top square
  7963. int8_t gcx = max(cx1, cx2), gcy = max(cy1, cy2);
  7964. if (cx2 != cx1 && TEST(x_splits, gcx)) {
  7965. COPY(end, destination);
  7966. destination[X_AXIS] = LOGICAL_X_POSITION(bilinear_start[X_AXIS] + ABL_BG_SPACING(X_AXIS) * gcx);
  7967. normalized_dist = (destination[X_AXIS] - current_position[X_AXIS]) / (end[X_AXIS] - current_position[X_AXIS]);
  7968. destination[Y_AXIS] = LINE_SEGMENT_END(Y);
  7969. CBI(x_splits, gcx);
  7970. }
  7971. else if (cy2 != cy1 && TEST(y_splits, gcy)) {
  7972. COPY(end, destination);
  7973. destination[Y_AXIS] = LOGICAL_Y_POSITION(bilinear_start[Y_AXIS] + ABL_BG_SPACING(Y_AXIS) * gcy);
  7974. normalized_dist = (destination[Y_AXIS] - current_position[Y_AXIS]) / (end[Y_AXIS] - current_position[Y_AXIS]);
  7975. destination[X_AXIS] = LINE_SEGMENT_END(X);
  7976. CBI(y_splits, gcy);
  7977. }
  7978. else {
  7979. // Already split on a border
  7980. line_to_destination(fr_mm_s);
  7981. set_current_to_destination();
  7982. return;
  7983. }
  7984. destination[Z_AXIS] = LINE_SEGMENT_END(Z);
  7985. destination[E_AXIS] = LINE_SEGMENT_END(E);
  7986. // Do the split and look for more borders
  7987. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  7988. // Restore destination from stack
  7989. COPY(destination, end);
  7990. bilinear_line_to_destination(fr_mm_s, x_splits, y_splits);
  7991. }
  7992. #endif // AUTO_BED_LEVELING_BILINEAR
  7993. #if IS_KINEMATIC
  7994. /**
  7995. * Prepare a linear move in a DELTA or SCARA setup.
  7996. *
  7997. * This calls planner.buffer_line several times, adding
  7998. * small incremental moves for DELTA or SCARA.
  7999. */
  8000. inline bool prepare_kinematic_move_to(float ltarget[NUM_AXIS]) {
  8001. // Get the top feedrate of the move in the XY plane
  8002. float _feedrate_mm_s = MMS_SCALED(feedrate_mm_s);
  8003. // If the move is only in Z/E don't split up the move
  8004. if (ltarget[X_AXIS] == current_position[X_AXIS] && ltarget[Y_AXIS] == current_position[Y_AXIS]) {
  8005. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  8006. return true;
  8007. }
  8008. // Get the cartesian distances moved in XYZE
  8009. float difference[NUM_AXIS];
  8010. LOOP_XYZE(i) difference[i] = ltarget[i] - current_position[i];
  8011. // Get the linear distance in XYZ
  8012. float cartesian_mm = sqrt(sq(difference[X_AXIS]) + sq(difference[Y_AXIS]) + sq(difference[Z_AXIS]));
  8013. // If the move is very short, check the E move distance
  8014. if (UNEAR_ZERO(cartesian_mm)) cartesian_mm = abs(difference[E_AXIS]);
  8015. // No E move either? Game over.
  8016. if (UNEAR_ZERO(cartesian_mm)) return false;
  8017. // Minimum number of seconds to move the given distance
  8018. float seconds = cartesian_mm / _feedrate_mm_s;
  8019. // The number of segments-per-second times the duration
  8020. // gives the number of segments
  8021. uint16_t segments = delta_segments_per_second * seconds;
  8022. // For SCARA minimum segment size is 0.5mm
  8023. #if IS_SCARA
  8024. NOMORE(segments, cartesian_mm * 2);
  8025. #endif
  8026. // At least one segment is required
  8027. NOLESS(segments, 1);
  8028. // The approximate length of each segment
  8029. float segment_distance[XYZE] = {
  8030. difference[X_AXIS] / segments,
  8031. difference[Y_AXIS] / segments,
  8032. difference[Z_AXIS] / segments,
  8033. difference[E_AXIS] / segments
  8034. };
  8035. // SERIAL_ECHOPAIR("mm=", cartesian_mm);
  8036. // SERIAL_ECHOPAIR(" seconds=", seconds);
  8037. // SERIAL_ECHOLNPAIR(" segments=", segments);
  8038. // Drop one segment so the last move is to the exact target.
  8039. // If there's only 1 segment, loops will be skipped entirely.
  8040. --segments;
  8041. // Get the logical current position as starting point
  8042. float logical[XYZE];
  8043. COPY(logical, current_position);
  8044. // Calculate and execute the segments
  8045. for (uint16_t s = segments + 1; --s;) {
  8046. LOOP_XYZE(i) logical[i] += segment_distance[i];
  8047. #if ENABLED(DELTA)
  8048. DELTA_LOGICAL_IK(); // Delta can inline its kinematics
  8049. #else
  8050. inverse_kinematics(logical);
  8051. #endif
  8052. ADJUST_DELTA(logical); // Adjust Z if bed leveling is enabled
  8053. planner.buffer_line(delta[A_AXIS], delta[B_AXIS], delta[C_AXIS], logical[E_AXIS], _feedrate_mm_s, active_extruder);
  8054. }
  8055. // Since segment_distance is only approximate,
  8056. // the final move must be to the exact destination.
  8057. planner.buffer_line_kinematic(ltarget, _feedrate_mm_s, active_extruder);
  8058. return true;
  8059. }
  8060. #else // !IS_KINEMATIC
  8061. /**
  8062. * Prepare a linear move in a Cartesian setup.
  8063. * If Mesh Bed Leveling is enabled, perform a mesh move.
  8064. */
  8065. inline bool prepare_move_to_destination_cartesian() {
  8066. // Do not use feedrate_percentage for E or Z only moves
  8067. if (current_position[X_AXIS] == destination[X_AXIS] && current_position[Y_AXIS] == destination[Y_AXIS]) {
  8068. line_to_destination();
  8069. }
  8070. else {
  8071. #if ENABLED(MESH_BED_LEVELING)
  8072. if (mbl.active()) {
  8073. mesh_line_to_destination(MMS_SCALED(feedrate_mm_s));
  8074. return false;
  8075. }
  8076. else
  8077. #elif ENABLED(AUTO_BED_LEVELING_UBL)
  8078. if (blm.state.active) {
  8079. // UBL_line_to_destination(MMS_SCALED(feedrate_mm_s));
  8080. UBL_line_to_destination(destination[X_AXIS], destination[Y_AXIS], destination[Z_AXIS], destination[E_AXIS],
  8081. // (feedrate*(1.0/60.0))*(feedrate_percentage*(1.0/100.0) ), active_extruder);
  8082. MMS_SCALED(feedrate_mm_s), active_extruder);
  8083. return false;
  8084. }
  8085. else
  8086. #elif ENABLED(AUTO_BED_LEVELING_BILINEAR)
  8087. if (planner.abl_enabled) {
  8088. bilinear_line_to_destination(MMS_SCALED(feedrate_mm_s));
  8089. return false;
  8090. }
  8091. else
  8092. #endif
  8093. line_to_destination(MMS_SCALED(feedrate_mm_s));
  8094. }
  8095. return true;
  8096. }
  8097. #endif // !IS_KINEMATIC
  8098. #if ENABLED(DUAL_X_CARRIAGE)
  8099. /**
  8100. * Prepare a linear move in a dual X axis setup
  8101. */
  8102. inline bool prepare_move_to_destination_dualx() {
  8103. if (active_extruder_parked) {
  8104. switch (dual_x_carriage_mode) {
  8105. case DXC_FULL_CONTROL_MODE:
  8106. break;
  8107. case DXC_AUTO_PARK_MODE:
  8108. if (current_position[E_AXIS] == destination[E_AXIS]) {
  8109. // This is a travel move (with no extrusion)
  8110. // Skip it, but keep track of the current position
  8111. // (so it can be used as the start of the next non-travel move)
  8112. if (delayed_move_time != 0xFFFFFFFFUL) {
  8113. set_current_to_destination();
  8114. NOLESS(raised_parked_position[Z_AXIS], destination[Z_AXIS]);
  8115. delayed_move_time = millis();
  8116. return false;
  8117. }
  8118. }
  8119. // unpark extruder: 1) raise, 2) move into starting XY position, 3) lower
  8120. for (uint8_t i = 0; i < 3; i++)
  8121. planner.buffer_line(
  8122. i == 0 ? raised_parked_position[X_AXIS] : current_position[X_AXIS],
  8123. i == 0 ? raised_parked_position[Y_AXIS] : current_position[Y_AXIS],
  8124. i == 2 ? current_position[Z_AXIS] : raised_parked_position[Z_AXIS],
  8125. current_position[E_AXIS],
  8126. i == 1 ? PLANNER_XY_FEEDRATE() : planner.max_feedrate_mm_s[Z_AXIS],
  8127. active_extruder
  8128. );
  8129. delayed_move_time = 0;
  8130. active_extruder_parked = false;
  8131. break;
  8132. case DXC_DUPLICATION_MODE:
  8133. if (active_extruder == 0) {
  8134. // move duplicate extruder into correct duplication position.
  8135. planner.set_position_mm(
  8136. LOGICAL_X_POSITION(inactive_extruder_x_pos),
  8137. current_position[Y_AXIS],
  8138. current_position[Z_AXIS],
  8139. current_position[E_AXIS]
  8140. );
  8141. planner.buffer_line(
  8142. current_position[X_AXIS] + duplicate_extruder_x_offset,
  8143. current_position[Y_AXIS], current_position[Z_AXIS], current_position[E_AXIS],
  8144. planner.max_feedrate_mm_s[X_AXIS], 1
  8145. );
  8146. SYNC_PLAN_POSITION_KINEMATIC();
  8147. stepper.synchronize();
  8148. extruder_duplication_enabled = true;
  8149. active_extruder_parked = false;
  8150. }
  8151. break;
  8152. }
  8153. }
  8154. return true;
  8155. }
  8156. #endif // DUAL_X_CARRIAGE
  8157. /**
  8158. * Prepare a single move and get ready for the next one
  8159. *
  8160. * This may result in several calls to planner.buffer_line to
  8161. * do smaller moves for DELTA, SCARA, mesh moves, etc.
  8162. */
  8163. void prepare_move_to_destination() {
  8164. clamp_to_software_endstops(destination);
  8165. refresh_cmd_timeout();
  8166. #if ENABLED(PREVENT_COLD_EXTRUSION)
  8167. if (!DEBUGGING(DRYRUN)) {
  8168. if (destination[E_AXIS] != current_position[E_AXIS]) {
  8169. if (thermalManager.tooColdToExtrude(active_extruder)) {
  8170. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  8171. SERIAL_ECHO_START;
  8172. SERIAL_ECHOLNPGM(MSG_ERR_COLD_EXTRUDE_STOP);
  8173. }
  8174. #if ENABLED(PREVENT_LENGTHY_EXTRUDE)
  8175. if (labs(destination[E_AXIS] - current_position[E_AXIS]) > EXTRUDE_MAXLENGTH) {
  8176. current_position[E_AXIS] = destination[E_AXIS]; // Behave as if the move really took place, but ignore E part
  8177. SERIAL_ECHO_START;
  8178. SERIAL_ECHOLNPGM(MSG_ERR_LONG_EXTRUDE_STOP);
  8179. }
  8180. #endif
  8181. }
  8182. }
  8183. #endif
  8184. #if IS_KINEMATIC
  8185. if (!prepare_kinematic_move_to(destination)) return;
  8186. #else
  8187. #if ENABLED(DUAL_X_CARRIAGE)
  8188. if (!prepare_move_to_destination_dualx()) return;
  8189. #endif
  8190. if (!prepare_move_to_destination_cartesian()) return;
  8191. #endif
  8192. set_current_to_destination();
  8193. }
  8194. #if ENABLED(ARC_SUPPORT)
  8195. /**
  8196. * Plan an arc in 2 dimensions
  8197. *
  8198. * The arc is approximated by generating many small linear segments.
  8199. * The length of each segment is configured in MM_PER_ARC_SEGMENT (Default 1mm)
  8200. * Arcs should only be made relatively large (over 5mm), as larger arcs with
  8201. * larger segments will tend to be more efficient. Your slicer should have
  8202. * options for G2/G3 arc generation. In future these options may be GCode tunable.
  8203. */
  8204. void plan_arc(
  8205. float logical[NUM_AXIS], // Destination position
  8206. float* offset, // Center of rotation relative to current_position
  8207. uint8_t clockwise // Clockwise?
  8208. ) {
  8209. float radius = HYPOT(offset[X_AXIS], offset[Y_AXIS]),
  8210. center_X = current_position[X_AXIS] + offset[X_AXIS],
  8211. center_Y = current_position[Y_AXIS] + offset[Y_AXIS],
  8212. linear_travel = logical[Z_AXIS] - current_position[Z_AXIS],
  8213. extruder_travel = logical[E_AXIS] - current_position[E_AXIS],
  8214. r_X = -offset[X_AXIS], // Radius vector from center to current location
  8215. r_Y = -offset[Y_AXIS],
  8216. rt_X = logical[X_AXIS] - center_X,
  8217. rt_Y = logical[Y_AXIS] - center_Y;
  8218. // CCW angle of rotation between position and target from the circle center. Only one atan2() trig computation required.
  8219. float angular_travel = atan2(r_X * rt_Y - r_Y * rt_X, r_X * rt_X + r_Y * rt_Y);
  8220. if (angular_travel < 0) angular_travel += RADIANS(360);
  8221. if (clockwise) angular_travel -= RADIANS(360);
  8222. // Make a circle if the angular rotation is 0
  8223. if (angular_travel == 0 && current_position[X_AXIS] == logical[X_AXIS] && current_position[Y_AXIS] == logical[Y_AXIS])
  8224. angular_travel += RADIANS(360);
  8225. float mm_of_travel = HYPOT(angular_travel * radius, fabs(linear_travel));
  8226. if (mm_of_travel < 0.001) return;
  8227. uint16_t segments = floor(mm_of_travel / (MM_PER_ARC_SEGMENT));
  8228. if (segments == 0) segments = 1;
  8229. /**
  8230. * Vector rotation by transformation matrix: r is the original vector, r_T is the rotated vector,
  8231. * and phi is the angle of rotation. Based on the solution approach by Jens Geisler.
  8232. * r_T = [cos(phi) -sin(phi);
  8233. * sin(phi) cos(phi)] * r ;
  8234. *
  8235. * For arc generation, the center of the circle is the axis of rotation and the radius vector is
  8236. * defined from the circle center to the initial position. Each line segment is formed by successive
  8237. * vector rotations. This requires only two cos() and sin() computations to form the rotation
  8238. * matrix for the duration of the entire arc. Error may accumulate from numerical round-off, since
  8239. * all double numbers are single precision on the Arduino. (True double precision will not have
  8240. * round off issues for CNC applications.) Single precision error can accumulate to be greater than
  8241. * tool precision in some cases. Therefore, arc path correction is implemented.
  8242. *
  8243. * Small angle approximation may be used to reduce computation overhead further. This approximation
  8244. * holds for everything, but very small circles and large MM_PER_ARC_SEGMENT values. In other words,
  8245. * theta_per_segment would need to be greater than 0.1 rad and N_ARC_CORRECTION would need to be large
  8246. * to cause an appreciable drift error. N_ARC_CORRECTION~=25 is more than small enough to correct for
  8247. * numerical drift error. N_ARC_CORRECTION may be on the order a hundred(s) before error becomes an
  8248. * issue for CNC machines with the single precision Arduino calculations.
  8249. *
  8250. * This approximation also allows plan_arc to immediately insert a line segment into the planner
  8251. * without the initial overhead of computing cos() or sin(). By the time the arc needs to be applied
  8252. * a correction, the planner should have caught up to the lag caused by the initial plan_arc overhead.
  8253. * This is important when there are successive arc motions.
  8254. */
  8255. // Vector rotation matrix values
  8256. float arc_target[XYZE],
  8257. theta_per_segment = angular_travel / segments,
  8258. linear_per_segment = linear_travel / segments,
  8259. extruder_per_segment = extruder_travel / segments,
  8260. sin_T = theta_per_segment,
  8261. cos_T = 1 - 0.5 * sq(theta_per_segment); // Small angle approximation
  8262. // Initialize the linear axis
  8263. arc_target[Z_AXIS] = current_position[Z_AXIS];
  8264. // Initialize the extruder axis
  8265. arc_target[E_AXIS] = current_position[E_AXIS];
  8266. float fr_mm_s = MMS_SCALED(feedrate_mm_s);
  8267. millis_t next_idle_ms = millis() + 200UL;
  8268. int8_t count = 0;
  8269. for (uint16_t i = 1; i < segments; i++) { // Iterate (segments-1) times
  8270. thermalManager.manage_heater();
  8271. if (ELAPSED(millis(), next_idle_ms)) {
  8272. next_idle_ms = millis() + 200UL;
  8273. idle();
  8274. }
  8275. if (++count < N_ARC_CORRECTION) {
  8276. // Apply vector rotation matrix to previous r_X / 1
  8277. float r_new_Y = r_X * sin_T + r_Y * cos_T;
  8278. r_X = r_X * cos_T - r_Y * sin_T;
  8279. r_Y = r_new_Y;
  8280. }
  8281. else {
  8282. // Arc correction to radius vector. Computed only every N_ARC_CORRECTION increments.
  8283. // Compute exact location by applying transformation matrix from initial radius vector(=-offset).
  8284. // To reduce stuttering, the sin and cos could be computed at different times.
  8285. // For now, compute both at the same time.
  8286. float cos_Ti = cos(i * theta_per_segment),
  8287. sin_Ti = sin(i * theta_per_segment);
  8288. r_X = -offset[X_AXIS] * cos_Ti + offset[Y_AXIS] * sin_Ti;
  8289. r_Y = -offset[X_AXIS] * sin_Ti - offset[Y_AXIS] * cos_Ti;
  8290. count = 0;
  8291. }
  8292. // Update arc_target location
  8293. arc_target[X_AXIS] = center_X + r_X;
  8294. arc_target[Y_AXIS] = center_Y + r_Y;
  8295. arc_target[Z_AXIS] += linear_per_segment;
  8296. arc_target[E_AXIS] += extruder_per_segment;
  8297. clamp_to_software_endstops(arc_target);
  8298. planner.buffer_line_kinematic(arc_target, fr_mm_s, active_extruder);
  8299. }
  8300. // Ensure last segment arrives at target location.
  8301. planner.buffer_line_kinematic(logical, fr_mm_s, active_extruder);
  8302. // As far as the parser is concerned, the position is now == target. In reality the
  8303. // motion control system might still be processing the action and the real tool position
  8304. // in any intermediate location.
  8305. set_current_to_destination();
  8306. }
  8307. #endif
  8308. #if ENABLED(BEZIER_CURVE_SUPPORT)
  8309. void plan_cubic_move(const float offset[4]) {
  8310. cubic_b_spline(current_position, destination, offset, MMS_SCALED(feedrate_mm_s), active_extruder);
  8311. // As far as the parser is concerned, the position is now == destination. In reality the
  8312. // motion control system might still be processing the action and the real tool position
  8313. // in any intermediate location.
  8314. set_current_to_destination();
  8315. }
  8316. #endif // BEZIER_CURVE_SUPPORT
  8317. #if HAS_CONTROLLERFAN
  8318. void controllerFan() {
  8319. static millis_t lastMotorOn = 0; // Last time a motor was turned on
  8320. static millis_t nextMotorCheck = 0; // Last time the state was checked
  8321. millis_t ms = millis();
  8322. if (ELAPSED(ms, nextMotorCheck)) {
  8323. nextMotorCheck = ms + 2500UL; // Not a time critical function, so only check every 2.5s
  8324. if (X_ENABLE_READ == X_ENABLE_ON || Y_ENABLE_READ == Y_ENABLE_ON || Z_ENABLE_READ == Z_ENABLE_ON || thermalManager.soft_pwm_bed > 0
  8325. || E0_ENABLE_READ == E_ENABLE_ON // If any of the drivers are enabled...
  8326. #if E_STEPPERS > 1
  8327. || E1_ENABLE_READ == E_ENABLE_ON
  8328. #if HAS_X2_ENABLE
  8329. || X2_ENABLE_READ == X_ENABLE_ON
  8330. #endif
  8331. #if E_STEPPERS > 2
  8332. || E2_ENABLE_READ == E_ENABLE_ON
  8333. #if E_STEPPERS > 3
  8334. || E3_ENABLE_READ == E_ENABLE_ON
  8335. #endif
  8336. #endif
  8337. #endif
  8338. ) {
  8339. lastMotorOn = ms; //... set time to NOW so the fan will turn on
  8340. }
  8341. // Fan off if no steppers have been enabled for CONTROLLERFAN_SECS seconds
  8342. uint8_t speed = (!lastMotorOn || ELAPSED(ms, lastMotorOn + (CONTROLLERFAN_SECS) * 1000UL)) ? 0 : CONTROLLERFAN_SPEED;
  8343. // allows digital or PWM fan output to be used (see M42 handling)
  8344. digitalWrite(CONTROLLERFAN_PIN, speed);
  8345. analogWrite(CONTROLLERFAN_PIN, speed);
  8346. }
  8347. }
  8348. #endif // HAS_CONTROLLERFAN
  8349. #if ENABLED(MORGAN_SCARA)
  8350. /**
  8351. * Morgan SCARA Forward Kinematics. Results in cartes[].
  8352. * Maths and first version by QHARLEY.
  8353. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  8354. */
  8355. void forward_kinematics_SCARA(const float &a, const float &b) {
  8356. float a_sin = sin(RADIANS(a)) * L1,
  8357. a_cos = cos(RADIANS(a)) * L1,
  8358. b_sin = sin(RADIANS(b)) * L2,
  8359. b_cos = cos(RADIANS(b)) * L2;
  8360. cartes[X_AXIS] = a_cos + b_cos + SCARA_OFFSET_X; //theta
  8361. cartes[Y_AXIS] = a_sin + b_sin + SCARA_OFFSET_Y; //theta+phi
  8362. /*
  8363. SERIAL_ECHOPAIR("SCARA FK Angle a=", a);
  8364. SERIAL_ECHOPAIR(" b=", b);
  8365. SERIAL_ECHOPAIR(" a_sin=", a_sin);
  8366. SERIAL_ECHOPAIR(" a_cos=", a_cos);
  8367. SERIAL_ECHOPAIR(" b_sin=", b_sin);
  8368. SERIAL_ECHOLNPAIR(" b_cos=", b_cos);
  8369. SERIAL_ECHOPAIR(" cartes[X_AXIS]=", cartes[X_AXIS]);
  8370. SERIAL_ECHOLNPAIR(" cartes[Y_AXIS]=", cartes[Y_AXIS]);
  8371. //*/
  8372. }
  8373. /**
  8374. * Morgan SCARA Inverse Kinematics. Results in delta[].
  8375. *
  8376. * See http://forums.reprap.org/read.php?185,283327
  8377. *
  8378. * Maths and first version by QHARLEY.
  8379. * Integrated into Marlin and slightly restructured by Joachim Cerny.
  8380. */
  8381. void inverse_kinematics(const float logical[XYZ]) {
  8382. static float C2, S2, SK1, SK2, THETA, PSI;
  8383. float sx = RAW_X_POSITION(logical[X_AXIS]) - SCARA_OFFSET_X, // Translate SCARA to standard X Y
  8384. sy = RAW_Y_POSITION(logical[Y_AXIS]) - SCARA_OFFSET_Y; // With scaling factor.
  8385. if (L1 == L2)
  8386. C2 = HYPOT2(sx, sy) / L1_2_2 - 1;
  8387. else
  8388. C2 = (HYPOT2(sx, sy) - (L1_2 + L2_2)) / (2.0 * L1 * L2);
  8389. S2 = sqrt(sq(C2) - 1);
  8390. // Unrotated Arm1 plus rotated Arm2 gives the distance from Center to End
  8391. SK1 = L1 + L2 * C2;
  8392. // Rotated Arm2 gives the distance from Arm1 to Arm2
  8393. SK2 = L2 * S2;
  8394. // Angle of Arm1 is the difference between Center-to-End angle and the Center-to-Elbow
  8395. THETA = atan2(SK1, SK2) - atan2(sx, sy);
  8396. // Angle of Arm2
  8397. PSI = atan2(S2, C2);
  8398. delta[A_AXIS] = DEGREES(THETA); // theta is support arm angle
  8399. delta[B_AXIS] = DEGREES(THETA + PSI); // equal to sub arm angle (inverted motor)
  8400. delta[C_AXIS] = logical[Z_AXIS];
  8401. /*
  8402. DEBUG_POS("SCARA IK", logical);
  8403. DEBUG_POS("SCARA IK", delta);
  8404. SERIAL_ECHOPAIR(" SCARA (x,y) ", sx);
  8405. SERIAL_ECHOPAIR(",", sy);
  8406. SERIAL_ECHOPAIR(" C2=", C2);
  8407. SERIAL_ECHOPAIR(" S2=", S2);
  8408. SERIAL_ECHOPAIR(" Theta=", THETA);
  8409. SERIAL_ECHOLNPAIR(" Phi=", PHI);
  8410. //*/
  8411. }
  8412. #endif // MORGAN_SCARA
  8413. #if ENABLED(TEMP_STAT_LEDS)
  8414. static bool red_led = false;
  8415. static millis_t next_status_led_update_ms = 0;
  8416. void handle_status_leds(void) {
  8417. if (ELAPSED(millis(), next_status_led_update_ms)) {
  8418. next_status_led_update_ms += 500; // Update every 0.5s
  8419. float max_temp = 0.0;
  8420. #if HAS_TEMP_BED
  8421. max_temp = MAX3(max_temp, thermalManager.degTargetBed(), thermalManager.degBed());
  8422. #endif
  8423. HOTEND_LOOP() {
  8424. max_temp = MAX3(max_temp, thermalManager.degHotend(e), thermalManager.degTargetHotend(e));
  8425. }
  8426. bool new_led = (max_temp > 55.0) ? true : (max_temp < 54.0) ? false : red_led;
  8427. if (new_led != red_led) {
  8428. red_led = new_led;
  8429. #if PIN_EXISTS(STAT_LED_RED)
  8430. WRITE(STAT_LED_RED_PIN, new_led ? HIGH : LOW);
  8431. #if PIN_EXISTS(STAT_LED_BLUE)
  8432. WRITE(STAT_LED_BLUE_PIN, new_led ? LOW : HIGH);
  8433. #endif
  8434. #else
  8435. WRITE(STAT_LED_BLUE_PIN, new_led ? HIGH : LOW);
  8436. #endif
  8437. }
  8438. }
  8439. }
  8440. #endif
  8441. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8442. void handle_filament_runout() {
  8443. if (!filament_ran_out) {
  8444. filament_ran_out = true;
  8445. enqueue_and_echo_commands_P(PSTR(FILAMENT_RUNOUT_SCRIPT));
  8446. stepper.synchronize();
  8447. }
  8448. }
  8449. #endif // FILAMENT_RUNOUT_SENSOR
  8450. #if ENABLED(FAST_PWM_FAN)
  8451. void setPwmFrequency(uint8_t pin, int val) {
  8452. val &= 0x07;
  8453. switch (digitalPinToTimer(pin)) {
  8454. #if defined(TCCR0A)
  8455. case TIMER0A:
  8456. case TIMER0B:
  8457. // TCCR0B &= ~(_BV(CS00) | _BV(CS01) | _BV(CS02));
  8458. // TCCR0B |= val;
  8459. break;
  8460. #endif
  8461. #if defined(TCCR1A)
  8462. case TIMER1A:
  8463. case TIMER1B:
  8464. // TCCR1B &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8465. // TCCR1B |= val;
  8466. break;
  8467. #endif
  8468. #if defined(TCCR2)
  8469. case TIMER2:
  8470. case TIMER2:
  8471. TCCR2 &= ~(_BV(CS10) | _BV(CS11) | _BV(CS12));
  8472. TCCR2 |= val;
  8473. break;
  8474. #endif
  8475. #if defined(TCCR2A)
  8476. case TIMER2A:
  8477. case TIMER2B:
  8478. TCCR2B &= ~(_BV(CS20) | _BV(CS21) | _BV(CS22));
  8479. TCCR2B |= val;
  8480. break;
  8481. #endif
  8482. #if defined(TCCR3A)
  8483. case TIMER3A:
  8484. case TIMER3B:
  8485. case TIMER3C:
  8486. TCCR3B &= ~(_BV(CS30) | _BV(CS31) | _BV(CS32));
  8487. TCCR3B |= val;
  8488. break;
  8489. #endif
  8490. #if defined(TCCR4A)
  8491. case TIMER4A:
  8492. case TIMER4B:
  8493. case TIMER4C:
  8494. TCCR4B &= ~(_BV(CS40) | _BV(CS41) | _BV(CS42));
  8495. TCCR4B |= val;
  8496. break;
  8497. #endif
  8498. #if defined(TCCR5A)
  8499. case TIMER5A:
  8500. case TIMER5B:
  8501. case TIMER5C:
  8502. TCCR5B &= ~(_BV(CS50) | _BV(CS51) | _BV(CS52));
  8503. TCCR5B |= val;
  8504. break;
  8505. #endif
  8506. }
  8507. }
  8508. #endif // FAST_PWM_FAN
  8509. float calculate_volumetric_multiplier(float diameter) {
  8510. if (!volumetric_enabled || diameter == 0) return 1.0;
  8511. return 1.0 / (M_PI * diameter * 0.5 * diameter * 0.5);
  8512. }
  8513. void calculate_volumetric_multipliers() {
  8514. for (uint8_t i = 0; i < COUNT(filament_size); i++)
  8515. volumetric_multiplier[i] = calculate_volumetric_multiplier(filament_size[i]);
  8516. }
  8517. void enable_all_steppers() {
  8518. enable_x();
  8519. enable_y();
  8520. enable_z();
  8521. enable_e0();
  8522. enable_e1();
  8523. enable_e2();
  8524. enable_e3();
  8525. }
  8526. void disable_all_steppers() {
  8527. disable_x();
  8528. disable_y();
  8529. disable_z();
  8530. disable_e0();
  8531. disable_e1();
  8532. disable_e2();
  8533. disable_e3();
  8534. }
  8535. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8536. void automatic_current_control(const TMC2130Stepper &st) {
  8537. #if CURRENT_STEP > 0
  8538. const bool is_otpw = st.checkOT(), // Check otpw even if we don't adjust. Allows for flag inspection.
  8539. is_otpw_triggered = st.getOTPW();
  8540. if (!is_otpw && !is_otpw_triggered) {
  8541. // OTPW bit not triggered yet -> Increase current
  8542. const uint16_t current = st.getCurrent() + CURRENT_STEP;
  8543. if (current <= AUTO_ADJUST_MAX) st.SilentStepStick2130(current);
  8544. }
  8545. else if (is_otpw && is_otpw_triggered) {
  8546. // OTPW bit triggered, triggered flag raised -> Decrease current
  8547. st.SilentStepStick2130((float)st.getCurrent() - CURRENT_STEP);
  8548. }
  8549. // OTPW bit cleared (we've cooled down), triggered flag still raised until manually cleared -> Do nothing, we're good
  8550. #endif
  8551. }
  8552. void checkOverTemp() {
  8553. static millis_t next_cOT = 0;
  8554. if (ELAPSED(millis(), next_cOT)) {
  8555. next_cOT = millis() + 5000;
  8556. #if ENABLED(X_IS_TMC2130)
  8557. automatic_current_control(stepperX);
  8558. #endif
  8559. #if ENABLED(Y_IS_TMC2130)
  8560. automatic_current_control(stepperY);
  8561. #endif
  8562. #if ENABLED(Z_IS_TMC2130)
  8563. automatic_current_control(stepperZ);
  8564. #endif
  8565. #if ENABLED(X2_IS_TMC2130)
  8566. automatic_current_control(stepperX2);
  8567. #endif
  8568. #if ENABLED(Y2_IS_TMC2130)
  8569. automatic_current_control(stepperY2);
  8570. #endif
  8571. #if ENABLED(Z2_IS_TMC2130)
  8572. automatic_current_control(stepperZ2);
  8573. #endif
  8574. #if ENABLED(E0_IS_TMC2130)
  8575. automatic_current_control(stepperE0);
  8576. #endif
  8577. #if ENABLED(E1_IS_TMC2130)
  8578. automatic_current_control(stepperE1);
  8579. #endif
  8580. #if ENABLED(E2_IS_TMC2130)
  8581. automatic_current_control(stepperE2);
  8582. #endif
  8583. #if ENABLED(E3_IS_TMC2130)
  8584. automatic_current_control(stepperE3);
  8585. #endif
  8586. }
  8587. }
  8588. #endif // AUTOMATIC_CURRENT_CONTROL
  8589. /**
  8590. * Manage several activities:
  8591. * - Check for Filament Runout
  8592. * - Keep the command buffer full
  8593. * - Check for maximum inactive time between commands
  8594. * - Check for maximum inactive time between stepper commands
  8595. * - Check if pin CHDK needs to go LOW
  8596. * - Check for KILL button held down
  8597. * - Check for HOME button held down
  8598. * - Check if cooling fan needs to be switched on
  8599. * - Check if an idle but hot extruder needs filament extruded (EXTRUDER_RUNOUT_PREVENT)
  8600. */
  8601. void manage_inactivity(bool ignore_stepper_queue/*=false*/) {
  8602. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8603. if ((IS_SD_PRINTING || print_job_timer.isRunning()) && (READ(FIL_RUNOUT_PIN) == FIL_RUNOUT_INVERTING))
  8604. handle_filament_runout();
  8605. #endif
  8606. if (commands_in_queue < BUFSIZE) get_available_commands();
  8607. millis_t ms = millis();
  8608. if (max_inactive_time && ELAPSED(ms, previous_cmd_ms + max_inactive_time)) {
  8609. SERIAL_ERROR_START;
  8610. SERIAL_ECHOLNPAIR(MSG_KILL_INACTIVE_TIME, current_command);
  8611. kill(PSTR(MSG_KILLED));
  8612. }
  8613. // Prevent steppers timing-out in the middle of M600
  8614. #if ENABLED(FILAMENT_CHANGE_FEATURE) && ENABLED(FILAMENT_CHANGE_NO_STEPPER_TIMEOUT)
  8615. #define M600_TEST !busy_doing_M600
  8616. #else
  8617. #define M600_TEST true
  8618. #endif
  8619. if (M600_TEST && stepper_inactive_time && ELAPSED(ms, previous_cmd_ms + stepper_inactive_time)
  8620. && !ignore_stepper_queue && !planner.blocks_queued()) {
  8621. #if ENABLED(DISABLE_INACTIVE_X)
  8622. disable_x();
  8623. #endif
  8624. #if ENABLED(DISABLE_INACTIVE_Y)
  8625. disable_y();
  8626. #endif
  8627. #if ENABLED(DISABLE_INACTIVE_Z)
  8628. disable_z();
  8629. #endif
  8630. #if ENABLED(DISABLE_INACTIVE_E)
  8631. disable_e0();
  8632. disable_e1();
  8633. disable_e2();
  8634. disable_e3();
  8635. #endif
  8636. }
  8637. #ifdef CHDK // Check if pin should be set to LOW after M240 set it to HIGH
  8638. if (chdkActive && ELAPSED(ms, chdkHigh + CHDK_DELAY)) {
  8639. chdkActive = false;
  8640. WRITE(CHDK, LOW);
  8641. }
  8642. #endif
  8643. #if HAS_KILL
  8644. // Check if the kill button was pressed and wait just in case it was an accidental
  8645. // key kill key press
  8646. // -------------------------------------------------------------------------------
  8647. static int killCount = 0; // make the inactivity button a bit less responsive
  8648. const int KILL_DELAY = 750;
  8649. if (!READ(KILL_PIN))
  8650. killCount++;
  8651. else if (killCount > 0)
  8652. killCount--;
  8653. // Exceeded threshold and we can confirm that it was not accidental
  8654. // KILL the machine
  8655. // ----------------------------------------------------------------
  8656. if (killCount >= KILL_DELAY) {
  8657. SERIAL_ERROR_START;
  8658. SERIAL_ERRORLNPGM(MSG_KILL_BUTTON);
  8659. kill(PSTR(MSG_KILLED));
  8660. }
  8661. #endif
  8662. #if HAS_HOME
  8663. // Check to see if we have to home, use poor man's debouncer
  8664. // ---------------------------------------------------------
  8665. static int homeDebounceCount = 0; // poor man's debouncing count
  8666. const int HOME_DEBOUNCE_DELAY = 2500;
  8667. if (!IS_SD_PRINTING && !READ(HOME_PIN)) {
  8668. if (!homeDebounceCount) {
  8669. enqueue_and_echo_commands_P(PSTR("G28"));
  8670. LCD_MESSAGEPGM(MSG_AUTO_HOME);
  8671. }
  8672. if (homeDebounceCount < HOME_DEBOUNCE_DELAY)
  8673. homeDebounceCount++;
  8674. else
  8675. homeDebounceCount = 0;
  8676. }
  8677. #endif
  8678. #if HAS_CONTROLLERFAN
  8679. controllerFan(); // Check if fan should be turned on to cool stepper drivers down
  8680. #endif
  8681. #if ENABLED(EXTRUDER_RUNOUT_PREVENT)
  8682. if (ELAPSED(ms, previous_cmd_ms + (EXTRUDER_RUNOUT_SECONDS) * 1000UL)
  8683. && thermalManager.degHotend(active_extruder) > EXTRUDER_RUNOUT_MINTEMP) {
  8684. bool oldstatus;
  8685. #if ENABLED(SWITCHING_EXTRUDER)
  8686. oldstatus = E0_ENABLE_READ;
  8687. enable_e0();
  8688. #else // !SWITCHING_EXTRUDER
  8689. switch (active_extruder) {
  8690. case 0:
  8691. oldstatus = E0_ENABLE_READ;
  8692. enable_e0();
  8693. break;
  8694. #if E_STEPPERS > 1
  8695. case 1:
  8696. oldstatus = E1_ENABLE_READ;
  8697. enable_e1();
  8698. break;
  8699. #if E_STEPPERS > 2
  8700. case 2:
  8701. oldstatus = E2_ENABLE_READ;
  8702. enable_e2();
  8703. break;
  8704. #if E_STEPPERS > 3
  8705. case 3:
  8706. oldstatus = E3_ENABLE_READ;
  8707. enable_e3();
  8708. break;
  8709. #endif
  8710. #endif
  8711. #endif
  8712. }
  8713. #endif // !SWITCHING_EXTRUDER
  8714. previous_cmd_ms = ms; // refresh_cmd_timeout()
  8715. #if IS_KINEMATIC
  8716. inverse_kinematics(current_position);
  8717. ADJUST_DELTA(current_position);
  8718. planner.buffer_line(
  8719. delta[A_AXIS], delta[B_AXIS], delta[C_AXIS],
  8720. current_position[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE,
  8721. MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder
  8722. );
  8723. #else
  8724. planner.buffer_line(
  8725. current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS],
  8726. current_position[E_AXIS] + EXTRUDER_RUNOUT_EXTRUDE,
  8727. MMM_TO_MMS(EXTRUDER_RUNOUT_SPEED), active_extruder
  8728. );
  8729. #endif
  8730. stepper.synchronize();
  8731. planner.set_e_position_mm(current_position[E_AXIS]);
  8732. #if ENABLED(SWITCHING_EXTRUDER)
  8733. E0_ENABLE_WRITE(oldstatus);
  8734. #else
  8735. switch (active_extruder) {
  8736. case 0:
  8737. E0_ENABLE_WRITE(oldstatus);
  8738. break;
  8739. #if E_STEPPERS > 1
  8740. case 1:
  8741. E1_ENABLE_WRITE(oldstatus);
  8742. break;
  8743. #if E_STEPPERS > 2
  8744. case 2:
  8745. E2_ENABLE_WRITE(oldstatus);
  8746. break;
  8747. #if E_STEPPERS > 3
  8748. case 3:
  8749. E3_ENABLE_WRITE(oldstatus);
  8750. break;
  8751. #endif
  8752. #endif
  8753. #endif
  8754. }
  8755. #endif // !SWITCHING_EXTRUDER
  8756. }
  8757. #endif // EXTRUDER_RUNOUT_PREVENT
  8758. #if ENABLED(DUAL_X_CARRIAGE)
  8759. // handle delayed move timeout
  8760. if (delayed_move_time && ELAPSED(ms, delayed_move_time + 1000UL) && IsRunning()) {
  8761. // travel moves have been received so enact them
  8762. delayed_move_time = 0xFFFFFFFFUL; // force moves to be done
  8763. set_destination_to_current();
  8764. prepare_move_to_destination();
  8765. }
  8766. #endif
  8767. #if ENABLED(TEMP_STAT_LEDS)
  8768. handle_status_leds();
  8769. #endif
  8770. #if ENABLED(AUTOMATIC_CURRENT_CONTROL)
  8771. checkOverTemp();
  8772. #endif
  8773. planner.check_axes_activity();
  8774. }
  8775. /**
  8776. * Standard idle routine keeps the machine alive
  8777. */
  8778. void idle(
  8779. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  8780. bool no_stepper_sleep/*=false*/
  8781. #endif
  8782. ) {
  8783. lcd_update();
  8784. host_keepalive();
  8785. #if ENABLED(AUTO_REPORT_TEMPERATURES) && (HAS_TEMP_HOTEND || HAS_TEMP_BED)
  8786. auto_report_temperatures();
  8787. #endif
  8788. manage_inactivity(
  8789. #if ENABLED(FILAMENT_CHANGE_FEATURE)
  8790. no_stepper_sleep
  8791. #endif
  8792. );
  8793. thermalManager.manage_heater();
  8794. #if ENABLED(PRINTCOUNTER)
  8795. print_job_timer.tick();
  8796. #endif
  8797. #if HAS_BUZZER && DISABLED(LCD_USE_I2C_BUZZER)
  8798. buzzer.tick();
  8799. #endif
  8800. }
  8801. /**
  8802. * Kill all activity and lock the machine.
  8803. * After this the machine will need to be reset.
  8804. */
  8805. void kill(const char* lcd_msg) {
  8806. SERIAL_ERROR_START;
  8807. SERIAL_ERRORLNPGM(MSG_ERR_KILLED);
  8808. #if ENABLED(ULTRA_LCD)
  8809. kill_screen(lcd_msg);
  8810. #else
  8811. UNUSED(lcd_msg);
  8812. #endif
  8813. delay(500); // Wait a short time
  8814. cli(); // Stop interrupts
  8815. thermalManager.disable_all_heaters();
  8816. disable_all_steppers();
  8817. #if HAS_POWER_SWITCH
  8818. SET_INPUT(PS_ON_PIN);
  8819. #endif
  8820. suicide();
  8821. while (1) {
  8822. #if ENABLED(USE_WATCHDOG)
  8823. watchdog_reset();
  8824. #endif
  8825. } // Wait for reset
  8826. }
  8827. /**
  8828. * Turn off heaters and stop the print in progress
  8829. * After a stop the machine may be resumed with M999
  8830. */
  8831. void stop() {
  8832. thermalManager.disable_all_heaters();
  8833. if (IsRunning()) {
  8834. Running = false;
  8835. Stopped_gcode_LastN = gcode_LastN; // Save last g_code for restart
  8836. SERIAL_ERROR_START;
  8837. SERIAL_ERRORLNPGM(MSG_ERR_STOPPED);
  8838. LCD_MESSAGEPGM(MSG_STOPPED);
  8839. }
  8840. }
  8841. /**
  8842. * Marlin entry-point: Set up before the program loop
  8843. * - Set up the kill pin, filament runout, power hold
  8844. * - Start the serial port
  8845. * - Print startup messages and diagnostics
  8846. * - Get EEPROM or default settings
  8847. * - Initialize managers for:
  8848. * • temperature
  8849. * • planner
  8850. * • watchdog
  8851. * • stepper
  8852. * • photo pin
  8853. * • servos
  8854. * • LCD controller
  8855. * • Digipot I2C
  8856. * • Z probe sled
  8857. * • status LEDs
  8858. */
  8859. void setup() {
  8860. #ifdef DISABLE_JTAG
  8861. // Disable JTAG on AT90USB chips to free up pins for IO
  8862. MCUCR = 0x80;
  8863. MCUCR = 0x80;
  8864. #endif
  8865. #if ENABLED(FILAMENT_RUNOUT_SENSOR)
  8866. setup_filrunoutpin();
  8867. #endif
  8868. setup_killpin();
  8869. setup_powerhold();
  8870. #if HAS_STEPPER_RESET
  8871. disableStepperDrivers();
  8872. #endif
  8873. MYSERIAL.begin(BAUDRATE);
  8874. SERIAL_PROTOCOLLNPGM("start");
  8875. SERIAL_ECHO_START;
  8876. // Check startup - does nothing if bootloader sets MCUSR to 0
  8877. byte mcu = MCUSR;
  8878. if (mcu & 1) SERIAL_ECHOLNPGM(MSG_POWERUP);
  8879. if (mcu & 2) SERIAL_ECHOLNPGM(MSG_EXTERNAL_RESET);
  8880. if (mcu & 4) SERIAL_ECHOLNPGM(MSG_BROWNOUT_RESET);
  8881. if (mcu & 8) SERIAL_ECHOLNPGM(MSG_WATCHDOG_RESET);
  8882. if (mcu & 32) SERIAL_ECHOLNPGM(MSG_SOFTWARE_RESET);
  8883. MCUSR = 0;
  8884. SERIAL_ECHOPGM(MSG_MARLIN);
  8885. SERIAL_CHAR(' ');
  8886. SERIAL_ECHOLNPGM(SHORT_BUILD_VERSION);
  8887. SERIAL_EOL;
  8888. #if defined(STRING_DISTRIBUTION_DATE) && defined(STRING_CONFIG_H_AUTHOR)
  8889. SERIAL_ECHO_START;
  8890. SERIAL_ECHOPGM(MSG_CONFIGURATION_VER);
  8891. SERIAL_ECHOPGM(STRING_DISTRIBUTION_DATE);
  8892. SERIAL_ECHOLNPGM(MSG_AUTHOR STRING_CONFIG_H_AUTHOR);
  8893. SERIAL_ECHOLNPGM("Compiled: " __DATE__);
  8894. #endif
  8895. SERIAL_ECHO_START;
  8896. SERIAL_ECHOPAIR(MSG_FREE_MEMORY, freeMemory());
  8897. SERIAL_ECHOLNPAIR(MSG_PLANNER_BUFFER_BYTES, (int)sizeof(block_t)*BLOCK_BUFFER_SIZE);
  8898. // Send "ok" after commands by default
  8899. for (int8_t i = 0; i < BUFSIZE; i++) send_ok[i] = true;
  8900. // Load data from EEPROM if available (or use defaults)
  8901. // This also updates variables in the planner, elsewhere
  8902. Config_RetrieveSettings();
  8903. #if DISABLED(NO_WORKSPACE_OFFSETS)
  8904. // Initialize current position based on home_offset
  8905. COPY(current_position, home_offset);
  8906. #else
  8907. ZERO(current_position);
  8908. #endif
  8909. // Vital to init stepper/planner equivalent for current_position
  8910. SYNC_PLAN_POSITION_KINEMATIC();
  8911. thermalManager.init(); // Initialize temperature loop
  8912. #if ENABLED(USE_WATCHDOG)
  8913. watchdog_init();
  8914. #endif
  8915. stepper.init(); // Initialize stepper, this enables interrupts!
  8916. servo_init();
  8917. #if HAS_PHOTOGRAPH
  8918. OUT_WRITE(PHOTOGRAPH_PIN, LOW);
  8919. #endif
  8920. #if HAS_CASE_LIGHT
  8921. update_case_light();
  8922. #endif
  8923. #if HAS_BED_PROBE
  8924. endstops.enable_z_probe(false);
  8925. #endif
  8926. #if HAS_CONTROLLERFAN
  8927. SET_OUTPUT(CONTROLLERFAN_PIN); //Set pin used for driver cooling fan
  8928. #endif
  8929. #if HAS_STEPPER_RESET
  8930. enableStepperDrivers();
  8931. #endif
  8932. #if ENABLED(DIGIPOT_I2C)
  8933. digipot_i2c_init();
  8934. #endif
  8935. #if ENABLED(DAC_STEPPER_CURRENT)
  8936. dac_init();
  8937. #endif
  8938. #if ENABLED(Z_PROBE_SLED) && PIN_EXISTS(SLED)
  8939. OUT_WRITE(SLED_PIN, LOW); // turn it off
  8940. #endif // Z_PROBE_SLED
  8941. setup_homepin();
  8942. #if PIN_EXISTS(STAT_LED_RED)
  8943. OUT_WRITE(STAT_LED_RED_PIN, LOW); // turn it off
  8944. #endif
  8945. #if PIN_EXISTS(STAT_LED_BLUE)
  8946. OUT_WRITE(STAT_LED_BLUE_PIN, LOW); // turn it off
  8947. #endif
  8948. #if ENABLED(RGB_LED)
  8949. SET_OUTPUT(RGB_LED_R_PIN);
  8950. SET_OUTPUT(RGB_LED_G_PIN);
  8951. SET_OUTPUT(RGB_LED_B_PIN);
  8952. #endif
  8953. lcd_init();
  8954. #if ENABLED(SHOW_BOOTSCREEN)
  8955. #if ENABLED(DOGLCD)
  8956. safe_delay(BOOTSCREEN_TIMEOUT);
  8957. #elif ENABLED(ULTRA_LCD)
  8958. bootscreen();
  8959. #if DISABLED(SDSUPPORT)
  8960. lcd_init();
  8961. #endif
  8962. #endif
  8963. #endif
  8964. #if ENABLED(MIXING_EXTRUDER) && MIXING_VIRTUAL_TOOLS > 1
  8965. // Initialize mixing to 100% color 1
  8966. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8967. mixing_factor[i] = (i == 0) ? 1.0 : 0.0;
  8968. for (uint8_t t = 0; t < MIXING_VIRTUAL_TOOLS; t++)
  8969. for (uint8_t i = 0; i < MIXING_STEPPERS; i++)
  8970. mixing_virtual_tool_mix[t][i] = mixing_factor[i];
  8971. #endif
  8972. #if ENABLED(BLTOUCH)
  8973. bltouch_command(BLTOUCH_RESET); // Just in case the BLTouch is in the error state, try to
  8974. set_bltouch_deployed(true); // reset it. Also needs to deploy and stow to clear the
  8975. set_bltouch_deployed(false); // error condition.
  8976. #endif
  8977. #if ENABLED(EXPERIMENTAL_I2CBUS) && I2C_SLAVE_ADDRESS > 0
  8978. i2c.onReceive(i2c_on_receive);
  8979. i2c.onRequest(i2c_on_request);
  8980. #endif
  8981. #if ENABLED(ENDSTOP_INTERRUPTS_FEATURE)
  8982. setup_endstop_interrupts();
  8983. #endif
  8984. }
  8985. /**
  8986. * The main Marlin program loop
  8987. *
  8988. * - Save or log commands to SD
  8989. * - Process available commands (if not saving)
  8990. * - Call heater manager
  8991. * - Call inactivity manager
  8992. * - Call endstop manager
  8993. * - Call LCD update
  8994. */
  8995. void loop() {
  8996. if (commands_in_queue < BUFSIZE) get_available_commands();
  8997. #if ENABLED(SDSUPPORT)
  8998. card.checkautostart(false);
  8999. #endif
  9000. if (commands_in_queue) {
  9001. #if ENABLED(SDSUPPORT)
  9002. if (card.saving) {
  9003. char* command = command_queue[cmd_queue_index_r];
  9004. if (strstr_P(command, PSTR("M29"))) {
  9005. // M29 closes the file
  9006. card.closefile();
  9007. SERIAL_PROTOCOLLNPGM(MSG_FILE_SAVED);
  9008. ok_to_send();
  9009. }
  9010. else {
  9011. // Write the string from the read buffer to SD
  9012. card.write_command(command);
  9013. if (card.logging)
  9014. process_next_command(); // The card is saving because it's logging
  9015. else
  9016. ok_to_send();
  9017. }
  9018. }
  9019. else
  9020. process_next_command();
  9021. #else
  9022. process_next_command();
  9023. #endif // SDSUPPORT
  9024. // The queue may be reset by a command handler or by code invoked by idle() within a handler
  9025. if (commands_in_queue) {
  9026. --commands_in_queue;
  9027. cmd_queue_index_r = (cmd_queue_index_r + 1) % BUFSIZE;
  9028. }
  9029. }
  9030. endstops.report_state();
  9031. idle();
  9032. }